qquickitem.cpp 166 KB
Newer Older
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 9
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
10 11 12 13 14 15
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** 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 20
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
21 22 23 24 25 26 27 28 29 30 31
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
32 33 34 35 36
**
**
**
**
**
37
**
38 39 40 41
** $QT_END_LICENSE$
**
****************************************************************************/

42
#include "qquickitem.h"
43

44
#include "qquickcanvas.h"
45
#include <QtQml/qjsengine.h>
46
#include "qquickcanvas_p.h"
47

48
#include "qquickevents_p_p.h"
Alan Alpert's avatar
Alan Alpert committed
49
#include "qquickscreen_p.h"
50

51 52 53
#include <QtQml/qqmlengine.h>
#include <QtQml/qqmlcomponent.h>
#include <QtQml/qqmlinfo.h>
54
#include <QtGui/qpen.h>
55
#include <QtGui/qcursor.h>
56
#include <QtGui/qguiapplication.h>
57
#include <QtGui/qinputmethod.h>
58 59 60 61
#include <QtCore/qdebug.h>
#include <QtCore/qcoreevent.h>
#include <QtCore/qnumeric.h>

62 63 64 65 66
#include <private/qqmlglobal_p.h>
#include <private/qqmlengine_p.h>
#include <QtQuick/private/qquickstategroup_p.h>
#include <private/qqmlopenmetaobject_p.h>
#include <QtQuick/private/qquickstate_p.h>
67
#include <private/qlistmodelinterface_p.h>
68
#include <private/qquickitem_p.h>
69
#include <private/qqmlaccessors_p.h>
70
#include <QtQuick/private/qquickaccessibleattached_p.h>
71 72 73 74 75 76 77

#include <float.h>

// XXX todo Check that elements that create items handle memory correctly after visual ownership change

QT_BEGIN_NAMESPACE

78
static void QQuickItem_parentNotifier(QObject *o, intptr_t, QQmlNotifier **n)
79 80 81 82 83 84 85 86 87 88 89
{
    QQuickItemPrivate *d = QQuickItemPrivate::get(static_cast<QQuickItem *>(o));
    *n = &d->parentNotifier;
}

QML_PRIVATE_ACCESSOR(QQuickItem, QQuickItem *, parent, parentItem)
QML_PRIVATE_ACCESSOR(QQuickItem, qreal, x, x)
QML_PRIVATE_ACCESSOR(QQuickItem, qreal, y, y)
QML_PRIVATE_ACCESSOR(QQuickItem, qreal, width, width)
QML_PRIVATE_ACCESSOR(QQuickItem, qreal, height, height)

90 91 92 93 94
static QQmlAccessors QQuickItem_parent = { QQuickItem_parentRead, QQuickItem_parentNotifier };
static QQmlAccessors QQuickItem_x = { QQuickItem_xRead, 0 };
static QQmlAccessors QQuickItem_y = { QQuickItem_yRead, 0 };
static QQmlAccessors QQuickItem_width = { QQuickItem_widthRead, 0 };
static QQmlAccessors QQuickItem_height = { QQuickItem_heightRead, 0 };
95 96 97 98 99 100 101 102 103 104 105 106 107 108

QML_DECLARE_PROPERTIES(QQuickItem) {
    { QML_PROPERTY_NAME(parent), 0, &QQuickItem_parent },
    { QML_PROPERTY_NAME(x), 0, &QQuickItem_x },
    { QML_PROPERTY_NAME(y), 0, &QQuickItem_y },
    { QML_PROPERTY_NAME(width), 0, &QQuickItem_width },
    { QML_PROPERTY_NAME(height), 0, &QQuickItem_height }
};

void QQuickItemPrivate::registerAccessorProperties()
{
    QML_DEFINE_PROPERTIES(QQuickItem);
}

Alan Alpert's avatar
Alan Alpert committed
109
/*!
110
    \qmlclass Transform QQuickTransform
Alan Alpert's avatar
Alan Alpert committed
111 112 113 114 115 116 117 118
    \inqmlmodule QtQuick 2
    \ingroup qml-transform-elements
    \brief The Transform elements provide a way of building advanced transformations on Items.

    The Transform element is a base type which cannot be instantiated directly.
    The following concrete Transform types are available:

    \list
119 120 121
    \li \l Rotation
    \li \l Scale
    \li \l Translate
Alan Alpert's avatar
Alan Alpert committed
122 123 124 125 126 127 128 129 130 131
    \endlist

    The Transform elements let you create and control advanced transformations that can be configured
    independently using specialized properties.

    You can assign any number of Transform elements to an \l Item. Each Transform is applied in order,
    one at a time.
*/

/*!
132
    \qmlclass Translate QQuickTranslate
Alan Alpert's avatar
Alan Alpert committed
133 134 135 136 137 138 139 140 141
    \inqmlmodule QtQuick 2
    \ingroup qml-transform-elements
    \brief The Translate object provides a way to move an Item without changing its x or y properties.

    The Translate object provides independent control over position in addition to the Item's x and y properties.

    The following example moves the Y axis of the \l Rectangle elements while still allowing the \l Row element
    to lay the items out as if they had not been transformed:
    \qml
142
    import QtQuick 2.0
Alan Alpert's avatar
Alan Alpert committed
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173

    Row {
        Rectangle {
            width: 100; height: 100
            color: "blue"
            transform: Translate { y: 20 }
        }
        Rectangle {
            width: 100; height: 100
            color: "red"
            transform: Translate { y: -20 }
        }
    }
    \endqml

    \image translate.png
*/

/*!
    \qmlproperty real QtQuick2::Translate::x

    The translation along the X axis.
*/

/*!
    \qmlproperty real QtQuick2::Translate::y

    The translation along the Y axis.
*/

/*!
174
    \qmlclass Scale QQuickScale
Alan Alpert's avatar
Alan Alpert committed
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
    \inqmlmodule QtQuick 2
    \ingroup qml-transform-elements
    \brief The Scale element provides a way to scale an Item.

    The Scale element gives more control over scaling than using \l Item's \l{Item::scale}{scale} property. Specifically,
    it allows a different scale for the x and y axes, and allows the scale to be relative to an
    arbitrary point.

    The following example scales the X axis of the Rectangle, relative to its interior point 25, 25:
    \qml
    Rectangle {
        width: 100; height: 100
        color: "blue"
        transform: Scale { origin.x: 25; origin.y: 25; xScale: 3}
    }
    \endqml

    \sa Rotation, Translate
*/

/*!
    \qmlproperty real QtQuick2::Scale::origin.x
    \qmlproperty real QtQuick2::Scale::origin.y

    The point that the item is scaled from (i.e., the point that stays fixed relative to the parent as
    the rest of the item grows). By default the origin is 0, 0.
*/

/*!
    \qmlproperty real QtQuick2::Scale::xScale

    The scaling factor for the X axis.
*/

/*!
    \qmlproperty real QtQuick2::Scale::yScale

    The scaling factor for the Y axis.
*/

/*!
216
    \qmlclass Rotation QQuickRotation
Alan Alpert's avatar
Alan Alpert committed
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
    \inqmlmodule QtQuick 2
    \ingroup qml-transform-elements
    \brief The Rotation object provides a way to rotate an Item.

    The Rotation object gives more control over rotation than using \l Item's \l{Item::rotation}{rotation} property.
    Specifically, it allows (z axis) rotation to be relative to an arbitrary point.

    The following example rotates a Rectangle around its interior point 25, 25:
    \qml
    Rectangle {
        width: 100; height: 100
        color: "blue"
        transform: Rotation { origin.x: 25; origin.y: 25; angle: 45}
    }
    \endqml

    Rotation also provides a way to specify 3D-like rotations for Items. For these types of
    rotations you must specify the axis to rotate around in addition to the origin point.

    The following example shows various 3D-like rotations applied to an \l Image.
237
    \snippet doc/src/snippets/qml/rotation.qml 0
Alan Alpert's avatar
Alan Alpert committed
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270

    \image axisrotation.png

    \sa {declarative/ui-components/dialcontrol}{Dial Control example}, {declarative/toys/clocks}{Clocks example}
*/

