animation_controller.dart 9.32 KB
Newer Older
1 2 3 4 5
// Copyright 2016 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' as ui show lerpDouble;
7

8
import 'package:flutter/scheduler.dart';
9 10 11
import 'package:newton/newton.dart';

import 'animation.dart';
12
import 'curves.dart';
13 14 15
import 'forces.dart';
import 'listener_helpers.dart';

Adam Barth's avatar
Adam Barth committed
16 17 18 19 20 21 22 23 24
/// The direction in which an animation is running.
enum _AnimationDirection {
  /// The animation is running from beginning to end.
  forward,

  /// The animation is running backwards, from end to beginning.
  reverse
}

25 26 27 28 29 30
/// A controller for an animation.
///
/// An animation controller can drive an animation forward or backward and can
/// set the animation to a particular value. The controller also defines the
/// bounds of the animation and can drive an animation using a physics
/// simulation.
31
class AnimationController extends Animation<double>
32
  with AnimationEagerListenerMixin, AnimationLocalListenersMixin, AnimationLocalStatusListenersMixin {
33 34 35 36 37 38 39 40

  /// Creates an animation controller.
  ///
  /// * value is the initial value of the animation.
  /// * duration is the length of time this animation should last.
  /// * debugLabel is a string to help identify this animation during debugging (used by toString).
  /// * lowerBound is the smallest value this animation can obtain and the value at which this animation is deemed to be dismissed.
  /// * upperBound is the largest value this animation can obtain and the value at which this animation is deemed to be completed.
41 42 43 44 45 46 47
  AnimationController({
    double value,
    this.duration,
    this.debugLabel,
    this.lowerBound: 0.0,
    this.upperBound: 1.0
  }) {
48
    assert(upperBound >= lowerBound);
49 50
    _value = (value ?? lowerBound).clamp(lowerBound, upperBound);
    _ticker = new Ticker(_tick);
51 52
  }

53 54 55 56 57 58 59
  /// Creates an animation controller with no upper or lower bound for its value.
  ///
  /// * value is the initial value of the animation.
  /// * duration is the length of time this animation should last.
  /// * debugLabel is a string to help identify this animation during debugging (used by toString).
  ///
  /// This constructor is most useful for animations that will be driven using a
60
  /// physics simulation, especially when the physics simulation has no
61
  /// pre-determined bounds.
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
  AnimationController.unbounded({
    double value: 0.0,
    this.duration,
    this.debugLabel
  }) : lowerBound = double.NEGATIVE_INFINITY,
       upperBound = double.INFINITY,
       _value = value {
    assert(value != null);
    _ticker = new Ticker(_tick);
  }

  /// The value at which this animation is deemed to be dismissed.
  final double lowerBound;

  /// The value at which this animation is deemed to be completed.
  final double upperBound;

79 80 81 82
  /// A label that is used in the [toString] output. Intended to aid with
  /// identifying animation controller instances in debug output.
  final String debugLabel;

83
  /// Returns an [Animated<double>] for this animation controller,
84 85 86 87 88 89 90
  /// so that a pointer to this object can be passed around without
  /// allowing users of that pointer to mutate the AnimationController state.
  Animation<double> get view => this;

  /// The length of time this animation should last.
  Duration duration;

91 92 93
  Ticker _ticker;
  Simulation _simulation;

94
  /// The current value of the animation.
95
  ///
96 97 98 99 100 101
  /// Setting this value notifies all the listeners that the value
  /// changed.
  ///
  /// Setting this value also stops the controller if it is currently
  /// running; if this happens, it also notifies all the status
  /// listeners.
102
  @override
103
  double get value => _value;
104 105 106
  double _value;
  void set value(double newValue) {
    assert(newValue != null);
107
    stop();
108 109
    _value = newValue.clamp(lowerBound, upperBound);
    notifyListeners();
110 111 112 113
    _checkStatusChanged();
  }

  /// Whether this animation is currently animating in either the forward or reverse direction.
114
  bool get isAnimating => _ticker.isTicking;
115

Adam Barth's avatar
Adam Barth committed
116 117
  _AnimationDirection _direction;

118
  @override
119
  AnimationStatus get status {
120
    if (!isAnimating && value == upperBound)
121
      return AnimationStatus.completed;
122
    if (!isAnimating && value == lowerBound)
123
      return AnimationStatus.dismissed;
Adam Barth's avatar
Adam Barth committed
124
    return _direction == _AnimationDirection.forward ?
125 126 127 128 129
        AnimationStatus.forward :
        AnimationStatus.reverse;
  }

  /// Starts running this animation forwards (towards the end).
130
  Future<Null> forward({ double from }) {
131 132
    if (from != null)
      value = from;
Adam Barth's avatar
Adam Barth committed
133 134
    _direction = _AnimationDirection.forward;
    return animateTo(upperBound);
135 136
  }

Adam Barth's avatar
Adam Barth committed
137
  /// Starts running this animation in reverse (towards the beginning).
138
  Future<Null> reverse({ double from }) {
139 140
    if (from != null)
      value = from;
Adam Barth's avatar
Adam Barth committed
141 142
    _direction = _AnimationDirection.reverse;
    return animateTo(lowerBound);
143 144
  }

145
  /// Drives the animation from its current value to target.
146
  Future<Null> animateTo(double target, { Duration duration, Curve curve: Curves.linear }) {
147 148 149
    Duration simulationDuration = duration;
    if (simulationDuration == null) {
      double range = upperBound - lowerBound;
150 151
      double remainingFraction = range.isFinite ? (target - _value).abs() / range : 1.0;
      simulationDuration = this.duration * remainingFraction;
152
    }
153
    stop();
154 155
    if (simulationDuration == Duration.ZERO) {
      assert(value == target);
156
      _checkStatusChanged();
157
      return new Future<Null>.value();
158 159
    }
    assert(simulationDuration > Duration.ZERO);
160
    assert(!isAnimating);
161
    return _startSimulation(new _InterpolationSimulation(_value, target, simulationDuration, curve));
162 163
  }

164 165
  /// Starts running this animation in the forward direction, and
  /// restarts the animation when it completes.
166 167
  ///
  /// Defaults to repeating between the lower and upper bounds.
168
  Future<Null> repeat({ double min, double max, Duration period }) {
169 170
    min ??= lowerBound;
    max ??= upperBound;
171 172 173 174 175 176 177
    period ??= duration;
    return animateWith(new _RepeatingSimulation(min, max, period));
  }

  /// Flings the timeline with an optional force (defaults to a critically
  /// damped spring) and initial velocity. If velocity is positive, the
  /// animation will complete, otherwise it will dismiss.
178
  Future<Null> fling({ double velocity: 1.0, Force force }) {
179
    force ??= kDefaultSpringForce;
Adam Barth's avatar
Adam Barth committed
180
    _direction = velocity < 0.0 ? _AnimationDirection.reverse : _AnimationDirection.forward;
181 182 183 184
    return animateWith(force.release(value, velocity));
  }

  /// Drives the animation according to the given simulation.
185
  Future<Null> animateWith(Simulation simulation) {
186 187 188 189
    stop();
    return _startSimulation(simulation);
  }

190
  Future<Null> _startSimulation(Simulation simulation) {
191 192 193
    assert(simulation != null);
    assert(!isAnimating);
    _simulation = simulation;
194
    _value = simulation.x(0.0).clamp(lowerBound, upperBound);
195
    Future<Null> result = _ticker.start();
196 197
    _checkStatusChanged();
    return result;
198 199
  }

200 201 202 203 204 205 206
  /// Stops running this animation.
  void stop() {
    _simulation = null;
    _ticker.stop();
  }

  /// Stops running this animation.
207
  @override
208 209 210 211
  void dispose() {
    stop();
  }

212
  AnimationStatus _lastReportedStatus = AnimationStatus.dismissed;
213 214
  void _checkStatusChanged() {
    AnimationStatus newStatus = status;
215 216
    if (_lastReportedStatus != newStatus) {
      _lastReportedStatus = newStatus;
217
      notifyStatusListeners(newStatus);
218
    }
219 220
  }

221 222
  void _tick(Duration elapsed) {
    double elapsedInSeconds = elapsed.inMicroseconds.toDouble() / Duration.MICROSECONDS_PER_SECOND;
223
    _value = _simulation.x(elapsedInSeconds).clamp(lowerBound, upperBound);
224 225
    if (_simulation.isDone(elapsedInSeconds))
      stop();
226 227 228 229
    notifyListeners();
    _checkStatusChanged();
  }

230
  @override
231
  String toStringDetails() {
232
    String paused = isAnimating ? '' : '; paused';
233 234 235 236 237 238
    String label = debugLabel == null ? '' : '; for $debugLabel';
    String more = '${super.toStringDetails()} ${value.toStringAsFixed(3)}';
    return '$more$paused$label';
  }
}

