recognizer.dart 21.5 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5

6
import 'dart:async';
7
import 'dart:collection';
8
import 'dart:ui' show Offset;
9

10
import 'package:vector_math/vector_math_64.dart';
11
import 'package:flutter/foundation.dart';
12

13
import 'arena.dart';
14
import 'binding.dart';
15
import 'constants.dart';
16
import 'debug.dart';
17
import 'events.dart';
18
import 'pointer_router.dart';
19
import 'team.dart';
20

21
export 'pointer_router.dart' show PointerRouter;
22

23 24 25 26
/// 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.
27
typedef RecognizerCallback<T> = T Function();
28

29 30 31 32 33 34 35
/// Configuration of offset passed to [DragStartDetails].
///
/// The settings determines when a drag formally starts when the user
/// initiates a drag.
///
/// See also:
///
36
///  * [DragGestureRecognizer.dragStartBehavior], which gives an example for the different behaviors.
37
enum DragStartBehavior {
38
  /// Set the initial offset, at the position where the first down event was
39 40 41 42 43 44 45 46
  /// detected.
  down,

  /// Set the initial position at the position where the drag start event was
  /// detected.
  start,
}

47
/// The base class that all gesture recognizers inherit from.
48 49 50 51
///
/// 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.
52 53 54 55
///
/// See also:
///
///  * [GestureDetector], the widget that is used to detect gestures.
56 57
///  * [debugPrintRecognizerCallbacksTrace], a flag that can be set to help
///    debug issues with gesture recognizers.
58
abstract class GestureRecognizer extends GestureArenaMember with DiagnosticableTreeMixin {
59 60 61 62
  /// Initializes the gesture recognizer.
  ///
  /// The argument is optional and is only used for debug purposes (e.g. in the
  /// [toString] serialization).
63 64 65 66 67 68
  ///
  /// {@template flutter.gestures.gestureRecognizer.kind}
  /// It's possible to limit this recognizer to a specific [PointerDeviceKind]
  /// by providing the optional [kind] argument. If [kind] is null,
  /// the recognizer will accept pointer events from all device kinds.
  /// {@endtemplate}
69
  GestureRecognizer({ this.debugOwner, PointerDeviceKind? kind }) : _kindFilter = kind;
70 71 72 73 74

  /// The recognizer's owner.
  ///
  /// This is used in the [toString] serialization to report the object for which
  /// this gesture recognizer was created, to aid in debugging.
75
  final Object? debugOwner;
76

77 78
  /// The kind of device that's allowed to be recognized. If null, events from
  /// all device kinds will be tracked and recognized.
79
  final PointerDeviceKind? _kindFilter;
80 81 82 83

  /// Holds a mapping between pointer IDs and the kind of devices they are
  /// coming from.
  final Map<int, PointerDeviceKind> _pointerToKind = <int, PointerDeviceKind>{};
84

85 86
  /// Registers a new pointer that might be relevant to this gesture
  /// detector.
Florian Loitsch's avatar
Florian Loitsch committed
87
  ///
88 89 90 91 92 93 94
  /// 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
95
  /// the global gesture arena manager (see [GestureArenaManager]) to track
96
  /// that pointer.
97 98 99 100
  ///
  /// This method is called for each and all pointers being added. In
  /// most cases, you want to override [addAllowedPointer] instead.
  void addPointer(PointerDownEvent event) {
101
    _pointerToKind[event.pointer] = event.kind;
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
    if (isPointerAllowed(event)) {
      addAllowedPointer(event);
    } else {
      handleNonAllowedPointer(event);
    }
  }

  /// Registers a new pointer that's been checked to be allowed by this gesture
  /// recognizer.
  ///
  /// Subclasses of [GestureRecognizer] are supposed to override this method
  /// instead of [addPointer] because [addPointer] will be called for each
  /// pointer being added while [addAllowedPointer] is only called for pointers
  /// that are allowed by this recognizer.
  @protected
  void addAllowedPointer(PointerDownEvent event) { }

  /// Handles a pointer being added that's not allowed by this recognizer.
  ///
  /// Subclasses can override this method and reject the gesture.
  ///
  /// See:
  /// - [OneSequenceGestureRecognizer.handleNonAllowedPointer].
  @protected
  void handleNonAllowedPointer(PointerDownEvent event) { }

