multitap.dart 10.8 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';
Hixie's avatar
Hixie committed
14 15 16 17 18 19 20

typedef void GestureDoubleTapCallback();

typedef void GestureMultiTapDownCallback(Point globalPosition, int pointer);
typedef void GestureMultiTapUpCallback(Point globalPosition, int pointer);
typedef void GestureMultiTapCallback(int pointer);
typedef void GestureMultiTapCancelCallback(int pointer);
Hixie's avatar
Hixie committed
21 22 23 24 25

/// TapTracker helps track individual tap sequences as part of a
/// larger gesture.
class _TapTracker {

Ian Hickson's avatar
Ian Hickson committed
26
  _TapTracker({ PointerDownEvent event, this.entry })
Hixie's avatar
Hixie committed
27
    : pointer = event.pointer,
Ian Hickson's avatar
Ian Hickson committed
28
      _initialPosition = event.position;
Hixie's avatar
Hixie committed
29 30 31 32 33 34 35

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

  bool _isTrackingPointer = false;

36
  void startTrackingPointer(PointerRoute route) {
Hixie's avatar
Hixie committed
37 38
    if (!_isTrackingPointer) {
      _isTrackingPointer = true;
39
      GestureBinding.instance.pointerRouter.addRoute(pointer, route);
Hixie's avatar
Hixie committed
40 41 42
    }
  }

43
  void stopTrackingPointer(PointerRoute route) {
Hixie's avatar
Hixie committed
44 45
    if (_isTrackingPointer) {
      _isTrackingPointer = false;
46
      GestureBinding.instance.pointerRouter.removeRoute(pointer, route);
Hixie's avatar
Hixie committed
47 48 49
    }
  }

Ian Hickson's avatar
Ian Hickson committed
50
  bool isWithinTolerance(PointerEvent event, double tolerance) {
Hixie's avatar
Hixie committed
51 52 53 54 55 56 57
    Offset offset = event.position - _initialPosition;
    return offset.distance <= tolerance;
  }

}


58
class DoubleTapGestureRecognizer extends GestureRecognizer {
Hixie's avatar
Hixie committed
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
  // 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
  // state, the callback is invoked and the state is reset.
  // 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

Hixie's avatar
Hixie committed
79
  GestureDoubleTapCallback onDoubleTap;
Hixie's avatar
Hixie committed
80 81 82 83 84

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

85
  @override
Ian Hickson's avatar
Ian Hickson committed
86
  void addPointer(PointerEvent event) {
Florian Loitsch's avatar
Florian Loitsch committed
87
    // Ignore out-of-bounds second taps.
Hixie's avatar
Hixie committed
88
    if (_firstTap != null &&
89
        !_firstTap.isWithinTolerance(event, kDoubleTapSlop))
Hixie's avatar
Hixie committed
90 91 92 93
      return;
    _stopDoubleTapTimer();
    _TapTracker tracker = new _TapTracker(
      event: event,
94
      entry: GestureBinding.instance.gestureArena.add(event.pointer, this)
Hixie's avatar
Hixie committed
95 96
    );
    _trackers[event.pointer] = tracker;
97
    tracker.startTrackingPointer(handleEvent);
Hixie's avatar
Hixie committed
98 99
  }

Ian Hickson's avatar
Ian Hickson committed
100
  void handleEvent(PointerEvent event) {
Hixie's avatar
Hixie committed
101 102
    _TapTracker tracker = _trackers[event.pointer];
    assert(tracker != null);
Ian Hickson's avatar
Ian Hickson committed
103 104 105 106 107 108 109
    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
110
        _reject(tracker);
Ian Hickson's avatar
Ian Hickson committed
111 112
    } else if (event is PointerCancelEvent) {
      _reject(tracker);
Hixie's avatar
Hixie committed
113 114 115
    }
  }

116
  @override
117
  void acceptGesture(int pointer) { }
Hixie's avatar
Hixie committed
118

119
  @override
Hixie's avatar
Hixie committed
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
  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();
  }

144
  @override
