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