  /// Checks whether or not a pointer is allowed to be tracked by this recognizer.
  @protected
  bool isPointerAllowed(PointerDownEvent event) {
    // Currently, it only checks for device kind. But in the future we could check
    // for other things e.g. mouse button.
133 134 135 136 137 138 139 140 141 142
    return _kindFilter == null || _kindFilter == event.kind;
  }

  /// For a given pointer ID, returns the device kind associated with it.
  ///
  /// The pointer ID is expected to be a valid one i.e. an event was received
  /// with that pointer ID.
  @protected
  PointerDeviceKind getKindForPointer(int pointer) {
    assert(_pointerToKind.containsKey(pointer));
143
    return _pointerToKind[pointer]!;
144
  }
145

Florian Loitsch's avatar
Florian Loitsch committed
146 147
  /// Releases any resources used by the object.
  ///
148 149
  /// This method is called by the owner of this gesture recognizer
  /// when the object is no longer needed (e.g. when a gesture
150
  /// recognizer is being unregistered from a [GestureDetector], the
151
  /// GestureDetector widget calls this method).
152
  @mustCallSuper
153 154
  void dispose() { }

155 156
  /// Returns a very short pretty description of the gesture that the
  /// recognizer looks for, like 'tap' or 'horizontal drag'.
157
  String get debugDescription;
158

159 160
  /// Invoke a callback provided by the application, catching and logging any
  /// exceptions.
161 162
  ///
  /// The `name` argument is ignored except when reporting exceptions.
163 164 165 166 167
  ///
  /// The `debugReport` argument is optional and is used when
  /// [debugPrintRecognizerCallbacksTrace] is true. If specified, it must be a
  /// callback that returns a string describing useful debugging information,
  /// e.g. the arguments passed to the callback.
168
  @protected
169
  T? invokeCallback<T>(String name, RecognizerCallback<T> callback, { String Function()? debugReport }) {
170
    assert(callback != null);
171
    T? result;
172
    try {
173 174
      assert(() {
        if (debugPrintRecognizerCallbacksTrace) {
175
          final String? report = debugReport != null ? debugReport() : null;
176 177 178 179 180 181
          // The 19 in the line below is the width of the prefix used by
          // _debugLogDiagnostic in arena.dart.
          final String prefix = debugPrintGestureArenaDiagnostics ? ' ' * 19 + '❙ ' : '';
          debugPrint('$prefix$this calling $name callback.${ report?.isNotEmpty == true ? " $report" : "" }');
        }
        return true;
182
      }());
183 184
      result = callback();
    } catch (exception, stack) {
185
      InformationCollector? collector;
186 187 188 189 190 191 192
      assert(() {
        collector = () sync* {
          yield StringProperty('Handler', name);
          yield DiagnosticsProperty<GestureRecognizer>('Recognizer', this, style: DiagnosticsTreeStyle.errorProperty);
        };
        return true;
      }());
193
      FlutterError.reportError(FlutterErrorDetails(
194 195 196
        exception: exception,
        stack: stack,
        library: 'gesture',
197
        context: ErrorDescription('while handling a gesture'),
198
        informationCollector: collector
199 200 201 202
      ));
    }
    return result;
  }
203 204

  @override
205 206
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
207
    properties.add(DiagnosticsProperty<Object>('debugOwner', debugOwner, defaultValue: null));
208
  }
209 210
}

211 212 213 214 215 216 217 218
/// 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.
219
abstract class OneSequenceGestureRecognizer extends GestureRecognizer {
220
  /// Initialize the object.
221 222 223
  ///
  /// {@macro flutter.gestures.gestureRecognizer.kind}
  OneSequenceGestureRecognizer({
224 225
    Object? debugOwner,
    PointerDeviceKind? kind,
226
  }) : super(debugOwner: debugOwner, kind: kind);
227

228
  final Map<int, GestureArenaEntry> _entries = <int, GestureArenaEntry>{};
229
  final Set<int> _trackedPointers = HashSet<int>();
230

231 232 233 234 235
  @override
  void handleNonAllowedPointer(PointerDownEvent event) {
    resolve(GestureDisposition.rejected);
  }

236 237
  /// Called when a pointer event is routed to this recognizer.
  @protected
Ian Hickson's avatar
Ian Hickson committed
238
  void handleEvent(PointerEvent event);
239 240

  @override
241
  void acceptGesture(int pointer) { }
242 243

