Home | History | Annotate | Download | only in animation
      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.
      4 
      5 #include "ui/views/animation/scroll_animator.h"
      6 
      7 #include <algorithm>
      8 #include <cmath>
      9 
     10 #include "base/logging.h"
     11 #include "ui/gfx/animation/slide_animation.h"
     12 
     13 namespace {
     14 const float kDefaultAcceleration = -1500.0f; // in pixels per second^2
     15 
     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);
     22 }
     23 
     24 float GetDelta(float v0, float a, float t1, float t2) {
     25   return GetPosition(v0, a, t2) - GetPosition(v0, a, t1);
     26 }
     27 
     28 }  // namespace
     29 
     30 namespace views {
     31 
     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);
     40 }
     41 
     42 ScrollAnimator::~ScrollAnimator() {
     43   Stop();
     44 }
     45 
     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();
     57 }
     58 
     59 void ScrollAnimator::Stop() {
     60   velocity_x_ = velocity_y_ = last_t_ = duration_ = 0.0f;
     61   animation_.reset();
     62 }
     63 
     64 void ScrollAnimator::AnimationEnded(const gfx::Animation* animation) {
     65   Stop();
     66 }
     67 
     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);
     76 }
     77 
     78 void ScrollAnimator::AnimationCanceled(const gfx::Animation* animation) {
     79   Stop();
     80 }
     81 
     82 }  // namespace views
     83