multitap.dart 13.3 KB
Newer Older
Hixie's avatar
Hixie committed
1 2 3 4 5 6 7 8
// 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';
import 'dart:ui' show Point, Offset;

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 44 45 46 47

  final int pointer;
  final GestureArenaEntry entry;
  final Point _initialPosition;

  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) {
Hixie's avatar
Hixie committed
63 64 65 66 67
    Offset offset = event.position - _initialPosition;
    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 {
Hixie's avatar
Hixie committed
71 72 73 74 75 76 77 78 79 80 81 82 83 84
  // 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
85
  // state, the callback is called and the state is reset.
Hixie's avatar
Hixie committed
86 87 88 89 90
  // 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

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

  Timer _doubleTapTimer;
  _TapTracker _firstTap;
  final Map<int, _TapTracker> _trackers = new Map<int, _TapTracker>();

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

114
  void _handleEvent(PointerEvent event) {
Hixie's avatar
Hixie committed
115 116
    _TapTracker tracker = _trackers[event.pointer];
    assert(tracker != null);
Ian Hickson's avatar
Ian Hickson committed
117 118 119 120 121 122 123
    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
124
        _reject(tracker);
Ian Hickson's avatar
Ian Hickson committed
125 126
    } else if (event is PointerCancelEvent) {
      _reject(tracker);
Hixie's avatar
Hixie committed
127 128 129
    }
  }

130
  @override
131
  void acceptGesture(int pointer) { }
Hixie's avatar
Hixie committed
132

133
  @override
Hixie's avatar
Hixie committed
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
  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();
  }

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

  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
168
      // to work properly.
Hixie's avatar
Hixie committed
169 170 171
      _TapTracker tracker = _firstTap;
      _firstTap = null;
      _reject(tracker);
172
      GestureBinding.instance.gestureArena.release(tracker.pointer);
Hixie's avatar
Hixie committed
173 174 175 176 177 178
    }
    _clearTrackers();
  }

  void _registerFirstTap(_TapTracker tracker) {
    _startDoubleTapTimer();
179
    GestureBinding.instance.gestureArena.hold(tracker.pointer);
Hixie's avatar
Hixie committed
180 181 182 183 184 185 186 187 188 189 190 191 192 193
    // 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)
194
      invokeCallback<Null>('onDoubleTap', onDoubleTap); // ignore: STRONG_MODE_INVALID_CAST_FUNCTION_EXPR, https://github.com/dart-lang/sdk/issues/27504
Hixie's avatar
Hixie committed
195 196 197 198 199 200 201 202 203 204 205
    _reset();
  }

  void _clearTrackers() {
    List<_TapTracker> localTrackers = new List<_TapTracker>.from(_trackers.values);
    for (_TapTracker tracker in localTrackers)
      _reject(tracker);
    assert(_trackers.isEmpty);
  }

  void _freezeTracker(_TapTracker tracker) {
206
    tracker.stopTrackingPointer(_handleEvent);
Hixie's avatar
Hixie committed
207 208 209 210 211 212 213 214 215 216 217 218 219
  }

  void _startDoubleTapTimer() {
    _doubleTapTimer ??= new Timer(kDoubleTapTimeout, () => _reset());
  }

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

220
  @override
221
  String toStringShort() => 'double tap';
Hixie's avatar
Hixie committed
222 223 224 225 226 227 228 229 230
}

/// 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({
    MultiTapGestureRecognizer gestureRecognizer,
Ian Hickson's avatar
Ian Hickson committed
231
    PointerEvent event,
Hixie's avatar
Hixie committed
232
    Duration longTapDelay
Hixie's avatar
Hixie committed
233
  }) : gestureRecognizer = gestureRecognizer,
Hixie's avatar
Hixie committed
234
       _lastPosition = event.position,
Ian Hickson's avatar
Ian Hickson committed
235 236
       super(
    event: event,
237
    entry: GestureBinding.instance.gestureArena.add(event.pointer, gestureRecognizer)
Ian Hickson's avatar
Ian Hickson committed
238
  ) {
239
    startTrackingPointer(handleEvent);
Hixie's avatar
Hixie committed
240 241 242
    if (longTapDelay > Duration.ZERO) {
      _timer = new Timer(longTapDelay, () {
        _timer = null;
243
        gestureRecognizer._dispatchLongTap(event.pointer, _lastPosition);
Hixie's avatar
Hixie committed
244 245
      });
    }
Hixie's avatar
Hixie committed
246 247 248 249 250
  }

  final MultiTapGestureRecognizer gestureRecognizer;

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

  Point _lastPosition;
Hixie's avatar
Hixie committed
254 255
  Point _finalPosition;

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

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

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

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

  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
295
      entry.resolve(GestureDisposition.rejected); // eventually calls reject()
Hixie's avatar
Hixie committed
296 297 298 299
  }

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

304 305 306 307 308 309 310 311 312
/// 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]
313
class MultiTapGestureRecognizer extends GestureRecognizer {
314 315 316 317
  /// 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
318
  MultiTapGestureRecognizer({
319 320
    this.longTapDelay: Duration.ZERO
  });
Hixie's avatar
Hixie committed
321

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

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

  /// A tap has occurred.
Hixie's avatar
Hixie committed
331
  GestureMultiTapCallback onTap;
332 333 334

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

  /// The amount of time between [onTapDown] and [onLongTapDown].
Hixie's avatar
Hixie committed
338
  Duration longTapDelay;
339 340 341

  /// 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
342
  GestureMultiTapDownCallback onLongTapDown;
Hixie's avatar
Hixie committed
343

Hixie's avatar
Hixie committed
344
  final Map<int, _TapGesture> _gestureMap = new Map<int, _TapGesture>();
Hixie's avatar
Hixie committed
345

346
  @override
Ian Hickson's avatar
Ian Hickson committed
347
  void addPointer(PointerEvent event) {
Hixie's avatar
Hixie committed
348 349 350
    assert(!_gestureMap.containsKey(event.pointer));
    _gestureMap[event.pointer] = new _TapGesture(
      gestureRecognizer: this,
Hixie's avatar
Hixie committed
351 352
      event: event,
      longTapDelay: longTapDelay
Hixie's avatar
Hixie committed
353 354
    );
    if (onTapDown != null)
355
      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
356 357
  }

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

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

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

  void _dispatchTap(int pointer, Point globalPosition) {
    assert(_gestureMap.containsKey(pointer));
    _gestureMap.remove(pointer);
    if (onTapUp != null)
382
      invokeCallback<Null>('onTapUp', () => onTapUp(pointer, new TapUpDetails(globalPosition: globalPosition))); // ignore: STRONG_MODE_INVALID_CAST_FUNCTION_EXPR, https://github.com/dart-lang/sdk/issues/27504
383
    if (onTap != null)
384
      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
385 386
  }

387
  void _dispatchLongTap(int pointer, Point lastPosition) {
Hixie's avatar
Hixie committed
388 389
    assert(_gestureMap.containsKey(pointer));
    if (onLongTapDown != null)
390
      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
391 392
  }

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

403
  @override
404
  String toStringShort() => 'multitap';
Hixie's avatar
Hixie committed
405
}