scroll_activity.dart 22 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5
// 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:math' as math;
7 8 9 10 11 12 13 14 15 16 17 18 19 20

import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/physics.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/scheduler.dart';

import 'basic.dart';
import 'framework.dart';
import 'gesture_detector.dart';
import 'scroll_metrics.dart';
import 'scroll_notification.dart';
import 'ticker_provider.dart';

21 22
/// A backend for a [ScrollActivity].
///
23
/// Used by subclasses of [ScrollActivity] to manipulate the scroll view that
24 25 26 27 28
/// they are acting upon.
///
/// See also:
///
///  * [ScrollActivity], which uses this class as its delegate.
29
///  * [ScrollPositionWithSingleContext], the main implementation of this interface.
30
abstract class ScrollActivityDelegate {
31
  /// The direction in which the scroll view scrolls.
32 33
  AxisDirection get axisDirection;

34 35 36 37
  /// Update the scroll position to the given pixel value.
  ///
  /// Returns the overscroll, if any. See [ScrollPosition.setPixels] for more
  /// information.
38
  double setPixels(double pixels);
39 40 41 42 43 44 45

  /// Updates the scroll position by the given amount.
  ///
  /// Appropriate for when the user is directly manipulating the scroll
  /// position, for example by dragging the scroll view. Typically applies
  /// [ScrollPhysics.applyPhysicsToUserOffset] and other transformations that
  /// are appropriate for user-driving scrolling.
46
  void applyUserOffset(double delta);
47

48
  /// Terminate the current activity and start an idle activity.
49
  void goIdle();
50 51 52

  /// Terminate the current activity and start a ballistic activity with the
  /// given velocity.
53 54 55 56 57 58 59
  void goBallistic(double velocity);
}

/// Base class for scrolling activities like dragging and flinging.
///
/// See also:
///
60 61
///  * [ScrollPosition], which uses [ScrollActivity] objects to manage the
///    [ScrollPosition] of a [Scrollable].
62
abstract class ScrollActivity {
63
  /// Initializes [delegate] for subclasses.
64 65
  ScrollActivity(this._delegate);

66
  /// The delegate that this activity will use to actuate the scroll view.
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
  ScrollActivityDelegate get delegate => _delegate;
  ScrollActivityDelegate _delegate;

  /// Updates the activity's link to the [ScrollActivityDelegate].
  ///
  /// This should only be called when an activity is being moved from a defunct
  /// (or about-to-be defunct) [ScrollActivityDelegate] object to a new one.
  void updateDelegate(ScrollActivityDelegate value) {
    assert(_delegate != value);
    _delegate = value;
  }

  /// Called by the [ScrollActivityDelegate] when it has changed type (for
  /// example, when changing from an Android-style scroll position to an
  /// iOS-style scroll position). If this activity can differ between the two
  /// modes, then it should tell the position to restart that activity
  /// appropriately.
  ///
  /// For example, [BallisticScrollActivity]'s implementation calls
  /// [ScrollActivityDelegate.goBallistic].
  void resetActivity() { }

89
  /// Dispatch a [ScrollStartNotification] with the given metrics.
90
  void dispatchScrollStartNotification(ScrollMetrics metrics, BuildContext? context) {
91
    ScrollStartNotification(metrics: metrics, context: context).dispatch(context);
92 93
  }

94
  /// Dispatch a [ScrollUpdateNotification] with the given metrics and scroll delta.
95
  void dispatchScrollUpdateNotification(ScrollMetrics metrics, BuildContext context, double scrollDelta) {
96
    ScrollUpdateNotification(metrics: metrics, context: context, scrollDelta: scrollDelta).dispatch(context);
97 98
  }

99
  /// Dispatch an [OverscrollNotification] with the given metrics and overscroll.
100
  void dispatchOverscrollNotification(ScrollMetrics metrics, BuildContext context, double overscroll) {
101
    OverscrollNotification(metrics: metrics, context: context, overscroll: overscroll).dispatch(context);
102 103
  }

104
  /// Dispatch a [ScrollEndNotification] with the given metrics and overscroll.
105
  void dispatchScrollEndNotification(ScrollMetrics metrics, BuildContext context) {
106
    ScrollEndNotification(metrics: metrics, context: context).dispatch(context);
107 108
  }

109
  /// Called when the scroll view that is performing this activity changes its metrics.
110 111
  void applyNewDimensions() { }

112 113
  /// Whether the scroll view should ignore pointer events while performing this
  /// activity.
114 115 116 117 118
  ///
  /// See also:
  ///
  ///  * [isScrolling], which describes whether the activity is considered
  ///    to represent user interaction or not.
119 120
  bool get shouldIgnorePointer;

121 122
  /// Whether performing this activity constitutes scrolling.
  ///
123 124
  /// Used, for example, to determine whether the user scroll
  /// direction (see [ScrollPosition.userScrollDirection]) is
125
  /// [ScrollDirection.idle].
126 127 128 129 130 131
  ///
  /// See also:
  ///
  ///  * [shouldIgnorePointer], which controls whether pointer events
  ///    are allowed while the activity is live.
  ///  * [UserScrollNotification], which exposes this status.
132 133
  bool get isScrolling;

134 135 136 137 138
  /// If applicable, the velocity at which the scroll offset is currently
  /// independently changing (i.e. without external stimuli such as a dragging
  /// gestures) in logical pixels per second for this activity.
  double get velocity;

139
  /// Called when the scroll view stops performing this activity.
140
  @mustCallSuper
141
  void dispose() { }
142 143

