multidrag.dart 17.8 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 Drag GestureMultiDragStartCallback(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 37 38

  final VelocityTracker _velocityTracker = new VelocityTracker();
  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 48 49 50 51 52 53 54 55
  Offset get pendingDelta => _pendingDelta;
  Offset _pendingDelta = Offset.zero;

  GestureArenaEntry _arenaEntry;
  void _setArenaEntry(GestureArenaEntry entry) {
    assert(_arenaEntry == null);
    assert(pendingDelta != null);
    assert(_client == null);
    _arenaEntry = entry;
  }

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

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

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

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

107
  void _startDrag(Drag client) {
108 109
    assert(_arenaEntry != null);
    assert(_client == null);
110
    assert(client != null);
111
    assert(pendingDelta != null);
112
    _client = client;
113 114 115 116
    final DragUpdateDetails details = new DragUpdateDetails(
      delta: pendingDelta,
      globalPosition: initialPosition,
    );
117
    _pendingDelta = null;
118 119
    // Call client last to avoid reentrancy.
    _client.update(details);
120 121 122 123 124 125
  }

  void _up() {
    assert(_arenaEntry != null);
    if (_client != null) {
      assert(pendingDelta == null);
126
      final DragEndDetails details = new DragEndDetails(velocity: _velocityTracker.getVelocity());
127
      final Drag client = _client;
128
      _client = null;
129 130
      // Call client last to avoid reentrancy.
      client.end(details);
131 132 133 134 135 136 137 138 139 140
    } else {
      assert(pendingDelta != null);
      _pendingDelta = null;
    }
  }

  void _cancel() {
    assert(_arenaEntry != null);
    if (_client != null) {
      assert(pendingDelta == null);
141
      final Drag client = _client;
142
      _client = null;
143 144
      // Call client last to avoid reentrancy.
      client.cancel();
145 146 147 148 149 150
    } else {
      assert(pendingDelta != null);
      _pendingDelta = null;
    }
  }

151
  /// Releases any resources used by the object.
152
  @protected
153
  @mustCallSuper
154
  void dispose() {
155
    _arenaEntry?.resolve(GestureDisposition.rejected);
156
    _arenaEntry = null;
157 158
    assert(() { _pendingDelta = null; return true; });
  }
159 160
}

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

185 186 187 188
  /// 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.
189 190 191 192
  GestureMultiDragStartCallback onStart;

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

193
  @override
194 195 196 197 198
  void addPointer(PointerDownEvent event) {
    assert(_pointers != null);
    assert(event.pointer != null);
    assert(event.position != null);
    assert(!_pointers.containsKey(event.pointer));
199
    final T state = createNewPointerState(event);
200
    _pointers[event.pointer] = state;
201
    GestureBinding.instance.pointerRouter.addRoute(event.pointer, _handleEvent);
202
    state._setArenaEntry(GestureBinding.instance.gestureArena.add(event.pointer, this));
203 204
  }

205
  /// Subclasses should override this method to create per-pointer state
206
  /// objects to track the pointer associated with the given event.
207
  @protected
208 209
  T createNewPointerState(PointerDownEvent event);

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

238
  @override
239 240
  void acceptGesture(int pointer) {
    assert(_pointers != null);
241
    final T state = _pointers[pointer];
242 243
    if (state == null)
      return; // We might already have canceled this drag if the up comes before the accept.
244
    state.accepted((Offset initialPosition) => _startDrag(initialPosition, pointer));
245 246
  }

247
  Drag _startDrag(Offset initialPosition, int pointer) {
248
    assert(_pointers != null);
249
    final T state = _pointers[pointer];
250 251
    assert(state != null);
    assert(state._pendingDelta != null);
252 253
    Drag drag;
    if (onStart != null)
254
      drag = invokeCallback<Drag>('onStart', () => onStart(initialPosition));
255
    if (drag != null) {
256
      state._startDrag(drag);
257 258 259
    } else {
      _removeState(pointer);
    }
260
    return drag;
261 262
  }

263
  @override
264 265 266
  void rejectGesture(int pointer) {
    assert(_pointers != null);
    if (_pointers.containsKey(pointer)) {
267
      final T state = _pointers[pointer];
268 269 270 271 272 273 274
      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) {
275 276 277 278 279
    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;
    }
280
    assert(_pointers.containsKey(pointer));
281
    GestureBinding.instance.pointerRouter.removeRoute(pointer, _handleEvent);
282
    _pointers.remove(pointer).dispose();
283 284
  }

285
  @override
286
  void dispose() {
287
    for (int pointer in _pointers.keys.toList())
288
      _removeState(pointer);
289
    assert(_pointers.isEmpty);
290 291 292 293 294 295
    _pointers = null;
    super.dispose();
  }
}

class _ImmediatePointerState extends MultiDragPointerState {
296
  _ImmediatePointerState(Offset initialPosition) : super(initialPosition);
297

298
  @override
299 300 301 302 303
  void checkForResolutionAfterMove() {
    assert(pendingDelta != null);
    if (pendingDelta.distance > kTouchSlop)
      resolve(GestureDisposition.accepted);
  }
304

305
  @override
306 307 308
  void accepted(GestureMultiDragStartCallback starter) {
    starter(initialPosition);
  }
309 310
}