/*!
    \qmlproperty real QtQuick2::Rotation::origin.x
    \qmlproperty real QtQuick2::Rotation::origin.y

    The origin point of the rotation (i.e., the point that stays fixed relative to the parent as
    the rest of the item rotates). By default the origin is 0, 0.
*/

/*!
    \qmlproperty real QtQuick2::Rotation::axis.x
    \qmlproperty real QtQuick2::Rotation::axis.y
    \qmlproperty real QtQuick2::Rotation::axis.z

    The axis to rotate around. For simple (2D) rotation around a point, you do not need to specify an axis,
    as the default axis is the z axis (\c{ axis { x: 0; y: 0; z: 1 } }).

    For a typical 3D-like rotation you will usually specify both the origin and the axis.

    \image 3d-rotation-axis.png
*/

/*!
    \qmlproperty real QtQuick2::Rotation::angle

    The angle to rotate, in degrees clockwise.
*/

271
QQuickTransformPrivate::QQuickTransformPrivate()
272 273 274
{
}

275 276
QQuickTransform::QQuickTransform(QObject *parent)
: QObject(*(new QQuickTransformPrivate), parent)
277 278 279
{
}

280
QQuickTransform::QQuickTransform(QQuickTransformPrivate &dd, QObject *parent)
281 282 283 284
: QObject(dd, parent)
{
}

285
QQuickTransform::~QQuickTransform()
286
{
287
    Q_D(QQuickTransform);
288
    for (int ii = 0; ii < d->items.count(); ++ii) {
289
        QQuickItemPrivate *p = QQuickItemPrivate::get(d->items.at(ii));
290
        p->transforms.removeOne(this);
291
        p->dirty(QQuickItemPrivate::Transform);
292 293 294
    }
}

295
void QQuickTransform::update()
296
{
297
    Q_D(QQuickTransform);
298
    for (int ii = 0; ii < d->items.count(); ++ii) {
299 300
        QQuickItemPrivate *p = QQuickItemPrivate::get(d->items.at(ii));
        p->dirty(QQuickItemPrivate::Transform);
301 302 303
    }
}

304
QQuickContents::QQuickContents(QQuickItem *item)
305 306 307 308
: m_item(item), m_x(0), m_y(0), m_width(0), m_height(0)
{
}

309
QQuickContents::~QQuickContents()
310
{
311
    QList<QQuickItem *> children = m_item->childItems();
312
    for (int i = 0; i < children.count(); ++i) {
313 314
        QQuickItem *child = children.at(i);
        QQuickItemPrivate::get(child)->removeItemChangeListener(this, QQuickItemPrivate::Geometry | QQuickItemPrivate::Destroyed);
315 316 317
    }
}

318
bool QQuickContents::calcHeight(QQuickItem *changed)
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
{
    qreal oldy = m_y;
    qreal oldheight = m_height;

    if (changed) {
        qreal top = oldy;
        qreal bottom = oldy + oldheight;
        qreal y = changed->y();
        if (y + changed->height() > bottom)
            bottom = y + changed->height();
        if (y < top)
            top = y;
        m_y = top;
        m_height = bottom - top;
    } else {
        qreal top = FLT_MAX;
        qreal bottom = 0;
336
        QList<QQuickItem *> children = m_item->childItems();
337
        for (int i = 0; i < children.count(); ++i) {
338
            QQuickItem *child = children.at(i);
339 340 341 342 343 344 345 346 347 348 349
            qreal y = child->y();
            if (y + child->height() > bottom)
                bottom = y + child->height();
            if (y < top)
                top = y;
        }
        if (!children.isEmpty())
            m_y = top;
        m_height = qMax(bottom - top, qreal(0.0));
    }

350
    return (m_height != oldheight || m_y != oldy);
351 352
}

353
bool QQuickContents::calcWidth(QQuickItem *changed)
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
{
    qreal oldx = m_x;
    qreal oldwidth = m_width;

    if (changed) {
        qreal left = oldx;
        qreal right = oldx + oldwidth;
        qreal x = changed->x();
        if (x + changed->width() > right)
            right = x + changed->width();
        if (x < left)
            left = x;
        m_x = left;
        m_width = right - left;
    } else {
        qreal left = FLT_MAX;
        qreal right = 0;
371
        QList<QQuickItem *> children = m_item->childItems();
372
        for (int i = 0; i < children.count(); ++i) {
373
            QQuickItem *child = children.at(i);
374 375 376 377 378 379 380 381 382 383 384
            qreal x = child->x();
            if (x + child->width() > right)
                right = x + child->width();
            if (x < left)
                left = x;
        }
        if (!children.isEmpty())
            m_x = left;
        m_width = qMax(right - left, qreal(0.0));
    }

385
    return (m_width != oldwidth || m_x != oldx);
386 387
}

388
void QQuickContents::complete()
389
{
390 391
    QQuickItemPrivate::get(m_item)->addItemChangeListener(this, QQuickItemPrivate::Children);

392
    QList<QQuickItem *> children = m_item->childItems();
393
    for (int i = 0; i < children.count(); ++i) {
394 395
        QQuickItem *child = children.at(i);
        QQuickItemPrivate::get(child)->addItemChangeListener(this, QQuickItemPrivate::Geometry | QQuickItemPrivate::Destroyed);
396 397 398 399 400
        //###what about changes to visibility?
    }
    calcGeometry();
}

401 402 403 404 405
void QQuickContents::updateRect()
{
    QQuickItemPrivate::get(m_item)->emitChildrenRectChanged(rectF());
}

406
void QQuickContents::itemGeometryChanged(QQuickItem *changed, const QRectF &newGeometry, const QRectF &oldGeometry)
407 408
{
    Q_UNUSED(changed)
409 410
    bool wChanged = false;
    bool hChanged = false;
411 412
    //### we can only pass changed if the left edge has moved left, or the right edge has moved right
    if (newGeometry.width() != oldGeometry.width() || newGeometry.x() != oldGeometry.x())
413
        wChanged = calcWidth(/*changed*/);
414
    if (newGeometry.height() != oldGeometry.height() || newGeometry.y() != oldGeometry.y())
415 416 417
        hChanged = calcHeight(/*changed*/);
    if (wChanged || hChanged)
        updateRect();
418 419
}

420
void QQuickContents::itemDestroyed(QQuickItem *item)
421 422
{
    if (item)
423
        QQuickItemPrivate::get(item)->removeItemChangeListener(this, QQuickItemPrivate::Geometry | QQuickItemPrivate::Destroyed);
424 425 426
    calcGeometry();
}

427
void QQuickContents::itemChildRemoved(QQuickItem *, QQuickItem *item)
428 429
{
    if (item)
430
        QQuickItemPrivate::get(item)->removeItemChangeListener(this, QQuickItemPrivate::Geometry | QQuickItemPrivate::Destroyed);
431 432 433
    calcGeometry();
}

434
void QQuickContents::itemChildAdded(QQuickItem *, QQuickItem *item)
435 436
{
    if (item)
437
        QQuickItemPrivate::get(item)->addItemChangeListener(this, QQuickItemPrivate::Geometry | QQuickItemPrivate::Destroyed);
438
    calcGeometry(item);
439 440
}

441
QQuickItemKeyFilter::QQuickItemKeyFilter(QQuickItem *item)
442 443
: m_processPost(false), m_next(0)
{
444
    QQuickItemPrivate *p = item?QQuickItemPrivate::get(item):0;
445
    if (p) {
446 447
        m_next = p->extra.value().keyHandler;
        p->extra->keyHandler = this;
448 449 450
    }
}

451
QQuickItemKeyFilter::~QQuickItemKeyFilter()
452 453 454
{
}

455
void QQuickItemKeyFilter::keyPressed(QKeyEvent *event, bool post)
456 457 458 459
{
    if (m_next) m_next->keyPressed(event, post);
}

460
void QQuickItemKeyFilter::keyReleased(QKeyEvent *event, bool post)
461 462 463 464
{
    if (m_next) m_next->keyReleased(event, post);
}

