performance.dart 24.1 KB
Newer Older
1 2 3 4
// 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.

Matt Perry's avatar
Matt Perry committed
5
import 'dart:async';
6 7 8
import 'dart:ui' show VoidCallback, lerpDouble;

import 'package:newton/newton.dart';
Matt Perry's avatar
Matt Perry committed
9

10
import 'animated_value.dart';
11
import 'curves.dart';
12
import 'forces.dart';
13
import 'listener_helpers.dart';
14
import 'simulation_stepper.dart';
15

Florian Loitsch's avatar
Florian Loitsch committed
16 17 18 19 20
/// A read-only view of a [Performance].
///
/// This interface is implemented by [Performance].
///
/// Read-only access to [Performance] is used by classes that
21 22
/// want to watch a performance but should not be able to change the
/// performance's state.
23
abstract class PerformanceView {
24 25
  const PerformanceView();

Florian Loitsch's avatar
Florian Loitsch committed
26
  /// Update the given variable according to the current progress of the performance.
27
  void updateVariable(Animatable variable);
Florian Loitsch's avatar
Florian Loitsch committed
28
  /// Calls the listener every time the progress of the performance changes.
29
  void addListener(VoidCallback listener);
Florian Loitsch's avatar
Florian Loitsch committed
30
  /// Stop calling the listener every time the progress of the performance changes.
31
  void removeListener(VoidCallback listener);
Florian Loitsch's avatar
Florian Loitsch committed
32
  /// Calls listener every time the status of the performance changes.
33
  void addStatusListener(PerformanceStatusListener listener);
Florian Loitsch's avatar
Florian Loitsch committed
34
  /// Stops calling the listener every time the status of the performance changes.
35
  void removeStatusListener(PerformanceStatusListener listener);
36

37
  /// The current status of this animation.
38 39
  PerformanceStatus get status;

40 41 42 43 44 45 46 47 48 49
  /// The current direction of the animation.
  AnimationDirection get direction;

  /// The direction used to select the current curve.
  ///
  /// The curve direction is only reset when we hit the beginning or the end of
  /// the timeline to avoid discontinuities in the value of any variables this
  /// performance is used to animate.
  AnimationDirection get curveDirection;

50
  /// The current progress of this animation (a value from 0.0 to 1.0).
Florian Loitsch's avatar
Florian Loitsch committed
51 52 53
  ///
  /// This is the value that is used to update any variables when using
  /// [updateVariable].
54 55
  double get progress;

Florian Loitsch's avatar
Florian Loitsch committed
56
  /// Whether this animation is stopped at the beginning.
57 58
  bool get isDismissed => status == PerformanceStatus.dismissed;

Florian Loitsch's avatar
Florian Loitsch committed
59
  /// Whether this animation is stopped at the end.
60
  bool get isCompleted => status == PerformanceStatus.completed;
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99

  String toString() {
    return '$runtimeType(${toStringDetails()})';
  }
  String toStringDetails() {
    assert(status != null);
    assert(direction != null);
    String icon;
    switch (status) {
      case PerformanceStatus.forward:
        icon = '\u25B6'; // >
        break;
      case PerformanceStatus.reverse:
        icon = '\u25C0'; // <
        break;
      case PerformanceStatus.completed:
        switch (direction) {
          case AnimationDirection.forward:
            icon = '\u23ED'; // >>|
            break;
          case AnimationDirection.reverse:
            icon = '\u29CF'; // <|
            break;
        }
        break;
      case PerformanceStatus.dismissed:
        switch (direction) {
          case AnimationDirection.forward:
            icon = '\u29D0'; // |>
            break;
          case AnimationDirection.reverse:
            icon = '\u23EE'; // |<<
            break;
        }
        break;
    }
    assert(icon != null);
    return '$icon ${progress.toStringAsFixed(3)}';
  }
100 101
}

102 103 104 105 106 107 108 109
class AlwaysCompletePerformance extends PerformanceView {
  const AlwaysCompletePerformance();