Hixie's avatar
Hixie committed
145 146 147 148 149 150 151 152
  void dispose() {
    _reset();
  }

  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
153
      // to work properly.
Hixie's avatar
Hixie committed
154 155 156
      _TapTracker tracker = _firstTap;
      _firstTap = null;
      _reject(tracker);
157
      GestureBinding.instance.gestureArena.release(tracker.pointer);
Hixie's avatar
Hixie committed
158 159 160 161 162 163
    }
    _clearTrackers();
  }

  void _registerFirstTap(_TapTracker tracker) {
    _startDoubleTapTimer();
164
    GestureBinding.instance.gestureArena.hold(tracker.pointer);
Hixie's avatar
Hixie committed
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
    // 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)
      onDoubleTap();
    _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) {
191
    tracker.stopTrackingPointer(handleEvent);
Hixie's avatar
Hixie committed
192 193 194 195 196 197 198 199 200 201 202 203 204
  }

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

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

205
  @override
206
  String toStringShort() => 'double tap';
Hixie's avatar
Hixie committed
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
}


enum _TapResolution {
  tap,
  cancel
}

/// 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
222
    PointerEvent event,
Hixie's avatar
Hixie committed
223
    Duration longTapDelay
Hixie's avatar
Hixie committed
224
  }) : gestureRecognizer = gestureRecognizer,
Hixie's avatar
Hixie committed
225
       _lastPosition = event.position,
Ian Hickson's avatar
Ian Hickson committed
226 227
       super(
    event: event,
228
    entry: GestureBinding.instance.gestureArena.add(event.pointer, gestureRecognizer)
Ian Hickson's avatar
Ian Hickson committed
229
  ) {
230
    startTrackingPointer(handleEvent);
Hixie's avatar
Hixie committed
231 232 233 234 235 236
    if (longTapDelay > Duration.ZERO) {
      _timer = new Timer(longTapDelay, () {
        _timer = null;
        gestureRecognizer._handleLongTap(event.pointer, _lastPosition);
      });
    }
Hixie's avatar
Hixie committed
237 238 239 240 241
  }

  final MultiTapGestureRecognizer gestureRecognizer;

  bool _wonArena = false;
Hixie's avatar
Hixie committed
242 243 244
  Timer _timer;

  Point _lastPosition;
Hixie's avatar
Hixie committed
245 246
  Point _finalPosition;

Ian Hickson's avatar
Ian Hickson committed
247
  void handleEvent(PointerEvent event) {
Hixie's avatar
Hixie committed
248
    assert(event.pointer == pointer);
Ian Hickson's avatar
Ian Hickson committed
249
    if (event is PointerMoveEvent) {
Hixie's avatar
Hixie committed
250 251 252 253
      if (!isWithinTolerance(event, kTouchSlop))
        cancel();
      else
        _lastPosition = event.position;
Ian Hickson's avatar
Ian Hickson committed
254
    } else if (event is PointerCancelEvent) {
Hixie's avatar
Hixie committed
255
      cancel();
Ian Hickson's avatar
Ian Hickson committed
256
    } else if (event is PointerUpEvent) {
257
      stopTrackingPointer(handleEvent);
Hixie's avatar
Hixie committed
258 259 260 261 262
      _finalPosition = event.position;
      _check();
    }
  }

263
  @override
264
  void stopTrackingPointer(PointerRoute route) {
Hixie's avatar
Hixie committed
265 266
    _timer?.cancel();
    _timer = null;
267
    super.stopTrackingPointer(route);
Hixie's avatar
Hixie committed
268 269
  }

Hixie's avatar
Hixie committed
270 271 272 273 274 275
  void accept() {
    _wonArena = true;
    _check();
  }

  void reject() {
276
    stopTrackingPointer(handleEvent);
Hixie's avatar
Hixie committed
277 278 279 280 281 282 283 284 285
    gestureRecognizer._resolveTap(pointer, _TapResolution.cancel, null);
  }

  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
286
      entry.resolve(GestureDisposition.rejected); // eventually calls reject()