465
void QQuickItemKeyFilter::inputMethodEvent(QInputMethodEvent *event, bool post)
466 467 468 469 470 471 472
{
    if (m_next)
        m_next->inputMethodEvent(event, post);
    else
        event->ignore();
}

473
QVariant QQuickItemKeyFilter::inputMethodQuery(Qt::InputMethodQuery query) const
474 475 476 477 478
{
    if (m_next) return m_next->inputMethodQuery(query);
    return QVariant();
}

479
void QQuickItemKeyFilter::componentComplete()
480 481 482
{
    if (m_next) m_next->componentComplete();
}
Alan Alpert's avatar
Alan Alpert committed
483
/*!
484
    \qmlclass KeyNavigation QQuickKeyNavigationAttached
Alan Alpert's avatar
Alan Alpert committed
485 486 487 488 489 490 491 492 493 494
    \inqmlmodule QtQuick 2
    \ingroup qml-basic-interaction-elements
    \brief The KeyNavigation attached property supports key navigation by arrow keys.

    Key-based user interfaces commonly allow the use of arrow keys to navigate between
    focusable items.  The KeyNavigation attached property enables this behavior by providing a
    convenient way to specify the item that should gain focus when an arrow or tab key is pressed.

    The following example provides key navigation for a 2x2 grid of items:

495
    \snippet doc/src/snippets/qml/keynavigation.qml 0
Alan Alpert's avatar
Alan Alpert committed
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545

    The top-left item initially receives focus by setting \l {Item::}{focus} to
    \c true. When an arrow key is pressed, the focus will move to the
    appropriate item, as defined by the value that has been set for
    the KeyNavigation \l left, \l right, \l up or \l down properties.

    Note that if a KeyNavigation attached property receives the key press and release
    events for a requested arrow or tab key, the event is accepted and does not
    propagate any further.

    By default, KeyNavigation receives key events after the item to which it is attached.
    If the item accepts the key event, the KeyNavigation attached property will not
    receive an event for that key.  Setting the \l priority property to
    \c KeyNavigation.BeforeItem allows the event to be used for key navigation
    before the item, rather than after.

    If item to which the focus is switching is not enabled or visible, an attempt will
    be made to skip this item and focus on the next. This is possible if there are
    a chain of items with the same KeyNavigation handler. If multiple items in a row are not enabled
    or visible, they will also be skipped.

    KeyNavigation will implicitly set the other direction to return focus to this item. So if you set
    \l left to another item, \l right will be set on that item's KeyNavigation to set focus back to this
    item. However, if that item's KeyNavigation has had right explicitly set then no change will occur.
    This means that the above example could have been written, with the same behaviour, without specifing
    KeyNavigation.right or KeyNavigation.down for any of the items.

    \sa {Keys}{Keys attached property}
*/

/*!
    \qmlproperty Item QtQuick2::KeyNavigation::left
    \qmlproperty Item QtQuick2::KeyNavigation::right
    \qmlproperty Item QtQuick2::KeyNavigation::up
    \qmlproperty Item QtQuick2::KeyNavigation::down
    \qmlproperty Item QtQuick2::KeyNavigation::tab
    \qmlproperty Item QtQuick2::KeyNavigation::backtab

    These properties hold the item to assign focus to
    when the left, right, up or down cursor keys, or the
    tab key are pressed.
*/

/*!
    \qmlproperty Item QtQuick2::KeyNavigation::tab
    \qmlproperty Item QtQuick2::KeyNavigation::backtab

    These properties hold the item to assign focus to
    when the Tab key or Shift+Tab key combination (Backtab) are pressed.
*/
546

547 548 549
QQuickKeyNavigationAttached::QQuickKeyNavigationAttached(QObject *parent)
: QObject(*(new QQuickKeyNavigationAttachedPrivate), parent),
  QQuickItemKeyFilter(qobject_cast<QQuickItem*>(parent))
550 551 552 553
{
    m_processPost = true;
}

554 555
QQuickKeyNavigationAttached *
QQuickKeyNavigationAttached::qmlAttachedProperties(QObject *obj)
556
{
557
    return new QQuickKeyNavigationAttached(obj);
558 559
}

560
QQuickItem *QQuickKeyNavigationAttached::left() const
561
{
562
    Q_D(const QQuickKeyNavigationAttached);
563 564 565
    return d->left;
}

566
void QQuickKeyNavigationAttached::setLeft(QQuickItem *i)
567
{
568
    Q_D(QQuickKeyNavigationAttached);
569 570 571 572
    if (d->left == i)
        return;
    d->left = i;
    d->leftSet = true;
573 574
    QQuickKeyNavigationAttached* other =
            qobject_cast<QQuickKeyNavigationAttached*>(qmlAttachedPropertiesObject<QQuickKeyNavigationAttached>(i));
575
    if (other && !other->d_func()->rightSet){
576
        other->d_func()->right = qobject_cast<QQuickItem*>(parent());
577 578 579 580 581
        emit other->rightChanged();
    }
    emit leftChanged();
}

582
QQuickItem *QQuickKeyNavigationAttached::right() const
583
{
584
    Q_D(const QQuickKeyNavigationAttached);
585 586 587
    return d->right;
}

588
void QQuickKeyNavigationAttached::setRight(QQuickItem *i)
589
{
590
    Q_D(QQuickKeyNavigationAttached);
591 592 593 594
    if (d->right == i)
        return;
    d->right = i;
    d->rightSet = true;
595 596
    QQuickKeyNavigationAttached* other =
            qobject_cast<QQuickKeyNavigationAttached*>(qmlAttachedPropertiesObject<QQuickKeyNavigationAttached>(i));
597
    if (other && !other->d_func()->leftSet){
598
        other->d_func()->left = qobject_cast<QQuickItem*>(parent());
599 600 601 602 603
        emit other->leftChanged();
    }
    emit rightChanged();
}

604
QQuickItem *QQuickKeyNavigationAttached::up() const
605
{
606
    Q_D(const QQuickKeyNavigationAttached);
607 608 609
    return d->up;
}

610
void QQuickKeyNavigationAttached::setUp(QQuickItem *i)
611
{
612
    Q_D(QQuickKeyNavigationAttached);
613 614 615 616
    if (d->up == i)
        return;
    d->up = i;
    d->upSet = true;
617 618
    QQuickKeyNavigationAttached* other =
            qobject_cast<QQuickKeyNavigationAttached*>(qmlAttachedPropertiesObject<QQuickKeyNavigationAttached>(i));
619
    if (other && !other->d_func()->downSet){
620
        other->d_func()->down = qobject_cast<QQuickItem*>(parent());
621 622 623 624 625
        emit other->downChanged();
    }
    emit upChanged();
}

626
QQuickItem *QQuickKeyNavigationAttached::down() const
627
{
628
    Q_D(const QQuickKeyNavigationAttached);
629 630 631
    return d->down;
}

632
void QQuickKeyNavigationAttached::setDown(QQuickItem *i)
633
{
634
    Q_D(QQuickKeyNavigationAttached);
635 636 637 638
    if (d->down == i)
        return;
    d->down = i;
    d->downSet = true;
639 640
    QQuickKeyNavigationAttached* other =
            qobject_cast<QQuickKeyNavigationAttached*>(qmlAttachedPropertiesObject<QQuickKeyNavigationAttached>(i));
Kent Hansen's avatar
Kent Hansen committed
641
    if (other && !other->d_func()->upSet) {
642
        other->d_func()->up = qobject_cast<QQuickItem*>(parent());
643 644 645 646 647
        emit other->upChanged();
    }
    emit downChanged();
}

648
QQuickItem *QQuickKeyNavigationAttached::tab() const
649
{
650
    Q_D(const QQuickKeyNavigationAttached);
651 652 653
    return d->tab;
}

