Home | History | Annotate | Download | only in common
      1 /*
      2  * Copyright (C) 2010 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package com.android.gallery3d.common;
     18 
     19 import android.content.Context;
     20 import android.hardware.SensorManager;
     21 import android.util.FloatMath;
     22 import android.util.Log;
     23 import android.view.ViewConfiguration;
     24 import android.view.animation.AnimationUtils;
     25 import android.view.animation.Interpolator;
     26 
     27 /**
     28  * This class encapsulates scrolling with the ability to overshoot the bounds
     29  * of a scrolling operation. This class is a drop-in replacement for
     30  * {@link android.widget.Scroller} in most cases.
     31  */
     32 public class OverScroller {
     33     private int mMode;
     34 
     35     private final SplineOverScroller mScrollerX;
     36     private final SplineOverScroller mScrollerY;
     37 
     38     private Interpolator mInterpolator;
     39 
     40     private final boolean mFlywheel;
     41 
     42     private static final int DEFAULT_DURATION = 250;
     43     private static final int SCROLL_MODE = 0;
     44     private static final int FLING_MODE = 1;
     45 
     46     /**
     47      * Creates an OverScroller with a viscous fluid scroll interpolator and flywheel.
     48      * @param context
     49      */
     50     public OverScroller(Context context) {
     51         this(context, null);
     52     }
     53 
     54     /**
     55      * Creates an OverScroller with flywheel enabled.
     56      * @param context The context of this application.
     57      * @param interpolator The scroll interpolator. If null, a default (viscous) interpolator will
     58      * be used.
     59      */
     60     public OverScroller(Context context, Interpolator interpolator) {
     61         this(context, interpolator, true);
     62     }
     63 
     64     /**
     65      * Creates an OverScroller.
     66      * @param context The context of this application.
     67      * @param interpolator The scroll interpolator. If null, a default (viscous) interpolator will
     68      * be used.
     69      * @param flywheel If true, successive fling motions will keep on increasing scroll speed.
     70      * @hide
     71      */
     72     public OverScroller(Context context, Interpolator interpolator, boolean flywheel) {
     73         mInterpolator = interpolator;
     74         mFlywheel = flywheel;
     75         mScrollerX = new SplineOverScroller();
     76         mScrollerY = new SplineOverScroller();
     77 
     78         SplineOverScroller.initFromContext(context);
     79     }
     80 
     81     /**
     82      * Creates an OverScroller with flywheel enabled.
     83      * @param context The context of this application.
     84      * @param interpolator The scroll interpolator. If null, a default (viscous) interpolator will
     85      * be used.
     86      * @param bounceCoefficientX A value between 0 and 1 that will determine the proportion of the
     87      * velocity which is preserved in the bounce when the horizontal edge is reached. A null value
     88      * means no bounce. This behavior is no longer supported and this coefficient has no effect.
     89      * @param bounceCoefficientY Same as bounceCoefficientX but for the vertical direction. This
     90      * behavior is no longer supported and this coefficient has no effect.
     91      * !deprecated Use {!link #OverScroller(Context, Interpolator, boolean)} instead.
     92      */
     93     public OverScroller(Context context, Interpolator interpolator,
     94             float bounceCoefficientX, float bounceCoefficientY) {
     95         this(context, interpolator, true);
     96     }
     97 
     98     /**
     99      * Creates an OverScroller.
    100      * @param context The context of this application.
    101      * @param interpolator The scroll interpolator. If null, a default (viscous) interpolator will
    102      * be used.
    103      * @param bounceCoefficientX A value between 0 and 1 that will determine the proportion of the
    104      * velocity which is preserved in the bounce when the horizontal edge is reached. A null value
    105      * means no bounce. This behavior is no longer supported and this coefficient has no effect.
    106      * @param bounceCoefficientY Same as bounceCoefficientX but for the vertical direction. This
    107      * behavior is no longer supported and this coefficient has no effect.
    108      * @param flywheel If true, successive fling motions will keep on increasing scroll speed.
    109      * !deprecated Use {!link OverScroller(Context, Interpolator, boolean)} instead.
    110      */
    111     public OverScroller(Context context, Interpolator interpolator,
    112             float bounceCoefficientX, float bounceCoefficientY, boolean flywheel) {
    113         this(context, interpolator, flywheel);
    114     }
    115 
    116     void setInterpolator(Interpolator interpolator) {
    117         mInterpolator = interpolator;
    118     }
    119 
    120     /**
    121      * The amount of friction applied to flings. The default value
    122      * is {@link ViewConfiguration#getScrollFriction}.
    123      *
    124      * @param friction A scalar dimension-less value representing the coefficient of
    125      *         friction.
    126      */
    127     public final void setFriction(float friction) {
    128         mScrollerX.setFriction(friction);
    129         mScrollerY.setFriction(friction);
    130     }
    131 
    132     /**
    133      *
    134      * Returns whether the scroller has finished scrolling.
    135      *
    136      * @return True if the scroller has finished scrolling, false otherwise.
    137      */
    138     public final boolean isFinished() {
    139         return mScrollerX.mFinished && mScrollerY.mFinished;
    140     }
    141 
    142     /**
    143      * Force the finished field to a particular value. Contrary to
    144      * {@link #abortAnimation()}, forcing the animation to finished
    145      * does NOT cause the scroller to move to the final x and y
    146      * position.
    147      *
    148      * @param finished The new finished value.
    149      */
    150     public final void forceFinished(boolean finished) {
    151         mScrollerX.mFinished = mScrollerY.mFinished = finished;
    152     }
    153 
    154     /**
    155      * Returns the current X offset in the scroll.
    156      *
    157      * @return The new X offset as an absolute distance from the origin.
    158      */
    159     public final int getCurrX() {
    160         return mScrollerX.mCurrentPosition;
    161     }
    162 
    163     /**
    164      * Returns the current Y offset in the scroll.
    165      *
    166      * @return The new Y offset as an absolute distance from the origin.
    167      */
    168     public final int getCurrY() {
    169         return mScrollerY.mCurrentPosition;
    170     }
    171 
    172     /**
    173      * Returns the absolute value of the current velocity.
    174      *
    175      * @return The original velocity less the deceleration, norm of the X and Y velocity vector.
    176      */
    177     public float getCurrVelocity() {
    178         float squaredNorm = mScrollerX.mCurrVelocity * mScrollerX.mCurrVelocity;
    179         squaredNorm += mScrollerY.mCurrVelocity * mScrollerY.mCurrVelocity;
    180         return FloatMath.sqrt(squaredNorm);
    181     }
    182 
    183     /**
    184      * Returns the start X offset in the scroll.
    185      *
    186      * @return The start X offset as an absolute distance from the origin.
    187      */
    188     public final int getStartX() {
    189         return mScrollerX.mStart;
    190     }
    191 
    192     /**
    193      * Returns the start Y offset in the scroll.
    194      *
    195      * @return The start Y offset as an absolute distance from the origin.
    196      */
    197     public final int getStartY() {
    198         return mScrollerY.mStart;
    199     }
    200 
    201     /**
    202      * Returns where the scroll will end. Valid only for "fling" scrolls.
    203      *
    204      * @return The final X offset as an absolute distance from the origin.
    205      */
    206     public final int getFinalX() {
    207         return mScrollerX.mFinal;
    208     }
    209 
    210     /**
    211      * Returns where the scroll will end. Valid only for "fling" scrolls.
    212      *
    213      * @return The final Y offset as an absolute distance from the origin.
    214      */
    215     public final int getFinalY() {
    216         return mScrollerY.mFinal;
    217     }
    218 
    219     /**
    220      * Returns how long the scroll event will take, in milliseconds.
    221      *
    222      * @return The duration of the scroll in milliseconds.
    223      *
    224      * @hide Pending removal once nothing depends on it
    225      * @deprecated OverScrollers don't necessarily have a fixed duration.
    226      *             This function will lie to the best of its ability.
    227      */
    228     @Deprecated
    229     public final int getDuration() {
    230         return Math.max(mScrollerX.mDuration, mScrollerY.mDuration);
    231     }
    232 
    233     /**
    234      * Extend the scroll animation. This allows a running animation to scroll
    235      * further and longer, when used with {@link #setFinalX(int)} or {@link #setFinalY(int)}.
    236      *
    237      * @param extend Additional time to scroll in milliseconds.
    238      * @see #setFinalX(int)
    239      * @see #setFinalY(int)
    240      *
    241      * @hide Pending removal once nothing depends on it
    242      * @deprecated OverScrollers don't necessarily have a fixed duration.
    243      *             Instead of setting a new final position and extending
    244      *             the duration of an existing scroll, use startScroll
    245      *             to begin a new animation.
    246      */
    247     @Deprecated
    248     public void extendDuration(int extend) {
    249         mScrollerX.extendDuration(extend);
    250         mScrollerY.extendDuration(extend);
    251     }
    252 
    253     /**
    254      * Sets the final position (X) for this scroller.
    255      *
    256      * @param newX The new X offset as an absolute distance from the origin.
    257      * @see #extendDuration(int)
    258      * @see #setFinalY(int)
    259      *
    260      * @hide Pending removal once nothing depends on it
    261      * @deprecated OverScroller's final position may change during an animation.
    262      *             Instead of setting a new final position and extending
    263      *             the duration of an existing scroll, use startScroll
    264      *             to begin a new animation.
    265      */
    266     @Deprecated
    267     public void setFinalX(int newX) {
    268         mScrollerX.setFinalPosition(newX);
    269     }
    270 
    271     /**
    272      * Sets the final position (Y) for this scroller.
    273      *
    274      * @param newY The new Y offset as an absolute distance from the origin.
    275      * @see #extendDuration(int)
    276      * @see #setFinalX(int)
    277      *
    278      * @hide Pending removal once nothing depends on it
    279      * @deprecated OverScroller's final position may change during an animation.
    280      *             Instead of setting a new final position and extending
    281      *             the duration of an existing scroll, use startScroll
    282      *             to begin a new animation.
    283      */
    284     @Deprecated
    285     public void setFinalY(int newY) {
    286         mScrollerY.setFinalPosition(newY);
    287     }
    288 
    289     /**
    290      * Call this when you want to know the new location. If it returns true, the
    291      * animation is not yet finished.
    292      */
    293     public boolean computeScrollOffset() {
    294         if (isFinished()) {
    295             return false;
    296         }
    297 
    298         switch (mMode) {
    299             case SCROLL_MODE:
    300                 long time = AnimationUtils.currentAnimationTimeMillis();
    301                 // Any scroller can be used for time, since they were started
    302                 // together in scroll mode. We use X here.
    303                 final long elapsedTime = time - mScrollerX.mStartTime;
    304 
    305                 final int duration = mScrollerX.mDuration;
    306                 if (elapsedTime < duration) {
    307                     float q = (float) (elapsedTime) / duration;
    308 
    309                     if (mInterpolator == null) {
    310                         q = Scroller.viscousFluid(q);
    311                     } else {
    312                         q = mInterpolator.getInterpolation(q);
    313                     }
    314 
    315                     mScrollerX.updateScroll(q);
    316                     mScrollerY.updateScroll(q);
    317                 } else {
    318                     abortAnimation();
    319                 }
    320                 break;
    321 
    322             case FLING_MODE:
    323                 if (!mScrollerX.mFinished) {
    324                     if (!mScrollerX.update()) {
    325                         if (!mScrollerX.continueWhenFinished()) {
    326                             mScrollerX.finish();
    327                         }
    328                     }
    329                 }
    330 
    331                 if (!mScrollerY.mFinished) {
    332                     if (!mScrollerY.update()) {
    333                         if (!mScrollerY.continueWhenFinished()) {
    334                             mScrollerY.finish();
    335                         }
    336                     }
    337                 }
    338 
    339                 break;
    340         }
    341 
    342         return true;
    343     }
    344 
    345     /**
    346      * Start scrolling by providing a starting point and the distance to travel.
    347      * The scroll will use the default value of 250 milliseconds for the
    348      * duration.
    349      *
    350      * @param startX Starting horizontal scroll offset in pixels. Positive
    351      *        numbers will scroll the content to the left.
    352      * @param startY Starting vertical scroll offset in pixels. Positive numbers
    353      *        will scroll the content up.
    354      * @param dx Horizontal distance to travel. Positive numbers will scroll the
    355      *        content to the left.
    356      * @param dy Vertical distance to travel. Positive numbers will scroll the
    357      *        content up.
    358      */
    359     public void startScroll(int startX, int startY, int dx, int dy) {
    360         startScroll(startX, startY, dx, dy, DEFAULT_DURATION);
    361     }
    362 
    363     /**
    364      * Start scrolling by providing a starting point and the distance to travel.
    365      *
    366      * @param startX Starting horizontal scroll offset in pixels. Positive
    367      *        numbers will scroll the content to the left.
    368      * @param startY Starting vertical scroll offset in pixels. Positive numbers
    369      *        will scroll the content up.
    370      * @param dx Horizontal distance to travel. Positive numbers will scroll the
    371      *        content to the left.
    372      * @param dy Vertical distance to travel. Positive numbers will scroll the
    373      *        content up.
    374      * @param duration Duration of the scroll in milliseconds.
    375      */
    376     public void startScroll(int startX, int startY, int dx, int dy, int duration) {
    377         mMode = SCROLL_MODE;
    378         mScrollerX.startScroll(startX, dx, duration);
    379         mScrollerY.startScroll(startY, dy, duration);
    380     }
    381 
    382     /**
    383      * Call this when you want to 'spring back' into a valid coordinate range.
    384      *
    385      * @param startX Starting X coordinate
    386      * @param startY Starting Y coordinate
    387      * @param minX Minimum valid X value
    388      * @param maxX Maximum valid X value
    389      * @param minY Minimum valid Y value
    390      * @param maxY Minimum valid Y value
    391      * @return true if a springback was initiated, false if startX and startY were
    392      *          already within the valid range.
    393      */
    394     public boolean springBack(int startX, int startY, int minX, int maxX, int minY, int maxY) {
    395         mMode = FLING_MODE;
    396 
    397         // Make sure both methods are called.
    398         final boolean spingbackX = mScrollerX.springback(startX, minX, maxX);
    399         final boolean spingbackY = mScrollerY.springback(startY, minY, maxY);
    400         return spingbackX || spingbackY;
    401     }
    402 
    403     public void fling(int startX, int startY, int velocityX, int velocityY,
    404             int minX, int maxX, int minY, int maxY) {
    405         fling(startX, startY, velocityX, velocityY, minX, maxX, minY, maxY, 0, 0);
    406     }
    407 
    408     /**
    409      * Start scrolling based on a fling gesture. The distance traveled will
    410      * depend on the initial velocity of the fling.
    411      *
    412      * @param startX Starting point of the scroll (X)
    413      * @param startY Starting point of the scroll (Y)
    414      * @param velocityX Initial velocity of the fling (X) measured in pixels per
    415      *            second.
    416      * @param velocityY Initial velocity of the fling (Y) measured in pixels per
    417      *            second
    418      * @param minX Minimum X value. The scroller will not scroll past this point
    419      *            unless overX > 0. If overfling is allowed, it will use minX as
    420      *            a springback boundary.
    421      * @param maxX Maximum X value. The scroller will not scroll past this point
    422      *            unless overX > 0. If overfling is allowed, it will use maxX as
    423      *            a springback boundary.
    424      * @param minY Minimum Y value. The scroller will not scroll past this point
    425      *            unless overY > 0. If overfling is allowed, it will use minY as
    426      *            a springback boundary.
    427      * @param maxY Maximum Y value. The scroller will not scroll past this point
    428      *            unless overY > 0. If overfling is allowed, it will use maxY as
    429      *            a springback boundary.
    430      * @param overX Overfling range. If > 0, horizontal overfling in either
    431      *            direction will be possible.
    432      * @param overY Overfling range. If > 0, vertical overfling in either
    433      *            direction will be possible.
    434      */
    435     public void fling(int startX, int startY, int velocityX, int velocityY,
    436             int minX, int maxX, int minY, int maxY, int overX, int overY) {
    437         // Continue a scroll or fling in progress
    438         if (mFlywheel && !isFinished()) {
    439             float oldVelocityX = mScrollerX.mCurrVelocity;
    440             float oldVelocityY = mScrollerY.mCurrVelocity;
    441             if (Math.signum(velocityX) == Math.signum(oldVelocityX) &&
    442                     Math.signum(velocityY) == Math.signum(oldVelocityY)) {
    443                 velocityX += oldVelocityX;
    444                 velocityY += oldVelocityY;
    445             }
    446         }
    447 
    448         mMode = FLING_MODE;
    449         mScrollerX.fling(startX, velocityX, minX, maxX, overX);
    450         mScrollerY.fling(startY, velocityY, minY, maxY, overY);
    451     }
    452 
    453     /**
    454      * Notify the scroller that we've reached a horizontal boundary.
    455      * Normally the information to handle this will already be known
    456      * when the animation is started, such as in a call to one of the
    457      * fling functions. However there are cases where this cannot be known
    458      * in advance. This function will transition the current motion and
    459      * animate from startX to finalX as appropriate.
    460      *
    461      * @param startX Starting/current X position
    462      * @param finalX Desired final X position
    463      * @param overX Magnitude of overscroll allowed. This should be the maximum
    464      *              desired distance from finalX. Absolute value - must be positive.
    465      */
    466     public void notifyHorizontalEdgeReached(int startX, int finalX, int overX) {
    467         mScrollerX.notifyEdgeReached(startX, finalX, overX);
    468     }
    469 
    470     /**
    471      * Notify the scroller that we've reached a vertical boundary.
    472      * Normally the information to handle this will already be known
    473      * when the animation is started, such as in a call to one of the
    474      * fling functions. However there are cases where this cannot be known
    475      * in advance. This function will animate a parabolic motion from
    476      * startY to finalY.
    477      *
    478      * @param startY Starting/current Y position
    479      * @param finalY Desired final Y position
    480      * @param overY Magnitude of overscroll allowed. This should be the maximum
    481      *              desired distance from finalY. Absolute value - must be positive.
    482      */
    483     public void notifyVerticalEdgeReached(int startY, int finalY, int overY) {
    484         mScrollerY.notifyEdgeReached(startY, finalY, overY);
    485     }
    486 
    487     /**
    488      * Returns whether the current Scroller is currently returning to a valid position.
    489      * Valid bounds were provided by the
    490      * {@link #fling(int, int, int, int, int, int, int, int, int, int)} method.
    491      *
    492      * One should check this value before calling
    493      * {@link #startScroll(int, int, int, int)} as the interpolation currently in progress
    494      * to restore a valid position will then be stopped. The caller has to take into account
    495      * the fact that the started scroll will start from an overscrolled position.
    496      *
    497      * @return true when the current position is overscrolled and in the process of
    498      *         interpolating back to a valid value.
    499      */
    500     public boolean isOverScrolled() {
    501         return ((!mScrollerX.mFinished &&
    502                 mScrollerX.mState != SplineOverScroller.SPLINE) ||
    503                 (!mScrollerY.mFinished &&
    504                         mScrollerY.mState != SplineOverScroller.SPLINE));
    505     }
    506 
    507     /**
    508      * Stops the animation. Contrary to {@link #forceFinished(boolean)},
    509      * aborting the animating causes the scroller to move to the final x and y
    510      * positions.
    511      *
    512      * @see #forceFinished(boolean)
    513      */
    514     public void abortAnimation() {
    515         mScrollerX.finish();
    516         mScrollerY.finish();
    517     }
    518 
    519     /**
    520      * Returns the time elapsed since the beginning of the scrolling.
    521      *
    522      * @return The elapsed time in milliseconds.
    523      *
    524      * @hide
    525      */
    526     public int timePassed() {
    527         final long time = AnimationUtils.currentAnimationTimeMillis();
    528         final long startTime = Math.min(mScrollerX.mStartTime, mScrollerY.mStartTime);
    529         return (int) (time - startTime);
    530     }
    531 
    532     /**
    533      * @hide
    534      */
    535     public boolean isScrollingInDirection(float xvel, float yvel) {
    536         final int dx = mScrollerX.mFinal - mScrollerX.mStart;
    537         final int dy = mScrollerY.mFinal - mScrollerY.mStart;
    538         return !isFinished() && Math.signum(xvel) == Math.signum(dx) &&
    539                 Math.signum(yvel) == Math.signum(dy);
    540     }
    541 
    542     static class SplineOverScroller {
    543         // Initial position
    544         private int mStart;
    545 
    546         // Current position
    547         private int mCurrentPosition;
    548 
    549         // Final position
    550         private int mFinal;
    551 
    552         // Initial velocity
    553         private int mVelocity;
    554 
    555         // Current velocity
    556         private float mCurrVelocity;
    557 
    558         // Constant current deceleration
    559         private float mDeceleration;
    560 
    561         // Animation starting time, in system milliseconds
    562         private long mStartTime;
    563 
    564         // Animation duration, in milliseconds
    565         private int mDuration;
    566 
    567         // Duration to complete spline component of animation
    568         private int mSplineDuration;
    569 
    570         // Distance to travel along spline animation
    571         private int mSplineDistance;
    572 
    573         // Whether the animation is currently in progress
    574         private boolean mFinished;
    575 
    576         // The allowed overshot distance before boundary is reached.
    577         private int mOver;
    578 
    579         // Fling friction
    580         private float mFlingFriction = ViewConfiguration.getScrollFriction();
    581 
    582         // Current state of the animation.
    583         private int mState = SPLINE;
    584 
    585         // Constant gravity value, used in the deceleration phase.
    586         private static final float GRAVITY = 2000.0f;
    587 
    588         // A device specific coefficient adjusted to physical values.
    589         private static float PHYSICAL_COEF;
    590 
    591         private static float DECELERATION_RATE = (float) (Math.log(0.78) / Math.log(0.9));
    592         private static final float INFLEXION = 0.35f; // Tension lines cross at (INFLEXION, 1)
    593         private static final float START_TENSION = 0.5f;
    594         private static final float END_TENSION = 1.0f;
    595         private static final float P1 = START_TENSION * INFLEXION;
    596         private static final float P2 = 1.0f - END_TENSION * (1.0f - INFLEXION);
    597 
    598         private static final int NB_SAMPLES = 100;
    599         private static final float[] SPLINE_POSITION = new float[NB_SAMPLES + 1];
    600         private static final float[] SPLINE_TIME = new float[NB_SAMPLES + 1];
    601 
    602         private static final int SPLINE = 0;
    603         private static final int CUBIC = 1;
    604         private static final int BALLISTIC = 2;
    605 
    606         static {
    607             float x_min = 0.0f;
    608             float y_min = 0.0f;
    609             for (int i = 0; i < NB_SAMPLES; i++) {
    610                 final float alpha = (float) i / NB_SAMPLES;
    611 
    612                 float x_max = 1.0f;
    613                 float x, tx, coef;
    614                 while (true) {
    615                     x = x_min + (x_max - x_min) / 2.0f;
    616                     coef = 3.0f * x * (1.0f - x);
    617                     tx = coef * ((1.0f - x) * P1 + x * P2) + x * x * x;
    618                     if (Math.abs(tx - alpha) < 1E-5) break;
    619                     if (tx > alpha) x_max = x;
    620                     else x_min = x;
    621                 }
    622                 SPLINE_POSITION[i] = coef * ((1.0f - x) * START_TENSION + x) + x * x * x;
    623 
    624                 float y_max = 1.0f;
    625                 float y, dy;
    626                 while (true) {
    627                     y = y_min + (y_max - y_min) / 2.0f;
    628                     coef = 3.0f * y * (1.0f - y);
    629                     dy = coef * ((1.0f - y) * START_TENSION + y) + y * y * y;
    630                     if (Math.abs(dy - alpha) < 1E-5) break;
    631                     if (dy > alpha) y_max = y;
    632                     else y_min = y;
    633                 }
    634                 SPLINE_TIME[i] = coef * ((1.0f - y) * P1 + y * P2) + y * y * y;
    635             }
    636             SPLINE_POSITION[NB_SAMPLES] = SPLINE_TIME[NB_SAMPLES] = 1.0f;
    637         }
    638 
    639         static void initFromContext(Context context) {
    640             final float ppi = context.getResources().getDisplayMetrics().density * 160.0f;
    641             PHYSICAL_COEF = SensorManager.GRAVITY_EARTH // g (m/s^2)
    642                     * 39.37f // inch/meter
    643                     * ppi
    644                     * 0.84f; // look and feel tuning
    645         }
    646 
    647         void setFriction(float friction) {
    648             mFlingFriction = friction;
    649         }
    650 
    651         SplineOverScroller() {
    652             mFinished = true;
    653         }
    654 
    655         void updateScroll(float q) {
    656             mCurrentPosition = mStart + Math.round(q * (mFinal - mStart));
    657         }
    658 
    659         /*
    660          * Get a signed deceleration that will reduce the velocity.
    661          */
    662         static private float getDeceleration(int velocity) {
    663             return velocity > 0 ? -GRAVITY : GRAVITY;
    664         }
    665 
    666         /*
    667          * Modifies mDuration to the duration it takes to get from start to newFinal using the
    668          * spline interpolation. The previous duration was needed to get to oldFinal.
    669          */
    670         private void adjustDuration(int start, int oldFinal, int newFinal) {
    671             final int oldDistance = oldFinal - start;
    672             final int newDistance = newFinal - start;
    673             final float x = Math.abs((float) newDistance / oldDistance);
    674             final int index = (int) (NB_SAMPLES * x);
    675             if (index < NB_SAMPLES) {
    676                 final float x_inf = (float) index / NB_SAMPLES;
    677                 final float x_sup = (float) (index + 1) / NB_SAMPLES;
    678                 final float t_inf = SPLINE_TIME[index];
    679                 final float t_sup = SPLINE_TIME[index + 1];
    680                 final float timeCoef = t_inf + (x - x_inf) / (x_sup - x_inf) * (t_sup - t_inf);
    681                 mDuration *= timeCoef;
    682             }
    683         }
    684 
    685         void startScroll(int start, int distance, int duration) {
    686             mFinished = false;
    687 
    688             mStart = start;
    689             mFinal = start + distance;
    690 
    691             mStartTime = AnimationUtils.currentAnimationTimeMillis();
    692             mDuration = duration;
    693 
    694             // Unused
    695             mDeceleration = 0.0f;
    696             mVelocity = 0;
    697         }
    698 
    699         void finish() {
    700             mCurrentPosition = mFinal;
    701             // Not reset since WebView relies on this value for fast fling.
    702             // TODO: restore when WebView uses the fast fling implemented in this class.
    703             // mCurrVelocity = 0.0f;
    704             mFinished = true;
    705         }
    706 
    707         void setFinalPosition(int position) {
    708             mFinal = position;
    709             mFinished = false;
    710         }
    711 
    712         void extendDuration(int extend) {
    713             final long time = AnimationUtils.currentAnimationTimeMillis();
    714             final int elapsedTime = (int) (time - mStartTime);
    715             mDuration = elapsedTime + extend;
    716             mFinished = false;
    717         }
    718 
    719         boolean springback(int start, int min, int max) {
    720             mFinished = true;
    721 
    722             mStart = mFinal = start;
    723             mVelocity = 0;
    724 
    725             mStartTime = AnimationUtils.currentAnimationTimeMillis();
    726             mDuration = 0;
    727 
    728             if (start < min) {
    729                 startSpringback(start, min, 0);
    730             } else if (start > max) {
    731                 startSpringback(start, max, 0);
    732             }
    733 
    734             return !mFinished;
    735         }
    736 
    737         private void startSpringback(int start, int end, int velocity) {
    738             // mStartTime has been set
    739             mFinished = false;
    740             mState = CUBIC;
    741             mStart = start;
    742             mFinal = end;
    743             final int delta = start - end;
    744             mDeceleration = getDeceleration(delta);
    745             // TODO take velocity into account
    746             mVelocity = -delta; // only sign is used
    747             mOver = Math.abs(delta);
    748             mDuration = (int) (1000.0 * Math.sqrt(-2.0 * delta / mDeceleration));
    749         }
    750 
    751         void fling(int start, int velocity, int min, int max, int over) {
    752             mOver = over;
    753             mFinished = false;
    754             mCurrVelocity = mVelocity = velocity;
    755             mDuration = mSplineDuration = 0;
    756             mStartTime = AnimationUtils.currentAnimationTimeMillis();
    757             mCurrentPosition = mStart = start;
    758 
    759             if (start > max || start < min) {
    760                 startAfterEdge(start, min, max, velocity);
    761                 return;
    762             }
    763 
    764             mState = SPLINE;
    765             double totalDistance = 0.0;
    766 
    767             if (velocity != 0) {
    768                 mDuration = mSplineDuration = getSplineFlingDuration(velocity);
    769                 totalDistance = getSplineFlingDistance(velocity);
    770             }
    771 
    772             mSplineDistance = (int) (totalDistance * Math.signum(velocity));
    773             mFinal = start + mSplineDistance;
    774 
    775             // Clamp to a valid final position
    776             if (mFinal < min) {
    777                 adjustDuration(mStart, mFinal, min);
    778                 mFinal = min;
    779             }
    780 
    781             if (mFinal > max) {
    782                 adjustDuration(mStart, mFinal, max);
    783                 mFinal = max;
    784             }
    785         }
    786 
    787         private double getSplineDeceleration(int velocity) {
    788             return Math.log(INFLEXION * Math.abs(velocity) / (mFlingFriction * PHYSICAL_COEF));
    789         }
    790 
    791         private double getSplineFlingDistance(int velocity) {
    792             final double l = getSplineDeceleration(velocity);
    793             final double decelMinusOne = DECELERATION_RATE - 1.0;
    794             return mFlingFriction * PHYSICAL_COEF * Math.exp(DECELERATION_RATE / decelMinusOne * l);
    795         }
    796 
    797         /* Returns the duration, expressed in milliseconds */
    798         private int getSplineFlingDuration(int velocity) {
    799             final double l = getSplineDeceleration(velocity);
    800             final double decelMinusOne = DECELERATION_RATE - 1.0;
    801             return (int) (1000.0 * Math.exp(l / decelMinusOne));
    802         }
    803 
    804         private void fitOnBounceCurve(int start, int end, int velocity) {
    805             // Simulate a bounce that started from edge
    806             final float durationToApex = - velocity / mDeceleration;
    807             final float distanceToApex = velocity * velocity / 2.0f / Math.abs(mDeceleration);
    808             final float distanceToEdge = Math.abs(end - start);
    809             final float totalDuration = (float) Math.sqrt(
    810                     2.0 * (distanceToApex + distanceToEdge) / Math.abs(mDeceleration));
    811             mStartTime -= (int) (1000.0f * (totalDuration - durationToApex));
    812             mStart = end;
    813             mVelocity = (int) (- mDeceleration * totalDuration);
    814         }
    815 
    816         private void startBounceAfterEdge(int start, int end, int velocity) {
    817             mDeceleration = getDeceleration(velocity == 0 ? start - end : velocity);
    818             fitOnBounceCurve(start, end, velocity);
    819             onEdgeReached();
    820         }
    821 
    822         private void startAfterEdge(int start, int min, int max, int velocity) {
    823             if (start > min && start < max) {
    824                 Log.e("OverScroller", "startAfterEdge called from a valid position");
    825                 mFinished = true;
    826                 return;
    827             }
    828             final boolean positive = start > max;
    829             final int edge = positive ? max : min;
    830             final int overDistance = start - edge;
    831             boolean keepIncreasing = overDistance * velocity >= 0;
    832             if (keepIncreasing) {
    833                 // Will result in a bounce or a to_boundary depending on velocity.
    834                 startBounceAfterEdge(start, edge, velocity);
    835             } else {
    836                 final double totalDistance = getSplineFlingDistance(velocity);
    837                 if (totalDistance > Math.abs(overDistance)) {
    838                     fling(start, velocity, positive ? min : start, positive ? start : max, mOver);
    839                 } else {
    840                     startSpringback(start, edge, velocity);
    841                 }
    842             }
    843         }
    844 
    845         void notifyEdgeReached(int start, int end, int over) {
    846             // mState is used to detect successive notifications
    847             if (mState == SPLINE) {
    848                 mOver = over;
    849                 mStartTime = AnimationUtils.currentAnimationTimeMillis();
    850                 // We were in fling/scroll mode before: current velocity is such that distance to
    851                 // edge is increasing. This ensures that startAfterEdge will not start a new fling.
    852                 startAfterEdge(start, end, end, (int) mCurrVelocity);
    853             }
    854         }
    855 
    856         private void onEdgeReached() {
    857             // mStart, mVelocity and mStartTime were adjusted to their values when edge was reached.
    858             float distance = mVelocity * mVelocity / (2.0f * Math.abs(mDeceleration));
    859             final float sign = Math.signum(mVelocity);
    860 
    861             if (distance > mOver) {
    862                 // Default deceleration is not sufficient to slow us down before boundary
    863                  mDeceleration = - sign * mVelocity * mVelocity / (2.0f * mOver);
    864                  distance = mOver;
    865             }
    866 
    867             mOver = (int) distance;
    868             mState = BALLISTIC;
    869             mFinal = mStart + (int) (mVelocity > 0 ? distance : -distance);
    870             mDuration = - (int) (1000.0f * mVelocity / mDeceleration);
    871         }
    872 
    873         boolean continueWhenFinished() {
    874             switch (mState) {
    875                 case SPLINE:
    876                     // Duration from start to null velocity
    877                     if (mDuration < mSplineDuration) {
    878                         // If the animation was clamped, we reached the edge
    879                         mStart = mFinal;
    880                         // TODO Better compute speed when edge was reached
    881                         mVelocity = (int) mCurrVelocity;
    882                         mDeceleration = getDeceleration(mVelocity);
    883                         mStartTime += mDuration;
    884                         onEdgeReached();
    885                     } else {
    886                         // Normal stop, no need to continue
    887                         return false;
    888                     }
    889                     break;
    890                 case BALLISTIC:
    891                     mStartTime += mDuration;
    892                     startSpringback(mFinal, mStart, 0);
    893                     break;
    894                 case CUBIC:
    895                     return false;
    896             }
    897 
    898             update();
    899             return true;
    900         }
    901 
    902         /*
    903          * Update the current position and velocity for current time. Returns
    904          * true if update has been done and false if animation duration has been
    905          * reached.
    906          */
    907         boolean update() {
    908             final long time = AnimationUtils.currentAnimationTimeMillis();
    909             final long currentTime = time - mStartTime;
    910 
    911             if (currentTime > mDuration) {
    912                 return false;
    913             }
    914 
    915             double distance = 0.0;
    916             switch (mState) {
    917                 case SPLINE: {
    918                     final float t = (float) currentTime / mSplineDuration;
    919                     final int index = (int) (NB_SAMPLES * t);
    920                     float distanceCoef = 1.f;
    921                     float velocityCoef = 0.f;
    922                     if (index < NB_SAMPLES) {
    923                         final float t_inf = (float) index / NB_SAMPLES;
    924                         final float t_sup = (float) (index + 1) / NB_SAMPLES;
    925                         final float d_inf = SPLINE_POSITION[index];
    926                         final float d_sup = SPLINE_POSITION[index + 1];
    927                         velocityCoef = (d_sup - d_inf) / (t_sup - t_inf);
    928                         distanceCoef = d_inf + (t - t_inf) * velocityCoef;
    929                     }
    930 
    931                     distance = distanceCoef * mSplineDistance;
    932                     mCurrVelocity = velocityCoef * mSplineDistance / mSplineDuration * 1000.0f;
    933                     break;
    934                 }
    935 
    936                 case BALLISTIC: {
    937                     final float t = currentTime / 1000.0f;
    938                     mCurrVelocity = mVelocity + mDeceleration * t;
    939                     distance = mVelocity * t + mDeceleration * t * t / 2.0f;
    940                     break;
    941                 }
    942 
    943                 case CUBIC: {
    944                     final float t = (float) (currentTime) / mDuration;
    945                     final float t2 = t * t;
    946                     final float sign = Math.signum(mVelocity);
    947                     distance = sign * mOver * (3.0f * t2 - 2.0f * t * t2);
    948                     mCurrVelocity = sign * mOver * 6.0f * (- t + t2);
    949                     break;
    950                 }
    951             }
    952 
    953             mCurrentPosition = mStart + (int) Math.round(distance);
    954 
    955             return true;
    956         }
    957     }
    958 }
    959