recognizer.dart 10.5 KB
Newer Older
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:collection';
Hixie's avatar
Hixie committed
7
import 'dart:ui' show Point, Offset;
8

9
import 'package:flutter/foundation.dart';
10

11
import 'arena.dart';
12
import 'binding.dart';
13
import 'constants.dart';
14
import 'events.dart';
15
import 'pointer_router.dart';
16
import 'team.dart';
17

18
export 'pointer_router.dart' show PointerRouter;
19

20 21 22 23
/// Generic signature for callbacks passed to
/// [GestureRecognizer.invokeCallback]. This allows the
/// [GestureRecognizer.invokeCallback] mechanism to be generically used with
/// anonymous functions that return objects of particular types.
24 25
typedef T RecognizerCallback<T>();

26 27 28 29 30
/// The base class that all GestureRecognizers should inherit from.
///
/// Provides a basic API that can be used by classes that work with
/// gesture recognizers but don't care about the specific details of
/// the gestures recognizers themselves.
31
abstract class GestureRecognizer extends GestureArenaMember {
32 33
  /// Registers a new pointer that might be relevant to this gesture
  /// detector.
Florian Loitsch's avatar
Florian Loitsch committed
34
  ///
35 36 37 38 39 40 41
  /// The owner of this gesture recognizer calls addPointer() with the
  /// PointerDownEvent of each pointer that should be considered for
  /// this gesture.
  ///
  /// It's the GestureRecognizer's responsibility to then add itself
  /// to the global pointer router (see [PointerRouter]) to receive
  /// subsequent events for this pointer, and to add the pointer to
42
  /// the global gesture arena manager (see [GestureArenaManager]) to track
43
  /// that pointer.
Ian Hickson's avatar
Ian Hickson committed
44
  void addPointer(PointerDownEvent event);
45

Florian Loitsch's avatar
Florian Loitsch committed
46 47
  /// Releases any resources used by the object.
  ///
48 49
  /// This method is called by the owner of this gesture recognizer
  /// when the object is no longer needed (e.g. when a gesture
50
  /// recognizer is being unregistered from a [GestureDetector], the
51
  /// GestureDetector widget calls this method).
52
  @mustCallSuper
53 54
  void dispose() { }

55 56 57
  /// Returns a very short pretty description of the gesture that the
  /// recognizer looks for, like 'tap' or 'horizontal drag'.
  String toStringShort() => toString();
58

59 60
  /// Invoke a callback provided by the application, catching and logging any
  /// exceptions.
61
  @protected
62 63
  T invokeCallback<T>(String name, RecognizerCallback<T> callback) {
    T result;
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
    try {
      result = callback();
    } catch (exception, stack) {
      FlutterError.reportError(new FlutterErrorDetails(
        exception: exception,
        stack: stack,
        library: 'gesture',
        context: 'while handling a gesture',
        informationCollector: (StringBuffer information) {
          information.writeln('Handler: $name');
          information.writeln('Recognizer:');
          information.writeln('  $this');
        }
      ));
    }
    return result;
  }
81 82
}

83 84 85 86 87 88 89 90
/// Base class for gesture recognizers that can only recognize one
/// gesture at a time. For example, a single [TapGestureRecognizer]
/// can never recognize two taps happening simultaneously, even if
/// multiple pointers are placed on the same widget.
///
/// This is in contrast to, for instance, [MultiTapGestureRecognizer],
/// which manages each pointer independently and can consider multiple
/// simultaneous touches to each result in a separate tap.
91
abstract class OneSequenceGestureRecognizer extends GestureRecognizer {
92
  final Map<int, GestureArenaEntry> _entries = <int, GestureArenaEntry>{};
93
  final Set<int> _trackedPointers = new HashSet<int>();
94

95 96
  /// Called when a pointer event is routed to this recognizer.
  @protected
Ian Hickson's avatar
Ian Hickson committed
97
  void handleEvent(PointerEvent event);
98 99

  @override
100
  void acceptGesture(int pointer) { }
101 102

