aboutsummaryrefslogtreecommitdiffstats
path: root/src/quick/handlers/qquicktaphandler.cpp
blob: aeda9a0357e3818cb9b4e5c1d259a1ed41d0651b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
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
174
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
/****************************************************************************
**
** Copyright (C) 2017 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtQuick module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qquicktaphandler_p.h"
#include <qpa/qplatformtheme.h>
#include <private/qguiapplication_p.h>
#include <QtGui/qstylehints.h>

QT_BEGIN_NAMESPACE

Q_LOGGING_CATEGORY(lcTapHandler, "qt.quick.handler.tap")

qreal QQuickTapHandler::m_multiTapInterval(0.0);
// single tap distance is the same as the drag threshold
int QQuickTapHandler::m_mouseMultiClickDistanceSquared(-1);
int QQuickTapHandler::m_touchMultiTapDistanceSquared(-1);

/*!
    \qmltype TapHandler
    \instantiates QQuickTapHandler
    \inqmlmodule QtQuick
    \ingroup qtquick-handlers
    \brief Handler for taps and clicks

    TapHandler is a handler for taps on a touchscreen or clicks on a mouse.

    Detection of a valid tap gesture depends on \l gesturePolicy.
    Note that buttons (such as QPushButton) are often implemented not to care
    whether the press and release occur close together: if you press the button
    and then change your mind, you need to drag all the way off the edge of the
    button in order to cancel the click.  Therefore the default
    \l gesturePolicy is \l ReleaseWithinBounds.  If you want to require
    that the press and release are close together in both space and time,
    set it to \l DragThreshold.

    For multi-tap gestures (double-tap, triple-tap etc.), the distance moved
    must not exceed QPlatformTheme::MouseDoubleClickDistance with mouse and
    QPlatformTheme::TouchDoubleTapDistance with touch, and the time between
    taps must not exceed QStyleHints::mouseDoubleClickInterval().

    \sa MouseArea
*/

QQuickTapHandler::QQuickTapHandler(QObject *parent)
    : QQuickPointerSingleHandler(parent)
    , m_pressed(false)
    , m_gesturePolicy(ReleaseWithinBounds)
    , m_tapCount(0)
    , m_longPressThreshold(-1)
    , m_lastTapTimestamp(0.0)
{
    setAcceptedButtons(Qt::LeftButton);
    if (m_mouseMultiClickDistanceSquared < 0) {
        m_multiTapInterval = qApp->styleHints()->mouseDoubleClickInterval() / 1000.0;
        m_mouseMultiClickDistanceSquared = QGuiApplicationPrivate::platformTheme()->
                    themeHint(QPlatformTheme::MouseDoubleClickDistance).toInt();
        m_mouseMultiClickDistanceSquared *= m_mouseMultiClickDistanceSquared;
        m_touchMultiTapDistanceSquared = QGuiApplicationPrivate::platformTheme()->
                    themeHint(QPlatformTheme::TouchDoubleTapDistance).toInt();
        m_touchMultiTapDistanceSquared *= m_touchMultiTapDistanceSquared;
    }
}

QQuickTapHandler::~QQuickTapHandler()
{
}

static bool dragOverThreshold(QQuickEventPoint *point)
{
    QPointF delta = point->scenePos() - point->scenePressPos();
    return (QQuickWindowPrivate::dragOverThreshold(delta.x(), Qt::XAxis, point) ||
            QQuickWindowPrivate::dragOverThreshold(delta.y(), Qt::YAxis, point));
}