  @override
144
  String toString() => describeIdentity(this);
145 146
}

147 148 149
/// A scroll activity that does nothing.
///
/// When a scroll view is not scrolling, it is performing the idle activity.
150 151 152
///
/// If the [Scrollable] changes dimensions, this activity triggers a ballistic
/// activity to restore the view.
153
class IdleScrollActivity extends ScrollActivity {
154
  /// Creates a scroll activity that does nothing.
155 156 157 158 159 160 161 162 163 164 165 166
  IdleScrollActivity(ScrollActivityDelegate delegate) : super(delegate);

  @override
  void applyNewDimensions() {
    delegate.goBallistic(0.0);
  }

  @override
  bool get shouldIgnorePointer => false;

  @override
  bool get isScrolling => false;
167 168 169

  @override
  double get velocity => 0.0;
170 171
}

172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
/// Interface for holding a [Scrollable] stationary.
///
/// An object that implements this interface is returned by
/// [ScrollPosition.hold]. It holds the scrollable stationary until an activity
/// is started or the [cancel] method is called.
abstract class ScrollHoldController {
  /// Release the [Scrollable], potentially letting it go ballistic if
  /// necessary.
  void cancel();
}

/// A scroll activity that does nothing but can be released to resume
/// normal idle behavior.
///
/// This is used while the user is touching the [Scrollable] but before the
/// touch has become a [Drag].
///
/// For the purposes of [ScrollNotification]s, this activity does not constitute
/// scrolling, and does not prevent the user from interacting with the contents
/// of the [Scrollable] (unlike when a drag has begun or there is a scroll
/// animation underway).
class HoldScrollActivity extends ScrollActivity implements ScrollHoldController {
  /// Creates a scroll activity that does nothing.
  HoldScrollActivity({
196
    required ScrollActivityDelegate delegate,
197 198 199 200
    this.onHoldCanceled,
  }) : super(delegate);

  /// Called when [dispose] is called.
201
  final VoidCallback? onHoldCanceled;
202 203 204 205 206 207 208

  @override
  bool get shouldIgnorePointer => false;

  @override
  bool get isScrolling => false;

209 210 211
  @override
  double get velocity => 0.0;

212 213 214 215 216 217 218 219
  @override
  void cancel() {
    delegate.goBallistic(0.0);
  }

  @override
  void dispose() {
    if (onHoldCanceled != null)
220
      onHoldCanceled!();
221 222 223 224
    super.dispose();
  }
}

