multidrag.dart 16.1 KB
Newer Older
1 2 3 4 5 6 7
// 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';
import 'dart:ui' show Point, Offset;

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

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

18
/// Signature for when [MultiDragGestureRecognizer] recognizes the start of a drag gesture.
19 20
typedef Drag GestureMultiDragStartCallback(Point position);

21 22
/// Interface for receiving updates about drags from a [MultiDragGestureRecognizer].
abstract class Drag {
23 24
  /// The pointer has moved.
  void update(DragUpdateDetails details) { }
25

26 27 28 29 30
  /// The pointer is no longer in contact with the screen.
  ///
  /// The velocity at which the pointer was moving when it stopped contacting
  /// the screen is available in the `details`.
  void end(DragEndDetails details) { }
31 32 33 34 35

  /// The input from the pointer is no longer directed towards this receiver.
  ///
  /// For example, the user might have been interrupted by a system-modal dialog
  /// in the middle of the drag.
36 37 38
  void cancel() { }
}

39 40 41 42
/// Per-pointer state for a [MultiDragGestureRecognizer].
///
/// A [MultiDragGestureRecognizer] tracks each pointer separately. The state for
/// each pointer is a subclass of [MultiDragPointerState].
43
abstract class MultiDragPointerState {
44 45 46 47 48 49
  /// Creates per-pointer state for a [MultiDragGestureRecognizer].
  ///
  /// The [initialPosition] argument must not be null.
  MultiDragPointerState(this.initialPosition) {
    assert(initialPosition != null);
  }
50

51
  /// The global coordinates of the pointer when the pointer contacted the screen.
52 53 54 55 56
  final Point initialPosition;

  final VelocityTracker _velocityTracker = new VelocityTracker();
  Drag _client;

57 58 59 60 61 62
  /// 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.
63 64 65 66 67 68 69 70 71 72 73
  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;
  }

74
  /// Resolve this pointer's entry in the [GestureArenaManager] with the given disposition.
75
  @protected
76
  @mustCallSuper
