multidrag.dart 18.1 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:ui' show Offset;
7

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)
    : assert(initialPosition != null);
32

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

36
  final VelocityTracker _velocityTracker = VelocityTracker();
37 38
  Drag _client;

39 40 41 42 43 44
  /// 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.
45 46 47
  Offset get pendingDelta => _pendingDelta;
  Offset _pendingDelta = Offset.zero;

48 49
  Duration _lastPendingEventTimestamp;

50 51 52 53 54 55 56 57
  GestureArenaEntry _arenaEntry;
  void _setArenaEntry(GestureArenaEntry entry) {
    assert(_arenaEntry == null);
    assert(pendingDelta != null);
    assert(_client == null);
    _arenaEntry = entry;
  }

58
  /// Resolve this pointer's entry in the [GestureArenaManager] with the given disposition.
59
  @protected
60
  @mustCallSuper
61 62 63 64 65 66
  void resolve(GestureDisposition disposition) {
    _arenaEntry.resolve(disposition);
  }

  void _move(PointerMoveEvent event) {
    assert(_arenaEntry != null);
67 68
    if (!event.synthesized)
      _velocityTracker.addPosition(event.timeStamp, event.position);
69 70
    if (_client != null) {
      assert(pendingDelta == null);
71
      // Call client last to avoid reentrancy.
72
      _client.update(DragUpdateDetails(
73
        sourceTimeStamp: event.timeStamp,
74 75 76
        delta: event.delta,
        globalPosition: event.position,
      ));
77 78 79
    } else {
      assert(pendingDelta != null);
      _pendingDelta += event.delta;
80
      _lastPendingEventTimestamp = event.timeStamp;
81 82 83 84 85 86 87
      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.
88
  @protected
89 90 91
  void checkForResolutionAfterMove() { }

  /// Called when the gesture was accepted.
92 93 94
  ///
  /// Either immediately or at some future point before the gesture is disposed,
  /// call starter(), passing it initialPosition, to start the drag.
95
  @protected
96 97 98 99
  void accepted(GestureMultiDragStartCallback starter);

  /// Called when the gesture was rejected.
  ///
100
  /// The [dispose] method will be called immediately following this.
101 102
  @protected
  @mustCallSuper
103
  void rejected() {
104 105
    assert(_arenaEntry != null);
    assert(_client == null);
106
    assert(pendingDelta != null);
107
    _pendingDelta = null;
108
    _lastPendingEventTimestamp = null;
109
    _arenaEntry = null;
110 111
  }

112
  void _startDrag(Drag client) {
113 114
    assert(_arenaEntry != null);
    assert(_client == null);
115
    assert(client != null);
116
    assert(pendingDelta != null);
117
    _client = client;
118
    final DragUpdateDetails details = DragUpdateDetails(
119
      sourceTimeStamp: _lastPendingEventTimestamp,
120 121 122
      delta: pendingDelta,
      globalPosition: initialPosition,
    );
123
    _pendingDelta = null;
124
    _lastPendingEventTimestamp = null;
125 126
    // Call client last to avoid reentrancy.
    _client.update(details);
127 128 129 130 131 132
  }

  void _up() {
    assert(_arenaEntry != null);
    if (_client != null) {
      assert(pendingDelta == null);
133
      final DragEndDetails details = DragEndDetails(velocity: _velocityTracker.getVelocity());
134
      final Drag client = _client;
135
      _client = null;
136 137
      // Call client last to avoid reentrancy.
      client.end(details);
138 139 140
    } else {
      assert(pendingDelta != null);
      _pendingDelta = null;
141
      _lastPendingEventTimestamp = null;
142 143 144 145 146 147 148
    }
  }

  void _cancel() {
    assert(_arenaEntry != null);
    if (_client != null) {
      assert(pendingDelta == null);
149
      final Drag client = _client;
150
      _client = null;
151 152
      // Call client last to avoid reentrancy.
      client.cancel();
153 154 155
    } else {
      assert(pendingDelta != null);
      _pendingDelta = null;
156
      _lastPendingEventTimestamp = null;
157 158 159
    }
  }

160
  /// Releases any resources used by the object.
161
  @protected
162
  @mustCallSuper
163
  void dispose() {
164
    _arenaEntry?.resolve(GestureDisposition.rejected);
165
    _arenaEntry = null;
166
    assert(() { _pendingDelta = null; return true; }());
167
  }
168 169
}

170 171
/// Recognizes movement on a per-pointer basis.
///
172 173 174
/// 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.
175 176 177 178 179 180 181
///
/// [MultiDragGestureRecognizer] is not intended to be used directly. Instead,
/// consider using one of its subclasses to recognize specific types for drag
/// gestures.
///
/// See also:
///
182 183 184 185 186 187 188 189
///  * [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.
190
abstract class MultiDragGestureRecognizer<T extends MultiDragPointerState> extends GestureRecognizer {
191 192 193
  /// Initialize the object.
  MultiDragGestureRecognizer({ @required Object debugOwner }) : super(debugOwner: debugOwner);

194 195 196 197
  /// 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.
198 199 200 201
  GestureMultiDragStartCallback onStart;

  Map<int, T> _pointers = <int, T>{};

202
  @override
203 204 205 206 207
  void addPointer(PointerDownEvent event) {
    assert(_pointers != null);
    assert(event.pointer != null);
    assert(event.position != null);
    assert(!_pointers.containsKey(event.pointer));
208
    final T state = createNewPointerState(event);
209
    _pointers[event.pointer] = state;
210
    GestureBinding.instance.pointerRouter.addRoute(event.pointer, _handleEvent);
211
    state._setArenaEntry(GestureBinding.instance.gestureArena.add(event.pointer, this));
212 213
  }

214
  /// Subclasses should override this method to create per-pointer state
215
  /// objects to track the pointer associated with the given event.
216
  @protected
217 218
  T createNewPointerState(PointerDownEvent event);

219
  void _handleEvent(PointerEvent event) {
220 221 222 223 224
    assert(_pointers != null);
    assert(event.pointer != null);
    assert(event.timeStamp != null);
    assert(event.position != null);
    assert(_pointers.containsKey(event.pointer));
225
    final T state = _pointers[event.pointer];
226 227
    if (event is PointerMoveEvent) {
      state._move(event);
228
      // We might be disposed here.
229 230 231
    } else if (event is PointerUpEvent) {
      assert(event.delta == Offset.zero);
      state._up();
232
      // We might be disposed here.
233 234 235 236
      _removeState(event.pointer);
    } else if (event is PointerCancelEvent) {
      assert(event.delta == Offset.zero);
      state._cancel();
237
      // We might be disposed here.
238 239
      _removeState(event.pointer);
    } else if (event is! PointerDownEvent) {
240
      // we get the PointerDownEvent that resulted in our addPointer getting called since we
241 242 243 244 245 246
      // add ourselves to the pointer router then (before the pointer router has heard of
      // the event).
      assert(false);
    }
  }

247
  @override
248 249
  void acceptGesture(int pointer) {
    assert(_pointers != null);
250
    final T state = _pointers[pointer];
251 252
    if (state == null)
      return; // We might already have canceled this drag if the up comes before the accept.
253
    state.accepted((Offset initialPosition) => _startDrag(initialPosition, pointer));
254 255
  }

256
  Drag _startDrag(Offset initialPosition, int pointer) {
257
    assert(_pointers != null);
258
    final T state = _pointers[pointer];
259 260
    assert(state != null);
    assert(state._pendingDelta != null);
261 262
    Drag drag;
    if (onStart != null)
263
      drag = invokeCallback<Drag>('onStart', () => onStart(initialPosition));
264
    if (drag != null) {
265
      state._startDrag(drag);
266 267 268
    } else {
      _removeState(pointer);
    }
269
    return drag;
270 271
  }

272
  @override
273 274 275
  void rejectGesture(int pointer) {
    assert(_pointers != null);
    if (_pointers.containsKey(pointer)) {
276
      final T state = _pointers[pointer];
277 278 279 280 281 282 283
      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) {
284 285 286 287 288
    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;
    }
289
    assert(_pointers.containsKey(pointer));
290
    GestureBinding.instance.pointerRouter.removeRoute(pointer, _handleEvent);
291
    _pointers.remove(pointer).dispose();
292 293
  }

294
  @override
295
  void dispose() {
296
    _pointers.keys.toList().forEach(_removeState);
297
    assert(_pointers.isEmpty);
298 299 300 301 302 303
    _pointers = null;
    super.dispose();
  }
}

class _ImmediatePointerState extends MultiDragPointerState {
304
  _ImmediatePointerState(Offset initialPosition) : super(initialPosition);
305

306
  @override
307 308 309 310 311
  void checkForResolutionAfterMove() {
    assert(pendingDelta != null);
    if (pendingDelta.distance > kTouchSlop)
      resolve(GestureDisposition.accepted);
  }
312

313
  @override
314 315 316
  void accepted(GestureMultiDragStartCallback starter) {
    starter(initialPosition);
  }
317 318
}

319 320 321 322 323 324 325 326
/// 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:
///
327 328 329 330 331 332 333 334
///  * [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.
335
class ImmediateMultiDragGestureRecognizer extends MultiDragGestureRecognizer<_ImmediatePointerState> {
336 337 338
  /// Create a gesture recognizer for tracking multiple pointers at once.
  ImmediateMultiDragGestureRecognizer({ Object debugOwner }) : super(debugOwner: debugOwner);

339
  @override
340
  _ImmediatePointerState createNewPointerState(PointerDownEvent event) {
341
    return _ImmediatePointerState(event.position);
342
  }
343

344
  @override
345
  String get debugDescription => 'multidrag';
346 347
}

348 349

class _HorizontalPointerState extends MultiDragPointerState {
350
  _HorizontalPointerState(Offset initialPosition) : super(initialPosition);
351

352
  @override
353 354 355 356 357 358
  void checkForResolutionAfterMove() {
    assert(pendingDelta != null);
    if (pendingDelta.dx.abs() > kTouchSlop)
      resolve(GestureDisposition.accepted);
  }

359
  @override
360 361 362 363 364
  void accepted(GestureMultiDragStartCallback starter) {
    starter(initialPosition);
  }
}

365 366 367 368 369 370 371 372 373
/// 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:
///
374 375 376 377 378 379
///  * [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.
380
class HorizontalMultiDragGestureRecognizer extends MultiDragGestureRecognizer<_HorizontalPointerState> {
381 382 383 384
  /// Create a gesture recognizer for tracking multiple pointers at once
  /// but only if they first move horizontally.
  HorizontalMultiDragGestureRecognizer({ Object debugOwner }) : super(debugOwner: debugOwner);

385
  @override
386
  _HorizontalPointerState createNewPointerState(PointerDownEvent event) {
387
    return _HorizontalPointerState(event.position);
388
  }
389

390
  @override
391
  String get debugDescription => 'horizontal multidrag';
392 393 394 395
}


class _VerticalPointerState extends MultiDragPointerState {
396
  _VerticalPointerState(Offset initialPosition) : super(initialPosition);
397

398
  @override
399 400 401 402 403 404
  void checkForResolutionAfterMove() {
    assert(pendingDelta != null);
    if (pendingDelta.dy.abs() > kTouchSlop)
      resolve(GestureDisposition.accepted);
  }

405
  @override
406 407 408 409 410
  void accepted(GestureMultiDragStartCallback starter) {
    starter(initialPosition);
  }
}

411 412 413 414 415 416 417 418 419
/// 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:
///
420 421 422 423 424 425
///  * [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.
426
class VerticalMultiDragGestureRecognizer extends MultiDragGestureRecognizer<_VerticalPointerState> {
427 428 429 430
  /// Create a gesture recognizer for tracking multiple pointers at once
  /// but only if they first move vertically.
  VerticalMultiDragGestureRecognizer({ Object debugOwner }) : super(debugOwner: debugOwner);

431
  @override
432
  _VerticalPointerState createNewPointerState(PointerDownEvent event) {
433
    return _VerticalPointerState(event.position);
434
  }
435

436
  @override
437
  String get debugDescription => 'vertical multidrag';
438 439
}

440
class _DelayedPointerState extends MultiDragPointerState {
441
  _DelayedPointerState(Offset initialPosition, Duration delay)
442 443
      : assert(delay != null),
        super(initialPosition) {
444
    _timer = Timer(delay, _delayPassed);
445 446 447
  }

  Timer _timer;
448
  GestureMultiDragStartCallback _starter;
449 450 451 452 453 454

  void _delayPassed() {
    assert(_timer != null);
    assert(pendingDelta != null);
    assert(pendingDelta.distance <= kTouchSlop);
    _timer = null;
455 456 457 458 459 460 461
    if (_starter != null) {
      _starter(initialPosition);
      _starter = null;
    } else {
      resolve(GestureDisposition.accepted);
    }
    assert(_starter == null);
462 463
  }

464 465 466 467 468
  void _ensureTimerStopped() {
    _timer?.cancel();
    _timer = null;
  }

469
  @override
470 471 472 473 474 475
  void accepted(GestureMultiDragStartCallback starter) {
    assert(_starter == null);
    if (_timer == null)
      starter(initialPosition);
    else
      _starter = starter;
476 477
  }

478
  @override
479
  void checkForResolutionAfterMove() {
480 481 482 483 484 485 486 487 488
    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;
    }
489
    assert(pendingDelta != null);
490
    if (pendingDelta.distance > kTouchSlop) {
491
      resolve(GestureDisposition.rejected);
492 493
      _ensureTimerStopped();
    }
494 495
  }

496
  @override
497
  void dispose() {
498
    _ensureTimerStopped();
499 500 501 502
    super.dispose();
  }
}

503 504
/// Recognizes movement both horizontally and vertically on a per-pointer basis
/// after a delay.
505
///
506
/// In contrast to [ImmediateMultiDragGestureRecognizer],
507 508 509 510 511 512 513 514 515 516
/// [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:
///
517 518 519 520
///  * [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.
521
class DelayedMultiDragGestureRecognizer extends MultiDragGestureRecognizer<_DelayedPointerState> {
522 523 524 525 526 527
  /// 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.
528
  DelayedMultiDragGestureRecognizer({
529
    this.delay = kLongPressTimeout,
530 531 532
    Object debugOwner,
  }) : assert(delay != null),
       super(debugOwner: debugOwner);
533

534 535
  /// The amount of time the pointer must remain in the same place for the drag
  /// to be recognized.
536
  final Duration delay;
537

538
  @override
539
  _DelayedPointerState createNewPointerState(PointerDownEvent event) {
540
    return _DelayedPointerState(event.position, delay);
541
  }
542

543
  @override
544
  String get debugDescription => 'long multidrag';
545
}