  @override
103
  void rejectGesture(int pointer) { }
104

105
  /// Called when the number of pointers this recognizer is tracking changes from one to zero.
106 107 108
  ///
  /// The given pointer ID is the ID of the last pointer this recognizer was
  /// tracking.
109
  @protected
110
  void didStopTrackingLastPointer(int pointer);
111

112
  /// Resolves this recognizer's participation in each gesture arena with the given disposition.
113 114
  @protected
  @mustCallSuper
115
  void resolve(GestureDisposition disposition) {
116
    final List<GestureArenaEntry> localEntries = new List<GestureArenaEntry>.from(_entries.values);
117 118 119 120 121
    _entries.clear();
    for (GestureArenaEntry entry in localEntries)
      entry.resolve(disposition);
  }

122
  @override
123 124 125
  void dispose() {
    resolve(GestureDisposition.rejected);
    for (int pointer in _trackedPointers)
126
      GestureBinding.instance.pointerRouter.removeRoute(pointer, handleEvent);
127 128
    _trackedPointers.clear();
    assert(_entries.isEmpty);
129
    super.dispose();
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
  /// The team that this recognizer belongs to, if any.
  ///
  /// If [team] is null, this recognizer competes directly in the
  /// [GestureArenaManager] to recognize a sequence of pointer events as a
  /// gesture. If [team] is non-null, this recognizer competes in the arena in
  /// a group with other recognizers on the same team.
  ///
  /// A recognizer can be assigned to a team only when it is not participating
  /// in the arena. For example, a common time to assign a recognizer to a team
  /// is shortly after creating the recognizer.
  GestureArenaTeam get team => _team;
  GestureArenaTeam _team;
  set team(GestureArenaTeam value) {
    assert(_entries.isEmpty);
    assert(_trackedPointers.isEmpty);
    assert(_team == null);
    _team = value;
  }

  GestureArenaEntry _addPointerToArena(int pointer) {
    if (_team != null)
      return _team.add(pointer, this);
    return GestureBinding.instance.gestureArena.add(pointer, this);
  }

157 158 159 160 161
  /// Causes events related to the given pointer ID to be routed to this recognizer.
  ///
  /// The pointer events are delivered to [handleEvent].
  ///
  /// Use [stopTrackingPointer] to remove the route added by this function.
162
  @protected
163
  void startTrackingPointer(int pointer) {
164
    GestureBinding.instance.pointerRouter.addRoute(pointer, handleEvent);
165
    _trackedPointers.add(pointer);
166
    assert(!_entries.containsValue(pointer));
167
    _entries[pointer] = _addPointerToArena(pointer);
168 169
  }

170 171 172 173 174 175
  /// Stops events related to the given pointer ID from being routed to this recognizer.
  ///
  /// If this function reduces the number of tracked pointers to zero, it will
  /// call [didStopTrackingLastPointer] synchronously.
  ///
  /// Use [startTrackingPointer] to add the routes in the first place.
176
  @protected
177
  void stopTrackingPointer(int pointer) {
178 179 180 181 182 183
    if (_trackedPointers.contains(pointer)) {
      GestureBinding.instance.pointerRouter.removeRoute(pointer, handleEvent);
      _trackedPointers.remove(pointer);
      if (_trackedPointers.isEmpty)
        didStopTrackingLastPointer(pointer);
    }
184 185
  }

186 187
  /// Stops tracking the pointer associated with the given event if the event is
  /// a [PointerUpEvent] or a [PointerCancelEvent] event.
188
  @protected
Ian Hickson's avatar
Ian Hickson committed
189 190
  void stopTrackingIfPointerNoLongerDown(PointerEvent event) {
    if (event is PointerUpEvent || event is PointerCancelEvent)
191 192 193 194
      stopTrackingPointer(event.pointer);
  }
}

195 196 197 198 199 200 201
/// The possible states of a [PrimaryPointerGestureRecognizer].
///
/// The recognizer advances from [ready] to [possible] when starts tracking a
/// primary pointer. When the primary pointer is resolve (either accepted or
/// or rejected), the recognizers advances to [defunct]. Once the recognizer
/// has stopped tracking any remaining pointers, the recognizer returns to
/// [ready].
202
enum GestureRecognizerState {
203
  /// The recognizer is ready to start recognizing a gesture.
204
  ready,
205

206
  /// The sequence of pointer events seen thus far is consistent with the
207 208
  /// gesture the recognizer is attempting to recognize but the gesture has not
  /// been accepted definitively.
209
  possible,
210

211
  /// Further pointer events cannot cause this recognizer to recognize the
212 213 214
  /// gesture until the recognizer returns to the [ready] state (typically when
  /// all the pointers the recognizer is tracking are removed from the screen).
  defunct,
215 216
}

217
/// A base class for gesture recognizers that track a single primary pointer.
218
abstract class PrimaryPointerGestureRecognizer extends OneSequenceGestureRecognizer {
219
  /// Initializes the [deadline] field during construction of subclasses.
220
  PrimaryPointerGestureRecognizer({ this.deadline });
221

222 223
  /// If non-null, the recognizer will call [didExceedDeadline] after this
  /// amount of time has elapsed since starting to track the primary pointer.
224 225
  final Duration deadline;

226 227 228
  /// The current state of the recognizer.
  ///
  /// See [GestureRecognizerState] for a description of the states.
229
  GestureRecognizerState state = GestureRecognizerState.ready;
230 231