  void updateVariable(Animatable variable) {
    variable.setProgress(1.0, AnimationDirection.forward);
  }

  // this performance never changes state
110 111
  void addListener(VoidCallback listener) { }
  void removeListener(VoidCallback listener) { }
112 113 114 115 116 117 118 119
  void addStatusListener(PerformanceStatusListener listener) { }
  void removeStatusListener(PerformanceStatusListener listener) { }
  PerformanceStatus get status => PerformanceStatus.completed;
  AnimationDirection get direction => AnimationDirection.forward;
  AnimationDirection get curveDirection => AnimationDirection.forward;
  double get progress => 1.0;
}
const AlwaysCompletePerformance alwaysCompletePerformance = const AlwaysCompletePerformance();
Hixie's avatar
Hixie committed
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
 
class AlwaysDismissedPerformance extends PerformanceView {
  const AlwaysDismissedPerformance();

  void updateVariable(Animatable variable) {
    variable.setProgress(0.0, AnimationDirection.forward);
  }

  // this performance never changes state
  void addListener(VoidCallback listener) { }
  void removeListener(VoidCallback listener) { }
  void addStatusListener(PerformanceStatusListener listener) { }
  void removeStatusListener(PerformanceStatusListener listener) { }
  PerformanceStatus get status => PerformanceStatus.dismissed;
  AnimationDirection get direction => AnimationDirection.forward;
  AnimationDirection get curveDirection => AnimationDirection.forward;
  double get progress => 0.0;
}
const AlwaysDismissedPerformance alwaysDismissedPerformance = const AlwaysDismissedPerformance();
139

140 141 142
class ReversePerformance extends PerformanceView
  with LazyListenerMixin, LocalPerformanceStatusListenersMixin {
  ReversePerformance(this.masterPerformance);
143 144 145 146 147 148 149

  final PerformanceView masterPerformance;

  void updateVariable(Animatable variable) {
    variable.setProgress(progress, curveDirection);
  }

150
  void addListener(VoidCallback listener) {
151
    didRegisterListener();
152 153
    masterPerformance.addListener(listener);
  }
154
  void removeListener(VoidCallback listener) {
155
    masterPerformance.removeListener(listener);
156
    didUnregisterListener();
157 158
  }

159 160
  void didStartListening() {
    masterPerformance.addStatusListener(_statusChangeHandler);
161 162
  }

163 164
  void didStopListening() {
    masterPerformance.removeStatusListener(_statusChangeHandler);
165 166 167
  }

  void _statusChangeHandler(PerformanceStatus status) {
168
    notifyStatusListeners(_reverseStatus(status));
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
  }

  PerformanceStatus get status => _reverseStatus(masterPerformance.status);
  AnimationDirection get direction => _reverseDirection(masterPerformance.direction);
  AnimationDirection get curveDirection => _reverseDirection(masterPerformance.curveDirection);
  double get progress => 1.0 - masterPerformance.progress;

  PerformanceStatus _reverseStatus(PerformanceStatus status) {
    switch (status) {
      case PerformanceStatus.forward: return PerformanceStatus.reverse;
      case PerformanceStatus.reverse: return PerformanceStatus.forward;
      case PerformanceStatus.completed: return PerformanceStatus.dismissed;
      case PerformanceStatus.dismissed: return PerformanceStatus.completed;
    }
  }

  AnimationDirection _reverseDirection(AnimationDirection direction) {
    switch (direction) {
      case AnimationDirection.forward: return AnimationDirection.reverse;
      case AnimationDirection.reverse: return AnimationDirection.forward;
    }
  }
}