311 312 313 314 315 316 317 318
/// 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:
///
319 320 321 322 323 324 325 326
///  * [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.
327
class ImmediateMultiDragGestureRecognizer extends MultiDragGestureRecognizer<_ImmediatePointerState> {
328 329 330
  /// Create a gesture recognizer for tracking multiple pointers at once.
  ImmediateMultiDragGestureRecognizer({ Object debugOwner }) : super(debugOwner: debugOwner);

331
  @override
332 333 334
  _ImmediatePointerState createNewPointerState(PointerDownEvent event) {
    return new _ImmediatePointerState(event.position);
  }
335

336
  @override
337
  String get debugDescription => 'multidrag';
338 339
}

340 341

class _HorizontalPointerState extends MultiDragPointerState {
342
  _HorizontalPointerState(Offset initialPosition) : super(initialPosition);
343

344
  @override
345 346 347 348 349 350
  void checkForResolutionAfterMove() {
    assert(pendingDelta != null);
    if (pendingDelta.dx.abs() > kTouchSlop)
      resolve(GestureDisposition.accepted);
  }

351
  @override
352 353 354 355 356
  void accepted(GestureMultiDragStartCallback starter) {
    starter(initialPosition);
  }
}

357 358 359 360 361 362 363 364 365
/// 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:
///
366 367 368 369 370 371
///  * [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.
372
class HorizontalMultiDragGestureRecognizer extends MultiDragGestureRecognizer<_HorizontalPointerState> {
373 374 375 376
  /// Create a gesture recognizer for tracking multiple pointers at once
  /// but only if they first move horizontally.
  HorizontalMultiDragGestureRecognizer({ Object debugOwner }) : super(debugOwner: debugOwner);

377
  @override
378 379 380
  _HorizontalPointerState createNewPointerState(PointerDownEvent event) {
    return new _HorizontalPointerState(event.position);
  }
381

382
  @override
383
  String get debugDescription => 'horizontal multidrag';
384 385 386 387
}


class _VerticalPointerState extends MultiDragPointerState {
388
  _VerticalPointerState(Offset initialPosition) : super(initialPosition);
389

390
  @override
391 392 393 394 395 396
  void checkForResolutionAfterMove() {
    assert(pendingDelta != null);
    if (pendingDelta.dy.abs() > kTouchSlop)
      resolve(GestureDisposition.accepted);
  }

397
  @override
398 399 400 401 402
  void accepted(GestureMultiDragStartCallback starter) {
    starter(initialPosition);
  }
}

403 404 405 406 407 408 409 410 411
/// 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:
///
412 413 414 415 416 417
///  * [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.
418
class VerticalMultiDragGestureRecognizer extends MultiDragGestureRecognizer<_VerticalPointerState> {
419 420 421 422
  /// Create a gesture recognizer for tracking multiple pointers at once
  /// but only if they first move vertically.
  VerticalMultiDragGestureRecognizer({ Object debugOwner }) : super(debugOwner: debugOwner);

423
  @override
424 425 426
  _VerticalPointerState createNewPointerState(PointerDownEvent event) {
    return new _VerticalPointerState(event.position);
  }
427

428
  @override
429
  String get debugDescription => 'vertical multidrag';
430 431
}

432
class _DelayedPointerState extends MultiDragPointerState {
433 434 435
  _DelayedPointerState(Offset initialPosition, Duration delay)
    : assert(delay != null),
      super(initialPosition) {
436 437 438 439
    _timer = new Timer(delay, _delayPassed);
  }

  Timer _timer;
440
  GestureMultiDragStartCallback _starter;
441 442 443 444 445 446

  void _delayPassed() {
    assert(_timer != null);
    assert(pendingDelta != null);
    assert(pendingDelta.distance <= kTouchSlop);
    _timer = null;
447 448 449 450 451 452 453
    if (_starter != null) {
      _starter(initialPosition);
      _starter = null;
    } else {
      resolve(GestureDisposition.accepted);
    }
    assert(_starter == null);
454 455
  }

456 457 458 459 460
  void _ensureTimerStopped() {
    _timer?.cancel();
    _timer = null;
  }

461
  @override
462 463 464 465 466 467
  void accepted(GestureMultiDragStartCallback starter) {
    assert(_starter == null);
    if (_timer == null)
      starter(initialPosition);
    else
      _starter = starter;
468 469
  }

470
  @override
471
  void checkForResolutionAfterMove() {
472 473 474 475 476 477 478 479 480
    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;
    }
481
    assert(pendingDelta != null);
482
    if (pendingDelta.distance > kTouchSlop) {
483
      resolve(GestureDisposition.rejected);
484 485
      _ensureTimerStopped();
    }
486 487
  }

488
  @override
489
  void dispose() {
490
    _ensureTimerStopped();
491 492 493 494
    super.dispose();
  }
}

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

526 527
  /// The amount of time the pointer must remain in the same place for the drag
  /// to be recognized.
528
  final Duration delay;
529

530
  @override
531
  _DelayedPointerState createNewPointerState(PointerDownEvent event) {
532
    return new _DelayedPointerState(event.position, delay);
533
  }
534

535
  @override
536
  String get debugDescription => 'long multidrag';
537
}