239 240
class _InterpolationSimulation extends Simulation {
  _InterpolationSimulation(this._begin, this._end, Duration duration, this._curve)
241 242 243 244 245 246 247 248 249 250 251
    : _durationInSeconds = duration.inMicroseconds / Duration.MICROSECONDS_PER_SECOND {
    assert(_durationInSeconds > 0.0);
    assert(_begin != null);
    assert(_end != null);
  }

  final double _durationInSeconds;
  final double _begin;
  final double _end;
  final Curve _curve;

252
  @override
253 254 255 256 257 258 259 260 261 262 263
  double x(double timeInSeconds) {
    assert(timeInSeconds >= 0.0);
    double t = (timeInSeconds / _durationInSeconds).clamp(0.0, 1.0);
    if (t == 0.0)
      return _begin;
    else if (t == 1.0)
      return _end;
    else
      return _begin + (_end - _begin) * _curve.transform(t);
  }

264
  @override
265 266
  double dx(double timeInSeconds) => 1.0;

267
  @override
268 269 270
  bool isDone(double timeInSeconds) => timeInSeconds > _durationInSeconds;
}

271 272 273 274 275 276 277 278 279 280 281
class _RepeatingSimulation extends Simulation {
  _RepeatingSimulation(this.min, this.max, Duration period)
    : _periodInSeconds = period.inMicroseconds / Duration.MICROSECONDS_PER_SECOND {
    assert(_periodInSeconds > 0.0);
  }

  final double min;
  final double max;

  final double _periodInSeconds;

282
  @override
283 284 285
  double x(double timeInSeconds) {
    assert(timeInSeconds >= 0.0);
    final double t = (timeInSeconds / _periodInSeconds) % 1.0;
286
    return ui.lerpDouble(min, max, t);
287 288
  }

289
  @override
290 291
  double dx(double timeInSeconds) => 1.0;

292
  @override
293 294
  bool isDone(double timeInSeconds) => false;
}