  @override
244
  void rejectGesture(int pointer) { }
245

246
  /// Called when the number of pointers this recognizer is tracking changes from one to zero.
247 248 249
  ///
  /// The given pointer ID is the ID of the last pointer this recognizer was
  /// tracking.
250
  @protected
251
  void didStopTrackingLastPointer(int pointer);
252

253 254
  /// Resolves this recognizer's participation in each gesture arena with the
  /// given disposition.
255 256
  @protected
  @mustCallSuper
257
  void resolve(GestureDisposition disposition) {
258
    final List<GestureArenaEntry> localEntries = List<GestureArenaEntry>.from(_entries.values);
259
    _entries.clear();
260
    for (final GestureArenaEntry entry in localEntries)
261 262 263
      entry.resolve(disposition);
  }

264 265 266 267 268
  /// Resolves this recognizer's participation in the given gesture arena with
  /// the given disposition.
  @protected
  @mustCallSuper
  void resolvePointer(int pointer, GestureDisposition disposition) {
269
    final GestureArenaEntry? entry = _entries[pointer];
270
    if (entry != null) {
271
      entry.resolve(disposition);
272
      _entries.remove(pointer);
273 274 275
    }
  }

276
  @override
277 278
  void dispose() {
    resolve(GestureDisposition.rejected);
279
    for (final int pointer in _trackedPointers)
280
      GestureBinding.instance!.pointerRouter.removeRoute(pointer, handleEvent);
281 282
    _trackedPointers.clear();
    assert(_entries.isEmpty);
283
    super.dispose();
284 285
  }

286 287 288 289 290 291 292 293 294 295
  /// 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.
296 297
  GestureArenaTeam? get team => _team;
  GestureArenaTeam? _team;
298
  /// The [team] can only be set once.
299
  set team(GestureArenaTeam? value) {
300
    assert(value != null);
301 302 303 304 305 306 307 308
    assert(_entries.isEmpty);
    assert(_trackedPointers.isEmpty);
    assert(_team == null);
    _team = value;
  }

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

313 314
  /// Causes events related to the given pointer ID to be routed to this recognizer.
  ///
315 316 317 318 319
  /// The pointer events are transformed according to `transform` and then delivered
  /// to [handleEvent]. The value for the `transform` argument is usually obtained
  /// from [PointerDownEvent.transform] to transform the events from the global
  /// coordinate space into the coordinate space of the event receiver. It may be
  /// null if no transformation is necessary.
320 321
  ///
  /// Use [stopTrackingPointer] to remove the route added by this function.
322
  @protected
323 324
  void startTrackingPointer(int pointer, [Matrix4? transform]) {
    GestureBinding.instance!.pointerRouter.addRoute(pointer, handleEvent, transform);
325
    _trackedPointers.add(pointer);
326
    assert(!_entries.containsValue(pointer));
327
    _entries[pointer] = _addPointerToArena(pointer);
328 329
  }

330 331 332 333 334 335
  /// 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.
336
  @protected
337
  void stopTrackingPointer(int pointer) {
338
    if (_trackedPointers.contains(pointer)) {
339
      GestureBinding.instance!.pointerRouter.removeRoute(pointer, handleEvent);
340 341 342 343
      _trackedPointers.remove(pointer);
      if (_trackedPointers.isEmpty)
        didStopTrackingLastPointer(pointer);
    }
344 345
  }

346 347
  /// Stops tracking the pointer associated with the given event if the event is
  /// a [PointerUpEvent] or a [PointerCancelEvent] event.
348
  @protected
Ian Hickson's avatar
Ian Hickson committed
349 350
  void stopTrackingIfPointerNoLongerDown(PointerEvent event) {
    if (event is PointerUpEvent || event is PointerCancelEvent)
351 352 353 354
      stopTrackingPointer(event.pointer);
  }
}

355 356
/// The possible states of a [PrimaryPointerGestureRecognizer].
///
357 358 359 360 361
/// The recognizer advances from [ready] to [possible] when it starts tracking a
/// primary pointer. When the primary pointer is resolved in the gesture
/// arena (either accepted or rejected), the recognizers advances to [defunct].
/// Once the recognizer has stopped tracking any remaining pointers, the
/// recognizer returns to [ready].
362
enum GestureRecognizerState {
363
  /// The recognizer is ready to start recognizing a gesture.
364
  ready,
365

366
  /// The sequence of pointer events seen thus far is consistent with the
367 368
  /// gesture the recognizer is attempting to recognize but the gesture has not
  /// been accepted definitively.
369
  possible,
370

371
  /// Further pointer events cannot cause this recognizer to recognize the
372 373 374
  /// gesture until the recognizer returns to the [ready] state (typically when
  /// all the pointers the recognizer is tracking are removed from the screen).
  defunct,
375 376
}

