multidrag.dart 18.8 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 7
import 'dart:async';

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

10
import 'arena.dart';
11
import 'binding.dart';
12
import 'constants.dart';
13
import 'drag.dart';
14
import 'drag_details.dart';
15 16 17 18
import 'events.dart';
import 'recognizer.dart';
import 'velocity_tracker.dart';

19
/// Signature for when [MultiDragGestureRecognizer] recognizes the start of a drag gesture.
20
typedef GestureMultiDragStartCallback = Drag? Function(Offset position);
21

22 23 24 25
/// Per-pointer state for a [MultiDragGestureRecognizer].
///
/// A [MultiDragGestureRecognizer] tracks each pointer separately. The state for
/// each pointer is a subclass of [MultiDragPointerState].
26
abstract class MultiDragPointerState {
27 28 29
  /// Creates per-pointer state for a [MultiDragGestureRecognizer].
  ///
  /// The [initialPosition] argument must not be null.
30 31
  MultiDragPointerState(this.initialPosition, this.kind)
    : assert(initialPosition != null),
32
      _velocityTracker = VelocityTracker.withKind(kind);
33

34
  /// The global coordinates of the pointer when the pointer contacted the screen.
35
  final Offset initialPosition;
36

37 38 39 40 41 42 43
  final VelocityTracker _velocityTracker;

  /// The kind of pointer performing the multi-drag gesture.
  ///
  /// Used by subclasses to determine the appropriate hit slop, for example.
  final PointerDeviceKind kind;

44
  Drag? _client;
45

46 47 48 49 50 51
  /// The offset of the pointer from the last position that was reported to the client.
  ///
  /// After the pointer contacts the screen, the pointer might move some
  /// distance before this movement will be recognized as a drag. This field
  /// accumulates that movement so that we can report it to the client after
  /// the drag starts.
52 53
  Offset? get pendingDelta => _pendingDelta;
  Offset? _pendingDelta = Offset.zero;
54

55
  Duration? _lastPendingEventTimestamp;
56

57
  GestureArenaEntry? _arenaEntry;
58 59 60 61 62 63 64
  void _setArenaEntry(GestureArenaEntry entry) {
    assert(_arenaEntry == null);
    assert(pendingDelta != null);
    assert(_client == null);
    _arenaEntry = entry;
  }

65
  /// Resolve this pointer's entry in the [GestureArenaManager] with the given disposition.
66
  @protected
67
  @mustCallSuper
68
  void resolve(GestureDisposition disposition) {
69
    _arenaEntry!.resolve(disposition);
70 71 72 73
  }

  void _move(PointerMoveEvent event) {
    assert(_arenaEntry != null);
74 75
    if (!event.synthesized)
      _velocityTracker.addPosition(event.timeStamp, event.position);
76 77
    if (_client != null) {
      assert(pendingDelta == null);
78
      // Call client last to avoid reentrancy.
79
      _client!.update(DragUpdateDetails(
80
        sourceTimeStamp: event.timeStamp,
81 82 83
        delta: event.delta,
        globalPosition: event.position,
      ));
84 85
    } else {
      assert(pendingDelta != null);
86
      _pendingDelta = _pendingDelta! + event.delta;
87
      _lastPendingEventTimestamp = event.timeStamp;
88 89 90 91 92 93 94
      checkForResolutionAfterMove();
    }
  }

  /// Override this to call resolve() if the drag should be accepted or rejected.
  /// This is called when a pointer movement is received, but only if the gesture
  /// has not yet been resolved.
95
  @protected
96 97 98
  void checkForResolutionAfterMove() { }

  /// Called when the gesture was accepted.
99 100 101
  ///
  /// Either immediately or at some future point before the gesture is disposed,
  /// call starter(), passing it initialPosition, to start the drag.
102
  @protected
103 104 105 106
  void accepted(GestureMultiDragStartCallback starter);

  /// Called when the gesture was rejected.
  ///
107
  /// The [dispose] method will be called immediately following this.
108 109
  @protected
  @mustCallSuper
110
  void rejected() {
111 112
    assert(_arenaEntry != null);
    assert(_client == null);
113
    assert(pendingDelta != null);
114
    _pendingDelta = null;
115
    _lastPendingEventTimestamp = null;
116
    _arenaEntry = null;
117 118
  }

119
  void _startDrag(Drag client) {
120 121
    assert(_arenaEntry != null);
    assert(_client == null);
122
    assert(client != null);
123
    assert(pendingDelta != null);
124
    _client = client;
125
    final DragUpdateDetails details = DragUpdateDetails(
126
      sourceTimeStamp: _lastPendingEventTimestamp,
127
      delta: pendingDelta!,
128 129
      globalPosition: initialPosition,
    );
130
    _pendingDelta = null;
131
    _lastPendingEventTimestamp = null;
132
    // Call client last to avoid reentrancy.
133
    _client!.update(details);
134 135 136 137 138 139
  }