225 226 227 228 229 230
/// Scrolls a scroll view as the user drags their finger across the screen.
///
/// See also:
///
///  * [DragScrollActivity], which is the activity the scroll view performs
///    while a drag is underway.
231
class ScrollDragController implements Drag {
232 233 234 235 236
  /// Creates an object that scrolls a scroll view as the user drags their
  /// finger across the screen.
  ///
  /// The [delegate] and `details` arguments must not be null.
  ScrollDragController({
237 238
    required ScrollActivityDelegate delegate,
    required DragStartDetails details,
239
    this.onDragCanceled,
240
    this.carriedVelocity,
241
    this.motionStartDistanceThreshold,
242 243
  }) : assert(delegate != null),
       assert(details != null),
244 245 246 247
       assert(
         motionStartDistanceThreshold == null || motionStartDistanceThreshold > 0.0,
         'motionStartDistanceThreshold must be a positive number or null'
       ),
248
       _delegate = delegate,
249 250
       _lastDetails = details,
       _retainMomentum = carriedVelocity != null && carriedVelocity != 0.0,
251 252
       _lastNonStationaryTimestamp = details.sourceTimeStamp,
       _offsetSinceLastStop = motionStartDistanceThreshold == null ? null : 0.0;
253

254
  /// The object that will actuate the scroll view as the user drags.
255 256
  ScrollActivityDelegate get delegate => _delegate;
  ScrollActivityDelegate _delegate;
257

258
  /// Called when [dispose] is called.
259
  final VoidCallback? onDragCanceled;
260

261 262
  /// Velocity that was present from a previous [ScrollActivity] when this drag
  /// began.
263
  final double? carriedVelocity;
264

265 266
  /// Amount of pixels in either direction the drag has to move by to start
  /// scroll movement again after each time scrolling came to a stop.
267
  final double? motionStartDistanceThreshold;
268

269
  Duration? _lastNonStationaryTimestamp;
270
  bool _retainMomentum;
271
  /// Null if already in motion or has no [motionStartDistanceThreshold].
272
  double? _offsetSinceLastStop;
273 274 275 276