654
void QQuickKeyNavigationAttached::setTab(QQuickItem *i)
655
{
656
    Q_D(QQuickKeyNavigationAttached);
657 658 659 660
    if (d->tab == i)
        return;
    d->tab = i;
    d->tabSet = true;
661 662
    QQuickKeyNavigationAttached* other =
            qobject_cast<QQuickKeyNavigationAttached*>(qmlAttachedPropertiesObject<QQuickKeyNavigationAttached>(i));
Kent Hansen's avatar
Kent Hansen committed
663
    if (other && !other->d_func()->backtabSet) {
664
        other->d_func()->backtab = qobject_cast<QQuickItem*>(parent());
665 666 667 668 669
        emit other->backtabChanged();
    }
    emit tabChanged();
}

670
QQuickItem *QQuickKeyNavigationAttached::backtab() const
671
{
672
    Q_D(const QQuickKeyNavigationAttached);
673 674 675
    return d->backtab;
}

676
void QQuickKeyNavigationAttached::setBacktab(QQuickItem *i)
677
{
678
    Q_D(QQuickKeyNavigationAttached);
679 680 681 682
    if (d->backtab == i)
        return;
    d->backtab = i;
    d->backtabSet = true;
683 684
    QQuickKeyNavigationAttached* other =
            qobject_cast<QQuickKeyNavigationAttached*>(qmlAttachedPropertiesObject<QQuickKeyNavigationAttached>(i));
Kent Hansen's avatar
Kent Hansen committed
685
    if (other && !other->d_func()->tabSet) {
686
        other->d_func()->tab = qobject_cast<QQuickItem*>(parent());
687 688 689 690 691
        emit other->tabChanged();
    }
    emit backtabChanged();
}

Alan Alpert's avatar
Alan Alpert committed
692 693 694 695 696 697 698
/*!
    \qmlproperty enumeration QtQuick2::KeyNavigation::priority

    This property determines whether the keys are processed before
    or after the attached item's own key handling.

    \list
699
    \li KeyNavigation.BeforeItem - process the key events before normal
Alan Alpert's avatar
Alan Alpert committed
700 701
    item key processing.  If the event is used for key navigation, it will be accepted and will not
    be passed on to the item.
702
    \li KeyNavigation.AfterItem (default) - process the key events after normal item key
Alan Alpert's avatar
Alan Alpert committed
703 704 705 706
    handling.  If the item accepts the key event it will not be
    handled by the KeyNavigation attached property handler.
    \endlist
*/
707
QQuickKeyNavigationAttached::Priority QQuickKeyNavigationAttached::priority() const
708 709 710 711
{
    return m_processPost ? AfterItem : BeforeItem;
}

712
void QQuickKeyNavigationAttached::setPriority(Priority order)
713 714 715 716 717 718 719 720
{
    bool processPost = order == AfterItem;
    if (processPost != m_processPost) {
        m_processPost = processPost;
        emit priorityChanged();
    }
}

721
void QQuickKeyNavigationAttached::keyPressed(QKeyEvent *event, bool post)
722
{
723
    Q_D(QQuickKeyNavigationAttached);
724 725 726
    event->ignore();

    if (post != m_processPost) {
727
        QQuickItemKeyFilter::keyPressed(event, post);
728 729 730 731
        return;
    }

    bool mirror = false;
Kent Hansen's avatar
Kent Hansen committed
732
    switch (event->key()) {
733
    case Qt::Key_Left: {
734 735 736
        if (QQuickItem *parentItem = qobject_cast<QQuickItem*>(parent()))
            mirror = QQuickItemPrivate::get(parentItem)->effectiveLayoutMirror;
        QQuickItem* leftItem = mirror ? d->right : d->left;
737 738 739 740 741 742 743
        if (leftItem) {
            setFocusNavigation(leftItem, mirror ? "right" : "left");
            event->accept();
        }
        break;
    }
    case Qt::Key_Right: {
744 745 746
        if (QQuickItem *parentItem = qobject_cast<QQuickItem*>(parent()))
            mirror = QQuickItemPrivate::get(parentItem)->effectiveLayoutMirror;
        QQuickItem* rightItem = mirror ? d->left : d->right;
747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780
        if (rightItem) {
            setFocusNavigation(rightItem, mirror ? "left" : "right");
            event->accept();
        }
        break;
    }
    case Qt::Key_Up:
        if (d->up) {
            setFocusNavigation(d->up, "up");
            event->accept();
        }
        break;
    case Qt::Key_Down:
        if (d->down) {
            setFocusNavigation(d->down, "down");
            event->accept();
        }
        break;
    case Qt::Key_Tab:
        if (d->tab) {
            setFocusNavigation(d->tab, "tab");
            event->accept();
        }
        break;
    case Qt::Key_Backtab:
        if (d->backtab) {
            setFocusNavigation(d->backtab, "backtab");
            event->accept();
        }
        break;
    default:
        break;
    }

781
    if (!event->isAccepted()) QQuickItemKeyFilter::keyPressed(event, post);
782 783
}

784
void QQuickKeyNavigationAttached::keyReleased(QKeyEvent *event, bool post)
785
{
786
    Q_D(QQuickKeyNavigationAttached);
787 788 789
    event->ignore();

    if (post != m_processPost) {
790
        QQuickItemKeyFilter::keyReleased(event, post);
791 792 793 794
        return;
    }

    bool mirror = false;
Kent Hansen's avatar
Kent Hansen committed
795
    switch (event->key()) {
796
    case Qt::Key_Left:
797 798
        if (QQuickItem *parentItem = qobject_cast<QQuickItem*>(parent()))
            mirror = QQuickItemPrivate::get(parentItem)->effectiveLayoutMirror;
799 800 801 802
        if (mirror ? d->right : d->left)
            event->accept();
        break;
    case Qt::Key_Right:
803 804
        if (QQuickItem *parentItem = qobject_cast<QQuickItem*>(parent()))
            mirror = QQuickItemPrivate::get(parentItem)->effectiveLayoutMirror;
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831
        if (mirror ? d->left : d->right)
            event->accept();
        break;
    case Qt::Key_Up:
        if (d->up) {
            event->accept();
        }
        break;
    case Qt::Key_Down:
        if (d->down) {
            event->accept();
        }
        break;
    case Qt::Key_Tab:
        if (d->tab) {
            event->accept();
        }
        break;
    case Qt::Key_Backtab:
        if (d->backtab) {
            event->accept();
        }
        break;
    default:
        break;
    }

832
    if (!event->isAccepted()) QQuickItemKeyFilter::keyReleased(event, post);
833 834
}

835
void QQuickKeyNavigationAttached::setFocusNavigation(QQuickItem *currentItem, const char *dir)
836
{
837
    QQuickItem *initialItem = currentItem;
838 839 840 841 842 843 844
    bool isNextItem = false;
    do {
        isNextItem = false;
        if (currentItem->isVisible() && currentItem->isEnabled()) {
            currentItem->setFocus(true);
        } else {
            QObject *attached =
845
                qmlAttachedPropertiesObject<QQuickKeyNavigationAttached>(currentItem, false);
846
            if (attached) {
847
                QQuickItem *tempItem = qvariant_cast<QQuickItem*>(attached->property(dir));
848 849 850 851 852 853 854 855 856 857
                if (tempItem) {
                    currentItem = tempItem;
                    isNextItem = true;
                }
            }
        }
    }
    while (currentItem != initialItem && isNextItem);
}

858
const QQuickKeysAttached::SigMap QQuickKeysAttached::sigMap[] = {
859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889
    { Qt::Key_Left, "leftPressed" },
    { Qt::Key_Right, "rightPressed" },
    { Qt::Key_Up, "upPressed" },
    { Qt::Key_Down, "downPressed" },
    { Qt::Key_Tab, "tabPressed" },
    { Qt::Key_Backtab, "backtabPressed" },
    { Qt::Key_Asterisk, "asteriskPressed" },
    { Qt::Key_NumberSign, "numberSignPressed" },
    { Qt::Key_Escape, "escapePressed" },
    { Qt::Key_Return, "returnPressed" },
    { Qt::Key_Enter, "enterPressed" },
    { Qt::Key_Delete, "deletePressed" },
    { Qt::Key_Space, "spacePressed" },
    { Qt::Key_Back, "backPressed" },
    { Qt::Key_Cancel, "cancelPressed" },
    { Qt::Key_Select, "selectPressed" },
    { Qt::Key_Yes, "yesPressed" },
    { Qt::Key_No, "noPressed" },
    { Qt::Key_Context1, "context1Pressed" },
    { Qt::Key_Context2, "context2Pressed" },
    { Qt::Key_Context3, "context3Pressed" },
    { Qt::Key_Context4, "context4Pressed" },
    { Qt::Key_Call, "callPressed" },
    { Qt::Key_Hangup, "hangupPressed" },
    { Qt::Key_Flip, "flipPressed" },
    { Qt::Key_Menu, "menuPressed" },
    { Qt::Key_VolumeUp, "volumeUpPressed" },
    { Qt::Key_VolumeDown, "volumeDownPressed" },
    { 0, 0 }
};

