multitap.dart 13.4 KB
Newer Older
Hixie's avatar
Hixie committed
1 2 3 4 5
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';
6
import 'dart:ui' show Offset;
Hixie's avatar
Hixie committed
7 8

import 'arena.dart';
9
import 'binding.dart';
Hixie's avatar
Hixie committed
10 11 12 13
import 'constants.dart';
import 'events.dart';
import 'pointer_router.dart';
import 'recognizer.dart';
14
import 'tap.dart';
Hixie's avatar
Hixie committed
15

16 17
/// Signature for callback when the user has tapped the screen at the same
/// location twice in quick succession.
Hixie's avatar
Hixie committed
18 19
typedef void GestureDoubleTapCallback();

20 21
/// Signature used by [MultiTapGestureRecognizer] for when a pointer that might
/// cause a tap has contacted the screen at a particular location.
22
typedef void GestureMultiTapDownCallback(int pointer, TapDownDetails details);
23 24 25

/// Signature used by [MultiTapGestureRecognizer] for when a pointer that will
/// trigger a tap has stopped contacting the screen at a particular location.
26
typedef void GestureMultiTapUpCallback(int pointer, TapUpDetails details);
27 28

/// Signature used by [MultiTapGestureRecognizer] for when a tap has occurred.
Hixie's avatar
Hixie committed
29
typedef void GestureMultiTapCallback(int pointer);
30 31 32

/// Signature for when the pointer that previously triggered a
/// [GestureMultiTapDownCallback] will not end up causing a tap.
Hixie's avatar
Hixie committed
33
typedef void GestureMultiTapCancelCallback(int pointer);
Hixie's avatar
Hixie committed
34 35 36 37

/// TapTracker helps track individual tap sequences as part of a
/// larger gesture.
class _TapTracker {
Ian Hickson's avatar
Ian Hickson committed
38
  _TapTracker({ PointerDownEvent event, this.entry })
Hixie's avatar
Hixie committed
39
    : pointer = event.pointer,
Ian Hickson's avatar
Ian Hickson committed
40
      _initialPosition = event.position;
Hixie's avatar
Hixie committed
41 42 43

  final int pointer;
  final GestureArenaEntry entry;
44
  final Offset _initialPosition;
Hixie's avatar
Hixie committed
45 46 47

  bool _isTrackingPointer = false;

48
  void startTrackingPointer(PointerRoute route) {
Hixie's avatar
Hixie committed
49 50
    if (!_isTrackingPointer) {
      _isTrackingPointer = true;
51
      GestureBinding.instance.pointerRouter.addRoute(pointer, route);
Hixie's avatar
Hixie committed
52 53 54
    }
  }

55
  void stopTrackingPointer(PointerRoute route) {
Hixie's avatar
Hixie committed
56 57
    if (_isTrackingPointer) {
      _isTrackingPointer = false;
58
      GestureBinding.instance.pointerRouter.removeRoute(pointer, route);
Hixie's avatar
Hixie committed
59 60 61
    }
  }

Ian Hickson's avatar
Ian Hickson committed
62
  bool isWithinTolerance(PointerEvent event, double tolerance) {
63
    final Offset offset = event.position - _initialPosition;
Hixie's avatar
Hixie committed
64 65 66 67
    return offset.distance <= tolerance;
  }
}