  /// Maximum amount of time interval the drag can have consecutive stationary
  /// pointer update events before losing the momentum carried from a previous
  /// scroll activity.
277
  static const Duration momentumRetainStationaryDurationThreshold =
278
      Duration(milliseconds: 20);
279

280 281 282 283
  /// Maximum amount of time interval the drag can have consecutive stationary
  /// pointer update events before needing to break the
  /// [motionStartDistanceThreshold] to start motion again.
  static const Duration motionStoppedDurationThreshold =
284
      Duration(milliseconds: 50);
285

286 287
  /// The drag distance past which, a [motionStartDistanceThreshold] breaking
  /// drag is considered a deliberate fling.
288
  static const double _bigThresholdBreakDistance = 24.0;
289

290 291
  bool get _reversed => axisDirectionIsReversed(delegate.axisDirection);

292 293 294 295 296 297 298 299 300
  /// Updates the controller's link to the [ScrollActivityDelegate].
  ///
  /// This should only be called when a controller is being moved from a defunct
  /// (or about-to-be defunct) [ScrollActivityDelegate] object to a new one.
  void updateDelegate(ScrollActivityDelegate value) {
    assert(_delegate != value);
    _delegate = value;
  }

301 302
  /// Determines whether to lose the existing incoming velocity when starting
  /// the drag.
303
  void _maybeLoseMomentum(double offset, Duration? timestamp) {
304 305 306
    if (_retainMomentum &&
        offset == 0.0 &&
        (timestamp == null || // If drag event has no timestamp, we lose momentum.
307
         timestamp - _lastNonStationaryTimestamp! > momentumRetainStationaryDurationThreshold)) {
308 309 310 311 312
      // If pointer is stationary for too long, we lose momentum.
      _retainMomentum = false;
    }
  }

313 314 315
  /// If a motion start threshold exists, determine whether the threshold needs
  /// to be broken to scroll. Also possibly apply an offset adjustment when
  /// threshold is first broken.
316
  ///
317 318
  /// Returns `0.0` when stationary or within threshold. Returns `offset`
  /// transparently when already in motion.
319
  double _adjustForScrollStartThreshold(double offset, Duration? timestamp) {
320 321 322
    if (timestamp == null) {
      // If we can't track time, we can't apply thresholds.
      // May be null for proxied drags like via accessibility.
323
      return offset;
324 325 326 327
    }
    if (offset == 0.0) {
      if (motionStartDistanceThreshold != null &&
          _offsetSinceLastStop == null &&
328
          timestamp - _lastNonStationaryTimestamp! > motionStoppedDurationThreshold) {
329 330 331 332
        // Enforce a new threshold.
        _offsetSinceLastStop = 0.0;
      }
      // Not moving can't break threshold.
333
      return 0.0;
334 335
    } else {
      if (_offsetSinceLastStop == null) {
336 337 338
        // Already in motion or no threshold behavior configured such as for
        // Android. Allow transparent offset transmission.
        return offset;
339
      } else {
340 341
        _offsetSinceLastStop = _offsetSinceLastStop! + offset;
        if (_offsetSinceLastStop!.abs() > motionStartDistanceThreshold!) {
342 343
          // Threshold broken.
          _offsetSinceLastStop = null;
344
          if (offset.abs() > _bigThresholdBreakDistance) {
345 346 347 348 349 350 351 352
            // This is heuristically a very deliberate fling. Leave the motion
            // unaffected.
            return offset;
          } else {
            // This is a normal speed threshold break.
            return math.min(
              // Ease into the motion when the threshold is initially broken
              // to avoid a visible jump.
353
              motionStartDistanceThreshold! / 3.0,
354
              offset.abs(),
355 356
            ) * offset.sign;
          }
357
        } else {
358
          return 0.0;
359 360 361 362 363
        }
      }
    }
  }

364 365 366 367
  @override
  void update(DragUpdateDetails details) {
    assert(details.primaryDelta != null);
    _lastDetails = details;
368
    double offset = details.primaryDelta!;
369
    if (offset != 0.0) {
370 371
      _lastNonStationaryTimestamp = details.sourceTimeStamp;
    }
372 373 374
    // By default, iOS platforms carries momentum and has a start threshold
    // (configured in [BouncingScrollPhysics]). The 2 operations below are
    // no-ops on Android.
375
    _maybeLoseMomentum(offset, details.sourceTimeStamp);
376 377
    offset = _adjustForScrollStartThreshold(offset, details.sourceTimeStamp);
    if (offset == 0.0) {
378 379
      return;
    }
380 381 382 383 384 385 386 387 388 389 390
    if (_reversed) // e.g. an AxisDirection.up scrollable
      offset = -offset;
    delegate.applyUserOffset(offset);
  }

  @override
  void end(DragEndDetails details) {
    assert(details.primaryVelocity != null);
    // We negate the velocity here because if the touch is moving downwards,
    // the scroll has to move upwards. It's the same reason that update()
    // above negates the delta before applying it to the scroll offset.
391
    double velocity = -details.primaryVelocity!;
392 393 394 395 396
    if (_reversed) // e.g. an AxisDirection.up scrollable
      velocity = -velocity;
    _lastDetails = details;

    // Build momentum only if dragging in the same direction.
397 398
    if (_retainMomentum && velocity.sign == carriedVelocity!.sign)
      velocity += carriedVelocity!;
399
    delegate.goBallistic(velocity);
400 401 402 403 404 405 406
  }

  @override
  void cancel() {
    delegate.goBallistic(0.0);
  }

407
  /// Called by the delegate when it is no longer sending events to this object.
408
  @mustCallSuper
409 410 411
  void dispose() {
    _lastDetails = null;
    if (onDragCanceled != null)
412
      onDragCanceled!();
413 414
  }

415 416
  /// The most recently observed [DragStartDetails], [DragUpdateDetails], or
  /// [DragEndDetails] object.
417
  dynamic get lastDetails => _lastDetails;
418
  dynamic _lastDetails;
419 420

  @override
421
  String toString() => describeIdentity(this);
422 423
}

