create changelog entry
[debian/openrocket] / android-libraries / ActionBarSherlock / src / com / actionbarsherlock / internal / nineoldandroids / animation / AnimatorSet.java
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.actionbarsherlock.internal.nineoldandroids.animation;
18
19 import java.util.ArrayList;
20 import java.util.Collection;
21 import java.util.HashMap;
22 import java.util.List;
23
24 import android.view.animation.Interpolator;
25
26 /**
27  * This class plays a set of {@link Animator} objects in the specified order. Animations
28  * can be set up to play together, in sequence, or after a specified delay.
29  *
30  * <p>There are two different approaches to adding animations to a <code>AnimatorSet</code>:
31  * either the {@link AnimatorSet#playTogether(Animator[]) playTogether()} or
32  * {@link AnimatorSet#playSequentially(Animator[]) playSequentially()} methods can be called to add
33  * a set of animations all at once, or the {@link AnimatorSet#play(Animator)} can be
34  * used in conjunction with methods in the {@link AnimatorSet.Builder Builder}
35  * class to add animations
36  * one by one.</p>
37  *
38  * <p>It is possible to set up a <code>AnimatorSet</code> with circular dependencies between
39  * its animations. For example, an animation a1 could be set up to start before animation a2, a2
40  * before a3, and a3 before a1. The results of this configuration are undefined, but will typically
41  * result in none of the affected animations being played. Because of this (and because
42  * circular dependencies do not make logical sense anyway), circular dependencies
43  * should be avoided, and the dependency flow of animations should only be in one direction.
44  */
45 @SuppressWarnings("unchecked")
46 public final class AnimatorSet extends Animator {
47
48     /**
49      * Internal variables
50      * NOTE: This object implements the clone() method, making a deep copy of any referenced
51      * objects. As other non-trivial fields are added to this class, make sure to add logic
52      * to clone() to make deep copies of them.
53      */
54
55     /**
56      * Tracks animations currently being played, so that we know what to
57      * cancel or end when cancel() or end() is called on this AnimatorSet
58      */
59     private ArrayList<Animator> mPlayingSet = new ArrayList<Animator>();
60
61     /**
62      * Contains all nodes, mapped to their respective Animators. When new
63      * dependency information is added for an Animator, we want to add it
64      * to a single node representing that Animator, not create a new Node
65      * if one already exists.
66      */
67     private HashMap<Animator, Node> mNodeMap = new HashMap<Animator, Node>();
68
69     /**
70      * Set of all nodes created for this AnimatorSet. This list is used upon
71      * starting the set, and the nodes are placed in sorted order into the
72      * sortedNodes collection.
73      */
74     private ArrayList<Node> mNodes = new ArrayList<Node>();
75
76     /**
77      * The sorted list of nodes. This is the order in which the animations will
78      * be played. The details about when exactly they will be played depend
79      * on the dependency relationships of the nodes.
80      */
81     private ArrayList<Node> mSortedNodes = new ArrayList<Node>();
82
83     /**
84      * Flag indicating whether the nodes should be sorted prior to playing. This
85      * flag allows us to cache the previous sorted nodes so that if the sequence
86      * is replayed with no changes, it does not have to re-sort the nodes again.
87      */
88     private boolean mNeedsSort = true;
89
90     private AnimatorSetListener mSetListener = null;
91
92     /**
93      * Flag indicating that the AnimatorSet has been manually
94      * terminated (by calling cancel() or end()).
95      * This flag is used to avoid starting other animations when currently-playing
96      * child animations of this AnimatorSet end. It also determines whether cancel/end
97      * notifications are sent out via the normal AnimatorSetListener mechanism.
98      */
99     boolean mTerminated = false;
100
101     /**
102      * Indicates whether an AnimatorSet has been start()'d, whether or
103      * not there is a nonzero startDelay.
104      */
105     private boolean mStarted = false;
106
107     // The amount of time in ms to delay starting the animation after start() is called
108     private long mStartDelay = 0;
109
110     // Animator used for a nonzero startDelay
111     private ValueAnimator mDelayAnim = null;
112
113
114     // How long the child animations should last in ms. The default value is negative, which
115     // simply means that there is no duration set on the AnimatorSet. When a real duration is
116     // set, it is passed along to the child animations.
117     private long mDuration = -1;
118
119
120     /**
121      * Sets up this AnimatorSet to play all of the supplied animations at the same time.
122      *
123      * @param items The animations that will be started simultaneously.
124      */
125     public void playTogether(Animator... items) {
126         if (items != null) {
127             mNeedsSort = true;
128             Builder builder = play(items[0]);
129             for (int i = 1; i < items.length; ++i) {
130                 builder.with(items[i]);
131             }
132         }
133     }
134
135     /**
136      * Sets up this AnimatorSet to play all of the supplied animations at the same time.
137      *
138      * @param items The animations that will be started simultaneously.
139      */
140     public void playTogether(Collection<Animator> items) {
141         if (items != null && items.size() > 0) {
142             mNeedsSort = true;
143             Builder builder = null;
144             for (Animator anim : items) {
145                 if (builder == null) {
146                     builder = play(anim);
147                 } else {
148                     builder.with(anim);
149                 }
150             }
151         }
152     }
153
154     /**
155      * Sets up this AnimatorSet to play each of the supplied animations when the
156      * previous animation ends.
157      *
158      * @param items The animations that will be started one after another.
159      */
160     public void playSequentially(Animator... items) {
161         if (items != null) {
162             mNeedsSort = true;
163             if (items.length == 1) {
164                 play(items[0]);
165             } else {
166                 for (int i = 0; i < items.length - 1; ++i) {
167                     play(items[i]).before(items[i+1]);
168                 }
169             }
170         }
171     }
172
173     /**
174      * Sets up this AnimatorSet to play each of the supplied animations when the
175      * previous animation ends.
176      *
177      * @param items The animations that will be started one after another.
178      */
179     public void playSequentially(List<Animator> items) {
180         if (items != null && items.size() > 0) {
181             mNeedsSort = true;
182             if (items.size() == 1) {
183                 play(items.get(0));
184             } else {
185                 for (int i = 0; i < items.size() - 1; ++i) {
186                     play(items.get(i)).before(items.get(i+1));
187                 }
188             }
189         }
190     }
191
192     /**
193      * Returns the current list of child Animator objects controlled by this
194      * AnimatorSet. This is a copy of the internal list; modifications to the returned list
195      * will not affect the AnimatorSet, although changes to the underlying Animator objects
196      * will affect those objects being managed by the AnimatorSet.
197      *
198      * @return ArrayList<Animator> The list of child animations of this AnimatorSet.
199      */
200     public ArrayList<Animator> getChildAnimations() {
201         ArrayList<Animator> childList = new ArrayList<Animator>();
202         for (Node node : mNodes) {
203             childList.add(node.animation);
204         }
205         return childList;
206     }
207
208     /**
209      * Sets the target object for all current {@link #getChildAnimations() child animations}
210      * of this AnimatorSet that take targets ({@link ObjectAnimator} and
211      * AnimatorSet).
212      *
213      * @param target The object being animated
214      */
215     @Override
216     public void setTarget(Object target) {
217         for (Node node : mNodes) {
218             Animator animation = node.animation;
219             if (animation instanceof AnimatorSet) {
220                 ((AnimatorSet)animation).setTarget(target);
221             } else if (animation instanceof ObjectAnimator) {
222                 ((ObjectAnimator)animation).setTarget(target);
223             }
224         }
225     }
226
227     /**
228      * Sets the TimeInterpolator for all current {@link #getChildAnimations() child animations}
229      * of this AnimatorSet.
230      *
231      * @param interpolator the interpolator to be used by each child animation of this AnimatorSet
232      */
233     @Override
234     public void setInterpolator(/*Time*/Interpolator interpolator) {
235         for (Node node : mNodes) {
236             node.animation.setInterpolator(interpolator);
237         }
238     }
239
240     /**
241      * This method creates a <code>Builder</code> object, which is used to
242      * set up playing constraints. This initial <code>play()</code> method
243      * tells the <code>Builder</code> the animation that is the dependency for
244      * the succeeding commands to the <code>Builder</code>. For example,
245      * calling <code>play(a1).with(a2)</code> sets up the AnimatorSet to play
246      * <code>a1</code> and <code>a2</code> at the same time,
247      * <code>play(a1).before(a2)</code> sets up the AnimatorSet to play
248      * <code>a1</code> first, followed by <code>a2</code>, and
249      * <code>play(a1).after(a2)</code> sets up the AnimatorSet to play
250      * <code>a2</code> first, followed by <code>a1</code>.
251      *
252      * <p>Note that <code>play()</code> is the only way to tell the
253      * <code>Builder</code> the animation upon which the dependency is created,
254      * so successive calls to the various functions in <code>Builder</code>
255      * will all refer to the initial parameter supplied in <code>play()</code>
256      * as the dependency of the other animations. For example, calling
257      * <code>play(a1).before(a2).before(a3)</code> will play both <code>a2</code>
258      * and <code>a3</code> when a1 ends; it does not set up a dependency between
259      * <code>a2</code> and <code>a3</code>.</p>
260      *
261      * @param anim The animation that is the dependency used in later calls to the
262      * methods in the returned <code>Builder</code> object. A null parameter will result
263      * in a null <code>Builder</code> return value.
264      * @return Builder The object that constructs the AnimatorSet based on the dependencies
265      * outlined in the calls to <code>play</code> and the other methods in the
266      * <code>Builder</code object.
267      */
268     public Builder play(Animator anim) {
269         if (anim != null) {
270             mNeedsSort = true;
271             return new Builder(anim);
272         }
273         return null;
274     }
275
276     /**
277      * {@inheritDoc}
278      *
279      * <p>Note that canceling a <code>AnimatorSet</code> also cancels all of the animations that it
280      * is responsible for.</p>
281      */
282     @Override
283     public void cancel() {
284         mTerminated = true;
285         if (isStarted()) {
286             ArrayList<AnimatorListener> tmpListeners = null;
287             if (mListeners != null) {
288                 tmpListeners = (ArrayList<AnimatorListener>) mListeners.clone();
289                 for (AnimatorListener listener : tmpListeners) {
290                     listener.onAnimationCancel(this);
291                 }
292             }
293             if (mDelayAnim != null && mDelayAnim.isRunning()) {
294                 // If we're currently in the startDelay period, just cancel that animator and
295                 // send out the end event to all listeners
296                 mDelayAnim.cancel();
297             } else  if (mSortedNodes.size() > 0) {
298                 for (Node node : mSortedNodes) {
299                     node.animation.cancel();
300                 }
301             }
302             if (tmpListeners != null) {
303                 for (AnimatorListener listener : tmpListeners) {
304                     listener.onAnimationEnd(this);
305                 }
306             }
307             mStarted = false;
308         }
309     }
310
311     /**
312      * {@inheritDoc}
313      *
314      * <p>Note that ending a <code>AnimatorSet</code> also ends all of the animations that it is
315      * responsible for.</p>
316      */
317     @Override
318     public void end() {
319         mTerminated = true;
320         if (isStarted()) {
321             if (mSortedNodes.size() != mNodes.size()) {
322                 // hasn't been started yet - sort the nodes now, then end them
323                 sortNodes();
324                 for (Node node : mSortedNodes) {
325                     if (mSetListener == null) {
326                         mSetListener = new AnimatorSetListener(this);
327                     }
328                     node.animation.addListener(mSetListener);
329                 }
330             }
331             if (mDelayAnim != null) {
332                 mDelayAnim.cancel();
333             }
334             if (mSortedNodes.size() > 0) {
335                 for (Node node : mSortedNodes) {
336                     node.animation.end();
337                 }
338             }
339             if (mListeners != null) {
340                 ArrayList<AnimatorListener> tmpListeners =
341                         (ArrayList<AnimatorListener>) mListeners.clone();
342                 for (AnimatorListener listener : tmpListeners) {
343                     listener.onAnimationEnd(this);
344                 }
345             }
346             mStarted = false;
347         }
348     }
349
350     /**
351      * Returns true if any of the child animations of this AnimatorSet have been started and have
352      * not yet ended.
353      * @return Whether this AnimatorSet has been started and has not yet ended.
354      */
355     @Override
356     public boolean isRunning() {
357         for (Node node : mNodes) {
358             if (node.animation.isRunning()) {
359                 return true;
360             }
361         }
362         return false;
363     }
364
365     @Override
366     public boolean isStarted() {
367         return mStarted;
368     }
369
370     /**
371      * The amount of time, in milliseconds, to delay starting the animation after
372      * {@link #start()} is called.
373      *
374      * @return the number of milliseconds to delay running the animation
375      */
376     @Override
377     public long getStartDelay() {
378         return mStartDelay;
379     }
380
381     /**
382      * The amount of time, in milliseconds, to delay starting the animation after
383      * {@link #start()} is called.
384
385      * @param startDelay The amount of the delay, in milliseconds
386      */
387     @Override
388     public void setStartDelay(long startDelay) {
389         mStartDelay = startDelay;
390     }
391
392     /**
393      * Gets the length of each of the child animations of this AnimatorSet. This value may
394      * be less than 0, which indicates that no duration has been set on this AnimatorSet
395      * and each of the child animations will use their own duration.
396      *
397      * @return The length of the animation, in milliseconds, of each of the child
398      * animations of this AnimatorSet.
399      */
400     @Override
401     public long getDuration() {
402         return mDuration;
403     }
404
405     /**
406      * Sets the length of each of the current child animations of this AnimatorSet. By default,
407      * each child animation will use its own duration. If the duration is set on the AnimatorSet,
408      * then each child animation inherits this duration.
409      *
410      * @param duration The length of the animation, in milliseconds, of each of the child
411      * animations of this AnimatorSet.
412      */
413     @Override
414     public AnimatorSet setDuration(long duration) {
415         if (duration < 0) {
416             throw new IllegalArgumentException("duration must be a value of zero or greater");
417         }
418         for (Node node : mNodes) {
419             // TODO: don't set the duration of the timing-only nodes created by AnimatorSet to
420             // insert "play-after" delays
421             node.animation.setDuration(duration);
422         }
423         mDuration = duration;
424         return this;
425     }
426
427     @Override
428     public void setupStartValues() {
429         for (Node node : mNodes) {
430             node.animation.setupStartValues();
431         }
432     }
433
434     @Override
435     public void setupEndValues() {
436         for (Node node : mNodes) {
437             node.animation.setupEndValues();
438         }
439     }
440
441     /**
442      * {@inheritDoc}
443      *
444      * <p>Starting this <code>AnimatorSet</code> will, in turn, start the animations for which
445      * it is responsible. The details of when exactly those animations are started depends on
446      * the dependency relationships that have been set up between the animations.
447      */
448     @Override
449     public void start() {
450         mTerminated = false;
451         mStarted = true;
452
453         // First, sort the nodes (if necessary). This will ensure that sortedNodes
454         // contains the animation nodes in the correct order.
455         sortNodes();
456
457         int numSortedNodes = mSortedNodes.size();
458         for (int i = 0; i < numSortedNodes; ++i) {
459             Node node = mSortedNodes.get(i);
460             // First, clear out the old listeners
461             ArrayList<AnimatorListener> oldListeners = node.animation.getListeners();
462             if (oldListeners != null && oldListeners.size() > 0) {
463                 final ArrayList<AnimatorListener> clonedListeners = new
464                         ArrayList<AnimatorListener>(oldListeners);
465
466                 for (AnimatorListener listener : clonedListeners) {
467                     if (listener instanceof DependencyListener ||
468                             listener instanceof AnimatorSetListener) {
469                         node.animation.removeListener(listener);
470                     }
471                 }
472             }
473         }
474
475         // nodesToStart holds the list of nodes to be started immediately. We don't want to
476         // start the animations in the loop directly because we first need to set up
477         // dependencies on all of the nodes. For example, we don't want to start an animation
478         // when some other animation also wants to start when the first animation begins.
479         final ArrayList<Node> nodesToStart = new ArrayList<Node>();
480         for (int i = 0; i < numSortedNodes; ++i) {
481             Node node = mSortedNodes.get(i);
482             if (mSetListener == null) {
483                 mSetListener = new AnimatorSetListener(this);
484             }
485             if (node.dependencies == null || node.dependencies.size() == 0) {
486                 nodesToStart.add(node);
487             } else {
488                 int numDependencies = node.dependencies.size();
489                 for (int j = 0; j < numDependencies; ++j) {
490                     Dependency dependency = node.dependencies.get(j);
491                     dependency.node.animation.addListener(
492                             new DependencyListener(this, node, dependency.rule));
493                 }
494                 node.tmpDependencies = (ArrayList<Dependency>) node.dependencies.clone();
495             }
496             node.animation.addListener(mSetListener);
497         }
498         // Now that all dependencies are set up, start the animations that should be started.
499         if (mStartDelay <= 0) {
500             for (Node node : nodesToStart) {
501                 node.animation.start();
502                 mPlayingSet.add(node.animation);
503             }
504         } else {
505             mDelayAnim = ValueAnimator.ofFloat(0f, 1f);
506             mDelayAnim.setDuration(mStartDelay);
507             mDelayAnim.addListener(new AnimatorListenerAdapter() {
508                 boolean canceled = false;
509                 public void onAnimationCancel(Animator anim) {
510                     canceled = true;
511                 }
512                 public void onAnimationEnd(Animator anim) {
513                     if (!canceled) {
514                         int numNodes = nodesToStart.size();
515                         for (int i = 0; i < numNodes; ++i) {
516                             Node node = nodesToStart.get(i);
517                             node.animation.start();
518                             mPlayingSet.add(node.animation);
519                         }
520                     }
521                 }
522             });
523             mDelayAnim.start();
524         }
525         if (mListeners != null) {
526             ArrayList<AnimatorListener> tmpListeners =
527                     (ArrayList<AnimatorListener>) mListeners.clone();
528             int numListeners = tmpListeners.size();
529             for (int i = 0; i < numListeners; ++i) {
530                 tmpListeners.get(i).onAnimationStart(this);
531             }
532         }
533         if (mNodes.size() == 0 && mStartDelay == 0) {
534             // Handle unusual case where empty AnimatorSet is started - should send out
535             // end event immediately since the event will not be sent out at all otherwise
536             mStarted = false;
537             if (mListeners != null) {
538                 ArrayList<AnimatorListener> tmpListeners =
539                         (ArrayList<AnimatorListener>) mListeners.clone();
540                 int numListeners = tmpListeners.size();
541                 for (int i = 0; i < numListeners; ++i) {
542                     tmpListeners.get(i).onAnimationEnd(this);
543                 }
544             }
545         }
546     }
547
548     @Override
549     public AnimatorSet clone() {
550         final AnimatorSet anim = (AnimatorSet) super.clone();
551         /*
552          * The basic clone() operation copies all items. This doesn't work very well for
553          * AnimatorSet, because it will copy references that need to be recreated and state
554          * that may not apply. What we need to do now is put the clone in an uninitialized
555          * state, with fresh, empty data structures. Then we will build up the nodes list
556          * manually, as we clone each Node (and its animation). The clone will then be sorted,
557          * and will populate any appropriate lists, when it is started.
558          */
559         anim.mNeedsSort = true;
560         anim.mTerminated = false;
561         anim.mStarted = false;
562         anim.mPlayingSet = new ArrayList<Animator>();
563         anim.mNodeMap = new HashMap<Animator, Node>();
564         anim.mNodes = new ArrayList<Node>();
565         anim.mSortedNodes = new ArrayList<Node>();
566
567         // Walk through the old nodes list, cloning each node and adding it to the new nodemap.
568         // One problem is that the old node dependencies point to nodes in the old AnimatorSet.
569         // We need to track the old/new nodes in order to reconstruct the dependencies in the clone.
570         HashMap<Node, Node> nodeCloneMap = new HashMap<Node, Node>(); // <old, new>
571         for (Node node : mNodes) {
572             Node nodeClone = node.clone();
573             nodeCloneMap.put(node, nodeClone);
574             anim.mNodes.add(nodeClone);
575             anim.mNodeMap.put(nodeClone.animation, nodeClone);
576             // Clear out the dependencies in the clone; we'll set these up manually later
577             nodeClone.dependencies = null;
578             nodeClone.tmpDependencies = null;
579             nodeClone.nodeDependents = null;
580             nodeClone.nodeDependencies = null;
581             // clear out any listeners that were set up by the AnimatorSet; these will
582             // be set up when the clone's nodes are sorted
583             ArrayList<AnimatorListener> cloneListeners = nodeClone.animation.getListeners();
584             if (cloneListeners != null) {
585                 ArrayList<AnimatorListener> listenersToRemove = null;
586                 for (AnimatorListener listener : cloneListeners) {
587                     if (listener instanceof AnimatorSetListener) {
588                         if (listenersToRemove == null) {
589                             listenersToRemove = new ArrayList<AnimatorListener>();
590                         }
591                         listenersToRemove.add(listener);
592                     }
593                 }
594                 if (listenersToRemove != null) {
595                     for (AnimatorListener listener : listenersToRemove) {
596                         cloneListeners.remove(listener);
597                     }
598                 }
599             }
600         }
601         // Now that we've cloned all of the nodes, we're ready to walk through their
602         // dependencies, mapping the old dependencies to the new nodes
603         for (Node node : mNodes) {
604             Node nodeClone = nodeCloneMap.get(node);
605             if (node.dependencies != null) {
606                 for (Dependency dependency : node.dependencies) {
607                     Node clonedDependencyNode = nodeCloneMap.get(dependency.node);
608                     Dependency cloneDependency = new Dependency(clonedDependencyNode,
609                             dependency.rule);
610                     nodeClone.addDependency(cloneDependency);
611                 }
612             }
613         }
614
615         return anim;
616     }
617
618     /**
619      * This class is the mechanism by which animations are started based on events in other
620      * animations. If an animation has multiple dependencies on other animations, then
621      * all dependencies must be satisfied before the animation is started.
622      */
623     private static class DependencyListener implements AnimatorListener {
624
625         private AnimatorSet mAnimatorSet;
626
627         // The node upon which the dependency is based.
628         private Node mNode;
629
630         // The Dependency rule (WITH or AFTER) that the listener should wait for on
631         // the node
632         private int mRule;
633
634         public DependencyListener(AnimatorSet animatorSet, Node node, int rule) {
635             this.mAnimatorSet = animatorSet;
636             this.mNode = node;
637             this.mRule = rule;
638         }
639
640         /**
641          * Ignore cancel events for now. We may want to handle this eventually,
642          * to prevent follow-on animations from running when some dependency
643          * animation is canceled.
644          */
645         public void onAnimationCancel(Animator animation) {
646         }
647
648         /**
649          * An end event is received - see if this is an event we are listening for
650          */
651         public void onAnimationEnd(Animator animation) {
652             if (mRule == Dependency.AFTER) {
653                 startIfReady(animation);
654             }
655         }
656
657         /**
658          * Ignore repeat events for now
659          */
660         public void onAnimationRepeat(Animator animation) {
661         }
662
663         /**
664          * A start event is received - see if this is an event we are listening for
665          */
666         public void onAnimationStart(Animator animation) {
667             if (mRule == Dependency.WITH) {
668                 startIfReady(animation);
669             }
670         }
671
672         /**
673          * Check whether the event received is one that the node was waiting for.
674          * If so, mark it as complete and see whether it's time to start
675          * the animation.
676          * @param dependencyAnimation the animation that sent the event.
677          */
678         private void startIfReady(Animator dependencyAnimation) {
679             if (mAnimatorSet.mTerminated) {
680                 // if the parent AnimatorSet was canceled, then don't start any dependent anims
681                 return;
682             }
683             Dependency dependencyToRemove = null;
684             int numDependencies = mNode.tmpDependencies.size();
685             for (int i = 0; i < numDependencies; ++i) {
686                 Dependency dependency = mNode.tmpDependencies.get(i);
687                 if (dependency.rule == mRule &&
688                         dependency.node.animation == dependencyAnimation) {
689                     // rule fired - remove the dependency and listener and check to
690                     // see whether it's time to start the animation
691                     dependencyToRemove = dependency;
692                     dependencyAnimation.removeListener(this);
693                     break;
694                 }
695             }
696             mNode.tmpDependencies.remove(dependencyToRemove);
697             if (mNode.tmpDependencies.size() == 0) {
698                 // all dependencies satisfied: start the animation
699                 mNode.animation.start();
700                 mAnimatorSet.mPlayingSet.add(mNode.animation);
701             }
702         }
703
704     }
705
706     private class AnimatorSetListener implements AnimatorListener {
707
708         private AnimatorSet mAnimatorSet;
709
710         AnimatorSetListener(AnimatorSet animatorSet) {
711             mAnimatorSet = animatorSet;
712         }
713
714         public void onAnimationCancel(Animator animation) {
715             if (!mTerminated) {
716                 // Listeners are already notified of the AnimatorSet canceling in cancel().
717                 // The logic below only kicks in when animations end normally
718                 if (mPlayingSet.size() == 0) {
719                     if (mListeners != null) {
720                         int numListeners = mListeners.size();
721                         for (int i = 0; i < numListeners; ++i) {
722                             mListeners.get(i).onAnimationCancel(mAnimatorSet);
723                         }
724                     }
725                 }
726             }
727         }
728
729         public void onAnimationEnd(Animator animation) {
730             animation.removeListener(this);
731             mPlayingSet.remove(animation);
732             Node animNode = mAnimatorSet.mNodeMap.get(animation);
733             animNode.done = true;
734             if (!mTerminated) {
735                 // Listeners are already notified of the AnimatorSet ending in cancel() or
736                 // end(); the logic below only kicks in when animations end normally
737                 ArrayList<Node> sortedNodes = mAnimatorSet.mSortedNodes;
738                 boolean allDone = true;
739                 int numSortedNodes = sortedNodes.size();
740                 for (int i = 0; i < numSortedNodes; ++i) {
741                     if (!sortedNodes.get(i).done) {
742                         allDone = false;
743                         break;
744                     }
745                 }
746                 if (allDone) {
747                     // If this was the last child animation to end, then notify listeners that this
748                     // AnimatorSet has ended
749                     if (mListeners != null) {
750                         ArrayList<AnimatorListener> tmpListeners =
751                                 (ArrayList<AnimatorListener>) mListeners.clone();
752                         int numListeners = tmpListeners.size();
753                         for (int i = 0; i < numListeners; ++i) {
754                             tmpListeners.get(i).onAnimationEnd(mAnimatorSet);
755                         }
756                     }
757                     mAnimatorSet.mStarted = false;
758                 }
759             }
760         }
761
762         // Nothing to do
763         public void onAnimationRepeat(Animator animation) {
764         }
765
766         // Nothing to do
767         public void onAnimationStart(Animator animation) {
768         }
769
770     }
771
772     /**
773      * This method sorts the current set of nodes, if needed. The sort is a simple
774      * DependencyGraph sort, which goes like this:
775      * - All nodes without dependencies become 'roots'
776      * - while roots list is not null
777      * -   for each root r
778      * -     add r to sorted list
779      * -     remove r as a dependency from any other node
780      * -   any nodes with no dependencies are added to the roots list
781      */
782     private void sortNodes() {
783         if (mNeedsSort) {
784             mSortedNodes.clear();
785             ArrayList<Node> roots = new ArrayList<Node>();
786             int numNodes = mNodes.size();
787             for (int i = 0; i < numNodes; ++i) {
788                 Node node = mNodes.get(i);
789                 if (node.dependencies == null || node.dependencies.size() == 0) {
790                     roots.add(node);
791                 }
792             }
793             ArrayList<Node> tmpRoots = new ArrayList<Node>();
794             while (roots.size() > 0) {
795                 int numRoots = roots.size();
796                 for (int i = 0; i < numRoots; ++i) {
797                     Node root = roots.get(i);
798                     mSortedNodes.add(root);
799                     if (root.nodeDependents != null) {
800                         int numDependents = root.nodeDependents.size();
801                         for (int j = 0; j < numDependents; ++j) {
802                             Node node = root.nodeDependents.get(j);
803                             node.nodeDependencies.remove(root);
804                             if (node.nodeDependencies.size() == 0) {
805                                 tmpRoots.add(node);
806                             }
807                         }
808                     }
809                 }
810                 roots.clear();
811                 roots.addAll(tmpRoots);
812                 tmpRoots.clear();
813             }
814             mNeedsSort = false;
815             if (mSortedNodes.size() != mNodes.size()) {
816                 throw new IllegalStateException("Circular dependencies cannot exist"
817                         + " in AnimatorSet");
818             }
819         } else {
820             // Doesn't need sorting, but still need to add in the nodeDependencies list
821             // because these get removed as the event listeners fire and the dependencies
822             // are satisfied
823             int numNodes = mNodes.size();
824             for (int i = 0; i < numNodes; ++i) {
825                 Node node = mNodes.get(i);
826                 if (node.dependencies != null && node.dependencies.size() > 0) {
827                     int numDependencies = node.dependencies.size();
828                     for (int j = 0; j < numDependencies; ++j) {
829                         Dependency dependency = node.dependencies.get(j);
830                         if (node.nodeDependencies == null) {
831                             node.nodeDependencies = new ArrayList<Node>();
832                         }
833                         if (!node.nodeDependencies.contains(dependency.node)) {
834                             node.nodeDependencies.add(dependency.node);
835                         }
836                     }
837                 }
838                 // nodes are 'done' by default; they become un-done when started, and done
839                 // again when ended
840                 node.done = false;
841             }
842         }
843     }
844
845     /**
846      * Dependency holds information about the node that some other node is
847      * dependent upon and the nature of that dependency.
848      *
849      */
850     private static class Dependency {
851         static final int WITH = 0; // dependent node must start with this dependency node
852         static final int AFTER = 1; // dependent node must start when this dependency node finishes
853
854         // The node that the other node with this Dependency is dependent upon
855         public Node node;
856
857         // The nature of the dependency (WITH or AFTER)
858         public int rule;
859
860         public Dependency(Node node, int rule) {
861             this.node = node;
862             this.rule = rule;
863         }
864     }
865
866     /**
867      * A Node is an embodiment of both the Animator that it wraps as well as
868      * any dependencies that are associated with that Animation. This includes
869      * both dependencies upon other nodes (in the dependencies list) as
870      * well as dependencies of other nodes upon this (in the nodeDependents list).
871      */
872     private static class Node implements Cloneable {
873         public Animator animation;
874
875         /**
876          *  These are the dependencies that this node's animation has on other
877          *  nodes. For example, if this node's animation should begin with some
878          *  other animation ends, then there will be an item in this node's
879          *  dependencies list for that other animation's node.
880          */
881         public ArrayList<Dependency> dependencies = null;
882
883         /**
884          * tmpDependencies is a runtime detail. We use the dependencies list for sorting.
885          * But we also use the list to keep track of when multiple dependencies are satisfied,
886          * but removing each dependency as it is satisfied. We do not want to remove
887          * the dependency itself from the list, because we need to retain that information
888          * if the AnimatorSet is launched in the future. So we create a copy of the dependency
889          * list when the AnimatorSet starts and use this tmpDependencies list to track the
890          * list of satisfied dependencies.
891          */
892         public ArrayList<Dependency> tmpDependencies = null;
893
894         /**
895          * nodeDependencies is just a list of the nodes that this Node is dependent upon.
896          * This information is used in sortNodes(), to determine when a node is a root.
897          */
898         public ArrayList<Node> nodeDependencies = null;
899
900         /**
901          * nodeDepdendents is the list of nodes that have this node as a dependency. This
902          * is a utility field used in sortNodes to facilitate removing this node as a
903          * dependency when it is a root node.
904          */
905         public ArrayList<Node> nodeDependents = null;
906
907         /**
908          * Flag indicating whether the animation in this node is finished. This flag
909          * is used by AnimatorSet to check, as each animation ends, whether all child animations
910          * are done and it's time to send out an end event for the entire AnimatorSet.
911          */
912         public boolean done = false;
913
914         /**
915          * Constructs the Node with the animation that it encapsulates. A Node has no
916          * dependencies by default; dependencies are added via the addDependency()
917          * method.
918          *
919          * @param animation The animation that the Node encapsulates.
920          */
921         public Node(Animator animation) {
922             this.animation = animation;
923         }
924
925         /**
926          * Add a dependency to this Node. The dependency includes information about the
927          * node that this node is dependency upon and the nature of the dependency.
928          * @param dependency
929          */
930         public void addDependency(Dependency dependency) {
931             if (dependencies == null) {
932                 dependencies = new ArrayList<Dependency>();
933                 nodeDependencies = new ArrayList<Node>();
934             }
935             dependencies.add(dependency);
936             if (!nodeDependencies.contains(dependency.node)) {
937                 nodeDependencies.add(dependency.node);
938             }
939             Node dependencyNode = dependency.node;
940             if (dependencyNode.nodeDependents == null) {
941                 dependencyNode.nodeDependents = new ArrayList<Node>();
942             }
943             dependencyNode.nodeDependents.add(this);
944         }
945
946         @Override
947         public Node clone() {
948             try {
949                 Node node = (Node) super.clone();
950                 node.animation = animation.clone();
951                 return node;
952             } catch (CloneNotSupportedException e) {
953                throw new AssertionError();
954             }
955         }
956     }
957
958     /**
959      * The <code>Builder</code> object is a utility class to facilitate adding animations to a
960      * <code>AnimatorSet</code> along with the relationships between the various animations. The
961      * intention of the <code>Builder</code> methods, along with the {@link
962      * AnimatorSet#play(Animator) play()} method of <code>AnimatorSet</code> is to make it possible
963      * to express the dependency relationships of animations in a natural way. Developers can also
964      * use the {@link AnimatorSet#playTogether(Animator[]) playTogether()} and {@link
965      * AnimatorSet#playSequentially(Animator[]) playSequentially()} methods if these suit the need,
966      * but it might be easier in some situations to express the AnimatorSet of animations in pairs.
967      * <p/>
968      * <p>The <code>Builder</code> object cannot be constructed directly, but is rather constructed
969      * internally via a call to {@link AnimatorSet#play(Animator)}.</p>
970      * <p/>
971      * <p>For example, this sets up a AnimatorSet to play anim1 and anim2 at the same time, anim3 to
972      * play when anim2 finishes, and anim4 to play when anim3 finishes:</p>
973      * <pre>
974      *     AnimatorSet s = new AnimatorSet();
975      *     s.play(anim1).with(anim2);
976      *     s.play(anim2).before(anim3);
977      *     s.play(anim4).after(anim3);
978      * </pre>
979      * <p/>
980      * <p>Note in the example that both {@link Builder#before(Animator)} and {@link
981      * Builder#after(Animator)} are used. These are just different ways of expressing the same
982      * relationship and are provided to make it easier to say things in a way that is more natural,
983      * depending on the situation.</p>
984      * <p/>
985      * <p>It is possible to make several calls into the same <code>Builder</code> object to express
986      * multiple relationships. However, note that it is only the animation passed into the initial
987      * {@link AnimatorSet#play(Animator)} method that is the dependency in any of the successive
988      * calls to the <code>Builder</code> object. For example, the following code starts both anim2
989      * and anim3 when anim1 ends; there is no direct dependency relationship between anim2 and
990      * anim3:
991      * <pre>
992      *   AnimatorSet s = new AnimatorSet();
993      *   s.play(anim1).before(anim2).before(anim3);
994      * </pre>
995      * If the desired result is to play anim1 then anim2 then anim3, this code expresses the
996      * relationship correctly:</p>
997      * <pre>
998      *   AnimatorSet s = new AnimatorSet();
999      *   s.play(anim1).before(anim2);
1000      *   s.play(anim2).before(anim3);
1001      * </pre>
1002      * <p/>
1003      * <p>Note that it is possible to express relationships that cannot be resolved and will not
1004      * result in sensible results. For example, <code>play(anim1).after(anim1)</code> makes no
1005      * sense. In general, circular dependencies like this one (or more indirect ones where a depends
1006      * on b, which depends on c, which depends on a) should be avoided. Only create AnimatorSets
1007      * that can boil down to a simple, one-way relationship of animations starting with, before, and
1008      * after other, different, animations.</p>
1009      */
1010     public class Builder {
1011
1012         /**
1013          * This tracks the current node being processed. It is supplied to the play() method
1014          * of AnimatorSet and passed into the constructor of Builder.
1015          */
1016         private Node mCurrentNode;
1017
1018         /**
1019          * package-private constructor. Builders are only constructed by AnimatorSet, when the
1020          * play() method is called.
1021          *
1022          * @param anim The animation that is the dependency for the other animations passed into
1023          * the other methods of this Builder object.
1024          */
1025         Builder(Animator anim) {
1026             mCurrentNode = mNodeMap.get(anim);
1027             if (mCurrentNode == null) {
1028                 mCurrentNode = new Node(anim);
1029                 mNodeMap.put(anim, mCurrentNode);
1030                 mNodes.add(mCurrentNode);
1031             }
1032         }
1033
1034         /**
1035          * Sets up the given animation to play at the same time as the animation supplied in the
1036          * {@link AnimatorSet#play(Animator)} call that created this <code>Builder</code> object.
1037          *
1038          * @param anim The animation that will play when the animation supplied to the
1039          * {@link AnimatorSet#play(Animator)} method starts.
1040          */
1041         public Builder with(Animator anim) {
1042             Node node = mNodeMap.get(anim);
1043             if (node == null) {
1044                 node = new Node(anim);
1045                 mNodeMap.put(anim, node);
1046                 mNodes.add(node);
1047             }
1048             Dependency dependency = new Dependency(mCurrentNode, Dependency.WITH);
1049             node.addDependency(dependency);
1050             return this;
1051         }
1052
1053         /**
1054          * Sets up the given animation to play when the animation supplied in the
1055          * {@link AnimatorSet#play(Animator)} call that created this <code>Builder</code> object
1056          * ends.
1057          *
1058          * @param anim The animation that will play when the animation supplied to the
1059          * {@link AnimatorSet#play(Animator)} method ends.
1060          */
1061         public Builder before(Animator anim) {
1062             Node node = mNodeMap.get(anim);
1063             if (node == null) {
1064                 node = new Node(anim);
1065                 mNodeMap.put(anim, node);
1066                 mNodes.add(node);
1067             }
1068             Dependency dependency = new Dependency(mCurrentNode, Dependency.AFTER);
1069             node.addDependency(dependency);
1070             return this;
1071         }
1072
1073         /**
1074          * Sets up the given animation to play when the animation supplied in the
1075          * {@link AnimatorSet#play(Animator)} call that created this <code>Builder</code> object
1076          * to start when the animation supplied in this method call ends.
1077          *
1078          * @param anim The animation whose end will cause the animation supplied to the
1079          * {@link AnimatorSet#play(Animator)} method to play.
1080          */
1081         public Builder after(Animator anim) {
1082             Node node = mNodeMap.get(anim);
1083             if (node == null) {
1084                 node = new Node(anim);
1085                 mNodeMap.put(anim, node);
1086                 mNodes.add(node);
1087             }
1088             Dependency dependency = new Dependency(node, Dependency.AFTER);
1089             mCurrentNode.addDependency(dependency);
1090             return this;
1091         }
1092
1093         /**
1094          * Sets up the animation supplied in the
1095          * {@link AnimatorSet#play(Animator)} call that created this <code>Builder</code> object
1096          * to play when the given amount of time elapses.
1097          *
1098          * @param delay The number of milliseconds that should elapse before the
1099          * animation starts.
1100          */
1101         public Builder after(long delay) {
1102             // setup dummy ValueAnimator just to run the clock
1103             ValueAnimator anim = ValueAnimator.ofFloat(0f, 1f);
1104             anim.setDuration(delay);
1105             after(anim);
1106             return this;
1107         }
1108
1109     }
1110
1111 }