Debian Codegraph @

src/LomiriGestures/ucswipearea.cpp

raw symbols SCIP
1 /*
2 * Copyright (C) 2015 Canonical Ltd.
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; version 3.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16
17 #include "ucswipearea_p_p.h"
18
19 #include <QtCore/QDebug>
20 #include <QtGui/QScreen>
21 #include <QtCore/QtMath>
22 #include <QtQuick/QQuickWindow>
23 #include <QtQuick/private/qquickwindow_p.h>
24
25 #include "touchownershipevent_p.h"
26 #include "touchregistry_p.h"
27 #include "unownedtouchevent_p.h"
28
29 UG_NAMESPACE_BEGIN
30
31 Q_LOGGING_CATEGORY(ucSwipeArea, "lomiri.components.SwipeArea", QtMsgType::QtWarningMsg)
32 Q_LOGGING_CATEGORY(ucActiveTouchInfo, "lomiri.components.SwipeArea.ActiveTouchInfo", QtMsgType::QtWarningMsg)
33
34 #define SA_TRACE(params) qCDebug(ucSwipeArea).nospace() << "[SwipeArea(" << qPrintable(objectName()) << ")] " << params
35 #define SA_WARN(params) qCWarning(ucSwipeArea).nospace() << "[SwipeArea(" << qPrintable(objectName()) << ")] " << params
36 #define TI_TRACE(params) qCDebug(ucActiveTouchInfo).nospace() << "[ActiveTouchInfo] " << params
37
38 namespace {
39 const char *statusToString(UCSwipeAreaPrivate::Status status)
40 {
41 if (status == UCSwipeAreaPrivate::WaitingForTouch) {
42 return "WaitingForTouch";
43 } else if (status == UCSwipeAreaPrivate::Undecided) {
44 return "Undecided";
45 } else {
46 return "Recognized";
47 }
48 }
49 } // namespace {
50
51 class Direction
52 {
53 public:
54 static bool isHorizontal(UCSwipeArea::Direction type)
55 {
56 return type == UCSwipeArea::Leftwards
57 || type == UCSwipeArea::Rightwards
58 || type == UCSwipeArea::Horizontal;
59 }
60
61 static bool isVertical(UCSwipeArea::Direction type)
62 {
63 return type == UCSwipeArea::Upwards
64 || type == UCSwipeArea::Downwards
65 || type == UCSwipeArea::Vertical;
66 }
67
68 static bool isPositive(UCSwipeArea::Direction type)
69 {
70 return type == UCSwipeArea::Rightwards
71 || type == UCSwipeArea::Downwards
72 || type == UCSwipeArea::Horizontal
73 || type == UCSwipeArea::Vertical;
74 }
75 };
76 /*!
77 * \qmltype SwipeArea
78 * \instantiates UCSwipeArea
79 * \inherits Item
80 * \inqmlmodule Lomiri.Components
81 * \since Lomiri.Components 1.3
82 * \ingroup lomiri-gestures
83 * \brief An area which detects axis-aligned single-finger drag gestures.
84 *
85 * The component can be used to detect gestures of a certain direction, and can
86 * grab gestures started on a component placed behind of the SwipeArea.
87 * The gesture is detected on the SwipeArea, therefore the size must be
88 * chosen carefully so it can properly detect the gesture.
89 *
90 * The gesture direction is specified by the \l direction property. The recognized
91 * and captured gesture is reported through the \l dragging property, which becomes
92 * \c true when the gesture is detected. If there was a component under the
93 * SwipeArea, the gesture will be cancelled on that component.
94 *
95 * The drag recognition is performed within the component area in the specified
96 * direction. If the drag deviates too much from this, recognition will fail,
97 * as well as if the drag or the flick is too short. Once the drag is
98 * intercepted, the gesture will be followed even after it leaves the detection area.
99 *
100 * Example:
101 * \qml
102 * import QtQuick 2.4
103 * import Lomiri.Components 1.3
104 *
105 * MainView {
106 * width: units.gu(40)
107 * height: units.gu(70)
108 *
109 * Page {
110 * title: "SwipeArea sample"
111 * SwipeArea {
112 * anchors {
113 * left: parent.left
114 * right: parent.right
115 * bottom: parent.bottom
116 * }
117 * height: units.gu(5)
118 * direction: SwipeArea.Upwards
119 * Label {
120 * text: "Drag upwards"
121 * anchors {
122 * centerIn: parent
123 * verticalOffset: parent.dragging ? parent.distance : 0
124 * }
125 * }
126 * }
127 * }
128 * }
129 * \endqml
130 * \note When used with a Flickable (or ListView, GridView) always put the
131 * SwipeArea next to the Flickable as sibling.
132 */
133 UCSwipeArea::UCSwipeArea(QQuickItem *parent)
134 : QQuickItem(*(new UCSwipeAreaPrivate), parent)
135 {
136 Q_D(UCSwipeArea);
137 d->init();
138
139 setAcceptTouchEvents(true);
140 }
141
142 /*!
143 * \qmlproperty enum SwipeArea::direction
144 * The direction in which the gesture should move in order to be recognized.
145 * \table
146 * \header
147 * \li Direction
148 * \li Description
149 * \row
150 * \li Rightwards
151 * \li Along the positive direction of the X axis
152 * \row
153 * \li Leftwards
154 * \li Along the negative direction of the X axis
155 * \row
156 * \li Downwards
157 * \li Along the positive direction of the Y axis
158 * \row
159 * \li Upwards
160 * \li Along the negative direction of the Y axis
161 * \row
162 * \li Horizontal
163 * \li Along the X axis, in any direction
164 * \row
165 * \li Vertical
166 * \li Along the Y axis, in any direction
167 * \endtable
168 */
169 UCSwipeArea::Direction UCSwipeArea::direction() const
170 {
171 Q_D(const UCSwipeArea);
172 return d->direction;
173 }
174
175 void UCSwipeArea::setDirection(Direction direction)
176 {
177 Q_D(UCSwipeArea);
178 if (direction != d->direction) {
179 d->direction = direction;
180 Q_EMIT directionChanged(d->direction);
181 }
182 }
183
184 void UCSwipeAreaPrivate::setDistanceThreshold(qreal value)
185 {
186 if (distanceThreshold != value) {
187 distanceThreshold = value;
188 distanceThresholdSquared = distanceThreshold * distanceThreshold;
189 }
190 }
191
192 void UCSwipeAreaPrivate::setCompositionTime(int value)
193 {
194 compositionTime = value;
195 }
196
197 void UCSwipeAreaPrivate::setMaxTime(int value)
198 {
199 if (maxTime != value) {
200 maxTime = value;
201 recognitionTimer->setInterval(maxTime);
202 }
203 }
204
205 void UCSwipeAreaPrivate::setRecognitionTimer(UG_PREPEND_NAMESPACE(AbstractTimer) *timer)
206 {
207 int interval = 0;
208 bool timerWasRunning = false;
209 bool wasSingleShot = false;
210 Q_Q(UCSwipeArea);
211
212 // can be null when called from the constructor
213 if (recognitionTimer) {
214 wasSingleShot = recognitionTimer->isSingleShot();
215 interval = recognitionTimer->interval();
216 timerWasRunning = recognitionTimer->isRunning();
217 if (recognitionTimer->parent() == q) {
218 delete recognitionTimer;
219 }
220 }
221
222 recognitionTimer = timer;
223 timer->setInterval(interval);
224 timer->setSingleShot(wasSingleShot);
225 QObject::connect(timer, &UG_PREPEND_NAMESPACE(AbstractTimer)::timeout,
226 q, &UCSwipeArea::rejectGesture);
227 if (timerWasRunning) {
228 recognitionTimer->start();
229 }
230 }
231
232 void UCSwipeAreaPrivate::setTimeSource(const SharedTimeSource &timeSource)
233 {
234 this->timeSource = timeSource;
235 activeTouches.m_timeSource = timeSource;
236 }
237
238 /*!
239 * \qmlproperty real SwipeArea::distance
240 * \readonly
241 * The property holds the distance of the swipe from the beginning of the gesture
242 * recognition to the current touch position.
243 */
244 qreal UCSwipeArea::distance() const
245 {
246 Q_D(const UCSwipeArea);
247 return d->sceneDistance;
248 }
249
250 /*!
251 * \qmlproperty point SwipeArea::touchPosition
252 * \readonly
253 * Position of the touch point performing the drag relative to this item.
254 */
255 QPointF UCSwipeArea::touchPosition() const
256 {
257 Q_D(const UCSwipeArea);
258 return mapFromScene(d->publicScenePos);
259 }
260
261 /*!
262 * \qmlproperty bool SwipeArea::dragging
263 * \readonly
264 * Reports whether a drag gesture is taking place.
265 */
266 bool UCSwipeArea::dragging() const
267 {
268 Q_D(const UCSwipeArea);
269 return d->status == UCSwipeAreaPrivate::Recognized;
270 }
271
272 /*!
273 * \qmlproperty bool SwipeArea::pressed
274 * \readonly
275 * Reports whether the drag area is pressed.
276 */
277 bool UCSwipeArea::pressed() const
278 {
279 Q_D(const UCSwipeArea);
280 return d->status != UCSwipeAreaPrivate::WaitingForTouch;
281 }
282
283 /*!
284 * \qmlproperty bool SwipeArea::immediateRecognition
285 * Drives whether the gesture should be recognized as soon as the touch lands on
286 * the area. With this property set it will work the same way as a MultiPointTouchArea,
287 *
288 * Defaults to false. In most cases this should not be set.
289 */
290 bool UCSwipeArea::immediateRecognition() const
291 {
292 Q_D(const UCSwipeArea);
293 return d->immediateRecognition;
294 }
295
296 void UCSwipeArea::setImmediateRecognition(bool enabled)
297 {
298 Q_D(UCSwipeArea);
299 if (d->immediateRecognition != enabled) {
300 d->immediateRecognition = enabled;
301 Q_EMIT immediateRecognitionChanged(enabled);
302 }
303 }
304
305 /*!
306 * \qmlproperty bool SwipeArea::grabGesture
307 * If true, any gestures will be grabbed and owned by the SwipeArea as usual.
308 * If false, gestures will still be reported, but events may be grabbed by
309 * another Qml object.
310 *
311 * Defaults to true. In most cases this should not be unset.
312 */
313 bool UCSwipeArea::grabGesture() const
314 {
315 Q_D(const UCSwipeArea);
316 return d->grabGesture;
317 }
318
319 void UCSwipeArea::setGrabGesture(bool enabled)
320 {
321 Q_D(UCSwipeArea);
322 if (d->grabGesture == enabled) {
323 return;
324 }
325
326 d->grabGesture = enabled;
327
328 if (!d->grabGesture && d->status == UCSwipeAreaPrivate::Undecided) {
329 TouchRegistry::instance()->removeCandidateOwnerForTouch(d->touchId, this);
330 // We still wanna know when it ends for keeping the composition time window up-to-date
331 TouchRegistry::instance()->addTouchWatcher(d->touchId, this);
332 }
333
334 Q_EMIT grabGestureChanged(enabled);
335 }
336
337 bool UCSwipeArea::event(QEvent *event)
338 {
339 Q_D(UCSwipeArea);
340 if (event->type() == TouchOwnershipEvent::touchOwnershipEventType()) {
341 d->touchOwnershipEvent(static_cast<TouchOwnershipEvent *>(event));
342 return true;
343 } else if (event->type() == UnownedTouchEvent::unownedTouchEventType()) {
344 d->unownedTouchEvent(static_cast<UnownedTouchEvent *>(event));
345 return true;
346 } else {
347 return QQuickItem::event(event);
348 }
349 }
350
351 void UCSwipeAreaPrivate::touchOwnershipEvent(TouchOwnershipEvent *event)
352 {
353 Q_Q(UCSwipeArea);
354 if (event->gained()) {
355 SA_TRACE("grabbing touch");
356 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
357 QPointerEvent *pointerEvent = event->pointerEvent();
358 const QEventPoint *point = event->point();
359 if (pointerEvent && point) {
360 pointerEvent->setExclusiveGrabber(*point, q);
361 } else {
362 SA_WARN("Receives a TouchOwnershipEvent without a QPointerEvent");
363 }
364 #else
365 QVector<int> ids;
366 ids.append(event->touchId());
367 q->grabTouchPoints(ids);
368 #endif
369 } else {
370 // We still wanna know when it ends for keeping the composition time window up-to-date
371 TouchRegistry::instance()->addTouchWatcher(touchId, q);
372
373 setStatus(WaitingForTouch);
374 }
375 }
376
377 void UCSwipeAreaPrivate::unownedTouchEvent(UnownedTouchEvent *unownedTouchEvent)
378 {
379 Q_Q(UCSwipeArea);
380 QTouchEvent *event = unownedTouchEvent->touchEvent();
381
382 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
383 Q_ASSERT(!event->touchPointStates().testFlag(QEventPoint::Pressed));
384 #else
385 Q_ASSERT(!event->touchPointStates().testFlag(Qt::TouchPointPressed));
386 #endif
387
388 SA_TRACE("Unowned " << timeSource->msecsSinceReference() << " " << event);
389
390 switch (status) {
391 case WaitingForTouch:
392 // do nothing
393 break;
394 case Undecided:
395 Q_ASSERT(q->isEnabled() && q->isVisible());
396 unownedTouchEvent_undecided(unownedTouchEvent);
397 break;
398 default: // Recognized:
399 if (!grabGesture) {
400 // Treat unowned event as if we owned it, but we are really just watching it
401 touchEvent_recognized(event);
402 }
403 break;
404 }
405
406 activeTouches.update(event);
407 }
408
409 void UCSwipeAreaPrivate::unownedTouchEvent_undecided(UnownedTouchEvent *unownedTouchEvent)
410 {
411 Q_Q(UCSwipeArea);
412 const QTouchEvent::TouchPoint *touchPoint = fetchTargetTouchPoint(unownedTouchEvent->touchEvent());
413 if (!touchPoint) {
414 qCritical() << "UCSwipeArea[status=Undecided]: touch " << touchId
415 << "missing from UnownedTouchEvent without first reaching state Qt::TouchPointReleased. "
416 "Considering it as released.";
417
418 TouchRegistry::instance()->removeCandidateOwnerForTouch(touchId, q);
419 setStatus(WaitingForTouch);
420 return;
421 }
422
423 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
424 const QPointF &touchScenePosition = touchPoint->scenePosition();
425 if (touchPoint->state() == QEventPoint::Released) {
426 #else
427 const QPointF &touchScenePosition = touchPoint->scenePos();
428 if (touchPoint->state() == Qt::TouchPointReleased) {
429 #endif
430 // touch has ended before recognition concluded
431 SA_TRACE("Touch has ended before recognition concluded");
432 TouchRegistry::instance()->removeCandidateOwnerForTouch(touchId, q);
433 setStatus(WaitingForTouch);
434 return;
435 }
436
437 previousDampedScenePos.setX(dampedScenePos.x());
438 previousDampedScenePos.setY(dampedScenePos.y());
439 dampedScenePos.update(touchScenePosition);
440
441 if (!movingInRightDirection()) {
442 SA_TRACE("Rejecting gesture because touch point is moving in the wrong direction.");
443 TouchRegistry::instance()->removeCandidateOwnerForTouch(touchId, q);
444 // We still wanna know when it ends for keeping the composition time window up-to-date
445 TouchRegistry::instance()->addTouchWatcher(touchId, q);
446 setStatus(WaitingForTouch);
447 return;
448 }
449
450 if (isWithinTouchCompositionWindow()) {
451 // There's still time for some new touch to appear and ruin our party as it would be combined
452 // with our touchId one and therefore deny the possibility of a single-finger gesture.
453 SA_TRACE("Sill within composition window. Let's wait more.");
454 return;
455 }
456
457 if (movedFarEnoughAlongGestureAxis()) {
458 if (grabGesture) {
459 TouchRegistry::instance()->requestTouchOwnership(touchId, q);
460 }
461 setStatus(Recognized);
462 updatePosition(touchScenePosition);
463 } else if (isPastMaxDistance()) {
464 SA_TRACE("Rejecting gesture because it went farther than maxDistance without getting recognized.");
465 TouchRegistry::instance()->removeCandidateOwnerForTouch(touchId, q);
466 // We still wanna know when it ends for keeping the composition time window up-to-date
467 TouchRegistry::instance()->addTouchWatcher(touchId, q);
468 setStatus(WaitingForTouch);
469 } else {
470 SA_TRACE("Didn't move far enough yet. Let's wait more.");
471 }
472 }
473
474 void UCSwipeArea::touchEvent(QTouchEvent *event)
475 {
476 // FIXME: Consider when more than one touch starts in the same event (although it's not possible
477 // with Mir's android-input). Have to track them all. Consider it a plus/bonus.
478
479 Q_D(UCSwipeArea);
480 SA_TRACE(d->timeSource->msecsSinceReference() << " " << event);
481
482 if (!isEnabled() || !isVisible()) {
483 QQuickItem::touchEvent(event);
484 return;
485 }
486
487 switch (d->status) {
488 case UCSwipeAreaPrivate::WaitingForTouch:
489 d->touchEvent_absent(event);
490 break;
491 case UCSwipeAreaPrivate::Undecided:
492 d->touchEvent_undecided(event);
493 break;
494 default: // Recognized:
495 d->touchEvent_recognized(event);
496 break;
497 }
498
499 d->activeTouches.update(event);
500 }
501
502 void UCSwipeAreaPrivate::touchEvent_absent(QTouchEvent *event)
503 {
504 // FIXME: accept/reject is for the whole event, not per touch id. See how that affects us.
505
506 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
507 if (!event->touchPointStates().testFlag(QEventPoint::Pressed)) {
508 #else
509 if (!event->touchPointStates().testFlag(Qt::TouchPointPressed)) {
510 #endif
511 // Nothing to see here. No touch starting in this event.
512 return;
513 }
514
515 // to be proven wrong, if that's the case
516 bool allGood = true;
517
518 if (isWithinTouchCompositionWindow()) {
519 // too close to the last touch start. So we consider them as starting roughly at the same time.
520 // Can't be a single-touch gesture.
521 SA_TRACE("A new touch point came in but we're still within time composition window. Ignoring it.");
522 allGood = false;
523 }
524
525 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
526 const QList<QTouchEvent::TouchPoint> &touchPoints = event->points();
527 #else
528 const QList<QTouchEvent::TouchPoint> &touchPoints = event->touchPoints();
529 #endif
530
531 const QTouchEvent::TouchPoint *newTouchPoint = nullptr;
532 for (int i = 0; i < touchPoints.count() && allGood; ++i) {
533 const QTouchEvent::TouchPoint &touchPoint = touchPoints.at(i);
534 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
535 if (touchPoint.state() == QEventPoint::Pressed) {
536 #else
537 if (touchPoint.state() == Qt::TouchPointPressed) {
538 #endif
539 if (newTouchPoint) {
540 // more than one touch starting in this QTouchEvent. Can't be a single-touch gesture
541 allGood = false;
542 } else {
543 // that's our candidate
544 newTouchPoint = &touchPoint;
545 }
546 }
547 }
548
549 if (allGood) {
550 allGood = sanityCheckRecognitionProperties();
551 if (!allGood) {
552 qWarning("UCSwipeArea: recognition properties are wrongly set. Gesture recognition"
553 " is impossible");
554 }
555 }
556
557 if (allGood) {
558 Q_ASSERT(newTouchPoint);
559 Q_Q(UCSwipeArea);
560
561 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
562 startScenePos = newTouchPoint->scenePosition();
563 #else
564 startScenePos = newTouchPoint->scenePos();
565 #endif
566 touchId = newTouchPoint->id();
567 dampedScenePos.reset(startScenePos);
568 updatePosition(startScenePos);
569
570 updateSceneDirectionVector();
571
572 if (recognitionIsDisabled()) {
573 // Behave like a dumb TouchArea
574 SA_TRACE("Gesture recognition is disabled. Requesting touch ownership immediately.");
575 setStatus(Recognized);
576 if (grabGesture) {
577 TouchRegistry::instance()->requestTouchOwnership(touchId, q);
578 event->accept();
579 } else {
580 watchPressedTouchPoints(touchPoints);
581 event->ignore();
582 }
583 } else {
584 // just monitor the touch points for now.
585 if (grabGesture) {
586 TouchRegistry::instance()->addCandidateOwnerForTouch(touchId, q);
587 } else {
588 watchPressedTouchPoints(touchPoints);
589 }
590
591 setStatus(Undecided);
592 // Let the item below have it. We will monitor it and grab it later if a gesture
593 // gets recognized.
594 event->ignore();
595 }
596 } else {
597 watchPressedTouchPoints(touchPoints);
598 event->ignore();
599 }
600 }
601
602 void UCSwipeAreaPrivate::touchEvent_undecided(QTouchEvent *event)
603 {
604 Q_ASSERT(fetchTargetTouchPoint(event) == nullptr);
605
606 // We're not interested in new touch points. We already have our candidate (touchId).
607 // But we do want to know when those new touches end for keeping the composition time
608 // window up-to-date
609 event->ignore();
610 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
611 watchPressedTouchPoints(event->points());
612 #else
613 watchPressedTouchPoints(event->touchPoints());
614 #endif
615
616 if (
617 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
618 event->touchPointStates().testFlag(QEventPoint::Pressed) &&
619 #else
620 event->touchPointStates().testFlag(Qt::TouchPointPressed) &&
621 #endif
622 isWithinTouchCompositionWindow()
623 ) {
624 // multi-finger drags are not accepted
625 SA_TRACE("Multi-finger drags are not accepted");
626
627 Q_Q(UCSwipeArea);
628 TouchRegistry::instance()->removeCandidateOwnerForTouch(touchId, q);
629 // We still wanna know when it ends for keeping the composition time window up-to-date
630 TouchRegistry::instance()->addTouchWatcher(touchId, q);
631
632 setStatus(WaitingForTouch);
633 }
634 }
635
636 void UCSwipeAreaPrivate::touchEvent_recognized(QTouchEvent *event)
637 {
638 const QTouchEvent::TouchPoint *touchPoint = fetchTargetTouchPoint(event);
639
640 if (!touchPoint) {
641 qCritical() << "UCSwipeArea[status=Recognized]: touch " << touchId
642 << "missing from QTouchEvent without first reaching state Qt::TouchPointReleased. "
643 "Considering it as released.";
644 setStatus(WaitingForTouch);
645 } else {
646 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
647 updatePosition(touchPoint->scenePosition());
648 if (touchPoint->state() == QEventPoint::Released) {
649 #else
650 updatePosition(touchPoint->scenePos());
651 if (touchPoint->state() == Qt::TouchPointReleased) {
652 #endif
653 setStatus(WaitingForTouch);
654 }
655 }
656 }
657
658 void UCSwipeAreaPrivate::watchPressedTouchPoints(const QList<QTouchEvent::TouchPoint> &touchPoints)
659 {
660 Q_Q(UCSwipeArea);
661 for (int i = 0; i < touchPoints.count(); ++i) {
662 const QTouchEvent::TouchPoint &touchPoint = touchPoints.at(i);
663 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
664 if (touchPoint.state() == QEventPoint::Pressed) {
665 #else
666 if (touchPoint.state() == Qt::TouchPointPressed) {
667 #endif
668 TouchRegistry::instance()->addTouchWatcher(touchPoint.id(), q);
669 }
670 }
671 }
672
673 bool UCSwipeAreaPrivate::recognitionIsDisabled() const
674 {
675 return immediateRecognition || (distanceThreshold <= 0 && compositionTime <= 0);
676 }
677
678 bool UCSwipeAreaPrivate::sanityCheckRecognitionProperties()
679 {
680 return recognitionIsDisabled()
681 || (distanceThreshold < maxDistance && compositionTime < maxTime);
682 }
683
684 const QTouchEvent::TouchPoint *UCSwipeAreaPrivate::fetchTargetTouchPoint(QTouchEvent *event)
685 {
686 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
687 const QList<QTouchEvent::TouchPoint> &touchPoints = event->points();
688 #else
689 const QList<QTouchEvent::TouchPoint> &touchPoints = event->touchPoints();
690 #endif
691 const QTouchEvent::TouchPoint *touchPoint = 0;
692 for (int i = 0; i < touchPoints.size(); ++i) {
693 if (touchPoints.at(i).id() == touchId) {
694 touchPoint = &touchPoints.at(i);
695 break;
696 }
697 }
698 return touchPoint;
699 }
700
701 bool UCSwipeAreaPrivate::movingInRightDirection() const
702 {
703 if (direction == UCSwipeArea::Horizontal || direction == UCSwipeArea::Vertical) {
704 return true;
705 } else {
706 QPointF movementVector(dampedScenePos.x() - previousDampedScenePos.x(),
707 dampedScenePos.y() - previousDampedScenePos.y());
708
709 qreal scalarProjection = projectOntoDirectionVector(movementVector);
710
711 return scalarProjection >= 0.;
712 }
713 }
714
715 bool UCSwipeAreaPrivate::movedFarEnoughAlongGestureAxis() const
716 {
717 if (distanceThreshold <= 0.) {
718 // distance threshold check is disabled
719 return true;
720 } else {
721 QPointF totalMovement(dampedScenePos.x() - startScenePos.x(),
722 dampedScenePos.y() - startScenePos.y());
723
724 qreal scalarProjection = projectOntoDirectionVector(totalMovement);
725
726 SA_TRACE(" movedFarEnoughAlongGestureAxis: scalarProjection=" << scalarProjection
727 << ", distanceThreshold=" << distanceThreshold);
728
729 if (direction == UCSwipeArea::Horizontal || direction == UCSwipeArea::Vertical) {
730 return qAbs(scalarProjection) > distanceThreshold;
731 } else {
732 return scalarProjection > distanceThreshold;
733 }
734 }
735 }
736
737 bool UCSwipeAreaPrivate::isPastMaxDistance() const
738 {
739 QPointF totalMovement(dampedScenePos.x() - startScenePos.x(),
740 dampedScenePos.y() - startScenePos.y());
741
742 qreal squaredDistance = totalMovement.x()*totalMovement.x() + totalMovement.y()*totalMovement.y();
743 return squaredDistance > maxDistance*maxDistance;
744 }
745
746 void UCSwipeArea::giveUpIfDisabledOrInvisible()
747 {
748 if (!isEnabled() || !isVisible()) {
749 Q_D(UCSwipeArea);
750 if (d->status == UCSwipeAreaPrivate::Undecided) {
751 TouchRegistry::instance()->removeCandidateOwnerForTouch(d->touchId, this);
752 // We still wanna know when it ends for keeping the composition time window up-to-date
753 TouchRegistry::instance()->addTouchWatcher(d->touchId, this);
754 }
755
756 if (d->status != UCSwipeAreaPrivate::WaitingForTouch) {
757 SA_TRACE("Resetting status because got disabled or made invisible");
758 d->setStatus(UCSwipeAreaPrivate::WaitingForTouch);
759 }
760 }
761 }
762
763 void UCSwipeArea::rejectGesture()
764 {
765 Q_D(UCSwipeArea);
766 if (d->status == UCSwipeAreaPrivate::Undecided) {
767 SA_TRACE("Rejecting gesture because it's taking too long to drag beyond the threshold.");
768
769 TouchRegistry::instance()->removeCandidateOwnerForTouch(d->touchId, this);
770 // We still wanna know when it ends for keeping the composition time window up-to-date
771 TouchRegistry::instance()->addTouchWatcher(d->touchId, this);
772
773 d->setStatus(UCSwipeAreaPrivate::WaitingForTouch);
774 }
775 }
776
777 void UCSwipeAreaPrivate::setStatus(Status newStatus)
778 {
779 if (newStatus == status)
780 return;
781
782 Status oldStatus = status;
783
784 if (oldStatus == Undecided) {
785 recognitionTimer->stop();
786 }
787
788 Q_Q(UCSwipeArea);
789 const bool wasDragging = q->dragging();
790 const bool wasPressed = q->pressed();
791
792 status = newStatus;
793 for (int i = 0; i < statusChangeListeners.size(); i++) {
794 statusChangeListeners[i]->swipeStatusChanged(oldStatus, status);
795 }
796
797 SA_TRACE(statusToString(oldStatus) << " -> " << statusToString(newStatus));
798
799 if (newStatus == Undecided) {
800 recognitionTimer->start();
801 }
802
803 const bool isDragging = q->dragging();
804 const bool isPressed = q->pressed();
805
806 if (isDragging != wasDragging)
807 Q_EMIT q->draggingChanged(isDragging);
808
809 if (isPressed != wasPressed)
810 Q_EMIT q->pressedChanged(isPressed);
811 }
812
813 void UCSwipeAreaPrivate::updatePosition(const QPointF &point)
814 {
815 bool xChanged = publicScenePos.x() != point.x();
816 bool yChanged = publicScenePos.y() != point.y();
817
818 // Public position should not get updated while the gesture is still being recognized
819 // (ie, Undecided status).
820 Q_ASSERT(status == WaitingForTouch || status == Recognized);
821
822 if (status == Recognized && !recognitionIsDisabled()) {
823 // When the gesture finally gets recognized, the finger will likely be
824 // reasonably far from the edge. If we made the contentX immediately
825 // follow the finger position it would be visually unpleasant as it
826 // would appear right next to the user's finger out of nowhere (ie,
827 // it would jump). Instead, we make contentX go towards the user's
828 // finger in several steps. ie., in an animated way.
829 QPointF delta = point - publicScenePos;
830 // the trick is not to go all the way (1.0) as it would cause a sudden jump
831 publicScenePos.rx() += 0.4 * delta.x();
832 publicScenePos.ry() += 0.4 * delta.y();
833 } else {
834 // no smoothing when initializing or if gesture recognition was immediate as there will
835 // be no jump.
836 publicScenePos = point;
837 }
838
839 if (xChanged || yChanged) {
840 Q_Q(UCSwipeArea);
841 Q_EMIT q->touchPositionChanged(q->touchPosition());
842
843 // handle distance change
844 QPointF totalMovement = publicScenePos - startScenePos;
845 sceneDistance = projectOntoDirectionVector(totalMovement);
846
847 Q_EMIT q->distanceChanged(sceneDistance);
848 }
849 }
850
851 bool UCSwipeAreaPrivate::isWithinTouchCompositionWindow()
852 {
853 return
854 compositionTime > 0 &&
855 !activeTouches.isEmpty() &&
856 timeSource->msecsSinceReference() <=
857 activeTouches.mostRecentStartTime() + (qint64)compositionTime;
858 }
859
860 void UCSwipeArea::itemChange(ItemChange change, const ItemChangeData &value)
861 {
862 if (change == QQuickItem::ItemSceneChange) {
863 if (value.window != nullptr) {
864 value.window->installEventFilter(TouchRegistry::instance());
865
866 // FIXME: Handle window->screen() changes (ie window changing screens)
867 Q_D(UCSwipeArea);
868 qreal pixelsPerInch = value.window->screen()->physicalDotsPerInch();
869 if (pixelsPerInch < 0) {
870 // FIXME: dpi can be negative lp#1525293
871 // It can return garbage when run in a XVFB server (Virtual Framebuffer 'fake' X server)
872 pixelsPerInch = 72;
873 }
874 d->setPixelsPerMm(pixelsPerInch / 25.4);
875 }
876 }
877 if (change == ItemVisibleHasChanged) {
878 giveUpIfDisabledOrInvisible();
879 }
880 }
881
882 void UCSwipeAreaPrivate::setPixelsPerMm(qreal pixelsPerMm)
883 {
884 dampedScenePos.setMaxDelta(1. * pixelsPerMm);
885 setDistanceThreshold(4. * pixelsPerMm);
886 maxDistance = 10. * pixelsPerMm;
887 }
888
889 //************************** ActiveTouchesInfo **************************
890
891 ActiveTouchesInfo::ActiveTouchesInfo(const SharedTimeSource &timeSource)
892 : m_timeSource(timeSource)
893 {
894 }
895
896 void ActiveTouchesInfo::update(QTouchEvent *event)
897 {
898 if (!(event->touchPointStates() & (Qt::TouchPointPressed | Qt::TouchPointReleased))) {
899 // nothing to update
900 TI_TRACE("Nothing to update");
901 return;
902 }
903
904 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
905 const QList<QTouchEvent::TouchPoint> &touchPoints = event->points();
906 #else
907 const QList<QTouchEvent::TouchPoint> &touchPoints = event->touchPoints();
908 #endif
909 for (int i = 0; i < touchPoints.count(); ++i) {
910 const QTouchEvent::TouchPoint &touchPoint = touchPoints.at(i);
911 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
912 if (touchPoint.state() == QEventPoint::Pressed) {
913 addTouchPoint(touchPoint.id());
914 } else if (touchPoint.state() == QEventPoint::Released) {
915 #else
916 if (touchPoint.state() == Qt::TouchPointPressed) {
917 addTouchPoint(touchPoint.id());
918 } else if (touchPoint.state() == Qt::TouchPointReleased) {
919 #endif
920 removeTouchPoint(touchPoint.id());
921 }
922 }
923 }
924
925 QString ActiveTouchesInfo::toString()
926 {
927 QString string = QStringLiteral("(");
928
929 {
930 QTextStream stream(&string);
931 m_touchInfoPool.forEach([&](Pool<ActiveTouchInfo>::Iterator &touchInfo) {
932 stream << "(id=" << touchInfo->id << ",startTime=" << touchInfo->startTime << ")";
933 return true;
934 });
935 }
936
937 string.append(QStringLiteral(")"));
938
939 return string;
940 }
941
942 void ActiveTouchesInfo::addTouchPoint(int touchId)
943 {
944 ActiveTouchInfo &activeTouchInfo = m_touchInfoPool.getEmptySlot();
945 activeTouchInfo.id = touchId;
946 activeTouchInfo.startTime = m_timeSource->msecsSinceReference();
947
948 TI_TRACE(qPrintable(toString()));
949 }
950
951 qint64 ActiveTouchesInfo::touchStartTime(int touchId)
952 {
953 qint64 result = -1;
954
955 m_touchInfoPool.forEach([&](Pool<ActiveTouchInfo>::Iterator &touchInfo) {
956 if (touchId == touchInfo->id) {
957 result = touchInfo->startTime;
958 return false;
959 } else {
960 return true;
961 }
962 });
963
964 Q_ASSERT(result != -1);
965 return result;
966 }
967
968 void ActiveTouchesInfo::removeTouchPoint(int touchId)
969 {
970 m_touchInfoPool.forEach([&](Pool<ActiveTouchInfo>::Iterator &touchInfo) {
971 if (touchId == touchInfo->id) {
972 m_touchInfoPool.freeSlot(touchInfo);
973 return false;
974 } else {
975 return true;
976 }
977 });
978
979 TI_TRACE(qPrintable(toString()));
980 }
981
982 qint64 ActiveTouchesInfo::mostRecentStartTime()
983 {
984 Q_ASSERT(!m_touchInfoPool.isEmpty());
985
986 qint64 highestStartTime = -1;
987
988 m_touchInfoPool.forEach([&](Pool<ActiveTouchInfo>::Iterator &activeTouchInfo) {
989 if (activeTouchInfo->startTime > highestStartTime) {
990 highestStartTime = activeTouchInfo->startTime;
991 }
992 return true;
993 });
994
995 return highestStartTime;
996 }
997
998 void UCSwipeAreaPrivate::updateSceneDirectionVector()
999 {
1000 QPointF localOrigin(0., 0.);
1001 QPointF localDirection;
1002 switch (direction) {
1003 case UCSwipeArea::Upwards:
1004 localDirection.rx() = 0.;
1005 localDirection.ry() = -1.;
1006 break;
1007 case UCSwipeArea::Downwards:
1008 case UCSwipeArea::Vertical:
1009 localDirection.rx() = 0.;
1010 localDirection.ry() = 1;
1011 break;
1012 case UCSwipeArea::Leftwards:
1013 localDirection.rx() = -1.;
1014 localDirection.ry() = 0.;
1015 break;
1016 default: // UCSwipeArea::Rightwards || Direction.Horizontal
1017 localDirection.rx() = 1.;
1018 localDirection.ry() = 0.;
1019 break;
1020 }
1021 Q_Q(UCSwipeArea);
1022 QPointF sceneOrigin = q->mapToScene(localOrigin);
1023 QPointF sceneDirection = q->mapToScene(localDirection);
1024 sceneDirectionVector = sceneDirection - sceneOrigin;
1025 }
1026
1027 qreal UCSwipeAreaPrivate::projectOntoDirectionVector(const QPointF &sceneVector) const
1028 {
1029 // same as dot product as sceneDirectionVector is a unit vector
1030 return sceneVector.x() * sceneDirectionVector.x() +
1031 sceneVector.y() * sceneDirectionVector.y();
1032 }
1033
1034 UCSwipeAreaPrivate::UCSwipeAreaPrivate()
1035 : QQuickItemPrivate()
1036 , timeSource(new RealTimeSource)
1037 , activeTouches(timeSource)
1038 , recognitionTimer(nullptr)
1039 , distanceThreshold(0)
1040 , distanceThresholdSquared(0.)
1041 , maxDistance(0.)
1042 , sceneDistance(0.)
1043 , touchId(-1)
1044 , maxTime(400)
1045 , compositionTime(60)
1046 , status(WaitingForTouch)
1047 , direction(UCSwipeArea::Rightwards)
1048 , immediateRecognition(false)
1049 , grabGesture(true)
1050 {
1051 }
1052
1053 void UCSwipeAreaPrivate::init()
1054 {
1055 Q_Q(UCSwipeArea);
1056 setRecognitionTimer(new Timer(q));
1057 recognitionTimer->setInterval(maxTime);
1058 recognitionTimer->setSingleShot(true);
1059
1060 QObject::connect(q, &QQuickItem::enabledChanged, q, &UCSwipeArea::giveUpIfDisabledOrInvisible);
1061 }
1062
1063 void UCSwipeAreaPrivate::addStatusChangeListener(UCSwipeAreaStatusListener *listener)
1064 {
1065 if (!statusChangeListeners.contains(listener)) {
1066 statusChangeListeners.append(listener);
1067 }
1068 }
1069
1070 void UCSwipeAreaPrivate::removeStatusChangeListener(UCSwipeAreaStatusListener *listener)
1071 {
1072 statusChangeListeners.removeAll(listener);
1073 }
1074
1075 UG_NAMESPACE_END