Hixie's avatar
Hixie committed
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 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 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
class MeanPerformance extends PerformanceView
  with LazyListenerMixin, LocalPerformanceListenersMixin, LocalPerformanceStatusListenersMixin {
  MeanPerformance(this._performances) {
    assert(_performances != null);
  }

  // This list is intended to be immutable. Behavior is undefined if you mutate it.
  final List<PerformanceView> _performances;

  void didStartListening() {
    for (PerformanceView performance in _performances) {
      performance.addListener(notifyListeners);
      performance.addStatusListener(notifyStatusListeners);
    }
  }

  void didStopListening() {
    for (PerformanceView performance in _performances) {
      performance.removeListener(notifyListeners);
      performance.removeStatusListener(notifyStatusListeners);
    }
  }

  void updateVariable(Animatable variable) {
    variable.setProgress(progress, curveDirection);
  }

  PerformanceStatus get status {
    bool dismissed = true;
    bool completed = true;
    int direction = 0;
    for (PerformanceView performance in _performances) {
      switch (performance.status) {
        case PerformanceStatus.dismissed:
          completed = false;
          break;
        case PerformanceStatus.completed:
          dismissed = false;
          break;
        case PerformanceStatus.forward:
          dismissed = false;
          completed = false;
          direction += 1;
          break;
        case PerformanceStatus.reverse:
          dismissed = false;
          completed = false;
          direction -= 1;
          break;
      }
    }
    if (direction > 1)
      return PerformanceStatus.forward;
    if (direction < 1)
      return PerformanceStatus.reverse;
    if (dismissed)
      return PerformanceStatus.dismissed; // all performances were dismissed, or we had none
    if (completed)
      return PerformanceStatus.completed; // all performances were completed
    // Performances were conflicted.
    // Either we had an equal non-zero number of forwards and reverse
    // transitions, or we had both completed and dismissed transitions.
    // We default to whatever our first performance was.
    assert(_performances.isNotEmpty);
    return _performances[0].status;
  }

  AnimationDirection get direction {
    if (_performances.isEmpty)
      return AnimationDirection.forward;
    int direction = 0;
    for (PerformanceView performance in _performances) {
      switch (performance.direction) {
        case AnimationDirection.forward:
          direction += 1;
          break;
        case AnimationDirection.reverse:
          direction -= 1;
          break;
      }
    }
    if (direction > 1)
      return AnimationDirection.forward;
    if (direction < 1)
      return AnimationDirection.reverse;
    // We had an equal (non-zero) number of forwards and reverse transitions.
    // Default to the first one.
    return _performances[0].direction;
  }

  AnimationDirection get curveDirection {
    if (_performances.isEmpty)
      return AnimationDirection.forward;
    int curveDirection = 0;
    for (PerformanceView performance in _performances) {
      switch (performance.curveDirection) {
        case AnimationDirection.forward:
          curveDirection += 1;
          break;
        case AnimationDirection.reverse:
          curveDirection -= 1;
          break;
      }
    }
    if (curveDirection > 1)
      return AnimationDirection.forward;
    if (curveDirection < 1)
      return AnimationDirection.reverse;
    // We had an equal (non-zero) number of forwards and reverse transitions.
    // Default to the first one.
    return _performances[0].curveDirection;
  }

  double get progress {
    if (_performances.isEmpty)
      return 0.0;
    double result = 0.0;
    for (PerformanceView performance in _performances)
      result += performance.progress;
    return result / _performances.length;
  }
}

Hixie's avatar
Hixie committed
316 317 318 319 320 321 322
enum _TrainHoppingMode { minimize, maximize }

