Only allow AM to update display orientation based on app containers

Activity manager choregraphs several app states when starting an
activity including when the display orientation should be updated based
on the app that is now in the foreground. It is possible for a call to
originate within WM after AM adds the starting app token, but before AM
makes the app visible and resumed. E.g. A relayout call due to a
starting window. When this happens WM can prematurely update the display
orientation with incomplete information causing the starting app to be
in an incorrect orientation initially.
To fix this problem we now only factor in app containers (stacks, task,
..) when updating the display orientation if the call to update is
coming from AM. Otherwise we only use the non-app/system containers to
determine the orientation or return the last orientation.

Change-Id: I431ce9260ee31257732311a548c62cbcdb27eae7
Fixes: 37550022
Test: Launch 2 apps that don't fix orientation and use the recent button
to switch between them while holding the device in landscape.
diff --git a/services/core/java/com/android/server/wm/DisplayContent.java b/services/core/java/com/android/server/wm/DisplayContent.java
index 67704e7..be242b6 100644
--- a/services/core/java/com/android/server/wm/DisplayContent.java
+++ b/services/core/java/com/android/server/wm/DisplayContent.java
@@ -1503,8 +1503,16 @@
         return mImeWindowsContainers.forAllWindows(callback, traverseTopToBottom);
     }
 
-    @Override
-    int getOrientation() {
+    /**
+     * Returns the orientation that this display should be in factoring in its children containers.
+     *
+     * @param includeAppContainers True if then app containers (stacks, tasks, ...) should be
+     *                             factored in when determining the orientation. If false only
+     *                             non-app/system containers will be used to determine the returned
+     *                             orientation.
+     * @return The orientation the display should be in.
+     */
+    int getOrientation(boolean includeAppContainers) {
         final WindowManagerPolicy policy = mService.mPolicy;
 
         if (mService.mDisplayFrozen) {
@@ -1533,8 +1541,14 @@
             }
         }
 
-        // Top system windows are not requesting an orientation. Start searching from apps.
-        return mTaskStackContainers.getOrientation();
+        // Top system windows are not requesting an orientation. Get orientation from app containers
+        // if allowed. Otherwise, return the last orientation.
+        return includeAppContainers ? mTaskStackContainers.getOrientation() : mLastOrientation;
+    }
+
+    @Override
+    int getOrientation() {
+        return getOrientation(true /* includeAppContainers */);
     }
 
     void updateDisplayInfo() {