  void _up() {
    assert(_arenaEntry != null);
    if (_client != null) {
      assert(pendingDelta == null);
140
      final DragEndDetails details = DragEndDetails(velocity: _velocityTracker.getVelocity());
141
      final Drag client = _client!;
142
      _client = null;
143 144
      // Call client last to avoid reentrancy.
      client.end(details);
145 146 147
    } else {
      assert(pendingDelta != null);
      _pendingDelta = null;
148
      _lastPendingEventTimestamp = null;
149 150 151 152 153 154 155
    }
  }

  void _cancel() {
    assert(_arenaEntry != null);
    if (_client != null) {
      assert(pendingDelta == null);
156
      final Drag client = _client!;
157
      _client = null;
158 159
      // Call client last to avoid reentrancy.
      client.cancel();
160 161 162
    } else {
      assert(pendingDelta != null);
      _pendingDelta = null;
163
      _lastPendingEventTimestamp = null;
164 165 166
    }
  }

167
  /// Releases any resources used by the object.
168
  @protected
169
  @mustCallSuper
170
  void dispose() {
171
    _arenaEntry?.resolve(GestureDisposition.rejected);
172
    _arenaEntry = null;
173 174 175 176
    assert(() {
      _pendingDelta = null;
      return true;
    }());
177
  }
178 179
}

180 181
/// Recognizes movement on a per-pointer basis.
///
182 183 184
/// In contrast to [DragGestureRecognizer], [MultiDragGestureRecognizer] watches
/// each pointer separately, which means multiple drags can be recognized
/// concurrently if multiple pointers are in contact with the screen.
185 186 187 188 189 190 191
///
/// [MultiDragGestureRecognizer] is not intended to be used directly. Instead,
/// consider using one of its subclasses to recognize specific types for drag
/// gestures.
///
/// See also:
///
192 193 194 195 196 197 198 199
///  * [ImmediateMultiDragGestureRecognizer], the most straight-forward variant
///    of multi-pointer drag gesture recognizer.
///  * [HorizontalMultiDragGestureRecognizer], which only recognizes drags that
///    start horizontally.
///  * [VerticalMultiDragGestureRecognizer], which only recognizes drags that
///    start vertically.
///  * [DelayedMultiDragGestureRecognizer], which only recognizes drags that
///    start after a long-press gesture.
200
abstract class MultiDragGestureRecognizer<T extends MultiDragPointerState> extends GestureRecognizer {
201
  /// Initialize the object.
202
  MultiDragGestureRecognizer({
203 204
    required Object? debugOwner,
    PointerDeviceKind? kind,
205
  }) : super(debugOwner: debugOwner, kind: kind);
206

207 208 209 210
  /// Called when this class recognizes the start of a drag gesture.
  ///
  /// The remaining notifications for this drag gesture are delivered to the
  /// [Drag] object returned by this callback.
211
  GestureMultiDragStartCallback? onStart;
212

213
  Map<int, T>? _pointers = <int, T>{};
214

215
  @override
216
  void addAllowedPointer(PointerDownEvent event) {
217 218 219
    assert(_pointers != null);
    assert(event.pointer != null);
    assert(event.position != null);
220
    assert(!_pointers!.containsKey(event.pointer));
221
    final T state = createNewPointerState(event);
222 223 224
    _pointers![event.pointer] = state;
    GestureBinding.instance!.pointerRouter.addRoute(event.pointer, _handleEvent);
    state._setArenaEntry(GestureBinding.instance!.gestureArena.add(event.pointer, this));
225 226
  }

227
  /// Subclasses should override this method to create per-pointer state
228
  /// objects to track the pointer associated with the given event.
229
  @protected
230
  @factory
231 232
  T createNewPointerState(PointerDownEvent event);

233
  void _handleEvent(PointerEvent event) {
234 235 236 237
    assert(_pointers != null);
    assert(event.pointer != null);
    assert(event.timeStamp != null);
    assert(event.position != null);
238 239
    assert(_pointers!.containsKey(event.pointer));
    final T state = _pointers![event.pointer]!;
240 241
    if (event is PointerMoveEvent) {
      state._move(event);
242
      // We might be disposed here.
243 244 245
    } else if (event is PointerUpEvent) {
      assert(event.delta == Offset.zero);
      state._up();
246
      // We might be disposed here.
247 248 249 250
      _removeState(event.pointer);
    } else if (event is PointerCancelEvent) {
      assert(event.delta == Offset.zero);
      state._cancel();
251
      // We might be disposed here.
252 253
      _removeState(event.pointer);
    } else if (event is! PointerDownEvent) {
254
      // we get the PointerDownEvent that resulted in our addPointer getting called since we
255 256 257 258 259 260
      // add ourselves to the pointer router then (before the pointer router has heard of
      // the event).
      assert(false);
    }
  }

261
  @override
262 263
  void acceptGesture(int pointer) {
    assert(_pointers != null);
264
    final T? state = _pointers![pointer];
265 266
    if (state == null)
      return; // We might already have canceled this drag if the up comes before the accept.
267
    state.accepted((Offset initialPosition) => _startDrag(initialPosition, pointer));
268 269
  }

270
  Drag? _startDrag(Offset initialPosition, int pointer) {
271
    assert(_pointers != null);
272
    final T state = _pointers![pointer]!;
273 274
    assert(state != null);
    assert(state._pendingDelta != null);
275
    Drag? drag;
276
    if (onStart != null)
277
      drag = invokeCallback<Drag?>('onStart', () => onStart!(initialPosition));
278
    if (drag != null) {
279
      state._startDrag(drag);
280 281 282
    } else {
      _removeState(pointer);
    }
283
    return drag;
284 285
  }

286
  @override
287 288
  void rejectGesture(int pointer) {
    assert(_pointers != null);
289 290
    if (_pointers!.containsKey(pointer)) {
      final T state = _pointers![pointer]!;
291 292 293 294 295 296 297
      assert(state != null);
      state.rejected();
      _removeState(pointer);
    } // else we already preemptively forgot about it (e.g. we got an up event)
  }