77 78 79 80 81 82 83 84 85
  void resolve(GestureDisposition disposition) {
    _arenaEntry.resolve(disposition);
  }

  void _move(PointerMoveEvent event) {
    assert(_arenaEntry != null);
    _velocityTracker.addPosition(event.timeStamp, event.position);
    if (_client != null) {
      assert(pendingDelta == null);
86
      // Call client last to avoid reentrancy.
87 88 89 90
      _client.update(new DragUpdateDetails(
        delta: event.delta,
        globalPosition: event.position,
      ));
91 92 93 94 95 96 97 98 99 100
    } 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.
101
  @protected
102 103 104
  void checkForResolutionAfterMove() { }

  /// Called when the gesture was accepted.
105 106 107
  ///
  /// Either immediately or at some future point before the gesture is disposed,
  /// call starter(), passing it initialPosition, to start the drag.
108
  @protected
109 110 111 112 113
  void accepted(GestureMultiDragStartCallback starter);

  /// Called when the gesture was rejected.
  ///
  /// [dispose()] will be called immediately following this.
114 115
  @protected
  @mustCallSuper
116
  void rejected() {
117 118
    assert(_arenaEntry != null);
    assert(_client == null);
119
    assert(pendingDelta != null);
120
    _pendingDelta = null;
121
    _arenaEntry = null;
122 123
  }

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

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

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

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

178 179
/// Recognizes movement on a per-pointer basis.
///
180 181 182
/// 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.
183 184 185 186 187 188 189 190 191 192 193
///
/// [MultiDragGestureRecognizer] is not intended to be used directly. Instead,
/// consider using one of its subclasses to recognize specific types for drag
/// gestures.
///
/// See also:
///
///  * [HorizontalMultiDragGestureRecognizer]
///  * [VerticalMultiDragGestureRecognizer]
///  * [ImmediateMultiDragGestureRecognizer]
///  * [DelayedMultiDragGestureRecognizer]
194
abstract class MultiDragGestureRecognizer<T extends MultiDragPointerState> extends GestureRecognizer {
195 196 197 198
  /// 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.
199 200 201 202
  GestureMultiDragStartCallback onStart;

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

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

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

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

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

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

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

295
  @override
296
  void dispose() {
297
    for (int pointer in _pointers.keys.toList())
298
      _removeState(pointer);
299
    assert(_pointers.isEmpty);
300 301 302 303 304 305 306 307
    _pointers = null;
    super.dispose();
  }
}

class _ImmediatePointerState extends MultiDragPointerState {
  _ImmediatePointerState(Point initialPosition) : super(initialPosition);

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

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

321 322 323 324 325 326 327 328 329 330
/// 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:
///
///  * [PanGestureRecognizer]
///  * [DelayedMultiDragGestureRecognizer]
331
class ImmediateMultiDragGestureRecognizer extends MultiDragGestureRecognizer<_ImmediatePointerState> {
332
  @override
333 334 335
  _ImmediatePointerState createNewPointerState(PointerDownEvent event) {
    return new _ImmediatePointerState(event.position);
  }
336

337
  @override
338
  String toStringShort() => 'multidrag';
339 340
}

341 342 343 344

class _HorizontalPointerState extends MultiDragPointerState {
  _HorizontalPointerState(Point initialPosition) : super(initialPosition);

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

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

358 359 360 361 362 363 364 365 366 367
/// 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:
///
///  * [HorizontalDragGestureRecognizer]
368
class HorizontalMultiDragGestureRecognizer extends MultiDragGestureRecognizer<_HorizontalPointerState> {
369
  @override
370 371 372
  _HorizontalPointerState createNewPointerState(PointerDownEvent event) {
    return new _HorizontalPointerState(event.position);
  }
373

374
  @override
375
  String toStringShort() => 'horizontal multidrag';
376 377 378 379 380 381
}


class _VerticalPointerState extends MultiDragPointerState {
  _VerticalPointerState(Point initialPosition) : super(initialPosition);

382
  @override
383 384 385 386 387 388
  void checkForResolutionAfterMove() {
    assert(pendingDelta != null);
    if (pendingDelta.dy.abs() > kTouchSlop)
      resolve(GestureDisposition.accepted);
  }

389
  @override
390 391 392 393 394
  void accepted(GestureMultiDragStartCallback starter) {
    starter(initialPosition);
  }
}

395 396 397 398 399 400 401 402 403 404
/// 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:
///
///  * [VerticalDragGestureRecognizer]
405
class VerticalMultiDragGestureRecognizer extends MultiDragGestureRecognizer<_VerticalPointerState> {
406
  @override
407 408 409
  _VerticalPointerState createNewPointerState(PointerDownEvent event) {
    return new _VerticalPointerState(event.position);
  }
410

411
  @override
412
  String toStringShort() => 'vertical multidrag';
413 414
}

415 416 417 418 419 420 421
class _DelayedPointerState extends MultiDragPointerState {
  _DelayedPointerState(Point initialPosition, Duration delay) : super(initialPosition) {
    assert(delay != null);
    _timer = new Timer(delay, _delayPassed);
  }

  Timer _timer;
422
  GestureMultiDragStartCallback _starter;
423 424 425 426 427 428

  void _delayPassed() {
    assert(_timer != null);
    assert(pendingDelta != null);
    assert(pendingDelta.distance <= kTouchSlop);
    _timer = null;
429 430 431 432 433 434 435
    if (_starter != null) {
      _starter(initialPosition);
      _starter = null;
    } else {
      resolve(GestureDisposition.accepted);
    }
    assert(_starter == null);
436 437
  }

438 439 440 441 442
  void _ensureTimerStopped() {
    _timer?.cancel();
    _timer = null;
  }

443
  @override
444 445 446 447 448 449
  void accepted(GestureMultiDragStartCallback starter) {
    assert(_starter == null);
    if (_timer == null)
      starter(initialPosition);
    else
      _starter = starter;
450 451
  }

452
  @override
453
  void checkForResolutionAfterMove() {
454 455 456 457 458 459 460 461 462
    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;
    }
463
    assert(pendingDelta != null);
464
    if (pendingDelta.distance > kTouchSlop) {
465
      resolve(GestureDisposition.rejected);
466 467
      _ensureTimerStopped();
    }
468 469
  }

470
  @override
471
  void dispose() {
472
    _ensureTimerStopped();
473 474 475 476
    super.dispose();
  }
}

477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
/// Recognizes movement both horizontally and vertically on a per-pointer basis after a delay.
///
/// 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:
///
///  * [PanGestureRecognizer]
///  * [ImmediateMultiDragGestureRecognizer]
492
class DelayedMultiDragGestureRecognizer extends MultiDragGestureRecognizer<_DelayedPointerState> {
493 494 495 496 497 498
  /// 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.
499
  DelayedMultiDragGestureRecognizer({
500 501
    this.delay: kLongPressTimeout
  }) {
502 503 504
    assert(delay != null);
  }

505 506
  /// The amount of time the pointer must remain in the same place for the drag
  /// to be recognized.
507
  final Duration delay;
508

509
  @override
510
  _DelayedPointerState createNewPointerState(PointerDownEvent event) {
511
    return new _DelayedPointerState(event.position, delay);
512
  }
513

514
  @override
515
  String toStringShort() => 'long multidrag';
516
}