summaryrefslogtreecommitdiffstats
path: root/gfx/layers/apz/src/GestureEventListener.cpp
blob: 4300e9ba4183e35284e283d799e517b9cccdd34f (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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "GestureEventListener.h"
#include <algorithm>  // for max
#include <ostream>
#include <math.h>                    // for fabsf
#include <stddef.h>                  // for size_t
#include "AsyncPanZoomController.h"  // for AsyncPanZoomController
#include "InputBlockState.h"         // for TouchBlockState
#include "base/task.h"               // for CancelableTask, etc
#include "InputBlockState.h"         // for TouchBlockState
#include "mozilla/Assertions.h"
#include "mozilla/EventForwards.h"
#include "mozilla/StaticPrefs_apz.h"
#include "mozilla/StaticPrefs_ui.h"
#include "nsDebug.h"      // for NS_WARNING
#include "nsMathUtils.h"  // for NS_hypot

static mozilla::LazyLogModule sApzGelLog("apz.gesture");
#define GEL_LOG(...) MOZ_LOG(sApzGelLog, LogLevel::Debug, (__VA_ARGS__))

namespace mozilla {
namespace layers {

/**
 * Amount of span or focus change needed to take us from the
 * GESTURE_WAITING_PINCH state to the GESTURE_PINCH state. This is measured as
 * either a change in distance between the fingers used to compute the span
 * ratio, or the a change in position of the focus point between the two
 * fingers.
 */
static const float PINCH_START_THRESHOLD = 35.0f;

/**
 * Determines how fast a one touch pinch zooms in and out. The greater the
 * value, the faster it zooms.
 */
static const float ONE_TOUCH_PINCH_SPEED = 0.005f;

static bool sLongTapEnabled = true;

static ScreenPoint GetCurrentFocus(const MultiTouchInput& aEvent) {
  const ScreenPoint& firstTouch = aEvent.mTouches[0].mScreenPoint;
  const ScreenPoint& secondTouch = aEvent.mTouches[1].mScreenPoint;
  return (firstTouch + secondTouch) / 2;
}

static ScreenCoord GetCurrentSpan(const MultiTouchInput& aEvent) {
  const ScreenPoint& firstTouch = aEvent.mTouches[0].mScreenPoint;
  const ScreenPoint& secondTouch = aEvent.mTouches[1].mScreenPoint;
  ScreenPoint delta = secondTouch - firstTouch;
  return delta.Length();
}

ScreenCoord GestureEventListener::GetYSpanFromGestureStartPoint() {
  // use the position that began the one-touch-pinch gesture rather
  // mTouchStartPosition
  const ScreenPoint start = mOneTouchPinchStartPosition;
  const ScreenPoint& current = mTouches[0].mScreenPoint;
  return current.y - start.y;
}

static TapGestureInput CreateTapEvent(const MultiTouchInput& aTouch,
                                      TapGestureInput::TapGestureType aType) {
  return TapGestureInput(aType, aTouch.mTimeStamp,
                         aTouch.mTouches[0].mScreenPoint, aTouch.modifiers);
}

GestureEventListener::GestureEventListener(
    AsyncPanZoomController* aAsyncPanZoomController)
    : mAsyncPanZoomController(aAsyncPanZoomController),
      mState(GESTURE_NONE),
      mSpanChange(0.0f),
      mPreviousSpan(0.0f),
      mFocusChange(0.0f),
      mLastTouchInput(MultiTouchInput::MULTITOUCH_START, 0, TimeStamp(), 0),
      mLastTapInput(MultiTouchInput::MULTITOUCH_START, 0, TimeStamp(), 0),
      mLongTapTimeoutTask(nullptr),
      mMaxTapTimeoutTask(nullptr) {}

GestureEventListener::~GestureEventListener() = default;

nsEventStatus GestureEventListener::HandleInputEvent(
    const MultiTouchInput& aEvent) {
  GEL_LOG("Receiving event type %d with %zu touches in state %s\n",
          aEvent.mType, aEvent.mTouches.Length(), ToString(mState).c_str());

  nsEventStatus rv = nsEventStatus_eIgnore;

  // Cache the current event since it may become the single or long tap that we
  // send.
  mLastTouchInput = aEvent;

  switch (aEvent.mType) {
    case MultiTouchInput::MULTITOUCH_START:
      mTouches.Clear();
      // Cache every touch.
      for (size_t i = 0; i < aEvent.mTouches.Length(); i++) {
        mTouches.AppendElement(aEvent.mTouches[i]);
      }

      if (aEvent.mTouches.Length() == 1) {
        rv = HandleInputTouchSingleStart();
      } else {
        rv = HandleInputTouchMultiStart();
      }
      break;
    case MultiTouchInput::MULTITOUCH_MOVE:
      // Update the screen points of the cached touches.
      for (size_t i = 0; i < aEvent.mTouches.Length(); i++) {
        for (size_t j = 0; j < mTouches.Length(); j++) {
          if (aEvent.mTouches[i].mIdentifier == mTouches[j].mIdentifier) {
            mTouches[j].mScreenPoint = aEvent.mTouches[i].mScreenPoint;
            mTouches[j].mLocalScreenPoint =
                aEvent.mTouches[i].mLocalScreenPoint;
          }
        }
      }
      rv = HandleInputTouchMove();
      break;
    case MultiTouchInput::MULTITOUCH_END:
      // Remove the cache of the touch that ended.
      for (size_t i = 0; i < aEvent.mTouches.Length(); i++) {
        for (size_t j = 0; j < mTouches.Length(); j++) {
          if (aEvent.mTouches[i].mIdentifier == mTouches[j].mIdentifier) {
            mTouches.RemoveElementAt(j);
            break;
          }
        }
      }

      rv = HandleInputTouchEnd();
      break;
    case MultiTouchInput::MULTITOUCH_CANCEL:
      mTouches.Clear();
      rv = HandleInputTouchCancel();
      break;
  }

  return rv;
}

int32_t GestureEventListener::GetLastTouchIdentifier() const {
  if (mTouches.Length() != 1) {
    NS_WARNING(
        "GetLastTouchIdentifier() called when last touch event "
        "did not have one touch");
  }
  return mTouches.IsEmpty() ? -1 : mTouches[0].mIdentifier;
}

/* static */
void GestureEventListener::SetLongTapEnabled(bool aLongTapEnabled) {
  sLongTapEnabled = aLongTapEnabled;
}

/* static */
bool GestureEventListener::IsLongTapEnabled() { return sLongTapEnabled; }

void GestureEventListener::EnterFirstSingleTouchDown() {
  SetState(GESTURE_FIRST_SINGLE_TOUCH_DOWN);
  mTouchStartPosition = mLastTouchInput.mTouches[0].mScreenPoint;
  mTouchStartOffset = mLastTouchInput.mScreenOffset;

  if (sLongTapEnabled) {
    CreateLongTapTimeoutTask();
  }
  CreateMaxTapTimeoutTask();
}

nsEventStatus GestureEventListener::HandleInputTouchSingleStart() {
  switch (mState) {
    case GESTURE_NONE:
      EnterFirstSingleTouchDown();
      break;
    case GESTURE_FIRST_SINGLE_TOUCH_UP:
      // Bail out of any gesture that includes the first tap.
      CancelLongTapTimeoutTask();
      CancelMaxTapTimeoutTask();
      if (SecondTapIsFar()) {
        // If the second tap goes down far away from the first,
        // allow the second tap to participate in a gesture
        // (e.g. lead to a single tap, or a double tap if an additional
        // tap occurs near the same location).
        mSingleTapSent = Nothing();
        EnterFirstSingleTouchDown();
      } else {
        // Otherwise, reset the touch start position so that, if this turns into
        // a one-touch-pinch gesture, it uses the second tap's down position as
        // the focus, rather than the first tap's.
        mTouchStartPosition = mLastTouchInput.mTouches[0].mScreenPoint;
        mTouchStartOffset = mLastTouchInput.mScreenOffset;
        SetState(GESTURE_SECOND_SINGLE_TOUCH_DOWN);
      }
      break;
    default:
      NS_WARNING("Unhandled state upon single touch start");
      SetState(GESTURE_NONE);
      break;
  }

  return nsEventStatus_eIgnore;
}

nsEventStatus GestureEventListener::HandleInputTouchMultiStart() {
  nsEventStatus rv = nsEventStatus_eIgnore;

  switch (mState) {
    case GESTURE_NONE:
      SetState(GESTURE_MULTI_TOUCH_DOWN);
      break;
    case GESTURE_FIRST_SINGLE_TOUCH_DOWN:
      CancelLongTapTimeoutTask();
      CancelMaxTapTimeoutTask();
      SetState(GESTURE_MULTI_TOUCH_DOWN);
      // Prevent APZC::OnTouchStart() from handling MULTITOUCH_START event
      rv = nsEventStatus_eConsumeNoDefault;
      break;
    case GESTURE_FIRST_SINGLE_TOUCH_MAX_TAP_DOWN:
      CancelLongTapTimeoutTask();
      SetState(GESTURE_MULTI_TOUCH_DOWN);
      // Prevent APZC::OnTouchStart() from handling MULTITOUCH_START event
      rv = nsEventStatus_eConsumeNoDefault;
      break;
    case GESTURE_FIRST_SINGLE_TOUCH_UP:
      // Cancel wait for double tap
      CancelMaxTapTimeoutTask();
      [[fallthrough]];
    case GESTURE_SECOND_SINGLE_TOUCH_DOWN:
      MOZ_ASSERT(mSingleTapSent.isSome());
      if (!mSingleTapSent.value()) {
        TriggerSingleTapConfirmedEvent();
      }
      mSingleTapSent = Nothing();
      SetState(GESTURE_MULTI_TOUCH_DOWN);
      // Prevent APZC::OnTouchStart() from handling MULTITOUCH_START event
      rv = nsEventStatus_eConsumeNoDefault;
      break;
    case GESTURE_LONG_TOUCH_DOWN:
      SetState(GESTURE_MULTI_TOUCH_DOWN);
      break;
    case GESTURE_MULTI_TOUCH_DOWN:
    case GESTURE_PINCH:
      // Prevent APZC::OnTouchStart() from handling MULTITOUCH_START event
      rv = nsEventStatus_eConsumeNoDefault;
      break;
    default:
      NS_WARNING("Unhandled state upon multitouch start");
      SetState(GESTURE_NONE);
      break;
  }

  return rv;
}

bool GestureEventListener::MoveDistanceExceeds(ScreenCoord aThreshold) const {
  ExternalPoint start = AsyncPanZoomController::ToExternalPoint(
      mTouchStartOffset, mTouchStartPosition);
  ExternalPoint end = AsyncPanZoomController::ToExternalPoint(
      mLastTouchInput.mScreenOffset, mLastTouchInput.mTouches[0].mScreenPoint);
  return (start - end).Length() > aThreshold;
}

bool GestureEventListener::MoveDistanceIsLarge() const {
  return MoveDistanceExceeds(mAsyncPanZoomController->GetTouchStartTolerance());
}

bool GestureEventListener::SecondTapIsFar() const {
  // Allow a little more room here, because the is actually lifting their finger
  // off the screen before replacing it, and that tends to have more error than
  // wiggling the finger while on the screen.
  return MoveDistanceExceeds(mAsyncPanZoomController->GetSecondTapTolerance());
}

nsEventStatus GestureEventListener::HandleInputTouchMove() {
  nsEventStatus rv = nsEventStatus_eIgnore;

  switch (mState) {
    case GESTURE_NONE:
      // Ignore this input signal as the corresponding events get handled by
      // APZC
      break;

    case GESTURE_LONG_TOUCH_DOWN:
      if (MoveDistanceIsLarge()) {
        // So that we don't fire a long-tap-up if the user moves around after a
        // long-tap
        SetState(GESTURE_NONE);
      }
      break;

    case GESTURE_FIRST_SINGLE_TOUCH_DOWN:
    case GESTURE_FIRST_SINGLE_TOUCH_MAX_TAP_DOWN: {
      // If we move too much, bail out of the tap.
      if (MoveDistanceIsLarge()) {
        CancelLongTapTimeoutTask();
        CancelMaxTapTimeoutTask();
        mSingleTapSent = Nothing();
        SetState(GESTURE_NONE);
      }
      break;
    }

    // The user has performed a double tap, but not lifted her finger.
    case GESTURE_SECOND_SINGLE_TOUCH_DOWN: {
      // If touch has moved noticeably (within StaticPrefs::apz_max_tap_time()),
      // change state.
      if (MoveDistanceIsLarge()) {
        mSingleTapSent = Nothing();
        if (!mAsyncPanZoomController->AllowOneTouchPinch()) {
          SetState(GESTURE_NONE);
          break;
        }

        SetState(GESTURE_ONE_TOUCH_PINCH);

        ScreenCoord currentSpan = 1.0f;
        ScreenPoint currentFocus = mTouchStartPosition;

        // save the position that the one-touch-pinch gesture actually begins
        mOneTouchPinchStartPosition = mLastTouchInput.mTouches[0].mScreenPoint;

        PinchGestureInput pinchEvent(
            PinchGestureInput::PINCHGESTURE_START, PinchGestureInput::ONE_TOUCH,
            mLastTouchInput.mTimeStamp, mLastTouchInput.mScreenOffset,
            currentFocus, currentSpan, currentSpan, mLastTouchInput.modifiers);

        rv = mAsyncPanZoomController->HandleGestureEvent(pinchEvent);

        mPreviousSpan = currentSpan;
        mPreviousFocus = currentFocus;
      }
      break;
    }

    case GESTURE_MULTI_TOUCH_DOWN: {
      if (mLastTouchInput.mTouches.Length() < 2) {
        NS_WARNING(
            "Wrong input: less than 2 moving points in "
            "GESTURE_MULTI_TOUCH_DOWN state");
        break;
      }

      ScreenCoord currentSpan = GetCurrentSpan(mLastTouchInput);
      ScreenPoint currentFocus = GetCurrentFocus(mLastTouchInput);

      mSpanChange += fabsf(currentSpan - mPreviousSpan);
      mFocusChange += (currentFocus - mPreviousFocus).Length();
      if (mSpanChange > PINCH_START_THRESHOLD ||
          mFocusChange > PINCH_START_THRESHOLD) {
        SetState(GESTURE_PINCH);
        PinchGestureInput pinchEvent(
            PinchGestureInput::PINCHGESTURE_START, PinchGestureInput::TOUCH,
            mLastTouchInput.mTimeStamp, mLastTouchInput.mScreenOffset,
            currentFocus, currentSpan, currentSpan, mLastTouchInput.modifiers);

        rv = mAsyncPanZoomController->HandleGestureEvent(pinchEvent);
      } else {
        // Prevent APZC::OnTouchMove from processing a move event when two
        // touches are active
        rv = nsEventStatus_eConsumeNoDefault;
      }

      mPreviousSpan = currentSpan;
      mPreviousFocus = currentFocus;
      break;
    }

    case GESTURE_PINCH: {
      if (mLastTouchInput.mTouches.Length() < 2) {
        NS_WARNING(
            "Wrong input: less than 2 moving points in GESTURE_PINCH state");
        // Prevent APZC::OnTouchMove() from handling this wrong input
        rv = nsEventStatus_eConsumeNoDefault;
        break;
      }

      ScreenCoord currentSpan = GetCurrentSpan(mLastTouchInput);

      PinchGestureInput pinchEvent(
          PinchGestureInput::PINCHGESTURE_SCALE, PinchGestureInput::TOUCH,
          mLastTouchInput.mTimeStamp, mLastTouchInput.mScreenOffset,
          GetCurrentFocus(mLastTouchInput), currentSpan, mPreviousSpan,
          mLastTouchInput.modifiers);

      rv = mAsyncPanZoomController->HandleGestureEvent(pinchEvent);
      mPreviousSpan = currentSpan;

      break;
    }

    case GESTURE_ONE_TOUCH_PINCH: {
      ScreenCoord currentSpan = GetYSpanFromGestureStartPoint();
      float effectiveSpan =
          1.0f + (fabsf(currentSpan.value) * ONE_TOUCH_PINCH_SPEED);
      ScreenPoint currentFocus = mTouchStartPosition;

      // Invert zoom.
      if (currentSpan.value < 0) {
        effectiveSpan = 1.0f / effectiveSpan;
      }

      PinchGestureInput pinchEvent(
          PinchGestureInput::PINCHGESTURE_SCALE, PinchGestureInput::ONE_TOUCH,
          mLastTouchInput.mTimeStamp, mLastTouchInput.mScreenOffset,
          currentFocus, effectiveSpan, mPreviousSpan,
          mLastTouchInput.modifiers);

      rv = mAsyncPanZoomController->HandleGestureEvent(pinchEvent);
      mPreviousSpan = effectiveSpan;

      break;
    }

    default:
      NS_WARNING("Unhandled state upon touch move");
      SetState(GESTURE_NONE);
      break;
  }

  return rv;
}

nsEventStatus GestureEventListener::HandleInputTouchEnd() {
  // We intentionally do not pass apzc return statuses up since
  // it may cause apzc stay in the touching state even after
  // gestures are completed (please see Bug 1013378 for reference).

  nsEventStatus rv = nsEventStatus_eIgnore;

  switch (mState) {
    case GESTURE_NONE:
      // GEL doesn't have a dedicated state for PANNING handled in APZC thus
      // ignore.
      break;

    case GESTURE_FIRST_SINGLE_TOUCH_DOWN: {
      CancelLongTapTimeoutTask();
      CancelMaxTapTimeoutTask();
      nsEventStatus tapupStatus = mAsyncPanZoomController->HandleGestureEvent(
          CreateTapEvent(mLastTouchInput, TapGestureInput::TAPGESTURE_UP));
      mSingleTapSent = Some(tapupStatus != nsEventStatus_eIgnore);
      SetState(GESTURE_FIRST_SINGLE_TOUCH_UP);
      CreateMaxTapTimeoutTask();
      break;
    }

    case GESTURE_SECOND_SINGLE_TOUCH_DOWN: {
      MOZ_ASSERT(mSingleTapSent.isSome());
      mAsyncPanZoomController->HandleGestureEvent(CreateTapEvent(
          mLastTouchInput, mSingleTapSent.value()
                               ? TapGestureInput::TAPGESTURE_SECOND
                               : TapGestureInput::TAPGESTURE_DOUBLE));
      mSingleTapSent = Nothing();
      SetState(GESTURE_NONE);
      break;
    }

    case GESTURE_FIRST_SINGLE_TOUCH_MAX_TAP_DOWN:
      CancelLongTapTimeoutTask();
      SetState(GESTURE_NONE);
      TriggerSingleTapConfirmedEvent();
      break;

    case GESTURE_LONG_TOUCH_DOWN: {
      SetState(GESTURE_NONE);
      mAsyncPanZoomController->HandleGestureEvent(
          CreateTapEvent(mLastTouchInput, TapGestureInput::TAPGESTURE_LONG_UP));
      break;
    }

    case GESTURE_MULTI_TOUCH_DOWN:
      if (mTouches.Length() < 2) {
        SetState(GESTURE_NONE);
      }
      break;

    case GESTURE_PINCH:
      if (mTouches.Length() < 2) {
        SetState(GESTURE_NONE);
        PinchGestureInput::PinchGestureType type =
            PinchGestureInput::PINCHGESTURE_END;
        ScreenPoint point;
        if (mTouches.Length() == 1) {
          // As user still keeps one finger down the event's focus point should
          // contain meaningful data.
          type = PinchGestureInput::PINCHGESTURE_FINGERLIFTED;
          point = mTouches[0].mScreenPoint;
        }
        PinchGestureInput pinchEvent(type, PinchGestureInput::TOUCH,
                                     mLastTouchInput.mTimeStamp,
                                     mLastTouchInput.mScreenOffset, point, 1.0f,
                                     1.0f, mLastTouchInput.modifiers);
        mAsyncPanZoomController->HandleGestureEvent(pinchEvent);
      }

      rv = nsEventStatus_eConsumeNoDefault;

      break;

    case GESTURE_ONE_TOUCH_PINCH: {
      SetState(GESTURE_NONE);
      PinchGestureInput pinchEvent(
          PinchGestureInput::PINCHGESTURE_END, PinchGestureInput::ONE_TOUCH,
          mLastTouchInput.mTimeStamp, mLastTouchInput.mScreenOffset,
          ScreenPoint(), 1.0f, 1.0f, mLastTouchInput.modifiers);
      mAsyncPanZoomController->HandleGestureEvent(pinchEvent);

      rv = nsEventStatus_eConsumeNoDefault;

      break;
    }

    default:
      NS_WARNING("Unhandled state upon touch end");
      SetState(GESTURE_NONE);
      break;
  }

  return rv;
}

nsEventStatus GestureEventListener::HandleInputTouchCancel() {
  mSingleTapSent = Nothing();
  SetState(GESTURE_NONE);
  CancelMaxTapTimeoutTask();
  CancelLongTapTimeoutTask();
  return nsEventStatus_eIgnore;
}

void GestureEventListener::HandleInputTimeoutLongTap() {
  MOZ_ASSERT(mState != GESTURE_SECOND_SINGLE_TOUCH_DOWN);
  GEL_LOG("Running long-tap timeout task in state %s\n",
          ToString(mState).c_str());

  mLongTapTimeoutTask = nullptr;

  switch (mState) {
    case GESTURE_FIRST_SINGLE_TOUCH_DOWN:
      // just in case MaxTapTime > ContextMenuDelay cancel MaxTap timer
      // and fall through
      CancelMaxTapTimeoutTask();
      [[fallthrough]];
    case GESTURE_FIRST_SINGLE_TOUCH_MAX_TAP_DOWN: {
      SetState(GESTURE_LONG_TOUCH_DOWN);
      mAsyncPanZoomController->HandleGestureEvent(
          CreateTapEvent(mLastTouchInput, TapGestureInput::TAPGESTURE_LONG));
      break;
    }
    default:
      NS_WARNING("Unhandled state upon long tap timeout");
      SetState(GESTURE_NONE);
      break;
  }
}

void GestureEventListener::HandleInputTimeoutMaxTap(bool aDuringFastFling) {
  MOZ_ASSERT(mState != GESTURE_SECOND_SINGLE_TOUCH_DOWN);
  GEL_LOG("Running max-tap timeout task in state %s\n",
          ToString(mState).c_str());

  mMaxTapTimeoutTask = nullptr;

  if (mState == GESTURE_FIRST_SINGLE_TOUCH_DOWN) {
    SetState(GESTURE_FIRST_SINGLE_TOUCH_MAX_TAP_DOWN);
  } else if (mState == GESTURE_FIRST_SINGLE_TOUCH_UP) {
    MOZ_ASSERT(mSingleTapSent.isSome());
    if (!aDuringFastFling && !mSingleTapSent.value()) {
      TriggerSingleTapConfirmedEvent();
    }
    mSingleTapSent = Nothing();
    SetState(GESTURE_NONE);
  } else {
    NS_WARNING("Unhandled state upon MAX_TAP timeout");
    SetState(GESTURE_NONE);
  }
}

void GestureEventListener::TriggerSingleTapConfirmedEvent() {
  mAsyncPanZoomController->HandleGestureEvent(
      CreateTapEvent(mLastTapInput, TapGestureInput::TAPGESTURE_CONFIRMED));
}

void GestureEventListener::SetState(GestureState aState) {
  GEL_LOG("State change from %s to %s", ToString(mState).c_str(),
          ToString(aState).c_str());
  mState = aState;

  if (mState == GESTURE_NONE) {
    mSpanChange = 0.0f;
    mPreviousSpan = 0.0f;
    mFocusChange = 0.0f;
  } else if (mState == GESTURE_MULTI_TOUCH_DOWN) {
    mPreviousSpan = GetCurrentSpan(mLastTouchInput);
    mPreviousFocus = GetCurrentFocus(mLastTouchInput);
  }
}

void GestureEventListener::CancelLongTapTimeoutTask() {
  MOZ_ASSERT(mState != GESTURE_SECOND_SINGLE_TOUCH_DOWN);

  if (mLongTapTimeoutTask) {
    mLongTapTimeoutTask->Cancel();
    mLongTapTimeoutTask = nullptr;
  }
}

void GestureEventListener::CreateLongTapTimeoutTask() {
  RefPtr<CancelableRunnable> task = NewCancelableRunnableMethod(
      "layers::GestureEventListener::HandleInputTimeoutLongTap", this,
      &GestureEventListener::HandleInputTimeoutLongTap);

  mLongTapTimeoutTask = task;

  TouchBlockState* block =
      mAsyncPanZoomController->GetInputQueue()->GetCurrentTouchBlock();
  MOZ_ASSERT(block);
  long alreadyElapsed =
      static_cast<long>(block->GetTimeSinceBlockStart().ToMilliseconds());
  long remainingDelay =
      StaticPrefs::ui_click_hold_context_menus_delay() - alreadyElapsed;
  mAsyncPanZoomController->PostDelayedTask(task.forget(),
                                           std::max(0L, remainingDelay));
}

void GestureEventListener::CancelMaxTapTimeoutTask() {
  MOZ_ASSERT(mState != GESTURE_SECOND_SINGLE_TOUCH_DOWN);

  if (mState == GESTURE_FIRST_SINGLE_TOUCH_MAX_TAP_DOWN) {
    // being in this state means the timer has just been triggered
    return;
  }

  if (mMaxTapTimeoutTask) {
    mMaxTapTimeoutTask->Cancel();
    mMaxTapTimeoutTask = nullptr;
  }
}

void GestureEventListener::CreateMaxTapTimeoutTask() {
  mLastTapInput = mLastTouchInput;

  TouchBlockState* block =
      mAsyncPanZoomController->GetInputQueue()->GetCurrentTouchBlock();
  MOZ_ASSERT(block);
  RefPtr<CancelableRunnable> task = NewCancelableRunnableMethod<bool>(
      "layers::GestureEventListener::HandleInputTimeoutMaxTap", this,
      &GestureEventListener::HandleInputTimeoutMaxTap,
      block->IsDuringFastFling());

  mMaxTapTimeoutTask = task;

  long alreadyElapsed =
      static_cast<long>(block->GetTimeSinceBlockStart().ToMilliseconds());
  long remainingDelay = StaticPrefs::apz_max_tap_time() - alreadyElapsed;
  mAsyncPanZoomController->PostDelayedTask(task.forget(),
                                           std::max(0L, remainingDelay));
}

std::ostream& operator<<(std::ostream& os,
                         GestureEventListener::GestureState aState) {
  switch (aState) {
    case GestureEventListener::GESTURE_NONE:
      os << "GESTURE_NONE";
      break;
    case GestureEventListener::GESTURE_FIRST_SINGLE_TOUCH_DOWN:
      os << "GESTURE_FIRST_SINGLE_TOUCH_DOWN";
      break;
    case GestureEventListener::GESTURE_FIRST_SINGLE_TOUCH_MAX_TAP_DOWN:
      os << "GESTURE_FIRST_SINGLE_TOUCH_MAX_TAP_DOWN";
      break;
    case GestureEventListener::GESTURE_FIRST_SINGLE_TOUCH_UP:
      os << "GESTURE_FIRST_SINGLE_TOUCH_UP";
      break;
    case GestureEventListener::GESTURE_SECOND_SINGLE_TOUCH_DOWN:
      os << "GESTURE_SECOND_SINGLE_TOUCH_DOWN";
      break;
    case GestureEventListener::GESTURE_LONG_TOUCH_DOWN:
      os << "GESTURE_LONG_TOUCH_DOWN";
      break;
    case GestureEventListener::GESTURE_MULTI_TOUCH_DOWN:
      os << "GESTURE_MULTI_TOUCH_DOWN";
      break;
    case GestureEventListener::GESTURE_PINCH:
      os << "GESTURE_PINCH";
      break;
    case GestureEventListener::GESTURE_ONE_TOUCH_PINCH:
      os << "GESTURE_ONE_TOUCH_PINCH";
      break;
  }

  return os;
}

}  // namespace layers
}  // namespace mozilla