multidrag.dart 18.3 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
  /// Initialize the object.
192 193 194 195
  MultiDragGestureRecognizer({
    @required Object debugOwner,
    PointerDeviceKind kind,
  }) : super(debugOwner: debugOwner, kind: kind);
196

197 198 199 200
  /// 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.
201 202 203 204
  GestureMultiDragStartCallback onStart;

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

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

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

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

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

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

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

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

class _ImmediatePointerState extends MultiDragPointerState {
307
  _ImmediatePointerState(Offset initialPosition) : super(initialPosition);
308

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

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

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

345
  @override
346
  _ImmediatePointerState createNewPointerState(PointerDownEvent event) {
347
    return _ImmediatePointerState(event.position);
348
  }
349

350
  @override
351
  String get debugDescription => 'multidrag';
352 353
}

354 355

class _HorizontalPointerState extends MultiDragPointerState {
356
  _HorizontalPointerState(Offset initialPosition) : super(initialPosition);
357

358
  @override
359 360 361 362 363 364
  void checkForResolutionAfterMove() {
    assert(pendingDelta != null);
    if (pendingDelta.dx.abs() > kTouchSlop)
      resolve(GestureDisposition.accepted);
  }

365
  @override
366 367 368 369 370
  void accepted(GestureMultiDragStartCallback starter) {
    starter(initialPosition);
  }
}

371 372 373 374 375 376 377 378 379
/// 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:
///
380 381 382 383 384 385
///  * [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.
386
class HorizontalMultiDragGestureRecognizer extends MultiDragGestureRecognizer<_HorizontalPointerState> {
387 388
  /// Create a gesture recognizer for tracking multiple pointers at once
  /// but only if they first move horizontally.
389 390 391 392
  HorizontalMultiDragGestureRecognizer({
    Object debugOwner,
    PointerDeviceKind kind,
  }) : super(debugOwner: debugOwner, kind: kind);
393

394
  @override
395
  _HorizontalPointerState createNewPointerState(PointerDownEvent event) {
396
    return _HorizontalPointerState(event.position);
397
  }
398

399
  @override
400
  String get debugDescription => 'horizontal multidrag';
401 402 403 404
}


class _VerticalPointerState extends MultiDragPointerState {
405
  _VerticalPointerState(Offset initialPosition) : super(initialPosition);
406

407
  @override
408 409 410 411 412 413
  void checkForResolutionAfterMove() {
    assert(pendingDelta != null);
    if (pendingDelta.dy.abs() > kTouchSlop)
      resolve(GestureDisposition.accepted);
  }

414
  @override
415 416 417 418 419
  void accepted(GestureMultiDragStartCallback starter) {
    starter(initialPosition);
  }
}

420 421 422 423 424 425 426 427 428
/// 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:
///
429 430 431 432 433 434
///  * [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.
435
class VerticalMultiDragGestureRecognizer extends MultiDragGestureRecognizer<_VerticalPointerState> {
436 437
  /// Create a gesture recognizer for tracking multiple pointers at once
  /// but only if they first move vertically.
438 439 440 441
  VerticalMultiDragGestureRecognizer({
    Object debugOwner,
    PointerDeviceKind kind,
  }) : super(debugOwner: debugOwner, kind: kind);
442

443
  @override
444
  _VerticalPointerState createNewPointerState(PointerDownEvent event) {
445
    return _VerticalPointerState(event.position);
446
  }
447

448
  @override
449
  String get debugDescription => 'vertical multidrag';
450 451
}

452
class _DelayedPointerState extends MultiDragPointerState {
453
  _DelayedPointerState(Offset initialPosition, Duration delay)
454 455
      : assert(delay != null),
        super(initialPosition) {
456
    _timer = Timer(delay, _delayPassed);
457 458 459
  }

  Timer _timer;
460
  GestureMultiDragStartCallback _starter;
461 462 463 464 465 466

  void _delayPassed() {
    assert(_timer != null);
    assert(pendingDelta != null);
    assert(pendingDelta.distance <= kTouchSlop);
    _timer = null;
467 468 469 470 471 472 473
    if (_starter != null) {
      _starter(initialPosition);
      _starter = null;
    } else {
      resolve(GestureDisposition.accepted);
    }
    assert(_starter == null);
474 475
  }

476 477 478 479 480
  void _ensureTimerStopped() {
    _timer?.cancel();
    _timer = null;
  }

481
  @override
482 483 484 485 486 487
  void accepted(GestureMultiDragStartCallback starter) {
    assert(_starter == null);
    if (_timer == null)
      starter(initialPosition);
    else
      _starter = starter;
488 489
  }

490
  @override
491
  void checkForResolutionAfterMove() {
492 493 494 495 496 497 498 499 500
    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;
    }
501
    assert(pendingDelta != null);
502
    if (pendingDelta.distance > kTouchSlop) {
503
      resolve(GestureDisposition.rejected);
504 505
      _ensureTimerStopped();
    }
506 507
  }

508
  @override
509
  void dispose() {
510
    _ensureTimerStopped();
511 512 513 514
    super.dispose();
  }
}

515 516
/// Recognizes movement both horizontally and vertically on a per-pointer basis
/// after a delay.
517
///
518
/// In contrast to [ImmediateMultiDragGestureRecognizer],
519 520 521 522 523 524 525 526 527 528
/// [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:
///
529 530 531 532
///  * [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.
533
class DelayedMultiDragGestureRecognizer extends MultiDragGestureRecognizer<_DelayedPointerState> {
534 535 536 537 538 539
  /// 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.
540
  DelayedMultiDragGestureRecognizer({
541
    this.delay = kLongPressTimeout,
542
    Object debugOwner,
543
    PointerDeviceKind kind,
544
  }) : assert(delay != null),
545
       super(debugOwner: debugOwner, kind: kind);
546

547 548
  /// The amount of time the pointer must remain in the same place for the drag
  /// to be recognized.
549
  final Duration delay;
550

551
  @override
552
  _DelayedPointerState createNewPointerState(PointerDownEvent event) {
553
    return _DelayedPointerState(event.position, delay);
554
  }
555

556
  @override
557
  String get debugDescription => 'long multidrag';
558
}