/// This performance starts by proxying one performance, but can be given a
/// second performance. When their times cross (either because the second is
/// going in the opposite direction, or because the one overtakes the other),
/// the performance hops over to proxying the second performance, and the second
/// performance becomes the new "first" performance.
323 324 325 326 327 328 329
///
/// Since this object must track the two performances even when it has no
/// listeners of its own, instead of shutting down when all its listeners are
/// removed, it exposes a [dispose()] method. Call this method to shut this
/// object down.
class TrainHoppingPerformance extends PerformanceView
  with EagerListenerMixin, LocalPerformanceListenersMixin, LocalPerformanceStatusListenersMixin {
Hixie's avatar
Hixie committed
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
  TrainHoppingPerformance(this._currentTrain, this._nextTrain, { this.onSwitchedTrain }) {
    assert(_currentTrain != null);
    if (_nextTrain != null) {
      if (_currentTrain.progress > _nextTrain.progress) {
        _mode = _TrainHoppingMode.maximize;
      } else {
        _mode = _TrainHoppingMode.minimize;
        if (_currentTrain.progress == _nextTrain.progress) {
          _currentTrain = _nextTrain;
          _nextTrain = null;
        }
      }
    }
    _currentTrain.addStatusListener(_statusChangeHandler);
    _currentTrain.addListener(_valueChangeHandler);
    if (_nextTrain != null)
      _nextTrain.addListener(_valueChangeHandler);
    assert(_mode != null);
  }

  PerformanceView get currentTrain => _currentTrain;
  PerformanceView _currentTrain;
  PerformanceView _nextTrain;
  _TrainHoppingMode _mode;

  VoidCallback onSwitchedTrain;

  void updateVariable(Animatable variable) {
    assert(_currentTrain != null);
    variable.setProgress(progress, curveDirection);
  }

  PerformanceStatus _lastStatus;
  void _statusChangeHandler(PerformanceStatus status) {
    assert(_currentTrain != null);
    if (status != _lastStatus) {
366
      notifyListeners();
Hixie's avatar
Hixie committed
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
      _lastStatus = status;
    }
    assert(_lastStatus != null);
  }

  PerformanceStatus get status => _currentTrain.status;
  AnimationDirection get direction => _currentTrain.direction;
  AnimationDirection get curveDirection => _currentTrain.curveDirection;

  double _lastProgress;  
  void _valueChangeHandler() {
    assert(_currentTrain != null);
    bool hop = false;
    if (_nextTrain != null) {
      switch (_mode) {
        case _TrainHoppingMode.minimize:
          hop = _nextTrain.progress <= _currentTrain.progress;
          break;
        case _TrainHoppingMode.maximize: 
          hop = _nextTrain.progress >= _currentTrain.progress;
          break;
      }
      if (hop) {
        _currentTrain.removeStatusListener(_statusChangeHandler);
        _currentTrain.removeListener(_valueChangeHandler);
        _currentTrain = _nextTrain;
        _nextTrain.addListener(_valueChangeHandler);
        _statusChangeHandler(_nextTrain.status);
      }
    }
    double newProgress = progress;
    if (newProgress != _lastProgress) {
399
      notifyListeners();
Hixie's avatar
Hixie committed
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
      _lastProgress = newProgress;
    }
    assert(_lastProgress != null);
    if (hop && onSwitchedTrain != null)
      onSwitchedTrain();
  }

  double get progress => _currentTrain.progress;

  /// Frees all the resources used by this performance.
  /// After this is called, this object is no longer usable.
  void dispose() {
    assert(_currentTrain != null);
    _currentTrain.removeStatusListener(_statusChangeHandler);
    _currentTrain.removeListener(_valueChangeHandler);
    _currentTrain = null;
    if (_nextTrain != null) {
      _nextTrain.removeListener(_valueChangeHandler);
      _nextTrain = null;
    }
  }
}

