summaryrefslogtreecommitdiffstats
path: root/src/gui/kernel/qeventpoint.cpp
blob: 4030ebce0c02ce4838e3eb7ea7109867f6d69e6f (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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
// Copyright (C) 2020 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

#include "qeventpoint.h"
#include "private/qeventpoint_p.h"
#include "private/qpointingdevice_p.h"

QT_BEGIN_NAMESPACE

Q_LOGGING_CATEGORY(lcPointerVel, "qt.pointer.velocity")
Q_LOGGING_CATEGORY(lcEPDetach, "qt.pointer.eventpoint.detach")

QT_DEFINE_QESDP_SPECIALIZATION_DTOR(QEventPointPrivate)

/*! \class QEventPoint
    \brief The QEventPoint class provides information about a point in a QPointerEvent.
    \since 6.0
    \inmodule QtGui
*/

/*!
    \enum QEventPoint::State

    Specifies the state of this event point.

    \value  Unknown
            Unknown state.

    \value  Stationary
            The event point did not move.

    \value  Pressed
            The touch point or button is pressed.

    \value  Updated
            The event point was updated.

    \value  Released
            The touch point or button was released.
*/

/*!
    \internal
    Constructs an invalid event point with the given \a id and the \a device
    from which it originated.

    This acts as a default constructor in usages like QMap<int, QEventPoint>,
    as in qgraphicsscene_p.h.
*/
QEventPoint::QEventPoint(int id, const QPointingDevice *device)
    : d(new QEventPointPrivate(id, device)) {}

/*!
    Constructs an event point with the given \a pointId, \a state,
    \a scenePosition and \a globalPosition.
*/
QEventPoint::QEventPoint(int pointId, State state, const QPointF &scenePosition, const QPointF &globalPosition)
    : d(new QEventPointPrivate(pointId, state, scenePosition, globalPosition)) {}

/*!
    Constructs an event point by making a shallow copy of \a other.
*/
QEventPoint::QEventPoint(const QEventPoint &other) noexcept = default;

/*!
    Assigns \a other to this event point and returns a reference to this
    event point.
*/
QEventPoint &QEventPoint::operator=(const QEventPoint &other) noexcept = default;

/*!
    \fn QEventPoint::QEventPoint(QEventPoint &&other) noexcept

    Constructs an event point by moving \a other.
*/

/*!
    \fn QEventPoint &QEventPoint::operator=(QEventPoint &&other) noexcept

    Move-assigns \a other to this event point instance.
*/

/*!
    Returns \c true if this event point is equal to \a other, otherwise
    return \c false.
*/
bool QEventPoint::operator==(const QEventPoint &other) const noexcept
{
    if (d == other.d)
        return true;
    if (!d || !other.d)
        return false;
    return *d == *other.d;
}

/*!
    \fn bool QEventPoint::operator!=(const QEventPoint &other) const noexcept

    Returns \c true if this event point is not equal to \a other, otherwise
    return \c false.
*/

/*!
    Destroys the event point.
*/
QEventPoint::~QEventPoint() = default;

/*! \fn QPointF QEventPoint::pos() const
    \deprecated [6.0] Use position() instead.

    Returns the position of this point, relative to the widget
    or item that received the event.
*/

/*!
    \property QEventPoint::position
    \brief the position of this point.

    The position is relative to the widget or item that received the event.
*/
QPointF QEventPoint::position() const
{ return d ? d->pos : QPointF(); }

/*!
    \property QEventPoint::pressPosition
    \brief the position at which this point was pressed.

    The position is relative to the widget or item that received the event.

    \sa position
*/
QPointF QEventPoint::pressPosition() const
{ return d ? d->globalPressPos - d->globalPos + d->pos : QPointF(); }

/*!
    \property QEventPoint::grabPosition
    \brief the position at which this point was grabbed.

    The position is relative to the widget or item that received the event.

    \sa position
*/
QPointF QEventPoint::grabPosition() const
{ return d ? d->globalGrabPos - d->globalPos + d->pos : QPointF(); }

/*!
    \property QEventPoint::lastPosition
    \brief the position of this point from the previous press or move event.

    The position is relative to the widget or item that received the event.

    \sa position, pressPosition
*/
QPointF QEventPoint::lastPosition() const
{ return d ? d->globalLastPos - d->globalPos + d->pos : QPointF(); }

/*!
    \property QEventPoint::scenePosition
    \brief the scene position of this point.

    The scene position is the position relative to QQuickWindow if handled in QQuickItem::event(),
    in QGraphicsScene coordinates if handled by an override of QGraphicsItem::touchEvent(),
    or the window position in widget applications.

    \sa scenePressPosition, position, globalPosition
*/
QPointF QEventPoint::scenePosition() const
{ return d ? d->scenePos : QPointF(); }

/*!
    \property QEventPoint::scenePressPosition
    \brief the scene position at which this point was pressed.

    The scene position is the position relative to QQuickWindow if handled in QQuickItem::event(),
    in QGraphicsScene coordinates if handled by an override of QGraphicsItem::touchEvent(),
    or the window position in widget applications.

    \sa scenePosition, pressPosition, globalPressPosition
*/
QPointF QEventPoint::scenePressPosition() const
{ return d ? d->globalPressPos - d->globalPos + d->scenePos : QPointF(); }

/*!
    \property QEventPoint::sceneGrabPosition
    \brief the scene position at which this point was grabbed.

    The scene position is the position relative to QQuickWindow if handled in QQuickItem::event(),
    in QGraphicsScene coordinates if handled by an override of QGraphicsItem::touchEvent(),
    or the window position in widget applications.

    \sa scenePosition, grabPosition, globalGrabPosition
*/
QPointF QEventPoint::sceneGrabPosition() const
{ return d ? d->globalGrabPos - d->globalPos + d->scenePos : QPointF(); }

/*!
    \property QEventPoint::sceneLastPosition
    \brief the scene position of this point from the previous press or move event.

    The scene position is the position relative to QQuickWindow if handled in QQuickItem::event(),
    in QGraphicsScene coordinates if handled by an override of QGraphicsItem::touchEvent(),
    or the window position in widget applications.

    \sa scenePosition, scenePressPosition
*/
QPointF QEventPoint::sceneLastPosition() const
{ return d ? d->globalLastPos - d->globalPos + d->scenePos : QPointF(); }

/*!
    \property QEventPoint::globalPosition
    \brief the global position of this point.

    The global position is relative to the screen or virtual desktop.

    \sa globalPressPosition, position, scenePosition
*/
QPointF QEventPoint::globalPosition() const
{ return d ? d->globalPos : QPointF(); }

/*!
    \property QEventPoint::globalPressPosition
    \brief the global position at which this point was pressed.

    The global position is relative to the screen or virtual desktop.

    \sa globalPosition, pressPosition, scenePressPosition
*/
QPointF QEventPoint::globalPressPosition() const
{ return d ? d->globalPressPos : QPointF(); }

/*!
    \property QEventPoint::globalGrabPosition
    \brief the global position at which this point was grabbed.

    The global position is relative to the screen or virtual desktop.

    \sa globalPosition, grabPosition, sceneGrabPosition
*/
QPointF QEventPoint::globalGrabPosition() const
{ return d ? d->globalGrabPos : QPointF(); }

/*!
    \property QEventPoint::globalLastPosition
    \brief the global position of this point from the previous press or move event.

    The global position is relative to the screen or virtual desktop.

    \sa globalPosition, lastPosition, sceneLastPosition
*/
QPointF QEventPoint::globalLastPosition() const
{ return d ? d->globalLastPos : QPointF(); }

/*!
    \property QEventPoint::velocity
    \brief a velocity vector, in units of pixels per second, in the coordinate.
    system of the screen or desktop.

    \note If the device's capabilities include QInputDevice::Velocity, it means
    velocity comes from the operating system (perhaps the touch hardware or
    driver provides it). But usually the \c Velocity capability is not set,
    indicating that the velocity is calculated by Qt, using a simple Kalman
    filter to provide a smoothed average velocity rather than an instantaneous
    value. Effectively it tells how fast and in what direction the user has
    been dragging this point over the last few events, with the most recent
    event having the strongest influence.

    \sa QInputDevice::capabilities(), QInputEvent::device()
*/
QVector2D QEventPoint::velocity() const
{ return d ? d->velocity : QVector2D(); }

/*!
    \property QEventPoint::state
    \brief the current state of the event point.
*/
QEventPoint::State QEventPoint::state() const
{ return d ? d->state : QEventPoint::State::Unknown; }

/*!
    \property QEventPoint::device
    \brief the pointing device from which this event point originates.
*/
const QPointingDevice *QEventPoint::device() const
{ return d ? d->device : nullptr; }

/*!
    \property QEventPoint::id
    \brief the ID number of this event point.

    \note Do not assume that ID numbers start at zero or that they are
          sequential. Such an assumption is often false due to the way
          the underlying drivers work.
*/
int QEventPoint::id() const
{ return d ? d->pointId : -1; }

/*!
    \property QEventPoint::uniqueId
    \brief the unique ID of this point or token, if any.

    It is often invalid (see \l {QPointingDeviceUniqueId::isValid()} {isValid()}),
    because touchscreens cannot uniquely identify fingers.

    When it comes from a QTabletEvent, it identifies the serial number of the
    stylus in use.

    It may identify a specific token (fiducial object) when the TUIO driver is
    in use with a touchscreen that supports them.
*/
QPointingDeviceUniqueId QEventPoint::uniqueId() const
{ return d ? d->uniqueId : QPointingDeviceUniqueId(); }

/*!
    \property QEventPoint::timestamp
    \brief the most recent time at which this point was included in a QPointerEvent.

    \sa QPointerEvent::timestamp()
*/
ulong QEventPoint::timestamp() const
{ return d ? d->timestamp : 0; }

/*!
    \property QEventPoint::lastTimestamp
    \brief the time from the previous QPointerEvent that contained this point.

    \sa globalLastPosition
*/
ulong QEventPoint::lastTimestamp() const
{ return d ? d->lastTimestamp : 0; }

/*!
    \property QEventPoint::pressTimestamp
    \brief the most recent time at which this point was pressed.

    \sa timestamp
*/
ulong QEventPoint::pressTimestamp() const
{ return d ? d->pressTimestamp : 0; }

/*!
    \property QEventPoint::timeHeld
    \brief the duration, in milliseconds, since this point was pressed and not released.

    \sa pressTimestamp, timestamp
*/
qreal QEventPoint::timeHeld() const
{ return d ? (d->timestamp - d->pressTimestamp) / qreal(1000) : 0.0; }

/*!
    \property QEventPoint::pressure
    \brief the pressure of this point.

    The return value is in the range \c 0.0 to \c 1.0.
*/
qreal QEventPoint::pressure() const
{ return d ? d->pressure : 0.0; }

/*!
    \property QEventPoint::rotation
    \brief the angular orientation of this point.

    The return value is in degrees, where zero (the default) indicates the finger,
    token or stylus is pointing upwards, a negative angle means it's rotated to the
    left, and a positive angle means it's rotated to the right.
    Most touchscreens do not detect rotation, so zero is the most common value.
*/
qreal QEventPoint::rotation() const
{ return d ? d->rotation : 0.0; }

/*!
    \property QEventPoint::ellipseDiameters
    \brief the width and height of the bounding ellipse of the touch point.

    The return value is in logical pixels. Most touchscreens do not detect the
    shape of the contact point, and no mice or tablet devices can detect it,
    so a null size is the most common value. On some touchscreens the diameters
    may be nonzero and always equal (the ellipse is approximated as a circle).
*/
QSizeF QEventPoint::ellipseDiameters() const
{ return d ? d->ellipseDiameters : QSizeF(); }

/*!
    \property QEventPoint::accepted
    \brief the accepted state of the event point.

    In widget-based applications, this property is not used, as it's only meaningful
    for a widget to accept or reject a complete QInputEvent.

    In Qt Quick however, it's normal for an Item or Event Handler to accept
    only the individual points in a QTouchEvent that are actually participating
    in a gesture, while other points can be delivered to other items or
    handlers. For the sake of consistency, that applies to any QPointerEvent;
    and delivery is done only when all points in a QPointerEvent have been
    accepted.

    \sa QEvent::accepted
*/
void QEventPoint::setAccepted(bool accepted)
{
    if (d)
        d->accept = accepted;
}

bool QEventPoint::isAccepted() const
{ return d ? d->accept : false; }


/*!
    \fn QPointF QEventPoint::normalizedPos() const
    \deprecated [6.0] Use normalizedPosition() instead.
*/

/*!
    Returns the normalized position of this point.

    The coordinates are calculated by transforming globalPosition() into the
    space of QInputDevice::availableVirtualGeometry(), i.e. \c (0, 0) is the
    top-left corner and \c (1, 1) is the bottom-right corner.

    \sa globalPosition
*/
QPointF QEventPoint::normalizedPosition() const
{
    if (!d)
        return {};

    auto geom = d->device->availableVirtualGeometry();
    if (geom.isNull())
        return QPointF();
    return (globalPosition() - geom.topLeft()) / geom.width();
}

/*!
    \deprecated [6.0] Use globalPressPosition() instead.

    Returns the normalized press position of this point.
*/
QPointF QEventPoint::startNormalizedPos() const
{
    if (!d)
        return {};

    auto geom = d->device->availableVirtualGeometry();
    if (geom.isNull())
        return QPointF();
    return (globalPressPosition() - geom.topLeft()) / geom.width();
}

/*!
    \deprecated [6.0] Use globalLastPosition() instead.

    Returns the normalized position of this point from the previous press or
    move event.

    The coordinates are normalized to QInputDevice::availableVirtualGeometry(),
    i.e. \c (0, 0) is the top-left corner and \c (1, 1) is the bottom-right corner.

    \sa normalizedPosition(), globalPressPosition()
*/
QPointF QEventPoint::lastNormalizedPos() const
{
    if (!d)
        return {};

    auto geom = d->device->availableVirtualGeometry();
    if (geom.isNull())
        return QPointF();
    return (globalLastPosition() - geom.topLeft()) / geom.width();
}


/*! \internal
    This class is explicitly shared, which means if you construct an event and
    then the point(s) that it holds are modified before the event is delivered,
    the event will be seen to hold the modified points. The workaround is that
    any code which modifies an eventpoint that could already be included in an
    event, or code that wants to save an eventpoint for later, has
    responsibility to detach before calling any setters, so as to hold and
    modify an independent copy. (The independent copy can then be used in a
    subsequent event.)
*/
void QMutableEventPoint::detach(QEventPoint &p)
{
    if (p.d)
        p.d.detach();
    else
        p.d.reset(new QEventPointPrivate(-1, nullptr));
}

/*! \internal
    Update \a target state from the \a other point, assuming that \a target
    contains state from the previous event and \a other contains new
    values that came in from a device.

    That is: global position and other valuators will be updated, but
    the following properties will not be updated:

    \list
    \li properties that are not likely to be set after a fresh touchpoint
    has been received from a device
    \li properties that should be persistent between events (such as grabbers)
    \endlist
*/
void QMutableEventPoint::update(const QEventPoint &other, QEventPoint &target)
{
    detach(target);
    setPressure(target, other.pressure());

    switch (other.state()) {
    case QEventPoint::State::Pressed:
        setGlobalPressPosition(target, other.globalPosition());
        setGlobalLastPosition(target, other.globalPosition());
        if (target.pressure() < 0)
            setPressure(target, 1);
        break;

    case QEventPoint::State::Released:
        if (target.globalPosition() != other.globalPosition())
            setGlobalLastPosition(target, target.globalPosition());
        setPressure(target, 0);
        break;

    default: // update or stationary
        if (target.globalPosition() != other.globalPosition())
            setGlobalLastPosition(target, target.globalPosition());
        if (target.pressure() < 0)
            setPressure(target, 1);
        break;
    }

    setState(target, other.state());
    setPosition(target, other.position());
    setScenePosition(target, other.scenePosition());
    setGlobalPosition(target, other.globalPosition());
    setEllipseDiameters(target, other.ellipseDiameters());
    setRotation(target, other.rotation());
    setVelocity(target, other.velocity());
}

/*! \internal
    Set the timestamp from the event that updated this point's positions,
    and calculate a new value for velocity().

    The velocity calculation is done here because none of the QPointerEvent
    subclass constructors take the timestamp directly, and because
    QGuiApplication traditionally constructs an event first and then sets its
    timestamp (see for example QGuiApplicationPrivate::processMouseEvent()).

    This function looks up the corresponding instance in QPointingDevicePrivate::activePoints,
    and assumes that its timestamp() still holds the previous time when this point
    was updated, its velocity() holds this point's last-known velocity, and
    its globalPosition() and globalLastPosition() hold this point's current
    and previous positions, respectively.  We assume timestamps are in milliseconds.

    The velocity calculation is skipped if the platform has promised to
    provide velocities already by setting the QInputDevice::Velocity capability.
*/
void QMutableEventPoint::setTimestamp(QEventPoint &p, ulong t)
{
    // On mouse press, if the mouse has moved from its last-known location,
    // QGuiApplicationPrivate::processMouseEvent() sends first a mouse move and
    // then a press. Both events will get the same timestamp. So we need to set
    // the press timestamp and position even when the timestamp isn't advancing,
    // but skip setting lastTimestamp and velocity because those need a time delta.
    if (p.d) {
        if (p.state() == QEventPoint::State::Pressed) {
            p.d->pressTimestamp = t;
            p.d->globalPressPos = p.d->globalPos;
        }
        if (p.d->timestamp == t)
            return;
    }
    detach(p);
    if (p.device()) {
        // get the persistent instance out of QPointingDevicePrivate::activePoints
        // (which sometimes might be the same as this instance)
        QEventPointPrivate *pd = QPointingDevicePrivate::get(
                    const_cast<QPointingDevice *>(p.d->device))->pointById(p.id())->eventPoint.d.get();
        if (t > pd->timestamp) {
            pd->lastTimestamp = pd->timestamp;
            pd->timestamp = t;
            if (p.state() == QEventPoint::State::Pressed)
                pd->pressTimestamp = t;
            if (pd->lastTimestamp > 0 && !p.device()->capabilities().testFlag(QInputDevice::Capability::Velocity)) {
                // calculate instantaneous velocity according to time and distance moved since the previous point
                QVector2D newVelocity = QVector2D(pd->globalPos - pd->globalLastPos) / (t - pd->lastTimestamp) * 1000;
                // VERY simple kalman filter: does a weighted average
                // where the older velocities get less and less significant
                static const float KalmanGain = 0.7f;
                pd->velocity = newVelocity * KalmanGain + pd->velocity * (1.0f - KalmanGain);
                qCDebug(lcPointerVel) << "velocity" << newVelocity << "filtered" << pd->velocity <<
                                         "based on movement" << pd->globalLastPos << "->" << pd->globalPos <<
                                         "over time" << pd->lastTimestamp << "->" << pd->timestamp;
            }
            if (p.d != pd) {
                p.d->lastTimestamp = pd->lastTimestamp;
                p.d->velocity = pd->velocity;
            }
        }
    }
    p.d->timestamp = t;
}

/*!
    \fn void QMutableEventPoint::setPosition(QPointF pos)
    \internal

    Sets the localized position.
    Often events need to be localized before delivery to specific widgets or
    items. This can be done directly, or in a copy (for which we have a copy
    constructor), depending on whether the original point needs to be retained.
    Usually it's calculated by mapping scenePosition() to the target anyway.
*/

QT_END_NAMESPACE

#include "moc_qeventpoint.cpp"