377
/// A base class for gesture recognizers that track a single primary pointer.
378
///
379 380 381 382 383 384
/// Gestures based on this class will stop tracking the gesture if the primary
/// pointer travels beyond [preAcceptSlopTolerance] or [postAcceptSlopTolerance]
/// pixels from the original contact point of the gesture.
///
/// If the [preAcceptSlopTolerance] was breached before the gesture was accepted
/// in the gesture arena, the gesture will be rejected.
385
abstract class PrimaryPointerGestureRecognizer extends OneSequenceGestureRecognizer {
386
  /// Initializes the [deadline] field during construction of subclasses.
387 388
  ///
  /// {@macro flutter.gestures.gestureRecognizer.kind}
389 390
  PrimaryPointerGestureRecognizer({
    this.deadline,
391 392
    this.preAcceptSlopTolerance = kTouchSlop,
    this.postAcceptSlopTolerance = kTouchSlop,
393 394
    Object? debugOwner,
    PointerDeviceKind? kind,
395 396 397 398 399 400 401 402
  }) : assert(
         preAcceptSlopTolerance == null || preAcceptSlopTolerance >= 0,
         'The preAcceptSlopTolerance must be positive or null',
       ),
       assert(
         postAcceptSlopTolerance == null || postAcceptSlopTolerance >= 0,
         'The postAcceptSlopTolerance must be positive or null',
       ),
403
       super(debugOwner: debugOwner, kind: kind);
404

405 406
  /// If non-null, the recognizer will call [didExceedDeadline] after this
  /// amount of time has elapsed since starting to track the primary pointer.
407 408 409
  ///
  /// The [didExceedDeadline] will not be called if the primary pointer is
  /// accepted, rejected, or all pointers are up or canceled before [deadline].
410
  final Duration? deadline;
411

412 413 414 415 416 417 418
  /// The maximum distance in logical pixels the gesture is allowed to drift
  /// from the initial touch down position before the gesture is accepted.
  ///
  /// Drifting past the allowed slop amount causes the gesture to be rejected.
  ///
  /// Can be null to indicate that the gesture can drift for any distance.
  /// Defaults to 18 logical pixels.
419
  final double? preAcceptSlopTolerance;
420 421 422 423 424 425 426 427 428

  /// The maximum distance in logical pixels the gesture is allowed to drift
  /// after the gesture has been accepted.
  ///
  /// Drifting past the allowed slop amount causes the gesture to stop tracking
  /// and signaling subsequent callbacks.
  ///
  /// Can be null to indicate that the gesture can drift for any distance.
  /// Defaults to 18 logical pixels.
429
  final double? postAcceptSlopTolerance;
430

431 432 433
  /// The current state of the recognizer.
  ///
  /// See [GestureRecognizerState] for a description of the states.
434
  GestureRecognizerState state = GestureRecognizerState.ready;
435 436

