scroll_activity.dart 16.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// 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 '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';

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

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

  /// 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.
45
  void applyUserOffset(double delta);
46

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

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

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

65
  /// The delegate that this activity will use to actuate the scroll view.
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
  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() { }

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

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

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

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

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

111 112
  /// Whether the scroll view should ignore pointer events while performing this
  /// activity.
113 114
  bool get shouldIgnorePointer;

115 116 117 118
  /// Whether performing this activity constitutes scrolling.
  ///
  /// Used, for example, to determine whether the user scroll direction is
  /// [ScrollDirection.idle].
119 120
  bool get isScrolling;

121
  /// Called when the scroll view stops performing this activity.
122 123 124 125 126 127
  @mustCallSuper
  void dispose() {
    _delegate = null;
  }

  @override
128
  String toString() => describeIdentity(this);
129 130
}

131 132 133
/// A scroll activity that does nothing.
///
/// When a scroll view is not scrolling, it is performing the idle activity.
134 135 136
///
/// If the [Scrollable] changes dimensions, this activity triggers a ballistic
/// activity to restore the view.
137
class IdleScrollActivity extends ScrollActivity {
138
  /// Creates a scroll activity that does nothing.
139 140 141 142 143 144 145 146 147 148 149 150 151 152
  IdleScrollActivity(ScrollActivityDelegate delegate) : super(delegate);

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

  @override
  bool get shouldIgnorePointer => false;

  @override
  bool get isScrolling => false;
}

153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 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 196 197 198 199 200 201 202
/// 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({
    @required ScrollActivityDelegate delegate,
    this.onHoldCanceled,
  }) : super(delegate);

  /// Called when [dispose] is called.
  final VoidCallback onHoldCanceled;

  @override
  bool get shouldIgnorePointer => false;

  @override
  bool get isScrolling => false;

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

  @override
  void dispose() {
    if (onHoldCanceled != null)
      onHoldCanceled();
    super.dispose();
  }
}

203 204 205 206 207 208
/// 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.
209
class ScrollDragController implements Drag {
210 211 212 213 214 215 216
  /// 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({
    @required ScrollActivityDelegate delegate,
    @required DragStartDetails details,
217
    this.onDragCanceled,
218 219 220 221
  }) : assert(delegate != null),
       assert(details != null),
       _delegate = delegate,
       _lastDetails = details;
222

223
  /// The object that will actuate the scroll view as the user drags.
224 225
  ScrollActivityDelegate get delegate => _delegate;
  ScrollActivityDelegate _delegate;
226

227
  /// Called when [dispose] is called.
228
  final VoidCallback onDragCanceled;
229 230 231

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

232 233 234 235 236 237 238 239 240
  /// 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;
  }

241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
  @override
  void update(DragUpdateDetails details) {
    assert(details.primaryDelta != null);
    _lastDetails = details;
    double offset = details.primaryDelta;
    if (offset == 0.0)
      return;
    if (_reversed) // e.g. an AxisDirection.up scrollable
      offset = -offset;
    delegate.applyUserOffset(offset);
  }

  @override
  void end(DragEndDetails details) {
    assert(details.primaryVelocity != null);
    double velocity = details.primaryVelocity;
    if (_reversed) // e.g. an AxisDirection.up scrollable
      velocity = -velocity;
    _lastDetails = details;
    // 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.
    delegate.goBallistic(-velocity);
  }

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

271
  /// Called by the delegate when it is no longer sending events to this object.
272
  @mustCallSuper
273 274 275 276 277 278
  void dispose() {
    _lastDetails = null;
    if (onDragCanceled != null)
      onDragCanceled();
  }

279 280
  /// The most recently observed [DragStartDetails], [DragUpdateDetails], or
  /// [DragEndDetails] object.
281
  dynamic get lastDetails => _lastDetails;
282
  dynamic _lastDetails;
283 284

  @override
285
  String toString() => describeIdentity(this);
286 287
}

288 289 290 291 292 293 294
/// 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.
295
class DragScrollActivity extends ScrollActivity {
296 297
  /// Creates an activity for when the user drags their finger across the
  /// screen.
298 299 300 301 302 303 304
  DragScrollActivity(
    ScrollActivityDelegate delegate,
    ScrollDragController controller,
  ) : _controller = controller, super(delegate);

  ScrollDragController _controller;

305 306
  @override
  void dispatchScrollStartNotification(ScrollMetrics metrics, BuildContext context) {
307 308 309
    final dynamic lastDetails = _controller.lastDetails;
    assert(lastDetails is DragStartDetails);
    new ScrollStartNotification(metrics: metrics, context: context, dragDetails: lastDetails).dispatch(context);
310 311 312 313
  }

  @override
  void dispatchScrollUpdateNotification(ScrollMetrics metrics, BuildContext context, double scrollDelta) {
314 315 316
    final dynamic lastDetails = _controller.lastDetails;
    assert(lastDetails is DragUpdateDetails);
    new ScrollUpdateNotification(metrics: metrics, context: context, scrollDelta: scrollDelta, dragDetails: lastDetails).dispatch(context);
317 318 319 320
  }

