Revert "Revert "Elevate remote/recents animation priority""

This reverts commit a8b48ab7332f61afe37b2e866e9cb67421fab1c0.

Original issue has been fixed in follow up CL.

Bug: 73555925
Change-Id: Ie0a157a91c3c66df52370adad7b188f59c4749ea
diff --git a/core/java/android/app/ActivityManagerInternal.java b/core/java/android/app/ActivityManagerInternal.java
index c78255f..cab6744 100644
--- a/core/java/android/app/ActivityManagerInternal.java
+++ b/core/java/android/app/ActivityManagerInternal.java
@@ -27,6 +27,7 @@
 import android.os.SystemClock;
 import android.service.voice.IVoiceInteractionSession;
 import android.util.SparseIntArray;
+import android.view.RemoteAnimationAdapter;
 
 import com.android.internal.app.IVoiceInteractor;
 
@@ -264,6 +265,17 @@
     public abstract void setHasOverlayUi(int pid, boolean hasOverlayUi);
 
     /**
+     * Sets if the given pid is currently running a remote animation, which is taken a signal for
+     * determining oom adjustment and scheduling behavior.
+     *
+     * @param pid The pid we are setting overlay UI for.
+     * @param runningRemoteAnimation True if the process is running a remote animation, false
+     *                               otherwise.
+     * @see RemoteAnimationAdapter
+     */
+    public abstract void setRunningRemoteAnimation(int pid, boolean runningRemoteAnimation);
+
+    /**
      * Called after the network policy rules are updated by
      * {@link com.android.server.net.NetworkPolicyManagerService} for a specific {@param uid} and
      * {@param procStateSeq}.
diff --git a/core/java/android/view/RemoteAnimationAdapter.java b/core/java/android/view/RemoteAnimationAdapter.java
index d597e59..a864e55 100644
--- a/core/java/android/view/RemoteAnimationAdapter.java
+++ b/core/java/android/view/RemoteAnimationAdapter.java
@@ -52,6 +52,9 @@
     private final long mDuration;
     private final long mStatusBarTransitionDelay;
 
+    /** @see #getCallingPid */
+    private int mCallingPid;
+
     /**
      * @param runner The interface that gets notified when we actually need to start the animation.
      * @param duration The duration of the animation.
@@ -83,6 +86,20 @@
         return mStatusBarTransitionDelay;
     }
 
+    /**
+     * To be called by system_server to keep track which pid is running this animation.
+     */
+    public void setCallingPid(int pid) {
+        mCallingPid = pid;
+    }
+
+    /**
+     * @return The pid of the process running the animation.
+     */
+    public int getCallingPid() {
+        return mCallingPid;
+    }
+
     @Override
     public int describeContents() {
         return 0;
diff --git a/core/java/android/view/RemoteAnimationDefinition.java b/core/java/android/view/RemoteAnimationDefinition.java
index 381f692..8def435 100644
--- a/core/java/android/view/RemoteAnimationDefinition.java
+++ b/core/java/android/view/RemoteAnimationDefinition.java
@@ -70,6 +70,16 @@
         mTransitionAnimationMap = in.readSparseArray(null /* loader */);
     }
 
+    /**
+     * To be called by system_server to keep track which pid is running the remote animations inside
+     * this definition.
+     */
+    public void setCallingPid(int pid) {
+        for (int i = mTransitionAnimationMap.size() - 1; i >= 0; i--) {
+            mTransitionAnimationMap.valueAt(i).setCallingPid(pid);
+        }
+    }
+
     @Override
     public int describeContents() {
         return 0;
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index bf25928..0bfd771 100644
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -5149,6 +5149,7 @@
     public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
                 IRecentsAnimationRunner recentsAnimationRunner) {
         enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
+        final int callingPid = Binder.getCallingPid();
         final long origId = Binder.clearCallingIdentity();
         try {
             synchronized (this) {
@@ -5174,7 +5175,7 @@
 
                 // Start a new recents animation
                 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
-                        mActivityStartController, mWindowManager, mUserController);
+                        mActivityStartController, mWindowManager, mUserController, callingPid);
                 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
                         recentsUid);
             }
