Add cacheItemCount property to PathView
[profile/ivi/qtdeclarative.git] / src / quick / items / qquickitem.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 "qquickitem.h"
43
44 #include "qquickwindow.h"
45 #include <QtQml/qjsengine.h>
46 #include "qquickwindow_p.h"
47
48 #include "qquickevents_p_p.h"
49 #include "qquickscreen_p.h"
50
51 #include <QtQml/qqmlengine.h>
52 #include <QtQml/qqmlcomponent.h>
53 #include <QtQml/qqmlinfo.h>
54 #include <QtGui/qpen.h>
55 #include <QtGui/qguiapplication.h>
56 #include <QtGui/private/qguiapplication_p.h>
57 #include <QtGui/qinputmethod.h>
58 #include <QtCore/qdebug.h>
59 #include <QtCore/qcoreevent.h>
60 #include <QtCore/qnumeric.h>
61
62 #include <private/qqmlglobal_p.h>
63 #include <private/qqmlengine_p.h>
64 #include <QtQuick/private/qquickstategroup_p.h>
65 #include <private/qqmlopenmetaobject_p.h>
66 #include <QtQuick/private/qquickstate_p.h>
67 #include <private/qquickitem_p.h>
68 #include <private/qqmlaccessors_p.h>
69 #include <QtQuick/private/qquickaccessibleattached_p.h>
70
71 #ifndef QT_NO_CURSOR
72 # include <QtGui/qcursor.h>
73 #endif
74
75 #include <float.h>
76
77 // XXX todo Check that elements that create items handle memory correctly after visual ownership change
78
79 QT_BEGIN_NAMESPACE
80
81 #ifdef FOCUS_DEBUG
82 void printFocusTree(QQuickItem *item, QQuickItem *scope = 0, int depth = 1);
83 void printFocusTree(QQuickItem *item, QQuickItem *scope, int depth)
84 {
85     qWarning()
86             << QByteArray(depth, '\t').constData()
87             << (scope && QQuickItemPrivate::get(scope)->subFocusItem == item ? '*' : ' ')
88             << item->hasFocus()
89             << item->hasActiveFocus()
90             << item->isFocusScope()
91             << item;
92     foreach (QQuickItem *child, item->childItems()) {
93         printFocusTree(
94                 child,
95                 item->isFocusScope() || !scope ? item : scope,
96                 item->isFocusScope() || !scope ? depth + 1 : depth);
97     }
98 }
99 #endif
100
101 static void QQuickItem_parentNotifier(QObject *o, intptr_t, QQmlNotifier **n)
102 {
103     QQuickItemPrivate *d = QQuickItemPrivate::get(static_cast<QQuickItem *>(o));
104     *n = &d->parentNotifier;
105 }
106
107 QML_PRIVATE_ACCESSOR(QQuickItem, QQuickItem *, parent, parentItem)
108 QML_PRIVATE_ACCESSOR(QQuickItem, qreal, x, x)
109 QML_PRIVATE_ACCESSOR(QQuickItem, qreal, y, y)
110 QML_PRIVATE_ACCESSOR(QQuickItem, qreal, width, width)
111 QML_PRIVATE_ACCESSOR(QQuickItem, qreal, height, height)
112
113 static QQmlAccessors QQuickItem_parent = { QQuickItem_parentRead, QQuickItem_parentNotifier };
114 static QQmlAccessors QQuickItem_x = { QQuickItem_xRead, 0 };
115 static QQmlAccessors QQuickItem_y = { QQuickItem_yRead, 0 };
116 static QQmlAccessors QQuickItem_width = { QQuickItem_widthRead, 0 };
117 static QQmlAccessors QQuickItem_height = { QQuickItem_heightRead, 0 };
118
119 QML_DECLARE_PROPERTIES(QQuickItem) {
120     { QML_PROPERTY_NAME(parent), 0, &QQuickItem_parent },
121     { QML_PROPERTY_NAME(x), 0, &QQuickItem_x },
122     { QML_PROPERTY_NAME(y), 0, &QQuickItem_y },
123     { QML_PROPERTY_NAME(width), 0, &QQuickItem_width },
124     { QML_PROPERTY_NAME(height), 0, &QQuickItem_height }
125 };
126
127 void QQuickItemPrivate::registerAccessorProperties()
128 {
129     QML_DEFINE_PROPERTIES(QQuickItem);
130 }
131
132 /*!
133     \qmltype Transform
134     \instantiates QQuickTransform
135     \inqmlmodule QtQuick 2
136     \ingroup qtquick-visual-transforms
137     \brief For specifying advanced transformations on Items
138
139     The Transform type is a base type which cannot be instantiated directly.
140     The following concrete Transform types are available:
141
142     \list
143     \li \l Rotation
144     \li \l Scale
145     \li \l Translate
146     \endlist
147
148     The Transform types let you create and control advanced transformations that can be configured
149     independently using specialized properties.
150
151     You can assign any number of Transforms to an \l Item. Each Transform is applied in order,
152     one at a time.
153 */
154 QQuickTransformPrivate::QQuickTransformPrivate()
155 {
156 }
157
158 QQuickTransform::QQuickTransform(QObject *parent)
159 : QObject(*(new QQuickTransformPrivate), parent)
160 {
161 }
162
163 QQuickTransform::QQuickTransform(QQuickTransformPrivate &dd, QObject *parent)
164 : QObject(dd, parent)
165 {
166 }
167
168 QQuickTransform::~QQuickTransform()
169 {
170     Q_D(QQuickTransform);
171     for (int ii = 0; ii < d->items.count(); ++ii) {
172         QQuickItemPrivate *p = QQuickItemPrivate::get(d->items.at(ii));
173         p->transforms.removeOne(this);
174         p->dirty(QQuickItemPrivate::Transform);
175     }
176 }
177
178 void QQuickTransform::update()
179 {
180     Q_D(QQuickTransform);
181     for (int ii = 0; ii < d->items.count(); ++ii) {
182         QQuickItemPrivate *p = QQuickItemPrivate::get(d->items.at(ii));
183         p->dirty(QQuickItemPrivate::Transform);
184     }
185 }
186
187 QQuickContents::QQuickContents(QQuickItem *item)
188 : m_item(item), m_x(0), m_y(0), m_width(0), m_height(0)
189 {
190 }
191
192 QQuickContents::~QQuickContents()
193 {
194     QList<QQuickItem *> children = m_item->childItems();
195     for (int i = 0; i < children.count(); ++i) {
196         QQuickItem *child = children.at(i);
197         QQuickItemPrivate::get(child)->removeItemChangeListener(this, QQuickItemPrivate::Geometry | QQuickItemPrivate::Destroyed);
198     }
199 }
200
201 bool QQuickContents::calcHeight(QQuickItem *changed)
202 {
203     qreal oldy = m_y;
204     qreal oldheight = m_height;
205
206     if (changed) {
207         qreal top = oldy;
208         qreal bottom = oldy + oldheight;
209         qreal y = changed->y();
210         if (y + changed->height() > bottom)
211             bottom = y + changed->height();
212         if (y < top)
213             top = y;
214         m_y = top;
215         m_height = bottom - top;
216     } else {
217         qreal top = FLT_MAX;
218         qreal bottom = 0;
219         QList<QQuickItem *> children = m_item->childItems();
220         for (int i = 0; i < children.count(); ++i) {
221             QQuickItem *child = children.at(i);
222             qreal y = child->y();
223             if (y + child->height() > bottom)
224                 bottom = y + child->height();
225             if (y < top)
226                 top = y;
227         }
228         if (!children.isEmpty())
229             m_y = top;
230         m_height = qMax(bottom - top, qreal(0.0));
231     }
232
233     return (m_height != oldheight || m_y != oldy);
234 }
235
236 bool QQuickContents::calcWidth(QQuickItem *changed)
237 {
238     qreal oldx = m_x;
239     qreal oldwidth = m_width;
240
241     if (changed) {
242         qreal left = oldx;
243         qreal right = oldx + oldwidth;
244         qreal x = changed->x();
245         if (x + changed->width() > right)
246             right = x + changed->width();
247         if (x < left)
248             left = x;
249         m_x = left;
250         m_width = right - left;
251     } else {
252         qreal left = FLT_MAX;
253         qreal right = 0;
254         QList<QQuickItem *> children = m_item->childItems();
255         for (int i = 0; i < children.count(); ++i) {
256             QQuickItem *child = children.at(i);
257             qreal x = child->x();
258             if (x + child->width() > right)
259                 right = x + child->width();
260             if (x < left)
261                 left = x;
262         }
263         if (!children.isEmpty())
264             m_x = left;
265         m_width = qMax(right - left, qreal(0.0));
266     }
267
268     return (m_width != oldwidth || m_x != oldx);
269 }
270
271 void QQuickContents::complete()
272 {
273     QQuickItemPrivate::get(m_item)->addItemChangeListener(this, QQuickItemPrivate::Children);
274
275     QList<QQuickItem *> children = m_item->childItems();
276     for (int i = 0; i < children.count(); ++i) {
277         QQuickItem *child = children.at(i);
278         QQuickItemPrivate::get(child)->addItemChangeListener(this, QQuickItemPrivate::Geometry | QQuickItemPrivate::Destroyed);
279         //###what about changes to visibility?
280     }
281     calcGeometry();
282 }
283
284 void QQuickContents::updateRect()
285 {
286     QQuickItemPrivate::get(m_item)->emitChildrenRectChanged(rectF());
287 }
288
289 void QQuickContents::itemGeometryChanged(QQuickItem *changed, const QRectF &newGeometry, const QRectF &oldGeometry)
290 {
291     Q_UNUSED(changed)
292     bool wChanged = false;
293     bool hChanged = false;
294     //### we can only pass changed if the left edge has moved left, or the right edge has moved right
295     if (newGeometry.width() != oldGeometry.width() || newGeometry.x() != oldGeometry.x())
296         wChanged = calcWidth(/*changed*/);
297     if (newGeometry.height() != oldGeometry.height() || newGeometry.y() != oldGeometry.y())
298         hChanged = calcHeight(/*changed*/);
299     if (wChanged || hChanged)
300         updateRect();
301 }
302
303 void QQuickContents::itemDestroyed(QQuickItem *item)
304 {
305     if (item)
306         QQuickItemPrivate::get(item)->removeItemChangeListener(this, QQuickItemPrivate::Geometry | QQuickItemPrivate::Destroyed);
307     calcGeometry();
308 }
309
310 void QQuickContents::itemChildRemoved(QQuickItem *, QQuickItem *item)
311 {
312     if (item)
313         QQuickItemPrivate::get(item)->removeItemChangeListener(this, QQuickItemPrivate::Geometry | QQuickItemPrivate::Destroyed);
314     calcGeometry();
315 }
316
317 void QQuickContents::itemChildAdded(QQuickItem *, QQuickItem *item)
318 {
319     if (item)
320         QQuickItemPrivate::get(item)->addItemChangeListener(this, QQuickItemPrivate::Geometry | QQuickItemPrivate::Destroyed);
321     calcGeometry(item);
322 }
323
324 QQuickItemKeyFilter::QQuickItemKeyFilter(QQuickItem *item)
325 : m_processPost(false), m_next(0)
326 {
327     QQuickItemPrivate *p = item?QQuickItemPrivate::get(item):0;
328     if (p) {
329         m_next = p->extra.value().keyHandler;
330         p->extra->keyHandler = this;
331     }
332 }
333
334 QQuickItemKeyFilter::~QQuickItemKeyFilter()
335 {
336 }
337
338 void QQuickItemKeyFilter::keyPressed(QKeyEvent *event, bool post)
339 {
340     if (m_next) m_next->keyPressed(event, post);
341 }
342
343 void QQuickItemKeyFilter::keyReleased(QKeyEvent *event, bool post)
344 {
345     if (m_next) m_next->keyReleased(event, post);
346 }
347
348 void QQuickItemKeyFilter::inputMethodEvent(QInputMethodEvent *event, bool post)
349 {
350     if (m_next)
351         m_next->inputMethodEvent(event, post);
352     else
353         event->ignore();
354 }
355
356 QVariant QQuickItemKeyFilter::inputMethodQuery(Qt::InputMethodQuery query) const
357 {
358     if (m_next) return m_next->inputMethodQuery(query);
359     return QVariant();
360 }
361
362 void QQuickItemKeyFilter::componentComplete()
363 {
364     if (m_next) m_next->componentComplete();
365 }
366 /*!
367     \qmltype KeyNavigation
368     \instantiates QQuickKeyNavigationAttached
369     \inqmlmodule QtQuick 2
370     \ingroup qtquick-input
371     \brief Supports key navigation by arrow keys
372
373     Key-based user interfaces commonly allow the use of arrow keys to navigate between
374     focusable items.  The KeyNavigation attached property enables this behavior by providing a
375     convenient way to specify the item that should gain focus when an arrow or tab key is pressed.
376
377     The following example provides key navigation for a 2x2 grid of items:
378
379     \snippet qml/keynavigation.qml 0
380
381     The top-left item initially receives focus by setting \l {Item::}{focus} to
382     \c true. When an arrow key is pressed, the focus will move to the
383     appropriate item, as defined by the value that has been set for
384     the KeyNavigation \l left, \l right, \l up or \l down properties.
385
386     Note that if a KeyNavigation attached property receives the key press and release
387     events for a requested arrow or tab key, the event is accepted and does not
388     propagate any further.
389
390     By default, KeyNavigation receives key events after the item to which it is attached.
391     If the item accepts the key event, the KeyNavigation attached property will not
392     receive an event for that key.  Setting the \l priority property to
393     \c KeyNavigation.BeforeItem allows the event to be used for key navigation
394     before the item, rather than after.
395
396     If item to which the focus is switching is not enabled or visible, an attempt will
397     be made to skip this item and focus on the next. This is possible if there are
398     a chain of items with the same KeyNavigation handler. If multiple items in a row are not enabled
399     or visible, they will also be skipped.
400
401     KeyNavigation will implicitly set the other direction to return focus to this item. So if you set
402     \l left to another item, \l right will be set on that item's KeyNavigation to set focus back to this
403     item. However, if that item's KeyNavigation has had right explicitly set then no change will occur.
404     This means that the above example could have been written, with the same behaviour, without specifing
405     KeyNavigation.right or KeyNavigation.down for any of the items.
406
407     \sa {Keys}{Keys attached property}
408 */
409
410 /*!
411     \qmlproperty Item QtQuick2::KeyNavigation::left
412     \qmlproperty Item QtQuick2::KeyNavigation::right
413     \qmlproperty Item QtQuick2::KeyNavigation::up
414     \qmlproperty Item QtQuick2::KeyNavigation::down
415     \qmlproperty Item QtQuick2::KeyNavigation::tab
416     \qmlproperty Item QtQuick2::KeyNavigation::backtab
417
418     These properties hold the item to assign focus to
419     when the left, right, up or down cursor keys, or the
420     tab key are pressed.
421 */
422
423 /*!
424     \qmlproperty Item QtQuick2::KeyNavigation::tab
425     \qmlproperty Item QtQuick2::KeyNavigation::backtab
426
427     These properties hold the item to assign focus to
428     when the Tab key or Shift+Tab key combination (Backtab) are pressed.
429 */
430
431 QQuickKeyNavigationAttached::QQuickKeyNavigationAttached(QObject *parent)
432 : QObject(*(new QQuickKeyNavigationAttachedPrivate), parent),
433   QQuickItemKeyFilter(qmlobject_cast<QQuickItem*>(parent))
434 {
435     m_processPost = true;
436 }
437
438 QQuickKeyNavigationAttached *
439 QQuickKeyNavigationAttached::qmlAttachedProperties(QObject *obj)
440 {
441     return new QQuickKeyNavigationAttached(obj);
442 }
443
444 QQuickItem *QQuickKeyNavigationAttached::left() const
445 {
446     Q_D(const QQuickKeyNavigationAttached);
447     return d->left;
448 }
449
450 void QQuickKeyNavigationAttached::setLeft(QQuickItem *i)
451 {
452     Q_D(QQuickKeyNavigationAttached);
453     if (d->left == i)
454         return;
455     d->left = i;
456     d->leftSet = true;
457     QQuickKeyNavigationAttached* other =
458             qobject_cast<QQuickKeyNavigationAttached*>(qmlAttachedPropertiesObject<QQuickKeyNavigationAttached>(i));
459     if (other && !other->d_func()->rightSet){
460         other->d_func()->right = qobject_cast<QQuickItem*>(parent());
461         emit other->rightChanged();
462     }
463     emit leftChanged();
464 }
465
466 QQuickItem *QQuickKeyNavigationAttached::right() const
467 {
468     Q_D(const QQuickKeyNavigationAttached);
469     return d->right;
470 }
471
472 void QQuickKeyNavigationAttached::setRight(QQuickItem *i)
473 {
474     Q_D(QQuickKeyNavigationAttached);
475     if (d->right == i)
476         return;
477     d->right = i;
478     d->rightSet = true;
479     QQuickKeyNavigationAttached* other =
480             qobject_cast<QQuickKeyNavigationAttached*>(qmlAttachedPropertiesObject<QQuickKeyNavigationAttached>(i));
481     if (other && !other->d_func()->leftSet){
482         other->d_func()->left = qobject_cast<QQuickItem*>(parent());
483         emit other->leftChanged();
484     }
485     emit rightChanged();
486 }
487
488 QQuickItem *QQuickKeyNavigationAttached::up() const
489 {
490     Q_D(const QQuickKeyNavigationAttached);
491     return d->up;
492 }
493
494 void QQuickKeyNavigationAttached::setUp(QQuickItem *i)
495 {
496     Q_D(QQuickKeyNavigationAttached);
497     if (d->up == i)
498         return;
499     d->up = i;
500     d->upSet = true;
501     QQuickKeyNavigationAttached* other =
502             qobject_cast<QQuickKeyNavigationAttached*>(qmlAttachedPropertiesObject<QQuickKeyNavigationAttached>(i));
503     if (other && !other->d_func()->downSet){
504         other->d_func()->down = qobject_cast<QQuickItem*>(parent());
505         emit other->downChanged();
506     }
507     emit upChanged();
508 }
509
510 QQuickItem *QQuickKeyNavigationAttached::down() const
511 {
512     Q_D(const QQuickKeyNavigationAttached);
513     return d->down;
514 }
515
516 void QQuickKeyNavigationAttached::setDown(QQuickItem *i)
517 {
518     Q_D(QQuickKeyNavigationAttached);
519     if (d->down == i)
520         return;
521     d->down = i;
522     d->downSet = true;
523     QQuickKeyNavigationAttached* other =
524             qobject_cast<QQuickKeyNavigationAttached*>(qmlAttachedPropertiesObject<QQuickKeyNavigationAttached>(i));
525     if (other && !other->d_func()->upSet) {
526         other->d_func()->up = qobject_cast<QQuickItem*>(parent());
527         emit other->upChanged();
528     }
529     emit downChanged();
530 }
531
532 QQuickItem *QQuickKeyNavigationAttached::tab() const
533 {
534     Q_D(const QQuickKeyNavigationAttached);
535     return d->tab;
536 }
537
538 void QQuickKeyNavigationAttached::setTab(QQuickItem *i)
539 {
540     Q_D(QQuickKeyNavigationAttached);
541     if (d->tab == i)
542         return;
543     d->tab = i;
544     d->tabSet = true;
545     QQuickKeyNavigationAttached* other =
546             qobject_cast<QQuickKeyNavigationAttached*>(qmlAttachedPropertiesObject<QQuickKeyNavigationAttached>(i));
547     if (other && !other->d_func()->backtabSet) {
548         other->d_func()->backtab = qobject_cast<QQuickItem*>(parent());
549         emit other->backtabChanged();
550     }
551     emit tabChanged();
552 }
553
554 QQuickItem *QQuickKeyNavigationAttached::backtab() const
555 {
556     Q_D(const QQuickKeyNavigationAttached);
557     return d->backtab;
558 }
559
560 void QQuickKeyNavigationAttached::setBacktab(QQuickItem *i)
561 {
562     Q_D(QQuickKeyNavigationAttached);
563     if (d->backtab == i)
564         return;
565     d->backtab = i;
566     d->backtabSet = true;
567     QQuickKeyNavigationAttached* other =
568             qobject_cast<QQuickKeyNavigationAttached*>(qmlAttachedPropertiesObject<QQuickKeyNavigationAttached>(i));
569     if (other && !other->d_func()->tabSet) {
570         other->d_func()->tab = qobject_cast<QQuickItem*>(parent());
571         emit other->tabChanged();
572     }
573     emit backtabChanged();
574 }
575
576 /*!
577     \qmlproperty enumeration QtQuick2::KeyNavigation::priority
578
579     This property determines whether the keys are processed before
580     or after the attached item's own key handling.
581
582     \list
583     \li KeyNavigation.BeforeItem - process the key events before normal
584     item key processing.  If the event is used for key navigation, it will be accepted and will not
585     be passed on to the item.
586     \li KeyNavigation.AfterItem (default) - process the key events after normal item key
587     handling.  If the item accepts the key event it will not be
588     handled by the KeyNavigation attached property handler.
589     \endlist
590 */
591 QQuickKeyNavigationAttached::Priority QQuickKeyNavigationAttached::priority() const
592 {
593     return m_processPost ? AfterItem : BeforeItem;
594 }
595
596 void QQuickKeyNavigationAttached::setPriority(Priority order)
597 {
598     bool processPost = order == AfterItem;
599     if (processPost != m_processPost) {
600         m_processPost = processPost;
601         emit priorityChanged();
602     }
603 }
604
605 void QQuickKeyNavigationAttached::keyPressed(QKeyEvent *event, bool post)
606 {
607     Q_D(QQuickKeyNavigationAttached);
608     event->ignore();
609
610     if (post != m_processPost) {
611         QQuickItemKeyFilter::keyPressed(event, post);
612         return;
613     }
614
615     bool mirror = false;
616     switch (event->key()) {
617     case Qt::Key_Left: {
618         if (QQuickItem *parentItem = qobject_cast<QQuickItem*>(parent()))
619             mirror = QQuickItemPrivate::get(parentItem)->effectiveLayoutMirror;
620         QQuickItem* leftItem = mirror ? d->right : d->left;
621         if (leftItem) {
622             setFocusNavigation(leftItem, mirror ? "right" : "left");
623             event->accept();
624         }
625         break;
626     }
627     case Qt::Key_Right: {
628         if (QQuickItem *parentItem = qobject_cast<QQuickItem*>(parent()))
629             mirror = QQuickItemPrivate::get(parentItem)->effectiveLayoutMirror;
630         QQuickItem* rightItem = mirror ? d->left : d->right;
631         if (rightItem) {
632             setFocusNavigation(rightItem, mirror ? "left" : "right");
633             event->accept();
634         }
635         break;
636     }
637     case Qt::Key_Up:
638         if (d->up) {
639             setFocusNavigation(d->up, "up");
640             event->accept();
641         }
642         break;
643     case Qt::Key_Down:
644         if (d->down) {
645             setFocusNavigation(d->down, "down");
646             event->accept();
647         }
648         break;
649     case Qt::Key_Tab:
650         if (d->tab) {
651             setFocusNavigation(d->tab, "tab");
652             event->accept();
653         }
654         break;
655     case Qt::Key_Backtab:
656         if (d->backtab) {
657             setFocusNavigation(d->backtab, "backtab");
658             event->accept();
659         }
660         break;
661     default:
662         break;
663     }
664
665     if (!event->isAccepted()) QQuickItemKeyFilter::keyPressed(event, post);
666 }
667
668 void QQuickKeyNavigationAttached::keyReleased(QKeyEvent *event, bool post)
669 {
670     Q_D(QQuickKeyNavigationAttached);
671     event->ignore();
672
673     if (post != m_processPost) {
674         QQuickItemKeyFilter::keyReleased(event, post);
675         return;
676     }
677
678     bool mirror = false;
679     switch (event->key()) {
680     case Qt::Key_Left:
681         if (QQuickItem *parentItem = qobject_cast<QQuickItem*>(parent()))
682             mirror = QQuickItemPrivate::get(parentItem)->effectiveLayoutMirror;
683         if (mirror ? d->right : d->left)
684             event->accept();
685         break;
686     case Qt::Key_Right:
687         if (QQuickItem *parentItem = qobject_cast<QQuickItem*>(parent()))
688             mirror = QQuickItemPrivate::get(parentItem)->effectiveLayoutMirror;
689         if (mirror ? d->left : d->right)
690             event->accept();
691         break;
692     case Qt::Key_Up:
693         if (d->up) {
694             event->accept();
695         }
696         break;
697     case Qt::Key_Down:
698         if (d->down) {
699             event->accept();
700         }
701         break;
702     case Qt::Key_Tab:
703         if (d->tab) {
704             event->accept();
705         }
706         break;
707     case Qt::Key_Backtab:
708         if (d->backtab) {
709             event->accept();
710         }
711         break;
712     default:
713         break;
714     }
715
716     if (!event->isAccepted()) QQuickItemKeyFilter::keyReleased(event, post);
717 }
718
719 void QQuickKeyNavigationAttached::setFocusNavigation(QQuickItem *currentItem, const char *dir)
720 {
721     QQuickItem *initialItem = currentItem;
722     bool isNextItem = false;
723     do {
724         isNextItem = false;
725         if (currentItem->isVisible() && currentItem->isEnabled()) {
726             currentItem->setFocus(true);
727         } else {
728             QObject *attached =
729                 qmlAttachedPropertiesObject<QQuickKeyNavigationAttached>(currentItem, false);
730             if (attached) {
731                 QQuickItem *tempItem = qvariant_cast<QQuickItem*>(attached->property(dir));
732                 if (tempItem) {
733                     currentItem = tempItem;
734                     isNextItem = true;
735                 }
736             }
737         }
738     }
739     while (currentItem != initialItem && isNextItem);
740 }
741
742 const QQuickKeysAttached::SigMap QQuickKeysAttached::sigMap[] = {
743     { Qt::Key_Left, "leftPressed" },
744     { Qt::Key_Right, "rightPressed" },
745     { Qt::Key_Up, "upPressed" },
746     { Qt::Key_Down, "downPressed" },
747     { Qt::Key_Tab, "tabPressed" },
748     { Qt::Key_Backtab, "backtabPressed" },
749     { Qt::Key_Asterisk, "asteriskPressed" },
750     { Qt::Key_NumberSign, "numberSignPressed" },
751     { Qt::Key_Escape, "escapePressed" },
752     { Qt::Key_Return, "returnPressed" },
753     { Qt::Key_Enter, "enterPressed" },
754     { Qt::Key_Delete, "deletePressed" },
755     { Qt::Key_Space, "spacePressed" },
756     { Qt::Key_Back, "backPressed" },
757     { Qt::Key_Cancel, "cancelPressed" },
758     { Qt::Key_Select, "selectPressed" },
759     { Qt::Key_Yes, "yesPressed" },
760     { Qt::Key_No, "noPressed" },
761     { Qt::Key_Context1, "context1Pressed" },
762     { Qt::Key_Context2, "context2Pressed" },
763     { Qt::Key_Context3, "context3Pressed" },
764     { Qt::Key_Context4, "context4Pressed" },
765     { Qt::Key_Call, "callPressed" },
766     { Qt::Key_Hangup, "hangupPressed" },
767     { Qt::Key_Flip, "flipPressed" },
768     { Qt::Key_Menu, "menuPressed" },
769     { Qt::Key_VolumeUp, "volumeUpPressed" },
770     { Qt::Key_VolumeDown, "volumeDownPressed" },
771     { 0, 0 }
772 };
773
774 bool QQuickKeysAttached::isConnected(const char *signalName)
775 {
776     Q_D(QQuickKeysAttached);
777     int signal_index = d->signalIndex(signalName);
778     return d->isSignalConnected(signal_index);
779 }
780
781 /*!
782     \qmltype Keys
783     \instantiates QQuickKeysAttached
784     \inqmlmodule QtQuick 2
785     \ingroup qtquick-input
786     \brief Provides key handling to Items
787
788     All visual primitives support key handling via the Keys
789     attached property.  Keys can be handled via the onPressed
790     and onReleased signal properties.
791
792     The signal properties have a \l KeyEvent parameter, named
793     \e event which contains details of the event.  If a key is
794     handled \e event.accepted should be set to true to prevent the
795     event from propagating up the item hierarchy.
796
797     \section1 Example Usage
798
799     The following example shows how the general onPressed handler can
800     be used to test for a certain key; in this case, the left cursor
801     key:
802
803     \snippet qml/keys/keys-pressed.qml key item
804
805     Some keys may alternatively be handled via specific signal properties,
806     for example \e onSelectPressed.  These handlers automatically set
807     \e event.accepted to true.
808
809     \snippet qml/keys/keys-handler.qml key item
810
811     See \l{Qt::Key}{Qt.Key} for the list of keyboard codes.
812
813     \section1 Key Handling Priorities
814
815     The Keys attached property can be configured to handle key events
816     before or after the item it is attached to. This makes it possible
817     to intercept events in order to override an item's default behavior,
818     or act as a fallback for keys not handled by the item.
819
820     If \l priority is Keys.BeforeItem (default) the order of key event processing is:
821
822     \list 1
823     \li Items specified in \c forwardTo
824     \li specific key handlers, e.g. onReturnPressed
825     \li onKeyPress, onKeyRelease handlers
826     \li Item specific key handling, e.g. TextInput key handling
827     \li parent item
828     \endlist
829
830     If priority is Keys.AfterItem the order of key event processing is:
831
832     \list 1
833     \li Item specific key handling, e.g. TextInput key handling
834     \li Items specified in \c forwardTo
835     \li specific key handlers, e.g. onReturnPressed
836     \li onKeyPress, onKeyRelease handlers
837     \li parent item
838     \endlist
839
840     If the event is accepted during any of the above steps, key
841     propagation stops.
842
843     \sa KeyEvent, {KeyNavigation}{KeyNavigation attached property}
844 */
845
846 /*!
847     \qmlproperty bool QtQuick2::Keys::enabled
848
849     This flags enables key handling if true (default); otherwise
850     no key handlers will be called.
851 */
852
853 /*!
854     \qmlproperty enumeration QtQuick2::Keys::priority
855
856     This property determines whether the keys are processed before
857     or after the attached item's own key handling.
858
859     \list
860     \li Keys.BeforeItem (default) - process the key events before normal
861     item key processing.  If the event is accepted it will not
862     be passed on to the item.
863     \li Keys.AfterItem - process the key events after normal item key
864     handling.  If the item accepts the key event it will not be
865     handled by the Keys attached property handler.
866     \endlist
867 */
868
869 /*!
870     \qmlproperty list<Object> QtQuick2::Keys::forwardTo
871
872     This property provides a way to forward key presses, key releases, and keyboard input
873     coming from input methods to other items. This can be useful when you want
874     one item to handle some keys (e.g. the up and down arrow keys), and another item to
875     handle other keys (e.g. the left and right arrow keys).  Once an item that has been
876     forwarded keys accepts the event it is no longer forwarded to items later in the
877     list.
878
879     This example forwards key events to two lists:
880     \qml
881     Item {
882         ListView {
883             id: list1
884             // ...
885         }
886         ListView {
887             id: list2
888             // ...
889         }
890         Keys.forwardTo: [list1, list2]
891         focus: true
892     }
893     \endqml
894 */
895
896 /*!
897     \qmlsignal QtQuick2::Keys::onPressed(KeyEvent event)
898
899     This handler is called when a key has been pressed. The \a event
900     parameter provides information about the event.
901 */
902
903 /*!
904     \qmlsignal QtQuick2::Keys::onReleased(KeyEvent event)
905
906     This handler is called when a key has been released. The \a event
907     parameter provides information about the event.
908 */
909
910 /*!
911     \qmlsignal QtQuick2::Keys::onDigit0Pressed(KeyEvent event)
912
913     This handler is called when the digit '0' has been pressed. The \a event
914     parameter provides information about the event.
915 */
916
917 /*!
918     \qmlsignal QtQuick2::Keys::onDigit1Pressed(KeyEvent event)
919
920     This handler is called when the digit '1' has been pressed. The \a event
921     parameter provides information about the event.
922 */
923
924 /*!
925     \qmlsignal QtQuick2::Keys::onDigit2Pressed(KeyEvent event)
926
927     This handler is called when the digit '2' has been pressed. The \a event
928     parameter provides information about the event.
929 */
930
931 /*!
932     \qmlsignal QtQuick2::Keys::onDigit3Pressed(KeyEvent event)
933
934     This handler is called when the digit '3' has been pressed. The \a event
935     parameter provides information about the event.
936 */
937
938 /*!
939     \qmlsignal QtQuick2::Keys::onDigit4Pressed(KeyEvent event)
940
941     This handler is called when the digit '4' has been pressed. The \a event
942     parameter provides information about the event.
943 */
944
945 /*!
946     \qmlsignal QtQuick2::Keys::onDigit5Pressed(KeyEvent event)
947
948     This handler is called when the digit '5' has been pressed. The \a event
949     parameter provides information about the event.
950 */
951
952 /*!
953     \qmlsignal QtQuick2::Keys::onDigit6Pressed(KeyEvent event)
954
955     This handler is called when the digit '6' has been pressed. The \a event
956     parameter provides information about the event.
957 */
958
959 /*!
960     \qmlsignal QtQuick2::Keys::onDigit7Pressed(KeyEvent event)
961
962     This handler is called when the digit '7' has been pressed. The \a event
963     parameter provides information about the event.
964 */
965
966 /*!
967     \qmlsignal QtQuick2::Keys::onDigit8Pressed(KeyEvent event)
968
969     This handler is called when the digit '8' has been pressed. The \a event
970     parameter provides information about the event.
971 */
972
973 /*!
974     \qmlsignal QtQuick2::Keys::onDigit9Pressed(KeyEvent event)
975
976     This handler is called when the digit '9' has been pressed. The \a event
977     parameter provides information about the event.
978 */
979
980 /*!
981     \qmlsignal QtQuick2::Keys::onLeftPressed(KeyEvent event)
982
983     This handler is called when the Left arrow has been pressed. The \a event
984     parameter provides information about the event.
985 */
986
987 /*!
988     \qmlsignal QtQuick2::Keys::onRightPressed(KeyEvent event)
989
990     This handler is called when the Right arrow has been pressed. The \a event
991     parameter provides information about the event.
992 */
993
994 /*!
995     \qmlsignal QtQuick2::Keys::onUpPressed(KeyEvent event)
996
997     This handler is called when the Up arrow has been pressed. The \a event
998     parameter provides information about the event.
999 */
1000
1001 /*!
1002     \qmlsignal QtQuick2::Keys::onDownPressed(KeyEvent event)
1003
1004     This handler is called when the Down arrow has been pressed. The \a event
1005     parameter provides information about the event.
1006 */
1007
1008 /*!
1009     \qmlsignal QtQuick2::Keys::onTabPressed(KeyEvent event)
1010
1011     This handler is called when the Tab key has been pressed. The \a event
1012     parameter provides information about the event.
1013 */
1014
1015 /*!
1016     \qmlsignal QtQuick2::Keys::onBacktabPressed(KeyEvent event)
1017
1018     This handler is called when the Shift+Tab key combination (Backtab) has
1019     been pressed. The \a event parameter provides information about the event.
1020 */
1021
1022 /*!
1023     \qmlsignal QtQuick2::Keys::onAsteriskPressed(KeyEvent event)
1024
1025     This handler is called when the Asterisk '*' has been pressed. The \a event
1026     parameter provides information about the event.
1027 */
1028
1029 /*!
1030     \qmlsignal QtQuick2::Keys::onEscapePressed(KeyEvent event)
1031
1032     This handler is called when the Escape key has been pressed. The \a event
1033     parameter provides information about the event.
1034 */
1035
1036 /*!
1037     \qmlsignal QtQuick2::Keys::onReturnPressed(KeyEvent event)
1038
1039     This handler is called when the Return key has been pressed. The \a event
1040     parameter provides information about the event.
1041 */
1042
1043 /*!
1044     \qmlsignal QtQuick2::Keys::onEnterPressed(KeyEvent event)
1045
1046     This handler is called when the Enter key has been pressed. The \a event
1047     parameter provides information about the event.
1048 */
1049
1050 /*!
1051     \qmlsignal QtQuick2::Keys::onDeletePressed(KeyEvent event)
1052
1053     This handler is called when the Delete key has been pressed. The \a event
1054     parameter provides information about the event.
1055 */
1056
1057 /*!
1058     \qmlsignal QtQuick2::Keys::onSpacePressed(KeyEvent event)
1059
1060     This handler is called when the Space key has been pressed. The \a event
1061     parameter provides information about the event.
1062 */
1063
1064 /*!
1065     \qmlsignal QtQuick2::Keys::onBackPressed(KeyEvent event)
1066
1067     This handler is called when the Back key has been pressed. The \a event
1068     parameter provides information about the event.
1069 */
1070
1071 /*!
1072     \qmlsignal QtQuick2::Keys::onCancelPressed(KeyEvent event)
1073
1074     This handler is called when the Cancel key has been pressed. The \a event
1075     parameter provides information about the event.
1076 */
1077
1078 /*!
1079     \qmlsignal QtQuick2::Keys::onSelectPressed(KeyEvent event)
1080
1081     This handler is called when the Select key has been pressed. The \a event
1082     parameter provides information about the event.
1083 */
1084
1085 /*!
1086     \qmlsignal QtQuick2::Keys::onYesPressed(KeyEvent event)
1087
1088     This handler is called when the Yes key has been pressed. The \a event
1089     parameter provides information about the event.
1090 */
1091
1092 /*!
1093     \qmlsignal QtQuick2::Keys::onNoPressed(KeyEvent event)
1094
1095     This handler is called when the No key has been pressed. The \a event
1096     parameter provides information about the event.
1097 */
1098
1099 /*!
1100     \qmlsignal QtQuick2::Keys::onContext1Pressed(KeyEvent event)
1101
1102     This handler is called when the Context1 key has been pressed. The \a event
1103     parameter provides information about the event.
1104 */
1105
1106 /*!
1107     \qmlsignal QtQuick2::Keys::onContext2Pressed(KeyEvent event)
1108
1109     This handler is called when the Context2 key has been pressed. The \a event
1110     parameter provides information about the event.
1111 */
1112
1113 /*!
1114     \qmlsignal QtQuick2::Keys::onContext3Pressed(KeyEvent event)
1115
1116     This handler is called when the Context3 key has been pressed. The \a event
1117     parameter provides information about the event.
1118 */
1119
1120 /*!
1121     \qmlsignal QtQuick2::Keys::onContext4Pressed(KeyEvent event)
1122
1123     This handler is called when the Context4 key has been pressed. The \a event
1124     parameter provides information about the event.
1125 */
1126
1127 /*!
1128     \qmlsignal QtQuick2::Keys::onCallPressed(KeyEvent event)
1129
1130     This handler is called when the Call key has been pressed. The \a event
1131     parameter provides information about the event.
1132 */
1133
1134 /*!
1135     \qmlsignal QtQuick2::Keys::onHangupPressed(KeyEvent event)
1136
1137     This handler is called when the Hangup key has been pressed. The \a event
1138     parameter provides information about the event.
1139 */
1140
1141 /*!
1142     \qmlsignal QtQuick2::Keys::onFlipPressed(KeyEvent event)
1143
1144     This handler is called when the Flip key has been pressed. The \a event
1145     parameter provides information about the event.
1146 */
1147
1148 /*!
1149     \qmlsignal QtQuick2::Keys::onMenuPressed(KeyEvent event)
1150
1151     This handler is called when the Menu key has been pressed. The \a event
1152     parameter provides information about the event.
1153 */
1154
1155 /*!
1156     \qmlsignal QtQuick2::Keys::onVolumeUpPressed(KeyEvent event)
1157
1158     This handler is called when the VolumeUp key has been pressed. The \a event
1159     parameter provides information about the event.
1160 */
1161
1162 /*!
1163     \qmlsignal QtQuick2::Keys::onVolumeDownPressed(KeyEvent event)
1164
1165     This handler is called when the VolumeDown key has been pressed. The \a event
1166     parameter provides information about the event.
1167 */
1168
1169 QQuickKeysAttached::QQuickKeysAttached(QObject *parent)
1170 : QObject(*(new QQuickKeysAttachedPrivate), parent),
1171   QQuickItemKeyFilter(qmlobject_cast<QQuickItem*>(parent))
1172 {
1173     Q_D(QQuickKeysAttached);
1174     m_processPost = false;
1175     d->item = qmlobject_cast<QQuickItem*>(parent);
1176 }
1177
1178 QQuickKeysAttached::~QQuickKeysAttached()
1179 {
1180 }
1181
1182 QQuickKeysAttached::Priority QQuickKeysAttached::priority() const
1183 {
1184     return m_processPost ? AfterItem : BeforeItem;
1185 }
1186
1187 void QQuickKeysAttached::setPriority(Priority order)
1188 {
1189     bool processPost = order == AfterItem;
1190     if (processPost != m_processPost) {
1191         m_processPost = processPost;
1192         emit priorityChanged();
1193     }
1194 }
1195
1196 void QQuickKeysAttached::componentComplete()
1197 {
1198     Q_D(QQuickKeysAttached);
1199     if (d->item) {
1200         for (int ii = 0; ii < d->targets.count(); ++ii) {
1201             QQuickItem *targetItem = d->targets.at(ii);
1202             if (targetItem && (targetItem->flags() & QQuickItem::ItemAcceptsInputMethod)) {
1203                 d->item->setFlag(QQuickItem::ItemAcceptsInputMethod);
1204                 break;
1205             }
1206         }
1207     }
1208 }
1209
1210 void QQuickKeysAttached::keyPressed(QKeyEvent *event, bool post)
1211 {
1212     Q_D(QQuickKeysAttached);
1213     if (post != m_processPost || !d->enabled || d->inPress) {
1214         event->ignore();
1215         QQuickItemKeyFilter::keyPressed(event, post);
1216         return;
1217     }
1218
1219     // first process forwards
1220     if (d->item && d->item->window()) {
1221         d->inPress = true;
1222         for (int ii = 0; ii < d->targets.count(); ++ii) {
1223             QQuickItem *i = d->targets.at(ii);
1224             if (i && i->isVisible()) {
1225                 d->item->window()->sendEvent(i, event);
1226                 if (event->isAccepted()) {
1227                     d->inPress = false;
1228                     return;
1229                 }
1230             }
1231         }
1232         d->inPress = false;
1233     }
1234
1235     QQuickKeyEvent ke(*event);
1236     QByteArray keySignal = keyToSignal(event->key());
1237     if (!keySignal.isEmpty()) {
1238         keySignal += "(QQuickKeyEvent*)";
1239         if (isConnected(keySignal)) {
1240             // If we specifically handle a key then default to accepted
1241             ke.setAccepted(true);
1242             int idx = QQuickKeysAttached::staticMetaObject.indexOfSignal(keySignal);
1243             metaObject()->method(idx).invoke(this, Qt::DirectConnection, Q_ARG(QQuickKeyEvent*, &ke));
1244         }
1245     }
1246     if (!ke.isAccepted())
1247         emit pressed(&ke);
1248     event->setAccepted(ke.isAccepted());
1249
1250     if (!event->isAccepted()) QQuickItemKeyFilter::keyPressed(event, post);
1251 }
1252
1253 void QQuickKeysAttached::keyReleased(QKeyEvent *event, bool post)
1254 {
1255     Q_D(QQuickKeysAttached);
1256     if (post != m_processPost || !d->enabled || d->inRelease) {
1257         event->ignore();
1258         QQuickItemKeyFilter::keyReleased(event, post);
1259         return;
1260     }
1261
1262     if (d->item && d->item->window()) {
1263         d->inRelease = true;
1264         for (int ii = 0; ii < d->targets.count(); ++ii) {
1265             QQuickItem *i = d->targets.at(ii);
1266             if (i && i->isVisible()) {
1267                 d->item->window()->sendEvent(i, event);
1268                 if (event->isAccepted()) {
1269                     d->inRelease = false;
1270                     return;
1271                 }
1272             }
1273         }
1274         d->inRelease = false;
1275     }
1276
1277     QQuickKeyEvent ke(*event);
1278     emit released(&ke);
1279     event->setAccepted(ke.isAccepted());
1280
1281     if (!event->isAccepted()) QQuickItemKeyFilter::keyReleased(event, post);
1282 }
1283
1284 void QQuickKeysAttached::inputMethodEvent(QInputMethodEvent *event, bool post)
1285 {
1286     Q_D(QQuickKeysAttached);
1287     if (post == m_processPost && d->item && !d->inIM && d->item->window()) {
1288         d->inIM = true;
1289         for (int ii = 0; ii < d->targets.count(); ++ii) {
1290             QQuickItem *i = d->targets.at(ii);
1291             if (i && i->isVisible() && (i->flags() & QQuickItem::ItemAcceptsInputMethod)) {
1292                 d->item->window()->sendEvent(i, event);
1293                 if (event->isAccepted()) {
1294                     d->imeItem = i;
1295                     d->inIM = false;
1296                     return;
1297                 }
1298             }
1299         }
1300         d->inIM = false;
1301     }
1302     QQuickItemKeyFilter::inputMethodEvent(event, post);
1303 }
1304
1305 QVariant QQuickKeysAttached::inputMethodQuery(Qt::InputMethodQuery query) const
1306 {
1307     Q_D(const QQuickKeysAttached);
1308     if (d->item) {
1309         for (int ii = 0; ii < d->targets.count(); ++ii) {
1310             QQuickItem *i = d->targets.at(ii);
1311             if (i && i->isVisible() && (i->flags() & QQuickItem::ItemAcceptsInputMethod) && i == d->imeItem) {
1312                 //### how robust is i == d->imeItem check?
1313                 QVariant v = i->inputMethodQuery(query);
1314                 if (v.userType() == QVariant::RectF)
1315                     v = d->item->mapRectFromItem(i, v.toRectF());  //### cost?
1316                 return v;
1317             }
1318         }
1319     }
1320     return QQuickItemKeyFilter::inputMethodQuery(query);
1321 }
1322
1323 QQuickKeysAttached *QQuickKeysAttached::qmlAttachedProperties(QObject *obj)
1324 {
1325     return new QQuickKeysAttached(obj);
1326 }
1327
1328 /*!
1329     \qmltype LayoutMirroring
1330     \instantiates QQuickLayoutMirroringAttached
1331     \inqmlmodule QtQuick 2
1332     \ingroup qtquick-positioners
1333     \ingroup qml-utility-elements
1334     \brief Property used to mirror layout behavior
1335
1336     The LayoutMirroring attached property is used to horizontally mirror \l {anchor-layout}{Item anchors},
1337     \l{Item Layouts}{positioner} types (such as \l Row and \l Grid)
1338     and views (such as \l GridView and horizontal \l ListView). Mirroring is a visual change: left
1339     anchors become right anchors, and positioner types like \l Grid and \l Row reverse the
1340     horizontal layout of child items.
1341
1342     Mirroring is enabled for an item by setting the \l enabled property to true. By default, this
1343     only affects the item itself; setting the \l childrenInherit property to true propagates the mirroring
1344     behavior to all child items as well. If the \c LayoutMirroring attached property has not been defined
1345     for an item, mirroring is not enabled.
1346
1347     The following example shows mirroring in action. The \l Row below is specified as being anchored
1348     to the left of its parent. However, since mirroring has been enabled, the anchor is horizontally
1349     reversed and it is now anchored to the right. Also, since items in a \l Row are positioned
1350     from left to right by default, they are now positioned from right to left instead, as demonstrated
1351     by the numbering and opacity of the items:
1352
1353     \snippet qml/layoutmirroring.qml 0
1354
1355     \image layoutmirroring.png
1356
1357     Layout mirroring is useful when it is necessary to support both left-to-right and right-to-left
1358     layout versions of an application to target different language areas. The \l childrenInherit
1359     property allows layout mirroring to be applied without manually setting layout configurations
1360     for every item in an application. Keep in mind, however, that mirroring does not affect any
1361     positioning that is defined by the \l Item \l {Item::}{x} coordinate value, so even with
1362     mirroring enabled, it will often be necessary to apply some layout fixes to support the
1363     desired layout direction. Also, it may be necessary to disable the mirroring of individual
1364     child items (by setting \l {enabled}{LayoutMirroring.enabled} to false for such items) if
1365     mirroring is not the desired behavior, or if the child item already implements mirroring in
1366     some custom way.
1367
1368     See \l {Right-to-left User Interfaces} for further details on using \c LayoutMirroring and
1369     other related features to implement right-to-left support for an application.
1370 */
1371
1372 /*!
1373     \qmlproperty bool QtQuick2::LayoutMirroring::enabled
1374
1375     This property holds whether the item's layout is mirrored horizontally. Setting this to true
1376     horizontally reverses \l {anchor-layout}{anchor} settings such that left anchors become right,
1377     and right anchors become left. For \l{Item Layouts}{positioner} types
1378     (such as \l Row and \l Grid) and view types (such as \l {GridView}{GridView} and \l {ListView}{ListView})
1379     this also mirrors the horizontal layout direction of the item.
1380
1381     The default value is false.
1382 */
1383
1384 /*!
1385     \qmlproperty bool QtQuick2::LayoutMirroring::childrenInherit
1386
1387     This property holds whether the \l {enabled}{LayoutMirroring.enabled} value for this item
1388     is inherited by its children.
1389
1390     The default value is false.
1391 */
1392
1393
1394 QQuickLayoutMirroringAttached::QQuickLayoutMirroringAttached(QObject *parent) : QObject(parent), itemPrivate(0)
1395 {
1396     if (QQuickItem *item = qobject_cast<QQuickItem*>(parent)) {
1397         itemPrivate = QQuickItemPrivate::get(item);
1398         itemPrivate->extra.value().layoutDirectionAttached = this;
1399     } else
1400         qmlInfo(parent) << tr("LayoutDirection attached property only works with Items");
1401 }
1402
1403 QQuickLayoutMirroringAttached * QQuickLayoutMirroringAttached::qmlAttachedProperties(QObject *object)
1404 {
1405     return new QQuickLayoutMirroringAttached(object);
1406 }
1407
1408 bool QQuickLayoutMirroringAttached::enabled() const
1409 {
1410     return itemPrivate ? itemPrivate->effectiveLayoutMirror : false;
1411 }
1412
1413 void QQuickLayoutMirroringAttached::setEnabled(bool enabled)
1414 {
1415     if (!itemPrivate)
1416         return;
1417
1418     itemPrivate->isMirrorImplicit = false;
1419     if (enabled != itemPrivate->effectiveLayoutMirror) {
1420         itemPrivate->setLayoutMirror(enabled);
1421         if (itemPrivate->inheritMirrorFromItem)
1422              itemPrivate->resolveLayoutMirror();
1423     }
1424 }
1425
1426 void QQuickLayoutMirroringAttached::resetEnabled()
1427 {
1428     if (itemPrivate && !itemPrivate->isMirrorImplicit) {
1429         itemPrivate->isMirrorImplicit = true;
1430         itemPrivate->resolveLayoutMirror();
1431     }
1432 }
1433
1434 bool QQuickLayoutMirroringAttached::childrenInherit() const
1435 {
1436     return itemPrivate ? itemPrivate->inheritMirrorFromItem : false;
1437 }
1438
1439 void QQuickLayoutMirroringAttached::setChildrenInherit(bool childrenInherit) {
1440     if (itemPrivate && childrenInherit != itemPrivate->inheritMirrorFromItem) {
1441         itemPrivate->inheritMirrorFromItem = childrenInherit;
1442         itemPrivate->resolveLayoutMirror();
1443         childrenInheritChanged();
1444     }
1445 }
1446
1447 void QQuickItemPrivate::resolveLayoutMirror()
1448 {
1449     Q_Q(QQuickItem);
1450     if (QQuickItem *parentItem = q->parentItem()) {
1451         QQuickItemPrivate *parentPrivate = QQuickItemPrivate::get(parentItem);
1452         setImplicitLayoutMirror(parentPrivate->inheritedLayoutMirror, parentPrivate->inheritMirrorFromParent);
1453     } else {
1454         setImplicitLayoutMirror(isMirrorImplicit ? false : effectiveLayoutMirror, inheritMirrorFromItem);
1455     }
1456 }
1457
1458 void QQuickItemPrivate::setImplicitLayoutMirror(bool mirror, bool inherit)
1459 {
1460     inherit = inherit || inheritMirrorFromItem;
1461     if (!isMirrorImplicit && inheritMirrorFromItem)
1462         mirror = effectiveLayoutMirror;
1463     if (mirror == inheritedLayoutMirror && inherit == inheritMirrorFromParent)
1464         return;
1465
1466     inheritMirrorFromParent = inherit;
1467     inheritedLayoutMirror = inheritMirrorFromParent ? mirror : false;
1468
1469     if (isMirrorImplicit)
1470         setLayoutMirror(inherit ? inheritedLayoutMirror : false);
1471     for (int i = 0; i < childItems.count(); ++i) {
1472         if (QQuickItem *child = qmlobject_cast<QQuickItem *>(childItems.at(i))) {
1473             QQuickItemPrivate *childPrivate = QQuickItemPrivate::get(child);
1474             childPrivate->setImplicitLayoutMirror(inheritedLayoutMirror, inheritMirrorFromParent);
1475         }
1476     }
1477 }
1478
1479 void QQuickItemPrivate::setLayoutMirror(bool mirror)
1480 {
1481     if (mirror != effectiveLayoutMirror) {
1482         effectiveLayoutMirror = mirror;
1483         if (_anchors) {
1484             QQuickAnchorsPrivate *anchor_d = QQuickAnchorsPrivate::get(_anchors);
1485             anchor_d->fillChanged();
1486             anchor_d->centerInChanged();
1487             anchor_d->updateHorizontalAnchors();
1488         }
1489         mirrorChange();
1490         if (extra.isAllocated() && extra->layoutDirectionAttached) {
1491             emit extra->layoutDirectionAttached->enabledChanged();
1492         }
1493     }
1494 }
1495
1496 void QQuickItemPrivate::setAccessibleFlagAndListener()
1497 {
1498     Q_Q(QQuickItem);
1499     QQuickItem *item = q;
1500     while (item) {
1501         if (item->d_func()->isAccessible)
1502             break; // already set - grandparents should have the flag set as well.
1503
1504         item->d_func()->isAccessible = true;
1505         item = item->d_func()->parentItem;
1506     }
1507 }
1508
1509 void QQuickItemPrivate::updateSubFocusItem(QQuickItem *scope, bool focus)
1510 {
1511     Q_Q(QQuickItem);
1512     Q_ASSERT(scope);
1513
1514     QQuickItemPrivate *scopePrivate = QQuickItemPrivate::get(scope);
1515
1516     QQuickItem *oldSubFocusItem = scopePrivate->subFocusItem;
1517     // Correct focus chain in scope
1518     if (oldSubFocusItem) {
1519         QQuickItem *sfi = scopePrivate->subFocusItem->parentItem();
1520         while (sfi && sfi != scope) {
1521             QQuickItemPrivate::get(sfi)->subFocusItem = 0;
1522             sfi = sfi->parentItem();
1523         }
1524     }
1525
1526     if (focus) {
1527         scopePrivate->subFocusItem = q;
1528         QQuickItem *sfi = scopePrivate->subFocusItem->parentItem();
1529         while (sfi && sfi != scope) {
1530             QQuickItemPrivate::get(sfi)->subFocusItem = q;
1531             sfi = sfi->parentItem();
1532         }
1533     } else {
1534         scopePrivate->subFocusItem = 0;
1535     }
1536 }
1537
1538 /*!
1539     \class QQuickItem
1540     \brief The QQuickItem class provides the most basic of all visual items in QtQuick.
1541     \inmodule QtQuick
1542
1543     All visual items in Qt Quick inherit from QQuickItem. Although a QQuickItem
1544     instance has no visual appearance, it defines all the attributes that are
1545     common across visual items, such as x and y position, width and height,
1546     \l {Positioning with Anchors}{anchoring} and key handling support.
1547
1548     You can subclass QQuickItem to provide your own custom visual item
1549     that inherits these features.
1550
1551     \section2 Custom Items using Scene Graph
1552
1553     All visual QML items are rendered using the scene graph, a
1554     low-level, high-performance rendering stack, closely tied to
1555     OpenGL. It is possible for subclasses of QQuickItem to add their
1556     own custom content into the scene graph by setting the
1557     QQuickItem::ItemHasContents flag and reimplementing the
1558     QQuickItem::updatePaintNode() function.
1559
1560     \warning It is crucial that OpenGL operations and interaction with
1561     the scene graph happens exclusively on the rendering thread,
1562     primarily during the updatePaintNode() call. The best rule of
1563     thumb is to only use classes with the "QSG" prefix inside the
1564     QQuickItem::updatePaintNode() function.
1565
1566     To read more about how the scene graph rendering works, see
1567     \l{Scene Graph and Rendering}
1568
1569     \section2 Custom Items using QPainter
1570
1571     The QQuickItem provides a subclass, QQuickPaintedItem, which
1572     allows the users to render content using QPainter.
1573
1574     \warning Using QQuickPaintedItem uses an indirect 2D surface to
1575     render its content, either using software rasterization or using
1576     an OpenGL framebuffer object (FBO), so the rendering is a two-step
1577     operation. First rasterize the surface, then draw the
1578     surface. Using scene graph API directly is always significantly
1579     faster.
1580
1581     \sa QQuickWindow, QQuickPaintedItem
1582 */
1583
1584 /*!
1585     \qmltype Item
1586     \instantiates QQuickItem
1587     \inherits QtObject
1588     \inqmlmodule QtQuick 2
1589     \ingroup qtquick-visual
1590     \brief A basic visual QML type
1591
1592     The Item type is the base type for all visual items in Qt Quick.
1593
1594     All visual items in Qt Quick inherit from Item. Although an Item
1595     object has no visual appearance, it defines all the attributes that are
1596     common across visual items, such as x and y position, width and height,
1597     \l {Positioning with Anchors}{anchoring} and key handling support.
1598
1599     The Item type can be useful for grouping several items under a single
1600     root visual item. For example:
1601
1602     \qml
1603     import QtQuick 2.0
1604
1605     Item {
1606         Image {
1607             source: "tile.png"
1608         }
1609         Image {
1610             x: 80
1611             width: 100
1612             height: 100
1613             source: "tile.png"
1614         }
1615         Image {
1616             x: 190
1617             width: 100
1618             height: 100
1619             fillMode: Image.Tile
1620             source: "tile.png"
1621         }
1622     }
1623     \endqml
1624
1625
1626     \section2 Key Handling
1627
1628     Key handling is available to all Item-based visual types via the \l Keys
1629     attached property.  The \e Keys attached property provides basic handlers
1630     such as \l {Keys::}{onPressed} and \l {Keys}{::onReleased}, as well as
1631     handlers for specific keys, such as \l {Keys::}{onSpacePressed}.  The
1632     example below assigns \l {Keyboard Focus in Qt Quick}{keyboard focus} to
1633     the item and handles the left key via the general \e onPressed handler
1634     and the return key via the onReturnPressed handler:
1635
1636     \qml
1637     import QtQuick 2.0
1638
1639     Item {
1640         focus: true
1641         Keys.onPressed: {
1642             if (event.key == Qt.Key_Left) {
1643                 console.log("move left");
1644                 event.accepted = true;
1645             }
1646         }
1647         Keys.onReturnPressed: console.log("Pressed return");
1648     }
1649     \endqml
1650
1651     See the \l Keys attached property for detailed documentation.
1652
1653     \section2 Layout Mirroring
1654
1655     Item layouts can be mirrored using the \l LayoutMirroring attached
1656     property. This causes \l{anchors.top}{anchors} to be horizontally
1657     reversed, and also causes items that lay out or position their children
1658     (such as ListView or \l Row) to horizontally reverse the direction of
1659     their layouts.
1660
1661     See LayoutMirroring for more details.
1662 */
1663
1664 /*!
1665     \enum QQuickItem::Flag
1666
1667     This enum type is used to specify various item properties.
1668
1669     \value ItemClipsChildrenToShape Indicates this item should visually clip
1670     its children so that they are rendered only within the boundaries of this
1671     item.
1672     \value ItemAcceptsInputMethod Indicates the item supports text input
1673     methods.
1674     \value ItemIsFocusScope Indicates the item is a focus scope. See
1675     \l {Keyboard Focus in Qt Quick} for more information.
1676     \value ItemHasContents Indicates the item has visual content and should be
1677     rendered by the scene graph.
1678     \value ItemAcceptsDrops Indicates the item accepts drag and drop events.
1679
1680     \sa setFlag(), setFlags(), flags()
1681 */
1682
1683 /*!
1684     \enum QQuickItem::ItemChange
1685     \internal
1686 */
1687
1688 /*!
1689     \enum QQuickItem::TransformOrigin
1690
1691     Controls the point about which simple transforms like scale apply.
1692
1693     \value TopLeft The top-left corner of the item.
1694     \value Top The center point of the top of the item.
1695     \value TopRight The top-right corner of the item.
1696     \value Left The left most point of the vertical middle.
1697     \value Center The center of the item.
1698     \value Right The right most point of the vertical middle.
1699     \value BottomLeft The bottom-left corner of the item.
1700     \value Bottom The center point of the bottom of the item.
1701     \value BottomRight The bottom-right corner of the item.
1702
1703     \sa transformOrigin
1704 */
1705
1706 /*!
1707     \fn void QQuickItem::childrenRectChanged(const QRectF &)
1708     \internal
1709 */
1710
1711 /*!
1712     \fn void QQuickItem::baselineOffsetChanged(qreal)
1713     \internal
1714 */
1715
1716 /*!
1717     \fn void QQuickItem::stateChanged(const QString &state)
1718     \internal
1719 */
1720
1721 /*!
1722     \fn void QQuickItem::parentChanged(QQuickItem *)
1723     \internal
1724 */
1725
1726 /*!
1727     \fn void QQuickItem::smoothChanged(bool)
1728     \internal
1729 */
1730
1731 /*!
1732     \fn void QQuickItem::antialiasingChanged(bool)
1733     \internal
1734 */
1735
1736 /*!
1737     \fn void QQuickItem::clipChanged(bool)
1738     \internal
1739 */
1740
1741 /*!
1742     \fn void QQuickItem::transformOriginChanged(TransformOrigin)
1743     \internal
1744 */
1745
1746 /*!
1747     \fn void QQuickItem::focusChanged(bool)
1748     \internal
1749 */
1750
1751 /*!
1752     \fn void QQuickItem::activeFocusChanged(bool)
1753     \internal
1754 */
1755
1756 /*!
1757     \fn void QQuickItem::childrenChanged()
1758     \internal
1759 */
1760
1761 /*!
1762     \fn void QQuickItem::opacityChanged()
1763     \internal
1764 */
1765
1766 /*!
1767     \fn void QQuickItem::enabledChanged()
1768     \internal
1769 */
1770
1771 /*!
1772     \fn void QQuickItem::visibleChanged()
1773     \internal
1774 */
1775
1776 /*!
1777     \fn void QQuickItem::visibleChildrenChanged()
1778     \internal
1779 */
1780
1781 /*!
1782     \fn void QQuickItem::rotationChanged()
1783     \internal
1784 */
1785
1786 /*!
1787     \fn void QQuickItem::scaleChanged()
1788     \internal
1789 */
1790
1791 /*!
1792     \fn void QQuickItem::xChanged()
1793     \internal
1794 */
1795
1796 /*!
1797     \fn void QQuickItem::yChanged()
1798     \internal
1799 */
1800
1801 /*!
1802     \fn void QQuickItem::widthChanged()
1803     \internal
1804 */
1805
1806 /*!
1807     \fn void QQuickItem::heightChanged()
1808     \internal
1809 */
1810
1811 /*!
1812     \fn void QQuickItem::zChanged()
1813     \internal
1814 */
1815
1816 /*!
1817     \fn void QQuickItem::implicitWidthChanged()
1818     \internal
1819 */
1820
1821 /*!
1822     \fn void QQuickItem::implicitHeightChanged()
1823     \internal
1824 */
1825
1826 /*!
1827     \fn QQuickItem::QQuickItem(QQuickItem *parent)
1828
1829     Constructs a QQuickItem with the given \a parent.
1830 */
1831 QQuickItem::QQuickItem(QQuickItem* parent)
1832 : QObject(*(new QQuickItemPrivate), parent)
1833 {
1834     Q_D(QQuickItem);
1835     d->init(parent);
1836 }
1837
1838 /*! \internal
1839 */
1840 QQuickItem::QQuickItem(QQuickItemPrivate &dd, QQuickItem *parent)
1841 : QObject(dd, parent)
1842 {
1843     Q_D(QQuickItem);
1844     d->init(parent);
1845 }
1846
1847 #ifndef QT_NO_DEBUG
1848 static int qt_item_count = 0;
1849
1850 static void qt_print_item_count()
1851 {
1852     qDebug("Number of leaked items: %i", qt_item_count);
1853     qt_item_count = -1;
1854 }
1855 #endif
1856
1857 /*!
1858     Destroys the QQuickItem.
1859 */
1860 QQuickItem::~QQuickItem()
1861 {
1862 #ifndef QT_NO_DEBUG
1863     --qt_item_count;
1864     if (qt_item_count < 0)
1865         qDebug("Item destroyed after qt_print_item_count() was called.");
1866 #endif
1867
1868     Q_D(QQuickItem);
1869
1870     if (d->windowRefCount > 1)
1871         d->windowRefCount = 1; // Make sure window is set to null in next call to derefWindow().
1872     if (d->parentItem)
1873         setParentItem(0);
1874     else if (d->window)
1875         d->derefWindow();
1876
1877     // XXX todo - optimize
1878     while (!d->childItems.isEmpty())
1879         d->childItems.first()->setParentItem(0);
1880
1881     for (int ii = 0; ii < d->changeListeners.count(); ++ii) {
1882         QQuickAnchorsPrivate *anchor = d->changeListeners.at(ii).listener->anchorPrivate();
1883         if (anchor)
1884             anchor->clearItem(this);
1885     }
1886
1887     /*
1888         update item anchors that depended on us unless they are our child (and will also be destroyed),
1889         or our sibling, and our parent is also being destroyed.
1890     */
1891     for (int ii = 0; ii < d->changeListeners.count(); ++ii) {
1892         QQuickAnchorsPrivate *anchor = d->changeListeners.at(ii).listener->anchorPrivate();
1893         if (anchor && anchor->item && anchor->item->parentItem() && anchor->item->parentItem() != this)
1894             anchor->update();
1895     }
1896
1897     for (int ii = 0; ii < d->changeListeners.count(); ++ii) {
1898         const QQuickItemPrivate::ChangeListener &change = d->changeListeners.at(ii);
1899         if (change.types & QQuickItemPrivate::Destroyed)
1900             change.listener->itemDestroyed(this);
1901     }
1902
1903     d->changeListeners.clear();
1904
1905     if (d->extra.isAllocated()) {
1906         delete d->extra->contents; d->extra->contents = 0;
1907         delete d->extra->layer; d->extra->layer = 0;
1908     }
1909
1910     delete d->_anchors; d->_anchors = 0;
1911     delete d->_stateGroup; d->_stateGroup = 0;
1912 }
1913
1914 /*!
1915     \qmlproperty Item QtQuick2::Item::parent
1916     This property holds the visual parent of the item.
1917
1918     \note The concept of the \e {visual parent} differs from that of the
1919     \e {QObject parent}. An item's visual parent may not necessarily be the
1920     same as its object parent. See \l {Concepts - Visual Parent in Qt Quick}
1921     for more details.
1922 */
1923 /*!
1924     \property QQuickItem::parent
1925     This property holds the visual parent of the item.
1926
1927     \note The concept of the \e {visual parent} differs from that of the
1928     \e {QObject parent}. An item's visual parent may not necessarily be the
1929     same as its object parent. See \l {Concepts - Visual Parent in Qt Quick}
1930     for more details.
1931 */
1932 QQuickItem *QQuickItem::parentItem() const
1933 {
1934     Q_D(const QQuickItem);
1935     return d->parentItem;
1936 }
1937
1938 void QQuickItem::setParentItem(QQuickItem *parentItem)
1939 {
1940     Q_D(QQuickItem);
1941     if (parentItem == d->parentItem)
1942         return;
1943
1944     if (parentItem) {
1945         QQuickItem *itemAncestor = parentItem->parentItem();
1946         while (itemAncestor != 0) {
1947             if (itemAncestor == this) {
1948                 qWarning("QQuickItem::setParentItem: Parent is already part of this items subtree.");
1949                 return;
1950             }
1951             itemAncestor = itemAncestor->parentItem();
1952         }
1953     }
1954
1955     d->removeFromDirtyList();
1956
1957     QQuickItem *oldParentItem = d->parentItem;
1958     QQuickItem *scopeFocusedItem = 0;
1959
1960     if (oldParentItem) {
1961         QQuickItemPrivate *op = QQuickItemPrivate::get(oldParentItem);
1962
1963         QQuickItem *scopeItem = 0;
1964
1965         if (hasFocus())
1966             scopeFocusedItem = this;
1967         else if (!isFocusScope() && d->subFocusItem)
1968             scopeFocusedItem = d->subFocusItem;
1969
1970         if (scopeFocusedItem) {
1971             scopeItem = oldParentItem;
1972             while (!scopeItem->isFocusScope() && scopeItem->parentItem())
1973                 scopeItem = scopeItem->parentItem();
1974             if (d->window) {
1975                 QQuickWindowPrivate::get(d->window)->clearFocusInScope(scopeItem, scopeFocusedItem,
1976                                                                 QQuickWindowPrivate::DontChangeFocusProperty);
1977                 if (scopeFocusedItem != this)
1978                     QQuickItemPrivate::get(scopeFocusedItem)->updateSubFocusItem(this, true);
1979             } else {
1980                 QQuickItemPrivate::get(scopeFocusedItem)->updateSubFocusItem(scopeItem, false);
1981             }
1982         }
1983
1984         const bool wasVisible = isVisible();
1985         op->removeChild(this);
1986         if (wasVisible) {
1987             emit oldParentItem->visibleChildrenChanged();
1988         }
1989     } else if (d->window) {
1990         QQuickWindowPrivate::get(d->window)->parentlessItems.remove(this);
1991     }
1992
1993     QQuickWindow *oldParentWindow = oldParentItem ? QQuickItemPrivate::get(oldParentItem)->window : 0;
1994     QQuickWindow *parentWindow = parentItem ? QQuickItemPrivate::get(parentItem)->window : 0;
1995     if (oldParentWindow == parentWindow) {
1996         // Avoid freeing and reallocating resources if the window stays the same.
1997         d->parentItem = parentItem;
1998     } else {
1999         if (oldParentWindow)
2000             d->derefWindow();
2001         d->parentItem = parentItem;
2002         if (parentWindow)
2003             d->refWindow(parentWindow);
2004     }
2005
2006     d->dirty(QQuickItemPrivate::ParentChanged);
2007
2008     if (d->parentItem)
2009         QQuickItemPrivate::get(d->parentItem)->addChild(this);
2010     else if (d->window)
2011         QQuickWindowPrivate::get(d->window)->parentlessItems.insert(this);
2012
2013     d->setEffectiveVisibleRecur(d->calcEffectiveVisible());
2014     d->setEffectiveEnableRecur(0, d->calcEffectiveEnable());
2015
2016     if (d->parentItem) {
2017         if (!scopeFocusedItem) {
2018             if (hasFocus())
2019                 scopeFocusedItem = this;
2020             else if (!isFocusScope() && d->subFocusItem)
2021                 scopeFocusedItem = d->subFocusItem;
2022         }
2023
2024         if (scopeFocusedItem) {
2025             // We need to test whether this item becomes scope focused
2026             QQuickItem *scopeItem = d->parentItem;
2027             while (!scopeItem->isFocusScope() && scopeItem->parentItem())
2028                 scopeItem = scopeItem->parentItem();
2029
2030             if (QQuickItemPrivate::get(scopeItem)->subFocusItem
2031                     || (!scopeItem->isFocusScope() && scopeItem->hasFocus())) {
2032                 if (scopeFocusedItem != this)
2033                     QQuickItemPrivate::get(scopeFocusedItem)->updateSubFocusItem(this, false);
2034                 QQuickItemPrivate::get(scopeFocusedItem)->focus = false;
2035                 emit scopeFocusedItem->focusChanged(false);
2036             } else {
2037                 if (d->window) {
2038                     QQuickWindowPrivate::get(d->window)->setFocusInScope(scopeItem, scopeFocusedItem,
2039                                                                   QQuickWindowPrivate::DontChangeFocusProperty);
2040                 } else {
2041                     QQuickItemPrivate::get(scopeFocusedItem)->updateSubFocusItem(scopeItem, true);
2042                 }
2043             }
2044         }
2045     }
2046
2047     d->resolveLayoutMirror();
2048
2049     d->itemChange(ItemParentHasChanged, d->parentItem);
2050
2051     d->parentNotifier.notify();
2052     if (d->isAccessible && d->parentItem) {
2053         d->parentItem->d_func()->setAccessibleFlagAndListener();
2054     }
2055
2056     emit parentChanged(d->parentItem);
2057     if (isVisible() && d->parentItem)
2058         emit d->parentItem->visibleChildrenChanged();
2059 }
2060
2061 /*!
2062     Moves the specified \a sibling item to the index before this item
2063     within the visual stacking order.
2064
2065     The given \a sibling must be a sibling of this item; that is, they must
2066     have the same immediate \l parent.
2067
2068     \sa {Concepts - Visual Parent in Qt Quick}
2069 */
2070 void QQuickItem::stackBefore(const QQuickItem *sibling)
2071 {
2072     Q_D(QQuickItem);
2073     if (!sibling || sibling == this || !d->parentItem || d->parentItem != QQuickItemPrivate::get(sibling)->parentItem) {
2074         qWarning("QQuickItem::stackBefore: Cannot stack before %p, which must be a sibling", sibling);
2075         return;
2076     }
2077
2078     QQuickItemPrivate *parentPrivate = QQuickItemPrivate::get(d->parentItem);
2079
2080     int myIndex = parentPrivate->childItems.lastIndexOf(this);
2081     int siblingIndex = parentPrivate->childItems.lastIndexOf(const_cast<QQuickItem *>(sibling));
2082
2083     Q_ASSERT(myIndex != -1 && siblingIndex != -1);
2084
2085     if (myIndex == siblingIndex - 1)
2086         return;
2087
2088     parentPrivate->childItems.move(myIndex, myIndex < siblingIndex ? siblingIndex - 1 : siblingIndex);
2089
2090     parentPrivate->dirty(QQuickItemPrivate::ChildrenStackingChanged);
2091     parentPrivate->markSortedChildrenDirty(this);
2092
2093     for (int ii = qMin(siblingIndex, myIndex); ii < parentPrivate->childItems.count(); ++ii)
2094         QQuickItemPrivate::get(parentPrivate->childItems.at(ii))->siblingOrderChanged();
2095 }
2096
2097 /*!
2098     Moves the specified \a sibling item to the index after this item
2099     within the visual stacking order.
2100
2101     The given \a sibling must be a sibling of this item; that is, they must
2102     have the same immediate \l parent.
2103
2104     \sa {Concepts - Visual Parent in Qt Quick}
2105 */
2106 void QQuickItem::stackAfter(const QQuickItem *sibling)
2107 {
2108     Q_D(QQuickItem);
2109     if (!sibling || sibling == this || !d->parentItem || d->parentItem != QQuickItemPrivate::get(sibling)->parentItem) {
2110         qWarning("QQuickItem::stackAfter: Cannot stack after %p, which must be a sibling", sibling);
2111         return;
2112     }
2113
2114     QQuickItemPrivate *parentPrivate = QQuickItemPrivate::get(d->parentItem);
2115
2116     int myIndex = parentPrivate->childItems.lastIndexOf(this);
2117     int siblingIndex = parentPrivate->childItems.lastIndexOf(const_cast<QQuickItem *>(sibling));
2118
2119     Q_ASSERT(myIndex != -1 && siblingIndex != -1);
2120
2121     if (myIndex == siblingIndex + 1)
2122         return;
2123
2124     parentPrivate->childItems.move(myIndex, myIndex > siblingIndex ? siblingIndex + 1 : siblingIndex);
2125
2126     parentPrivate->dirty(QQuickItemPrivate::ChildrenStackingChanged);
2127     parentPrivate->markSortedChildrenDirty(this);
2128
2129     for (int ii = qMin(myIndex, siblingIndex + 1); ii < parentPrivate->childItems.count(); ++ii)
2130         QQuickItemPrivate::get(parentPrivate->childItems.at(ii))->siblingOrderChanged();
2131 }
2132
2133 /*!
2134   Returns the window in which this item is rendered.
2135   */
2136 QQuickWindow *QQuickItem::window() const
2137 {
2138     Q_D(const QQuickItem);
2139     return d->window;
2140 }
2141
2142 static bool itemZOrder_sort(QQuickItem *lhs, QQuickItem *rhs)
2143 {
2144     return lhs->z() < rhs->z();
2145 }
2146
2147 QList<QQuickItem *> QQuickItemPrivate::paintOrderChildItems() const
2148 {
2149     if (sortedChildItems)
2150         return *sortedChildItems;
2151
2152     // If none of the items have set Z then the paint order list is the same as
2153     // the childItems list.  This is by far the most common case.
2154     bool haveZ = false;
2155     for (int i = 0; i < childItems.count(); ++i) {
2156         if (QQuickItemPrivate::get(childItems.at(i))->z() != 0.) {
2157             haveZ = true;
2158             break;
2159         }
2160     }
2161     if (haveZ) {
2162         sortedChildItems = new QList<QQuickItem*>(childItems);
2163         qStableSort(sortedChildItems->begin(), sortedChildItems->end(), itemZOrder_sort);
2164         return *sortedChildItems;
2165     }
2166
2167     sortedChildItems = const_cast<QList<QQuickItem*>*>(&childItems);
2168
2169     return childItems;
2170 }
2171
2172 void QQuickItemPrivate::addChild(QQuickItem *child)
2173 {
2174     Q_Q(QQuickItem);
2175
2176     Q_ASSERT(!childItems.contains(child));
2177
2178     childItems.append(child);
2179
2180     markSortedChildrenDirty(child);
2181     dirty(QQuickItemPrivate::ChildrenChanged);
2182
2183     itemChange(QQuickItem::ItemChildAddedChange, child);
2184
2185     emit q->childrenChanged();
2186 }
2187
2188 void QQuickItemPrivate::removeChild(QQuickItem *child)
2189 {
2190     Q_Q(QQuickItem);
2191
2192     Q_ASSERT(child);
2193     Q_ASSERT(childItems.contains(child));
2194     childItems.removeOne(child);
2195     Q_ASSERT(!childItems.contains(child));
2196
2197     markSortedChildrenDirty(child);
2198     dirty(QQuickItemPrivate::ChildrenChanged);
2199
2200     itemChange(QQuickItem::ItemChildRemovedChange, child);
2201
2202     emit q->childrenChanged();
2203 }
2204
2205 void QQuickItemPrivate::refWindow(QQuickWindow *c)
2206 {
2207     // An item needs a window if it is referenced by another item which has a window.
2208     // Typically the item is referenced by a parent, but can also be referenced by a
2209     // ShaderEffect or ShaderEffectSource. 'windowRefCount' counts how many items with
2210     // a window is referencing this item. When the reference count goes from zero to one,
2211     // or one to zero, the window of this item is updated and propagated to the children.
2212     // As long as the reference count stays above zero, the window is unchanged.
2213     // refWindow() increments the reference count.
2214     // derefWindow() decrements the reference count.
2215
2216     Q_Q(QQuickItem);
2217     Q_ASSERT((window != 0) == (windowRefCount > 0));
2218     Q_ASSERT(c);
2219     if (++windowRefCount > 1) {
2220         if (c != window)
2221             qWarning("QQuickItem: Cannot use same item on different windows at the same time.");
2222         return; // Window already set.
2223     }
2224
2225     Q_ASSERT(window == 0);
2226     window = c;
2227
2228     if (polishScheduled)
2229         QQuickWindowPrivate::get(window)->itemsToPolish.insert(q);
2230
2231     if (!parentItem)
2232         QQuickWindowPrivate::get(window)->parentlessItems.insert(q);
2233
2234     for (int ii = 0; ii < childItems.count(); ++ii) {
2235         QQuickItem *child = childItems.at(ii);
2236         QQuickItemPrivate::get(child)->refWindow(c);
2237     }
2238
2239     dirty(Window);
2240
2241     if (extra.isAllocated() && extra->screenAttached)
2242         extra->screenAttached->windowChanged(c);
2243     itemChange(QQuickItem::ItemSceneChange, c);
2244 }
2245
2246 void QQuickItemPrivate::derefWindow()
2247 {
2248     Q_Q(QQuickItem);
2249     Q_ASSERT((window != 0) == (windowRefCount > 0));
2250
2251     if (!window)
2252         return; // This can happen when destroying recursive shader effect sources.
2253
2254     if (--windowRefCount > 0)
2255         return; // There are still other references, so don't set window to null yet.
2256
2257     q->releaseResources();
2258     removeFromDirtyList();
2259     QQuickWindowPrivate *c = QQuickWindowPrivate::get(window);
2260     if (polishScheduled)
2261         c->itemsToPolish.remove(q);
2262     QMutableHashIterator<int, QQuickItem *> itemTouchMapIt(c->itemForTouchPointId);
2263     while (itemTouchMapIt.hasNext()) {
2264         if (itemTouchMapIt.next().value() == q)
2265             itemTouchMapIt.remove();
2266     }
2267     if (c->mouseGrabberItem == q)
2268         c->mouseGrabberItem = 0;
2269 #ifndef QT_NO_CURSOR
2270     if (c->cursorItem == q)
2271         c->cursorItem = 0;
2272 #endif
2273     if ( hoverEnabled )
2274         c->hoverItems.removeAll(q);
2275     if (itemNodeInstance)
2276         c->cleanup(itemNodeInstance);
2277     if (!parentItem)
2278         c->parentlessItems.remove(q);
2279
2280     window = 0;
2281
2282     itemNodeInstance = 0;
2283
2284     if (extra.isAllocated()) {
2285         extra->opacityNode = 0;
2286         extra->clipNode = 0;
2287         extra->rootNode = 0;
2288         extra->beforePaintNode = 0;
2289     }
2290
2291     groupNode = 0;
2292     paintNode = 0;
2293
2294     for (int ii = 0; ii < childItems.count(); ++ii) {
2295         QQuickItem *child = childItems.at(ii);
2296         QQuickItemPrivate::get(child)->derefWindow();
2297     }
2298
2299     dirty(Window);
2300
2301     if (extra.isAllocated() && extra->screenAttached)
2302         extra->screenAttached->windowChanged(0);
2303     itemChange(QQuickItem::ItemSceneChange, (QQuickWindow *)0);
2304 }
2305
2306
2307 /*!
2308 Returns a transform that maps points from window space into item space.
2309 */
2310 QTransform QQuickItemPrivate::windowToItemTransform() const
2311 {
2312     // XXX todo - optimize
2313     return itemToWindowTransform().inverted();
2314 }
2315
2316 /*!
2317 Returns a transform that maps points from item space into window space.
2318 */
2319 QTransform QQuickItemPrivate::itemToWindowTransform() const
2320 {
2321     // XXX todo
2322     QTransform rv = parentItem?QQuickItemPrivate::get(parentItem)->itemToWindowTransform():QTransform();
2323     itemToParentTransform(rv);
2324     return rv;
2325 }
2326
2327 /*!
2328 Motifies \a t with this items local transform relative to its parent.
2329 */
2330 void QQuickItemPrivate::itemToParentTransform(QTransform &t) const
2331 {
2332     if (x || y)
2333         t.translate(x, y);
2334
2335     if (!transforms.isEmpty()) {
2336         QMatrix4x4 m(t);
2337         for (int ii = transforms.count() - 1; ii >= 0; --ii)
2338             transforms.at(ii)->applyTo(&m);
2339         t = m.toTransform();
2340     }
2341
2342     if (scale() != 1. || rotation() != 0.) {
2343         QPointF tp = computeTransformOrigin();
2344         t.translate(tp.x(), tp.y());
2345         t.scale(scale(), scale());
2346         t.rotate(rotation());
2347         t.translate(-tp.x(), -tp.y());
2348     }
2349 }
2350
2351 /*!
2352     Returns true if construction of the QML component is complete; otherwise
2353     returns false.
2354
2355     It is often desirable to delay some processing until the component is
2356     completed.
2357
2358     \sa componentComplete()
2359 */
2360 bool QQuickItem::isComponentComplete() const
2361 {
2362     Q_D(const QQuickItem);
2363     return d->componentComplete;
2364 }
2365
2366 QQuickItemPrivate::QQuickItemPrivate()
2367     : _anchors(0)
2368     , _stateGroup(0)
2369     , flags(0)
2370     , widthValid(false)
2371     , heightValid(false)
2372     , baselineOffsetValid(false)
2373     , componentComplete(true)
2374     , keepMouse(false)
2375     , keepTouch(false)
2376     , hoverEnabled(false)
2377     , smooth(true)
2378     , antialiasing(false)
2379     , focus(false)
2380     , activeFocus(false)
2381     , notifiedFocus(false)
2382     , notifiedActiveFocus(false)
2383     , filtersChildMouseEvents(false)
2384     , explicitVisible(true)
2385     , effectiveVisible(true)
2386     , explicitEnable(true)
2387     , effectiveEnable(true)
2388     , polishScheduled(false)
2389     , inheritedLayoutMirror(false)
2390     , effectiveLayoutMirror(false)
2391     , isMirrorImplicit(true)
2392     , inheritMirrorFromParent(false)
2393     , inheritMirrorFromItem(false)
2394     , isAccessible(false)
2395     , culled(false)
2396     , hasCursor(false)
2397     , dirtyAttributes(0)
2398     , nextDirtyItem(0)
2399     , prevDirtyItem(0)
2400     , window(0)
2401     , windowRefCount(0)
2402     , parentItem(0)
2403     , sortedChildItems(&childItems)
2404     , subFocusItem(0)
2405     , x(0)
2406     , y(0)
2407     , width(0)
2408     , height(0)
2409     , implicitWidth(0)
2410     , implicitHeight(0)
2411     , baselineOffset(0)
2412     , itemNodeInstance(0)
2413     , groupNode(0)
2414     , paintNode(0)
2415 {
2416 }
2417
2418 QQuickItemPrivate::~QQuickItemPrivate()
2419 {
2420     if (sortedChildItems != &childItems)
2421         delete sortedChildItems;
2422 }
2423
2424 void QQuickItemPrivate::init(QQuickItem *parent)
2425 {
2426 #ifndef QT_NO_DEBUG
2427     ++qt_item_count;
2428     static bool atexit_registered = false;
2429     if (!atexit_registered) {
2430         atexit(qt_print_item_count);
2431         atexit_registered = true;
2432     }
2433 #endif
2434
2435     Q_Q(QQuickItem);
2436
2437     registerAccessorProperties();
2438
2439     baselineOffsetValid = false;
2440
2441     if (parent) {
2442         q->setParentItem(parent);
2443         QQuickItemPrivate *parentPrivate = QQuickItemPrivate::get(parent);
2444         setImplicitLayoutMirror(parentPrivate->inheritedLayoutMirror, parentPrivate->inheritMirrorFromParent);
2445     }
2446 }
2447
2448 void QQuickItemPrivate::data_append(QQmlListProperty<QObject> *prop, QObject *o)
2449 {
2450     if (!o)
2451         return;
2452
2453     QQuickItem *that = static_cast<QQuickItem *>(prop->object);
2454
2455     if (QQuickItem *item = qmlobject_cast<QQuickItem *>(o)) {
2456         item->setParentItem(that);
2457     } else {
2458         if (o->inherits("QGraphicsItem"))
2459             qWarning("Cannot add a QtQuick 1.0 item (%s) into a QtQuick 2.0 scene!", o->metaObject()->className());
2460
2461         // XXX todo - do we really want this behavior?
2462         o->setParent(that);
2463     }
2464 }
2465
2466 /*!
2467     \qmlproperty list<Object> QtQuick2::Item::data
2468     \default
2469
2470     The data property allows you to freely mix visual children and resources
2471     in an item.  If you assign a visual item to the data list it becomes
2472     a child and if you assign any other object type, it is added as a resource.
2473
2474     So you can write:
2475     \qml
2476     Item {
2477         Text {}
2478         Rectangle {}
2479         Timer {}
2480     }
2481     \endqml
2482
2483     instead of:
2484     \qml
2485     Item {
2486         children: [
2487             Text {},
2488             Rectangle {}
2489         ]
2490         resources: [
2491             Timer {}
2492         ]
2493     }
2494     \endqml
2495
2496     It should not generally be necessary to refer to the \c data property,
2497     as it is the default property for Item and thus all child items are
2498     automatically assigned to this property.
2499  */
2500
2501 int QQuickItemPrivate::data_count(QQmlListProperty<QObject> *prop)
2502 {
2503     Q_UNUSED(prop);
2504     // XXX todo
2505     return 0;
2506 }
2507
2508 QObject *QQuickItemPrivate::data_at(QQmlListProperty<QObject> *prop, int i)
2509 {
2510     Q_UNUSED(prop);
2511     Q_UNUSED(i);
2512     // XXX todo
2513     return 0;
2514 }
2515
2516 void QQuickItemPrivate::data_clear(QQmlListProperty<QObject> *prop)
2517 {
2518     Q_UNUSED(prop);
2519     // XXX todo
2520 }
2521
2522 QObject *QQuickItemPrivate::resources_at(QQmlListProperty<QObject> *prop, int index)
2523 {
2524     const QObjectList children = prop->object->children();
2525     if (index < children.count())
2526         return children.at(index);
2527     else
2528         return 0;
2529 }
2530
2531 void QQuickItemPrivate::resources_append(QQmlListProperty<QObject> *prop, QObject *o)
2532 {
2533     // XXX todo - do we really want this behavior?
2534     o->setParent(prop->object);
2535 }
2536
2537 int QQuickItemPrivate::resources_count(QQmlListProperty<QObject> *prop)
2538 {
2539     return prop->object->children().count();
2540 }
2541
2542 void QQuickItemPrivate::resources_clear(QQmlListProperty<QObject> *prop)
2543 {
2544     // XXX todo - do we really want this behavior?
2545     const QObjectList children = prop->object->children();
2546     for (int index = 0; index < children.count(); index++)
2547         children.at(index)->setParent(0);
2548 }
2549
2550 QQuickItem *QQuickItemPrivate::children_at(QQmlListProperty<QQuickItem> *prop, int index)
2551 {
2552     QQuickItemPrivate *p = QQuickItemPrivate::get(static_cast<QQuickItem *>(prop->object));
2553     if (index >= p->childItems.count() || index < 0)
2554         return 0;
2555     else
2556         return p->childItems.at(index);
2557 }
2558
2559 void QQuickItemPrivate::children_append(QQmlListProperty<QQuickItem> *prop, QQuickItem *o)
2560 {
2561     if (!o)
2562         return;
2563
2564     QQuickItem *that = static_cast<QQuickItem *>(prop->object);
2565     if (o->parentItem() == that)
2566         o->setParentItem(0);
2567
2568     o->setParentItem(that);
2569 }
2570
2571 int QQuickItemPrivate::children_count(QQmlListProperty<QQuickItem> *prop)
2572 {
2573     QQuickItemPrivate *p = QQuickItemPrivate::get(static_cast<QQuickItem *>(prop->object));
2574     return p->childItems.count();
2575 }
2576
2577 void QQuickItemPrivate::children_clear(QQmlListProperty<QQuickItem> *prop)
2578 {
2579     QQuickItem *that = static_cast<QQuickItem *>(prop->object);
2580     QQuickItemPrivate *p = QQuickItemPrivate::get(that);
2581     while (!p->childItems.isEmpty())
2582         p->childItems.at(0)->setParentItem(0);
2583 }
2584
2585 void QQuickItemPrivate::visibleChildren_append(QQmlListProperty<QQuickItem>*, QQuickItem *self)
2586 {
2587     // do nothing
2588     qmlInfo(self) << "QQuickItem: visibleChildren property is readonly and cannot be assigned to.";
2589 }
2590
2591 int QQuickItemPrivate::visibleChildren_count(QQmlListProperty<QQuickItem> *prop)
2592 {
2593     QQuickItemPrivate *p = QQuickItemPrivate::get(static_cast<QQuickItem *>(prop->object));
2594     int visibleCount = 0;
2595     int c = p->childItems.count();
2596     while (c--) {
2597         if (p->childItems.at(c)->isVisible()) visibleCount++;
2598     }
2599
2600     return visibleCount;
2601 }
2602
2603 QQuickItem *QQuickItemPrivate::visibleChildren_at(QQmlListProperty<QQuickItem> *prop, int index)
2604 {
2605     QQuickItemPrivate *p = QQuickItemPrivate::get(static_cast<QQuickItem *>(prop->object));
2606     const int childCount = p->childItems.count();
2607     if (index >= childCount || index < 0)
2608         return 0;
2609
2610     int visibleCount = -1;
2611     for (int i = 0; i < childCount; i++) {
2612         if (p->childItems.at(i)->isVisible()) visibleCount++;
2613         if (visibleCount == index) return p->childItems.at(i);
2614     }
2615     return 0;
2616 }
2617
2618 int QQuickItemPrivate::transform_count(QQmlListProperty<QQuickTransform> *prop)
2619 {
2620     QQuickItem *that = static_cast<QQuickItem *>(prop->object);
2621     QQuickItemPrivate *p = QQuickItemPrivate::get(that);
2622
2623     return p->transforms.count();
2624 }
2625
2626 void QQuickTransform::appendToItem(QQuickItem *item)
2627 {
2628     Q_D(QQuickTransform);
2629     if (!item)
2630         return;
2631
2632     QQuickItemPrivate *p = QQuickItemPrivate::get(item);
2633
2634     if (!d->items.isEmpty() && !p->transforms.isEmpty() && p->transforms.contains(this)) {
2635         p->transforms.removeOne(this);
2636         p->transforms.append(this);
2637     } else {
2638         p->transforms.append(this);
2639         d->items.append(item);
2640     }
2641
2642     p->dirty(QQuickItemPrivate::Transform);
2643 }
2644
2645 void QQuickTransform::prependToItem(QQuickItem *item)
2646 {
2647     Q_D(QQuickTransform);
2648     if (!item)
2649         return;
2650
2651     QQuickItemPrivate *p = QQuickItemPrivate::get(item);
2652
2653     if (!d->items.isEmpty() && !p->transforms.isEmpty() && p->transforms.contains(this)) {
2654         p->transforms.removeOne(this);
2655         p->transforms.prepend(this);
2656     } else {
2657         p->transforms.prepend(this);
2658         d->items.append(item);
2659     }
2660
2661     p->dirty(QQuickItemPrivate::Transform);
2662 }
2663
2664 void QQuickItemPrivate::transform_append(QQmlListProperty<QQuickTransform> *prop, QQuickTransform *transform)
2665 {
2666     if (!transform)
2667         return;
2668
2669     QQuickItem *that = static_cast<QQuickItem *>(prop->object);
2670     transform->appendToItem(that);
2671 }
2672
2673 QQuickTransform *QQuickItemPrivate::transform_at(QQmlListProperty<QQuickTransform> *prop, int idx)
2674 {
2675     QQuickItem *that = static_cast<QQuickItem *>(prop->object);
2676     QQuickItemPrivate *p = QQuickItemPrivate::get(that);
2677
2678     if (idx < 0 || idx >= p->transforms.count())
2679         return 0;
2680     else
2681         return p->transforms.at(idx);
2682 }
2683
2684 void QQuickItemPrivate::transform_clear(QQmlListProperty<QQuickTransform> *prop)
2685 {
2686     QQuickItem *that = static_cast<QQuickItem *>(prop->object);
2687     QQuickItemPrivate *p = QQuickItemPrivate::get(that);
2688
2689     for (int ii = 0; ii < p->transforms.count(); ++ii) {
2690         QQuickTransform *t = p->transforms.at(ii);
2691         QQuickTransformPrivate *tp = QQuickTransformPrivate::get(t);
2692         tp->items.removeOne(that);
2693     }
2694
2695     p->transforms.clear();
2696
2697     p->dirty(QQuickItemPrivate::Transform);
2698 }
2699
2700 /*!
2701   \qmlproperty AnchorLine QtQuick2::Item::anchors.top
2702   \qmlproperty AnchorLine QtQuick2::Item::anchors.bottom
2703   \qmlproperty AnchorLine QtQuick2::Item::anchors.left
2704   \qmlproperty AnchorLine QtQuick2::Item::anchors.right
2705   \qmlproperty AnchorLine QtQuick2::Item::anchors.horizontalCenter
2706   \qmlproperty AnchorLine QtQuick2::Item::anchors.verticalCenter
2707   \qmlproperty AnchorLine QtQuick2::Item::anchors.baseline
2708
2709   \qmlproperty Item QtQuick2::Item::anchors.fill
2710   \qmlproperty Item QtQuick2::Item::anchors.centerIn
2711
2712   \qmlproperty real QtQuick2::Item::anchors.margins
2713   \qmlproperty real QtQuick2::Item::anchors.topMargin
2714   \qmlproperty real QtQuick2::Item::anchors.bottomMargin
2715   \qmlproperty real QtQuick2::Item::anchors.leftMargin
2716   \qmlproperty real QtQuick2::Item::anchors.rightMargin
2717   \qmlproperty real QtQuick2::Item::anchors.horizontalCenterOffset
2718   \qmlproperty real QtQuick2::Item::anchors.verticalCenterOffset
2719   \qmlproperty real QtQuick2::Item::anchors.baselineOffset
2720
2721   \qmlproperty bool QtQuick2::Item::anchors.alignWhenCentered
2722
2723   Anchors provide a way to position an item by specifying its
2724   relationship with other items.
2725
2726   Margins apply to top, bottom, left, right, and fill anchors.
2727   The \c anchors.margins property can be used to set all of the various margins at once, to the same value.
2728   It will not override a specific margin that has been previously set; to clear an explicit margin
2729   set it's value to \c undefined.
2730   Note that margins are anchor-specific and are not applied if an item does not
2731   use anchors.
2732
2733   Offsets apply for horizontal center, vertical center, and baseline anchors.
2734
2735   \table
2736   \row
2737   \li \image declarative-anchors_example.png
2738   \li Text anchored to Image, horizontally centered and vertically below, with a margin.
2739   \qml
2740   Item {
2741       Image {
2742           id: pic
2743           // ...
2744       }
2745       Text {
2746           id: label
2747           anchors.horizontalCenter: pic.horizontalCenter
2748           anchors.top: pic.bottom
2749           anchors.topMargin: 5
2750           // ...
2751       }
2752   }
2753   \endqml
2754   \row
2755   \li \image declarative-anchors_example2.png
2756   \li
2757   Left of Text anchored to right of Image, with a margin. The y
2758   property of both defaults to 0.
2759
2760   \qml
2761   Item {
2762       Image {
2763           id: pic
2764           // ...
2765       }
2766       Text {
2767           id: label
2768           anchors.left: pic.right
2769           anchors.leftMargin: 5
2770           // ...
2771       }
2772   }
2773   \endqml
2774   \endtable
2775
2776   \c anchors.fill provides a convenient way for one item to have the
2777   same geometry as another item, and is equivalent to connecting all
2778   four directional anchors.
2779
2780   To clear an anchor value, set it to \c undefined.
2781
2782   \c anchors.alignWhenCentered (default true) forces centered anchors to align to a
2783   whole pixel, i.e. if the item being centered has an odd width/height the item
2784   will be positioned on a whole pixel rather than being placed on a half-pixel.
2785   This ensures the item is painted crisply.  There are cases where this is not
2786   desirable, for example when rotating the item jitters may be apparent as the
2787   center is rounded.
2788
2789   \note You can only anchor an item to siblings or a parent.
2790
2791   For more information see \l {anchor-layout}{Anchor Layouts}.
2792 */
2793 QQuickAnchors *QQuickItemPrivate::anchors() const
2794 {
2795     if (!_anchors) {
2796         Q_Q(const QQuickItem);
2797         _anchors = new QQuickAnchors(const_cast<QQuickItem *>(q));
2798         if (!componentComplete)
2799             _anchors->classBegin();
2800     }
2801     return _anchors;
2802 }
2803
2804 void QQuickItemPrivate::siblingOrderChanged()
2805 {
2806     Q_Q(QQuickItem);
2807     for (int ii = 0; ii < changeListeners.count(); ++ii) {
2808         const QQuickItemPrivate::ChangeListener &change = changeListeners.at(ii);
2809         if (change.types & QQuickItemPrivate::SiblingOrder) {
2810             change.listener->itemSiblingOrderChanged(q);
2811         }
2812     }
2813 }
2814
2815 QQmlListProperty<QObject> QQuickItemPrivate::data()
2816 {
2817     return QQmlListProperty<QObject>(q_func(), 0, QQuickItemPrivate::data_append,
2818                                              QQuickItemPrivate::data_count,
2819                                              QQuickItemPrivate::data_at,
2820                                              QQuickItemPrivate::data_clear);
2821 }
2822
2823 /*!
2824     \qmlproperty real QtQuick2::Item::childrenRect.x
2825     \qmlproperty real QtQuick2::Item::childrenRect.y
2826     \qmlproperty real QtQuick2::Item::childrenRect.width
2827     \qmlproperty real QtQuick2::Item::childrenRect.height
2828
2829     This property holds the collective position and size of the item's
2830     children.
2831
2832     This property is useful if you need to access the collective geometry
2833     of an item's children in order to correctly size the item.
2834 */
2835 /*!
2836     \property QQuickItem::childrenRect
2837
2838     This property holds the collective position and size of the item's
2839     children.
2840
2841     This property is useful if you need to access the collective geometry
2842     of an item's children in order to correctly size the item.
2843 */
2844 QRectF QQuickItem::childrenRect()
2845 {
2846     Q_D(QQuickItem);
2847     if (!d->extra.isAllocated() || !d->extra->contents) {
2848         d->extra.value().contents = new QQuickContents(this);
2849         if (d->componentComplete)
2850             d->extra->contents->complete();
2851     }
2852     return d->extra->contents->rectF();
2853 }
2854
2855 /*!
2856     Returns the children of this item.
2857   */
2858 QList<QQuickItem *> QQuickItem::childItems() const
2859 {
2860     Q_D(const QQuickItem);
2861     return d->childItems;
2862 }
2863
2864 /*!
2865   \qmlproperty bool QtQuick2::Item::clip
2866   This property holds whether clipping is enabled. The default clip value is \c false.
2867
2868   If clipping is enabled, an item will clip its own painting, as well
2869   as the painting of its children, to its bounding rectangle.
2870
2871   Non-rectangular clipping regions are not supported for performance reasons.
2872 */
2873 /*!
2874   \property QQuickItem::clip
2875   This property holds whether clipping is enabled. The default clip value is \c false.
2876
2877   If clipping is enabled, an item will clip its own painting, as well
2878   as the painting of its children, to its bounding rectangle. If you set
2879   clipping during an item's paint operation, remember to re-set it to
2880   prevent clipping the rest of your scene.
2881
2882   Non-rectangular clipping regions are not supported for performance reasons.
2883 */
2884 bool QQuickItem::clip() const
2885 {
2886     return flags() & ItemClipsChildrenToShape;
2887 }
2888
2889 void QQuickItem::setClip(bool c)
2890 {
2891     if (clip() == c)
2892         return;
2893
2894     setFlag(ItemClipsChildrenToShape, c);
2895
2896     emit clipChanged(c);
2897 }
2898
2899
2900 /*!
2901   This function is called to handle this item's changes in
2902   geometry from \a oldGeometry to \a newGeometry. If the two
2903   geometries are the same, it doesn't do anything.
2904
2905   Derived classes must call the base class method within their implementation.
2906  */
2907 void QQuickItem::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry)
2908 {
2909     Q_D(QQuickItem);
2910
2911     if (d->_anchors)
2912         QQuickAnchorsPrivate::get(d->_anchors)->updateMe();
2913
2914     bool xChange = (newGeometry.x() != oldGeometry.x());
2915     bool yChange = (newGeometry.y() != oldGeometry.y());
2916     bool widthChange = (newGeometry.width() != oldGeometry.width());
2917     bool heightChange = (newGeometry.height() != oldGeometry.height());
2918
2919     for (int ii = 0; ii < d->changeListeners.count(); ++ii) {
2920         const QQuickItemPrivate::ChangeListener &change = d->changeListeners.at(ii);
2921         if (change.types & QQuickItemPrivate::Geometry) {
2922             if (change.gTypes == QQuickItemPrivate::GeometryChange) {
2923                 change.listener->itemGeometryChanged(this, newGeometry, oldGeometry);
2924             } else if ((xChange && (change.gTypes & QQuickItemPrivate::XChange)) ||
2925                        (yChange && (change.gTypes & QQuickItemPrivate::YChange)) ||
2926                        (widthChange && (change.gTypes & QQuickItemPrivate::WidthChange)) ||
2927                        (heightChange && (change.gTypes & QQuickItemPrivate::HeightChange))) {
2928                 change.listener->itemGeometryChanged(this, newGeometry, oldGeometry);
2929             }
2930         }
2931     }
2932
2933     if (xChange)
2934         emit xChanged();
2935     if (yChange)
2936         emit yChanged();
2937     if (widthChange)
2938         emit widthChanged();
2939     if (heightChange)
2940         emit heightChanged();
2941 }
2942
2943 /*!
2944     Called by the rendering thread, as a result of
2945     QQuickItem::update(), when it is time to sync the state of the QML
2946     objects with the scene graph objects.
2947
2948     The function should return the root of the scene graph subtree for
2949     this item. Most implementations will return a single
2950     QSGGeometryNode containing the visual representation of this item.
2951     \a oldNode is the node that was returned the last time the
2952     function was called.
2953
2954     \code
2955     QSGNode *MyItem::updatePaintNode(QSGNode *node, UpdatePaintNodeData *)
2956     {
2957         QSGSimpleRectNode *n = static_cast<QSGSimpleRectNode *>(node);
2958         if (!n) {
2959             n = new QSGSimpleRectNode();
2960             n->setColor(Qt::red);
2961         }
2962         n->setRect(boundingRect());
2963         return n;
2964     }
2965     \endcode
2966
2967     The main thread is blocked while this function is executed so it is safe to read
2968     values from the QQuickItem instance and other objects in the main thread.
2969
2970     If no call to QQuickItem::updatePaintNode() result in actual scene graph
2971     changes, like QSGNode::markDirty() or adding and removing nodes, then
2972     the underlying implementation may decide to not render the scene again as
2973     the visual outcome is identical.
2974
2975     \warning It is crucial that OpenGL operations and interaction with
2976     the scene graph happens exclusively on the rendering thread,
2977     primarily during the QQuickItem::updatePaintNode() call. The best
2978     rule of thumb is to only use classes with the "QSG" prefix inside
2979     the QQuickItem::updatePaintNode() function.
2980
2981     \sa QSGMaterial, QSGSimpleMaterial, QSGGeometryNode, QSGGeometry,
2982     QSGFlatColorMaterial, QSGTextureMaterial, QSGNode::markDirty()
2983  */
2984
2985 QSGNode *QQuickItem::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *)
2986 {
2987     delete oldNode;
2988     return 0;
2989 }
2990
2991 /*!
2992     This function is called when the item's scene graph resources are no longer needed.
2993     It allows items to free its resources, for instance textures, that are not owned by scene graph
2994     nodes. Note that scene graph nodes are managed by QQuickWindow and should not be deleted by
2995     this function. Scene graph resources are no longer needed when the parent is set to null and
2996     the item is not used by any \l ShaderEffect or \l ShaderEffectSource.
2997
2998     This function is called from the main thread. Therefore, resources used by the scene graph
2999     should not be deleted directly, but by calling \l QObject::deleteLater().
3000
3001     \note The item destructor still needs to free its scene graph resources if not already done.
3002  */
3003
3004 void QQuickItem::releaseResources()
3005 {
3006 }
3007
3008 QSGTransformNode *QQuickItemPrivate::createTransformNode()
3009 {
3010     return new QSGTransformNode;
3011 }
3012
3013 /*!
3014     This function should perform any layout as required for this item.
3015
3016     When polish() is called, the scene graph schedules a polish event for this
3017     item. When the scene graph is ready to render this item, it calls
3018     updatePolish() to do any item layout as required before it renders the
3019     next frame.
3020   */
3021 void QQuickItem::updatePolish()
3022 {
3023 }
3024
3025 void QQuickItemPrivate::addItemChangeListener(QQuickItemChangeListener *listener, ChangeTypes types)
3026 {
3027     changeListeners.append(ChangeListener(listener, types));
3028 }
3029
3030 void QQuickItemPrivate::removeItemChangeListener(QQuickItemChangeListener *listener, ChangeTypes types)
3031 {
3032     ChangeListener change(listener, types);
3033     changeListeners.removeOne(change);
3034 }
3035
3036 void QQuickItemPrivate::updateOrAddGeometryChangeListener(QQuickItemChangeListener *listener, GeometryChangeTypes types)
3037 {
3038     ChangeListener change(listener, types);
3039     int index = changeListeners.find(change);
3040     if (index > -1)
3041         changeListeners[index].gTypes = change.gTypes;  //we may have different GeometryChangeTypes
3042     else
3043         changeListeners.append(change);
3044 }
3045
3046 void QQuickItemPrivate::updateOrRemoveGeometryChangeListener(QQuickItemChangeListener *listener,
3047                                                              GeometryChangeTypes types)
3048 {
3049     ChangeListener change(listener, types);
3050     if (types == NoChange) {
3051         changeListeners.removeOne(change);
3052     } else {
3053         int index = changeListeners.find(change);
3054         if (index > -1)
3055             changeListeners[index].gTypes = change.gTypes;  //we may have different GeometryChangeTypes
3056     }
3057 }
3058
3059 /*!
3060     This event handler can be reimplemented in a subclass to receive key
3061     press events for an item. The event information is provided by the
3062     \a event parameter.
3063   */
3064 void QQuickItem::keyPressEvent(QKeyEvent *event)
3065 {
3066     event->ignore();
3067 }
3068
3069 /*!
3070     This event handler can be reimplemented in a subclass to receive key
3071     release events for an item. The event information is provided by the
3072     \a event parameter.
3073   */
3074 void QQuickItem::keyReleaseEvent(QKeyEvent *event)
3075 {
3076     event->ignore();
3077 }
3078
3079 /*!
3080     This event handler can be reimplemented in a subclass to receive input
3081     method events for an item. The event information is provided by the
3082     \a event parameter.
3083   */
3084 void QQuickItem::inputMethodEvent(QInputMethodEvent *event)
3085 {
3086     event->ignore();
3087 }
3088
3089 /*!
3090     This event handler can be reimplemented in a subclass to receive focus-in
3091     events for an item. The event information is provided by the
3092     \a event parameter.
3093   */
3094 void QQuickItem::focusInEvent(QFocusEvent *event)
3095 {
3096 #ifndef QT_NO_ACCESSIBILITY
3097     QAccessibleEvent ev(this, QAccessible::Focus);
3098     QAccessible::updateAccessibility(&ev);
3099 #endif
3100 }
3101
3102 /*!
3103     This event handler can be reimplemented in a subclass to receive focus-out
3104     events for an item. The event information is provided by the
3105     \a event parameter.
3106   */
3107 void QQuickItem::focusOutEvent(QFocusEvent *event)
3108 {
3109 }
3110
3111 /*!
3112     This event handler can be reimplemented in a subclass to receive mouse
3113     press events for an item. The event information is provided by the
3114     \a event parameter.
3115   */
3116 void QQuickItem::mousePressEvent(QMouseEvent *event)
3117 {
3118     event->ignore();
3119 }
3120
3121 /*!
3122     This event handler can be reimplemented in a subclass to receive mouse
3123     move events for an item. The event information is provided by the
3124     \a event parameter.
3125   */
3126 void QQuickItem::mouseMoveEvent(QMouseEvent *event)
3127 {
3128     event->ignore();
3129 }
3130
3131 /*!
3132     This event handler can be reimplemented in a subclass to receive mouse
3133     release events for an item. The event information is provided by the
3134     \a event parameter.
3135   */
3136 void QQuickItem::mouseReleaseEvent(QMouseEvent *event)
3137 {
3138     event->ignore();
3139 }
3140
3141 /*!
3142     This event handler can be reimplemented in a subclass to receive mouse
3143     double-click events for an item. The event information is provided by the
3144     \a event parameter.
3145   */
3146 void QQuickItem::mouseDoubleClickEvent(QMouseEvent *)
3147 {
3148 }
3149
3150 /*!
3151     This event handler can be reimplemented in a subclass to be notified
3152     when a mouse ungrab event has occurred on this item.
3153
3154     \sa ungrabMouse()
3155   */
3156 void QQuickItem::mouseUngrabEvent()
3157 {
3158     // XXX todo
3159 }
3160
3161 /*!
3162     This event handler can be reimplemented in a subclass to be notified
3163     when a touch ungrab event has occurred on this item.
3164   */
3165 void QQuickItem::touchUngrabEvent()
3166 {
3167     // XXX todo
3168 }
3169
3170 /*!
3171     This event handler can be reimplemented in a subclass to receive
3172     wheel events for an item. The event information is provided by the
3173     \a event parameter.
3174   */
3175 void QQuickItem::wheelEvent(QWheelEvent *event)
3176 {
3177     event->ignore();
3178 }
3179
3180 /*!
3181     This event handler can be reimplemented in a subclass to receive touch
3182     events for an item. The event information is provided by the
3183     \a event parameter.
3184   */
3185 void QQuickItem::touchEvent(QTouchEvent *event)
3186 {
3187     event->ignore();
3188 }
3189
3190 /*!
3191     This event handler can be reimplemented in a subclass to receive hover-enter
3192     events for an item. The event information is provided by the
3193     \a event parameter.
3194
3195     Hover events are only provided if acceptHoverEvents() is true.
3196   */
3197 void QQuickItem::hoverEnterEvent(QHoverEvent *event)
3198 {
3199     Q_UNUSED(event);
3200 }
3201
3202 /*!
3203     This event handler can be reimplemented in a subclass to receive hover-move
3204     events for an item. The event information is provided by the
3205     \a event parameter.
3206
3207     Hover events are only provided if acceptHoverEvents() is true.
3208   */
3209 void QQuickItem::hoverMoveEvent(QHoverEvent *event)
3210 {
3211     Q_UNUSED(event);
3212 }
3213
3214 /*!
3215     This event handler can be reimplemented in a subclass to receive hover-leave
3216     events for an item. The event information is provided by the
3217     \a event parameter.
3218
3219     Hover events are only provided if acceptHoverEvents() is true.
3220   */
3221 void QQuickItem::hoverLeaveEvent(QHoverEvent *event)
3222 {
3223     Q_UNUSED(event);
3224 }
3225
3226 #ifndef QT_NO_DRAGANDDROP
3227 /*!
3228     This event handler can be reimplemented in a subclass to receive drag-enter
3229     events for an item. The event information is provided by the
3230     \a event parameter.
3231
3232     Drag and drop events are only provided if the ItemAcceptsDrops flag
3233     has been set for this item.
3234
3235     \sa Drag, {Drag and Drop}
3236   */
3237 void QQuickItem::dragEnterEvent(QDragEnterEvent *event)
3238 {
3239     Q_UNUSED(event);
3240 }
3241
3242 /*!
3243     This event handler can be reimplemented in a subclass to receive drag-move
3244     events for an item. The event information is provided by the
3245     \a event parameter.
3246
3247     Drag and drop events are only provided if the ItemAcceptsDrops flag
3248     has been set for this item.
3249
3250     \sa Drag, {Drag and Drop}
3251   */
3252 void QQuickItem::dragMoveEvent(QDragMoveEvent *event)
3253 {
3254     Q_UNUSED(event);
3255 }
3256
3257 /*!
3258     This event handler can be reimplemented in a subclass to receive drag-leave
3259     events for an item. The event information is provided by the
3260     \a event parameter.
3261
3262     Drag and drop events are only provided if the ItemAcceptsDrops flag
3263     has been set for this item.
3264
3265     \sa Drag, {Drag and Drop}
3266   */
3267 void QQuickItem::dragLeaveEvent(QDragLeaveEvent *event)
3268 {
3269     Q_UNUSED(event);
3270 }
3271
3272 /*!
3273     This event handler can be reimplemented in a subclass to receive drop
3274     events for an item. The event information is provided by the
3275     \a event parameter.
3276
3277     Drag and drop events are only provided if the ItemAcceptsDrops flag
3278     has been set for this item.
3279
3280     \sa Drag, {Drag and Drop}
3281   */
3282 void QQuickItem::dropEvent(QDropEvent *event)
3283 {
3284     Q_UNUSED(event);
3285 }
3286 #endif // QT_NO_DRAGANDDROP
3287
3288 /*!
3289     Reimplement this method to filter the mouse events that are received by
3290     this item's children.
3291
3292     This method will only be called if filtersChildMouseEvents() is true.
3293
3294     Return true if the specified \a event should not be passed onto the
3295     specified child \a item, and false otherwise.
3296
3297     \sa setFiltersChildMouseEvents()
3298   */
3299 bool QQuickItem::childMouseEventFilter(QQuickItem *item, QEvent *event)
3300 {
3301     Q_UNUSED(item);
3302     Q_UNUSED(event);
3303     return false;
3304 }
3305
3306 /*!
3307     \internal
3308   */
3309 void QQuickItem::windowDeactivateEvent()
3310 {
3311     foreach (QQuickItem* item, childItems()) {
3312         item->windowDeactivateEvent();
3313     }
3314 }
3315
3316 /*!
3317     This method is only relevant for input items.
3318
3319     If this item is an input item, this method should be reimplemented to
3320     return the relevant input method flags for the given \a query.
3321
3322     \sa QWidget::inputMethodQuery()
3323   */
3324 QVariant QQuickItem::inputMethodQuery(Qt::InputMethodQuery query) const
3325 {
3326     Q_D(const QQuickItem);
3327     QVariant v;
3328
3329     switch (query) {
3330     case Qt::ImEnabled:
3331         v = (bool)(flags() & ItemAcceptsInputMethod);
3332         break;
3333     case Qt::ImHints:
3334     case Qt::ImCursorRectangle:
3335     case Qt::ImFont:
3336     case Qt::ImCursorPosition:
3337     case Qt::ImSurroundingText:
3338     case Qt::ImCurrentSelection:
3339     case Qt::ImMaximumTextLength:
3340     case Qt::ImAnchorPosition:
3341     case Qt::ImPreferredLanguage:
3342         if (d->extra.isAllocated() && d->extra->keyHandler)
3343             v = d->extra->keyHandler->inputMethodQuery(query);
3344     default:
3345         break;
3346     }
3347
3348     return v;
3349 }
3350
3351 QQuickAnchorLine QQuickItemPrivate::left() const
3352 {
3353     Q_Q(const QQuickItem);
3354     return QQuickAnchorLine(const_cast<QQuickItem *>(q), QQuickAnchorLine::Left);
3355 }
3356
3357 QQuickAnchorLine QQuickItemPrivate::right() const
3358 {
3359     Q_Q(const QQuickItem);
3360     return QQuickAnchorLine(const_cast<QQuickItem *>(q), QQuickAnchorLine::Right);
3361 }
3362
3363 QQuickAnchorLine QQuickItemPrivate::horizontalCenter() const
3364 {
3365     Q_Q(const QQuickItem);
3366     return QQuickAnchorLine(const_cast<QQuickItem *>(q), QQuickAnchorLine::HCenter);
3367 }
3368
3369 QQuickAnchorLine QQuickItemPrivate::top() const
3370 {
3371     Q_Q(const QQuickItem);
3372     return QQuickAnchorLine(const_cast<QQuickItem *>(q), QQuickAnchorLine::Top);
3373 }
3374
3375 QQuickAnchorLine QQuickItemPrivate::bottom() const
3376 {
3377     Q_Q(const QQuickItem);
3378     return QQuickAnchorLine(const_cast<QQuickItem *>(q), QQuickAnchorLine::Bottom);
3379 }
3380
3381 QQuickAnchorLine QQuickItemPrivate::verticalCenter() const
3382 {
3383     Q_Q(const QQuickItem);
3384     return QQuickAnchorLine(const_cast<QQuickItem *>(q), QQuickAnchorLine::VCenter);
3385 }
3386
3387 QQuickAnchorLine QQuickItemPrivate::baseline() const
3388 {
3389     Q_Q(const QQuickItem);
3390     return QQuickAnchorLine(const_cast<QQuickItem *>(q), QQuickAnchorLine::Baseline);
3391 }
3392
3393 /*!
3394   \qmlproperty int QtQuick2::Item::baselineOffset
3395
3396   Specifies the position of the item's baseline in local coordinates.
3397
3398   The baseline of a \l Text item is the imaginary line on which the text
3399   sits. Controls containing text usually set their baseline to the
3400   baseline of their text.
3401
3402   For non-text items, a default baseline offset of 0 is used.
3403 */
3404 /*!
3405   \property QQuickItem::baselineOffset
3406
3407   Specifies the position of the item's baseline in local coordinates.
3408
3409   The baseline of a \l Text item is the imaginary line on which the text
3410   sits. Controls containing text usually set their baseline to the
3411   baseline of their text.
3412
3413   For non-text items, a default baseline offset of 0 is used.
3414 */
3415 qreal QQuickItem::baselineOffset() const
3416 {
3417     Q_D(const QQuickItem);
3418     if (d->baselineOffsetValid) {
3419         return d->baselineOffset;
3420     } else {
3421         return 0.0;
3422     }
3423 }
3424
3425 void QQuickItem::setBaselineOffset(qreal offset)
3426 {
3427     Q_D(QQuickItem);
3428     if (offset == d->baselineOffset)
3429         return;
3430
3431     d->baselineOffset = offset;
3432     d->baselineOffsetValid = true;
3433
3434     for (int ii = 0; ii < d->changeListeners.count(); ++ii) {
3435         const QQuickItemPrivate::ChangeListener &change = d->changeListeners.at(ii);
3436         if (change.types & QQuickItemPrivate::Geometry) {
3437             QQuickAnchorsPrivate *anchor = change.listener->anchorPrivate();
3438             if (anchor)
3439                 anchor->updateVerticalAnchors();
3440         }
3441     }
3442
3443     if (d->_anchors && (d->_anchors->usedAnchors() & QQuickAnchors::BaselineAnchor))
3444         QQuickAnchorsPrivate::get(d->_anchors)->updateVerticalAnchors();
3445
3446     emit baselineOffsetChanged(offset);
3447 }
3448
3449
3450 /*!
3451  * Schedules a call to updatePaintNode() for this item.
3452  *
3453  * The call to QQuickItem::updatePaintNode() will always happen if the
3454  * item is showing in a QQuickWindow.
3455  *
3456  * Only items which specifies QQuickItem::ItemHasContents are allowed
3457  * to call QQuickItem::update().
3458  */
3459 void QQuickItem::update()
3460 {
3461     Q_D(QQuickItem);
3462     Q_ASSERT(flags() & ItemHasContents);
3463     d->dirty(QQuickItemPrivate::Content);
3464 }
3465
3466 /*!
3467     Schedules a polish event for this item.
3468
3469     When the scene graph processes the request, it will call updatePolish()
3470     on this item.
3471   */
3472 void QQuickItem::polish()
3473 {
3474     Q_D(QQuickItem);
3475     if (!d->polishScheduled) {
3476         d->polishScheduled = true;
3477         if (d->window) {
3478             QQuickWindowPrivate *p = QQuickWindowPrivate::get(d->window);
3479             bool maybeupdate = p->itemsToPolish.isEmpty();
3480             p->itemsToPolish.insert(this);
3481             if (maybeupdate) d->window->maybeUpdate();
3482         }
3483     }
3484 }
3485
3486 /*!
3487     \qmlmethod object QtQuick2::Item::mapFromItem(Item item, real x, real y)
3488     \qmlmethod object QtQuick2::Item::mapFromItem(Item item, real x, real y, real width, real height)
3489
3490     Maps the point (\a x, \a y) or rect (\a x, \a y, \a width, \a height), which is in \a
3491     item's coordinate system, to this item's coordinate system, and returns an object with \c x and
3492     \c y (and optionally \c width and \c height) properties matching the mapped coordinate.
3493
3494     If \a item is a \c null value, this maps the point or rect from the coordinate system of
3495     the root QML view.
3496 */
3497 /*!
3498     \internal
3499   */
3500 void QQuickItem::mapFromItem(QQmlV8Function *args) const
3501 {
3502     if (args->Length() != 0) {
3503         v8::Local<v8::Value> item = (*args)[0];
3504         QV8Engine *engine = args->engine();
3505
3506         QQuickItem *itemObj = 0;
3507         if (!item->IsNull())
3508             itemObj = qobject_cast<QQuickItem*>(engine->toQObject(item));
3509
3510         if (!itemObj && !item->IsNull()) {
3511             qmlInfo(this) << "mapFromItem() given argument \"" << engine->toString(item->ToString())
3512                           << "\" which is neither null nor an Item";
3513             return;
3514         }
3515
3516         v8::Local<v8::Object> rv = v8::Object::New();
3517         args->returnValue(rv);
3518
3519         qreal x = (args->Length() > 1)?(*args)[1]->NumberValue():0;
3520         qreal y = (args->Length() > 2)?(*args)[2]->NumberValue():0;
3521
3522         if (args->Length() > 3) {
3523             qreal w = (*args)[3]->NumberValue();
3524             qreal h = (args->Length() > 4)?(*args)[4]->NumberValue():0;
3525
3526             QRectF r = mapRectFromItem(itemObj, QRectF(x, y, w, h));
3527
3528             rv->Set(v8::String::New("x"), v8::Number::New(r.x()));
3529             rv->Set(v8::String::New("y"), v8::Number::New(r.y()));
3530             rv->Set(v8::String::New("width"), v8::Number::New(r.width()));
3531             rv->Set(v8::String::New("height"), v8::Number::New(r.height()));
3532         } else {
3533             QPointF p = mapFromItem(itemObj, QPointF(x, y));
3534
3535             rv->Set(v8::String::New("x"), v8::Number::New(p.x()));
3536             rv->Set(v8::String::New("y"), v8::Number::New(p.y()));
3537         }
3538     }
3539 }
3540
3541 /*!
3542     \internal
3543   */
3544 QTransform QQuickItem::itemTransform(QQuickItem *other, bool *ok) const
3545 {
3546     Q_D(const QQuickItem);
3547
3548     // XXX todo - we need to be able to handle common parents better and detect
3549     // invalid cases
3550     if (ok) *ok = true;
3551
3552     QTransform t = d->itemToWindowTransform();
3553     if (other) t *= QQuickItemPrivate::get(other)->windowToItemTransform();
3554
3555     return t;
3556 }
3557
3558 /*!
3559     \qmlmethod object QtQuick2::Item::mapToItem(Item item, real x, real y)
3560     \qmlmethod object QtQuick2::Item::mapToItem(Item item, real x, real y, real width, real height)
3561
3562     Maps the point (\a x, \a y) or rect (\a x, \a y, \a width, \a height), which is in this
3563     item's coordinate system, to \a item's coordinate system, and returns an object with \c x and
3564     \c y (and optionally \c width and \c height) properties matching the mapped coordinate.
3565
3566     If \a item is a \c null value, this maps the point or rect to the coordinate system of the
3567     root QML view.
3568 */
3569 /*!
3570     \internal
3571   */
3572 void QQuickItem::mapToItem(QQmlV8Function *args) const
3573 {
3574     if (args->Length() != 0) {
3575         v8::Local<v8::Value> item = (*args)[0];
3576         QV8Engine *engine = args->engine();
3577
3578         QQuickItem *itemObj = 0;
3579         if (!item->IsNull())
3580             itemObj = qobject_cast<QQuickItem*>(engine->toQObject(item));
3581
3582         if (!itemObj && !item->IsNull()) {
3583             qmlInfo(this) << "mapToItem() given argument \"" << engine->toString(item->ToString())
3584                           << "\" which is neither null nor an Item";
3585             return;
3586         }
3587
3588         v8::Local<v8::Object> rv = v8::Object::New();
3589         args->returnValue(rv);
3590
3591         qreal x = (args->Length() > 1)?(*args)[1]->NumberValue():0;
3592         qreal y = (args->Length() > 2)?(*args)[2]->NumberValue():0;
3593
3594         if (args->Length() > 3) {
3595             qreal w = (*args)[3]->NumberValue();
3596             qreal h = (args->Length() > 4)?(*args)[4]->NumberValue():0;
3597
3598             QRectF r = mapRectToItem(itemObj, QRectF(x, y, w, h));
3599
3600             rv->Set(v8::String::New("x"), v8::Number::New(r.x()));
3601             rv->Set(v8::String::New("y"), v8::Number::New(r.y()));
3602             rv->Set(v8::String::New("width"), v8::Number::New(r.width()));
3603             rv->Set(v8::String::New("height"), v8::Number::New(r.height()));
3604         } else {
3605             QPointF p = mapToItem(itemObj, QPointF(x, y));
3606
3607             rv->Set(v8::String::New("x"), v8::Number::New(p.x()));
3608             rv->Set(v8::String::New("y"), v8::Number::New(p.y()));
3609         }
3610     }
3611 }
3612
3613 /*!
3614     \qmlmethod QtQuick2::Item::forceActiveFocus()
3615
3616     Forces active focus on the item.
3617
3618     This method sets focus on the item and ensures that all ancestor
3619     FocusScope objects in the object hierarchy are also given \l focus.
3620
3621     \sa activeFocus
3622 */
3623 /*!
3624     Forces active focus on the item.
3625
3626     This method sets focus on the item and ensures that all ancestor
3627     FocusScope objects in the object hierarchy are also given \l focus.
3628
3629     \sa activeFocus
3630 */
3631 void QQuickItem::forceActiveFocus()
3632 {
3633     setFocus(true);
3634     QQuickItem *parent = parentItem();
3635     while (parent) {
3636         if (parent->flags() & QQuickItem::ItemIsFocusScope) {
3637             parent->setFocus(true);
3638         }
3639         parent = parent->parentItem();
3640     }
3641 }
3642
3643 /*!
3644     \qmlmethod QtQuick2::Item::childAt(real x, real y)
3645
3646     Returns the first visible child item found at point (\a x, \a y) within
3647     the coordinate system of this item.
3648
3649     Returns \c null if there is no such item.
3650 */
3651 /*!
3652     Returns the first visible child item found at point (\a x, \a y) within
3653     the coordinate system of this item.
3654
3655     Returns 0 if there is no such item.
3656 */
3657 QQuickItem *QQuickItem::childAt(qreal x, qreal y) const
3658 {
3659     // XXX todo - should this include transform etc.?
3660     const QList<QQuickItem *> children = childItems();
3661     for (int i = children.count()-1; i >= 0; --i) {
3662         QQuickItem *child = children.at(i);
3663         if (child->isVisible() && child->x() <= x
3664                 && child->x() + child->width() >= x
3665                 && child->y() <= y
3666                 && child->y() + child->height() >= y)
3667             return child;
3668     }
3669     return 0;
3670 }
3671
3672 QQmlListProperty<QObject> QQuickItemPrivate::resources()
3673 {
3674     return QQmlListProperty<QObject>(q_func(), 0, QQuickItemPrivate::resources_append,
3675                                              QQuickItemPrivate::resources_count,
3676                                              QQuickItemPrivate::resources_at,
3677                                              QQuickItemPrivate::resources_clear);
3678 }
3679
3680 /*!
3681     \qmlproperty list<Item> QtQuick2::Item::children
3682     \qmlproperty list<Object> QtQuick2::Item::resources
3683
3684     The children property contains the list of visual children of this item.
3685     The resources property contains non-visual resources that you want to
3686     reference by name.
3687
3688     It is not generally necessary to refer to these properties when adding
3689     child items or resources, as the default \l data property will
3690     automatically assign child objects to the \c children and \c resources
3691     properties as appropriate. See the \l data documentation for details.
3692 */
3693 /*!
3694     \property QQuickItem::children
3695     \internal
3696   */
3697 /*!
3698     \fn void QQuickItem::childrenChanged()
3699     \internal
3700 */
3701 QQmlListProperty<QQuickItem> QQuickItemPrivate::children()
3702 {
3703     return QQmlListProperty<QQuickItem>(q_func(), 0, QQuickItemPrivate::children_append,
3704                                              QQuickItemPrivate::children_count,
3705                                              QQuickItemPrivate::children_at,
3706                                              QQuickItemPrivate::children_clear);
3707
3708 }
3709
3710 /*!
3711   \qmlproperty real QtQuick2::Item::visibleChildren
3712   This read-only property lists all of the item's children that are currently visible.
3713   Note that a child's visibility may have changed explicitly, or because the visibility
3714   of this (it's parent) item or another grandparent changed.
3715 */
3716 /*!
3717     \property QQuickItem::visibleChildren
3718     \internal
3719   */
3720 /*!
3721     \fn void QQuickItem::visibleChildrenChanged()
3722     \internal
3723 */
3724 QQmlListProperty<QQuickItem> QQuickItemPrivate::visibleChildren()
3725 {
3726     return QQmlListProperty<QQuickItem>(q_func(), 0, QQuickItemPrivate::visibleChildren_append,
3727                                              QQuickItemPrivate::visibleChildren_count,
3728                                              QQuickItemPrivate::visibleChildren_at);
3729
3730 }
3731
3732 /*!
3733     \qmlproperty list<State> QtQuick2::Item::states
3734
3735     This property holds the list of possible states for this item. To change
3736     the state of this item, set the \l state property to one of these states,
3737     or set the \l state property to an empty string to revert the item to its
3738     default state.
3739
3740     This property is specified as a list of \l State objects. For example,
3741     below is an item with "red_color" and "blue_color" states:
3742
3743     \qml
3744     import QtQuick 2.0
3745
3746     Rectangle {
3747         id: root
3748         width: 100; height: 100
3749
3750         states: [
3751             State {
3752                 name: "red_color"
3753                 PropertyChanges { target: root; color: "red" }
3754             },
3755             State {
3756                 name: "blue_color"
3757                 PropertyChanges { target: root; color: "blue" }
3758             }
3759         ]
3760     }
3761     \endqml
3762
3763     See \l{Qt Quick States} and \l{Animation and Transitions in Qt Quick} for
3764     more details on using states and transitions.
3765
3766     \sa transitions
3767 */
3768 /*!
3769     \property QQuickItem::states
3770     \internal
3771   */
3772 QQmlListProperty<QQuickState> QQuickItemPrivate::states()
3773 {
3774     return _states()->statesProperty();
3775 }
3776
3777 /*!
3778     \qmlproperty list<Transition> QtQuick2::Item::transitions
3779
3780     This property holds the list of transitions for this item. These define the
3781     transitions to be applied to the item whenever it changes its \l state.
3782
3783     This property is specified as a list of \l Transition objects. For example:
3784
3785     \qml
3786     import QtQuick 2.0
3787
3788     Item {
3789         transitions: [
3790             Transition {
3791                 //...
3792             },
3793             Transition {
3794                 //...
3795             }
3796         ]
3797     }
3798     \endqml
3799
3800     See \l{Qt Quick States} and \l{Animation and Transitions in Qt Quick} for
3801     more details on using states and transitions.
3802
3803     \sa transitions
3804 */
3805 /*!
3806     \property QQuickItem::transitions
3807     \internal
3808   */
3809 QQmlListProperty<QQuickTransition> QQuickItemPrivate::transitions()
3810 {
3811     return _states()->transitionsProperty();
3812 }
3813
3814 QString QQuickItemPrivate::state() const
3815 {
3816     if (!_stateGroup)
3817         return QString();
3818     else
3819         return _stateGroup->state();
3820 }
3821
3822 void QQuickItemPrivate::setState(const QString &state)
3823 {
3824     _states()->setState(state);
3825 }
3826
3827 /*!
3828     \qmlproperty string QtQuick2::Item::state
3829
3830     This property holds the name of the current state of the item.
3831
3832     If the item is in its default state â€” that is, no explicit state has been
3833     set â€” then this property holds an empty string. Likewise, you can return
3834     an item to its default state by setting this property to an empty string.
3835
3836     \sa {Qt Quick States}
3837 */
3838 /*!
3839     \property QQuickItem::state
3840
3841     This property holds the name of the current state of the item.
3842
3843     If the item is in its default state â€” that is, no explicit state has been
3844     set â€” then this property holds an empty string. Likewise, you can return
3845     an item to its default state by setting this property to an empty string.
3846
3847     \sa {Qt Quick States}
3848 */
3849 QString QQuickItem::state() const
3850 {
3851     Q_D(const QQuickItem);
3852     return d->state();
3853 }
3854
3855 void QQuickItem::setState(const QString &state)
3856 {
3857     Q_D(QQuickItem);
3858     d->setState(state);
3859 }
3860
3861 /*!
3862   \qmlproperty list<Transform> QtQuick2::Item::transform
3863   This property holds the list of transformations to apply.
3864
3865   For more information see \l Transform.
3866 */
3867 /*!
3868     \property QQuickItem::transform
3869     \internal
3870   */
3871 QQmlListProperty<QQuickTransform> QQuickItem::transform()
3872 {
3873     return QQmlListProperty<QQuickTransform>(this, 0, QQuickItemPrivate::transform_append,
3874                                                      QQuickItemPrivate::transform_count,
3875                                                      QQuickItemPrivate::transform_at,
3876                                                      QQuickItemPrivate::transform_clear);
3877 }
3878
3879 /*!
3880   \reimp
3881   Derived classes should call the base class method before adding their own action to
3882   perform at classBegin.
3883 */
3884 void QQuickItem::classBegin()
3885 {
3886     Q_D(QQuickItem);
3887     d->componentComplete = false;
3888     if (d->_stateGroup)
3889         d->_stateGroup->classBegin();
3890     if (d->_anchors)
3891         d->_anchors->classBegin();
3892     if (d->extra.isAllocated() && d->extra->layer)
3893         d->extra->layer->classBegin();
3894 }
3895
3896 /*!
3897   \reimp
3898   Derived classes should call the base class method before adding their own actions to
3899   perform at componentComplete.
3900 */
3901 void QQuickItem::componentComplete()
3902 {
3903     Q_D(QQuickItem);
3904     d->componentComplete = true;
3905     if (d->_stateGroup)
3906         d->_stateGroup->componentComplete();
3907     if (d->_anchors) {
3908         d->_anchors->componentComplete();
3909         QQuickAnchorsPrivate::get(d->_anchors)->updateOnComplete();
3910     }
3911
3912     if (d->extra.isAllocated() && d->extra->layer)
3913         d->extra->layer->componentComplete();
3914
3915     if (d->extra.isAllocated() && d->extra->keyHandler)
3916         d->extra->keyHandler->componentComplete();
3917
3918     if (d->extra.isAllocated() && d->extra->contents)
3919         d->extra->contents->complete();
3920
3921     if (d->window && d->dirtyAttributes) {
3922         d->addToDirtyList();
3923         QQuickWindowPrivate::get(d->window)->dirtyItem(this);
3924     }
3925 }
3926
3927 QQuickStateGroup *QQuickItemPrivate::_states()
3928 {
3929     Q_Q(QQuickItem);
3930     if (!_stateGroup) {
3931         _stateGroup = new QQuickStateGroup;
3932         if (!componentComplete)
3933             _stateGroup->classBegin();
3934         qmlobject_connect(_stateGroup, QQuickStateGroup, SIGNAL(stateChanged(QString)),
3935                           q, QQuickItem, SIGNAL(stateChanged(QString)))
3936     }
3937
3938     return _stateGroup;
3939 }
3940
3941 QPointF QQuickItemPrivate::computeTransformOrigin() const
3942 {
3943     switch (origin()) {
3944     default:
3945     case QQuickItem::TopLeft:
3946         return QPointF(0, 0);
3947     case QQuickItem::Top:
3948         return QPointF(width / 2., 0);
3949     case QQuickItem::TopRight:
3950         return QPointF(width, 0);
3951     case QQuickItem::Left:
3952         return QPointF(0, height / 2.);
3953     case QQuickItem::Center:
3954         return QPointF(width / 2., height / 2.);
3955     case QQuickItem::Right:
3956         return QPointF(width, height / 2.);
3957     case QQuickItem::BottomLeft:
3958         return QPointF(0, height);
3959     case QQuickItem::Bottom:
3960         return QPointF(width / 2., height);
3961     case QQuickItem::BottomRight:
3962         return QPointF(width, height);
3963     }
3964 }
3965
3966 void QQuickItemPrivate::transformChanged()
3967 {
3968     if (extra.isAllocated() && extra->layer)
3969         extra->layer->updateMatrix();
3970 }
3971
3972 void QQuickItemPrivate::deliverKeyEvent(QKeyEvent *e)
3973 {
3974     Q_Q(QQuickItem);
3975
3976     Q_ASSERT(e->isAccepted());
3977     if (extra.isAllocated() && extra->keyHandler) {
3978         if (e->type() == QEvent::KeyPress)
3979             extra->keyHandler->keyPressed(e, false);
3980         else
3981             extra->keyHandler->keyReleased(e, false);
3982
3983         if (e->isAccepted())
3984             return;
3985         else
3986             e->accept();
3987     }
3988
3989     if (e->type() == QEvent::KeyPress)
3990         q->keyPressEvent(e);
3991     else
3992         q->keyReleaseEvent(e);
3993
3994     if (e->isAccepted())
3995         return;
3996
3997     if (extra.isAllocated() && extra->keyHandler) {
3998         e->accept();
3999
4000         if (e->type() == QEvent::KeyPress)
4001             extra->keyHandler->keyPressed(e, true);
4002         else
4003             extra->keyHandler->keyReleased(e, true);
4004     }
4005 }
4006
4007 void QQuickItemPrivate::deliverInputMethodEvent(QInputMethodEvent *e)
4008 {
4009     Q_Q(QQuickItem);
4010
4011     Q_ASSERT(e->isAccepted());
4012     if (extra.isAllocated() && extra->keyHandler) {
4013         extra->keyHandler->inputMethodEvent(e, false);
4014
4015         if (e->isAccepted())
4016             return;
4017         else
4018             e->accept();
4019     }
4020
4021     q->inputMethodEvent(e);
4022
4023     if (e->isAccepted())
4024         return;
4025
4026     if (extra.isAllocated() && extra->keyHandler) {
4027         e->accept();
4028
4029         extra->keyHandler->inputMethodEvent(e, true);
4030     }
4031 }
4032
4033 void QQuickItemPrivate::deliverFocusEvent(QFocusEvent *e)
4034 {
4035     Q_Q(QQuickItem);
4036
4037     if (e->type() == QEvent::FocusIn) {
4038         q->focusInEvent(e);
4039     } else {
4040         q->focusOutEvent(e);
4041     }
4042 }
4043
4044 void QQuickItemPrivate::deliverMouseEvent(QMouseEvent *e)
4045 {
4046     Q_Q(QQuickItem);
4047
4048     Q_ASSERT(e->isAccepted());
4049
4050     switch (e->type()) {
4051     default:
4052         Q_ASSERT(!"Unknown event type");
4053     case QEvent::MouseMove:
4054         q->mouseMoveEvent(e);
4055         break;
4056     case QEvent::MouseButtonPress:
4057         q->mousePressEvent(e);
4058         break;
4059     case QEvent::MouseButtonRelease:
4060         q->mouseReleaseEvent(e);
4061         break;
4062     case QEvent::MouseButtonDblClick:
4063         q->mouseDoubleClickEvent(e);
4064         break;
4065     }
4066 }
4067
4068 void QQuickItemPrivate::deliverWheelEvent(QWheelEvent *e)
4069 {
4070     Q_Q(QQuickItem);
4071     q->wheelEvent(e);
4072 }
4073
4074 void QQuickItemPrivate::deliverTouchEvent(QTouchEvent *e)
4075 {
4076     Q_Q(QQuickItem);
4077     q->touchEvent(e);
4078 }
4079
4080 void QQuickItemPrivate::deliverHoverEvent(QHoverEvent *e)
4081 {
4082     Q_Q(QQuickItem);
4083     switch (e->type()) {
4084     default:
4085         Q_ASSERT(!"Unknown event type");
4086     case QEvent::HoverEnter:
4087         q->hoverEnterEvent(e);
4088         break;
4089     case QEvent::HoverLeave:
4090         q->hoverLeaveEvent(e);
4091         break;
4092     case QEvent::HoverMove:
4093         q->hoverMoveEvent(e);
4094         break;
4095     }
4096 }
4097
4098 #ifndef QT_NO_DRAGANDDROP
4099 void QQuickItemPrivate::deliverDragEvent(QEvent *e)
4100 {
4101     Q_Q(QQuickItem);
4102     switch (e->type()) {
4103     default:
4104         Q_ASSERT(!"Unknown event type");
4105     case QEvent::DragEnter:
4106         q->dragEnterEvent(static_cast<QDragEnterEvent *>(e));
4107         break;
4108     case QEvent::DragLeave:
4109         q->dragLeaveEvent(static_cast<QDragLeaveEvent *>(e));
4110         break;
4111     case QEvent::DragMove:
4112         q->dragMoveEvent(static_cast<QDragMoveEvent *>(e));
4113         break;
4114     case QEvent::Drop:
4115         q->dropEvent(static_cast<QDropEvent *>(e));
4116         break;
4117     }
4118 }
4119 #endif // QT_NO_DRAGANDDROP
4120
4121 /*!
4122   \internal
4123   */
4124 void QQuickItem::itemChange(ItemChange change, const ItemChangeData &value)
4125 {
4126     Q_UNUSED(change);
4127     Q_UNUSED(value);
4128 }
4129
4130 /*!
4131     Notify input method on updated query values if needed. \a indicates changed attributes.
4132 */
4133 void QQuickItem::updateInputMethod(Qt::InputMethodQueries queries)
4134 {
4135     if (hasActiveFocus())
4136         qApp->inputMethod()->update(queries);
4137 }
4138
4139 /*! \internal */
4140 // XXX todo - do we want/need this anymore?
4141 QRectF QQuickItem::boundingRect() const
4142 {
4143     Q_D(const QQuickItem);
4144     return QRectF(0, 0, d->width, d->height);
4145 }
4146
4147 /*! \internal */
4148 QRectF QQuickItem::clipRect() const
4149 {
4150     Q_D(const QQuickItem);
4151     return QRectF(0, 0, d->width, d->height);
4152 }
4153
4154 /*!
4155     \qmlproperty enumeration QtQuick2::Item::transformOrigin
4156     This property holds the origin point around which scale and rotation transform.
4157
4158     Nine transform origins are available, as shown in the image below.
4159     The default transform origin is \c Item.Center.
4160
4161     \image declarative-transformorigin.png
4162
4163     This example rotates an image around its bottom-right corner.
4164     \qml
4165     Image {
4166         source: "myimage.png"
4167         transformOrigin: Item.BottomRight
4168         rotation: 45
4169     }
4170     \endqml
4171
4172     To set an arbitrary transform origin point use the \l Scale or \l Rotation
4173     transform types with \l transform.
4174 */
4175 /*!
4176     \property QQuickItem::transformOrigin
4177     This property holds the origin point around which scale and rotation transform.
4178
4179     Nine transform origins are available, as shown in the image below.
4180     The default transform origin is \c Item.Center.
4181
4182     \image declarative-transformorigin.png
4183 */
4184 QQuickItem::TransformOrigin QQuickItem::transformOrigin() const
4185 {
4186     Q_D(const QQuickItem);
4187     return d->origin();
4188 }
4189
4190 void QQuickItem::setTransformOrigin(TransformOrigin origin)
4191 {
4192     Q_D(QQuickItem);
4193     if (origin == d->origin())
4194         return;
4195
4196     d->extra.value().origin = origin;
4197     d->dirty(QQuickItemPrivate::TransformOrigin);
4198
4199     emit transformOriginChanged(d->origin());
4200 }
4201
4202 /*!
4203     \property QQuickItem::transformOriginPoint
4204     \internal
4205   */
4206 /*!
4207   \internal
4208   */
4209 QPointF QQuickItem::transformOriginPoint() const
4210 {
4211     Q_D(const QQuickItem);
4212     if (d->extra.isAllocated() && !d->extra->userTransformOriginPoint.isNull())
4213         return d->extra->userTransformOriginPoint;
4214     return d->computeTransformOrigin();
4215 }
4216
4217 /*!
4218   \internal
4219   */
4220 void QQuickItem::setTransformOriginPoint(const QPointF &point)
4221 {
4222     Q_D(QQuickItem);
4223     if (d->extra.value().userTransformOriginPoint == point)
4224         return;
4225
4226     d->extra->userTransformOriginPoint = point;
4227     d->dirty(QQuickItemPrivate::TransformOrigin);
4228 }
4229
4230 /*!
4231   \qmlproperty real QtQuick2::Item::z
4232
4233   Sets the stacking order of sibling items.  By default the stacking order is 0.
4234
4235   Items with a higher stacking value are drawn on top of siblings with a
4236   lower stacking order.  Items with the same stacking value are drawn
4237   bottom up in the order they appear.  Items with a negative stacking
4238   value are drawn under their parent's content.
4239
4240   The following example shows the various effects of stacking order.
4241
4242   \table
4243   \row
4244   \li \image declarative-item_stacking1.png
4245   \li Same \c z - later children above earlier children:
4246   \qml
4247   Item {
4248       Rectangle {
4249           color: "red"
4250           width: 100; height: 100
4251       }
4252       Rectangle {
4253           color: "blue"
4254           x: 50; y: 50; width: 100; height: 100
4255       }
4256   }
4257   \endqml
4258   \row
4259   \li \image declarative-item_stacking2.png
4260   \li Higher \c z on top:
4261   \qml
4262   Item {
4263       Rectangle {
4264           z: 1
4265           color: "red"
4266           width: 100; height: 100
4267       }
4268       Rectangle {
4269           color: "blue"
4270           x: 50; y: 50; width: 100; height: 100
4271       }
4272   }
4273   \endqml
4274   \row
4275   \li \image declarative-item_stacking3.png
4276   \li Same \c z - children above parents:
4277   \qml
4278   Item {
4279       Rectangle {
4280           color: "red"
4281           width: 100; height: 100
4282           Rectangle {
4283               color: "blue"
4284               x: 50; y: 50; width: 100; height: 100
4285           }
4286       }
4287   }
4288   \endqml
4289   \row
4290   \li \image declarative-item_stacking4.png
4291   \li Lower \c z below:
4292   \qml
4293   Item {
4294       Rectangle {
4295           color: "red"
4296           width: 100; height: 100
4297           Rectangle {
4298               z: -1
4299               color: "blue"
4300               x: 50; y: 50; width: 100; height: 100
4301           }
4302       }
4303   }
4304   \endqml
4305   \endtable
4306  */
4307 /*!
4308   \qmlproperty real QtQuick2::Item::z
4309
4310   Sets the stacking order of sibling items.  By default the stacking order is 0.
4311
4312   Items with a higher stacking value are drawn on top of siblings with a
4313   lower stacking order.  Items with the same stacking value are drawn
4314   bottom up in the order they appear.  Items with a negative stacking
4315   value are drawn under their parent's content.
4316
4317   The following example shows the various effects of stacking order.
4318
4319   \table
4320   \row
4321   \li \image declarative-item_stacking1.png
4322   \li Same \c z - later children above earlier children:
4323   \qml
4324   Item {
4325       Rectangle {
4326           color: "red"
4327           width: 100; height: 100
4328       }
4329       Rectangle {
4330           color: "blue"
4331           x: 50; y: 50; width: 100; height: 100
4332       }
4333   }
4334   \endqml
4335   \row
4336   \li \image declarative-item_stacking2.png
4337   \li Higher \c z on top:
4338   \qml
4339   Item {
4340       Rectangle {
4341           z: 1
4342           color: "red"
4343           width: 100; height: 100
4344       }
4345       Rectangle {
4346           color: "blue"
4347           x: 50; y: 50; width: 100; height: 100
4348       }
4349   }
4350   \endqml
4351   \row
4352   \li \image declarative-item_stacking3.png
4353   \li Same \c z - children above parents:
4354   \qml
4355   Item {
4356       Rectangle {
4357           color: "red"
4358           width: 100; height: 100
4359           Rectangle {
4360               color: "blue"
4361               x: 50; y: 50; width: 100; height: 100
4362           }
4363       }
4364   }
4365   \endqml
4366   \row
4367   \li \image declarative-item_stacking4.png
4368   \li Lower \c z below:
4369   \qml
4370   Item {
4371       Rectangle {
4372           color: "red"
4373           width: 100; height: 100
4374           Rectangle {
4375               z: -1
4376               color: "blue"
4377               x: 50; y: 50; width: 100; height: 100
4378           }
4379       }
4380   }
4381   \endqml
4382   \endtable
4383   */
4384 qreal QQuickItem::z() const
4385 {
4386     Q_D(const QQuickItem);
4387     return d->z();
4388 }
4389
4390 void QQuickItem::setZ(qreal v)
4391 {
4392     Q_D(QQuickItem);
4393     if (d->z() == v)
4394         return;
4395
4396     d->extra.value().z = v;
4397
4398     d->dirty(QQuickItemPrivate::ZValue);
4399     if (d->parentItem) {
4400         QQuickItemPrivate::get(d->parentItem)->dirty(QQuickItemPrivate::ChildrenStackingChanged);
4401         QQuickItemPrivate::get(d->parentItem)->markSortedChildrenDirty(this);
4402     }
4403
4404     emit zChanged();
4405
4406     if (d->extra.isAllocated() && d->extra->layer)
4407         d->extra->layer->updateZ();
4408 }
4409
4410 /*!
4411   \qmlproperty real QtQuick2::Item::rotation
4412   This property holds the rotation of the item in degrees clockwise around
4413   its transformOrigin.
4414
4415   The default value is 0 degrees (that is, no rotation).
4416
4417   \table
4418   \row
4419   \li \image declarative-rotation.png
4420   \li
4421   \qml
4422   Rectangle {
4423       color: "blue"
4424       width: 100; height: 100
4425       Rectangle {
4426           color: "red"
4427           x: 25; y: 25; width: 50; height: 50
4428           rotation: 30
4429       }
4430   }
4431   \endqml
4432   \endtable
4433
4434   \sa transform, Rotation
4435 */
4436 /*!
4437   \property QQuickItem::rotation
4438   This property holds the rotation of the item in degrees clockwise around
4439   its transformOrigin.
4440
4441   The default value is 0 degrees (that is, no rotation).
4442
4443   \table
4444   \row
4445   \li \image declarative-rotation.png
4446   \li
4447   \qml
4448   Rectangle {
4449       color: "blue"
4450       width: 100; height: 100
4451       Rectangle {
4452           color: "red"
4453           x: 25; y: 25; width: 50; height: 50
4454           rotation: 30
4455       }
4456   }
4457   \endqml
4458   \endtable
4459
4460   \sa transform, Rotation
4461   */
4462 qreal QQuickItem::rotation() const
4463 {
4464     Q_D(const QQuickItem);
4465     return d->rotation();
4466 }
4467
4468 void QQuickItem::setRotation(qreal r)
4469 {
4470     Q_D(QQuickItem);
4471     if (d->rotation() == r)
4472         return;
4473
4474     d->extra.value().rotation = r;
4475
4476     d->dirty(QQuickItemPrivate::BasicTransform);
4477
4478     d->itemChange(ItemRotationHasChanged, r);
4479
4480     emit rotationChanged();
4481 }
4482
4483 /*!
4484   \qmlproperty real QtQuick2::Item::scale
4485   This property holds the scale factor for this item.
4486
4487   A scale of less than 1.0 causes the item to be rendered at a smaller
4488   size, and a scale greater than 1.0 renders the item at a larger size.
4489   A negative scale causes the item to be mirrored when rendered.
4490
4491   The default value is 1.0.
4492
4493   Scaling is applied from the transformOrigin.
4494
4495   \table
4496   \row
4497   \li \image declarative-scale.png
4498   \li
4499   \qml
4500   import QtQuick 2.0
4501
4502   Rectangle {
4503       color: "blue"
4504       width: 100; height: 100
4505
4506       Rectangle {
4507           color: "green"
4508           width: 25; height: 25
4509       }
4510
4511       Rectangle {
4512           color: "red"
4513           x: 25; y: 25; width: 50; height: 50
4514           scale: 1.4
4515       }
4516   }
4517   \endqml
4518   \endtable
4519
4520   \sa transform, Scale
4521 */
4522 /*!
4523   \property QQuickItem::scale
4524   This property holds the scale factor for this item.
4525
4526   A scale of less than 1.0 causes the item to be rendered at a smaller
4527   size, and a scale greater than 1.0 renders the item at a larger size.
4528   A negative scale causes the item to be mirrored when rendered.
4529
4530   The default value is 1.0.
4531
4532   Scaling is applied from the transformOrigin.
4533
4534   \table
4535   \row
4536   \li \image declarative-scale.png
4537   \li
4538   \qml
4539   import QtQuick 2.0
4540
4541   Rectangle {
4542       color: "blue"
4543       width: 100; height: 100
4544
4545       Rectangle {
4546           color: "green"
4547           width: 25; height: 25
4548       }
4549
4550       Rectangle {
4551           color: "red"
4552           x: 25; y: 25; width: 50; height: 50
4553           scale: 1.4
4554       }
4555   }
4556   \endqml
4557   \endtable
4558
4559   \sa transform, Scale
4560   */
4561 qreal QQuickItem::scale() const
4562 {
4563     Q_D(const QQuickItem);
4564     return d->scale();
4565 }
4566
4567 void QQuickItem::setScale(qreal s)
4568 {
4569     Q_D(QQuickItem);
4570     if (d->scale() == s)
4571         return;
4572
4573     d->extra.value().scale = s;
4574
4575     d->dirty(QQuickItemPrivate::BasicTransform);
4576
4577     emit scaleChanged();
4578 }
4579
4580 /*!
4581   \qmlproperty real QtQuick2::Item::opacity
4582
4583   This property holds the opacity of the item.  Opacity is specified as a
4584   number between 0.0 (fully transparent) and 1.0 (fully opaque). The default
4585   value is 1.0.
4586
4587   When this property is set, the specified opacity is also applied
4588   individually to child items. This may have an unintended effect in some
4589   circumstances. For example in the second set of rectangles below, the red
4590   rectangle has specified an opacity of 0.5, which affects the opacity of
4591   its blue child rectangle even though the child has not specified an opacity.
4592
4593   \table
4594   \row
4595   \li \image declarative-item_opacity1.png
4596   \li
4597   \qml
4598     Item {
4599         Rectangle {
4600             color: "red"
4601             width: 100; height: 100
4602             Rectangle {
4603                 color: "blue"
4604                 x: 50; y: 50; width: 100; height: 100
4605             }
4606         }
4607     }
4608   \endqml
4609   \row
4610   \li \image declarative-item_opacity2.png
4611   \li
4612   \qml
4613     Item {
4614         Rectangle {
4615             opacity: 0.5
4616             color: "red"
4617             width: 100; height: 100
4618             Rectangle {
4619                 color: "blue"
4620                 x: 50; y: 50; width: 100; height: 100
4621             }
4622         }
4623     }
4624   \endqml
4625   \endtable
4626
4627   Changing an item's opacity does not affect whether the item receives user
4628   input events. (In contrast, setting \l visible property to \c false stops
4629   mouse events, and setting the \l enabled property to \c false stops mouse
4630   and keyboard events, and also removes active focus from the item.)
4631
4632   \sa visible
4633 */
4634 /*!
4635   \property QQuickItem::opacity
4636
4637   This property holds the opacity of the item.  Opacity is specified as a
4638   number between 0.0 (fully transparent) and 1.0 (fully opaque). The default
4639   value is 1.0.
4640
4641   When this property is set, the specified opacity is also applied
4642   individually to child items. This may have an unintended effect in some
4643   circumstances. For example in the second set of rectangles below, the red
4644   rectangle has specified an opacity of 0.5, which affects the opacity of
4645   its blue child rectangle even though the child has not specified an opacity.
4646
4647   \table
4648   \row
4649   \li \image declarative-item_opacity1.png
4650   \li
4651   \qml
4652     Item {
4653         Rectangle {
4654             color: "red"
4655             width: 100; height: 100
4656             Rectangle {
4657                 color: "blue"
4658                 x: 50; y: 50; width: 100; height: 100
4659             }
4660         }
4661     }
4662   \endqml
4663   \row
4664   \li \image declarative-item_opacity2.png
4665   \li
4666   \qml
4667     Item {
4668         Rectangle {
4669             opacity: 0.5
4670             color: "red"
4671             width: 100; height: 100
4672             Rectangle {
4673                 color: "blue"
4674                 x: 50; y: 50; width: 100; height: 100
4675             }
4676         }
4677     }
4678   \endqml
4679   \endtable
4680
4681   Changing an item's opacity does not affect whether the item receives user
4682   input events. (In contrast, setting \l visible property to \c false stops
4683   mouse events, and setting the \l enabled property to \c false stops mouse
4684   and keyboard events, and also removes active focus from the item.)
4685
4686   \sa visible
4687 */
4688 qreal QQuickItem::opacity() const
4689 {
4690     Q_D(const QQuickItem);
4691     return d->opacity();
4692 }
4693
4694 void QQuickItem::setOpacity(qreal o)
4695 {
4696     Q_D(QQuickItem);
4697     if (d->opacity() == o)
4698         return;
4699
4700     d->extra.value().opacity = o;
4701
4702     d->dirty(QQuickItemPrivate::OpacityValue);
4703
4704     d->itemChange(ItemOpacityHasChanged, o);
4705
4706     emit opacityChanged();
4707 }
4708
4709 /*!
4710     \qmlproperty bool QtQuick2::Item::visible
4711
4712     This property holds whether the item is visible. By default this is true.
4713
4714     Setting this property directly affects the \c visible value of child
4715     items. When set to \c false, the \c visible values of all child items also
4716     become \c false. When set to \c true, the \c visible values of child items
4717     are returned to \c true, unless they have explicitly been set to \c false.
4718
4719     (Because of this flow-on behavior, using the \c visible property may not
4720     have the intended effect if a property binding should only respond to
4721     explicit property changes. In such cases it may be better to use the
4722     \l opacity property instead.)
4723
4724     If this property is set to \c false, the item will no longer receive mouse
4725     events, but will continue to receive key events and will retain the keyboard
4726     \l focus if it has been set. (In contrast, setting the \l enabled property
4727     to \c false stops both mouse and keyboard events, and also removes focus
4728     from the item.)
4729
4730     \note This property's value is only affected by changes to this property or
4731     the parent's \c visible property. It does not change, for example, if this
4732     item moves off-screen, or if the \l opacity changes to 0.
4733
4734     \sa opacity, enabled
4735 */
4736 /*!
4737     \property QQuickItem::visible
4738
4739     This property holds whether the item is visible. By default this is true.
4740
4741     Setting this property directly affects the \c visible value of child
4742     items. When set to \c false, the \c visible values of all child items also
4743     become \c false. When set to \c true, the \c visible values of child items
4744     are returned to \c true, unless they have explicitly been set to \c false.
4745
4746     (Because of this flow-on behavior, using the \c visible property may not
4747     have the intended effect if a property binding should only respond to
4748     explicit property changes. In such cases it may be better to use the
4749     \l opacity property instead.)
4750
4751     If this property is set to \c false, the item will no longer receive mouse
4752     events, but will continue to receive key events and will retain the keyboard
4753     \l focus if it has been set. (In contrast, setting the \l enabled property
4754     to \c false stops both mouse and keyboard events, and also removes focus
4755     from the item.)
4756
4757     \note This property's value is only affected by changes to this property or
4758     the parent's \c visible property. It does not change, for example, if this
4759     item moves off-screen, or if the \l opacity changes to 0.
4760
4761     \sa opacity, enabled
4762 */
4763 bool QQuickItem::isVisible() const
4764 {
4765     Q_D(const QQuickItem);
4766     return d->effectiveVisible;
4767 }
4768
4769 void QQuickItem::setVisible(bool v)
4770 {
4771     Q_D(QQuickItem);
4772     if (v == d->explicitVisible)
4773         return;
4774
4775     d->explicitVisible = v;
4776     if (!v)
4777         d->dirty(QQuickItemPrivate::Visible);
4778
4779     const bool childVisibilityChanged = d->setEffectiveVisibleRecur(d->calcEffectiveVisible());
4780     if (childVisibilityChanged && d->parentItem)
4781         emit d->parentItem->visibleChildrenChanged();   // signal the parent, not this!
4782 }
4783
4784 /*!
4785     \qmlproperty bool QtQuick2::Item::enabled
4786
4787     This property holds whether the item receives mouse and keyboard events.
4788     By default this is true.
4789
4790     Setting this property directly affects the \c enabled value of child
4791     items. When set to \c false, the \c enabled values of all child items also
4792     become \c false. When set to \c true, the \c enabled values of child items
4793     are returned to \c true, unless they have explicitly been set to \c false.
4794
4795     Setting this property to \c false automatically causes \l activeFocus to be
4796     set to \c false, and this item will longer receive keyboard events.
4797
4798     \sa visible
4799 */
4800 /*!
4801     \property QQuickItem::enabled
4802
4803     This property holds whether the item receives mouse and keyboard events.
4804     By default this is true.
4805
4806     Setting this property directly affects the \c enabled value of child
4807     items. When set to \c false, the \c enabled values of all child items also
4808     become \c false. When set to \c true, the \c enabled values of child items
4809     are returned to \c true, unless they have explicitly been set to \c false.
4810
4811     Setting this property to \c false automatically causes \l activeFocus to be
4812     set to \c false, and this item will longer receive keyboard events.
4813
4814     \sa visible
4815 */
4816 bool QQuickItem::isEnabled() const
4817 {
4818     Q_D(const QQuickItem);
4819     return d->effectiveEnable;
4820 }
4821
4822 void QQuickItem::setEnabled(bool e)
4823 {
4824     Q_D(QQuickItem);
4825     if (e == d->explicitEnable)
4826         return;
4827
4828     d->explicitEnable = e;
4829
4830     QQuickItem *scope = parentItem();
4831     while (scope && !scope->isFocusScope())
4832         scope = scope->parentItem();
4833
4834     d->setEffectiveEnableRecur(scope, d->calcEffectiveEnable());
4835 }
4836
4837 bool QQuickItemPrivate::calcEffectiveVisible() const
4838 {
4839     // XXX todo - Should the effective visible of an element with no parent just be the current
4840     // effective visible?  This would prevent pointless re-processing in the case of an element
4841     // moving to/from a no-parent situation, but it is different from what graphics view does.
4842     return explicitVisible && (!parentItem || QQuickItemPrivate::get(parentItem)->effectiveVisible);
4843 }
4844
4845 bool QQuickItemPrivate::setEffectiveVisibleRecur(bool newEffectiveVisible)
4846 {
4847     Q_Q(QQuickItem);
4848
4849     if (newEffectiveVisible && !explicitVisible) {
4850         // This item locally overrides visibility
4851         return false;   // effective visibility didn't change
4852     }
4853
4854     if (newEffectiveVisible == effectiveVisible) {
4855         // No change necessary
4856         return false;   // effective visibility didn't change
4857     }
4858
4859     effectiveVisible = newEffectiveVisible;
4860     dirty(Visible);
4861     if (parentItem) QQuickItemPrivate::get(parentItem)->dirty(ChildrenStackingChanged);
4862
4863     if (window) {
4864         QQuickWindowPrivate *windowPriv = QQuickWindowPrivate::get(window);
4865         if (windowPriv->mouseGrabberItem == q)
4866             q->ungrabMouse();
4867     }
4868
4869     bool childVisibilityChanged = false;
4870     for (int ii = 0; ii < childItems.count(); ++ii)
4871         childVisibilityChanged |= QQuickItemPrivate::get(childItems.at(ii))->setEffectiveVisibleRecur(newEffectiveVisible);
4872
4873     itemChange(QQuickItem::ItemVisibleHasChanged, effectiveVisible);
4874 #ifndef QT_NO_ACCESSIBILITY
4875     if (isAccessible) {
4876         QAccessibleEvent ev(q, effectiveVisible ? QAccessible::ObjectShow : QAccessible::ObjectHide);
4877         QAccessible::updateAccessibility(&ev);
4878     }
4879 #endif
4880     emit q->visibleChanged();
4881     if (childVisibilityChanged)
4882         emit q->visibleChildrenChanged();
4883
4884     return true;    // effective visibility DID change
4885 }
4886
4887 bool QQuickItemPrivate::calcEffectiveEnable() const
4888 {
4889     // XXX todo - Should the effective enable of an element with no parent just be the current
4890     // effective enable?  This would prevent pointless re-processing in the case of an element
4891     // moving to/from a no-parent situation, but it is different from what graphics view does.
4892     return explicitEnable && (!parentItem || QQuickItemPrivate::get(parentItem)->effectiveEnable);
4893 }
4894
4895 void QQuickItemPrivate::setEffectiveEnableRecur(QQuickItem *scope, bool newEffectiveEnable)
4896 {
4897     Q_Q(QQuickItem);
4898
4899     if (newEffectiveEnable && !explicitEnable) {
4900         // This item locally overrides enable
4901         return;
4902     }
4903
4904     if (newEffectiveEnable == effectiveEnable) {
4905         // No change necessary
4906         return;
4907     }
4908
4909     effectiveEnable = newEffectiveEnable;
4910
4911     if (window) {
4912         QQuickWindowPrivate *windowPriv = QQuickWindowPrivate::get(window);
4913         if (windowPriv->mouseGrabberItem == q)
4914             q->ungrabMouse();
4915         if (scope && !effectiveEnable && activeFocus) {
4916             windowPriv->clearFocusInScope(
4917                     scope, q,  QQuickWindowPrivate::DontChangeFocusProperty | QQuickWindowPrivate::DontChangeSubFocusItem);
4918         }
4919     }
4920
4921     for (int ii = 0; ii < childItems.count(); ++ii) {
4922         QQuickItemPrivate::get(childItems.at(ii))->setEffectiveEnableRecur(
4923                 (flags & QQuickItem::ItemIsFocusScope) && scope ? q : scope, newEffectiveEnable);
4924     }
4925
4926     if (window && scope && effectiveEnable && focus) {
4927         QQuickWindowPrivate::get(window)->setFocusInScope(
4928                 scope, q, QQuickWindowPrivate::DontChangeFocusProperty | QQuickWindowPrivate::DontChangeSubFocusItem);
4929     }
4930
4931     emit q->enabledChanged();
4932 }
4933
4934 QString QQuickItemPrivate::dirtyToString() const
4935 {
4936 #define DIRTY_TO_STRING(value) if (dirtyAttributes & value) { \
4937     if (!rv.isEmpty()) \
4938         rv.append(QLatin1String("|")); \
4939     rv.append(QLatin1String(#value)); \
4940 }
4941
4942 //    QString rv = QLatin1String("0x") + QString::number(dirtyAttributes, 16);
4943     QString rv;
4944
4945     DIRTY_TO_STRING(TransformOrigin);
4946     DIRTY_TO_STRING(Transform);
4947     DIRTY_TO_STRING(BasicTransform);
4948     DIRTY_TO_STRING(Position);
4949     DIRTY_TO_STRING(Size);
4950     DIRTY_TO_STRING(ZValue);
4951     DIRTY_TO_STRING(Content);
4952     DIRTY_TO_STRING(Smooth);
4953     DIRTY_TO_STRING(OpacityValue);
4954     DIRTY_TO_STRING(ChildrenChanged);
4955     DIRTY_TO_STRING(ChildrenStackingChanged);
4956     DIRTY_TO_STRING(ParentChanged);
4957     DIRTY_TO_STRING(Clip);
4958     DIRTY_TO_STRING(Window);
4959     DIRTY_TO_STRING(EffectReference);
4960     DIRTY_TO_STRING(Visible);
4961     DIRTY_TO_STRING(HideReference);
4962     DIRTY_TO_STRING(Antialiasing);
4963
4964     return rv;
4965 }
4966
4967 void QQuickItemPrivate::dirty(DirtyType type)
4968 {
4969     Q_Q(QQuickItem);
4970     if (type & (TransformOrigin | Transform | BasicTransform | Position | Size))
4971         transformChanged();
4972
4973     if (!(dirtyAttributes & type) || (window && !prevDirtyItem)) {
4974         dirtyAttributes |= type;
4975         if (window && componentComplete) {
4976             addToDirtyList();
4977             QQuickWindowPrivate::get(window)->dirtyItem(q);
4978         }
4979     }
4980 }
4981
4982 void QQuickItemPrivate::addToDirtyList()
4983 {
4984     Q_Q(QQuickItem);
4985
4986     Q_ASSERT(window);
4987     if (!prevDirtyItem) {
4988         Q_ASSERT(!nextDirtyItem);
4989
4990         QQuickWindowPrivate *p = QQuickWindowPrivate::get(window);
4991         nextDirtyItem = p->dirtyItemList;
4992         if (nextDirtyItem) QQuickItemPrivate::get(nextDirtyItem)->prevDirtyItem = &nextDirtyItem;
4993         prevDirtyItem = &p->dirtyItemList;
4994         p->dirtyItemList = q;
4995         p->dirtyItem(q);
4996     }
4997     Q_ASSERT(prevDirtyItem);
4998 }
4999
5000 void QQuickItemPrivate::removeFromDirtyList()
5001 {
5002     if (prevDirtyItem) {
5003         if (nextDirtyItem) QQuickItemPrivate::get(nextDirtyItem)->prevDirtyItem = prevDirtyItem;
5004         *prevDirtyItem = nextDirtyItem;
5005         prevDirtyItem = 0;
5006         nextDirtyItem = 0;
5007     }
5008     Q_ASSERT(!prevDirtyItem);
5009     Q_ASSERT(!nextDirtyItem);
5010 }
5011
5012 void QQuickItemPrivate::refFromEffectItem(bool hide)
5013 {
5014     ++extra.value().effectRefCount;
5015     if (1 == extra->effectRefCount) {
5016         dirty(EffectReference);
5017         if (parentItem) QQuickItemPrivate::get(parentItem)->dirty(ChildrenStackingChanged);
5018     }
5019     if (hide) {
5020         if (++extra->hideRefCount == 1)
5021             dirty(HideReference);
5022     }
5023 }
5024
5025 void QQuickItemPrivate::derefFromEffectItem(bool unhide)
5026 {
5027     Q_ASSERT(extra->effectRefCount);
5028     --extra->effectRefCount;
5029     if (0 == extra->effectRefCount) {
5030         dirty(EffectReference);
5031         if (parentItem) QQuickItemPrivate::get(parentItem)->dirty(ChildrenStackingChanged);
5032     }
5033     if (unhide) {
5034         if (--extra->hideRefCount == 0)
5035             dirty(HideReference);
5036     }
5037 }
5038
5039 void QQuickItemPrivate::setCulled(bool cull)
5040 {
5041     if (cull == culled)
5042         return;
5043
5044     culled = cull;
5045     if ((cull && ++extra.value().hideRefCount == 1) || (!cull && --extra.value().hideRefCount == 0))
5046         dirty(HideReference);
5047 }
5048
5049 void QQuickItemPrivate::itemChange(QQuickItem::ItemChange change, const QQuickItem::ItemChangeData &data)
5050 {
5051     Q_Q(QQuickItem);
5052     switch (change) {
5053     case QQuickItem::ItemChildAddedChange:
5054         q->itemChange(change, data);
5055         for (int ii = 0; ii < changeListeners.count(); ++ii) {
5056             const QQuickItemPrivate::ChangeListener &change = changeListeners.at(ii);
5057             if (change.types & QQuickItemPrivate::Children) {
5058                 change.listener->itemChildAdded(q, data.item);
5059             }
5060         }
5061         break;
5062     case QQuickItem::ItemChildRemovedChange:
5063         q->itemChange(change, data);
5064         for (int ii = 0; ii < changeListeners.count(); ++ii) {
5065             const QQuickItemPrivate::ChangeListener &change = changeListeners.at(ii);
5066             if (change.types & QQuickItemPrivate::Children) {
5067                 change.listener->itemChildRemoved(q, data.item);
5068             }
5069         }
5070         break;
5071     case QQuickItem::ItemSceneChange:
5072         q->itemChange(change, data);
5073         break;
5074     case QQuickItem::ItemVisibleHasChanged:
5075         q->itemChange(change, data);
5076         for (int ii = 0; ii < changeListeners.count(); ++ii) {
5077             const QQuickItemPrivate::ChangeListener &change = changeListeners.at(ii);
5078             if (change.types & QQuickItemPrivate::Visibility) {
5079                 change.listener->itemVisibilityChanged(q);
5080             }
5081         }
5082         break;
5083     case QQuickItem::ItemParentHasChanged:
5084         q->itemChange(change, data);
5085         for (int ii = 0; ii < changeListeners.count(); ++ii) {
5086             const QQuickItemPrivate::ChangeListener &change = changeListeners.at(ii);
5087             if (change.types & QQuickItemPrivate::Parent) {
5088                 change.listener->itemParentChanged(q, data.item);
5089             }
5090         }
5091         break;
5092     case QQuickItem::ItemOpacityHasChanged:
5093         q->itemChange(change, data);
5094         for (int ii = 0; ii < changeListeners.count(); ++ii) {
5095             const QQuickItemPrivate::ChangeListener &change = changeListeners.at(ii);
5096             if (change.types & QQuickItemPrivate::Opacity) {
5097                 change.listener->itemOpacityChanged(q);
5098             }
5099         }
5100         break;
5101     case QQuickItem::ItemActiveFocusHasChanged:
5102         q->itemChange(change, data);
5103         break;
5104     case QQuickItem::ItemRotationHasChanged:
5105         q->itemChange(change, data);
5106         for (int ii = 0; ii < changeListeners.count(); ++ii) {
5107             const QQuickItemPrivate::ChangeListener &change = changeListeners.at(ii);
5108             if (change.types & QQuickItemPrivate::Rotation) {
5109                 change.listener->itemRotationChanged(q);
5110             }
5111         }
5112         break;
5113     }
5114 }
5115
5116 /*!
5117     \qmlproperty bool QtQuick2::Item::smooth
5118
5119     Primarily used in image based items to decide if the item should use smooth
5120     sampling or not. Smooth sampling is performed using linear interpolation, while
5121     non-smooth is performed using nearest neighbor.
5122
5123     In Qt Quick 2.0, this property has minimal impact on performance.
5124
5125     By default is true.
5126 */
5127 /*!
5128     \property QQuickItem::smooth
5129     \brief Specifies whether the item is smoothed or not
5130
5131     Primarily used in image based items to decide if the item should use smooth
5132     sampling or not. Smooth sampling is performed using linear interpolation, while
5133     non-smooth is performed using nearest neighbor.
5134
5135     In Qt Quick 2.0, this property has minimal impact on performance.
5136
5137     By default is true.
5138 */
5139 bool QQuickItem::smooth() const
5140 {
5141     Q_D(const QQuickItem);
5142     return d->smooth;
5143 }
5144 void QQuickItem::setSmooth(bool smooth)
5145 {
5146     Q_D(QQuickItem);
5147     if (d->smooth == smooth)
5148         return;
5149
5150     d->smooth = smooth;
5151     d->dirty(QQuickItemPrivate::Smooth);
5152
5153     emit smoothChanged(smooth);
5154 }
5155
5156 /*!
5157     \qmlproperty bool QtQuick2::Item::antialiasing
5158
5159     Primarily used in Rectangle and image based elements to decide if the item should
5160     use antialiasing or not. Items with antialiasing enabled require more memory and
5161     are potentially slower to render.
5162
5163     The default is false.
5164 */
5165 /*!
5166     \property QQuickItem::antialiasing
5167     \brief Specifies whether the item is antialiased or not
5168
5169     Primarily used in Rectangle and image based elements to decide if the item should
5170     use antialiasing or not. Items with antialiasing enabled require more memory and
5171     are potentially slower to render.
5172
5173     The default is false.
5174 */
5175 bool QQuickItem::antialiasing() const
5176 {
5177     Q_D(const QQuickItem);
5178     return d->antialiasing;
5179 }
5180 void QQuickItem::setAntialiasing(bool antialiasing)
5181 {
5182     Q_D(QQuickItem);
5183     if (d->antialiasing == antialiasing)
5184         return;
5185
5186     d->antialiasing = antialiasing;
5187     d->dirty(QQuickItemPrivate::Antialiasing);
5188
5189     emit antialiasingChanged(antialiasing);
5190 }
5191
5192 /*!
5193     Returns the item flags for this item.
5194
5195     \sa setFlag()
5196   */
5197 QQuickItem::Flags QQuickItem::flags() const
5198 {
5199     Q_D(const QQuickItem);
5200     return (QQuickItem::Flags)d->flags;
5201 }
5202
5203 /*!
5204     Enables the specified \a flag for this item if \a enabled is true;
5205     if \a enabled is false, the flag is disabled.
5206
5207     These provide various hints for the item; for example, the
5208     ItemClipsChildrenToShape flag indicates that all children of this
5209     item should be clipped to fit within the item area.
5210   */
5211 void QQuickItem::setFlag(Flag flag, bool enabled)
5212 {
5213     Q_D(QQuickItem);
5214     if (enabled)
5215         setFlags((Flags)(d->flags | (quint32)flag));
5216     else
5217         setFlags((Flags)(d->flags & ~(quint32)flag));
5218 }
5219
5220 /*!
5221     Enables the specified \a flags for this item.
5222
5223     \sa setFlag()
5224   */
5225 void QQuickItem::setFlags(Flags flags)
5226 {
5227     Q_D(QQuickItem);
5228
5229     if ((flags & ItemIsFocusScope) != (d->flags & ItemIsFocusScope)) {
5230         if (flags & ItemIsFocusScope && !d->childItems.isEmpty() && d->window) {
5231             qWarning("QQuickItem: Cannot set FocusScope once item has children and is in a window.");
5232             flags &= ~ItemIsFocusScope;
5233         } else if (d->flags & ItemIsFocusScope) {
5234             qWarning("QQuickItem: Cannot unset FocusScope flag.");
5235             flags |= ItemIsFocusScope;
5236         }
5237     }
5238
5239     if ((flags & ItemClipsChildrenToShape ) != (d->flags & ItemClipsChildrenToShape))
5240         d->dirty(QQuickItemPrivate::Clip);
5241
5242     d->flags = flags;
5243 }
5244
5245 /*!
5246   \qmlproperty real QtQuick2::Item::x
5247   \qmlproperty real QtQuick2::Item::y
5248   \qmlproperty real QtQuick2::Item::width
5249   \qmlproperty real QtQuick2::Item::height
5250
5251   Defines the item's position and size.
5252
5253   The (x,y) position is relative to the \l parent.
5254
5255   \qml
5256   Item { x: 100; y: 100; width: 100; height: 100 }
5257   \endqml
5258  */
5259 /*!
5260   \property QQuickItem::x
5261
5262   Defines the item's x position relative to its parent.
5263   */
5264 /*!
5265   \property QQuickItem::y
5266
5267   Defines the item's y position relative to its parent.
5268   */
5269 qreal QQuickItem::x() const
5270 {
5271     Q_D(const QQuickItem);
5272     return d->x;
5273 }
5274
5275 qreal QQuickItem::y() const
5276 {
5277     Q_D(const QQuickItem);
5278     return d->y;
5279 }
5280
5281 /*!
5282     \property QQuickItem::pos
5283     \internal
5284   */
5285 /*!
5286     \internal
5287   */
5288 QPointF QQuickItem::pos() const
5289 {
5290     Q_D(const QQuickItem);
5291     return QPointF(d->x, d->y);
5292 }
5293
5294 void QQuickItem::setX(qreal v)
5295 {
5296     Q_D(QQuickItem);
5297     if (d->x == v)
5298         return;
5299
5300     qreal oldx = d->x;
5301     d->x = v;
5302
5303     d->dirty(QQuickItemPrivate::Position);
5304
5305     geometryChanged(QRectF(x(), y(), width(), height()),
5306                     QRectF(oldx, y(), width(), height()));
5307 }
5308
5309 void QQuickItem::setY(qreal v)
5310 {
5311     Q_D(QQuickItem);
5312     if (d->y == v)
5313         return;
5314
5315     qreal oldy = d->y;
5316     d->y = v;
5317
5318     d->dirty(QQuickItemPrivate::Position);
5319
5320     geometryChanged(QRectF(x(), y(), width(), height()),
5321                     QRectF(x(), oldy, width(), height()));
5322 }
5323
5324 /*!
5325     \internal
5326   */
5327 void QQuickItem::setPos(const QPointF &pos)
5328 {
5329     Q_D(QQuickItem);
5330     if (QPointF(d->x, d->y) == pos)
5331         return;
5332
5333     qreal oldx = d->x;
5334     qreal oldy = d->y;
5335
5336     d->x = pos.x();
5337     d->y = pos.y();
5338
5339     d->dirty(QQuickItemPrivate::Position);
5340
5341     geometryChanged(QRectF(x(), y(), width(), height()),
5342                     QRectF(oldx, oldy, width(), height()));
5343 }
5344
5345 /*!
5346     \property QQuickItem::width
5347
5348     This property holds the width of this item.
5349   */
5350 qreal QQuickItem::width() const
5351 {
5352     Q_D(const QQuickItem);
5353     return d->width;
5354 }
5355
5356 void QQuickItem::setWidth(qreal w)
5357 {
5358     Q_D(QQuickItem);
5359     if (qIsNaN(w))
5360         return;
5361
5362     d->widthValid = true;
5363     if (d->width == w)
5364         return;
5365
5366     qreal oldWidth = d->width;
5367     d->width = w;
5368
5369     d->dirty(QQuickItemPrivate::Size);
5370
5371     geometryChanged(QRectF(x(), y(), width(), height()),
5372                     QRectF(x(), y(), oldWidth, height()));
5373 }
5374
5375 void QQuickItem::resetWidth()
5376 {
5377     Q_D(QQuickItem);
5378     d->widthValid = false;
5379     setImplicitWidth(implicitWidth());
5380 }
5381
5382 void QQuickItemPrivate::implicitWidthChanged()
5383 {
5384     Q_Q(QQuickItem);
5385     for (int ii = 0; ii < changeListeners.count(); ++ii) {
5386         const QQuickItemPrivate::ChangeListener &change = changeListeners.at(ii);
5387         if (change.types & QQuickItemPrivate::ImplicitWidth) {
5388             change.listener->itemImplicitWidthChanged(q);
5389         }
5390     }
5391     emit q->implicitWidthChanged();
5392 }
5393
5394 qreal QQuickItemPrivate::getImplicitWidth() const
5395 {
5396     return implicitWidth;
5397 }
5398 /*!
5399     Returns the width of the item that is implied by other properties that determine the content.
5400 */
5401 qreal QQuickItem::implicitWidth() const
5402 {
5403     Q_D(const QQuickItem);
5404     return d->getImplicitWidth();
5405 }
5406
5407 /*!
5408     \qmlproperty real QtQuick2::Item::implicitWidth
5409     \qmlproperty real QtQuick2::Item::implicitHeight
5410
5411     Defines the natural width or height of the Item if no \l width or \l height is specified.
5412
5413     The default implicit size for most items is 0x0, however some items have an inherent
5414     implicit size which cannot be overridden, e.g. Image, Text.
5415
5416     Setting the implicit size is useful for defining components that have a preferred size
5417     based on their content, for example:
5418
5419     \qml
5420     // Label.qml
5421     import QtQuick 2.0
5422
5423     Item {
5424         property alias icon: image.source
5425         property alias label: text.text
5426         implicitWidth: text.implicitWidth + image.implicitWidth
5427         implicitHeight: Math.max(text.implicitHeight, image.implicitHeight)
5428         Image { id: image }
5429         Text {
5430             id: text
5431             wrapMode: Text.Wrap
5432             anchors.left: image.right; anchors.right: parent.right
5433             anchors.verticalCenter: parent.verticalCenter
5434         }
5435     }
5436     \endqml
5437
5438     \b Note: using implicitWidth of Text or TextEdit and setting the width explicitly
5439     incurs a performance penalty as the text must be laid out twice.
5440 */
5441 /*!
5442     \property QQuickItem::implicitWidth
5443     \property QQuickItem::implicitHeight
5444
5445     Defines the natural width or height of the Item if no \l width or \l height is specified.
5446
5447     The default implicit size for most items is 0x0, however some items have an inherent
5448     implicit size which cannot be overridden, e.g. Image, Text.
5449
5450     Setting the implicit size is useful for defining components that have a preferred size
5451     based on their content, for example:
5452
5453     \qml
5454     // Label.qml
5455     import QtQuick 2.0
5456
5457     Item {
5458         property alias icon: image.source
5459         property alias label: text.text
5460         implicitWidth: text.implicitWidth + image.implicitWidth
5461         implicitHeight: Math.max(text.implicitHeight, image.implicitHeight)
5462         Image { id: image }
5463         Text {
5464             id: text
5465             wrapMode: Text.Wrap
5466             anchors.left: image.right; anchors.right: parent.right
5467             anchors.verticalCenter: parent.verticalCenter
5468         }
5469     }
5470     \endqml
5471
5472     \b Note: using implicitWidth of Text or TextEdit and setting the width explicitly
5473     incurs a performance penalty as the text must be laid out twice.
5474 */
5475 void QQuickItem::setImplicitWidth(qreal w)
5476 {
5477     Q_D(QQuickItem);
5478     bool changed = w != d->implicitWidth;
5479     d->implicitWidth = w;
5480     if (d->width == w || widthValid()) {
5481         if (changed)
5482             d->implicitWidthChanged();
5483         if (d->width == w || widthValid())
5484             return;
5485         changed = false;
5486     }
5487
5488     qreal oldWidth = d->width;
5489     d->width = w;
5490
5491     d->dirty(QQuickItemPrivate::Size);
5492
5493     geometryChanged(QRectF(x(), y(), width(), height()),
5494                     QRectF(x(), y(), oldWidth, height()));
5495
5496     if (changed)
5497         d->implicitWidthChanged();
5498 }
5499
5500 /*!
5501     Returns whether the width property has been set explicitly.
5502 */
5503 bool QQuickItem::widthValid() const
5504 {
5505     Q_D(const QQuickItem);
5506     return d->widthValid;
5507 }
5508
5509 /*!
5510     \property QQuickItem::height
5511
5512     This property holds the height of this item.
5513   */
5514 qreal QQuickItem::height() const
5515 {
5516     Q_D(const QQuickItem);
5517     return d->height;
5518 }
5519
5520 void QQuickItem::setHeight(qreal h)
5521 {
5522     Q_D(QQuickItem);
5523     if (qIsNaN(h))
5524         return;
5525
5526     d->heightValid = true;
5527     if (d->height == h)
5528         return;
5529
5530     qreal oldHeight = d->height;
5531     d->height = h;
5532
5533     d->dirty(QQuickItemPrivate::Size);
5534
5535     geometryChanged(QRectF(x(), y(), width(), height()),
5536                     QRectF(x(), y(), width(), oldHeight));
5537 }
5538
5539 void QQuickItem::resetHeight()
5540 {
5541     Q_D(QQuickItem);
5542     d->heightValid = false;
5543     setImplicitHeight(implicitHeight());
5544 }
5545
5546 void QQuickItemPrivate::implicitHeightChanged()
5547 {
5548     Q_Q(QQuickItem);
5549     for (int ii = 0; ii < changeListeners.count(); ++ii) {
5550         const QQuickItemPrivate::ChangeListener &change = changeListeners.at(ii);
5551         if (change.types & QQuickItemPrivate::ImplicitHeight) {
5552             change.listener->itemImplicitHeightChanged(q);
5553         }
5554     }
5555     emit q->implicitHeightChanged();
5556 }
5557
5558 qreal QQuickItemPrivate::getImplicitHeight() const
5559 {
5560     return implicitHeight;
5561 }
5562
5563 qreal QQuickItem::implicitHeight() const
5564 {
5565     Q_D(const QQuickItem);
5566     return d->getImplicitHeight();
5567 }
5568
5569 void QQuickItem::setImplicitHeight(qreal h)
5570 {
5571     Q_D(QQuickItem);
5572     bool changed = h != d->implicitHeight;
5573     d->implicitHeight = h;
5574     if (d->height == h || heightValid()) {
5575         if (changed)
5576             d->implicitHeightChanged();
5577         if (d->height == h || heightValid())
5578             return;
5579         changed = false;
5580     }
5581
5582     qreal oldHeight = d->height;
5583     d->height = h;
5584
5585     d->dirty(QQuickItemPrivate::Size);
5586
5587     geometryChanged(QRectF(x(), y(), width(), height()),
5588                     QRectF(x(), y(), width(), oldHeight));
5589
5590     if (changed)
5591         d->implicitHeightChanged();
5592 }
5593
5594 /*!
5595     \internal
5596   */
5597 void QQuickItem::setImplicitSize(qreal w, qreal h)
5598 {
5599     Q_D(QQuickItem);
5600     bool wChanged = w != d->implicitWidth;
5601     bool hChanged = h != d->implicitHeight;
5602
5603     d->implicitWidth = w;
5604     d->implicitHeight = h;
5605
5606     bool wDone = false;
5607     bool hDone = false;
5608     if (d->width == w || widthValid()) {
5609         if (wChanged)
5610             d->implicitWidthChanged();
5611         wDone = d->width == w || widthValid();
5612         wChanged = false;
5613     }
5614     if (d->height == h || heightValid()) {
5615         if (hChanged)
5616             d->implicitHeightChanged();
5617         hDone = d->height == h || heightValid();
5618         hChanged = false;
5619     }
5620     if (wDone && hDone)
5621         return;
5622
5623     qreal oldWidth = d->width;
5624     qreal oldHeight = d->height;
5625     if (!wDone)
5626         d->width = w;
5627     if (!hDone)
5628         d->height = h;
5629
5630     d->dirty(QQuickItemPrivate::Size);
5631
5632     geometryChanged(QRectF(x(), y(), width(), height()),
5633                     QRectF(x(), y(), oldWidth, oldHeight));
5634
5635     if (!wDone && wChanged)
5636         d->implicitWidthChanged();
5637     if (!hDone && hChanged)
5638         d->implicitHeightChanged();
5639 }
5640
5641 /*!
5642     Returns whether the height property has been set explicitly.
5643 */
5644 bool QQuickItem::heightValid() const
5645 {
5646     Q_D(const QQuickItem);
5647     return d->heightValid;
5648 }
5649
5650 /*!
5651     \internal
5652   */
5653 void QQuickItem::setSize(const QSizeF &size)
5654 {
5655     Q_D(QQuickItem);
5656     d->heightValid = true;
5657     d->widthValid = true;
5658
5659     if (QSizeF(d->width, d->height) == size)
5660         return;
5661
5662     qreal oldHeight = d->height;
5663     qreal oldWidth = d->width;
5664     d->height = size.height();
5665     d->width = size.width();
5666
5667     d->dirty(QQuickItemPrivate::Size);
5668
5669     geometryChanged(QRectF(x(), y(), width(), height()),
5670                     QRectF(x(), y(), oldWidth, oldHeight));
5671 }
5672
5673 /*!
5674     \qmlproperty bool QtQuick2::Item::activeFocus
5675
5676     This read-only property indicates whether the item has active focus.
5677
5678     If activeFocus is true, either this item is the one that currently
5679     receives keyboard input, or it is a FocusScope ancestor of the item
5680     that currently receives keyboard input.
5681
5682     Usually, activeFocus is gained by setting \l focus on an item and its
5683     enclosing FocusScope objects. In the following example, the \c input
5684     and \c focusScope objects will have active focus, while the root
5685     rectangle object will not.
5686
5687     \qml
5688     import QtQuick 2.0
5689
5690     Rectangle {
5691         width: 100; height: 100
5692
5693         FocusScope {
5694             id: focusScope
5695             focus: true
5696
5697             TextInput {
5698                 id: input
5699                 focus: true
5700             }
5701         }
5702     }
5703     \endqml
5704
5705     \sa focus, {Keyboard Focus in Qt Quick}
5706 */
5707 /*!
5708     \property QQuickItem::activeFocus
5709
5710     This read-only property indicates whether the item has active focus.
5711
5712     If activeFocus is true, either this item is the one that currently
5713     receives keyboard input, or it is a FocusScope ancestor of the item
5714     that currently receives keyboard input.
5715
5716     Usually, activeFocus is gained by setting \l focus on an item and its
5717     enclosing FocusScope objects. In the following example, the \c input
5718     and \c focusScope objects will have active focus, while the root
5719     rectangle object will not.
5720
5721     \qml
5722     import QtQuick 2.0
5723
5724     Rectangle {
5725         width: 100; height: 100
5726
5727         FocusScope {
5728             focus: true
5729
5730             TextInput {
5731                 id: input
5732                 focus: true
5733             }
5734         }
5735     }
5736     \endqml
5737
5738     \sa focus, {Keyboard Focus in Qt Quick}
5739 */
5740 bool QQuickItem::hasActiveFocus() const
5741 {
5742     Q_D(const QQuickItem);
5743     return d->activeFocus;
5744 }
5745
5746 /*!
5747     \qmlproperty bool QtQuick2::Item::focus
5748
5749     This property holds whether the item has focus within the enclosing
5750     FocusScope. If true, this item will gain active focus when the
5751     enclosing FocusScope gains active focus.
5752
5753     In the following example, \c input will be given active focus when
5754     \c scope gains active focus:
5755
5756     \qml
5757     import QtQuick 2.0
5758
5759     Rectangle {
5760         width: 100; height: 100
5761
5762         FocusScope {
5763             id: scope
5764
5765             TextInput {
5766                 id: input
5767                 focus: true
5768             }
5769         }
5770     }
5771     \endqml
5772
5773     For the purposes of this property, the scene as a whole is assumed
5774     to act like a focus scope. On a practical level, that means the
5775     following QML will give active focus to \c input on startup.
5776
5777     \qml
5778     Rectangle {
5779         width: 100; height: 100
5780
5781         TextInput {
5782               id: input
5783               focus: true
5784         }
5785     }
5786     \endqml
5787
5788     \sa activeFocus, {Keyboard Focus in Qt Quick}
5789 */
5790 /*!
5791     \property QQuickItem::focus
5792
5793     This property holds whether the item has focus within the enclosing
5794     FocusScope. If true, this item will gain active focus when the
5795     enclosing FocusScope gains active focus.
5796
5797     In the following example, \c input will be given active focus when
5798     \c scope gains active focus:
5799
5800     \qml
5801     import QtQuick 2.0
5802
5803     Rectangle {
5804         width: 100; height: 100
5805
5806         FocusScope {
5807             id: scope
5808
5809             TextInput {
5810                 id: input
5811                 focus: true
5812             }
5813         }
5814     }
5815     \endqml
5816
5817     For the purposes of this property, the scene as a whole is assumed
5818     to act like a focus scope. On a practical level, that means the
5819     following QML will give active focus to \c input on startup.
5820
5821     \qml
5822     Rectangle {
5823         width: 100; height: 100
5824
5825         TextInput {
5826               id: input
5827               focus: true
5828         }
5829     }
5830     \endqml
5831
5832     \sa activeFocus, {Keyboard Focus in Qt Quick}
5833 */
5834 bool QQuickItem::hasFocus() const
5835 {
5836     Q_D(const QQuickItem);
5837     return d->focus;
5838 }
5839
5840 void QQuickItem::setFocus(bool focus)
5841 {
5842     Q_D(QQuickItem);
5843     if (d->focus == focus)
5844         return;
5845
5846     if (d->window || d->parentItem) {
5847         // Need to find our nearest focus scope
5848         QQuickItem *scope = parentItem();
5849         while (scope && !scope->isFocusScope() && scope->parentItem())
5850             scope = scope->parentItem();
5851         if (d->window) {
5852             if (focus)
5853                 QQuickWindowPrivate::get(d->window)->setFocusInScope(scope, this);
5854             else
5855                 QQuickWindowPrivate::get(d->window)->clearFocusInScope(scope, this);
5856         } else {
5857             // do the focus changes from setFocusInScope/clearFocusInScope that are
5858             // unrelated to a window
5859             QVarLengthArray<QQuickItem *, 20> changed;
5860             QQuickItem *oldSubFocusItem = QQuickItemPrivate::get(scope)->subFocusItem;
5861             if (oldSubFocusItem) {
5862                 QQuickItemPrivate::get(oldSubFocusItem)->updateSubFocusItem(scope, false);
5863                 QQuickItemPrivate::get(oldSubFocusItem)->focus = false;
5864                 changed << oldSubFocusItem;
5865             } else if (!scope->isFocusScope() && scope->hasFocus()) {
5866                 QQuickItemPrivate::get(scope)->focus = false;
5867                 changed << scope;
5868             }
5869             d->updateSubFocusItem(scope, focus);
5870
5871             d->focus = focus;
5872             changed << this;
5873             emit focusChanged(focus);
5874
5875             QQuickWindowPrivate::notifyFocusChangesRecur(changed.data(), changed.count() - 1);
5876         }
5877     } else {
5878         QVarLengthArray<QQuickItem *, 20> changed;
5879         QQuickItem *oldSubFocusItem = d->subFocusItem;
5880         if (!isFocusScope() && oldSubFocusItem) {
5881             QQuickItemPrivate::get(oldSubFocusItem)->updateSubFocusItem(this, false);
5882             QQuickItemPrivate::get(oldSubFocusItem)->focus = false;
5883             changed << oldSubFocusItem;
5884         }
5885
5886         d->focus = focus;
5887         changed << this;
5888         emit focusChanged(focus);
5889
5890         QQuickWindowPrivate::notifyFocusChangesRecur(changed.data(), changed.count() - 1);
5891     }
5892 }
5893
5894 /*!
5895     Returns true if this item is a focus scope, and false otherwise.
5896   */
5897 bool QQuickItem::isFocusScope() const
5898 {
5899     return flags() & ItemIsFocusScope;
5900 }
5901
5902 /*!
5903     If this item is a focus scope, this returns the item in its focus chain
5904     that currently has focus.
5905
5906     Returns 0 if this item is not a focus scope.
5907   */
5908 QQuickItem *QQuickItem::scopedFocusItem() const
5909 {
5910     Q_D(const QQuickItem);
5911     if (!isFocusScope())
5912         return 0;
5913     else
5914         return d->subFocusItem;
5915 }
5916
5917 /*!
5918     Returns the mouse buttons accepted by this item.
5919
5920     The default value is Qt::NoButton; that is, no mouse buttons are accepted.
5921
5922     If an item does not accept the mouse button for a particular mouse event,
5923     the mouse event will not be delivered to the item and will be delivered
5924     to the next item in the item hierarchy instead.
5925   */
5926 Qt::MouseButtons QQuickItem::acceptedMouseButtons() const
5927 {
5928     Q_D(const QQuickItem);
5929     return d->acceptedMouseButtons();
5930 }
5931
5932 /*!
5933     Sets the mouse buttons accepted by this item to \a buttons.
5934   */
5935 void QQuickItem::setAcceptedMouseButtons(Qt::MouseButtons buttons)
5936 {
5937     Q_D(QQuickItem);
5938     if (buttons & Qt::LeftButton)
5939         d->extra.setFlag();
5940     else
5941         d->extra.clearFlag();
5942
5943     buttons &= ~Qt::LeftButton;
5944     if (buttons || d->extra.isAllocated())
5945         d->extra.value().acceptedMouseButtons = buttons;
5946 }
5947
5948 /*!
5949     Returns whether mouse events of this item's children should be filtered
5950     through this item.
5951
5952     \sa setFiltersChildMouseEvents(), childMouseEventFilter()
5953   */
5954 bool QQuickItem::filtersChildMouseEvents() const
5955 {
5956     Q_D(const QQuickItem);
5957     return d->filtersChildMouseEvents;
5958 }
5959
5960 /*!
5961     Sets whether mouse events of this item's children should be filtered
5962     through this item.
5963
5964     If \a filter is true, childMouseEventFilter() will be called when
5965     a mouse event is triggered for a child item.
5966
5967     \sa filtersChildMouseEvents()
5968   */
5969 void QQuickItem::setFiltersChildMouseEvents(bool filter)
5970 {
5971     Q_D(QQuickItem);
5972     d->filtersChildMouseEvents = filter;
5973 }
5974
5975 /*!
5976     \internal
5977   */
5978 bool QQuickItem::isUnderMouse() const
5979 {
5980     Q_D(const QQuickItem);
5981     if (!d->window)
5982         return false;
5983
5984     QPointF cursorPos = QGuiApplicationPrivate::lastCursorPosition;
5985     return contains(mapFromScene(d->window->mapFromGlobal(cursorPos.toPoint())));
5986 }
5987
5988 /*!
5989     Returns whether hover events are accepted by this item.
5990
5991     The default value is false.
5992
5993     If this is false, then the item will not receive any hover events through
5994     the hoverEnterEvent(), hoverMoveEvent() and hoverLeaveEvent() functions.
5995 */
5996 bool QQuickItem::acceptHoverEvents() const
5997 {
5998     Q_D(const QQuickItem);
5999     return d->hoverEnabled;
6000 }
6001
6002 /*!
6003     If \a enabled is true, this sets the item to accept hover events;
6004     otherwise, hover events are not accepted by this item.
6005
6006     \sa acceptHoverEvents()
6007 */
6008 void QQuickItem::setAcceptHoverEvents(bool enabled)
6009 {
6010     Q_D(QQuickItem);
6011     d->hoverEnabled = enabled;
6012 }
6013
6014 #ifndef QT_NO_CURSOR
6015
6016
6017 /*!
6018     Returns the cursor shape for this item.
6019
6020     The mouse cursor will assume this shape when it is over this
6021     item, unless an override cursor is set.
6022     See the \l{Qt::CursorShape}{list of predefined cursor objects} for a
6023     range of useful shapes.
6024
6025     If no cursor shape has been set this returns a cursor with the Qt::ArrowCursor shape, however
6026     another cursor shape may be displayed if an overlapping item has a valid cursor.
6027
6028     \sa setCursor(), unsetCursor()
6029 */
6030
6031 QCursor QQuickItem::cursor() const
6032 {
6033     Q_D(const QQuickItem);
6034     return d->extra.isAllocated()
6035             ? d->extra->cursor
6036             : QCursor();
6037 }
6038
6039 /*!
6040     Sets the \a cursor shape for this item.
6041
6042     \sa cursor(), unsetCursor()
6043 */
6044
6045 void QQuickItem::setCursor(const QCursor &cursor)
6046 {
6047     Q_D(QQuickItem);
6048
6049     Qt::CursorShape oldShape = d->extra.isAllocated() ? d->extra->cursor.shape() : Qt::ArrowCursor;
6050
6051     if (oldShape != cursor.shape() || oldShape >= Qt::LastCursor || cursor.shape() >= Qt::LastCursor) {
6052         d->extra.value().cursor = cursor;
6053         if (d->window) {
6054             QQuickWindowPrivate *windowPrivate = QQuickWindowPrivate::get(d->window);
6055             if (windowPrivate->cursorItem == this)
6056                 d->window->setCursor(cursor);
6057         }
6058     }
6059
6060     if (!d->hasCursor) {
6061         d->hasCursor = true;
6062         if (d->window) {
6063             QPointF pos = d->window->mapFromGlobal(QGuiApplicationPrivate::lastCursorPosition.toPoint());
6064             if (contains(mapFromScene(pos)))
6065                 QQuickWindowPrivate::get(d->window)->updateCursor(pos);
6066         }
6067     }
6068 }
6069
6070 /*!
6071     Clears the cursor shape for this item.
6072
6073     \sa cursor(), setCursor()
6074 */
6075
6076 void QQuickItem::unsetCursor()
6077 {
6078     Q_D(QQuickItem);
6079     if (!d->hasCursor)
6080         return;
6081     d->hasCursor = false;
6082     if (d->extra.isAllocated())
6083         d->extra->cursor = QCursor();
6084
6085     if (d->window) {
6086         QQuickWindowPrivate *windowPrivate = QQuickWindowPrivate::get(d->window);
6087         if (windowPrivate->cursorItem == this) {
6088             QPointF pos = d->window->mapFromGlobal(QGuiApplicationPrivate::lastCursorPosition.toPoint());
6089             windowPrivate->updateCursor(pos);
6090         }
6091     }
6092 }
6093
6094 #endif
6095
6096 /*!
6097     Grabs the mouse input.
6098
6099     This item will receive all mouse events until ungrabMouse() is called.
6100
6101     \warning This function should be used with caution.
6102   */
6103 void QQuickItem::grabMouse()
6104 {
6105     Q_D(QQuickItem);
6106     if (!d->window)
6107         return;
6108     QQuickWindowPrivate *windowPriv = QQuickWindowPrivate::get(d->window);
6109     if (windowPriv->mouseGrabberItem == this)
6110         return;
6111
6112     QQuickItem *oldGrabber = windowPriv->mouseGrabberItem;
6113     windowPriv->mouseGrabberItem = this;
6114     if (oldGrabber) {
6115         QEvent ev(QEvent::UngrabMouse);
6116         d->window->sendEvent(oldGrabber, &ev);
6117     }
6118 }
6119
6120 /*!
6121     Releases the mouse grab following a call to grabMouse().
6122 */
6123 void QQuickItem::ungrabMouse()
6124 {
6125     Q_D(QQuickItem);
6126     if (!d->window)
6127         return;
6128     QQuickWindowPrivate *windowPriv = QQuickWindowPrivate::get(d->window);
6129     if (windowPriv->mouseGrabberItem != this) {
6130         qWarning("QQuickItem::ungrabMouse(): Item is not the mouse grabber.");
6131         return;
6132     }
6133
6134     windowPriv->mouseGrabberItem = 0;
6135
6136     QEvent ev(QEvent::UngrabMouse);
6137     d->window->sendEvent(this, &ev);
6138 }
6139
6140
6141 /*!
6142     Returns whether mouse input should exclusively remain with this item.
6143
6144     \sa setKeepMouseGrab()
6145  */
6146 bool QQuickItem::keepMouseGrab() const
6147 {
6148     Q_D(const QQuickItem);
6149     return d->keepMouse;
6150 }
6151
6152 /*!
6153   Sets whether the mouse input should remain exclusively with this item.
6154
6155   This is useful for items that wish to grab and keep mouse
6156   interaction following a predefined gesture.  For example,
6157   an item that is interested in horizontal mouse movement
6158   may set keepMouseGrab to true once a threshold has been
6159   exceeded.  Once keepMouseGrab has been set to true, filtering
6160   items will not react to mouse events.
6161
6162   If \a keep is false, a filtering item may steal the grab. For example,
6163   \l Flickable may attempt to steal a mouse grab if it detects that the
6164   user has begun to move the viewport.
6165
6166   \sa keepMouseGrab()
6167  */
6168 void QQuickItem::setKeepMouseGrab(bool keep)
6169 {
6170     Q_D(QQuickItem);
6171     d->keepMouse = keep;
6172 }
6173
6174 /*!
6175     Grabs the touch points specified by \a ids.
6176
6177     These touch points will be owned by the item until
6178     they are released. Alternatively, the grab can be stolen
6179     by a filtering item like Flickable. Use setKeepTouchGrab()
6180     to prevent the grab from being stolen.
6181
6182     \sa ungrabTouchPoints(), setKeepTouchGrab()
6183 */
6184 void QQuickItem::grabTouchPoints(const QVector<int> &ids)
6185 {
6186     Q_D(QQuickItem);
6187     if (!d->window)
6188         return;
6189     QQuickWindowPrivate *windowPriv = QQuickWindowPrivate::get(d->window);
6190
6191     QSet<QQuickItem*> ungrab;
6192     for (int i = 0; i < ids.count(); ++i) {
6193         QQuickItem *oldGrabber = windowPriv->itemForTouchPointId.value(ids.at(i));
6194         if (oldGrabber == this)
6195             return;
6196
6197         windowPriv->itemForTouchPointId[ids.at(i)] = this;
6198         if (oldGrabber)
6199             ungrab.insert(oldGrabber);
6200     }
6201     foreach (QQuickItem *oldGrabber, ungrab)
6202         oldGrabber->touchUngrabEvent();
6203 }
6204
6205 /*!
6206     Ungrabs the touch points owned by this item.
6207
6208     \sa grabTouchPoints()
6209 */
6210 void QQuickItem::ungrabTouchPoints()
6211 {
6212     Q_D(QQuickItem);
6213     if (!d->window)
6214         return;
6215     QQuickWindowPrivate *windowPriv = QQuickWindowPrivate::get(d->window);
6216
6217     QMutableHashIterator<int, QQuickItem*> i(windowPriv->itemForTouchPointId);
6218     while (i.hasNext()) {
6219         i.next();
6220         if (i.value() == this)
6221             i.remove();
6222     }
6223     touchUngrabEvent();
6224 }
6225
6226 /*!
6227     Returns whether the touch points grabbed by this item should exclusively
6228     remain with this item.
6229
6230     \sa setKeepTouchGrab(), keepMouseGrab()
6231 */
6232 bool QQuickItem::keepTouchGrab() const
6233 {
6234     Q_D(const QQuickItem);
6235     return d->keepTouch;
6236 }
6237
6238 /*!
6239   Sets whether the touch points grabbed by this item should remain
6240   exclusively with this item.
6241
6242   This is useful for items that wish to grab and keep specific touch
6243   points following a predefined gesture.  For example,
6244   an item that is interested in horizontal touch point movement
6245   may set setKeepTouchGrab to true once a threshold has been
6246   exceeded.  Once setKeepTouchGrab has been set to true, filtering
6247   items will not react to the relevant touch points.
6248
6249   If \a keep is false, a filtering item may steal the grab. For example,
6250   \l Flickable may attempt to steal a touch point grab if it detects that the
6251   user has begun to move the viewport.
6252
6253   \sa keepTouchGrab(), setKeepMouseGrab()
6254  */
6255 void QQuickItem::setKeepTouchGrab(bool keep)
6256 {
6257     Q_D(QQuickItem);
6258     d->keepTouch = keep;
6259 }
6260
6261 /*!
6262   Returns true if this item contains \a point, which is in local coordinates;
6263   returns false otherwise.
6264
6265   This function can be overwritten in order to handle point collisions in items
6266   with custom shapes. The default implementation checks if the point is inside
6267   the item's bounding rect.
6268
6269   Note that this method is generally used to check whether the item is under the mouse cursor,
6270   and for that reason, the implementation of this function should be as light-weight
6271   as possible.
6272 */
6273 bool QQuickItem::contains(const QPointF &point) const
6274 {
6275     Q_D(const QQuickItem);
6276     return QRectF(0, 0, d->width, d->height).contains(point);
6277 }
6278
6279 /*!
6280     Maps the given \a point in this item's coordinate system to the equivalent
6281     point within \a item's coordinate system, and returns the mapped
6282     coordinate.
6283
6284     If \a item is 0, this maps \a point to the coordinate system of the
6285     scene.
6286
6287     \sa {Concepts - Visual Coordinates in Qt Quick}
6288 */
6289 QPointF QQuickItem::mapToItem(const QQuickItem *item, const QPointF &point) const
6290 {
6291     QPointF p = mapToScene(point);
6292     if (item)
6293         p = item->mapFromScene(p);
6294     return p;
6295 }
6296
6297 /*!
6298     Maps the given \a point in this item's coordinate system to the equivalent
6299     point within the scene's coordinate system, and returns the mapped
6300     coordinate.
6301
6302     \sa {Concepts - Visual Coordinates in Qt Quick}
6303 */
6304 QPointF QQuickItem::mapToScene(const QPointF &point) const
6305 {
6306     Q_D(const QQuickItem);
6307     return d->itemToWindowTransform().map(point);
6308 }
6309
6310 /*!
6311     Maps the given \a rect in this item's coordinate system to the equivalent
6312     rectangular area within \a item's coordinate system, and returns the mapped
6313     rectangle value.
6314
6315     If \a item is 0, this maps \a rect to the coordinate system of the
6316     scene.
6317
6318     \sa {Concepts - Visual Coordinates in Qt Quick}
6319 */
6320 QRectF QQuickItem::mapRectToItem(const QQuickItem *item, const QRectF &rect) const
6321 {
6322     Q_D(const QQuickItem);
6323     QTransform t = d->itemToWindowTransform();
6324     if (item)
6325         t *= QQuickItemPrivate::get(item)->windowToItemTransform();
6326     return t.mapRect(rect);
6327 }
6328
6329 /*!
6330     Maps the given \a rect in this item's coordinate system to the equivalent
6331     rectangular area within the scene's coordinate system, and returns the mapped
6332     rectangle value.
6333
6334     \sa {Concepts - Visual Coordinates in Qt Quick}
6335 */
6336 QRectF QQuickItem::mapRectToScene(const QRectF &rect) const
6337 {
6338     Q_D(const QQuickItem);
6339     return d->itemToWindowTransform().mapRect(rect);
6340 }
6341
6342 /*!
6343     Maps the given \a point in \a item's coordinate system to the equivalent
6344     point within this item's coordinate system, and returns the mapped
6345     coordinate.
6346
6347     If \a item is 0, this maps \a point from the coordinate system of the
6348     scene.
6349
6350     \sa {Concepts - Visual Coordinates in Qt Quick}
6351 */
6352 QPointF QQuickItem::mapFromItem(const QQuickItem *item, const QPointF &point) const
6353 {
6354     QPointF p = item?item->mapToScene(point):point;
6355     return mapFromScene(p);
6356 }
6357
6358 /*!
6359     Maps the given \a point in the scene's coordinate system to the equivalent
6360     point within this item's coordinate system, and returns the mapped
6361     coordinate.
6362
6363     \sa {Concepts - Visual Coordinates in Qt Quick}
6364 */
6365 QPointF QQuickItem::mapFromScene(const QPointF &point) const
6366 {
6367     Q_D(const QQuickItem);
6368     return d->windowToItemTransform().map(point);
6369 }
6370
6371 /*!
6372     Maps the given \a rect in \a item's coordinate system to the equivalent
6373     rectangular area within this item's coordinate system, and returns the mapped
6374     rectangle value.
6375
6376     If \a item is 0, this maps \a rect from the coordinate system of the
6377     scene.
6378
6379     \sa {Concepts - Visual Coordinates in Qt Quick}
6380 */
6381 QRectF QQuickItem::mapRectFromItem(const QQuickItem *item, const QRectF &rect) const
6382 {
6383     Q_D(const QQuickItem);
6384     QTransform t = item?QQuickItemPrivate::get(item)->itemToWindowTransform():QTransform();
6385     t *= d->windowToItemTransform();
6386     return t.mapRect(rect);
6387 }
6388
6389 /*!
6390     Maps the given \a rect in the scene's coordinate system to the equivalent
6391     rectangular area within this item's coordinate system, and returns the mapped
6392     rectangle value.
6393
6394     \sa {Concepts - Visual Coordinates in Qt Quick}
6395 */
6396 QRectF QQuickItem::mapRectFromScene(const QRectF &rect) const
6397 {
6398     Q_D(const QQuickItem);
6399     return d->windowToItemTransform().mapRect(rect);
6400 }
6401
6402 /*!
6403   \property QQuickItem::anchors
6404   \internal
6405 */
6406
6407 /*!
6408   \property QQuickItem::left
6409   \internal
6410 */
6411
6412 /*!
6413   \property QQuickItem::right
6414   \internal
6415 */
6416
6417 /*!
6418   \property QQuickItem::horizontalCenter
6419   \internal
6420 */
6421
6422 /*!
6423   \property QQuickItem::top
6424   \internal
6425 */
6426
6427 /*!
6428   \property QQuickItem::bottom
6429   \internal
6430 */
6431
6432 /*!
6433   \property QQuickItem::verticalCenter
6434   \internal
6435 */
6436
6437 /*!
6438   \property QQuickItem::baseline
6439   \internal
6440 */
6441
6442 /*!
6443   \property QQuickItem::data
6444   \internal
6445 */
6446
6447 /*!
6448   \property QQuickItem::resources
6449   \internal
6450 */
6451
6452 /*!
6453   \reimp
6454   */
6455 bool QQuickItem::event(QEvent *ev)
6456 {
6457 #if 0
6458     if (ev->type() == QEvent::PolishRequest) {
6459         Q_D(QQuickItem);
6460         d->polishScheduled = false;
6461         updatePolish();
6462         return true;
6463     } else {
6464         return QObject::event(ev);
6465     }
6466 #endif
6467     if (ev->type() == QEvent::InputMethodQuery) {
6468         QInputMethodQueryEvent *query = static_cast<QInputMethodQueryEvent *>(ev);
6469         Qt::InputMethodQueries queries = query->queries();
6470         for (uint i = 0; i < 32; ++i) {
6471             Qt::InputMethodQuery q = (Qt::InputMethodQuery)(int)(queries & (1<<i));
6472             if (q) {
6473                 QVariant v = inputMethodQuery(q);
6474                 query->setValue(q, v);
6475             }
6476         }
6477         query->accept();
6478         return true;
6479     } else if (ev->type() == QEvent::InputMethod) {
6480         inputMethodEvent(static_cast<QInputMethodEvent *>(ev));
6481         return true;
6482     }
6483     return QObject::event(ev);
6484 }
6485
6486 #ifndef QT_NO_DEBUG_STREAM
6487 QDebug operator<<(QDebug debug, QQuickItem *item)
6488 {
6489     if (!item) {
6490         debug << "QQuickItem(0)";
6491         return debug;
6492     }
6493
6494     debug << item->metaObject()->className() << "(this =" << ((void*)item)
6495           << ", name=" << item->objectName()
6496           << ", parent =" << ((void*)item->parentItem())
6497           << ", geometry =" << QRectF(item->pos(), QSizeF(item->width(), item->height()))
6498           << ", z =" << item->z() << ')';
6499     return debug;
6500 }
6501 #endif
6502
6503 qint64 QQuickItemPrivate::consistentTime = -1;
6504 void QQuickItemPrivate::setConsistentTime(qint64 t)
6505 {
6506     consistentTime = t;
6507 }
6508
6509 class QElapsedTimerConsistentTimeHack
6510 {
6511 public:
6512     void start() {
6513         t1 = QQuickItemPrivate::consistentTime;
6514         t2 = 0;
6515     }
6516     qint64 elapsed() {
6517         return QQuickItemPrivate::consistentTime - t1;
6518     }
6519     qint64 restart() {
6520         qint64 val = QQuickItemPrivate::consistentTime - t1;
6521         t1 = QQuickItemPrivate::consistentTime;
6522         t2 = 0;
6523         return val;
6524     }
6525
6526 private:
6527     qint64 t1;
6528     qint64 t2;
6529 };
6530
6531 void QQuickItemPrivate::start(QElapsedTimer &t)
6532 {
6533     if (QQuickItemPrivate::consistentTime == -1)
6534         t.start();
6535     else
6536         ((QElapsedTimerConsistentTimeHack*)&t)->start();
6537 }
6538
6539 qint64 QQuickItemPrivate::elapsed(QElapsedTimer &t)
6540 {
6541     if (QQuickItemPrivate::consistentTime == -1)
6542         return t.elapsed();
6543     else
6544         return ((QElapsedTimerConsistentTimeHack*)&t)->elapsed();
6545 }
6546
6547 qint64 QQuickItemPrivate::restart(QElapsedTimer &t)
6548 {
6549     if (QQuickItemPrivate::consistentTime == -1)
6550         return t.restart();
6551     else
6552         return ((QElapsedTimerConsistentTimeHack*)&t)->restart();
6553 }
6554
6555 /*!
6556     \fn bool QQuickItem::isTextureProvider() const
6557
6558     Returns true if this item is a texture provider. The default
6559     implementation returns false.
6560
6561     This function can be called from any thread.
6562  */
6563
6564 bool QQuickItem::isTextureProvider() const
6565 {
6566     Q_D(const QQuickItem);
6567     return d->extra.isAllocated() && d->extra->layer && d->extra->layer->effectSource() ?
6568            d->extra->layer->effectSource()->isTextureProvider() : false;
6569 }
6570
6571 /*!
6572     \fn QSGTextureProvider *QQuickItem::textureProvider() const
6573
6574     Returns the texture provider for an item. The default implementation
6575     returns 0.
6576
6577     This function may only be called on the rendering thread.
6578  */
6579
6580 QSGTextureProvider *QQuickItem::textureProvider() const
6581 {
6582     Q_D(const QQuickItem);
6583     return d->extra.isAllocated() && d->extra->layer && d->extra->layer->effectSource() ?
6584            d->extra->layer->effectSource()->textureProvider() : 0;
6585 }
6586
6587 /*!
6588     \property QQuickItem::layer
6589     \internal
6590   */
6591 QQuickItemLayer *QQuickItemPrivate::layer() const
6592 {
6593     if (!extra.isAllocated() || !extra->layer) {
6594         extra.value().layer = new QQuickItemLayer(const_cast<QQuickItem *>(q_func()));
6595         if (!componentComplete)
6596             extra->layer->classBegin();
6597     }
6598     return extra->layer;
6599 }
6600
6601 QQuickItemLayer::QQuickItemLayer(QQuickItem *item)
6602     : m_item(item)
6603     , m_enabled(false)
6604     , m_mipmap(false)
6605     , m_smooth(false)
6606     , m_componentComplete(true)
6607     , m_wrapMode(QQuickShaderEffectSource::ClampToEdge)
6608     , m_format(QQuickShaderEffectSource::RGBA)
6609     , m_name("source")
6610     , m_effectComponent(0)
6611     , m_effect(0)
6612     , m_effectSource(0)
6613 {
6614 }
6615
6616 QQuickItemLayer::~QQuickItemLayer()
6617 {
6618     delete m_effectSource;
6619     delete m_effect;
6620 }
6621
6622 /*!
6623     \qmlproperty bool QtQuick2::Item::layer.enabled
6624
6625     Holds whether the item is layered or not. Layering is disabled by default.
6626
6627     A layered item is rendered into an offscreen surface and cached until
6628     it is changed. Enabling layering for complex QML item hierarchies can
6629     sometimes be an optimization.
6630
6631     None of the other layer properties have any effect when the layer
6632     is disabled.
6633  */
6634 void QQuickItemLayer::setEnabled(bool e)
6635 {
6636     if (e == m_enabled)
6637         return;
6638     m_enabled = e;
6639     if (m_componentComplete) {
6640         if (m_enabled)
6641             activate();
6642         else
6643             deactivate();
6644     }
6645
6646     emit enabledChanged(e);
6647 }
6648
6649 void QQuickItemLayer::classBegin()
6650 {
6651     Q_ASSERT(!m_effectSource);
6652     Q_ASSERT(!m_effect);
6653     m_componentComplete = false;
6654 }
6655
6656 void QQuickItemLayer::componentComplete()
6657 {
6658     Q_ASSERT(!m_componentComplete);
6659     m_componentComplete = true;
6660     if (m_enabled)
6661         activate();
6662 }
6663
6664 void QQuickItemLayer::activate()
6665 {
6666     Q_ASSERT(!m_effectSource);
6667     m_effectSource = new QQuickShaderEffectSource();
6668
6669     QQuickItem *parentItem = m_item->parentItem();
6670     if (parentItem) {
6671         m_effectSource->setParentItem(parentItem);
6672         m_effectSource->stackAfter(m_item);
6673     }
6674
6675     m_effectSource->setSourceItem(m_item);
6676     m_effectSource->setHideSource(true);
6677     m_effectSource->setSmooth(m_smooth);
6678     m_effectSource->setTextureSize(m_size);
6679     m_effectSource->setSourceRect(m_sourceRect);
6680     m_effectSource->setMipmap(m_mipmap);
6681     m_effectSource->setWrapMode(m_wrapMode);
6682     m_effectSource->setFormat(m_format);
6683
6684     if (m_effectComponent)
6685         activateEffect();
6686
6687     m_effectSource->setVisible(m_item->isVisible() && !m_effect);
6688
6689     updateZ();
6690     updateGeometry();
6691     updateOpacity();
6692     updateMatrix();
6693
6694     QQuickItemPrivate *id = QQuickItemPrivate::get(m_item);
6695     id->addItemChangeListener(this, QQuickItemPrivate::Geometry | QQuickItemPrivate::Opacity | QQuickItemPrivate::Parent | QQuickItemPrivate::Visibility | QQuickItemPrivate::SiblingOrder);
6696 }
6697
6698 void QQuickItemLayer::deactivate()
6699 {
6700     Q_ASSERT(m_effectSource);
6701
6702     if (m_effectComponent)
6703         deactivateEffect();
6704
6705     delete m_effectSource;
6706     m_effectSource = 0;
6707
6708     QQuickItemPrivate *id = QQuickItemPrivate::get(m_item);
6709     id->removeItemChangeListener(this,  QQuickItemPrivate::Geometry | QQuickItemPrivate::Opacity | QQuickItemPrivate::Parent | QQuickItemPrivate::Visibility | QQuickItemPrivate::SiblingOrder);
6710 }
6711
6712 void QQuickItemLayer::activateEffect()
6713 {
6714     Q_ASSERT(m_effectSource);
6715     Q_ASSERT(m_effectComponent);
6716     Q_ASSERT(!m_effect);
6717
6718     QObject *created = m_effectComponent->beginCreate(m_effectComponent->creationContext());
6719     m_effect = qobject_cast<QQuickItem *>(created);
6720     if (!m_effect) {
6721         qWarning("Item: layer.effect is not a QML Item.");
6722         m_effectComponent->completeCreate();
6723         delete created;
6724         return;
6725     }
6726     QQuickItem *parentItem = m_item->parentItem();
6727     if (parentItem) {
6728         m_effect->setParentItem(parentItem);
6729         m_effect->stackAfter(m_effectSource);
6730     }
6731     m_effect->setVisible(m_item->isVisible());
6732     m_effect->setProperty(m_name, qVariantFromValue<QObject *>(m_effectSource));
6733     m_effectComponent->completeCreate();
6734 }
6735
6736 void QQuickItemLayer::deactivateEffect()
6737 {
6738     Q_ASSERT(m_effectSource);
6739     Q_ASSERT(m_effectComponent);
6740
6741     delete m_effect;
6742     m_effect = 0;
6743 }
6744
6745
6746 /*!
6747     \qmlproperty Component QtQuick2::Item::layer.effect
6748
6749     Holds the effect that is applied to this layer.
6750
6751     The effect is typically a \l ShaderEffect component, although any \l Item component can be
6752     assigned. The effect should have a source texture property with a name matching \l layer.samplerName.
6753
6754     \sa layer.samplerName
6755  */
6756
6757 void QQuickItemLayer::setEffect(QQmlComponent *component)
6758 {
6759     if (component == m_effectComponent)
6760         return;
6761
6762     bool updateNeeded = false;
6763     if (m_effectSource && m_effectComponent) {
6764         deactivateEffect();
6765         updateNeeded = true;
6766     }
6767
6768     m_effectComponent = component;
6769
6770     if (m_effectSource && m_effectComponent) {
6771         activateEffect();
6772         updateNeeded = true;
6773     }
6774
6775     if (updateNeeded) {
6776         updateZ();
6777         updateGeometry();
6778         updateOpacity();
6779         updateMatrix();
6780         m_effectSource->setVisible(m_item->isVisible() && !m_effect);
6781     }
6782
6783     emit effectChanged(component);
6784 }
6785
6786
6787 /*!
6788     \qmlproperty bool QtQuick2::Item::layer.mipmap
6789
6790     If this property is true, mipmaps are generated for the texture.
6791
6792     \note Some OpenGL ES 2 implementations do not support mipmapping of
6793     non-power-of-two textures.
6794  */
6795
6796 void QQuickItemLayer::setMipmap(bool mipmap)
6797 {
6798     if (mipmap == m_mipmap)
6799         return;
6800     m_mipmap = mipmap;
6801
6802     if (m_effectSource)
6803         m_effectSource->setMipmap(m_mipmap);
6804
6805     emit mipmapChanged(mipmap);
6806 }
6807
6808
6809 /*!
6810     \qmlproperty enumeration QtQuick2::Item::layer.format
6811
6812     This property defines the internal OpenGL format of the texture.
6813     Modifying this property makes most sense when the \a layer.effect is also
6814     specified. Depending on the OpenGL implementation, this property might
6815     allow you to save some texture memory.
6816
6817     \list
6818     \li ShaderEffectSource.Alpha - GL_ALPHA
6819     \li ShaderEffectSource.RGB - GL_RGB
6820     \li ShaderEffectSource.RGBA - GL_RGBA
6821     \endlist
6822
6823     \note Some OpenGL implementations do not support the GL_ALPHA format.
6824  */
6825
6826 void QQuickItemLayer::setFormat(QQuickShaderEffectSource::Format f)
6827 {
6828     if (f == m_format)
6829         return;
6830     m_format = f;
6831
6832     if (m_effectSource)
6833         m_effectSource->setFormat(m_format);
6834
6835     emit formatChanged(m_format);
6836 }
6837
6838
6839 /*!
6840     \qmlproperty enumeration QtQuick2::Item::layer.sourceRect
6841
6842     This property defines the rectangular area of the item that should be
6843     rendered into the texture. The source rectangle can be larger than
6844     the item itself. If the rectangle is null, which is the default,
6845     then the whole item is rendered to the texture.
6846  */
6847
6848 void QQuickItemLayer::setSourceRect(const QRectF &sourceRect)
6849 {
6850     if (sourceRect == m_sourceRect)
6851         return;
6852     m_sourceRect = sourceRect;
6853
6854     if (m_effectSource)
6855         m_effectSource->setSourceRect(m_sourceRect);
6856
6857     emit sourceRectChanged(sourceRect);
6858 }
6859
6860 /*!
6861     \qmlproperty bool QtQuick2::Item::layer.smooth
6862
6863     Holds whether the layer is smoothly transformed.
6864  */
6865
6866 void QQuickItemLayer::setSmooth(bool s)
6867 {
6868     if (m_smooth == s)
6869         return;
6870     m_smooth = s;
6871
6872     if (m_effectSource)
6873         m_effectSource->setSmooth(m_smooth);
6874
6875     emit smoothChanged(s);
6876 }
6877
6878 /*!
6879     \qmlproperty size QtQuick2::Item::layer.textureSize
6880
6881     This property holds the requested pixel size of the layers texture. If it is empty,
6882     which is the default, the size of the item is used.
6883
6884     \note Some platforms have a limit on how small framebuffer objects can be,
6885     which means the actual texture size might be larger than the requested
6886     size.
6887  */
6888
6889 void QQuickItemLayer::setSize(const QSize &size)
6890 {
6891     if (size == m_size)
6892         return;
6893     m_size = size;
6894
6895     if (m_effectSource)
6896         m_effectSource->setTextureSize(size);
6897
6898     emit sizeChanged(size);
6899 }
6900
6901 /*!
6902     \qmlproperty enumeration QtQuick2::Item::layer.wrapMode
6903
6904     This property defines the OpenGL wrap modes associated with the texture.
6905     Modifying this property makes most sense when the \a layer.effect is
6906     specified.
6907
6908     \list
6909     \li ShaderEffectSource.ClampToEdge - GL_CLAMP_TO_EDGE both horizontally and vertically
6910     \li ShaderEffectSource.RepeatHorizontally - GL_REPEAT horizontally, GL_CLAMP_TO_EDGE vertically
6911     \li ShaderEffectSource.RepeatVertically - GL_CLAMP_TO_EDGE horizontally, GL_REPEAT vertically
6912     \li ShaderEffectSource.Repeat - GL_REPEAT both horizontally and vertically
6913     \endlist
6914
6915     \note Some OpenGL ES 2 implementations do not support the GL_REPEAT
6916     wrap mode with non-power-of-two textures.
6917  */
6918
6919 void QQuickItemLayer::setWrapMode(QQuickShaderEffectSource::WrapMode mode)
6920 {
6921     if (mode == m_wrapMode)
6922         return;
6923     m_wrapMode = mode;
6924
6925     if (m_effectSource)
6926         m_effectSource->setWrapMode(m_wrapMode);
6927
6928     emit wrapModeChanged(mode);
6929 }
6930
6931 /*!
6932     \qmlproperty string QtQuick2::Item::layer.samplerName
6933
6934     Holds the name of the effect's source texture property.
6935
6936     This value must match the name of the effect's source texture property
6937     so that the Item can pass the layer's offscreen surface to the effect correctly.
6938
6939     \sa layer.effect, ShaderEffect
6940  */
6941
6942 void QQuickItemLayer::setName(const QByteArray &name) {
6943     if (m_name == name)
6944         return;
6945     if (m_effect) {
6946         m_effect->setProperty(m_name, QVariant());
6947         m_effect->setProperty(name, qVariantFromValue<QObject *>(m_effectSource));
6948     }
6949     m_name = name;
6950     emit nameChanged(name);
6951 }
6952
6953 void QQuickItemLayer::itemOpacityChanged(QQuickItem *item)
6954 {
6955     Q_UNUSED(item)
6956     updateOpacity();
6957 }
6958
6959 void QQuickItemLayer::itemGeometryChanged(QQuickItem *, const QRectF &, const QRectF &)
6960 {
6961     updateGeometry();
6962 }
6963
6964 void QQuickItemLayer::itemParentChanged(QQuickItem *item, QQuickItem *parent)
6965 {
6966     Q_UNUSED(item)
6967     Q_ASSERT(item == m_item);
6968     Q_ASSERT(parent != m_effectSource);
6969     Q_ASSERT(parent == 0 || parent != m_effect);
6970
6971     m_effectSource->setParentItem(parent);
6972     if (parent)
6973         m_effectSource->stackAfter(m_item);
6974
6975     if (m_effect) {
6976         m_effect->setParentItem(parent);
6977         if (parent)
6978             m_effect->stackAfter(m_effectSource);
6979     }
6980 }
6981
6982 void QQuickItemLayer::itemSiblingOrderChanged(QQuickItem *)
6983 {
6984     m_effectSource->stackAfter(m_item);
6985     if (m_effect)
6986         m_effect->stackAfter(m_effectSource);
6987 }
6988
6989 void QQuickItemLayer::itemVisibilityChanged(QQuickItem *)
6990 {
6991     QQuickItem *l = m_effect ? (QQuickItem *) m_effect : (QQuickItem *) m_effectSource;
6992     Q_ASSERT(l);
6993     l->setVisible(m_item->isVisible());
6994 }
6995
6996 void QQuickItemLayer::updateZ()
6997 {
6998     if (!m_componentComplete || !m_enabled)
6999         return;
7000     QQuickItem *l = m_effect ? (QQuickItem *) m_effect : (QQuickItem *) m_effectSource;
7001     Q_ASSERT(l);
7002     l->setZ(m_item->z());
7003 }
7004
7005 void QQuickItemLayer::updateOpacity()
7006 {
7007     QQuickItem *l = m_effect ? (QQuickItem *) m_effect : (QQuickItem *) m_effectSource;
7008     Q_ASSERT(l);
7009     l->setOpacity(m_item->opacity());
7010 }
7011
7012 void QQuickItemLayer::updateGeometry()
7013 {
7014     QQuickItem *l = m_effect ? (QQuickItem *) m_effect : (QQuickItem *) m_effectSource;
7015     Q_ASSERT(l);
7016     QRectF bounds = m_item->clipRect();
7017     l->setWidth(bounds.width());
7018     l->setHeight(bounds.height());
7019     l->setX(bounds.x() + m_item->x());
7020     l->setY(bounds.y() + m_item->y());
7021 }
7022
7023 void QQuickItemLayer::updateMatrix()
7024 {
7025     // Called directly from transformChanged(), so needs some extra
7026     // checks.
7027     if (!m_componentComplete || !m_enabled)
7028         return;
7029     QQuickItem *l = m_effect ? (QQuickItem *) m_effect : (QQuickItem *) m_effectSource;
7030     Q_ASSERT(l);
7031     QQuickItemPrivate *ld = QQuickItemPrivate::get(l);
7032     l->setScale(m_item->scale());
7033     l->setRotation(m_item->rotation());
7034     ld->transforms = QQuickItemPrivate::get(m_item)->transforms;
7035     if (ld->origin() != QQuickItemPrivate::get(m_item)->origin())
7036         ld->extra.value().origin = QQuickItemPrivate::get(m_item)->origin();
7037     ld->dirty(QQuickItemPrivate::Transform);
7038 }
7039
7040 QQuickItemPrivate::ExtraData::ExtraData()
7041 : z(0), scale(1), rotation(0), opacity(1),
7042   contents(0), screenAttached(0), layoutDirectionAttached(0),
7043   keyHandler(0), layer(0), effectRefCount(0), hideRefCount(0),
7044   opacityNode(0), clipNode(0), rootNode(0), beforePaintNode(0),
7045   acceptedMouseButtons(0), origin(QQuickItem::Center)
7046 {
7047 }
7048
7049 QT_END_NAMESPACE
7050
7051 #include <moc_qquickitem.cpp>