  @override
  void dispatchOverscrollNotification(ScrollMetrics metrics, BuildContext context, double overscroll) {
321 322 323
    final dynamic lastDetails = _controller.lastDetails;
    assert(lastDetails is DragUpdateDetails);
    new OverscrollNotification(metrics: metrics, context: context, overscroll: overscroll, dragDetails: lastDetails).dispatch(context);
324 325 326 327 328
  }

  @override
  void dispatchScrollEndNotification(ScrollMetrics metrics, BuildContext context) {
    // We might not have DragEndDetails yet if we're being called from beginActivity.
329
    final dynamic lastDetails = _controller.lastDetails;
330 331 332
    new ScrollEndNotification(
      metrics: metrics,
      context: context,
333
      dragDetails: lastDetails is DragEndDetails ? lastDetails : null
334 335 336 337 338 339 340 341
    ).dispatch(context);
  }

  @override
  bool get shouldIgnorePointer => true;

  @override
  bool get isScrolling => true;
342 343 344 345 346 347

  @override
  void dispose() {
    _controller = null;
    super.dispose();
  }
348 349 350

  @override
  String toString() {
351
    return '${describeIdentity(this)}($_controller)';
352
  }
353 354
}

355
/// An activity that animates a scroll view based on a physics [Simulation].
356 357 358 359 360 361
///
/// 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
362
/// situations, the [Simulation] typically starts with a zero velocity.
363 364 365 366 367
///
/// See also:
///
///  * [DrivenScrollActivity], which animates a scroll view based on a set of
///    animation parameters.
368
class BallisticScrollActivity extends ScrollActivity {
369 370 371
  /// Creates an activity that animates a scroll view based on a [simulation].
  ///
  /// The [delegate], [simulation], and [vsync] arguments must not be null.
372 373 374 375 376 377 378 379 380 381 382 383 384 385
  BallisticScrollActivity(
    ScrollActivityDelegate delegate,
    Simulation simulation,
    TickerProvider vsync,
  ) : super(delegate) {
    _controller = new AnimationController.unbounded(
      debugLabel: '$runtimeType',
      vsync: vsync,
    )
      ..addListener(_tick)
      ..animateWith(simulation)
       .whenComplete(_end); // won't trigger if we dispose _controller first
  }

386 387
  /// The velocity at which the scroll offset is currently changing (in logical
  /// pixels per second).
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
  double get velocity => _controller.velocity;

  AnimationController _controller;

  @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.
  ///
409 410
  /// If the new position was fully applied, returns true. If there was any
  /// overflow, returns false.
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
  ///
  /// 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() {
    delegate?.goBallistic(0.0);
  }

  @override
  void dispatchOverscrollNotification(ScrollMetrics metrics, BuildContext context, double overscroll) {
    new OverscrollNotification(metrics: metrics, context: context, overscroll: overscroll, velocity: velocity).dispatch(context);
  }

  @override
  bool get shouldIgnorePointer => true;

  @override
  bool get isScrolling => true;

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  String toString() {
442
    return '${describeIdentity(this)}($_controller)';
443 444 445
  }
}

446 447 448 449 450 451 452 453 454
/// 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].
455
class DrivenScrollActivity extends ScrollActivity {
456 457 458 459
  /// Creates an activity that animates a scroll view based on animation
  /// parameters.
  ///
  /// All of the parameters must be non-null.
460 461 462 463 464 465 466
  DrivenScrollActivity(
    ScrollActivityDelegate delegate, {
    @required double from,
    @required double to,
    @required Duration duration,
    @required Curve curve,
    @required TickerProvider vsync,
467 468 469 470 471 472
  }) : assert(from != null),
       assert(to != null),
       assert(duration != null),
       assert(duration > Duration.ZERO),
       assert(curve != null),
       super(delegate) {
473 474 475 476 477 478 479 480 481 482 483 484 485 486
    _completer = new Completer<Null>();
    _controller = new AnimationController.unbounded(
      value: from,
      debugLabel: '$runtimeType',
      vsync: vsync,
    )
      ..addListener(_tick)
      ..animateTo(to, duration: duration, curve: curve)
       .whenComplete(_end); // won't trigger if we dispose _controller first
  }

  Completer<Null> _completer;
  AnimationController _controller;

487 488 489 490 491
  /// 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.
492 493
  Future<Null> get done => _completer.future;

494 495
  /// The velocity at which the scroll offset is currently changing (in logical
  /// pixels per second).
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
  double get velocity => _controller.velocity;

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

  void _end() {
    delegate?.goBallistic(velocity);
  }

  @override
  void dispatchOverscrollNotification(ScrollMetrics metrics, BuildContext context, double overscroll) {
    new OverscrollNotification(metrics: metrics, context: context, overscroll: overscroll, velocity: velocity).dispatch(context);
  }

  @override
  bool get shouldIgnorePointer => true;

  @override
  bool get isScrolling => true;

  @override
  void dispose() {
    _completer.complete();
    _controller.dispose();
    super.dispose();
  }

  @override
  String toString() {
527
    return '${describeIdentity(this)}($_controller)';
528 529
  }
}