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