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