@@ -14337,6 +14338,28 @@
         }
     }
 
+    void setRunningRemoteAnimation(int pid, boolean runningRemoteAnimation) {
+        synchronized (ActivityManagerService.this) {
+            final ProcessRecord pr;
+            synchronized (mPidsSelfLocked) {
+                pr = mPidsSelfLocked.get(pid);
+                if (pr == null) {
+                    Slog.w(TAG, "setRunningRemoteAnimation called on unknown pid: " + pid);
+                    return;
+                }
+            }
+            if (pr.runningRemoteAnimation == runningRemoteAnimation) {
+                return;
+            }
+            pr.runningRemoteAnimation = runningRemoteAnimation;
+            if (DEBUG_OOM_ADJ) {
+                Slog.i(TAG, "Setting runningRemoteAnimation=" + pr.runningRemoteAnimation
+                        + " for pid=" + pid);
+            }
+            updateOomAdjLocked(pr, true);
+        }
+    }
+
     public final void enterSafeMode() {
         synchronized(this) {
             // It only makes sense to do this before the system is ready
@@ -22747,6 +22770,12 @@
             foregroundActivities = true;
             procState = PROCESS_STATE_CUR_TOP;
             if (DEBUG_OOM_ADJ_REASON) Slog.d(TAG, "Making top: " + app);
+        } else if (app.runningRemoteAnimation) {
+            adj = ProcessList.VISIBLE_APP_ADJ;
+            schedGroup = ProcessList.SCHED_GROUP_TOP_APP;
+            app.adjType = "running-remote-anim";
+            procState = PROCESS_STATE_CUR_TOP;
+            if (DEBUG_OOM_ADJ_REASON) Slog.d(TAG, "Making running remote anim: " + app);
         } else if (app.instr != null) {
             // Don't want to kill running instrumentation.
             adj = ProcessList.FOREGROUND_APP_ADJ;
@@ -22822,7 +22851,9 @@
                         app.adjType = "vis-activity";
                         if (DEBUG_OOM_ADJ_REASON) Slog.d(TAG, "Raise to vis-activity: " + app);
                     }
-                    schedGroup = ProcessList.SCHED_GROUP_DEFAULT;
+                    if (schedGroup < ProcessList.SCHED_GROUP_DEFAULT) {
+                        schedGroup = ProcessList.SCHED_GROUP_DEFAULT;
+                    }
                     app.cached = false;
                     app.empty = false;
                     foregroundActivities = true;
@@ -22845,7 +22876,9 @@
                         app.adjType = "pause-activity";
                         if (DEBUG_OOM_ADJ_REASON) Slog.d(TAG, "Raise to pause-activity: " + app);
                     }
-                    schedGroup = ProcessList.SCHED_GROUP_DEFAULT;
+                    if (schedGroup < ProcessList.SCHED_GROUP_DEFAULT) {
+                        schedGroup = ProcessList.SCHED_GROUP_DEFAULT;
+                    }
                     app.cached = false;
                     app.empty = false;
                     foregroundActivities = true;
@@ -25986,6 +26019,11 @@
             }
         }
 