890
bool QQuickKeysAttachedPrivate::isConnected(const char *signalName)
891 892 893 894
{
    return isSignalConnected(signalIndex(signalName));
}

Alan Alpert's avatar
Alan Alpert committed
895
/*!
896
    \qmlclass Keys QQuickKeysAttached
Alan Alpert's avatar
Alan Alpert committed
897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915
    \inqmlmodule QtQuick 2
    \ingroup qml-basic-interaction-elements
    \brief The Keys attached property provides key handling to Items.

    All visual primitives support key handling via the Keys
    attached property.  Keys can be handled via the onPressed
    and onReleased signal properties.

    The signal properties have a \l KeyEvent parameter, named
    \e event which contains details of the event.  If a key is
    handled \e event.accepted should be set to true to prevent the
    event from propagating up the item hierarchy.

    \section1 Example Usage

    The following example shows how the general onPressed handler can
    be used to test for a certain key; in this case, the left cursor
    key:

916
    \snippet doc/src/snippets/qml/keys/keys-pressed.qml key item
Alan Alpert's avatar
Alan Alpert committed
917 918 919 920 921

    Some keys may alternatively be handled via specific signal properties,
    for example \e onSelectPressed.  These handlers automatically set
    \e event.accepted to true.

922
    \snippet doc/src/snippets/qml/keys/keys-handler.qml key item
Alan Alpert's avatar
Alan Alpert committed
923 924 925 926 927 928 929 930 931 932 933 934 935

    See \l{Qt::Key}{Qt.Key} for the list of keyboard codes.

    \section1 Key Handling Priorities

    The Keys attached property can be configured to handle key events
    before or after the item it is attached to. This makes it possible
    to intercept events in order to override an item's default behavior,
    or act as a fallback for keys not handled by the item.

    If \l priority is Keys.BeforeItem (default) the order of key event processing is:

    \list 1
936 937 938 939 940
    \li Items specified in \c forwardTo
    \li specific key handlers, e.g. onReturnPressed
    \li onKeyPress, onKeyRelease handlers
    \li Item specific key handling, e.g. TextInput key handling
    \li parent item
Alan Alpert's avatar
Alan Alpert committed
941 942 943 944 945
    \endlist

    If priority is Keys.AfterItem the order of key event processing is:

    \list 1
946 947 948 949 950
    \li Item specific key handling, e.g. TextInput key handling
    \li Items specified in \c forwardTo
    \li specific key handlers, e.g. onReturnPressed
    \li onKeyPress, onKeyRelease handlers
    \li parent item
Alan Alpert's avatar
Alan Alpert committed
951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972
    \endlist

    If the event is accepted during any of the above steps, key
    propagation stops.

    \sa KeyEvent, {KeyNavigation}{KeyNavigation attached property}
*/

/*!
    \qmlproperty bool QtQuick2::Keys::enabled

    This flags enables key handling if true (default); otherwise
    no key handlers will be called.
*/

/*!
    \qmlproperty enumeration QtQuick2::Keys::priority

    This property determines whether the keys are processed before
    or after the attached item's own key handling.

    \list
973
    \li Keys.BeforeItem (default) - process the key events before normal
Alan Alpert's avatar
Alan Alpert committed
974 975
    item key processing.  If the event is accepted it will not
    be passed on to the item.
976
    \li Keys.AfterItem - process the key events after normal item key
Alan Alpert's avatar
Alan Alpert committed
977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
    handling.  If the item accepts the key event it will not be
    handled by the Keys attached property handler.
    \endlist
*/

/*!
    \qmlproperty list<Object> QtQuick2::Keys::forwardTo

    This property provides a way to forward key presses, key releases, and keyboard input
    coming from input methods to other items. This can be useful when you want
    one item to handle some keys (e.g. the up and down arrow keys), and another item to
    handle other keys (e.g. the left and right arrow keys).  Once an item that has been
    forwarded keys accepts the event it is no longer forwarded to items later in the
    list.

    This example forwards key events to two lists:
    \qml
    Item {
        ListView {
            id: list1
            // ...
        }
        ListView {
            id: list2
            // ...
        }
        Keys.forwardTo: [list1, list2]
        focus: true
    }
    \endqml
*/

/*!
    \qmlsignal QtQuick2::Keys::onPressed(KeyEvent event)

    This handler is called when a key has been pressed. The \a event
    parameter provides information about the event.
*/

/*!
    \qmlsignal QtQuick2::Keys::onReleased(KeyEvent event)

    This handler is called when a key has been released. The \a event
    parameter provides information about the event.
*/

/*!
    \qmlsignal QtQuick2::Keys::onDigit0Pressed(KeyEvent event)

    This handler is called when the digit '0' has been pressed. The \a event
    parameter provides information about the event.
*/

/*!
    \qmlsignal QtQuick2::Keys::onDigit1Pressed(KeyEvent event)

    This handler is called when the digit '1' has been pressed. The \a event
    parameter provides information about the event.
*/

/*!
    \qmlsignal QtQuick2::Keys::onDigit2Pressed(KeyEvent event)

    This handler is called when the digit '2' has been pressed. The \a event
    parameter provides information about the event.
*/

/*!
    \qmlsignal QtQuick2::Keys::onDigit3Pressed(KeyEvent event)

    This handler is called when the digit '3' has been pressed. The \a event
    parameter provides information about the event.
*/

/*!
    \qmlsignal QtQuick2::Keys::onDigit4Pressed(KeyEvent event)

    This handler is called when the digit '4' has been pressed. The \a event
    parameter provides information about the event.
*/

/*!
    \qmlsignal QtQuick2::Keys::onDigit5Pressed(KeyEvent event)

    This handler is called when the digit '5' has been pressed. The \a event
    parameter provides information about the event.
*/

/*!
    \qmlsignal QtQuick2::Keys::onDigit6Pressed(KeyEvent event)

    This handler is called when the digit '6' has been pressed. The \a event
    parameter provides information about the event.
*/

/*!
    \qmlsignal QtQuick2::Keys::onDigit7Pressed(KeyEvent event)

    This handler is called when the digit '7' has been pressed. The \a event
    parameter provides information about the event.
*/

/*!
    \qmlsignal QtQuick2::Keys::onDigit8Pressed(KeyEvent event)

    This handler is called when the digit '8' has been pressed. The \a event
    parameter provides information about the event.
*/

/*!
    \qmlsignal QtQuick2::Keys::onDigit9Pressed(KeyEvent event)

    This handler is called when the digit '9' has been pressed. The \a event
    parameter provides information about the event.
*/

/*!
    \qmlsignal QtQuick2::Keys::onLeftPressed(KeyEvent event)

    This handler is called when the Left arrow has been pressed. The \a event
    parameter provides information about the event.
*/

/*!
    \qmlsignal QtQuick2::Keys::onRightPressed(KeyEvent event)

    This handler is called when the Right arrow has been pressed. The \a event
    parameter provides information about the event.
*/

/*!
    \qmlsignal QtQuick2::Keys::onUpPressed(KeyEvent event)

    This handler is called when the Up arrow has been pressed. The \a event
    parameter provides information about the event.
*/

/*!
    \qmlsignal QtQuick2::Keys::onDownPressed(KeyEvent event)

    This handler is called when the Down arrow has been pressed. The \a event
    parameter provides information about the event.
*/

/*!
    \qmlsignal QtQuick2::Keys::onTabPressed(KeyEvent event)

    This handler is called when the Tab key has been pressed. The \a event
    parameter provides information about the event.
*/

