Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / ui / views / animation / scroll_animator.cc
blob7d689993f2b236027f9496a3d5e576fde3c32a51
1 // Copyright (c) 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.
5 #include "ui/views/animation/scroll_animator.h"
7 #include <algorithm>
8 #include <cmath>
10 #include "base/logging.h"
11 #include "ui/gfx/animation/slide_animation.h"
13 namespace {
14 const float kDefaultAcceleration = -1500.0f; // in pixels per second^2
16 // Assumes that d0 == 0.0f
17 float GetPosition(float v0, float a, float t) {
18 float max_t = -v0 / a;
19 if (t > max_t)
20 t = max_t;
21 return t * (v0 + 0.5f * a * t);
24 float GetDelta(float v0, float a, float t1, float t2) {
25 return GetPosition(v0, a, t2) - GetPosition(v0, a, t1);
28 } // namespace
30 namespace views {
32 ScrollAnimator::ScrollAnimator(ScrollDelegate* delegate)
33 : delegate_(delegate),
34 velocity_x_(0.0f),
35 velocity_y_(0.0f),
36 last_t_(0.0f),
37 duration_(0.0f),
38 acceleration_(kDefaultAcceleration) {
39 DCHECK(delegate);
42 ScrollAnimator::~ScrollAnimator() {
43 Stop();
46 void ScrollAnimator::Start(float velocity_x, float velocity_y) {
47 if (acceleration_ >= 0.0f)
48 acceleration_ = kDefaultAcceleration;
49 float v = std::max(fabs(velocity_x), fabs(velocity_y));
50 last_t_ = 0.0f;
51 velocity_x_ = velocity_x;
52 velocity_y_ = velocity_y;
53 duration_ = -v / acceleration_; // in seconds
54 animation_.reset(new gfx::SlideAnimation(this));
55 animation_->SetSlideDuration(static_cast<int>(duration_ * 1000));
56 animation_->Show();
59 void ScrollAnimator::Stop() {
60 velocity_x_ = velocity_y_ = last_t_ = duration_ = 0.0f;
61 animation_.reset();
64 void ScrollAnimator::AnimationEnded(const gfx::Animation* animation) {
65 Stop();
68 void ScrollAnimator::AnimationProgressed(const gfx::Animation* animation) {
69 float t = static_cast<float>(animation->GetCurrentValue()) * duration_;
70 float a_x = velocity_x_ > 0 ? acceleration_ : -acceleration_;
71 float a_y = velocity_y_ > 0 ? acceleration_ : -acceleration_;
72 float dx = GetDelta(velocity_x_, a_x, last_t_, t);
73 float dy = GetDelta(velocity_y_, a_y, last_t_, t);
74 last_t_ = t;
75 delegate_->OnScroll(dx, dy);
78 void ScrollAnimator::AnimationCanceled(const gfx::Animation* animation) {
79 Stop();
82 } // namespace views