424 425 426 427 428 429 430
/// The activity a scroll view performs when a the user drags their finger
/// across the screen.
///
/// See also:
///
///  * [ScrollDragController], which listens to the [Drag] and actually scrolls
///    the scroll view.
431
class DragScrollActivity extends ScrollActivity {
432 433
  /// Creates an activity for when the user drags their finger across the
  /// screen.
434 435 436
  DragScrollActivity(
    ScrollActivityDelegate delegate,
    ScrollDragController controller,
437 438
  ) : _controller = controller,
      super(delegate);
439

440
  ScrollDragController? _controller;
441

442
  @override
443 444
  void dispatchScrollStartNotification(ScrollMetrics metrics, BuildContext? context) {
    final dynamic lastDetails = _controller!.lastDetails;
445
    assert(lastDetails is DragStartDetails);
446
    ScrollStartNotification(metrics: metrics, context: context, dragDetails: lastDetails as DragStartDetails).dispatch(context);
447 448 449 450
  }

  @override
  void dispatchScrollUpdateNotification(ScrollMetrics metrics, BuildContext context, double scrollDelta) {
451
    final dynamic lastDetails = _controller!.lastDetails;
452
    assert(lastDetails is DragUpdateDetails);
453
    ScrollUpdateNotification(metrics: metrics, context: context, scrollDelta: scrollDelta, dragDetails: lastDetails as DragUpdateDetails).dispatch(context);
454 455 456 457
  }

  @override
  void dispatchOverscrollNotification(ScrollMetrics metrics, BuildContext context, double overscroll) {
458
    final dynamic lastDetails = _controller!.lastDetails;
459
    assert(lastDetails is DragUpdateDetails);
460
    OverscrollNotification(metrics: metrics, context: context, overscroll: overscroll, dragDetails: lastDetails as DragUpdateDetails).dispatch(context);
461 462 463 464 465
  }

  @override
  void dispatchScrollEndNotification(ScrollMetrics metrics, BuildContext context) {
    // We might not have DragEndDetails yet if we're being called from beginActivity.
466
    final dynamic lastDetails = _controller!.lastDetails;
467
    ScrollEndNotification(
468 469
      metrics: metrics,
      context: context,
470
      dragDetails: lastDetails is DragEndDetails ? lastDetails : null,
471 472 473 474 475 476 477 478
    ).dispatch(context);
  }

  @override
  bool get shouldIgnorePointer => true;

  @override
  bool get isScrolling => true;
479

480 481 482 483 484
  // DragScrollActivity is not independently changing velocity yet
  // until the drag is ended.
  @override
  double get velocity => 0.0;

485 486 487 488 489
  @override
  void dispose() {
    _controller = null;
    super.dispose();
  }
490 491 492

  @override
  String toString() {
493
    return '${describeIdentity(this)}($_controller)';
494
  }
495 496
}

497
/// An activity that animates a scroll view based on a physics [Simulation].
498 499 500 501 502 503
///
/// A [BallisticScrollActivity] is typically used when the user lifts their
/// finger off the screen to continue the scrolling gesture with the current velocity.
///
/// [BallisticScrollActivity] is also used to restore a scroll view to a valid
/// scroll offset when the geometry of the scroll view changes. In these
Ian Hickson's avatar
Ian Hickson committed
504
/// situations, the [Simulation] typically starts with a zero velocity.
505 506 507 508 509
///
/// See also:
///
///  * [DrivenScrollActivity], which animates a scroll view based on a set of
///    animation parameters.
510
class BallisticScrollActivity extends ScrollActivity {
511 512 513
  /// Creates an activity that animates a scroll view based on a [simulation].
  ///
  /// The [delegate], [simulation], and [vsync] arguments must not be null.
514 515 516 517 518
  BallisticScrollActivity(
    ScrollActivityDelegate delegate,
    Simulation simulation,
    TickerProvider vsync,
  ) : super(delegate) {
519
    _controller = AnimationController.unbounded(
520
      debugLabel: kDebugMode ? objectRuntimeType(this, 'BallisticScrollActivity') : null,
521 522 523 524 525 526 527
      vsync: vsync,
    )
      ..addListener(_tick)
      ..animateWith(simulation)
       .whenComplete(_end); // won't trigger if we dispose _controller first
  }

528
  late AnimationController _controller;
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546