68 69
/// Recognizes when the user has tapped the screen at the same location twice in
/// quick succession.
70
class DoubleTapGestureRecognizer extends GestureRecognizer {
71 72 73
  /// Create a gesture recognizer for double taps.
  DoubleTapGestureRecognizer({ Object debugOwner }) : super(debugOwner: debugOwner);

Hixie's avatar
Hixie committed
74 75 76 77 78 79 80 81 82 83 84 85 86 87
  // Implementation notes:
  // The double tap recognizer can be in one of four states. There's no
  // explicit enum for the states, because they are already captured by
  // the state of existing fields.  Specifically:
  // Waiting on first tap: In this state, the _trackers list is empty, and
  // _firstTap is null.
  // First tap in progress: In this state, the _trackers list contains all
  // the states for taps that have begun but not completed. This list can
  // have more than one entry if two pointers begin to tap.
  // Waiting on second tap: In this state, one of the in-progress taps has
  // completed successfully. The _trackers list is again empty, and
  // _firstTap records the successful tap.
  // Second tap in progress: Much like the "first tap in progress" state, but
  // _firstTap is non-null.  If a tap completes successfully while in this
88
  // state, the callback is called and the state is reset.
Hixie's avatar
Hixie committed
89 90 91 92 93
  // There are various other scenarios that cause the state to reset:
  // - All in-progress taps are rejected (by time, distance, pointercancel, etc)
  // - The long timer between taps expires
  // - The gesture arena decides we have been rejected wholesale

94 95
  /// Called when the user has tapped the screen at the same location twice in
  /// quick succession.
Hixie's avatar
Hixie committed
96
  GestureDoubleTapCallback onDoubleTap;
Hixie's avatar
Hixie committed
97 98 99

  Timer _doubleTapTimer;
  _TapTracker _firstTap;
100
  final Map<int, _TapTracker> _trackers = <int, _TapTracker>{};
Hixie's avatar
Hixie committed
101

102
  @override
Ian Hickson's avatar
Ian Hickson committed
103
  void addPointer(PointerEvent event) {
Florian Loitsch's avatar
Florian Loitsch committed
104
    // Ignore out-of-bounds second taps.
Hixie's avatar
Hixie committed
105
    if (_firstTap != null &&
106
        !_firstTap.isWithinTolerance(event, kDoubleTapSlop))
Hixie's avatar
Hixie committed
107 108
      return;
    _stopDoubleTapTimer();
109
    final _TapTracker tracker = new _TapTracker(
Hixie's avatar
Hixie committed
110
      event: event,
111
      entry: GestureBinding.instance.gestureArena.add(event.pointer, this)
Hixie's avatar
Hixie committed
112 113
    );
    _trackers[event.pointer] = tracker;
114
    tracker.startTrackingPointer(_handleEvent);
Hixie's avatar
Hixie committed
115 116
  }

117
  void _handleEvent(PointerEvent event) {
118
    final _TapTracker tracker = _trackers[event.pointer];
Hixie's avatar
Hixie committed
119
    assert(tracker != null);
Ian Hickson's avatar
Ian Hickson committed
120 121 122 123 124 125 126
    if (event is PointerUpEvent) {
      if (_firstTap == null)
        _registerFirstTap(tracker);
      else
        _registerSecondTap(tracker);
    } else if (event is PointerMoveEvent) {
      if (!tracker.isWithinTolerance(event, kDoubleTapTouchSlop))
Hixie's avatar
Hixie committed
127
        _reject(tracker);
Ian Hickson's avatar
Ian Hickson committed
128 129
    } else if (event is PointerCancelEvent) {
      _reject(tracker);
Hixie's avatar
Hixie committed
130 131 132
    }
  }

133
  @override
134
  void acceptGesture(int pointer) { }
Hixie's avatar
Hixie committed
135

136
  @override
Hixie's avatar
Hixie committed
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
  void rejectGesture(int pointer) {
    _TapTracker tracker = _trackers[pointer];
    // If tracker isn't in the list, check if this is the first tap tracker
    if (tracker == null &&
        _firstTap != null &&
        _firstTap.pointer == pointer)
      tracker = _firstTap;
    // If tracker is still null, we rejected ourselves already
    if (tracker != null)
      _reject(tracker);
  }

  void _reject(_TapTracker tracker) {
    _trackers.remove(tracker.pointer);
    tracker.entry.resolve(GestureDisposition.rejected);
    _freezeTracker(tracker);
    // If the first tap is in progress, and we've run out of taps to track,
    // reset won't have any work to do.  But if we're in the second tap, we need
    // to clear intermediate state.
    if (_firstTap != null &&
        (_trackers.isEmpty || tracker == _firstTap))
      _reset();
  }

161
  @override
Hixie's avatar
Hixie committed
162 163
  void dispose() {
    _reset();
164
    super.dispose();
Hixie's avatar
Hixie committed
165 166 167 168 169 170
  }