+        @Override
+        public void setRunningRemoteAnimation(int pid, boolean runningRemoteAnimation) {
+            ActivityManagerService.this.setRunningRemoteAnimation(pid, runningRemoteAnimation);
+        }
+
         /**
          * Called after the network policy rules are updated by
          * {@link com.android.server.net.NetworkPolicyManagerService} for a specific {@param uid}
@@ -26535,6 +26573,7 @@
             throws RemoteException {
         enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
                 "registerRemoteAnimations");
+        definition.setCallingPid(Binder.getCallingPid());
         synchronized (this) {
             final ActivityRecord r = ActivityRecord.isInStackLocked(token);
             if (r == null) {
diff --git a/services/core/java/com/android/server/am/ProcessRecord.java b/services/core/java/com/android/server/am/ProcessRecord.java
index 1f60755..0bf2691 100644
--- a/services/core/java/com/android/server/am/ProcessRecord.java
+++ b/services/core/java/com/android/server/am/ProcessRecord.java
@@ -129,6 +129,12 @@
                                 // When true the process will oom adj score will be set to
                                 // ProcessList#PERCEPTIBLE_APP_ADJ at minimum to reduce the chance
                                 // of the process getting killed.
+    boolean runningRemoteAnimation; // Is the process currently running a RemoteAnimation? When true
+                                // the process will be set to use the
+                                // ProcessList#SCHED_GROUP_TOP_APP scheduling group to boost
+                                // performance, as well as oom adj score will be set to
+                                // ProcessList#VISIBLE_APP_ADJ at minimum to reduce the chance
+                                // of the process getting killed.
     boolean pendingUiClean;     // Want to clean up resources from showing UI?
     boolean hasAboveClient;     // Bound using BIND_ABOVE_CLIENT, so want to be lower
     boolean treatLikeActivity;  // Bound using BIND_TREAT_LIKE_ACTIVITY
@@ -336,9 +342,10 @@
                     pw.print(" hasAboveClient="); pw.print(hasAboveClient);
                     pw.print(" treatLikeActivity="); pw.println(treatLikeActivity);
         }
-        if (hasTopUi || hasOverlayUi) {
+        if (hasTopUi || hasOverlayUi || runningRemoteAnimation) {
             pw.print(prefix); pw.print("hasTopUi="); pw.print(hasTopUi);
-                    pw.print(" hasOverlayUi="); pw.println(hasOverlayUi);
+                    pw.print(" hasOverlayUi="); pw.print(hasOverlayUi);
+                    pw.print(" runningRemoteAnimation="); pw.println(runningRemoteAnimation);
         }
         if (foregroundServices || forcingToImportant != null) {
             pw.print(prefix); pw.print("foregroundServices="); pw.print(foregroundServices);
diff --git a/services/core/java/com/android/server/am/RecentsAnimation.java b/services/core/java/com/android/server/am/RecentsAnimation.java
index 4b1594c..322d66b 100644
--- a/services/core/java/com/android/server/am/RecentsAnimation.java
+++ b/services/core/java/com/android/server/am/RecentsAnimation.java
@@ -50,6 +50,7 @@
     private final WindowManagerService mWindowManager;
     private final UserController mUserController;
     private final Handler mHandler;
+    private final int mCallingPid;
 
     private final Runnable mCancelAnimationRunnable;
 
@@ -58,13 +59,14 @@
 
     RecentsAnimation(ActivityManagerService am, ActivityStackSupervisor stackSupervisor,
             ActivityStartController activityStartController, WindowManagerService wm,
-            UserController userController) {
+            UserController userController, int callingPid) {
         mService = am;
         mStackSupervisor = stackSupervisor;
         mActivityStartController = activityStartController;
         mHandler = new Handler(mStackSupervisor.mLooper);
         mWindowManager = wm;
         mUserController = userController;
+        mCallingPid = callingPid;
 
         mCancelAnimationRunnable = () -> {
             // The caller has not finished the animation in a predefined amount of time, so
@@ -94,9 +96,10 @@
             }
         }
 
+        mService.setRunningRemoteAnimation(mCallingPid, true);
+
         mWindowManager.deferSurfaceLayout();
         try {
-
             final ActivityDisplay display;
             if (hasExistingHomeActivity) {
                 // Move the home activity into place for the animation if it is not already top most
@@ -153,6 +156,8 @@
         synchronized (mService) {
             if (mWindowManager.getRecentsAnimationController() == null) return;
 
+            mService.setRunningRemoteAnimation(mCallingPid, false);
+
             mWindowManager.inSurfaceTransaction(() -> {
                 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER,
                         "RecentsAnimation#onAnimationFinished_inSurfaceTransaction");
diff --git a/services/core/java/com/android/server/am/SafeActivityOptions.java b/services/core/java/com/android/server/am/SafeActivityOptions.java
index d08111e..ac6f01f 100644
--- a/services/core/java/com/android/server/am/SafeActivityOptions.java
+++ b/services/core/java/com/android/server/am/SafeActivityOptions.java
@@ -121,10 +121,16 @@
         if (mOriginalOptions != null) {
             checkPermissions(intent, aInfo, callerApp, supervisor, mOriginalOptions,
                     mOriginalCallingPid, mOriginalCallingUid);
+            if (mOriginalOptions.getRemoteAnimationAdapter() != null) {
+                mOriginalOptions.getRemoteAnimationAdapter().setCallingPid(mOriginalCallingPid);
+            }
         }
         if (mCallerOptions != null) {
             checkPermissions(intent, aInfo, callerApp, supervisor, mCallerOptions,
                     mRealCallingPid, mRealCallingUid);
+            if (mCallerOptions.getRemoteAnimationAdapter() != null) {
+                mCallerOptions.getRemoteAnimationAdapter().setCallingPid(mRealCallingPid);
+            }
         }
         return mergeActivityOptions(mOriginalOptions, mCallerOptions);
     }
diff --git a/services/core/java/com/android/server/wm/RemoteAnimationController.java b/services/core/java/com/android/server/wm/RemoteAnimationController.java
index ed6e606..e4bb043 100644
--- a/services/core/java/com/android/server/wm/RemoteAnimationController.java
+++ b/services/core/java/com/android/server/wm/RemoteAnimationController.java
@@ -103,6 +103,7 @@
                 onAnimationFinished();
             }
         });
+        sendRunningRemoteAnimation(true);
     }
 
     private RemoteAnimationTarget[] createAnimations() {
@@ -131,6 +132,7 @@
                 mService.closeSurfaceTransaction("RemoteAnimationController#finished");
             }
         }
+        sendRunningRemoteAnimation(false);
     }
 
     private void invokeAnimationCancelled() {
@@ -148,6 +150,14 @@
         }
     }
 
+    private void sendRunningRemoteAnimation(boolean running) {
+        final int pid = mRemoteAnimationAdapter.getCallingPid();
+        if (pid == 0) {
+            throw new RuntimeException("Calling pid of remote animation was null");
+        }
+        mService.sendSetRunningRemoteAnimation(pid, running);
+    }
+
     private static final class FinishedCallback extends IRemoteAnimationFinishedCallback.Stub {
 
         RemoteAnimationController mOuter;
@@ -251,6 +261,7 @@
                 mHandler.removeCallbacks(mTimeoutRunnable);
                 releaseFinishedCallback();
                 invokeAnimationCancelled();
+                sendRunningRemoteAnimation(false);
             }
         }
 
diff --git a/services/core/java/com/android/server/wm/WindowManagerService.java b/services/core/java/com/android/server/wm/WindowManagerService.java
index 2041c6f..4fb9d31 100644
--- a/services/core/java/com/android/server/wm/WindowManagerService.java
+++ b/services/core/java/com/android/server/wm/WindowManagerService.java
@@ -4555,6 +4555,7 @@
         public static final int NOTIFY_KEYGUARD_FLAGS_CHANGED = 56;
         public static final int NOTIFY_KEYGUARD_TRUSTED_CHANGED = 57;
         public static final int SET_HAS_OVERLAY_UI = 58;
+        public static final int SET_RUNNING_REMOTE_ANIMATION = 59;
 
         /**
          * Used to denote that an integer field in a message will not be used.
@@ -4969,6 +4970,10 @@
                     mAmInternal.setHasOverlayUi(msg.arg1, msg.arg2 == 1);
                 }
                 break;
+                case SET_RUNNING_REMOTE_ANIMATION: {
+                    mAmInternal.setRunningRemoteAnimation(msg.arg1, msg.arg2 == 1);
+                }
+                break;
             }
             if (DEBUG_WINDOW_TRACE) {
                 Slog.v(TAG_WM, "handleMessage: exit");
@@ -7409,5 +7414,10 @@
     SurfaceControl.Builder makeSurfaceBuilder(SurfaceSession s) {
         return mSurfaceBuilderFactory.make(s);
     }
+
+    void sendSetRunningRemoteAnimation(int pid, boolean runningRemoteAnimation) {
+        mH.obtainMessage(H.SET_RUNNING_REMOTE_ANIMATION, pid, runningRemoteAnimation ? 1 : 0)
+                .sendToTarget();
+    }
 }