1// Copyright 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "cc/animation/animation.h"
6
7#include <cmath>
8
9#include "base/debug/trace_event.h"
10#include "base/strings/string_util.h"
11#include "cc/animation/animation_curve.h"
12
13namespace {
14
15// This should match the RunState enum.
16static const char* const s_runStateNames[] = {
17  "WaitingForTargetAvailability",
18  "WaitingForDeletion",
19  "Starting",
20  "Running",
21  "Paused",
22  "Finished",
23  "Aborted"
24};
25
26COMPILE_ASSERT(static_cast<int>(cc::Animation::RunStateEnumSize) ==
27               arraysize(s_runStateNames),
28               RunState_names_match_enum);
29
30// This should match the TargetProperty enum.
31static const char* const s_targetPropertyNames[] = {
32  "Transform",
33  "Opacity",
34  "Filter",
35  "ScrollOffset",
36  "BackgroundColor"
37};
38
39COMPILE_ASSERT(static_cast<int>(cc::Animation::TargetPropertyEnumSize) ==
40               arraysize(s_targetPropertyNames),
41               TargetProperty_names_match_enum);
42
43}  // namespace
44
45namespace cc {
46
47scoped_ptr<Animation> Animation::Create(
48    scoped_ptr<AnimationCurve> curve,
49    int animation_id,
50    int group_id,
51    TargetProperty target_property) {
52  return make_scoped_ptr(new Animation(curve.Pass(),
53                                       animation_id,
54                                       group_id,
55                                       target_property)); }
56
57Animation::Animation(scoped_ptr<AnimationCurve> curve,
58                     int animation_id,
59                     int group_id,
60                     TargetProperty target_property)
61    : curve_(curve.Pass()),
62      id_(animation_id),
63      group_(group_id),
64      target_property_(target_property),
65      run_state_(WaitingForTargetAvailability),
66      iterations_(1),
67      direction_(Normal),
68      needs_synchronized_start_time_(false),
69      received_finished_event_(false),
70      suspended_(false),
71      is_controlling_instance_(false),
72      is_impl_only_(false),
73      affects_active_observers_(true),
74      affects_pending_observers_(true) {
75}
76
77Animation::~Animation() {
78  if (run_state_ == Running || run_state_ == Paused)
79    SetRunState(Aborted, base::TimeTicks());
80}
81
82void Animation::SetRunState(RunState run_state,
83                            base::TimeTicks monotonic_time) {
84  if (suspended_)
85    return;
86
87  char name_buffer[256];
88  base::snprintf(name_buffer,
89                 sizeof(name_buffer),
90                 "%s-%d%s",
91                 s_targetPropertyNames[target_property_],
92                 group_,
93                 is_controlling_instance_ ? "(impl)" : "");
94
95  bool is_waiting_to_start = run_state_ == WaitingForTargetAvailability ||
96                             run_state_ == Starting;
97
98  if (is_waiting_to_start && run_state == Running) {
99    TRACE_EVENT_ASYNC_BEGIN1(
100        "cc", "Animation", this, "Name", TRACE_STR_COPY(name_buffer));
101  }
102
103  bool was_finished = is_finished();
104
105  const char* old_run_state_name = s_runStateNames[run_state_];
106
107  if (run_state == Running && run_state_ == Paused)
108    total_paused_time_ += (monotonic_time - pause_time_);
109  else if (run_state == Paused)
110    pause_time_ = monotonic_time;
111  run_state_ = run_state;
112
113  const char* new_run_state_name = s_runStateNames[run_state];
114
115  if (!was_finished && is_finished())
116    TRACE_EVENT_ASYNC_END0("cc", "Animation", this);
117
118  char state_buffer[256];
119  base::snprintf(state_buffer,
120                 sizeof(state_buffer),
121                 "%s->%s",
122                 old_run_state_name,
123                 new_run_state_name);
124
125  TRACE_EVENT_INSTANT2("cc",
126                       "LayerAnimationController::SetRunState",
127                       TRACE_EVENT_SCOPE_THREAD,
128                       "Name",
129                       TRACE_STR_COPY(name_buffer),
130                       "State",
131                       TRACE_STR_COPY(state_buffer));
132}
133
134void Animation::Suspend(base::TimeTicks monotonic_time) {
135  SetRunState(Paused, monotonic_time);
136  suspended_ = true;
137}
138
139void Animation::Resume(base::TimeTicks monotonic_time) {
140  suspended_ = false;
141  SetRunState(Running, monotonic_time);
142}
143
144bool Animation::IsFinishedAt(base::TimeTicks monotonic_time) const {
145  if (is_finished())
146    return true;
147
148  if (needs_synchronized_start_time_)
149    return false;
150
151  return run_state_ == Running && iterations_ >= 0 &&
152         iterations_ * curve_->Duration() <=
153             (monotonic_time + time_offset_ - start_time_ - total_paused_time_)
154                 .InSecondsF();
155}
156
157double Animation::TrimTimeToCurrentIteration(
158    base::TimeTicks monotonic_time) const {
159  base::TimeTicks trimmed = monotonic_time + time_offset_;
160
161  // If we're paused, time is 'stuck' at the pause time.
162  if (run_state_ == Paused)
163    trimmed = pause_time_;
164
165  // Returned time should always be relative to the start time and should
166  // subtract all time spent paused.
167  trimmed -= (start_time_ - base::TimeTicks()) + total_paused_time_;
168
169  // If we're just starting or we're waiting on receiving a start time,
170  // time is 'stuck' at the initial state.
171  if ((run_state_ == Starting && !has_set_start_time()) ||
172      needs_synchronized_start_time())
173    trimmed = base::TimeTicks() + time_offset_;
174
175  double trimmed_in_seconds = (trimmed - base::TimeTicks()).InSecondsF();
176
177  // Return 0 if we are before the start of the animation
178  if (trimmed_in_seconds < 0)
179    return 0;
180
181  // Always return zero if we have no iterations.
182  if (!iterations_)
183    return 0;
184
185  // Don't attempt to trim if we have no duration.
186  if (curve_->Duration() <= 0)
187    return 0;
188
189  // check if we are past active interval
190  bool is_past_total_duration =
191      (iterations_ > 0 &&
192       trimmed_in_seconds >= curve_->Duration() * iterations_);
193
194  // We need to know the current iteration if we're alternating.
195  int iteration = 0;
196
197  // If we are past the active interval, return iteration duration.
198  if (is_past_total_duration) {
199    iteration = iterations_ - 1;
200    trimmed_in_seconds = curve_->Duration();
201  } else {
202    iteration = static_cast<int>(trimmed_in_seconds / curve_->Duration());
203    // Calculate x where trimmed = x + n * curve_->Duration() for some positive
204    // integer n.
205    trimmed_in_seconds = fmod(trimmed_in_seconds, curve_->Duration());
206  }
207
208  // check if we are running the animation in reverse direction for the current
209  // iteration
210  bool reverse = (direction_ == Reverse) ||
211                 (direction_ == Alternate && iteration % 2 == 1) ||
212                 (direction_ == AlternateReverse && iteration % 2 == 0);
213
214  // if we are running the animation in reverse direction, reverse the result
215  if (reverse)
216    return curve_->Duration() - trimmed_in_seconds;
217
218  return trimmed_in_seconds;
219}
220
221scoped_ptr<Animation> Animation::CloneAndInitialize(
222    RunState initial_run_state) const {
223  scoped_ptr<Animation> to_return(
224      new Animation(curve_->Clone(), id_, group_, target_property_));
225  to_return->run_state_ = initial_run_state;
226  to_return->iterations_ = iterations_;
227  to_return->start_time_ = start_time_;
228  to_return->pause_time_ = pause_time_;
229  to_return->total_paused_time_ = total_paused_time_;
230  to_return->time_offset_ = time_offset_;
231  to_return->direction_ = direction_;
232  DCHECK(!to_return->is_controlling_instance_);
233  to_return->is_controlling_instance_ = true;
234  return to_return.Pass();
235}
236
237void Animation::PushPropertiesTo(Animation* other) const {
238  // Currently, we only push changes due to pausing and resuming animations on
239  // the main thread.
240  if (run_state_ == Animation::Paused ||
241      other->run_state_ == Animation::Paused) {
242    other->run_state_ = run_state_;
243    other->pause_time_ = pause_time_;
244    other->total_paused_time_ = total_paused_time_;
245  }
246}
247
248}  // namespace cc
249