  void _reset() {
    _stopDoubleTapTimer();
    if (_firstTap != null) {
      // Note, order is important below in order for the resolve -> reject logic
Florian Loitsch's avatar
Florian Loitsch committed
171
      // to work properly.
172
      final _TapTracker tracker = _firstTap;
Hixie's avatar
Hixie committed
173 174
      _firstTap = null;
      _reject(tracker);
175
      GestureBinding.instance.gestureArena.release(tracker.pointer);
Hixie's avatar
Hixie committed
176 177 178 179 180 181
    }
    _clearTrackers();
  }

  void _registerFirstTap(_TapTracker tracker) {
    _startDoubleTapTimer();
182
    GestureBinding.instance.gestureArena.hold(tracker.pointer);
Hixie's avatar
Hixie committed
183 184 185 186 187 188 189 190 191 192 193 194 195 196
    // Note, order is important below in order for the clear -> reject logic to
    // work properly.
    _freezeTracker(tracker);
    _trackers.remove(tracker.pointer);
    _clearTrackers();
    _firstTap = tracker;
  }

  void _registerSecondTap(_TapTracker tracker) {
    _firstTap.entry.resolve(GestureDisposition.accepted);
    tracker.entry.resolve(GestureDisposition.accepted);
    _freezeTracker(tracker);
    _trackers.remove(tracker.pointer);
    if (onDoubleTap != null)
197
      invokeCallback<Null>('onDoubleTap', onDoubleTap); // ignore: STRONG_MODE_INVALID_CAST_FUNCTION_EXPR, https://github.com/dart-lang/sdk/issues/27504
Hixie's avatar
Hixie committed
198 199 200 201
    _reset();
  }

  void _clearTrackers() {
202
    final List<_TapTracker> localTrackers = new List<_TapTracker>.from(_trackers.values);
Hixie's avatar
Hixie committed
203 204 205 206 207 208
    for (_TapTracker tracker in localTrackers)
      _reject(tracker);
    assert(_trackers.isEmpty);
  }

  void _freezeTracker(_TapTracker tracker) {
209
    tracker.stopTrackingPointer(_handleEvent);
Hixie's avatar
Hixie committed
210 211 212
  }

  void _startDoubleTapTimer() {
213
    _doubleTapTimer ??= new Timer(kDoubleTapTimeout, _reset);
Hixie's avatar
Hixie committed
214 215 216 217 218 219 220 221 222
  }

  void _stopDoubleTapTimer() {
    if (_doubleTapTimer != null) {
      _doubleTapTimer.cancel();
      _doubleTapTimer = null;
    }
  }

223
  @override
224
  String get debugDescription => 'double tap';
Hixie's avatar
Hixie committed
225 226 227 228 229 230 231 232
}

/// TapGesture represents a full gesture resulting from a single tap sequence,
/// as part of a [MultiTapGestureRecognizer]. Tap gestures are passive, meaning
/// that they will not preempt any other arena member in play.
class _TapGesture extends _TapTracker {

  _TapGesture({
233
    this.gestureRecognizer,
Ian Hickson's avatar
Ian Hickson committed
234
    PointerEvent event,
Hixie's avatar
Hixie committed
235
    Duration longTapDelay
236
  }) : _lastPosition = event.position,
Ian Hickson's avatar
Ian Hickson committed
237 238
       super(
    event: event,
239
    entry: GestureBinding.instance.gestureArena.add(event.pointer, gestureRecognizer)
Ian Hickson's avatar
Ian Hickson committed
240
  ) {
241
    startTrackingPointer(handleEvent);
Hixie's avatar
Hixie committed
242 243 244
    if (longTapDelay > Duration.ZERO) {
      _timer = new Timer(longTapDelay, () {
        _timer = null;
245
        gestureRecognizer._dispatchLongTap(event.pointer, _lastPosition);
Hixie's avatar
Hixie committed
246 247
      });
    }
Hixie's avatar
Hixie committed
248 249 250 251 252
  }

  final MultiTapGestureRecognizer gestureRecognizer;

