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