  void _removeState(int pointer) {
298 299 300 301 302
    if (_pointers == null) {
      // We've already been disposed. It's harmless to skip removing the state
      // for the given pointer because dispose() has already removed it.
      return;
    }
303 304 305
    assert(_pointers!.containsKey(pointer));
    GestureBinding.instance!.pointerRouter.removeRoute(pointer, _handleEvent);
    _pointers!.remove(pointer)!.dispose();
306 307
  }

308
  @override
309
  void dispose() {
310 311
    _pointers!.keys.toList().forEach(_removeState);
    assert(_pointers!.isEmpty);
312 313 314 315 316 317
    _pointers = null;
    super.dispose();
  }
}

class _ImmediatePointerState extends MultiDragPointerState {
318
  _ImmediatePointerState(Offset initialPosition, PointerDeviceKind kind) : super(initialPosition, kind);
319

320
  @override
321 322
  void checkForResolutionAfterMove() {
    assert(pendingDelta != null);
323
    if (pendingDelta!.distance > computeHitSlop(kind))
324 325
      resolve(GestureDisposition.accepted);
  }
326

327
  @override
328 329 330
  void accepted(GestureMultiDragStartCallback starter) {
    starter(initialPosition);
  }
331 332
}

333 334 335 336 337 338 339 340
/// Recognizes movement both horizontally and vertically on a per-pointer basis.
///
/// In contrast to [PanGestureRecognizer], [ImmediateMultiDragGestureRecognizer]
/// watches each pointer separately, which means multiple drags can be
/// recognized concurrently if multiple pointers are in contact with the screen.
///
/// See also:
///
341 342 343 344 345 346 347 348
///  * [PanGestureRecognizer], which recognizes only one drag gesture at a time,
///    regardless of how many fingers are involved.
///  * [HorizontalMultiDragGestureRecognizer], which only recognizes drags that
///    start horizontally.
///  * [VerticalMultiDragGestureRecognizer], which only recognizes drags that
///    start vertically.
///  * [DelayedMultiDragGestureRecognizer], which only recognizes drags that
///    start after a long-press gesture.
349
class ImmediateMultiDragGestureRecognizer extends MultiDragGestureRecognizer<_ImmediatePointerState> {
350
  /// Create a gesture recognizer for tracking multiple pointers at once.
351
  ImmediateMultiDragGestureRecognizer({
352 353
    Object? debugOwner,
    PointerDeviceKind? kind,
354
  }) : super(debugOwner: debugOwner, kind: kind);
355

356
  @override
357
  _ImmediatePointerState createNewPointerState(PointerDownEvent event) {
358
    return _ImmediatePointerState(event.position, event.kind);
359
  }
360

361
  @override
362
  String get debugDescription => 'multidrag';
363 364
}