  @override
  void resetActivity() {
    delegate.goBallistic(velocity);
  }

  @override
  void applyNewDimensions() {
    delegate.goBallistic(velocity);
  }

  void _tick() {
    if (!applyMoveTo(_controller.value))
      delegate.goIdle();
  }

  /// Move the position to the given location.
  ///
547 548
  /// If the new position was fully applied, returns true. If there was any
  /// overflow, returns false.
549 550 551 552 553 554 555 556 557
  ///
  /// The default implementation calls [ScrollActivityDelegate.setPixels]
  /// and returns true if the overflow was zero.
  @protected
  bool applyMoveTo(double value) {
    return delegate.setPixels(value) == 0.0;
  }

  void _end() {
558
    delegate.goBallistic(0.0);
559 560 561 562
  }

  @override
  void dispatchOverscrollNotification(ScrollMetrics metrics, BuildContext context, double overscroll) {
563
    OverscrollNotification(metrics: metrics, context: context, overscroll: overscroll, velocity: velocity).dispatch(context);
564 565 566 567 568 569 570 571
  }

  @override
  bool get shouldIgnorePointer => true;

  @override
  bool get isScrolling => true;

572 573 574
  @override
  double get velocity => _controller.velocity;

575 576 577 578 579 580 581 582
  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  String toString() {
583
    return '${describeIdentity(this)}($_controller)';
584 585 586
  }
}

587 588 589 590 591 592 593 594 595
/// An activity that animates a scroll view based on animation parameters.
///
/// For example, a [DrivenScrollActivity] is used to implement
/// [ScrollController.animateTo].
///
/// See also:
///
///  * [BallisticScrollActivity], which animates a scroll view based on a
///    physics [Simulation].
596
class DrivenScrollActivity extends ScrollActivity {
597 598 599 600
  /// Creates an activity that animates a scroll view based on animation
  /// parameters.
  ///
  /// All of the parameters must be non-null.
601 602
  DrivenScrollActivity(
    ScrollActivityDelegate delegate, {
603 604 605 606 607
    required double from,
    required double to,
    required Duration duration,
    required Curve curve,
    required TickerProvider vsync,
608 609 610
  }) : assert(from != null),
       assert(to != null),
       assert(duration != null),
611
       assert(duration > Duration.zero),
612 613
       assert(curve != null),
       super(delegate) {
614
    _completer = Completer<void>();
615
    _controller = AnimationController.unbounded(
616
      value: from,
617
      debugLabel: objectRuntimeType(this, 'DrivenScrollActivity'),
618 619 620 621 622 623 624
      vsync: vsync,
    )
      ..addListener(_tick)
      ..animateTo(to, duration: duration, curve: curve)
       .whenComplete(_end); // won't trigger if we dispose _controller first
  }

625 626
  late final Completer<void> _completer;
  late final AnimationController _controller;
627

628 629 630 631 632
  /// A [Future] that completes when the activity stops.
  ///
  /// For example, this [Future] will complete if the animation reaches the end
  /// or if the user interacts with the scroll view in way that causes the
  /// animation to stop before it reaches the end.
633
  Future<void> get done => _completer.future;
634 635 636 637 638 639 640

  void _tick() {
    if (delegate.setPixels(_controller.value) != 0.0)
      delegate.goIdle();
  }

  void _end() {
641
    delegate.goBallistic(velocity);
642 643 644 645
  }

  @override
  void dispatchOverscrollNotification(ScrollMetrics metrics, BuildContext context, double overscroll) {
646
    OverscrollNotification(metrics: metrics, context: context, overscroll: overscroll, velocity: velocity).dispatch(context);
647 648 649 650 651 652 653 654
  }

  @override
  bool get shouldIgnorePointer => true;

  @override
  bool get isScrolling => true;

655 656 657
  @override
  double get velocity => _controller.velocity;

658 659 660 661 662 663 664 665 666
  @override
  void dispose() {
    _completer.complete();
    _controller.dispose();
    super.dispose();
  }

  @override
  String toString() {
667
    return '${describeIdentity(this)}($_controller)';
668 669
  }
}