  /// The ID of the primary pointer this recognizer is tracking.
437
  int? primaryPointer;
438

439
  /// The location at which the primary pointer contacted the screen.
440
  OffsetPair? initialPosition;
441

442 443 444
  // Whether this pointer is accepted by winning the arena or as defined by
  // a subclass calling acceptGesture.
  bool _gestureAccepted = false;
445
  Timer? _timer;
446

447
  @override
448
  void addAllowedPointer(PointerDownEvent event) {
449
    startTrackingPointer(event.pointer, event.transform);
450 451 452
    if (state == GestureRecognizerState.ready) {
      state = GestureRecognizerState.possible;
      primaryPointer = event.pointer;
453
      initialPosition = OffsetPair(local: event.localPosition, global: event.position);
454
      if (deadline != null)
455
        _timer = Timer(deadline!, () => didExceedDeadlineWithEvent(event));
456 457 458
    }
  }

459
  @override
Ian Hickson's avatar
Ian Hickson committed
460
  void handleEvent(PointerEvent event) {
461
    assert(state != GestureRecognizerState.ready);
xster's avatar
xster committed
462
    if (state == GestureRecognizerState.possible && event.pointer == primaryPointer) {
463 464 465
      final bool isPreAcceptSlopPastTolerance =
          !_gestureAccepted &&
          preAcceptSlopTolerance != null &&
466
          _getGlobalDistance(event) > preAcceptSlopTolerance!;
467 468 469
      final bool isPostAcceptSlopPastTolerance =
          _gestureAccepted &&
          postAcceptSlopTolerance != null &&
470
          _getGlobalDistance(event) > postAcceptSlopTolerance!;
471 472

      if (event is PointerMoveEvent && (isPreAcceptSlopPastTolerance || isPostAcceptSlopPastTolerance)) {
473
        resolve(GestureDisposition.rejected);
474
        stopTrackingPointer(primaryPointer!);
475
      } else {
476
        handlePrimaryPointer(event);
477
      }
478 479 480 481 482
    }
    stopTrackingIfPointerNoLongerDown(event);
  }

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

Florian Loitsch's avatar
Florian Loitsch committed
486
  /// Override to be notified when [deadline] is exceeded.
487
  ///
488 489
  /// You must override this method or [didExceedDeadlineWithEvent] if you
  /// supply a [deadline].
490
  @protected
491 492 493 494
  void didExceedDeadline() {
    assert(deadline == null);
  }

495 496 497 498 499 500 501 502 503 504
  /// Same as [didExceedDeadline] but receives the [event] that initiated the
  /// gesture.
  ///
  /// You must override this method or [didExceedDeadline] if you supply a
  /// [deadline].
  @protected
  void didExceedDeadlineWithEvent(PointerDownEvent event) {
    didExceedDeadline();
  }

505 506
  @override
  void acceptGesture(int pointer) {
507 508 509 510
    if (pointer == primaryPointer) {
      _stopTimer();
      _gestureAccepted = true;
    }
511 512
  }

513 514
  @override
  void rejectGesture(int pointer) {
xster's avatar
xster committed
515
    if (pointer == primaryPointer && state == GestureRecognizerState.possible) {
516
      _stopTimer();
517
      state = GestureRecognizerState.defunct;
518
    }
519 520
  }

521
  @override
522
  void didStopTrackingLastPointer(int pointer) {
523
    assert(state != GestureRecognizerState.ready);
524
    _stopTimer();
525 526 527
    state = GestureRecognizerState.ready;
  }

528
  @override
529 530 531 532 533 534 535
  void dispose() {
    _stopTimer();
    super.dispose();
  }

  void _stopTimer() {
    if (_timer != null) {
536
      _timer!.cancel();
537 538 539 540
      _timer = null;
    }
  }

541
  double _getGlobalDistance(PointerEvent event) {
542
    final Offset offset = event.position - initialPosition!.global;
543 544 545
    return offset.distance;
  }

546
  @override
547 548
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
549
    properties.add(EnumProperty<GestureRecognizerState>('state', state));
550
  }
551
}
552 553 554 555 556 557 558 559 560

/// A container for a [local] and [global] [Offset] pair.
///
/// Usually, the [global] [Offset] is in the coordinate space of the screen
/// after conversion to logical pixels and the [local] offset is the same
/// [Offset], but transformed to a local coordinate space.
class OffsetPair {
  /// Creates a [OffsetPair] combining a [local] and [global] [Offset].
  const OffsetPair({
561 562
    required this.local,
    required this.global,
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
  });

  /// Creates a [OffsetPair] from [PointerEvent.localPosition] and
  /// [PointerEvent.position].
  factory OffsetPair.fromEventPosition(PointerEvent event) {
    return OffsetPair(local: event.localPosition, global: event.position);
  }

  /// Creates a [OffsetPair] from [PointerEvent.localDelta] and
  /// [PointerEvent.delta].
  factory OffsetPair.fromEventDelta(PointerEvent event) {
    return OffsetPair(local: event.localDelta, global: event.delta);
  }

  /// A [OffsetPair] where both [Offset]s are [Offset.zero].
  static const OffsetPair zero = OffsetPair(local: Offset.zero, global: Offset.zero);

  /// The [Offset] in the local coordinate space.
  final Offset local;

  /// The [Offset] in the global coordinate space after conversion to logical
  /// pixels.
  final Offset global;

  /// Adds the `other.global` to [global] and `other.local` to [local].
  OffsetPair operator+(OffsetPair other) {
    return OffsetPair(
      local: local + other.local,
      global: global + other.global,
    );
  }

  /// Subtracts the `other.global` from [global] and `other.local` from [local].
  OffsetPair operator-(OffsetPair other) {
    return OffsetPair(
      local: local - other.local,
      global: global - other.global,
    );
  }

  @override
604
  String toString() => '${objectRuntimeType(this, 'OffsetPair')}(local: $local, global: $global)';
605
}