365 366

class _HorizontalPointerState extends MultiDragPointerState {
367
  _HorizontalPointerState(Offset initialPosition, PointerDeviceKind kind) : super(initialPosition, kind);
368

369
  @override
370 371
  void checkForResolutionAfterMove() {
    assert(pendingDelta != null);
372
    if (pendingDelta!.dx.abs() > computeHitSlop(kind))
373 374 375
      resolve(GestureDisposition.accepted);
  }

376
  @override
377 378 379 380 381
  void accepted(GestureMultiDragStartCallback starter) {
    starter(initialPosition);
  }
}

382 383 384 385 386 387 388 389 390
/// Recognizes movement in the horizontal direction on a per-pointer basis.
///
/// In contrast to [HorizontalDragGestureRecognizer],
/// [HorizontalMultiDragGestureRecognizer] watches each pointer separately,
/// which means multiple drags can be recognized concurrently if multiple
/// pointers are in contact with the screen.
///
/// See also:
///
391 392 393 394 395 396
///  * [HorizontalDragGestureRecognizer], a gesture recognizer that just
///    looks at horizontal movement.
///  * [ImmediateMultiDragGestureRecognizer], a similar recognizer, but without
///    the limitation that the drag must start horizontally.
///  * [VerticalMultiDragGestureRecognizer], which only recognizes drags that
///    start vertically.
397
class HorizontalMultiDragGestureRecognizer extends MultiDragGestureRecognizer<_HorizontalPointerState> {
398 399
  /// Create a gesture recognizer for tracking multiple pointers at once
  /// but only if they first move horizontally.
400
  HorizontalMultiDragGestureRecognizer({
401 402
    Object? debugOwner,
    PointerDeviceKind? kind,
403
  }) : super(debugOwner: debugOwner, kind: kind);
404

405
  @override
406
  _HorizontalPointerState createNewPointerState(PointerDownEvent event) {
407
    return _HorizontalPointerState(event.position, event.kind);
408
  }
409

410
  @override
411
  String get debugDescription => 'horizontal multidrag';
412 413 414 415
}


class _VerticalPointerState extends MultiDragPointerState {
416
  _VerticalPointerState(Offset initialPosition, PointerDeviceKind kind) : super(initialPosition, kind);
417

418
  @override
419 420
  void checkForResolutionAfterMove() {
    assert(pendingDelta != null);
421
    if (pendingDelta!.dy.abs() > computeHitSlop(kind))
422 423 424
      resolve(GestureDisposition.accepted);
  }

425
  @override
426 427 428 429 430
  void accepted(GestureMultiDragStartCallback starter) {
    starter(initialPosition);
  }
}

431 432 433 434 435 436 437 438 439
/// Recognizes movement in the vertical direction on a per-pointer basis.
///
/// In contrast to [VerticalDragGestureRecognizer],
/// [VerticalMultiDragGestureRecognizer] watches each pointer separately,
/// which means multiple drags can be recognized concurrently if multiple
/// pointers are in contact with the screen.
///
/// See also:
///
440 441 442 443 444 445
///  * [VerticalDragGestureRecognizer], a gesture recognizer that just
///    looks at vertical movement.
///  * [ImmediateMultiDragGestureRecognizer], a similar recognizer, but without
///    the limitation that the drag must start vertically.
///  * [HorizontalMultiDragGestureRecognizer], which only recognizes drags that
///    start horizontally.
446
class VerticalMultiDragGestureRecognizer extends MultiDragGestureRecognizer<_VerticalPointerState> {
447 448
  /// Create a gesture recognizer for tracking multiple pointers at once
  /// but only if they first move vertically.
449
  VerticalMultiDragGestureRecognizer({
450 451
    Object? debugOwner,
    PointerDeviceKind? kind,
452
  }) : super(debugOwner: debugOwner, kind: kind);
453

454
  @override
455
  _VerticalPointerState createNewPointerState(PointerDownEvent event) {
456
    return _VerticalPointerState(event.position, event.kind);
457
  }
458

459
  @override
460
  String get debugDescription => 'vertical multidrag';
461 462
}