  /// The ID of the primary pointer this recognizer is tracking.
232
  int primaryPointer;
233 234

  /// The global location at which the primary pointer contacted the screen.
Hixie's avatar
Hixie committed
235
  Point initialPosition;
236

237 238
  Timer _timer;

239
  @override
Ian Hickson's avatar
Ian Hickson committed
240
  void addPointer(PointerDownEvent event) {
241 242 243 244
    startTrackingPointer(event.pointer);
    if (state == GestureRecognizerState.ready) {
      state = GestureRecognizerState.possible;
      primaryPointer = event.pointer;
Hixie's avatar
Hixie committed
245
      initialPosition = event.position;
246 247 248 249 250
      if (deadline != null)
        _timer = new Timer(deadline, didExceedDeadline);
    }
  }

251
  @override
Ian Hickson's avatar
Ian Hickson committed
252
  void handleEvent(PointerEvent event) {
253 254 255
    assert(state != GestureRecognizerState.ready);
    if (state == GestureRecognizerState.possible && event.pointer == primaryPointer) {
      // TODO(abarth): Maybe factor the slop handling out into a separate class?
Ian Hickson's avatar
Ian Hickson committed
256
      if (event is PointerMoveEvent && _getDistance(event) > kTouchSlop) {
257
        resolve(GestureDisposition.rejected);
Ian Hickson's avatar
Ian Hickson committed
258
        stopTrackingPointer(primaryPointer);
259
      } else {
260
        handlePrimaryPointer(event);
261
      }
262 263 264 265 266
    }
    stopTrackingIfPointerNoLongerDown(event);
  }

  /// Override to provide behavior for the primary pointer when the gesture is still possible.
267
  @protected
Ian Hickson's avatar
Ian Hickson committed
268
  void handlePrimaryPointer(PointerEvent event);
269

Florian Loitsch's avatar
Florian Loitsch committed
270
  /// Override to be notified when [deadline] is exceeded.
271
  ///
272
  /// You must override this method if you supply a [deadline].
273
  @protected
274 275 276 277
  void didExceedDeadline() {
    assert(deadline == null);
  }

278
  @override
279
  void rejectGesture(int pointer) {
280 281
    if (pointer == primaryPointer) {
      _stopTimer();
282
      state = GestureRecognizerState.defunct;
283
    }
284 285
  }

286
  @override
287
  void didStopTrackingLastPointer(int pointer) {
288
    _stopTimer();
289 290 291
    state = GestureRecognizerState.ready;
  }

292
  @override
293 294 295 296 297 298 299 300 301 302 303 304
  void dispose() {
    _stopTimer();
    super.dispose();
  }

  void _stopTimer() {
    if (_timer != null) {
      _timer.cancel();
      _timer = null;
    }
  }

Ian Hickson's avatar
Ian Hickson committed
305
  double _getDistance(PointerEvent event) {
306
    final Offset offset = event.position - initialPosition;
307 308 309 310
    return offset.distance;
  }

}