423 424
class ProxyPerformance extends PerformanceView
  with LazyListenerMixin, LocalPerformanceListenersMixin, LocalPerformanceStatusListenersMixin {
Hixie's avatar
Hixie committed
425
  ProxyPerformance([PerformanceView performance]) {
426 427 428 429 430 431 432
    _masterPerformance = performance;
    if (_masterPerformance == null) {
      _status = PerformanceStatus.dismissed;
      _direction = AnimationDirection.forward;
      _curveDirection = AnimationDirection.forward;
      _progress = 0.0;
    }
Hixie's avatar
Hixie committed
433 434
  }

435 436 437 438 439
  PerformanceStatus _status;
  AnimationDirection _direction;
  AnimationDirection _curveDirection;
  double _progress;

Hixie's avatar
Hixie committed
440 441 442 443 444 445
  PerformanceView get masterPerformance => _masterPerformance;
  PerformanceView _masterPerformance;
  void set masterPerformance(PerformanceView value) {
    if (value == _masterPerformance)
      return;
    if (_masterPerformance != null) {
446 447 448 449 450 451
      _status = _masterPerformance.status;
      _direction = _masterPerformance.direction;
      _curveDirection = _masterPerformance.curveDirection;
      _progress = _masterPerformance.progress;
      if (isListening)
        didStopListening();
Hixie's avatar
Hixie committed
452 453 454
    }
    _masterPerformance = value;
    if (_masterPerformance != null) {
455 456 457 458 459 460 461 462 463 464
      if (isListening)
        didStartListening();
      if (_progress != _masterPerformance.progress)
        notifyListeners();
      if (_status != _masterPerformance.status)
        notifyStatusListeners(_masterPerformance.status);
      _status = null;
      _direction = null;
      _curveDirection = null;
      _progress = null;
Hixie's avatar
Hixie committed
465 466 467
    }
  }

468 469
  void didStartListening() {
    if (_masterPerformance != null) {
Hixie's avatar
Hixie committed
470 471
      _masterPerformance.addListener(notifyListeners);
      _masterPerformance.addStatusListener(notifyStatusListeners);
472
    }
Hixie's avatar
Hixie committed
473 474
  }

475 476
  void didStopListening() {
    if (_masterPerformance != null) {
Hixie's avatar
Hixie committed
477 478
      _masterPerformance.removeListener(notifyListeners);
      _masterPerformance.removeStatusListener(notifyStatusListeners);
Hixie's avatar
Hixie committed
479 480 481
    }
  }

482 483
  void updateVariable(Animatable variable) {
    variable.setProgress(progress, curveDirection);
484 485
  }

486 487 488 489
  PerformanceStatus get status => _masterPerformance != null ? _masterPerformance.status : _status;
  AnimationDirection get direction => _masterPerformance != null ? _masterPerformance.direction : _direction;
  AnimationDirection get curveDirection => _masterPerformance != null ? _masterPerformance.curveDirection : _curveDirection;
  double get progress => _masterPerformance != null ? _masterPerformance.progress : _progress;
490
}
491

492 493 494 495 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 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
class CurvedPerformance extends PerformanceView {
  CurvedPerformance(this._performance, { this.curve, this.reverseCurve });

  final PerformanceView _performance;

  /// The curve to use in the forward direction
  Curve curve;

  /// The curve to use in the reverse direction
  ///
  /// If this field is null, use [curve] in both directions.
  Curve reverseCurve;

  void addListener(VoidCallback listener) {
    _performance.addListener(listener);
  }
  void removeListener(VoidCallback listener) {
    _performance.removeListener(listener);
  }

  void addStatusListener(PerformanceStatusListener listener) {
    _performance.addStatusListener(listener);
  }
  void removeStatusListener(PerformanceStatusListener listener) {
    _performance.removeStatusListener(listener);
  }

  void updateVariable(Animatable variable) {
    variable.setProgress(progress, curveDirection);
  }

  PerformanceStatus get status => _performance.status;
  AnimationDirection get direction => _performance.direction;
  AnimationDirection get curveDirection => _performance.curveDirection;
  double get progress {
    Curve activeCurve;
    if (curveDirection == AnimationDirection.forward || reverseCurve == null)
      activeCurve = curve;
    else
      activeCurve = reverseCurve;
    if (activeCurve == null)
      return _performance.progress;
    if (_performance.status == PerformanceStatus.dismissed) {
      assert(_performance.progress == 0.0);
      assert(activeCurve.transform(0.0).roundToDouble() == 0.0);
      return 0.0;
    }
    if (_performance.status == PerformanceStatus.completed) {
      assert(_performance.progress == 1.0);
      assert(activeCurve.transform(1.0).roundToDouble() == 1.0);
      return 1.0;
    }
    return activeCurve.transform(_performance.progress);
  }
}