463
class _DelayedPointerState extends MultiDragPointerState {
464
  _DelayedPointerState(Offset initialPosition, Duration delay, PointerDeviceKind kind)
465
      : assert(delay != null),
466
        super(initialPosition, kind) {
467
    _timer = Timer(delay, _delayPassed);
468 469
  }

470 471
  Timer? _timer;
  GestureMultiDragStartCallback? _starter;
472 473 474 475

  void _delayPassed() {
    assert(_timer != null);
    assert(pendingDelta != null);
476
    assert(pendingDelta!.distance <= computeHitSlop(kind));
477
    _timer = null;
478
    if (_starter != null) {
479
      _starter!(initialPosition);
480 481 482 483 484
      _starter = null;
    } else {
      resolve(GestureDisposition.accepted);
    }
    assert(_starter == null);
485 486
  }

487 488 489 490 491
  void _ensureTimerStopped() {
    _timer?.cancel();
    _timer = null;
  }

492
  @override
493 494 495 496 497 498
  void accepted(GestureMultiDragStartCallback starter) {
    assert(_starter == null);
    if (_timer == null)
      starter(initialPosition);
    else
      _starter = starter;
499 500
  }

501
  @override
502
  void checkForResolutionAfterMove() {
503 504 505 506 507 508 509 510 511
    if (_timer == null) {
      // If we've been accepted by the gesture arena but the pointer moves too
      // much before the timer fires, we end up a state where the timer is
      // stopped but we keep getting calls to this function because we never
      // actually started the drag. In this case, _starter will be non-null
      // because we're essentially waiting forever to start the drag.
      assert(_starter != null);
      return;
    }
512
    assert(pendingDelta != null);
513
    if (pendingDelta!.distance > computeHitSlop(kind)) {
514
      resolve(GestureDisposition.rejected);
515 516
      _ensureTimerStopped();
    }
517 518
  }

519
  @override
520
  void dispose() {
521
    _ensureTimerStopped();
522 523 524 525
    super.dispose();
  }
}

526 527
/// Recognizes movement both horizontally and vertically on a per-pointer basis
/// after a delay.
528
///
529
/// In contrast to [ImmediateMultiDragGestureRecognizer],
530 531 532 533 534 535 536 537 538 539
/// [DelayedMultiDragGestureRecognizer] waits for a [delay] before recognizing
/// the drag. If the pointer moves more than [kTouchSlop] before the delay
/// expires, the gesture is not recognized.
///
/// In contrast to [PanGestureRecognizer], [DelayedMultiDragGestureRecognizer]
/// watches each pointer separately, which means multiple drags can be
/// recognized concurrently if multiple pointers are in contact with the screen.
///
/// See also:
///
540 541 542 543
///  * [ImmediateMultiDragGestureRecognizer], a similar recognizer but without
///    the delay.
///  * [PanGestureRecognizer], which recognizes only one drag gesture at a time,
///    regardless of how many fingers are involved.
544
class DelayedMultiDragGestureRecognizer extends MultiDragGestureRecognizer<_DelayedPointerState> {
545 546 547 548 549 550
  /// Creates a drag recognizer that works on a per-pointer basis after a delay.
  ///
  /// In order for a drag to be recognized by this recognizer, the pointer must
  /// remain in the same place for [delay] (up to [kTouchSlop]). The [delay]
  /// defaults to [kLongPressTimeout] to match [LongPressGestureRecognizer] but
  /// can be changed for specific behaviors.
551
  DelayedMultiDragGestureRecognizer({
552
    this.delay = kLongPressTimeout,
553 554
    Object? debugOwner,
    PointerDeviceKind? kind,
555
  }) : assert(delay != null),
556
       super(debugOwner: debugOwner, kind: kind);
557

558 559
  /// The amount of time the pointer must remain in the same place for the drag
  /// to be recognized.
560
  final Duration delay;
561

562
  @override
563
  _DelayedPointerState createNewPointerState(PointerDownEvent event) {
564
    return _DelayedPointerState(event.position, delay, event.kind);
565
  }
566

567
  @override
568
  String get debugDescription => 'long multidrag';
569
}