/*!
    \qmlsignal QtQuick2::Keys::onBacktabPressed(KeyEvent event)

    This handler is called when the Shift+Tab key combination (Backtab) has
    been pressed. The \a event parameter provides information about the event.
*/

/*!
    \qmlsignal QtQuick2::Keys::onAsteriskPressed(KeyEvent event)

    This handler is called when the Asterisk '*' has been pressed. The \a event
    parameter provides information about the event.
*/

/*!
    \qmlsignal QtQuick2::Keys::onEscapePressed(KeyEvent event)

    This handler is called when the Escape key has been pressed. The \a event
    parameter provides information about the event.
*/

/*!
    \qmlsignal QtQuick2::Keys::onReturnPressed(KeyEvent event)

    This handler is called when the Return key has been pressed. The \a event
    parameter provides information about the event.
*/

/*!
    \qmlsignal QtQuick2::Keys::onEnterPressed(KeyEvent event)

    This handler is called when the Enter key has been pressed. The \a event
    parameter provides information about the event.
*/

/*!
    \qmlsignal QtQuick2::Keys::onDeletePressed(KeyEvent event)

    This handler is called when the Delete key has been pressed. The \a event
    parameter provides information about the event.
*/

/*!
    \qmlsignal QtQuick2::Keys::onSpacePressed(KeyEvent event)

    This handler is called when the Space key has been pressed. The \a event
    parameter provides information about the event.
*/

/*!
    \qmlsignal QtQuick2::Keys::onBackPressed(KeyEvent event)

    This handler is called when the Back key has been pressed. The \a event
    parameter provides information about the event.
*/

/*!
    \qmlsignal QtQuick2::Keys::onCancelPressed(KeyEvent event)

    This handler is called when the Cancel key has been pressed. The \a event
    parameter provides information about the event.
*/

/*!
    \qmlsignal QtQuick2::Keys::onSelectPressed(KeyEvent event)

    This handler is called when the Select key has been pressed. The \a event
    parameter provides information about the event.
*/

/*!
    \qmlsignal QtQuick2::Keys::onYesPressed(KeyEvent event)

    This handler is called when the Yes key has been pressed. The \a event
    parameter provides information about the event.
*/

/*!
    \qmlsignal QtQuick2::Keys::onNoPressed(KeyEvent event)

    This handler is called when the No key has been pressed. The \a event
    parameter provides information about the event.
*/

/*!
    \qmlsignal QtQuick2::Keys::onContext1Pressed(KeyEvent event)

    This handler is called when the Context1 key has been pressed. The \a event
    parameter provides information about the event.
*/

/*!
    \qmlsignal QtQuick2::Keys::onContext2Pressed(KeyEvent event)

    This handler is called when the Context2 key has been pressed. The \a event
    parameter provides information about the event.
*/

/*!
    \qmlsignal QtQuick2::Keys::onContext3Pressed(KeyEvent event)

    This handler is called when the Context3 key has been pressed. The \a event
    parameter provides information about the event.
*/

/*!
    \qmlsignal QtQuick2::Keys::onContext4Pressed(KeyEvent event)

    This handler is called when the Context4 key has been pressed. The \a event
    parameter provides information about the event.
*/

/*!
    \qmlsignal QtQuick2::Keys::onCallPressed(KeyEvent event)

    This handler is called when the Call key has been pressed. The \a event
    parameter provides information about the event.
*/

/*!
    \qmlsignal QtQuick2::Keys::onHangupPressed(KeyEvent event)

    This handler is called when the Hangup key has been pressed. The \a event
    parameter provides information about the event.
*/

/*!
    \qmlsignal QtQuick2::Keys::onFlipPressed(KeyEvent event)

    This handler is called when the Flip key has been pressed. The \a event
    parameter provides information about the event.
*/

/*!
    \qmlsignal QtQuick2::Keys::onMenuPressed(KeyEvent event)

    This handler is called when the Menu key has been pressed. The \a event
    parameter provides information about the event.
*/

/*!
    \qmlsignal QtQuick2::Keys::onVolumeUpPressed(KeyEvent event)

    This handler is called when the VolumeUp key has been pressed. The \a event
    parameter provides information about the event.
*/

/*!
    \qmlsignal QtQuick2::Keys::onVolumeDownPressed(KeyEvent event)

    This handler is called when the VolumeDown key has been pressed. The \a event
    parameter provides information about the event.
*/

1282 1283 1284
QQuickKeysAttached::QQuickKeysAttached(QObject *parent)
: QObject(*(new QQuickKeysAttachedPrivate), parent),
  QQuickItemKeyFilter(qobject_cast<QQuickItem*>(parent))
1285
{
1286
    Q_D(QQuickKeysAttached);
1287
    m_processPost = false;
1288
    d->item = qobject_cast<QQuickItem*>(parent);
1289 1290
}

1291
QQuickKeysAttached::~QQuickKeysAttached()
1292 1293 1294
{
}

1295
QQuickKeysAttached::Priority QQuickKeysAttached::priority() const
1296 1297 1298 1299
{
    return m_processPost ? AfterItem : BeforeItem;
}

1300
void QQuickKeysAttached::setPriority(Priority order)
1301 1302 1303 1304 1305 1306 1307 1308
{
    bool processPost = order == AfterItem;
    if (processPost != m_processPost) {
        m_processPost = processPost;
        emit priorityChanged();
    }
}

1309
void QQuickKeysAttached::componentComplete()
1310
{
1311
    Q_D(QQuickKeysAttached);
1312 1313
    if (d->item) {
        for (int ii = 0; ii < d->targets.count(); ++ii) {
1314 1315 1316
            QQuickItem *targetItem = d->targets.at(ii);
            if (targetItem && (targetItem->flags() & QQuickItem::ItemAcceptsInputMethod)) {
                d->item->setFlag(QQuickItem::ItemAcceptsInputMethod);
1317 1318 1319 1320 1321 1322
                break;
            }
        }
    }
}

1323
void QQuickKeysAttached::keyPressed(QKeyEvent *event, bool post)
1324
{
1325
    Q_D(QQuickKeysAttached);
1326 1327
    if (post != m_processPost || !d->enabled || d->inPress) {
        event->ignore();
1328
        QQuickItemKeyFilter::keyPressed(event, post);
1329 1330 1331 1332 1333 1334 1335
        return;
    }

    // first process forwards
    if (d->item && d->item->canvas()) {
        d->inPress = true;
        for (int ii = 0; ii < d->targets.count(); ++ii) {
1336
            QQuickItem *i = d->targets.at(ii);
1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
            if (i && i->isVisible()) {
                d->item->canvas()->sendEvent(i, event);
                if (event->isAccepted()) {
                    d->inPress = false;
                    return;
                }
            }
        }
        d->inPress = false;
    }

1348
    QQuickKeyEvent ke(*event);
1349 1350
    QByteArray keySignal = keyToSignal(event->key());
    if (!keySignal.isEmpty()) {
1351
        keySignal += "(QQuickKeyEvent*)";
1352 1353 1354
        if (d->isConnected(keySignal)) {
            // If we specifically handle a key then default to accepted
            ke.setAccepted(true);
1355 1356
            int idx = QQuickKeysAttached::staticMetaObject.indexOfSignal(keySignal);
            metaObject()->method(idx).invoke(this, Qt::DirectConnection, Q_ARG(QQuickKeyEvent*, &ke));
1357 1358 1359 1360 1361 1362
        }
    }
    if (!ke.isAccepted())
        emit pressed(&ke);
    event->setAccepted(ke.isAccepted());

1363
    if (!event->isAccepted()) QQuickItemKeyFilter::keyPressed(event, post);
1364 1365
}