548
/// A timeline that can be reversed and used to update [Animatable]s.
549 550 551 552 553 554 555
///
/// For example, a performance may handle an animation of a menu opening by
/// sliding and fading in (changing Y value and opacity) over .5 seconds. The
/// performance can move forwards (present) or backwards (dismiss). A consumer
/// may also take direct control of the timeline by manipulating [progress], or
/// [fling] the timeline causing a physics-based simulation to take over the
/// progression.
556 557
class Performance extends PerformanceView
  with EagerListenerMixin, LocalPerformanceListenersMixin, LocalPerformanceStatusListenersMixin {
558
  Performance({ this.duration, double progress, this.debugLabel }) {
Adam Barth's avatar
Adam Barth committed
559
    _timeline = new SimulationStepper(_tick);
Hixie's avatar
Hixie committed
560 561
    if (progress != null)
      _timeline.value = progress.clamp(0.0, 1.0);
562 563
  }

Florian Loitsch's avatar
Florian Loitsch committed
564
  /// A label that is used in the [toString] output. Intended to aid with
565 566 567
  /// identifying performance instances in debug output.
  final String debugLabel;

568
  /// Returns a [PerformanceView] for this performance,
569
  /// so that a pointer to this object can be passed around without
570
  /// allowing users of that pointer to mutate the Performance state.
571
  PerformanceView get view => this;
572

Florian Loitsch's avatar
Florian Loitsch committed
573
  /// The length of time this performance should last.
574 575
  Duration duration;

Adam Barth's avatar
Adam Barth committed
576
  SimulationStepper _timeline;
577
  AnimationDirection get direction => _direction;
578
  AnimationDirection _direction = AnimationDirection.forward;
579
  AnimationDirection get curveDirection => _curveDirection;
580
  AnimationDirection _curveDirection = AnimationDirection.forward;
581

Florian Loitsch's avatar
Florian Loitsch committed
582
  /// The progress of this performance along the timeline.
583 584
  ///
  /// Note: Setting this value stops the current animation.
585
  double get progress => _timeline.value.clamp(0.0, 1.0);
586 587
  void set progress(double t) {
    stop();
588
    _timeline.value = t.clamp(0.0, 1.0);
589
    _checkStatusChanged();
590 591
  }

Florian Loitsch's avatar
Florian Loitsch committed
592
  /// Whether this animation is currently animating in either the forward or reverse direction.
593 594
  bool get isAnimating => _timeline.isAnimating;

595
  PerformanceStatus get status {
596
    if (!isAnimating && progress == 1.0)
597
      return PerformanceStatus.completed;
598
    if (!isAnimating && progress == 0.0)
599 600 601 602
      return PerformanceStatus.dismissed;
    return _direction == AnimationDirection.forward ?
        PerformanceStatus.forward :
        PerformanceStatus.reverse;
603 604
  }

Florian Loitsch's avatar
Florian Loitsch committed
605
  /// Updates the given variable according to the current progress of this performance.
606
  void updateVariable(Animatable variable) {
607
    variable.setProgress(progress, _curveDirection);
608 609
  }

Florian Loitsch's avatar
Florian Loitsch committed
610
  /// Starts running this animation forwards (towards the end).
611
  Future forward() => play(AnimationDirection.forward);
612

Florian Loitsch's avatar
Florian Loitsch committed
613
  /// Starts running this animation in reverse (towards the beginning).
614
  Future reverse() => play(AnimationDirection.reverse);
615

Florian Loitsch's avatar
Florian Loitsch committed
616
  /// Starts running this animation in the given direction.
617
  Future play([AnimationDirection direction = AnimationDirection.forward]) {
618 619 620 621
    _direction = direction;
    return resume();
  }

Florian Loitsch's avatar
Florian Loitsch committed
622
  /// Resumes this animation in the most recent direction.
623
  Future resume() {
624
    return _animateTo(_direction == AnimationDirection.forward ? 1.0 : 0.0);
625
  }
626

Florian Loitsch's avatar
Florian Loitsch committed
627
  /// Stops running this animation.
628
  void stop() {
629
    _timeline.stop();
630 631
  }

Florian Loitsch's avatar
Florian Loitsch committed
632
  /// Releases any resources used by this object.
633 634 635 636 637 638
  ///
  /// Same as stop().
  void dispose() {
    stop();
  }

639 640 641 642
  ///
  /// 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.
643
  Future fling({double velocity: 1.0, Force force}) {
Florian Loitsch's avatar
Florian Loitsch committed
644
    force ??= kDefaultSpringForce;
645
    _direction = velocity < 0.0 ? AnimationDirection.reverse : AnimationDirection.forward;
Adam Barth's avatar
Adam Barth committed
646
    return _timeline.animateWith(force.release(progress, velocity));
647 648
  }

649
  Future repeat({ double min: 0.0, double max: 1.0, Duration period }) {
Florian Loitsch's avatar
Florian Loitsch committed
650
    period ??= duration;
651 652 653
    return _timeline.animateWith(new _RepeatingSimulation(min, max, period));
  }

654
  PerformanceStatus _lastStatus = PerformanceStatus.dismissed;
655
  void _checkStatusChanged() {
656
    PerformanceStatus currentStatus = status;
657 658
    if (currentStatus != _lastStatus)
      notifyStatusListeners(status);
659 660 661
    _lastStatus = currentStatus;
  }

662 663
  void _updateCurveDirection() {
    if (status != _lastStatus) {
664
      if (_lastStatus == PerformanceStatus.dismissed || _lastStatus == PerformanceStatus.completed)
665
        _curveDirection = _direction;
666 667 668
    }
  }

Matt Perry's avatar
Matt Perry committed
669
  Future _animateTo(double target) {
670 671
    Duration remainingDuration = duration * (target - _timeline.value).abs();
    _timeline.stop();
672
    if (remainingDuration == Duration.ZERO)
Matt Perry's avatar
Matt Perry committed
673
      return new Future.value();
674
    return _timeline.animateTo(target, duration: remainingDuration);
675 676 677
  }

  void _tick(double t) {
678
    _updateCurveDirection();
Hixie's avatar
Hixie committed
679 680 681 682
    didTick(t);
  }

  void didTick(double t) {
683
    notifyListeners();
684
    _checkStatusChanged();
685
  }
686

687 688 689 690 691
  String toStringDetails() {    
    String paused = _timeline.isAnimating ? '' : '; paused';
    String label = debugLabel == null ? '' : '; for $debugLabel';
    String more = super.toStringDetails();
    return '$more$paused$label';
692
  }
693
}
694

