Wait with reparenting back until all app animations are done

An activity A that has a shorter animation that is above another
activity B with a longer animation in the same task, the animation
layer would put the B on top of A, but from the hierarchy, A needs
to be on top of B. Thus, we defer reparenting A to the original
hierarchy such that it stays on top of B until B finishes
animating.

Test: Above scenario
Test: AnimatingAppWindowTokenRegistryTest
Fixes: 75246892
Change-Id: I73796376c1cbeb8327262a304911ce2abfbbb0b6
diff --git a/services/core/java/com/android/server/wm/AnimatingAppWindowTokenRegistry.java b/services/core/java/com/android/server/wm/AnimatingAppWindowTokenRegistry.java
new file mode 100644
index 0000000..ae343da
--- /dev/null
+++ b/services/core/java/com/android/server/wm/AnimatingAppWindowTokenRegistry.java
@@ -0,0 +1,91 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+
+package com.android.server.wm;
+
+import android.util.ArrayMap;
+import android.util.ArraySet;
+
+import java.util.ArrayList;
+
+/**
+ * Keeps track of all {@link AppWindowToken} that are animating and makes sure all animations are
+ * finished at the same time such that we don't run into issues with z-ordering: An activity A
+ * that has a shorter animation that is above another activity B with a longer animation in the same
+ * task, the animation layer would put the B on top of A, but from the hierarchy, A needs to be on
+ * top of B. Thus, we defer reparenting A to the original hierarchy such that it stays on top of B
+ * until B finishes animating.
+ */
+class AnimatingAppWindowTokenRegistry {
+
+    private ArraySet<AppWindowToken> mAnimatingTokens = new ArraySet<>();
+    private ArrayMap<AppWindowToken, Runnable> mFinishedTokens = new ArrayMap<>();
+
+    private ArrayList<Runnable> mTmpRunnableList = new ArrayList<>();
+
+    /**
+     * Notifies that an {@link AppWindowToken} has started animating.
+     */
+    void notifyStarting(AppWindowToken token) {
+        mAnimatingTokens.add(token);
+    }
+
+    /**
+     * Notifies that an {@link AppWindowToken} has finished animating.
+     */
+    void notifyFinished(AppWindowToken token) {
+        mAnimatingTokens.remove(token);
+        mFinishedTokens.remove(token);
+    }
+
+    /**
+     * Called when an {@link AppWindowToken} is about to finish animating.
+     *
+     * @param endDeferFinishCallback Callback to run when defer finish should be ended.
+     * @return {@code true} if finishing the animation should be deferred, {@code false} otherwise.
+     */
+    boolean notifyAboutToFinish(AppWindowToken token, Runnable endDeferFinishCallback) {
+        final boolean removed = mAnimatingTokens.remove(token);
+        if (!removed) {
+            return false;
+        }
+
+        if (mAnimatingTokens.isEmpty()) {
+
+            // If no animations are animating anymore, finish all others.
+            endDeferringFinished();
+            return false;
+        } else {
+
+            // Otherwise let's put it into the pending list of to be finished animations.
+            mFinishedTokens.put(token, endDeferFinishCallback);
+            return true;
+        }
+    }
+
+    private void endDeferringFinished() {
+        // Copy it into a separate temp list to avoid modifying the collection while iterating as
+        // calling the callback may call back into notifyFinished.
+        for (int i = mFinishedTokens.size() - 1; i >= 0; i--) {
+            mTmpRunnableList.add(mFinishedTokens.valueAt(i));
+        }
+        mFinishedTokens.clear();
+        for (int i = mTmpRunnableList.size() - 1; i >= 0; i--) {
+            mTmpRunnableList.get(i).run();
+        }
+        mTmpRunnableList.clear();
+    }
+}
diff --git a/services/core/java/com/android/server/wm/AppWindowToken.java b/services/core/java/com/android/server/wm/AppWindowToken.java
index 1f71b8f..8540feb 100644
--- a/services/core/java/com/android/server/wm/AppWindowToken.java
+++ b/services/core/java/com/android/server/wm/AppWindowToken.java
@@ -252,6 +252,7 @@
     private final Point mTmpPoint = new Point();
     private final Rect mTmpRect = new Rect();
     private RemoteAnimationDefinition mRemoteAnimationDefinition;
+    private AnimatingAppWindowTokenRegistry mAnimatingAppWindowTokenRegistry;
 
     AppWindowToken(WindowManagerService service, IApplicationToken token, boolean voiceInteraction,
             DisplayContent dc, long inputDispatchingTimeoutNanos, boolean fullscreen,
@@ -781,6 +782,16 @@
                 task.mStack.mExitingAppTokens.remove(this);
             }
         }
