Fix z-order of displays when adjusting position of stack

When moving a stack to top including its parent (display),
if the target position is adjusted to non-top because there
is other always-on-top stack in this container, the display
should also be moved to top for higher focus priority.

Z-order
Top          |----------------|
   Display 1 | [Normal stack] |
             |----------------|

             |----------------|
   Display 0 | [Pinned stack] |
             | [Normal stack] | <- Moving task in here
Bottom       |----------------|

Bug: 113099160
Test: atest TaskStackContainersTests#testDisplayPositionWithPinnedStack
Change-Id: I877fd2acddeeb6d68fe6f4336dd202b9db11d94e
diff --git a/services/core/java/com/android/server/wm/DisplayContent.java b/services/core/java/com/android/server/wm/DisplayContent.java
index 5d0101f..ac65826 100644
--- a/services/core/java/com/android/server/wm/DisplayContent.java
+++ b/services/core/java/com/android/server/wm/DisplayContent.java
@@ -3606,6 +3606,18 @@
             final int targetPosition = findPositionForStack(position, child, false /* adding */);
             super.positionChildAt(targetPosition, child, includingParents);
 
+            if (includingParents) {
+                // We still want to move the display of this stack container to top because even the
+                // target position is adjusted to non-top, the intention of the condition is to have
+                // higher z-order to gain focus (e.g. moving a task of a fullscreen stack to front
+                // in a non-top display which is using picture-in-picture mode).
+                final int topChildPosition = getChildCount() - 1;
+                if (targetPosition < topChildPosition && position >= topChildPosition) {
+                    getParent().positionChildAt(POSITION_TOP, this /* child */,
+                            true /* includingParents */);
+                }
+            }
+
             setLayoutNeeded();
         }