Florian Loitsch's avatar
Florian Loitsch committed
695
/// An animation performance with an animated variable with a concrete type.
696 697
class ValuePerformance<T> extends Performance {
  ValuePerformance({ this.variable, Duration duration, double progress }) :
Hixie's avatar
Hixie committed
698
    super(duration: duration, progress: progress);
699

Hixie's avatar
Hixie committed
700
  AnimatedValue<T> variable;
701
  T get value => variable.value;
Hixie's avatar
Hixie committed
702 703 704

  void didTick(double t) {
    if (variable != null)
705
      variable.setProgress(progress, _curveDirection);
Hixie's avatar
Hixie committed
706 707
    super.didTick(t);
  }
708
}
709 710 711

class _RepeatingSimulation extends Simulation {
  _RepeatingSimulation(this.min, this.max, Duration period)
Florian Loitsch's avatar
Florian Loitsch committed
712
    : _periodInSeconds = period.inMicroseconds / Duration.MICROSECONDS_PER_SECOND {
713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
    assert(_periodInSeconds > 0.0);
  }

  final double min;
  final double max;

  final double _periodInSeconds;

  double x(double timeInSeconds) {
    assert(timeInSeconds >= 0.0);
    final double t = (timeInSeconds / _periodInSeconds) % 1.0;
    return lerpDouble(min, max, t);
  }

  double dx(double timeInSeconds) => 1.0;

  bool isDone(double timeInSeconds) => false;
}