  bool _wonArena = false;
Hixie's avatar
Hixie committed
253 254
  Timer _timer;

255 256
  Offset _lastPosition;
  Offset _finalPosition;
Hixie's avatar
Hixie committed
257

Ian Hickson's avatar
Ian Hickson committed
258
  void handleEvent(PointerEvent event) {
Hixie's avatar
Hixie committed
259
    assert(event.pointer == pointer);
Ian Hickson's avatar
Ian Hickson committed
260
    if (event is PointerMoveEvent) {
Hixie's avatar
Hixie committed
261 262 263 264
      if (!isWithinTolerance(event, kTouchSlop))
        cancel();
      else
        _lastPosition = event.position;
Ian Hickson's avatar
Ian Hickson committed
265
    } else if (event is PointerCancelEvent) {
Hixie's avatar
Hixie committed
266
      cancel();
Ian Hickson's avatar
Ian Hickson committed
267
    } else if (event is PointerUpEvent) {
268
      stopTrackingPointer(handleEvent);
Hixie's avatar
Hixie committed
269 270 271 272 273
      _finalPosition = event.position;
      _check();
    }
  }

274
  @override
275
  void stopTrackingPointer(PointerRoute route) {
Hixie's avatar
Hixie committed
276 277
    _timer?.cancel();
    _timer = null;
278
    super.stopTrackingPointer(route);
Hixie's avatar
Hixie committed
279 280
  }

Hixie's avatar
Hixie committed
281 282 283 284 285 286
  void accept() {
    _wonArena = true;
    _check();
  }

  void reject() {
287
    stopTrackingPointer(handleEvent);
288
    gestureRecognizer._dispatchCancel(pointer);
Hixie's avatar
Hixie committed
289 290 291 292 293 294 295 296
  }

  void cancel() {
    // If we won the arena already, then entry is resolved, so resolving
    // again is a no-op. But we still need to clean up our own state.
    if (_wonArena)
      reject();
    else
297
      entry.resolve(GestureDisposition.rejected); // eventually calls reject()
Hixie's avatar
Hixie committed
298 299 300 301
  }

  void _check() {
    if (_wonArena && _finalPosition != null)
302
      gestureRecognizer._dispatchTap(pointer, _finalPosition);
Hixie's avatar
Hixie committed
303 304 305
  }
}

306 307 308 309 310 311 312 313 314
/// Recognizes taps on a per-pointer basis.
///
/// [MultiTapGestureRecognizer] considers each sequence of pointer events that
/// could constitute a tap independently of other pointers: For example, down-1,
/// down-2, up-1, up-2 produces two taps, on up-1 and up-2.
///
/// See also:
///
///  * [TapGestureRecognizer]
315
class MultiTapGestureRecognizer extends GestureRecognizer {
316 317 318 319
  /// Creates a multi-tap gesture recognizer.
  ///
  /// The [longTapDelay] defaults to [Duration.ZERO], which means
  /// [onLongTapDown] is called immediately after [onTapDown].
Hixie's avatar
Hixie committed
320
  MultiTapGestureRecognizer({
321 322 323
    this.longTapDelay: Duration.ZERO,
    Object debugOwner,
  }) : super(debugOwner: debugOwner);
Hixie's avatar
Hixie committed
324

325 326
  /// A pointer that might cause a tap has contacted the screen at a particular
  /// location.
Hixie's avatar
Hixie committed
327
  GestureMultiTapDownCallback onTapDown;
328 329 330

  /// A pointer that will trigger a tap has stopped contacting the screen at a
  /// particular location.
Hixie's avatar
Hixie committed
331
  GestureMultiTapUpCallback onTapUp;
332 333

  /// A tap has occurred.
Hixie's avatar
Hixie committed
334
  GestureMultiTapCallback onTap;
335 336 337

  /// The pointer that previously triggered [onTapDown] will not end up causing
  /// a tap.
Hixie's avatar
Hixie committed
338
  GestureMultiTapCancelCallback onTapCancel;
339 340

  /// The amount of time between [onTapDown] and [onLongTapDown].
Hixie's avatar
Hixie committed
341
  Duration longTapDelay;
342 343 344

