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.animation;
18
19import android.os.Handler;
20import android.os.Looper;
21import android.os.Message;
22import android.os.SystemProperties;
23import android.util.AndroidRuntimeException;
24import android.view.Choreographer;
25import android.view.animation.AccelerateDecelerateInterpolator;
26import android.view.animation.AnimationUtils;
27import android.view.animation.LinearInterpolator;
28
29import java.util.ArrayList;
30import java.util.HashMap;
31
32/**
33 * This class provides a simple timing engine for running animations
34 * which calculate animated values and set them on target objects.
35 *
36 * <p>There is a single timing pulse that all animations use. It runs in a
37 * custom handler to ensure that property changes happen on the UI thread.</p>
38 *
39 * <p>By default, ValueAnimator uses non-linear time interpolation, via the
40 * {@link AccelerateDecelerateInterpolator} class, which accelerates into and decelerates
41 * out of an animation. This behavior can be changed by calling
42 * {@link ValueAnimator#setInterpolator(TimeInterpolator)}.</p>
43 *
44 * <div class="special reference">
45 * <h3>Developer Guides</h3>
46 * <p>For more information about animating with {@code ValueAnimator}, read the
47 * <a href="{@docRoot}guide/topics/graphics/prop-animation.html#value-animator">Property
48 * Animation</a> developer guide.</p>
49 * </div>
50 */
51public class ValueAnimator extends Animator {
52
53    /**
54     * Internal constants
55     */
56    private static float sDurationScale = 1.0f;
57
58    /**
59     * Values used with internal variable mPlayingState to indicate the current state of an
60     * animation.
61     */
62    static final int STOPPED    = 0; // Not yet playing
63    static final int RUNNING    = 1; // Playing normally
64    static final int SEEKED     = 2; // Seeked to some time value
65
66    /**
67     * Internal variables
68     * NOTE: This object implements the clone() method, making a deep copy of any referenced
69     * objects. As other non-trivial fields are added to this class, make sure to add logic
70     * to clone() to make deep copies of them.
71     */
72
73    // The first time that the animation's animateFrame() method is called. This time is used to
74    // determine elapsed time (and therefore the elapsed fraction) in subsequent calls
75    // to animateFrame()
76    long mStartTime;
77
78    /**
79     * Set when setCurrentPlayTime() is called. If negative, animation is not currently seeked
80     * to a value.
81     */
82    long mSeekTime = -1;
83
84    // The static sAnimationHandler processes the internal timing loop on which all animations
85    // are based
86    private static ThreadLocal<AnimationHandler> sAnimationHandler =
87            new ThreadLocal<AnimationHandler>();
88
89    // The time interpolator to be used if none is set on the animation
90    private static final TimeInterpolator sDefaultInterpolator =
91            new AccelerateDecelerateInterpolator();
92
93    /**
94     * Used to indicate whether the animation is currently playing in reverse. This causes the
95     * elapsed fraction to be inverted to calculate the appropriate values.
96     */
97    private boolean mPlayingBackwards = false;
98
99    /**
100     * This variable tracks the current iteration that is playing. When mCurrentIteration exceeds the
101     * repeatCount (if repeatCount!=INFINITE), the animation ends
102     */
103    private int mCurrentIteration = 0;
104
105    /**
106     * Tracks current elapsed/eased fraction, for querying in getAnimatedFraction().
107     */
108    private float mCurrentFraction = 0f;
109
110    /**
111     * Tracks whether a startDelay'd animation has begun playing through the startDelay.
112     */
113    private boolean mStartedDelay = false;
114
115    /**
116     * Tracks the time at which the animation began playing through its startDelay. This is
117     * different from the mStartTime variable, which is used to track when the animation became
118     * active (which is when the startDelay expired and the animation was added to the active
119     * animations list).
120     */
121    private long mDelayStartTime;
122
123    /**
124     * Flag that represents the current state of the animation. Used to figure out when to start
125     * an animation (if state == STOPPED). Also used to end an animation that
126     * has been cancel()'d or end()'d since the last animation frame. Possible values are
127     * STOPPED, RUNNING, SEEKED.
128     */
129    int mPlayingState = STOPPED;
130
131    /**
132     * Additional playing state to indicate whether an animator has been start()'d. There is
133     * some lag between a call to start() and the first animation frame. We should still note
134     * that the animation has been started, even if it's first animation frame has not yet
135     * happened, and reflect that state in isRunning().
136     * Note that delayed animations are different: they are not started until their first
137     * animation frame, which occurs after their delay elapses.
138     */
139    private boolean mRunning = false;
140
141    /**
142     * Additional playing state to indicate whether an animator has been start()'d, whether or
143     * not there is a nonzero startDelay.
144     */
145    private boolean mStarted = false;
146
147    /**
148     * Tracks whether we've notified listeners of the onAnimationSTart() event. This can be
149     * complex to keep track of since we notify listeners at different times depending on
150     * startDelay and whether start() was called before end().
151     */
152    private boolean mStartListenersCalled = false;
153
154    /**
155     * Flag that denotes whether the animation is set up and ready to go. Used to
156     * set up animation that has not yet been started.
157     */
158    boolean mInitialized = false;
159
160    //
161    // Backing variables
162    //
163
164    // How long the animation should last in ms
165    private long mDuration = (long)(300 * sDurationScale);
166    private long mUnscaledDuration = 300;
167
168    // The amount of time in ms to delay starting the animation after start() is called
169    private long mStartDelay = 0;
170    private long mUnscaledStartDelay = 0;
171
172    // The number of times the animation will repeat. The default is 0, which means the animation
173    // will play only once
174    private int mRepeatCount = 0;
175
176    /**
177     * The type of repetition that will occur when repeatMode is nonzero. RESTART means the
178     * animation will start from the beginning on every new cycle. REVERSE means the animation
179     * will reverse directions on each iteration.
180     */
181    private int mRepeatMode = RESTART;
182
183    /**
184     * The time interpolator to be used. The elapsed fraction of the animation will be passed
185     * through this interpolator to calculate the interpolated fraction, which is then used to
186     * calculate the animated values.
187     */
188    private TimeInterpolator mInterpolator = sDefaultInterpolator;
189
190    /**
191     * The set of listeners to be sent events through the life of an animation.
192     */
193    private ArrayList<AnimatorUpdateListener> mUpdateListeners = null;
194
195    /**
196     * The property/value sets being animated.
197     */
198    PropertyValuesHolder[] mValues;
199
200    /**
201     * A hashmap of the PropertyValuesHolder objects. This map is used to lookup animated values
202     * by property name during calls to getAnimatedValue(String).
203     */
204    HashMap<String, PropertyValuesHolder> mValuesMap;
205
206    /**
207     * Public constants
208     */
209
210    /**
211     * When the animation reaches the end and <code>repeatCount</code> is INFINITE
212     * or a positive value, the animation restarts from the beginning.
213     */
214    public static final int RESTART = 1;
215    /**
216     * When the animation reaches the end and <code>repeatCount</code> is INFINITE
217     * or a positive value, the animation reverses direction on every iteration.
218     */
219    public static final int REVERSE = 2;
220    /**
221     * This value used used with the {@link #setRepeatCount(int)} property to repeat
222     * the animation indefinitely.
223     */
224    public static final int INFINITE = -1;
225
226
227    /**
228     * @hide
229     */
230    public static void setDurationScale(float durationScale) {
231        sDurationScale = durationScale;
232    }
233
234    /**
235     * @hide
236     */
237    public static float getDurationScale() {
238        return sDurationScale;
239    }
240
241    /**
242     * Creates a new ValueAnimator object. This default constructor is primarily for
243     * use internally; the factory methods which take parameters are more generally
244     * useful.
245     */
246    public ValueAnimator() {
247    }
248
249    /**
250     * Constructs and returns a ValueAnimator that animates between int values. A single
251     * value implies that that value is the one being animated to. However, this is not typically
252     * useful in a ValueAnimator object because there is no way for the object to determine the
253     * starting value for the animation (unlike ObjectAnimator, which can derive that value
254     * from the target object and property being animated). Therefore, there should typically
255     * be two or more values.
256     *
257     * @param values A set of values that the animation will animate between over time.
258     * @return A ValueAnimator object that is set up to animate between the given values.
259     */
260    public static ValueAnimator ofInt(int... values) {
261        ValueAnimator anim = new ValueAnimator();
262        anim.setIntValues(values);
263        return anim;
264    }
265
266    /**
267     * Constructs and returns a ValueAnimator that animates between float values. A single
268     * value implies that that value is the one being animated to. However, this is not typically
269     * useful in a ValueAnimator object because there is no way for the object to determine the
270     * starting value for the animation (unlike ObjectAnimator, which can derive that value
271     * from the target object and property being animated). Therefore, there should typically
272     * be two or more values.
273     *
274     * @param values A set of values that the animation will animate between over time.
275     * @return A ValueAnimator object that is set up to animate between the given values.
276     */
277    public static ValueAnimator ofFloat(float... values) {
278        ValueAnimator anim = new ValueAnimator();
279        anim.setFloatValues(values);
280        return anim;
281    }
282
283    /**
284     * Constructs and returns a ValueAnimator that animates between the values
285     * specified in the PropertyValuesHolder objects.
286     *
287     * @param values A set of PropertyValuesHolder objects whose values will be animated
288     * between over time.
289     * @return A ValueAnimator object that is set up to animate between the given values.
290     */
291    public static ValueAnimator ofPropertyValuesHolder(PropertyValuesHolder... values) {
292        ValueAnimator anim = new ValueAnimator();
293        anim.setValues(values);
294        return anim;
295    }
296    /**
297     * Constructs and returns a ValueAnimator that animates between Object values. A single
298     * value implies that that value is the one being animated to. However, this is not typically
299     * useful in a ValueAnimator object because there is no way for the object to determine the
300     * starting value for the animation (unlike ObjectAnimator, which can derive that value
301     * from the target object and property being animated). Therefore, there should typically
302     * be two or more values.
303     *
304     * <p>Since ValueAnimator does not know how to animate between arbitrary Objects, this
305     * factory method also takes a TypeEvaluator object that the ValueAnimator will use
306     * to perform that interpolation.
307     *
308     * @param evaluator A TypeEvaluator that will be called on each animation frame to
309     * provide the ncessry interpolation between the Object values to derive the animated
310     * value.
311     * @param values A set of values that the animation will animate between over time.
312     * @return A ValueAnimator object that is set up to animate between the given values.
313     */
314    public static ValueAnimator ofObject(TypeEvaluator evaluator, Object... values) {
315        ValueAnimator anim = new ValueAnimator();
316        anim.setObjectValues(values);
317        anim.setEvaluator(evaluator);
318        return anim;
319    }
320
321    /**
322     * Sets int values that will be animated between. A single
323     * value implies that that value is the one being animated to. However, this is not typically
324     * useful in a ValueAnimator object because there is no way for the object to determine the
325     * starting value for the animation (unlike ObjectAnimator, which can derive that value
326     * from the target object and property being animated). Therefore, there should typically
327     * be two or more values.
328     *
329     * <p>If there are already multiple sets of values defined for this ValueAnimator via more
330     * than one PropertyValuesHolder object, this method will set the values for the first
331     * of those objects.</p>
332     *
333     * @param values A set of values that the animation will animate between over time.
334     */
335    public void setIntValues(int... values) {
336        if (values == null || values.length == 0) {
337            return;
338        }
339        if (mValues == null || mValues.length == 0) {
340            setValues(new PropertyValuesHolder[]{PropertyValuesHolder.ofInt("", values)});
341        } else {
342            PropertyValuesHolder valuesHolder = mValues[0];
343            valuesHolder.setIntValues(values);
344        }
345        // New property/values/target should cause re-initialization prior to starting
346        mInitialized = false;
347    }
348
349    /**
350     * Sets float values that will be animated between. A single
351     * value implies that that value is the one being animated to. However, this is not typically
352     * useful in a ValueAnimator object because there is no way for the object to determine the
353     * starting value for the animation (unlike ObjectAnimator, which can derive that value
354     * from the target object and property being animated). Therefore, there should typically
355     * be two or more values.
356     *
357     * <p>If there are already multiple sets of values defined for this ValueAnimator via more
358     * than one PropertyValuesHolder object, this method will set the values for the first
359     * of those objects.</p>
360     *
361     * @param values A set of values that the animation will animate between over time.
362     */
363    public void setFloatValues(float... values) {
364        if (values == null || values.length == 0) {
365            return;
366        }
367        if (mValues == null || mValues.length == 0) {
368            setValues(new PropertyValuesHolder[]{PropertyValuesHolder.ofFloat("", values)});
369        } else {
370            PropertyValuesHolder valuesHolder = mValues[0];
371            valuesHolder.setFloatValues(values);
372        }
373        // New property/values/target should cause re-initialization prior to starting
374        mInitialized = false;
375    }
376
377    /**
378     * Sets the values to animate between for this animation. A single
379     * value implies that that value is the one being animated to. However, this is not typically
380     * useful in a ValueAnimator object because there is no way for the object to determine the
381     * starting value for the animation (unlike ObjectAnimator, which can derive that value
382     * from the target object and property being animated). Therefore, there should typically
383     * be two or more values.
384     *
385     * <p>If there are already multiple sets of values defined for this ValueAnimator via more
386     * than one PropertyValuesHolder object, this method will set the values for the first
387     * of those objects.</p>
388     *
389     * <p>There should be a TypeEvaluator set on the ValueAnimator that knows how to interpolate
390     * between these value objects. ValueAnimator only knows how to interpolate between the
391     * primitive types specified in the other setValues() methods.</p>
392     *
393     * @param values The set of values to animate between.
394     */
395    public void setObjectValues(Object... values) {
396        if (values == null || values.length == 0) {
397            return;
398        }
399        if (mValues == null || mValues.length == 0) {
400            setValues(new PropertyValuesHolder[]{PropertyValuesHolder.ofObject("",
401                    (TypeEvaluator)null, values)});
402        } else {
403            PropertyValuesHolder valuesHolder = mValues[0];
404            valuesHolder.setObjectValues(values);
405        }
406        // New property/values/target should cause re-initialization prior to starting
407        mInitialized = false;
408    }
409
410    /**
411     * Sets the values, per property, being animated between. This function is called internally
412     * by the constructors of ValueAnimator that take a list of values. But a ValueAnimator can
413     * be constructed without values and this method can be called to set the values manually
414     * instead.
415     *
416     * @param values The set of values, per property, being animated between.
417     */
418    public void setValues(PropertyValuesHolder... values) {
419        int numValues = values.length;
420        mValues = values;
421        mValuesMap = new HashMap<String, PropertyValuesHolder>(numValues);
422        for (int i = 0; i < numValues; ++i) {
423            PropertyValuesHolder valuesHolder = (PropertyValuesHolder) values[i];
424            mValuesMap.put(valuesHolder.getPropertyName(), valuesHolder);
425        }
426        // New property/values/target should cause re-initialization prior to starting
427        mInitialized = false;
428    }
429
430    /**
431     * Returns the values that this ValueAnimator animates between. These values are stored in
432     * PropertyValuesHolder objects, even if the ValueAnimator was created with a simple list
433     * of value objects instead.
434     *
435     * @return PropertyValuesHolder[] An array of PropertyValuesHolder objects which hold the
436     * values, per property, that define the animation.
437     */
438    public PropertyValuesHolder[] getValues() {
439        return mValues;
440    }
441
442    /**
443     * This function is called immediately before processing the first animation
444     * frame of an animation. If there is a nonzero <code>startDelay</code>, the
445     * function is called after that delay ends.
446     * It takes care of the final initialization steps for the
447     * animation.
448     *
449     *  <p>Overrides of this method should call the superclass method to ensure
450     *  that internal mechanisms for the animation are set up correctly.</p>
451     */
452    void initAnimation() {
453        if (!mInitialized) {
454            int numValues = mValues.length;
455            for (int i = 0; i < numValues; ++i) {
456                mValues[i].init();
457            }
458            mInitialized = true;
459        }
460    }
461
462
463    /**
464     * Sets the length of the animation. The default duration is 300 milliseconds.
465     *
466     * @param duration The length of the animation, in milliseconds. This value cannot
467     * be negative.
468     * @return ValueAnimator The object called with setDuration(). This return
469     * value makes it easier to compose statements together that construct and then set the
470     * duration, as in <code>ValueAnimator.ofInt(0, 10).setDuration(500).start()</code>.
471     */
472    public ValueAnimator setDuration(long duration) {
473        if (duration < 0) {
474            throw new IllegalArgumentException("Animators cannot have negative duration: " +
475                    duration);
476        }
477        mUnscaledDuration = duration;
478        mDuration = (long)(duration * sDurationScale);
479        return this;
480    }
481
482    /**
483     * Gets the length of the animation. The default duration is 300 milliseconds.
484     *
485     * @return The length of the animation, in milliseconds.
486     */
487    public long getDuration() {
488        return mUnscaledDuration;
489    }
490
491    /**
492     * Sets the position of the animation to the specified point in time. This time should
493     * be between 0 and the total duration of the animation, including any repetition. If
494     * the animation has not yet been started, then it will not advance forward after it is
495     * set to this time; it will simply set the time to this value and perform any appropriate
496     * actions based on that time. If the animation is already running, then setCurrentPlayTime()
497     * will set the current playing time to this value and continue playing from that point.
498     *
499     * @param playTime The time, in milliseconds, to which the animation is advanced or rewound.
500     */
501    public void setCurrentPlayTime(long playTime) {
502        initAnimation();
503        long currentTime = AnimationUtils.currentAnimationTimeMillis();
504        if (mPlayingState != RUNNING) {
505            mSeekTime = playTime;
506            mPlayingState = SEEKED;
507        }
508        mStartTime = currentTime - playTime;
509        doAnimationFrame(currentTime);
510    }
511
512    /**
513     * Gets the current position of the animation in time, which is equal to the current
514     * time minus the time that the animation started. An animation that is not yet started will
515     * return a value of zero.
516     *
517     * @return The current position in time of the animation.
518     */
519    public long getCurrentPlayTime() {
520        if (!mInitialized || mPlayingState == STOPPED) {
521            return 0;
522        }
523        return AnimationUtils.currentAnimationTimeMillis() - mStartTime;
524    }
525
526    /**
527     * This custom, static handler handles the timing pulse that is shared by
528     * all active animations. This approach ensures that the setting of animation
529     * values will happen on the UI thread and that all animations will share
530     * the same times for calculating their values, which makes synchronizing
531     * animations possible.
532     *
533     * The handler uses the Choreographer for executing periodic callbacks.
534     */
535    private static class AnimationHandler implements Runnable {
536        // The per-thread list of all active animations
537        private final ArrayList<ValueAnimator> mAnimations = new ArrayList<ValueAnimator>();
538
539        // Used in doAnimationFrame() to avoid concurrent modifications of mAnimations
540        private final ArrayList<ValueAnimator> mTmpAnimations = new ArrayList<ValueAnimator>();
541
542        // The per-thread set of animations to be started on the next animation frame
543        private final ArrayList<ValueAnimator> mPendingAnimations = new ArrayList<ValueAnimator>();
544
545        /**
546         * Internal per-thread collections used to avoid set collisions as animations start and end
547         * while being processed.
548         */
549        private final ArrayList<ValueAnimator> mDelayedAnims = new ArrayList<ValueAnimator>();
550        private final ArrayList<ValueAnimator> mEndingAnims = new ArrayList<ValueAnimator>();
551        private final ArrayList<ValueAnimator> mReadyAnims = new ArrayList<ValueAnimator>();
552
553        private final Choreographer mChoreographer;
554        private boolean mAnimationScheduled;
555
556        private AnimationHandler() {
557            mChoreographer = Choreographer.getInstance();
558        }
559
560        /**
561         * Start animating on the next frame.
562         */
563        public void start() {
564            scheduleAnimation();
565        }
566
567        private void doAnimationFrame(long frameTime) {
568            // mPendingAnimations holds any animations that have requested to be started
569            // We're going to clear mPendingAnimations, but starting animation may
570            // cause more to be added to the pending list (for example, if one animation
571            // starting triggers another starting). So we loop until mPendingAnimations
572            // is empty.
573            while (mPendingAnimations.size() > 0) {
574                ArrayList<ValueAnimator> pendingCopy =
575                        (ArrayList<ValueAnimator>) mPendingAnimations.clone();
576                mPendingAnimations.clear();
577                int count = pendingCopy.size();
578                for (int i = 0; i < count; ++i) {
579                    ValueAnimator anim = pendingCopy.get(i);
580                    // If the animation has a startDelay, place it on the delayed list
581                    if (anim.mStartDelay == 0) {
582                        anim.startAnimation(this);
583                    } else {
584                        mDelayedAnims.add(anim);
585                    }
586                }
587            }
588            // Next, process animations currently sitting on the delayed queue, adding
589            // them to the active animations if they are ready
590            int numDelayedAnims = mDelayedAnims.size();
591            for (int i = 0; i < numDelayedAnims; ++i) {
592                ValueAnimator anim = mDelayedAnims.get(i);
593                if (anim.delayedAnimationFrame(frameTime)) {
594                    mReadyAnims.add(anim);
595                }
596            }
597            int numReadyAnims = mReadyAnims.size();
598            if (numReadyAnims > 0) {
599                for (int i = 0; i < numReadyAnims; ++i) {
600                    ValueAnimator anim = mReadyAnims.get(i);
601                    anim.startAnimation(this);
602                    anim.mRunning = true;
603                    mDelayedAnims.remove(anim);
604                }
605                mReadyAnims.clear();
606            }
607
608            // Now process all active animations. The return value from animationFrame()
609            // tells the handler whether it should now be ended
610            int numAnims = mAnimations.size();
611            for (int i = 0; i < numAnims; ++i) {
612                mTmpAnimations.add(mAnimations.get(i));
613            }
614            for (int i = 0; i < numAnims; ++i) {
615                ValueAnimator anim = mTmpAnimations.get(i);
616                if (mAnimations.contains(anim) && anim.doAnimationFrame(frameTime)) {
617                    mEndingAnims.add(anim);
618                }
619            }
620            mTmpAnimations.clear();
621            if (mEndingAnims.size() > 0) {
622                for (int i = 0; i < mEndingAnims.size(); ++i) {
623                    mEndingAnims.get(i).endAnimation(this);
624                }
625                mEndingAnims.clear();
626            }
627
628            // If there are still active or delayed animations, schedule a future call to
629            // onAnimate to process the next frame of the animations.
630            if (!mAnimations.isEmpty() || !mDelayedAnims.isEmpty()) {
631                scheduleAnimation();
632            }
633        }
634
635        // Called by the Choreographer.
636        @Override
637        public void run() {
638            mAnimationScheduled = false;
639            doAnimationFrame(mChoreographer.getFrameTime());
640        }
641
642        private void scheduleAnimation() {
643            if (!mAnimationScheduled) {
644                mChoreographer.postCallback(Choreographer.CALLBACK_ANIMATION, this, null);
645                mAnimationScheduled = true;
646            }
647        }
648    }
649
650    /**
651     * The amount of time, in milliseconds, to delay starting the animation after
652     * {@link #start()} is called.
653     *
654     * @return the number of milliseconds to delay running the animation
655     */
656    public long getStartDelay() {
657        return mUnscaledStartDelay;
658    }
659
660    /**
661     * The amount of time, in milliseconds, to delay starting the animation after
662     * {@link #start()} is called.
663
664     * @param startDelay The amount of the delay, in milliseconds
665     */
666    public void setStartDelay(long startDelay) {
667        this.mStartDelay = (long)(startDelay * sDurationScale);
668        mUnscaledStartDelay = startDelay;
669    }
670
671    /**
672     * The amount of time, in milliseconds, between each frame of the animation. This is a
673     * requested time that the animation will attempt to honor, but the actual delay between
674     * frames may be different, depending on system load and capabilities. This is a static
675     * function because the same delay will be applied to all animations, since they are all
676     * run off of a single timing loop.
677     *
678     * The frame delay may be ignored when the animation system uses an external timing
679     * source, such as the display refresh rate (vsync), to govern animations.
680     *
681     * @return the requested time between frames, in milliseconds
682     */
683    public static long getFrameDelay() {
684        return Choreographer.getFrameDelay();
685    }
686
687    /**
688     * The amount of time, in milliseconds, between each frame of the animation. This is a
689     * requested time that the animation will attempt to honor, but the actual delay between
690     * frames may be different, depending on system load and capabilities. This is a static
691     * function because the same delay will be applied to all animations, since they are all
692     * run off of a single timing loop.
693     *
694     * The frame delay may be ignored when the animation system uses an external timing
695     * source, such as the display refresh rate (vsync), to govern animations.
696     *
697     * @param frameDelay the requested time between frames, in milliseconds
698     */
699    public static void setFrameDelay(long frameDelay) {
700        Choreographer.setFrameDelay(frameDelay);
701    }
702
703    /**
704     * The most recent value calculated by this <code>ValueAnimator</code> when there is just one
705     * property being animated. This value is only sensible while the animation is running. The main
706     * purpose for this read-only property is to retrieve the value from the <code>ValueAnimator</code>
707     * during a call to {@link AnimatorUpdateListener#onAnimationUpdate(ValueAnimator)}, which
708     * is called during each animation frame, immediately after the value is calculated.
709     *
710     * @return animatedValue The value most recently calculated by this <code>ValueAnimator</code> for
711     * the single property being animated. If there are several properties being animated
712     * (specified by several PropertyValuesHolder objects in the constructor), this function
713     * returns the animated value for the first of those objects.
714     */
715    public Object getAnimatedValue() {
716        if (mValues != null && mValues.length > 0) {
717            return mValues[0].getAnimatedValue();
718        }
719        // Shouldn't get here; should always have values unless ValueAnimator was set up wrong
720        return null;
721    }
722
723    /**
724     * The most recent value calculated by this <code>ValueAnimator</code> for <code>propertyName</code>.
725     * The main purpose for this read-only property is to retrieve the value from the
726     * <code>ValueAnimator</code> during a call to
727     * {@link AnimatorUpdateListener#onAnimationUpdate(ValueAnimator)}, which
728     * is called during each animation frame, immediately after the value is calculated.
729     *
730     * @return animatedValue The value most recently calculated for the named property
731     * by this <code>ValueAnimator</code>.
732     */
733    public Object getAnimatedValue(String propertyName) {
734        PropertyValuesHolder valuesHolder = mValuesMap.get(propertyName);
735        if (valuesHolder != null) {
736            return valuesHolder.getAnimatedValue();
737        } else {
738            // At least avoid crashing if called with bogus propertyName
739            return null;
740        }
741    }
742
743    /**
744     * Sets how many times the animation should be repeated. If the repeat
745     * count is 0, the animation is never repeated. If the repeat count is
746     * greater than 0 or {@link #INFINITE}, the repeat mode will be taken
747     * into account. The repeat count is 0 by default.
748     *
749     * @param value the number of times the animation should be repeated
750     */
751    public void setRepeatCount(int value) {
752        mRepeatCount = value;
753    }
754    /**
755     * Defines how many times the animation should repeat. The default value
756     * is 0.
757     *
758     * @return the number of times the animation should repeat, or {@link #INFINITE}
759     */
760    public int getRepeatCount() {
761        return mRepeatCount;
762    }
763
764    /**
765     * Defines what this animation should do when it reaches the end. This
766     * setting is applied only when the repeat count is either greater than
767     * 0 or {@link #INFINITE}. Defaults to {@link #RESTART}.
768     *
769     * @param value {@link #RESTART} or {@link #REVERSE}
770     */
771    public void setRepeatMode(int value) {
772        mRepeatMode = value;
773    }
774
775    /**
776     * Defines what this animation should do when it reaches the end.
777     *
778     * @return either one of {@link #REVERSE} or {@link #RESTART}
779     */
780    public int getRepeatMode() {
781        return mRepeatMode;
782    }
783
784    /**
785     * Adds a listener to the set of listeners that are sent update events through the life of
786     * an animation. This method is called on all listeners for every frame of the animation,
787     * after the values for the animation have been calculated.
788     *
789     * @param listener the listener to be added to the current set of listeners for this animation.
790     */
791    public void addUpdateListener(AnimatorUpdateListener listener) {
792        if (mUpdateListeners == null) {
793            mUpdateListeners = new ArrayList<AnimatorUpdateListener>();
794        }
795        mUpdateListeners.add(listener);
796    }
797
798    /**
799     * Removes all listeners from the set listening to frame updates for this animation.
800     */
801    public void removeAllUpdateListeners() {
802        if (mUpdateListeners == null) {
803            return;
804        }
805        mUpdateListeners.clear();
806        mUpdateListeners = null;
807    }
808
809    /**
810     * Removes a listener from the set listening to frame updates for this animation.
811     *
812     * @param listener the listener to be removed from the current set of update listeners
813     * for this animation.
814     */
815    public void removeUpdateListener(AnimatorUpdateListener listener) {
816        if (mUpdateListeners == null) {
817            return;
818        }
819        mUpdateListeners.remove(listener);
820        if (mUpdateListeners.size() == 0) {
821            mUpdateListeners = null;
822        }
823    }
824
825
826    /**
827     * The time interpolator used in calculating the elapsed fraction of this animation. The
828     * interpolator determines whether the animation runs with linear or non-linear motion,
829     * such as acceleration and deceleration. The default value is
830     * {@link android.view.animation.AccelerateDecelerateInterpolator}
831     *
832     * @param value the interpolator to be used by this animation. A value of <code>null</code>
833     * will result in linear interpolation.
834     */
835    @Override
836    public void setInterpolator(TimeInterpolator value) {
837        if (value != null) {
838            mInterpolator = value;
839        } else {
840            mInterpolator = new LinearInterpolator();
841        }
842    }
843
844    /**
845     * Returns the timing interpolator that this ValueAnimator uses.
846     *
847     * @return The timing interpolator for this ValueAnimator.
848     */
849    public TimeInterpolator getInterpolator() {
850        return mInterpolator;
851    }
852
853    /**
854     * The type evaluator to be used when calculating the animated values of this animation.
855     * The system will automatically assign a float or int evaluator based on the type
856     * of <code>startValue</code> and <code>endValue</code> in the constructor. But if these values
857     * are not one of these primitive types, or if different evaluation is desired (such as is
858     * necessary with int values that represent colors), a custom evaluator needs to be assigned.
859     * For example, when running an animation on color values, the {@link ArgbEvaluator}
860     * should be used to get correct RGB color interpolation.
861     *
862     * <p>If this ValueAnimator has only one set of values being animated between, this evaluator
863     * will be used for that set. If there are several sets of values being animated, which is
864     * the case if PropertyValuesHOlder objects were set on the ValueAnimator, then the evaluator
865     * is assigned just to the first PropertyValuesHolder object.</p>
866     *
867     * @param value the evaluator to be used this animation
868     */
869    public void setEvaluator(TypeEvaluator value) {
870        if (value != null && mValues != null && mValues.length > 0) {
871            mValues[0].setEvaluator(value);
872        }
873    }
874
875    private void notifyStartListeners() {
876        if (mListeners != null && !mStartListenersCalled) {
877            ArrayList<AnimatorListener> tmpListeners =
878                    (ArrayList<AnimatorListener>) mListeners.clone();
879            int numListeners = tmpListeners.size();
880            for (int i = 0; i < numListeners; ++i) {
881                tmpListeners.get(i).onAnimationStart(this);
882            }
883        }
884        mStartListenersCalled = true;
885    }
886
887    /**
888     * Start the animation playing. This version of start() takes a boolean flag that indicates
889     * whether the animation should play in reverse. The flag is usually false, but may be set
890     * to true if called from the reverse() method.
891     *
892     * <p>The animation started by calling this method will be run on the thread that called
893     * this method. This thread should have a Looper on it (a runtime exception will be thrown if
894     * this is not the case). Also, if the animation will animate
895     * properties of objects in the view hierarchy, then the calling thread should be the UI
896     * thread for that view hierarchy.</p>
897     *
898     * @param playBackwards Whether the ValueAnimator should start playing in reverse.
899     */
900    private void start(boolean playBackwards) {
901        if (Looper.myLooper() == null) {
902            throw new AndroidRuntimeException("Animators may only be run on Looper threads");
903        }
904        mPlayingBackwards = playBackwards;
905        mCurrentIteration = 0;
906        mPlayingState = STOPPED;
907        mStarted = true;
908        mStartedDelay = false;
909        AnimationHandler animationHandler = getOrCreateAnimationHandler();
910        animationHandler.mPendingAnimations.add(this);
911        if (mStartDelay == 0) {
912            // This sets the initial value of the animation, prior to actually starting it running
913            setCurrentPlayTime(0);
914            mPlayingState = STOPPED;
915            mRunning = true;
916            notifyStartListeners();
917        }
918        animationHandler.start();
919    }
920
921    @Override
922    public void start() {
923        start(false);
924    }
925
926    @Override
927    public void cancel() {
928        // Only cancel if the animation is actually running or has been started and is about
929        // to run
930        AnimationHandler handler = getOrCreateAnimationHandler();
931        if (mPlayingState != STOPPED
932                || handler.mPendingAnimations.contains(this)
933                || handler.mDelayedAnims.contains(this)) {
934            // Only notify listeners if the animator has actually started
935            if ((mStarted || mRunning) && mListeners != null) {
936                if (!mRunning) {
937                    // If it's not yet running, then start listeners weren't called. Call them now.
938                    notifyStartListeners();
939                }
940                ArrayList<AnimatorListener> tmpListeners =
941                        (ArrayList<AnimatorListener>) mListeners.clone();
942                for (AnimatorListener listener : tmpListeners) {
943                    listener.onAnimationCancel(this);
944                }
945            }
946            endAnimation(handler);
947        }
948    }
949
950    @Override
951    public void end() {
952        AnimationHandler handler = getOrCreateAnimationHandler();
953        if (!handler.mAnimations.contains(this) && !handler.mPendingAnimations.contains(this)) {
954            // Special case if the animation has not yet started; get it ready for ending
955            mStartedDelay = false;
956            startAnimation(handler);
957            mStarted = true;
958        } else if (!mInitialized) {
959            initAnimation();
960        }
961        animateValue(mPlayingBackwards ? 0f : 1f);
962        endAnimation(handler);
963    }
964
965    @Override
966    public boolean isRunning() {
967        return (mPlayingState == RUNNING || mRunning);
968    }
969
970    @Override
971    public boolean isStarted() {
972        return mStarted;
973    }
974
975    /**
976     * Plays the ValueAnimator in reverse. If the animation is already running,
977     * it will stop itself and play backwards from the point reached when reverse was called.
978     * If the animation is not currently running, then it will start from the end and
979     * play backwards. This behavior is only set for the current animation; future playing
980     * of the animation will use the default behavior of playing forward.
981     */
982    public void reverse() {
983        mPlayingBackwards = !mPlayingBackwards;
984        if (mPlayingState == RUNNING) {
985            long currentTime = AnimationUtils.currentAnimationTimeMillis();
986            long currentPlayTime = currentTime - mStartTime;
987            long timeLeft = mDuration - currentPlayTime;
988            mStartTime = currentTime - timeLeft;
989        } else {
990            start(true);
991        }
992    }
993
994    /**
995     * Called internally to end an animation by removing it from the animations list. Must be
996     * called on the UI thread.
997     */
998    private void endAnimation(AnimationHandler handler) {
999        handler.mAnimations.remove(this);
1000        handler.mPendingAnimations.remove(this);
1001        handler.mDelayedAnims.remove(this);
1002        mPlayingState = STOPPED;
1003        if ((mStarted || mRunning) && mListeners != null) {
1004            if (!mRunning) {
1005                // If it's not yet running, then start listeners weren't called. Call them now.
1006                notifyStartListeners();
1007             }
1008            ArrayList<AnimatorListener> tmpListeners =
1009                    (ArrayList<AnimatorListener>) mListeners.clone();
1010            int numListeners = tmpListeners.size();
1011            for (int i = 0; i < numListeners; ++i) {
1012                tmpListeners.get(i).onAnimationEnd(this);
1013            }
1014        }
1015        mRunning = false;
1016        mStarted = false;
1017        mStartListenersCalled = false;
1018    }
1019
1020    /**
1021     * Called internally to start an animation by adding it to the active animations list. Must be
1022     * called on the UI thread.
1023     */
1024    private void startAnimation(AnimationHandler handler) {
1025        initAnimation();
1026        handler.mAnimations.add(this);
1027        if (mStartDelay > 0 && mListeners != null) {
1028            // Listeners were already notified in start() if startDelay is 0; this is
1029            // just for delayed animations
1030            notifyStartListeners();
1031        }
1032    }
1033
1034    /**
1035     * Internal function called to process an animation frame on an animation that is currently
1036     * sleeping through its <code>startDelay</code> phase. The return value indicates whether it
1037     * should be woken up and put on the active animations queue.
1038     *
1039     * @param currentTime The current animation time, used to calculate whether the animation
1040     * has exceeded its <code>startDelay</code> and should be started.
1041     * @return True if the animation's <code>startDelay</code> has been exceeded and the animation
1042     * should be added to the set of active animations.
1043     */
1044    private boolean delayedAnimationFrame(long currentTime) {
1045        if (!mStartedDelay) {
1046            mStartedDelay = true;
1047            mDelayStartTime = currentTime;
1048        } else {
1049            long deltaTime = currentTime - mDelayStartTime;
1050            if (deltaTime > mStartDelay) {
1051                // startDelay ended - start the anim and record the
1052                // mStartTime appropriately
1053                mStartTime = currentTime - (deltaTime - mStartDelay);
1054                mPlayingState = RUNNING;
1055                return true;
1056            }
1057        }
1058        return false;
1059    }
1060
1061    /**
1062     * This internal function processes a single animation frame for a given animation. The
1063     * currentTime parameter is the timing pulse sent by the handler, used to calculate the
1064     * elapsed duration, and therefore
1065     * the elapsed fraction, of the animation. The return value indicates whether the animation
1066     * should be ended (which happens when the elapsed time of the animation exceeds the
1067     * animation's duration, including the repeatCount).
1068     *
1069     * @param currentTime The current time, as tracked by the static timing handler
1070     * @return true if the animation's duration, including any repetitions due to
1071     * <code>repeatCount</code> has been exceeded and the animation should be ended.
1072     */
1073    boolean animationFrame(long currentTime) {
1074        boolean done = false;
1075        switch (mPlayingState) {
1076        case RUNNING:
1077        case SEEKED:
1078            float fraction = mDuration > 0 ? (float)(currentTime - mStartTime) / mDuration : 1f;
1079            if (fraction >= 1f) {
1080                if (mCurrentIteration < mRepeatCount || mRepeatCount == INFINITE) {
1081                    // Time to repeat
1082                    if (mListeners != null) {
1083                        int numListeners = mListeners.size();
1084                        for (int i = 0; i < numListeners; ++i) {
1085                            mListeners.get(i).onAnimationRepeat(this);
1086                        }
1087                    }
1088                    if (mRepeatMode == REVERSE) {
1089                        mPlayingBackwards = mPlayingBackwards ? false : true;
1090                    }
1091                    mCurrentIteration += (int)fraction;
1092                    fraction = fraction % 1f;
1093                    mStartTime += mDuration;
1094                } else {
1095                    done = true;
1096                    fraction = Math.min(fraction, 1.0f);
1097                }
1098            }
1099            if (mPlayingBackwards) {
1100                fraction = 1f - fraction;
1101            }
1102            animateValue(fraction);
1103            break;
1104        }
1105
1106        return done;
1107    }
1108
1109    /**
1110     * Processes a frame of the animation, adjusting the start time if needed.
1111     *
1112     * @param frameTime The frame time.
1113     * @return true if the animation has ended.
1114     */
1115    final boolean doAnimationFrame(long frameTime) {
1116        if (mPlayingState == STOPPED) {
1117            mPlayingState = RUNNING;
1118            if (mSeekTime < 0) {
1119                mStartTime = frameTime;
1120            } else {
1121                mStartTime = frameTime - mSeekTime;
1122                // Now that we're playing, reset the seek time
1123                mSeekTime = -1;
1124            }
1125        }
1126        // The frame time might be before the start time during the first frame of
1127        // an animation.  The "current time" must always be on or after the start
1128        // time to avoid animating frames at negative time intervals.  In practice, this
1129        // is very rare and only happens when seeking backwards.
1130        final long currentTime = Math.max(frameTime, mStartTime);
1131        return animationFrame(currentTime);
1132    }
1133
1134    /**
1135     * Returns the current animation fraction, which is the elapsed/interpolated fraction used in
1136     * the most recent frame update on the animation.
1137     *
1138     * @return Elapsed/interpolated fraction of the animation.
1139     */
1140    public float getAnimatedFraction() {
1141        return mCurrentFraction;
1142    }
1143
1144    /**
1145     * This method is called with the elapsed fraction of the animation during every
1146     * animation frame. This function turns the elapsed fraction into an interpolated fraction
1147     * and then into an animated value (from the evaluator. The function is called mostly during
1148     * animation updates, but it is also called when the <code>end()</code>
1149     * function is called, to set the final value on the property.
1150     *
1151     * <p>Overrides of this method must call the superclass to perform the calculation
1152     * of the animated value.</p>
1153     *
1154     * @param fraction The elapsed fraction of the animation.
1155     */
1156    void animateValue(float fraction) {
1157        fraction = mInterpolator.getInterpolation(fraction);
1158        mCurrentFraction = fraction;
1159        int numValues = mValues.length;
1160        for (int i = 0; i < numValues; ++i) {
1161            mValues[i].calculateValue(fraction);
1162        }
1163        if (mUpdateListeners != null) {
1164            int numListeners = mUpdateListeners.size();
1165            for (int i = 0; i < numListeners; ++i) {
1166                mUpdateListeners.get(i).onAnimationUpdate(this);
1167            }
1168        }
1169    }
1170
1171    @Override
1172    public ValueAnimator clone() {
1173        final ValueAnimator anim = (ValueAnimator) super.clone();
1174        if (mUpdateListeners != null) {
1175            ArrayList<AnimatorUpdateListener> oldListeners = mUpdateListeners;
1176            anim.mUpdateListeners = new ArrayList<AnimatorUpdateListener>();
1177            int numListeners = oldListeners.size();
1178            for (int i = 0; i < numListeners; ++i) {
1179                anim.mUpdateListeners.add(oldListeners.get(i));
1180            }
1181        }
1182        anim.mSeekTime = -1;
1183        anim.mPlayingBackwards = false;
1184        anim.mCurrentIteration = 0;
1185        anim.mInitialized = false;
1186        anim.mPlayingState = STOPPED;
1187        anim.mStartedDelay = false;
1188        PropertyValuesHolder[] oldValues = mValues;
1189        if (oldValues != null) {
1190            int numValues = oldValues.length;
1191            anim.mValues = new PropertyValuesHolder[numValues];
1192            anim.mValuesMap = new HashMap<String, PropertyValuesHolder>(numValues);
1193            for (int i = 0; i < numValues; ++i) {
1194                PropertyValuesHolder newValuesHolder = oldValues[i].clone();
1195                anim.mValues[i] = newValuesHolder;
1196                anim.mValuesMap.put(newValuesHolder.getPropertyName(), newValuesHolder);
1197            }
1198        }
1199        return anim;
1200    }
1201
1202    /**
1203     * Implementors of this interface can add themselves as update listeners
1204     * to an <code>ValueAnimator</code> instance to receive callbacks on every animation
1205     * frame, after the current frame's values have been calculated for that
1206     * <code>ValueAnimator</code>.
1207     */
1208    public static interface AnimatorUpdateListener {
1209        /**
1210         * <p>Notifies the occurrence of another frame of the animation.</p>
1211         *
1212         * @param animation The animation which was repeated.
1213         */
1214        void onAnimationUpdate(ValueAnimator animation);
1215
1216    }
1217
1218    /**
1219     * Return the number of animations currently running.
1220     *
1221     * Used by StrictMode internally to annotate violations.
1222     * May be called on arbitrary threads!
1223     *
1224     * @hide
1225     */
1226    public static int getCurrentAnimationsCount() {
1227        AnimationHandler handler = sAnimationHandler.get();
1228        return handler != null ? handler.mAnimations.size() : 0;
1229    }
1230
1231    /**
1232     * Clear all animations on this thread, without canceling or ending them.
1233     * This should be used with caution.
1234     *
1235     * @hide
1236     */
1237    public static void clearAllAnimations() {
1238        AnimationHandler handler = sAnimationHandler.get();
1239        if (handler != null) {
1240            handler.mAnimations.clear();
1241            handler.mPendingAnimations.clear();
1242            handler.mDelayedAnims.clear();
1243        }
1244    }
1245
1246    private AnimationHandler getOrCreateAnimationHandler() {
1247        AnimationHandler handler = sAnimationHandler.get();
1248        if (handler == null) {
1249            handler = new AnimationHandler();
1250            sAnimationHandler.set(handler);
1251        }
1252        return handler;
1253    }
1254
1255    @Override
1256    public String toString() {
1257        String returnVal = "ValueAnimator@" + Integer.toHexString(hashCode());
1258        if (mValues != null) {
1259            for (int i = 0; i < mValues.length; ++i) {
1260                returnVal += "\n    " + mValues[i].toString();
1261            }
1262        }
1263        return returnVal;
1264    }
1265}
1266