1366
void QQuickKeysAttached::keyReleased(QKeyEvent *event, bool post)
1367
{
1368
    Q_D(QQuickKeysAttached);
1369 1370
    if (post != m_processPost || !d->enabled || d->inRelease) {
        event->ignore();
1371
        QQuickItemKeyFilter::keyReleased(event, post);
1372 1373 1374 1375 1376 1377
        return;
    }

    if (d->item && d->item->canvas()) {
        d->inRelease = true;
        for (int ii = 0; ii < d->targets.count(); ++ii) {
1378
            QQuickItem *i = d->targets.at(ii);
1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389
            if (i && i->isVisible()) {
                d->item->canvas()->sendEvent(i, event);
                if (event->isAccepted()) {
                    d->inRelease = false;
                    return;
                }
            }
        }
        d->inRelease = false;
    }

1390
    QQuickKeyEvent ke(*event);
1391 1392 1393
    emit released(&ke);
    event->setAccepted(ke.isAccepted());

1394
    if (!event->isAccepted()) QQuickItemKeyFilter::keyReleased(event, post);
1395 1396
}

1397
void QQuickKeysAttached::inputMethodEvent(QInputMethodEvent *event, bool post)
1398
{
1399
    Q_D(QQuickKeysAttached);
1400 1401 1402
    if (post == m_processPost && d->item && !d->inIM && d->item->canvas()) {
        d->inIM = true;
        for (int ii = 0; ii < d->targets.count(); ++ii) {
1403 1404
            QQuickItem *i = d->targets.at(ii);
            if (i && i->isVisible() && (i->flags() & QQuickItem::ItemAcceptsInputMethod)) {
1405 1406 1407 1408 1409 1410 1411 1412 1413 1414
                d->item->canvas()->sendEvent(i, event);
                if (event->isAccepted()) {
                    d->imeItem = i;
                    d->inIM = false;
                    return;
                }
            }
        }
        d->inIM = false;
    }
1415
    QQuickItemKeyFilter::inputMethodEvent(event, post);
1416 1417
}

1418
QVariant QQuickKeysAttached::inputMethodQuery(Qt::InputMethodQuery query) const
1419
{
1420
    Q_D(const QQuickKeysAttached);
1421 1422
    if (d->item) {
        for (int ii = 0; ii < d->targets.count(); ++ii) {
1423 1424
            QQuickItem *i = d->targets.at(ii);
            if (i && i->isVisible() && (i->flags() & QQuickItem::ItemAcceptsInputMethod) && i == d->imeItem) {
1425 1426 1427 1428 1429 1430 1431 1432
                //### how robust is i == d->imeItem check?
                QVariant v = i->inputMethodQuery(query);
                if (v.userType() == QVariant::RectF)
                    v = d->item->mapRectFromItem(i, v.toRectF());  //### cost?
                return v;
            }
        }
    }
1433
    return QQuickItemKeyFilter::inputMethodQuery(query);
1434 1435
}

1436
QQuickKeysAttached *QQuickKeysAttached::qmlAttachedProperties(QObject *obj)
1437
{
1438
    return new QQuickKeysAttached(obj);
1439 1440
}

Alan Alpert's avatar
Alan Alpert committed
1441
/*!
1442
    \qmlclass LayoutMirroring QQuickLayoutMirroringAttached
Alan Alpert's avatar
Alan Alpert committed
1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463
    \inqmlmodule QtQuick 2
    \ingroup qml-utility-elements
    \brief The LayoutMirroring attached property is used to mirror layout behavior.

    The LayoutMirroring attached property is used to horizontally mirror \l {anchor-layout}{Item anchors},
    \l{Using QML Positioner and Repeater Items}{positioner} elements (such as \l Row and \l Grid)
    and views (such as \l GridView and horizontal \l ListView). Mirroring is a visual change: left
    anchors become right anchors, and positioner elements like \l Grid and \l Row reverse the
    horizontal layout of child items.

    Mirroring is enabled for an item by setting the \l enabled property to true. By default, this
    only affects the item itself; setting the \l childrenInherit property to true propagates the mirroring
    behavior to all child elements as well. If the \c LayoutMirroring attached property has not been defined
    for an item, mirroring is not enabled.

    The following example shows mirroring in action. The \l Row below is specified as being anchored
    to the left of its parent. However, since mirroring has been enabled, the anchor is horizontally
    reversed and it is now anchored to the right. Also, since items in a \l Row are positioned
    from left to right by default, they are now positioned from right to left instead, as demonstrated
    by the numbering and opacity of the items:

1464
    \snippet doc/src/snippets/qml/layoutmirroring.qml 0
Alan Alpert's avatar
Alan Alpert committed
1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503

    \image layoutmirroring.png

    Layout mirroring is useful when it is necessary to support both left-to-right and right-to-left
    layout versions of an application to target different language areas. The \l childrenInherit
    property allows layout mirroring to be applied without manually setting layout configurations
    for every item in an application. Keep in mind, however, that mirroring does not affect any
    positioning that is defined by the \l Item \l {Item::}{x} coordinate value, so even with
    mirroring enabled, it will often be necessary to apply some layout fixes to support the
    desired layout direction. Also, it may be necessary to disable the mirroring of individual
    child items (by setting \l {enabled}{LayoutMirroring.enabled} to false for such items) if
    mirroring is not the desired behavior, or if the child item already implements mirroring in
    some custom way.

    See \l {QML Right-to-left User Interfaces} for further details on using \c LayoutMirroring and
    other related features to implement right-to-left support for an application.
*/

/*!
    \qmlproperty bool QtQuick2::LayoutMirroring::enabled

    This property holds whether the item's layout is mirrored horizontally. Setting this to true
    horizontally reverses \l {anchor-layout}{anchor} settings such that left anchors become right,
    and right anchors become left. For \l{Using QML Positioner and Repeater Items}{positioner} elements
    (such as \l Row and \l Grid) and view elements (such as \l {GridView}{GridView} and \l {ListView}{ListView})
    this also mirrors the horizontal layout direction of the item.

    The default value is false.
*/

/*!
    \qmlproperty bool QtQuick2::LayoutMirroring::childrenInherit

    This property holds whether the \l {enabled}{LayoutMirroring.enabled} value for this item
    is inherited by its children.

    The default value is false.
*/

1504

1505
QQuickLayoutMirroringAttached::QQuickLayoutMirroringAttached(QObject *parent) : QObject(parent), itemPrivate(0)
1506
{
1507 1508
    if (QQuickItem *item = qobject_cast<QQuickItem*>(parent)) {
        itemPrivate = QQuickItemPrivate::get(item);
1509
        itemPrivate->extra.value().layoutDirectionAttached = this;
1510 1511 1512 1513
    } else
        qmlInfo(parent) << tr("LayoutDirection attached property only works with Items");
}

1514
QQuickLayoutMirroringAttached * QQuickLayoutMirroringAttached::qmlAttachedProperties(QObject *object)
1515
{
1516
    return new QQuickLayoutMirroringAttached(object);
1517 1518
}

1519
bool QQuickLayoutMirroringAttached::enabled() const
1520 1521 1522 1523
{
    return itemPrivate ? itemPrivate->effectiveLayoutMirror : false;
}

1524
void QQuickLayoutMirroringAttached::setEnabled(bool enabled)
1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536
{
    if (!itemPrivate)
        return;

    itemPrivate->isMirrorImplicit = false;
    if (enabled != itemPrivate->effectiveLayoutMirror) {
        itemPrivate->setLayoutMirror(enabled);
        if (itemPrivate->inheritMirrorFromItem)
             itemPrivate->resolveLayoutMirror();
    }
}

1537
void QQuickLayoutMirroringAttached::resetEnabled()
1538 1539 1540 1541 1542 1543 1544
{
    if (itemPrivate && !itemPrivate->isMirrorImplicit) {
        itemPrivate->isMirrorImplicit = true;
        itemPrivate->resolveLayoutMirror();
    }
}

1545
bool QQuickLayoutMirroringAttached::childrenInherit() const
1546 1547 1548 1549
{
    return itemPrivate ? itemPrivate->inheritMirrorFromItem : false;
}

1550
void QQuickLayoutMirroringAttached::setChildrenInherit(bool childrenInherit) {
1551 1552 1553 1554 1555 1556 1557
    if (itemPrivate && childrenInherit != itemPrivate->inheritMirrorFromItem) {
        itemPrivate->inheritMirrorFromItem = childrenInherit;
        itemPrivate->resolveLayoutMirror();
        childrenInheritChanged();
    }
}