bool QQuickTapHandler::wantsEventPoint(QQuickEventPoint *point)
{
    // If the user has not violated any constraint, it could be a tap.
    // Otherwise we want to give up the grab so that a competing handler
    // (e.g. DragHandler) gets a chance to take over.
    // Don't forget to emit released in case of a cancel.
    bool ret = false;
    switch (point->state()) {
    case QQuickEventPoint::Pressed:
    case QQuickEventPoint::Released:
        ret = parentContains(point);
        break;
    default: // update or stationary
        switch (m_gesturePolicy) {
        case DragThreshold:
            ret = !dragOverThreshold(point);
            break;
        case WithinBounds:
            ret = parentContains(point);
            break;
        case ReleaseWithinBounds:
            ret = point->pointId() == pointId();
            break;
        }
        break;
    }
    // If this is the grabber, returning false from this function will cancel the grab,
    // so onGrabChanged(this, CancelGrabExclusive, point) and setPressed(false) will be called.
    // But when m_gesturePolicy is DragThreshold, we don't get an exclusive grab, but
    // we still don't want to be pressed anymore.
    if (!ret && point->pointId() == pointId())
        setPressed(false, true, point);
    return ret;
}

void QQuickTapHandler::handleEventPoint(QQuickEventPoint *point)
{
    switch (point->state()) {
    case QQuickEventPoint::Pressed:
        setPressed(true, false, point);
        break;
    case QQuickEventPoint::Released:
        if ((point->pointerEvent()->buttons() & acceptedButtons()) == Qt::NoButton)
            setPressed(false, false, point);
        break;
    default:
        break;
    }
}

/*!
    \qmlproperty longPressThreshold

    The time in seconds that an event point must be pressed in order to
    trigger a long press gesture and emit the \l longPressed() signal.
    If the point is released before this time limit, a tap can be detected
    if the \l gesturePolicy constraint is satisfied. The default value is
    QStyleHints::mousePressAndHoldInterval() converted to seconds.
*/
qreal QQuickTapHandler::longPressThreshold() const
{
    return longPressThresholdMilliseconds() / 1000.0;
}

void QQuickTapHandler::setLongPressThreshold(qreal longPressThreshold)
{
    int ms = qRound(longPressThreshold * 1000);
    if (m_longPressThreshold == ms)
        return;

    m_longPressThreshold = ms;
    emit longPressThresholdChanged();
}

int QQuickTapHandler::longPressThresholdMilliseconds() const
{
    return (m_longPressThreshold < 0 ? QGuiApplication::styleHints()->mousePressAndHoldInterval() : m_longPressThreshold);
}

void QQuickTapHandler::timerEvent(QTimerEvent *event)
{
    if (event->timerId() == m_longPressTimer.timerId()) {
        m_longPressTimer.stop();
        qCDebug(lcTapHandler) << objectName() << "longPressed";
        emit longPressed();
    }
}

/*!
    \qmlproperty gesturePolicy

    The spatial constraint for a tap or long press gesture to be recognized,
    in addition to the constraint that the release must occur before
    \l longPressThreshold has elapsed. If these constraints are not satisfied,
    the \l tapped signal is not emitted, and \l tapCount is not incremented.
    If the spatial constraint is violated, \l isPressed transitions immediately
    from true to false, regardless of the time held.

    \c DragThreshold means that the event point must not move significantly.
    If the mouse, finger or stylus moves past the system-wide drag threshold
    (QStyleHints::startDragDistance), the tap gesture is canceled, even if
    the button or finger is still pressed. This policy can be useful whenever
    TapHandler needs to cooperate with other pointer handlers (for example
    \l DragHandler), because in this case TapHandler will never grab.

    \c WithinBounds means that if the event point leaves the bounds of the
    \l target item, the tap gesture is canceled. The TapHandler will grab on
    press, but release the grab as soon as the boundary constraint is no
    longer satisfied.

    \c ReleaseWithinBounds (the default value) means that at the time of release
    (the mouse button is released or the finger is lifted), if the event point
    is outside the bounds of the \l target item, a tap gesture is not
    recognized. This is the default value, because it corresponds to typical
    button behavior: you can cancel a click by dragging outside the button, and
    you can also change your mind by dragging back inside the button before
    release. Note that it's necessary for TapHandler to grab on press and
    retain it until release (greedy grab) in order to detect this gesture.
*/
void QQuickTapHandler::setGesturePolicy(QQuickTapHandler::GesturePolicy gesturePolicy)
{
    if (m_gesturePolicy == gesturePolicy)
        return;

    m_gesturePolicy = gesturePolicy;
    emit gesturePolicyChanged();
}