Hixie's avatar
Hixie committed
287 288 289 290 291 292 293 294 295 296 297 298 299
  }

  void _check() {
    if (_wonArena && _finalPosition != null)
      gestureRecognizer._resolveTap(pointer, _TapResolution.tap, _finalPosition);
  }

}

/// MultiTapGestureRecognizer is a tap recognizer that treats taps
/// independently. That is, each pointer sequence that could resolve to a tap
/// does so independently of others: down-1, down-2, up-1, up-2 produces two
/// taps, on up-1 and up-2.
300
class MultiTapGestureRecognizer extends GestureRecognizer {
Hixie's avatar
Hixie committed
301
  MultiTapGestureRecognizer({
302 303
    this.longTapDelay: Duration.ZERO
  });
Hixie's avatar
Hixie committed
304

Hixie's avatar
Hixie committed
305 306 307 308 309 310
  GestureMultiTapDownCallback onTapDown;
  GestureMultiTapUpCallback onTapUp;
  GestureMultiTapCallback onTap;
  GestureMultiTapCancelCallback onTapCancel;
  Duration longTapDelay;
  GestureMultiTapDownCallback onLongTapDown;
Hixie's avatar
Hixie committed
311

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

314
  @override
Ian Hickson's avatar
Ian Hickson committed
315
  void addPointer(PointerEvent event) {
Hixie's avatar
Hixie committed
316 317 318
    assert(!_gestureMap.containsKey(event.pointer));
    _gestureMap[event.pointer] = new _TapGesture(
      gestureRecognizer: this,
Hixie's avatar
Hixie committed
319 320
      event: event,
      longTapDelay: longTapDelay
Hixie's avatar
Hixie committed
321 322
    );
    if (onTapDown != null)
Hixie's avatar
Hixie committed
323
      onTapDown(event.position, event.pointer);
Hixie's avatar
Hixie committed
324 325
  }

326
  @override
Hixie's avatar
Hixie committed
327 328 329
  void acceptGesture(int pointer) {
    assert(_gestureMap.containsKey(pointer));
    _gestureMap[pointer]?.accept();
Hixie's avatar
Hixie committed
330
    assert(!_gestureMap.containsKey(pointer));
Hixie's avatar
Hixie committed
331 332
  }

333
  @override
Hixie's avatar
Hixie committed
334 335 336
  void rejectGesture(int pointer) {
    assert(_gestureMap.containsKey(pointer));
    _gestureMap[pointer]?.reject();
Hixie's avatar
Hixie committed
337
    assert(!_gestureMap.containsKey(pointer));
Hixie's avatar
Hixie committed
338 339 340 341 342 343
  }

  void _resolveTap(int pointer, _TapResolution resolution, Point globalPosition) {
    _gestureMap.remove(pointer);
    if (resolution == _TapResolution.tap) {
      if (onTapUp != null)
Hixie's avatar
Hixie committed
344
        onTapUp(globalPosition, pointer);
Hixie's avatar
Hixie committed
345
      if (onTap != null)
Hixie's avatar
Hixie committed
346
        onTap(pointer);
Hixie's avatar
Hixie committed
347 348
    } else {
      if (onTapCancel != null)
Hixie's avatar
Hixie committed
349
        onTapCancel(pointer);
Hixie's avatar
Hixie committed
350 351 352
    }
  }

Hixie's avatar
Hixie committed
353 354 355 356 357 358
  void _handleLongTap(int pointer, Point lastPosition) {
    assert(_gestureMap.containsKey(pointer));
    if (onLongTapDown != null)
      onLongTapDown(lastPosition, pointer);
  }

359
  @override
Hixie's avatar
Hixie committed
360 361 362 363 364 365 366 367
  void dispose() {
    List<_TapGesture> localGestures = new List<_TapGesture>.from(_gestureMap.values);
    for (_TapGesture gesture in localGestures)
      gesture.cancel();
    // Rejection of each gesture should cause it to be removed from our map
    assert(_gestureMap.isEmpty);
  }

368
  @override
369
  String toStringShort() => 'multitap';
Hixie's avatar
Hixie committed
370
}