1558
void QQuickItemPrivate::resolveLayoutMirror()
1559
{
1560 1561 1562
    Q_Q(QQuickItem);
    if (QQuickItem *parentItem = q->parentItem()) {
        QQuickItemPrivate *parentPrivate = QQuickItemPrivate::get(parentItem);
1563 1564 1565 1566 1567 1568
        setImplicitLayoutMirror(parentPrivate->inheritedLayoutMirror, parentPrivate->inheritMirrorFromParent);
    } else {
        setImplicitLayoutMirror(isMirrorImplicit ? false : effectiveLayoutMirror, inheritMirrorFromItem);
    }
}

1569
void QQuickItemPrivate::setImplicitLayoutMirror(bool mirror, bool inherit)
1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582
{
    inherit = inherit || inheritMirrorFromItem;
    if (!isMirrorImplicit && inheritMirrorFromItem)
        mirror = effectiveLayoutMirror;
    if (mirror == inheritedLayoutMirror && inherit == inheritMirrorFromParent)
        return;

    inheritMirrorFromParent = inherit;
    inheritedLayoutMirror = inheritMirrorFromParent ? mirror : false;

    if (isMirrorImplicit)
        setLayoutMirror(inherit ? inheritedLayoutMirror : false);
    for (int i = 0; i < childItems.count(); ++i) {
1583 1584
        if (QQuickItem *child = qobject_cast<QQuickItem *>(childItems.at(i))) {
            QQuickItemPrivate *childPrivate = QQuickItemPrivate::get(child);
1585 1586 1587 1588 1589
            childPrivate->setImplicitLayoutMirror(inheritedLayoutMirror, inheritMirrorFromParent);
        }
    }
}

1590
void QQuickItemPrivate::setLayoutMirror(bool mirror)
1591 1592 1593 1594
{
    if (mirror != effectiveLayoutMirror) {
        effectiveLayoutMirror = mirror;
        if (_anchors) {
1595
            QQuickAnchorsPrivate *anchor_d = QQuickAnchorsPrivate::get(_anchors);
1596 1597 1598 1599 1600 1601
            anchor_d->fillChanged();
            anchor_d->centerInChanged();
            anchor_d->updateHorizontalAnchors();
            emit _anchors->mirroredChanged();
        }
        mirrorChange();
1602 1603
        if (extra.isAllocated() && extra->layoutDirectionAttached) {
            emit extra->layoutDirectionAttached->enabledChanged();
1604 1605 1606 1607
        }
    }
}

1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623
void QQuickItemPrivate::setAccessibleFlagAndListener()
{
    Q_Q(QQuickItem);
    QQuickItem *item = q;
    while (item) {
        if (item->d_func()->isAccessible)
            break; // already set - grandparents should have the flag set as well.

        if (item->canvas() && item->canvas()->rootItem() == item)
            break; // don't add a listener to the canvas root item

        item->d_func()->isAccessible = true;
        item = item->d_func()->parentItem;
    }
}

1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634
void QQuickItemPrivate::updateSubFocusItem(QQuickItem *scope, bool focus)
{
    Q_Q(QQuickItem);
    Q_ASSERT(scope);

    QQuickItemPrivate *scopePrivate = QQuickItemPrivate::get(scope);

    QQuickItem *oldSubFocusItem = scopePrivate->subFocusItem;
    // Correct focus chain in scope
    if (oldSubFocusItem) {
        QQuickItem *sfi = scopePrivate->subFocusItem->parentItem();
1635
        while (sfi && sfi != scope) {
1636 1637 1638 1639 1640 1641 1642 1643
            QQuickItemPrivate::get(sfi)->subFocusItem = 0;
            sfi = sfi->parentItem();
        }
    }

    if (focus) {
        scopePrivate->subFocusItem = q;
        QQuickItem *sfi = scopePrivate->subFocusItem->parentItem();
1644
        while (sfi && sfi != scope) {
1645 1646 1647 1648 1649 1650 1651 1652 1653
            QQuickItemPrivate::get(sfi)->subFocusItem = q;
            sfi = sfi->parentItem();
        }
    } else {
        scopePrivate->subFocusItem = 0;
    }
}


Alan Alpert's avatar
Alan Alpert committed
1654
/*!
1655 1656
    \class QQuickItem
    \brief The QQuickItem class provides the most basic of all visual items in QML.
Alan Alpert's avatar
Alan Alpert committed
1657

1658 1659
    \inmodule QtQuick

1660
    All visual items in Qt Quick inherit from QQuickItem.  Although QQuickItem
Alan Alpert's avatar
Alan Alpert committed
1661 1662 1663 1664
    has no visual appearance, it defines all the properties that are
    common across visual items - such as the x and y position, the
    width and height, \l {anchor-layout}{anchoring} and key handling.

1665 1666 1667
    You can subclass QQuickItem to provide your own custom visual item that inherits
    these features. Note that, because it does not draw anything, QQuickItem sets the
    QGraphicsItem::ItemHasNoContents flag. If you subclass QQuickItem to create a visual
Alan Alpert's avatar
Alan Alpert committed
1668 1669 1670 1671 1672
    item, you will need to unset this flag.

*/

/*!
1673
    \qmlclass Item QQuickItem
1674
    \inherits QtObject
Alan Alpert's avatar
Alan Alpert committed
1675 1676 1677 1678
    \inqmlmodule QtQuick 2
    \ingroup qml-basic-visual-elements
    \brief The Item is the most basic of all visual items in QML.

1679
    All visual items in Qt Quick inherit from Item.  Although Item
Alan Alpert's avatar
Alan Alpert committed
1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740
    has no visual appearance, it defines all the properties that are
    common across visual items - such as the x and y position, the
    width and height, \l {anchor-layout}{anchoring} and key handling.

    Item is also useful for grouping items together.

    \qml
    Item {
        Image {
            source: "tile.png"
        }
        Image {
            x: 80
            width: 100
            height: 100
            source: "tile.png"
        }
        Image {
            x: 190
            width: 100
            height: 100
            fillMode: Image.Tile
            source: "tile.png"
        }
    }
    \endqml


    \section1 Key Handling

    Key handling is available to all Item-based visual elements via the \l {Keys}{Keys}
    attached property.  The \e Keys attached property provides basic handlers such
    as \l {Keys::onPressed}{onPressed} and \l {Keys::onReleased}{onReleased},
    as well as handlers for specific keys, such as
    \l {Keys::onCancelPressed}{onCancelPressed}.  The example below
    assigns \l {qmlfocus}{focus} to the item and handles
    the Left key via the general \e onPressed handler and the Select key via the
    onSelectPressed handler:

    \qml
    Item {
        focus: true
        Keys.onPressed: {
            if (event.key == Qt.Key_Left) {
                console.log("move left");
                event.accepted = true;
            }
        }
        Keys.onSelectPressed: console.log("Selected");
    }
    \endqml

    See the \l {Keys}{Keys} attached property for detailed documentation.

    \section1 Layout Mirroring

    Item layouts can be mirrored using the \l {LayoutMirroring}{LayoutMirroring} attached property.

*/

/*!
1741
    \fn void QQuickItem::childrenRectChanged(const QRectF &)
Alan Alpert's avatar
Alan Alpert committed
1742 1743 1744 1745
    \internal
*/

/*!
1746
    \fn void QQuickItem::baselineOffsetChanged(qreal)
Alan Alpert's avatar
Alan Alpert committed
1747 1748 1749 1750
    \internal
*/

/*!
1751
    \fn void QQuickItem::stateChanged(const QString &state)
Alan Alpert's avatar
Alan Alpert committed
1752 1753 1754 1755
    \internal
*/

/*!
1756
    \fn void QQuickItem::parentChanged(QQuickItem *)
Alan Alpert's avatar
Alan Alpert committed
1757 1758 1759 1760
    \internal
*/

/*!
1761
    \fn void QQuickItem::smoothChanged(bool)
Alan Alpert's avatar
Alan Alpert committed
1762 1763 1764 1765
    \internal
*/

/*!