/*!
    \qmlproperty pressed

    This property will be true whenever the mouse or touch point is pressed,
    and any movement since the press is compliant with the current
    \l gesturePolicy. When the event point is released or the policy is
    violated, pressed will change to false.
*/
void QQuickTapHandler::setPressed(bool press, bool cancel, QQuickEventPoint *point)
{
    if (m_pressed != press) {
        qCDebug(lcTapHandler) << objectName() << "pressed" << m_pressed << "->" << press << (cancel ? "CANCEL" : "") << point;
        m_pressed = press;
        connectPreRenderSignal(press);
        updateTimeHeld();
        if (press) {
            m_longPressTimer.start(longPressThresholdMilliseconds(), this);
            m_holdTimer.start();
        } else {
            m_longPressTimer.stop();
            m_holdTimer.invalidate();
        }
        if (press) {
            // on press, grab before emitting changed signals
            if (m_gesturePolicy == DragThreshold)
                setPassiveGrab(point, press);
            else
                setExclusiveGrab(point, press);
        }
        if (!cancel && !press) {
            if (point->timeHeld() < longPressThreshold()) {
                // Assuming here that pointerEvent()->timestamp() is in ms.
                qreal ts = point->pointerEvent()->timestamp() / 1000.0;
                if (ts - m_lastTapTimestamp < m_multiTapInterval &&
                        QVector2D(point->scenePos() - m_lastTapPos).lengthSquared() <
                        (point->pointerEvent()->device()->type() == QQuickPointerDevice::Mouse ?
                         m_mouseMultiClickDistanceSquared : m_touchMultiTapDistanceSquared))
                    ++m_tapCount;
                else
                    m_tapCount = 1;
                qCDebug(lcTapHandler) << objectName() << "tapped" << m_tapCount << "times";
                emit tapped(point);
                emit tapCountChanged();
                m_lastTapTimestamp = ts;
                m_lastTapPos = point->scenePos();
            } else {
                qCDebug(lcTapHandler) << objectName() << "tap threshold" << longPressThreshold() << "exceeded:" << point->timeHeld();
            }
        }
        emit pressedChanged();
        if (!press) {
            // on release, ungrab after emitting changed signals
            if (m_gesturePolicy == DragThreshold)
                setPassiveGrab(point, press);
            else
                setExclusiveGrab(point, press);
        }
    }
}

void QQuickTapHandler::onGrabChanged(QQuickPointerHandler *grabber, QQuickEventPoint::GrabState stateChange, QQuickEventPoint *point)
{
    QQuickPointerSingleHandler::onGrabChanged(grabber, stateChange, point);
    if (grabber == this && stateChange == QQuickEventPoint::CancelGrabExclusive)
        setPressed(false, true, point);
}

void QQuickTapHandler::connectPreRenderSignal(bool conn)
{
    if (conn)
        connect(parentItem()->window(), &QQuickWindow::beforeSynchronizing, this, &QQuickTapHandler::updateTimeHeld);
    else
        disconnect(parentItem()->window(), &QQuickWindow::beforeSynchronizing, this, &QQuickTapHandler::updateTimeHeld);
}

void QQuickTapHandler::updateTimeHeld()
{
    emit timeHeldChanged();
}

/*!
    \qmlproperty tapCount

    The number of taps which have occurred within the time and space
    constraints to be considered a single gesture.  For example, to detect
    a double-tap, you can write

    \qml
    Rectangle {
        width: 100; height: 30
        signal doubleTap
        TapHandler {
            acceptedButtons: Qt.AllButtons
            onTapped: if (tapCount == 2) doubleTap()
        }
    }
*/

/*!
    \qmlproperty timeHeld

    The amount of time in seconds that a pressed point has been held, without
    moving beyond the drag threshold. It will be updated at least once per
    frame rendered, which enables rendering an animation showing the progress
    towards an action which will be triggered by a long-press. It is also
    possible to trigger one of a series of actions depending on how long the
    press is held.

    A value less than zero means no point is being held within this handler's Item.
*/

QT_END_NAMESPACE