+        final TaskStack stack = getStack();
+
+        // If we reparent, make sure to remove ourselves from the old animation registry.
+        if (mAnimatingAppWindowTokenRegistry != null) {
+            mAnimatingAppWindowTokenRegistry.notifyFinished(this);
+        }
+        mAnimatingAppWindowTokenRegistry = stack != null
+                ? stack.getAnimatingAppWindowTokenRegistry()
+                : null;
+
         mLastParent = task;
     }
 
@@ -1784,6 +1795,21 @@
     }
 
     @Override
+    public boolean shouldDeferAnimationFinish(Runnable endDeferFinishCallback) {
+        return mAnimatingAppWindowTokenRegistry != null
+                && mAnimatingAppWindowTokenRegistry.notifyAboutToFinish(
+                        this, endDeferFinishCallback);
+    }
+
+    @Override
+    public void onAnimationLeashDestroyed(Transaction t) {
+        super.onAnimationLeashDestroyed(t);
+        if (mAnimatingAppWindowTokenRegistry != null) {
+            mAnimatingAppWindowTokenRegistry.notifyFinished(this);
+        }
+    }
+
+    @Override
     protected void setLayer(Transaction t, int layer) {
         if (!mSurfaceAnimator.hasLeash()) {
             t.setLayer(mSurfaceControl, layer);
@@ -1825,6 +1851,9 @@
 
         final DisplayContent dc = getDisplayContent();
         dc.assignStackOrdering(t);
+        if (mAnimatingAppWindowTokenRegistry != null) {
+            mAnimatingAppWindowTokenRegistry.notifyStarting(this);
+        }
     }
 
     /**
diff --git a/services/core/java/com/android/server/wm/SurfaceAnimator.java b/services/core/java/com/android/server/wm/SurfaceAnimator.java
index c06caaf..f10ff8c 100644
--- a/services/core/java/com/android/server/wm/SurfaceAnimator.java
+++ b/services/core/java/com/android/server/wm/SurfaceAnimator.java
@@ -81,9 +81,14 @@
                 if (anim != mAnimation) {
                     return;
                 }
-                reset(mAnimatable.getPendingTransaction(), true /* destroyLeash */);
-                if (animationFinishedCallback != null) {
-                    animationFinishedCallback.run();
+                final Runnable resetAndInvokeFinish = () -> {
+                    reset(mAnimatable.getPendingTransaction(), true /* destroyLeash */);
+                    if (animationFinishedCallback != null) {
+                        animationFinishedCallback.run();
+                    }
+                };
+                if (!mAnimatable.shouldDeferAnimationFinish(resetAndInvokeFinish)) {
+                    resetAndInvokeFinish.run();
                 }
             }
         };
@@ -407,5 +412,17 @@
          * @return The height of the surface to be animated.
          */
         int getSurfaceHeight();
+
+        /**
+         * Gets called when the animation is about to finish and gives the client the opportunity to
+         * defer finishing the animation, i.e. it keeps the leash around until the client calls
+         * {@link #cancelAnimation}.
+         *
+         * @param endDeferFinishCallback The callback to call when defer finishing should be ended.
+         * @return Whether the client would like to defer the animation finish.
+         */
+        default boolean shouldDeferAnimationFinish(Runnable endDeferFinishCallback) {
+            return false;
+        }
     }
 }
diff --git a/services/core/java/com/android/server/wm/TaskStack.java b/services/core/java/com/android/server/wm/TaskStack.java
index b5d00a7..460edec 100644
--- a/services/core/java/com/android/server/wm/TaskStack.java
+++ b/services/core/java/com/android/server/wm/TaskStack.java
@@ -155,6 +155,9 @@
     final Rect mTmpDimBoundsRect = new Rect();
     private final Point mLastSurfaceSize = new Point();
 
+    private final AnimatingAppWindowTokenRegistry mAnimatingAppWindowTokenRegistry =
+            new AnimatingAppWindowTokenRegistry();
+
     TaskStack(WindowManagerService service, int stackId, StackWindowController controller) {
         super(service);
         mStackId = stackId;
@@ -1782,4 +1785,8 @@
         outPos.x -= outset;
         outPos.y -= outset;
     }
+
+    AnimatingAppWindowTokenRegistry getAnimatingAppWindowTokenRegistry() {
+        return mAnimatingAppWindowTokenRegistry;
+    }
 }