  /// A pointer that might cause a tap is still in contact with the screen at a
  /// particular location after [longTapDelay].
Hixie's avatar
Hixie committed
345
  GestureMultiTapDownCallback onLongTapDown;
Hixie's avatar
Hixie committed
346

347
  final Map<int, _TapGesture> _gestureMap = <int, _TapGesture>{};
Hixie's avatar
Hixie committed
348

349
  @override
Ian Hickson's avatar
Ian Hickson committed
350
  void addPointer(PointerEvent event) {
Hixie's avatar
Hixie committed
351 352 353
    assert(!_gestureMap.containsKey(event.pointer));
    _gestureMap[event.pointer] = new _TapGesture(
      gestureRecognizer: this,
Hixie's avatar
Hixie committed
354 355
      event: event,
      longTapDelay: longTapDelay
Hixie's avatar
Hixie committed
356 357
    );
    if (onTapDown != null)
358
      invokeCallback<Null>('onTapDown', () => onTapDown(event.pointer, new TapDownDetails(globalPosition: event.position))); // ignore: STRONG_MODE_INVALID_CAST_FUNCTION_EXPR, https://github.com/dart-lang/sdk/issues/27504
Hixie's avatar
Hixie committed
359 360
  }

361
  @override
Hixie's avatar
Hixie committed
362 363
  void acceptGesture(int pointer) {
    assert(_gestureMap.containsKey(pointer));
364
    _gestureMap[pointer].accept();
Hixie's avatar
Hixie committed
365 366
  }

367
  @override
Hixie's avatar
Hixie committed
368 369
  void rejectGesture(int pointer) {
    assert(_gestureMap.containsKey(pointer));
370
    _gestureMap[pointer].reject();
Hixie's avatar
Hixie committed
371
    assert(!_gestureMap.containsKey(pointer));
Hixie's avatar
Hixie committed
372 373
  }

374 375
  void _dispatchCancel(int pointer) {
    assert(_gestureMap.containsKey(pointer));
Hixie's avatar
Hixie committed
376
    _gestureMap.remove(pointer);
377
    if (onTapCancel != null)
378
      invokeCallback<Null>('onTapCancel', () => onTapCancel(pointer)); // ignore: STRONG_MODE_INVALID_CAST_FUNCTION_EXPR, https://github.com/dart-lang/sdk/issues/27504
379 380
  }

381
  void _dispatchTap(int pointer, Offset globalPosition) {
382 383 384
    assert(_gestureMap.containsKey(pointer));
    _gestureMap.remove(pointer);
    if (onTapUp != null)
385
      invokeCallback<Null>('onTapUp', () => onTapUp(pointer, new TapUpDetails(globalPosition: globalPosition))); // ignore: STRONG_MODE_INVALID_CAST_FUNCTION_EXPR, https://github.com/dart-lang/sdk/issues/27504
386
    if (onTap != null)
387
      invokeCallback<Null>('onTap', () => onTap(pointer)); // ignore: STRONG_MODE_INVALID_CAST_FUNCTION_EXPR, https://github.com/dart-lang/sdk/issues/27504
Hixie's avatar
Hixie committed
388 389
  }

390
  void _dispatchLongTap(int pointer, Offset lastPosition) {
Hixie's avatar
Hixie committed
391 392
    assert(_gestureMap.containsKey(pointer));
    if (onLongTapDown != null)
393
      invokeCallback<Null>('onLongTapDown', () => onLongTapDown(pointer, new TapDownDetails(globalPosition: lastPosition))); // ignore: STRONG_MODE_INVALID_CAST_FUNCTION_EXPR, https://github.com/dart-lang/sdk/issues/27504
Hixie's avatar
Hixie committed
394 395
  }

396
  @override
Hixie's avatar
Hixie committed
397
  void dispose() {
398
    final List<_TapGesture> localGestures = new List<_TapGesture>.from(_gestureMap.values);
Hixie's avatar
Hixie committed
399 400 401 402
    for (_TapGesture gesture in localGestures)
      gesture.cancel();
    // Rejection of each gesture should cause it to be removed from our map
    assert(_gestureMap.isEmpty);
403
    super.dispose();
Hixie's avatar
Hixie committed
404 405
  }

406
  @override
407
  String get debugDescription => 'multitap';
Hixie's avatar
Hixie committed
408
}