blob: 0722b8efd2cf4b067c1e956777b406b00c0c538d [file] [log] [blame]
Andrii Kulian526ad432020-03-27 12:19:51 -07001/*
2 * Copyright (C) 2020 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
17package com.android.server.wm;
18
19import static android.app.WindowConfiguration.ACTIVITY_TYPE_HOME;
Andrii Kulian9ea12da2020-03-27 17:16:38 -070020import static android.app.WindowConfiguration.ACTIVITY_TYPE_STANDARD;
Andrii Kulian526ad432020-03-27 12:19:51 -070021import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Andrii Kulian9ea12da2020-03-27 17:16:38 -070022import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
23import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
24import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN_OR_SPLIT_SCREEN_SECONDARY;
25import static android.app.WindowConfiguration.WINDOWING_MODE_MULTI_WINDOW;
Andrii Kulian526ad432020-03-27 12:19:51 -070026import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
27import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Andrii Kulian9ea12da2020-03-27 17:16:38 -070028import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
29import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
30import static android.app.WindowConfiguration.isSplitScreenWindowingMode;
Andrii Kulian526ad432020-03-27 12:19:51 -070031import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_BEHIND;
32import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_UNSET;
33import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Andrii Kulian526ad432020-03-27 12:19:51 -070034
Andrii Kulian9ea12da2020-03-27 17:16:38 -070035import static com.android.server.wm.ActivityStack.ActivityState.RESUMED;
36import static com.android.server.wm.ActivityStack.STACK_VISIBILITY_VISIBLE;
37import static com.android.server.wm.ActivityStackSupervisor.TAG_TASKS;
38import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STATES;
39import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
40import static com.android.server.wm.ActivityTaskManagerService.TAG_STACK;
41import static com.android.server.wm.DisplayContent.alwaysCreateStack;
Andrii Kulian526ad432020-03-27 12:19:51 -070042import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_ADD_REMOVE;
43import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_ORIENTATION;
Andrii Kulian9ea12da2020-03-27 17:16:38 -070044import static com.android.server.wm.RootWindowContainer.TAG_STATES;
Andrii Kulian86d676c2020-03-27 19:34:54 -070045import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_STACK;
Andrii Kulian526ad432020-03-27 12:19:51 -070046import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
47
Andrii Kulian9ea12da2020-03-27 17:16:38 -070048import android.annotation.Nullable;
49import android.app.ActivityOptions;
50import android.app.WindowConfiguration;
51import android.content.Intent;
52import android.content.pm.ActivityInfo;
53import android.content.pm.ApplicationInfo;
54import android.os.UserHandle;
Andrii Kulian526ad432020-03-27 12:19:51 -070055import android.util.Slog;
56import android.view.SurfaceControl;
Andrii Kulian9ea12da2020-03-27 17:16:38 -070057import android.window.WindowContainerTransaction;
Andrii Kulian526ad432020-03-27 12:19:51 -070058
59import com.android.internal.annotations.VisibleForTesting;
60import com.android.internal.util.ToBooleanFunction;
Andrii Kulian9ea12da2020-03-27 17:16:38 -070061import com.android.internal.util.function.pooled.PooledLambda;
62import com.android.internal.util.function.pooled.PooledPredicate;
Andrii Kulian526ad432020-03-27 12:19:51 -070063import com.android.server.protolog.common.ProtoLog;
64
Andrii Kulianf9df4a82020-03-31 12:09:27 -070065import java.io.PrintWriter;
Andrii Kulian526ad432020-03-27 12:19:51 -070066import java.util.ArrayList;
67import java.util.List;
68
69/**
Andrii Kulian86d676c2020-03-27 19:34:54 -070070 * {@link DisplayArea} that represents a section of a screen that contains app window containers.
Andrii Kulian526ad432020-03-27 12:19:51 -070071 */
Andrii Kulian86d676c2020-03-27 19:34:54 -070072final class TaskDisplayArea extends DisplayArea<ActivityStack> {
Andrii Kulian1cb59dd2020-04-10 12:17:17 -070073
Andrii Kulian86d676c2020-03-27 19:34:54 -070074 DisplayContent mDisplayContent;
Andrii Kulian1cb59dd2020-04-10 12:17:17 -070075
Andrii Kulian526ad432020-03-27 12:19:51 -070076 /**
77 * A control placed at the appropriate level for transitions to occur.
78 */
79 private SurfaceControl mAppAnimationLayer;
80 private SurfaceControl mBoostedAppAnimationLayer;
81 private SurfaceControl mHomeAppAnimationLayer;
82
83 /**
84 * Given that the split-screen divider does not have an AppWindowToken, it
85 * will have to live inside of a "NonAppWindowContainer". However, in visual Z order
86 * it will need to be interleaved with some of our children, appearing on top of
87 * both docked stacks but underneath any assistant stacks.
88 *
89 * To solve this problem we have this anchor control, which will always exist so
90 * we can always assign it the correct value in our {@link #assignChildLayers}.
91 * Likewise since it always exists, we can always
92 * assign the divider a layer relative to it. This way we prevent linking lifecycle
93 * events between tasks and the divider window.
94 */
95 private SurfaceControl mSplitScreenDividerAnchor;
96
97 // Cached reference to some special tasks we tend to get a lot so we don't need to loop
98 // through the list to find them.
99 private ActivityStack mRootHomeTask;
100 private ActivityStack mRootPinnedTask;
101 private ActivityStack mRootSplitScreenPrimaryTask;
102
103 private final ArrayList<ActivityStack> mTmpAlwaysOnTopStacks = new ArrayList<>();
104 private final ArrayList<ActivityStack> mTmpNormalStacks = new ArrayList<>();
105 private final ArrayList<ActivityStack> mTmpHomeStacks = new ArrayList<>();
106
Andrii Kulian9ea12da2020-03-27 17:16:38 -0700107 private ArrayList<Task> mTmpTasks = new ArrayList<>();
108
109 private ActivityTaskManagerService mAtmService;
110
111 private RootWindowContainer mRootWindowContainer;
112
113 // When non-null, new tasks get put into this root task.
Andrii Kulian86d676c2020-03-27 19:34:54 -0700114 Task mLaunchRootTask = null;
Andrii Kulian9ea12da2020-03-27 17:16:38 -0700115
116 /**
117 * A focusable stack that is purposely to be positioned at the top. Although the stack may not
118 * have the topmost index, it is used as a preferred candidate to prevent being unable to resume
119 * target stack properly when there are other focusable always-on-top stacks.
120 */
Andrii Kulian86d676c2020-03-27 19:34:54 -0700121 ActivityStack mPreferredTopFocusableStack;
Andrii Kulian9ea12da2020-03-27 17:16:38 -0700122
123 private final RootWindowContainer.FindTaskResult
124 mTmpFindTaskResult = new RootWindowContainer.FindTaskResult();
125
126 /**
127 * If this is the same as {@link #getFocusedStack} then the activity on the top of the focused
128 * stack has been resumed. If stacks are changing position this will hold the old stack until
129 * the new stack becomes resumed after which it will be set to current focused stack.
130 */
131 ActivityStack mLastFocusedStack;
Andrii Kulian4c0fd0d2020-03-29 13:32:14 -0700132 /**
133 * All of the stacks on this display. Order matters, topmost stack is in front of all other
134 * stacks, bottommost behind. Accessed directly by ActivityManager package classes. Any calls
135 * changing the list should also call {@link #onStackOrderChanged()}.
136 */
137 private ArrayList<OnStackOrderChangedListener> mStackOrderChangedCallbacks = new ArrayList<>();
Andrii Kulian9ea12da2020-03-27 17:16:38 -0700138
Andrii Kulianf9df4a82020-03-31 12:09:27 -0700139 /**
140 * The task display area is removed from the system and we are just waiting for all activities
141 * on it to be finished before removing this object.
142 */
143 private boolean mRemoved;
144
Andrii Kulian44b3c562020-04-01 12:49:56 -0700145 TaskDisplayArea(DisplayContent displayContent, WindowManagerService service, String name,
146 int displayAreaFeature) {
147 super(service, Type.ANY, name, displayAreaFeature);
Andrii Kulian526ad432020-03-27 12:19:51 -0700148 mDisplayContent = displayContent;
Andrii Kulian9ea12da2020-03-27 17:16:38 -0700149 mRootWindowContainer = service.mRoot;
150 mAtmService = service.mAtmService;
Andrii Kulian526ad432020-03-27 12:19:51 -0700151 }
152
153 /**
154 * Returns the topmost stack on the display that is compatible with the input windowing mode
155 * and activity type. Null is no compatible stack on the display.
156 */
157 ActivityStack getStack(int windowingMode, int activityType) {
158 if (activityType == ACTIVITY_TYPE_HOME) {
159 return mRootHomeTask;
160 }
161 if (windowingMode == WINDOWING_MODE_PINNED) {
162 return mRootPinnedTask;
163 } else if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
164 return mRootSplitScreenPrimaryTask;
165 }
166 for (int i = getChildCount() - 1; i >= 0; --i) {
167 final ActivityStack stack = getChildAt(i);
168 if (activityType == ACTIVITY_TYPE_UNDEFINED
169 && windowingMode == stack.getWindowingMode()) {
170 // Passing in undefined type means we want to match the topmost stack with the
171 // windowing mode.
172 return stack;
173 }
174 if (stack.isCompatible(windowingMode, activityType)) {
175 return stack;
176 }
177 }
178 return null;
179 }
180
181 @VisibleForTesting
182 ActivityStack getTopStack() {
183 final int count = getChildCount();
184 return count > 0 ? getChildAt(count - 1) : null;
185 }
186
187 int getIndexOf(ActivityStack stack) {
188 return mChildren.indexOf(stack);
189 }
190
191 ActivityStack getRootHomeTask() {
192 return mRootHomeTask;
193 }
194
195 ActivityStack getRootPinnedTask() {
196 return mRootPinnedTask;
197 }
198
199 ActivityStack getRootSplitScreenPrimaryTask() {
200 return mRootSplitScreenPrimaryTask;
201 }
202
203 ArrayList<Task> getVisibleTasks() {
204 final ArrayList<Task> visibleTasks = new ArrayList<>();
205 forAllTasks(task -> {
206 if (task.isLeafTask() && task.isVisible()) {
207 visibleTasks.add(task);
208 }
209 });
210 return visibleTasks;
211 }
212
213 void onStackWindowingModeChanged(ActivityStack stack) {
214 removeStackReferenceIfNeeded(stack);
215 addStackReferenceIfNeeded(stack);
216 if (stack == mRootPinnedTask && getTopStack() != stack) {
217 // Looks like this stack changed windowing mode to pinned. Move it to the top.
218 positionChildAt(POSITION_TOP, stack, false /* includingParents */);
219 }
220 }
221
222 void addStackReferenceIfNeeded(ActivityStack stack) {
223 if (stack.isActivityTypeHome()) {
224 if (mRootHomeTask != null) {
225 if (!stack.isDescendantOf(mRootHomeTask)) {
226 throw new IllegalArgumentException("addStackReferenceIfNeeded: home stack="
227 + mRootHomeTask + " already exist on display=" + this
228 + " stack=" + stack);
229 }
230 } else {
231 mRootHomeTask = stack;
232 }
233 }
234
235 if (!stack.isRootTask()) {
236 return;
237 }
238 final int windowingMode = stack.getWindowingMode();
239 if (windowingMode == WINDOWING_MODE_PINNED) {
240 if (mRootPinnedTask != null) {
241 throw new IllegalArgumentException(
242 "addStackReferenceIfNeeded: pinned stack=" + mRootPinnedTask
243 + " already exist on display=" + this + " stack=" + stack);
244 }
245 mRootPinnedTask = stack;
246 } else if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
247 if (mRootSplitScreenPrimaryTask != null) {
248 throw new IllegalArgumentException(
249 "addStackReferenceIfNeeded: split screen primary stack="
250 + mRootSplitScreenPrimaryTask
251 + " already exist on display=" + this + " stack=" + stack);
252 }
253 mRootSplitScreenPrimaryTask = stack;
254 }
255 }
256
257 void removeStackReferenceIfNeeded(ActivityStack stack) {
258 if (stack == mRootHomeTask) {
259 mRootHomeTask = null;
260 } else if (stack == mRootPinnedTask) {
261 mRootPinnedTask = null;
262 } else if (stack == mRootSplitScreenPrimaryTask) {
263 mRootSplitScreenPrimaryTask = null;
264 }
265 }
266
267 @Override
268 void addChild(ActivityStack stack, int position) {
Vishnu Nair7c8a2472020-04-17 16:08:29 -0700269 if (DEBUG_STACK) Slog.d(TAG_WM, "Set stack=" + stack + " on taskDisplayArea=" + this);
Andrii Kulian526ad432020-03-27 12:19:51 -0700270 addStackReferenceIfNeeded(stack);
271 position = findPositionForStack(position, stack, true /* adding */);
272
273 super.addChild(stack, position);
Andrii Kulian9ea12da2020-03-27 17:16:38 -0700274 mAtmService.updateSleepIfNeededLocked();
Andrii Kulian526ad432020-03-27 12:19:51 -0700275
Vishnu Nair7c8a2472020-04-17 16:08:29 -0700276 positionStackAt(stack, position);
Andrii Kulian526ad432020-03-27 12:19:51 -0700277 }
278
279 @Override
280 protected void removeChild(ActivityStack stack) {
281 super.removeChild(stack);
Andrii Kulian9ea12da2020-03-27 17:16:38 -0700282 onStackRemoved(stack);
283 mAtmService.updateSleepIfNeededLocked();
Andrii Kulian526ad432020-03-27 12:19:51 -0700284 removeStackReferenceIfNeeded(stack);
285 }
286
287 @Override
288 boolean isOnTop() {
289 // Considered always on top
290 return true;
291 }
292
293 @Override
294 void positionChildAt(int position, ActivityStack child, boolean includingParents) {
295 final boolean moveToTop = (position == POSITION_TOP || position == getChildCount());
296 final boolean moveToBottom = (position == POSITION_BOTTOM || position == 0);
297 if (child.getWindowConfiguration().isAlwaysOnTop() && !moveToTop) {
298 // This stack is always-on-top, override the default behavior.
299 Slog.w(TAG_WM, "Ignoring move of always-on-top stack=" + this + " to bottom");
300
301 // Moving to its current position, as we must call super but we don't want to
302 // perform any meaningful action.
303 final int currentPosition = mChildren.indexOf(child);
304 super.positionChildAt(currentPosition, child, false /* includingParents */);
305 return;
306 }
307 // We don't allow untrusted display to top when task stack moves to top,
308 // until user tapping this display to change display position as top intentionally.
309 if (mDisplayContent.isUntrustedVirtualDisplay() && !getParent().isOnTop()) {
310 includingParents = false;
311 }
312 final int targetPosition = findPositionForStack(position, child, false /* adding */);
313 super.positionChildAt(targetPosition, child, false /* includingParents */);
314
315 if (includingParents && (moveToTop || moveToBottom)) {
316 // The DisplayContent children do not re-order, but we still want to move the
317 // display of this stack container because the intention of positioning is to have
318 // higher z-order to gain focus.
319 mDisplayContent.positionDisplayAt(moveToTop ? POSITION_TOP : POSITION_BOTTOM,
320 true /* includingParents */);
321 }
322
323 child.updateTaskMovement(moveToTop);
324
325 mDisplayContent.setLayoutNeeded();
326 }
327
328 /**
329 * When stack is added or repositioned, find a proper position for it.
330 * This will make sure that pinned stack always stays on top.
331 * @param requestedPosition Position requested by caller.
332 * @param stack Stack to be added or positioned.
333 * @param adding Flag indicates whether we're adding a new stack or positioning an existing.
334 * @return The proper position for the stack.
335 */
336 private int findPositionForStack(int requestedPosition, ActivityStack stack,
337 boolean adding) {
338 if (stack.isActivityTypeDream()) {
339 return POSITION_TOP;
340 }
341
342 if (stack.inPinnedWindowingMode()) {
343 return POSITION_TOP;
344 }
345
346 final int topChildPosition = mChildren.size() - 1;
347 int belowAlwaysOnTopPosition = POSITION_BOTTOM;
348 for (int i = topChildPosition; i >= 0; --i) {
349 // Since a stack could be repositioned while being one of the child, return
350 // current index if that's the same stack we are positioning and it is always on
351 // top.
Andrii Kulian4c0fd0d2020-03-29 13:32:14 -0700352 final boolean sameStack = mChildren.get(i) == stack;
Andrii Kulian526ad432020-03-27 12:19:51 -0700353 if ((sameStack && stack.isAlwaysOnTop())
Andrii Kulian4c0fd0d2020-03-29 13:32:14 -0700354 || (!sameStack && !mChildren.get(i).isAlwaysOnTop())) {
Andrii Kulian526ad432020-03-27 12:19:51 -0700355 belowAlwaysOnTopPosition = i;
356 break;
357 }
358 }
359
360 // The max possible position we can insert the stack at.
361 int maxPosition = POSITION_TOP;
362 // The min possible position we can insert the stack at.
363 int minPosition = POSITION_BOTTOM;
364
365 if (stack.isAlwaysOnTop()) {
Andrii Kulian86d676c2020-03-27 19:34:54 -0700366 if (hasPinnedTask()) {
Andrii Kulian526ad432020-03-27 12:19:51 -0700367 // Always-on-top stacks go below the pinned stack.
Andrii Kulian4c0fd0d2020-03-29 13:32:14 -0700368 maxPosition = mChildren.indexOf(mRootPinnedTask) - 1;
Andrii Kulian526ad432020-03-27 12:19:51 -0700369 }
370 // Always-on-top stacks need to be above all other stacks.
371 minPosition = belowAlwaysOnTopPosition
372 != POSITION_BOTTOM ? belowAlwaysOnTopPosition : topChildPosition;
373 } else {
374 // Other stacks need to be below the always-on-top stacks.
375 maxPosition = belowAlwaysOnTopPosition
376 != POSITION_BOTTOM ? belowAlwaysOnTopPosition : 0;
377 }
378
379 // Cap the requested position to something reasonable for the previous position check
380 // below.
381 if (requestedPosition == POSITION_TOP) {
382 requestedPosition = mChildren.size();
383 } else if (requestedPosition == POSITION_BOTTOM) {
384 requestedPosition = 0;
385 }
386
387 int targetPosition = requestedPosition;
388 targetPosition = Math.min(targetPosition, maxPosition);
389 targetPosition = Math.max(targetPosition, minPosition);
390
Andrii Kulian4c0fd0d2020-03-29 13:32:14 -0700391 int prevPosition = mChildren.indexOf(stack);
Andrii Kulian526ad432020-03-27 12:19:51 -0700392 // The positions we calculated above (maxPosition, minPosition) do not take into
393 // consideration the following edge cases.
394 // 1) We need to adjust the position depending on the value "adding".
395 // 2) When we are moving a stack to another position, we also need to adjust the
396 // position depending on whether the stack is moving to a higher or lower position.
397 if ((targetPosition != requestedPosition) && (adding || targetPosition < prevPosition)) {
398 targetPosition++;
399 }
400
401 return targetPosition;
402 }
403
404 @Override
405 boolean forAllWindows(ToBooleanFunction<WindowState> callback,
406 boolean traverseTopToBottom) {
407 if (traverseTopToBottom) {
408 if (super.forAllWindows(callback, traverseTopToBottom)) {
409 return true;
410 }
411 if (forAllExitingAppTokenWindows(callback, traverseTopToBottom)) {
412 return true;
413 }
414 } else {
415 if (forAllExitingAppTokenWindows(callback, traverseTopToBottom)) {
416 return true;
417 }
418 if (super.forAllWindows(callback, traverseTopToBottom)) {
419 return true;
420 }
421 }
422 return false;
423 }
424
425 private boolean forAllExitingAppTokenWindows(ToBooleanFunction<WindowState> callback,
426 boolean traverseTopToBottom) {
427 // For legacy reasons we process the TaskStack.mExitingActivities first here before the
428 // app tokens.
429 // TODO: Investigate if we need to continue to do this or if we can just process them
430 // in-order.
431 if (traverseTopToBottom) {
432 for (int i = mChildren.size() - 1; i >= 0; --i) {
433 final List<ActivityRecord> activities = mChildren.get(i).mExitingActivities;
434 for (int j = activities.size() - 1; j >= 0; --j) {
435 if (activities.get(j).forAllWindowsUnchecked(callback,
436 traverseTopToBottom)) {
437 return true;
438 }
439 }
440 }
441 } else {
442 final int count = mChildren.size();
443 for (int i = 0; i < count; ++i) {
444 final List<ActivityRecord> activities = mChildren.get(i).mExitingActivities;
445 final int appTokensCount = activities.size();
446 for (int j = 0; j < appTokensCount; j++) {
447 if (activities.get(j).forAllWindowsUnchecked(callback,
448 traverseTopToBottom)) {
449 return true;
450 }
451 }
452 }
453 }
454 return false;
455 }
456
457 void setExitingTokensHasVisible(boolean hasVisible) {
458 for (int i = mChildren.size() - 1; i >= 0; --i) {
459 final ArrayList<ActivityRecord> activities = mChildren.get(i).mExitingActivities;
460 for (int j = activities.size() - 1; j >= 0; --j) {
461 activities.get(j).hasVisible = hasVisible;
462 }
463 }
464 }
465
466 void removeExistingAppTokensIfPossible() {
467 for (int i = mChildren.size() - 1; i >= 0; --i) {
468 final ArrayList<ActivityRecord> activities = mChildren.get(i).mExitingActivities;
469 for (int j = activities.size() - 1; j >= 0; --j) {
470 final ActivityRecord activity = activities.get(j);
471 if (!activity.hasVisible && !mDisplayContent.mClosingApps.contains(activity)
472 && (!activity.mIsExiting || activity.isEmpty())) {
473 // Make sure there is no animation running on this activity, so any windows
474 // associated with it will be removed as soon as their animations are
475 // complete.
476 cancelAnimation();
477 ProtoLog.v(WM_DEBUG_ADD_REMOVE,
478 "performLayout: Activity exiting now removed %s", activity);
479 activity.removeIfPossible();
480 }
481 }
482 }
483 }
484
485 @Override
486 int getOrientation(int candidate) {
Andrii Kulian4c0fd0d2020-03-29 13:32:14 -0700487 if (isStackVisible(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY)) {
Andrii Kulian526ad432020-03-27 12:19:51 -0700488 // Apps and their containers are not allowed to specify an orientation while using
489 // root tasks...except for the home stack if it is not resizable and currently
490 // visible (top of) its root task.
491 if (mRootHomeTask != null && mRootHomeTask.isVisible()) {
492 final Task topMost = mRootHomeTask.getTopMostTask();
493 final boolean resizable = topMost != null && topMost.isResizeable();
494 if (!(resizable && mRootHomeTask.matchParentBounds())) {
495 final int orientation = mRootHomeTask.getOrientation();
496 if (orientation != SCREEN_ORIENTATION_UNSET) {
497 return orientation;
498 }
499 }
500 }
501 return SCREEN_ORIENTATION_UNSPECIFIED;
502 }
503
504 final int orientation = super.getOrientation(candidate);
505 if (orientation != SCREEN_ORIENTATION_UNSET
506 && orientation != SCREEN_ORIENTATION_BEHIND) {
507 ProtoLog.v(WM_DEBUG_ORIENTATION,
508 "App is requesting an orientation, return %d for display id=%d",
509 orientation, mDisplayContent.mDisplayId);
510 return orientation;
511 }
512
513 ProtoLog.v(WM_DEBUG_ORIENTATION,
514 "No app is requesting an orientation, return %d for display id=%d",
515 mDisplayContent.getLastOrientation(), mDisplayContent.mDisplayId);
516 // The next app has not been requested to be visible, so we keep the current orientation
517 // to prevent freezing/unfreezing the display too early.
518 return mDisplayContent.getLastOrientation();
519 }
520
521 @Override
522 void assignChildLayers(SurfaceControl.Transaction t) {
523 assignStackOrdering(t);
524
525 for (int i = 0; i < mChildren.size(); i++) {
526 final ActivityStack s = mChildren.get(i);
527 s.assignChildLayers(t);
528 }
529 }
530
531 void assignStackOrdering(SurfaceControl.Transaction t) {
532 if (getParent() == null) {
533 return;
534 }
535 mTmpAlwaysOnTopStacks.clear();
536 mTmpHomeStacks.clear();
537 mTmpNormalStacks.clear();
538 for (int i = 0; i < mChildren.size(); ++i) {
539 final ActivityStack s = mChildren.get(i);
540 if (s.isAlwaysOnTop()) {
541 mTmpAlwaysOnTopStacks.add(s);
542 } else if (s.isActivityTypeHome()) {
543 mTmpHomeStacks.add(s);
544 } else {
545 mTmpNormalStacks.add(s);
546 }
547 }
548
549 int layer = 0;
550 // Place home stacks to the bottom.
551 for (int i = 0; i < mTmpHomeStacks.size(); i++) {
552 mTmpHomeStacks.get(i).assignLayer(t, layer++);
553 }
554 // The home animation layer is between the home stacks and the normal stacks.
555 final int layerForHomeAnimationLayer = layer++;
556 int layerForSplitScreenDividerAnchor = layer++;
557 int layerForAnimationLayer = layer++;
558 for (int i = 0; i < mTmpNormalStacks.size(); i++) {
559 final ActivityStack s = mTmpNormalStacks.get(i);
560 s.assignLayer(t, layer++);
561 if (s.inSplitScreenWindowingMode()) {
562 // The split screen divider anchor is located above the split screen window.
563 layerForSplitScreenDividerAnchor = layer++;
564 }
565 if (s.isTaskAnimating() || s.isAppTransitioning()) {
566 // The animation layer is located above the highest animating stack and no
567 // higher.
568 layerForAnimationLayer = layer++;
569 }
570 }
571 // The boosted animation layer is between the normal stacks and the always on top
572 // stacks.
573 final int layerForBoostedAnimationLayer = layer++;
574 for (int i = 0; i < mTmpAlwaysOnTopStacks.size(); i++) {
575 mTmpAlwaysOnTopStacks.get(i).assignLayer(t, layer++);
576 }
577
578 t.setLayer(mHomeAppAnimationLayer, layerForHomeAnimationLayer);
579 t.setLayer(mAppAnimationLayer, layerForAnimationLayer);
580 t.setLayer(mSplitScreenDividerAnchor, layerForSplitScreenDividerAnchor);
581 t.setLayer(mBoostedAppAnimationLayer, layerForBoostedAnimationLayer);
582 }
583
584 @Override
585 SurfaceControl getAppAnimationLayer(@AnimationLayer int animationLayer) {
586 switch (animationLayer) {
587 case ANIMATION_LAYER_BOOSTED:
588 return mBoostedAppAnimationLayer;
589 case ANIMATION_LAYER_HOME:
590 return mHomeAppAnimationLayer;
591 case ANIMATION_LAYER_STANDARD:
592 default:
593 return mAppAnimationLayer;
594 }
595 }
596
597 SurfaceControl getSplitScreenDividerAnchor() {
598 return mSplitScreenDividerAnchor;
599 }
600
601 @Override
602 void onParentChanged(ConfigurationContainer newParent, ConfigurationContainer oldParent) {
603 if (getParent() != null) {
604 super.onParentChanged(newParent, oldParent, () -> {
605 mAppAnimationLayer = makeChildSurface(null)
606 .setName("animationLayer")
607 .build();
608 mBoostedAppAnimationLayer = makeChildSurface(null)
609 .setName("boostedAnimationLayer")
610 .build();
611 mHomeAppAnimationLayer = makeChildSurface(null)
612 .setName("homeAnimationLayer")
613 .build();
614 mSplitScreenDividerAnchor = makeChildSurface(null)
615 .setName("splitScreenDividerAnchor")
616 .build();
617 getPendingTransaction()
618 .show(mAppAnimationLayer)
619 .show(mBoostedAppAnimationLayer)
620 .show(mHomeAppAnimationLayer)
621 .show(mSplitScreenDividerAnchor);
622 });
623 } else {
624 super.onParentChanged(newParent, oldParent);
625 mWmService.mTransactionFactory.get()
626 .remove(mAppAnimationLayer)
627 .remove(mBoostedAppAnimationLayer)
628 .remove(mHomeAppAnimationLayer)
629 .remove(mSplitScreenDividerAnchor)
630 .apply();
631 mAppAnimationLayer = null;
632 mBoostedAppAnimationLayer = null;
633 mHomeAppAnimationLayer = null;
634 mSplitScreenDividerAnchor = null;
635 }
636 }
Andrii Kulian9ea12da2020-03-27 17:16:38 -0700637
Andrii Kulian9ea12da2020-03-27 17:16:38 -0700638 void onStackRemoved(ActivityStack stack) {
639 if (ActivityTaskManagerDebugConfig.DEBUG_STACK) {
640 Slog.v(TAG_STACK, "removeStack: detaching " + stack + " from displayId="
641 + mDisplayContent.mDisplayId);
642 }
643 if (mPreferredTopFocusableStack == stack) {
644 mPreferredTopFocusableStack = null;
645 }
646 mDisplayContent.releaseSelfIfNeeded();
Andrii Kulian4c0fd0d2020-03-29 13:32:14 -0700647 onStackOrderChanged(stack);
Andrii Kulian9ea12da2020-03-27 17:16:38 -0700648 }
649
650 void positionStackAt(int position, ActivityStack child, boolean includingParents) {
651 positionChildAt(position, child, includingParents);
652 mDisplayContent.layoutAndAssignWindowLayersIfNeeded();
653 }
654
655 void positionStackAtTop(ActivityStack stack, boolean includingParents) {
656 positionStackAtTop(stack, includingParents, null /* updateLastFocusedStackReason */);
657 }
658
659 void positionStackAtTop(ActivityStack stack, boolean includingParents,
660 String updateLastFocusedStackReason) {
661 positionStackAt(stack, getStackCount(), includingParents,
662 updateLastFocusedStackReason);
663 }
664
665 void positionStackAtBottom(ActivityStack stack) {
666 positionStackAtBottom(stack, null /* updateLastFocusedStackReason */);
667 }
668
669 void positionStackAtBottom(ActivityStack stack, String updateLastFocusedStackReason) {
670 positionStackAt(stack, 0, false /* includingParents */,
671 updateLastFocusedStackReason);
672 }
673
674 void positionStackAt(ActivityStack stack, int position) {
675 positionStackAt(stack, position, false /* includingParents */,
676 null /* updateLastFocusedStackReason */);
677 }
678
679 void positionStackAt(ActivityStack stack, int position, boolean includingParents,
680 String updateLastFocusedStackReason) {
681 // TODO: Keep in sync with WindowContainer.positionChildAt(), once we change that to adjust
682 // the position internally, also update the logic here
683 final ActivityStack prevFocusedStack = updateLastFocusedStackReason != null
684 ? getFocusedStack() : null;
685 final boolean wasContained = getIndexOf(stack) >= 0;
686 if (mDisplayContent.mSingleTaskInstance && getStackCount() == 1 && !wasContained) {
687 throw new IllegalStateException(
688 "positionStackAt: Can only have one task on display=" + this);
689 }
690
691 final boolean movingToTop = wasContained && position >= getStackCount() - 1;
692 // Reset mPreferredTopFocusableStack before positioning to top or {@link
693 // ActivityStackSupervisor#updateTopResumedActivityIfNeeded()} won't update the top
694 // resumed activity.
695 if (movingToTop && stack.isFocusable()) {
696 mPreferredTopFocusableStack = null;
697 }
698
699 // Since positionChildAt() is called during the creation process of pinned stacks,
700 // ActivityStack#getStack() can be null.
701 positionStackAt(position, stack, includingParents);
702
703 // The insert position may be adjusted to non-top when there is always-on-top stack. Since
704 // the original position is preferred to be top, the stack should have higher priority when
705 // we are looking for top focusable stack. The condition {@code wasContained} restricts the
706 // preferred stack is set only when moving an existing stack to top instead of adding a new
707 // stack that may be too early (e.g. in the middle of launching or reparenting).
708 if (movingToTop && stack.isFocusableAndVisible()) {
709 mPreferredTopFocusableStack = stack;
710 } else if (mPreferredTopFocusableStack == stack) {
711 mPreferredTopFocusableStack = null;
712 }
713
714 if (updateLastFocusedStackReason != null) {
715 final ActivityStack currentFocusedStack = getFocusedStack();
716 if (currentFocusedStack != prevFocusedStack) {
717 mLastFocusedStack = prevFocusedStack;
718 EventLogTags.writeWmFocusedStack(mRootWindowContainer.mCurrentUser,
719 mDisplayContent.mDisplayId,
720 currentFocusedStack == null ? -1 : currentFocusedStack.getRootTaskId(),
721 mLastFocusedStack == null ? -1 : mLastFocusedStack.getRootTaskId(),
722 updateLastFocusedStackReason);
723 }
724 }
725
Andrii Kulian4c0fd0d2020-03-29 13:32:14 -0700726 onStackOrderChanged(stack);
Andrii Kulian9ea12da2020-03-27 17:16:38 -0700727 }
728
729 ActivityStack getStack(int rootTaskId) {
730 for (int i = getStackCount() - 1; i >= 0; --i) {
731 final ActivityStack stack = getStackAt(i);
732 if (stack.getRootTaskId() == rootTaskId) {
733 return stack;
734 }
735 }
736 return null;
737 }
738
739 /**
740 * Returns an existing stack compatible with the windowing mode and activity type or creates one
741 * if a compatible stack doesn't exist.
Wale Ogunwalec27e1ac2020-03-31 13:18:47 -0700742 * @see #getOrCreateStack(int, int, boolean, Intent, Task)
Andrii Kulian9ea12da2020-03-27 17:16:38 -0700743 */
744 ActivityStack getOrCreateStack(int windowingMode, int activityType, boolean onTop) {
745 return getOrCreateStack(windowingMode, activityType, onTop, null /* intent */,
Wale Ogunwalec27e1ac2020-03-31 13:18:47 -0700746 null /* candidateTask */);
Andrii Kulian9ea12da2020-03-27 17:16:38 -0700747 }
748
749 /**
750 * When two level tasks are required for given windowing mode and activity type, returns an
751 * existing compatible root task or creates a new one.
752 * For one level task, the candidate task would be reused to also be the root task or create
753 * a new root task if no candidate task.
754 * @see #getStack(int, int)
755 * @see #createStack(int, int, boolean)
756 */
757 ActivityStack getOrCreateStack(int windowingMode, int activityType, boolean onTop,
Wale Ogunwalec27e1ac2020-03-31 13:18:47 -0700758 Intent intent, Task candidateTask) {
Louis Chang6c5d7252020-03-30 15:42:01 +0800759 // Need to pass in a determined windowing mode to see if a new stack should be created,
760 // so use its parent's windowing mode if it is undefined.
761 if (!alwaysCreateStack(
762 windowingMode != WINDOWING_MODE_UNDEFINED ? windowingMode : getWindowingMode(),
763 activityType)) {
Andrii Kulian9ea12da2020-03-27 17:16:38 -0700764 ActivityStack stack = getStack(windowingMode, activityType);
765 if (stack != null) {
766 return stack;
767 }
768 } else if (candidateTask != null) {
769 final ActivityStack stack = (ActivityStack) candidateTask;
770 final int position = onTop ? POSITION_TOP : POSITION_BOTTOM;
Wale Ogunwalec27e1ac2020-03-31 13:18:47 -0700771 Task launchRootTask = updateLaunchRootTask(windowingMode);
772
773 if (launchRootTask != null) {
Andrii Kulian9ea12da2020-03-27 17:16:38 -0700774 if (stack.getParent() == null) {
Wale Ogunwalec27e1ac2020-03-31 13:18:47 -0700775 launchRootTask.addChild(stack, position);
776 } else if (stack.getParent() != launchRootTask) {
777 stack.reparent(launchRootTask, position);
Andrii Kulian9ea12da2020-03-27 17:16:38 -0700778 }
Andrii Kulian4c0fd0d2020-03-29 13:32:14 -0700779 } else if (stack.getDisplayArea() != this || !stack.isRootTask()) {
Andrii Kulian9ea12da2020-03-27 17:16:38 -0700780 if (stack.getParent() == null) {
Vishnu Nair7c8a2472020-04-17 16:08:29 -0700781 addChild(stack, position);
Andrii Kulian9ea12da2020-03-27 17:16:38 -0700782 } else {
Andrii Kulian4c0fd0d2020-03-29 13:32:14 -0700783 stack.reparent(this, onTop);
Andrii Kulian9ea12da2020-03-27 17:16:38 -0700784 }
785 }
786 // Update windowing mode if necessary, e.g. moving a pinned task to fullscreen.
787 if (candidateTask.getWindowingMode() != windowingMode) {
788 candidateTask.setWindowingMode(windowingMode);
789 }
790 return stack;
791 }
792 return createStack(windowingMode, activityType, onTop, null /*info*/, intent,
Wale Ogunwalec27e1ac2020-03-31 13:18:47 -0700793 false /* createdByOrganizer */);
Andrii Kulian9ea12da2020-03-27 17:16:38 -0700794 }
795
796 /**
797 * Returns an existing stack compatible with the input params or creates one
798 * if a compatible stack doesn't exist.
799 * @see #getOrCreateStack(int, int, boolean)
800 */
801 ActivityStack getOrCreateStack(@Nullable ActivityRecord r,
802 @Nullable ActivityOptions options, @Nullable Task candidateTask, int activityType,
803 boolean onTop) {
804 // First preference is the windowing mode in the activity options if set.
805 int windowingMode = (options != null)
806 ? options.getLaunchWindowingMode() : WINDOWING_MODE_UNDEFINED;
807 // Validate that our desired windowingMode will work under the current conditions.
808 // UNDEFINED windowing mode is a valid result and means that the new stack will inherit
809 // it's display's windowing mode.
810 windowingMode = validateWindowingMode(windowingMode, r, candidateTask, activityType);
811 return getOrCreateStack(windowingMode, activityType, onTop, null /* intent */,
Wale Ogunwalec27e1ac2020-03-31 13:18:47 -0700812 candidateTask);
Andrii Kulian9ea12da2020-03-27 17:16:38 -0700813 }
814
815 @VisibleForTesting
816 int getNextStackId() {
817 return mAtmService.mStackSupervisor.getNextTaskIdForUser();
818 }
819
820 ActivityStack createStack(int windowingMode, int activityType, boolean onTop) {
821 return createStack(windowingMode, activityType, onTop, null /* info */, null /* intent */,
822 false /* createdByOrganizer */);
823 }
824
825 /**
826 * Creates a stack matching the input windowing mode and activity type on this display.
827 * @param windowingMode The windowing mode the stack should be created in. If
828 * {@link WindowConfiguration#WINDOWING_MODE_UNDEFINED} then the stack will
829 * inherit its parent's windowing mode.
830 * @param activityType The activityType the stack should be created in. If
831 * {@link WindowConfiguration#ACTIVITY_TYPE_UNDEFINED} then the stack will
832 * be created in {@link WindowConfiguration#ACTIVITY_TYPE_STANDARD}.
833 * @param onTop If true the stack will be created at the top of the display, else at the bottom.
834 * @param info The started activity info.
835 * @param intent The intent that started this task.
836 * @param createdByOrganizer @{code true} if this is created by task organizer, @{code false}
837 * otherwise.
838 * @return The newly created stack.
839 */
840 ActivityStack createStack(int windowingMode, int activityType, boolean onTop, ActivityInfo info,
841 Intent intent, boolean createdByOrganizer) {
842 if (mDisplayContent.mSingleTaskInstance && getStackCount() > 0) {
843 // Create stack on default display instead since this display can only contain 1 stack.
844 // TODO: Kinda a hack, but better that having the decision at each call point. Hoping
845 // this goes away once ActivityView is no longer using virtual displays.
Andrii Kulian4c0fd0d2020-03-29 13:32:14 -0700846 return mRootWindowContainer.getDefaultTaskDisplayArea().createStack(
Andrii Kulian9ea12da2020-03-27 17:16:38 -0700847 windowingMode, activityType, onTop, info, intent, createdByOrganizer);
848 }
849
850 if (activityType == ACTIVITY_TYPE_UNDEFINED && !createdByOrganizer) {
851 // Can't have an undefined stack type yet...so re-map to standard. Anyone that wants
852 // anything else should be passing it in anyways...except for the task organizer.
853 activityType = ACTIVITY_TYPE_STANDARD;
854 }
855
856 if (activityType != ACTIVITY_TYPE_STANDARD && activityType != ACTIVITY_TYPE_UNDEFINED) {
857 // For now there can be only one stack of a particular non-standard activity type on a
858 // display. So, get that ignoring whatever windowing mode it is currently in.
859 ActivityStack stack = getStack(WINDOWING_MODE_UNDEFINED, activityType);
860 if (stack != null) {
861 throw new IllegalArgumentException("Stack=" + stack + " of activityType="
862 + activityType + " already on display=" + this + ". Can't have multiple.");
863 }
864 }
865
866 if (!isWindowingModeSupported(windowingMode, mAtmService.mSupportsMultiWindow,
867 mAtmService.mSupportsSplitScreenMultiWindow,
868 mAtmService.mSupportsFreeformWindowManagement,
869 mAtmService.mSupportsPictureInPicture, activityType)) {
870 throw new IllegalArgumentException("Can't create stack for unsupported windowingMode="
871 + windowingMode);
872 }
873
Evan Rosky688c8382020-04-03 17:27:08 -0700874 if (windowingMode == WINDOWING_MODE_PINNED && getRootPinnedTask() != null) {
875 // Only 1 stack can be PINNED at a time, so dismiss the existing one
876 getRootPinnedTask().dismissPip();
877 }
878
Andrii Kulian9ea12da2020-03-27 17:16:38 -0700879 final int stackId = getNextStackId();
880 return createStackUnchecked(windowingMode, activityType, stackId, onTop, info, intent,
881 createdByOrganizer);
882 }
883
884 /** @return the root task to create the next task in. */
885 private Task updateLaunchRootTask(int windowingMode) {
886 if (!isSplitScreenWindowingMode(windowingMode)) {
887 // Only split-screen windowing modes can do this currently...
888 return null;
889 }
890 for (int i = getStackCount() - 1; i >= 0; --i) {
891 final Task t = getStackAt(i);
892 if (!t.mCreatedByOrganizer || t.getRequestedOverrideWindowingMode() != windowingMode) {
893 continue;
894 }
895 // If not already set, pick a launch root which is not the one we are launching into.
896 if (mLaunchRootTask == null) {
897 for (int j = 0, n = getStackCount(); j < n; ++j) {
898 final Task tt = getStackAt(j);
899 if (tt.mCreatedByOrganizer && tt != t) {
900 mLaunchRootTask = tt;
901 break;
902 }
903 }
904 }
905 return t;
906 }
907 return mLaunchRootTask;
908 }
909
910 @VisibleForTesting
911 ActivityStack createStackUnchecked(int windowingMode, int activityType, int stackId,
912 boolean onTop, ActivityInfo info, Intent intent, boolean createdByOrganizer) {
913 if (windowingMode == WINDOWING_MODE_PINNED && activityType != ACTIVITY_TYPE_STANDARD) {
914 throw new IllegalArgumentException("Stack with windowing mode cannot with non standard "
915 + "activity type.");
916 }
917 if (info == null) {
918 info = new ActivityInfo();
919 info.applicationInfo = new ApplicationInfo();
920 }
921
922 // Task created by organizer are added as root.
923 Task launchRootTask = createdByOrganizer ? null : updateLaunchRootTask(windowingMode);
924 if (launchRootTask != null) {
925 // Since this stack will be put into a root task, its windowingMode will be inherited.
926 windowingMode = WINDOWING_MODE_UNDEFINED;
927 }
928
929 final ActivityStack stack = (ActivityStack) Task.create(mAtmService, stackId, activityType,
930 info, intent, createdByOrganizer);
931 if (launchRootTask != null) {
932 launchRootTask.addChild(stack, onTop ? POSITION_TOP : POSITION_BOTTOM);
933 if (onTop) {
934 positionStackAtTop((ActivityStack) launchRootTask, false /* includingParents */);
935 }
936 } else {
Vishnu Nair7c8a2472020-04-17 16:08:29 -0700937 addChild(stack, onTop ? POSITION_TOP : POSITION_BOTTOM);
Evan Rosky50ea8c12020-04-02 20:49:05 -0700938 stack.setWindowingMode(windowingMode, true /* creating */);
Andrii Kulian9ea12da2020-03-27 17:16:38 -0700939 }
940 return stack;
941 }
942
943 /**
944 * Get the preferred focusable stack in priority. If the preferred stack does not exist, find a
945 * focusable and visible stack from the top of stacks in this display.
946 */
947 ActivityStack getFocusedStack() {
948 if (mPreferredTopFocusableStack != null) {
949 return mPreferredTopFocusableStack;
950 }
951
952 for (int i = getStackCount() - 1; i >= 0; --i) {
953 final ActivityStack stack = getStackAt(i);
954 if (stack.isFocusableAndVisible()) {
955 return stack;
956 }
957 }
958
959 return null;
960 }
961
962 ActivityStack getNextFocusableStack(ActivityStack currentFocus, boolean ignoreCurrent) {
963 final int currentWindowingMode = currentFocus != null
964 ? currentFocus.getWindowingMode() : WINDOWING_MODE_UNDEFINED;
965
966 ActivityStack candidate = null;
967 for (int i = getStackCount() - 1; i >= 0; --i) {
968 final ActivityStack stack = getStackAt(i);
969 if (ignoreCurrent && stack == currentFocus) {
970 continue;
971 }
972 if (!stack.isFocusableAndVisible()) {
973 continue;
974 }
975
976 if (currentWindowingMode == WINDOWING_MODE_SPLIT_SCREEN_SECONDARY
977 && candidate == null && stack.inSplitScreenPrimaryWindowingMode()) {
978 // If the currently focused stack is in split-screen secondary we save off the
979 // top primary split-screen stack as a candidate for focus because we might
980 // prefer focus to move to an other stack to avoid primary split-screen stack
981 // overlapping with a fullscreen stack when a fullscreen stack is higher in z
982 // than the next split-screen stack. Assistant stack, I am looking at you...
983 // We only move the focus to the primary-split screen stack if there isn't a
984 // better alternative.
985 candidate = stack;
986 continue;
987 }
988 if (candidate != null && stack.inSplitScreenSecondaryWindowingMode()) {
989 // Use the candidate stack since we are now at the secondary split-screen.
990 return candidate;
991 }
992 return stack;
993 }
994 return candidate;
995 }
996
Andrii Kulianf9df4a82020-03-31 12:09:27 -0700997 ActivityRecord getFocusedActivity() {
Andrii Kulian9ea12da2020-03-27 17:16:38 -0700998 final ActivityStack focusedStack = getFocusedStack();
999 if (focusedStack == null) {
1000 return null;
1001 }
1002 // TODO(b/111541062): Move this into ActivityStack#getResumedActivity()
1003 // Check if the focused stack has the resumed activity
1004 ActivityRecord resumedActivity = focusedStack.getResumedActivity();
1005 if (resumedActivity == null || resumedActivity.app == null) {
1006 // If there is no registered resumed activity in the stack or it is not running -
1007 // try to use previously resumed one.
1008 resumedActivity = focusedStack.mPausingActivity;
1009 if (resumedActivity == null || resumedActivity.app == null) {
1010 // If previously resumed activity doesn't work either - find the topmost running
1011 // activity that can be focused.
1012 resumedActivity = focusedStack.topRunningActivity(true /* focusableOnly */);
1013 }
1014 }
1015 return resumedActivity;
1016 }
1017
1018 ActivityStack getLastFocusedStack() {
1019 return mLastFocusedStack;
1020 }
1021
1022 boolean allResumedActivitiesComplete() {
1023 for (int stackNdx = getStackCount() - 1; stackNdx >= 0; --stackNdx) {
1024 final ActivityRecord r = getStackAt(stackNdx).getResumedActivity();
1025 if (r != null && !r.isState(RESUMED)) {
1026 return false;
1027 }
1028 }
1029 final ActivityStack currentFocusedStack = getFocusedStack();
1030 if (ActivityTaskManagerDebugConfig.DEBUG_STACK) {
1031 Slog.d(TAG_STACK, "allResumedActivitiesComplete: mLastFocusedStack changing from="
1032 + mLastFocusedStack + " to=" + currentFocusedStack);
1033 }
1034 mLastFocusedStack = currentFocusedStack;
1035 return true;
1036 }
1037
1038 /**
1039 * Pause all activities in either all of the stacks or just the back stacks. This is done before
1040 * resuming a new activity and to make sure that previously active activities are
1041 * paused in stacks that are no longer visible or in pinned windowing mode. This does not
1042 * pause activities in visible stacks, so if an activity is launched within the same stack/task,
1043 * then we should explicitly pause that stack's top activity.
1044 * @param userLeaving Passed to pauseActivity() to indicate whether to call onUserLeaving().
1045 * @param resuming The resuming activity.
1046 * @return {@code true} if any activity was paused as a result of this call.
1047 */
1048 boolean pauseBackStacks(boolean userLeaving, ActivityRecord resuming) {
1049 boolean someActivityPaused = false;
1050 for (int stackNdx = getStackCount() - 1; stackNdx >= 0; --stackNdx) {
1051 final ActivityStack stack = getStackAt(stackNdx);
1052 final ActivityRecord resumedActivity = stack.getResumedActivity();
1053 if (resumedActivity != null
1054 && (stack.getVisibility(resuming) != STACK_VISIBILITY_VISIBLE
1055 || !stack.isTopActivityFocusable())) {
1056 if (DEBUG_STATES) {
1057 Slog.d(TAG_STATES, "pauseBackStacks: stack=" + stack
1058 + " mResumedActivity=" + resumedActivity);
1059 }
1060 someActivityPaused |= stack.startPausingLocked(userLeaving, false /* uiSleeping*/,
1061 resuming);
1062 }
1063 }
1064 return someActivityPaused;
1065 }
1066
1067 /**
1068 * Find task for putting the Activity in.
1069 */
Andrii Kulian1cb59dd2020-04-10 12:17:17 -07001070 void findTaskLocked(final ActivityRecord r, final boolean isPreferredDisplayArea,
Andrii Kulian9ea12da2020-03-27 17:16:38 -07001071 RootWindowContainer.FindTaskResult result) {
1072 mTmpFindTaskResult.clear();
1073 for (int stackNdx = getStackCount() - 1; stackNdx >= 0; --stackNdx) {
1074 final ActivityStack stack = getStackAt(stackNdx);
1075 if (!r.hasCompatibleActivityType(stack) && stack.isLeafTask()) {
1076 if (DEBUG_TASKS) {
1077 Slog.d(TAG_TASKS, "Skipping stack: (mismatch activity/stack) " + stack);
1078 }
1079 continue;
1080 }
1081
1082 mTmpFindTaskResult.process(r, stack);
1083 // It is possible to have tasks in multiple stacks with the same root affinity, so
1084 // we should keep looking after finding an affinity match to see if there is a
1085 // better match in another stack. Also, task affinity isn't a good enough reason
1086 // to target a display which isn't the source of the intent, so skip any affinity
1087 // matches not on the specified display.
1088 if (mTmpFindTaskResult.mRecord != null) {
1089 if (mTmpFindTaskResult.mIdealMatch) {
1090 result.setTo(mTmpFindTaskResult);
1091 return;
Andrii Kulian1cb59dd2020-04-10 12:17:17 -07001092 } else if (isPreferredDisplayArea) {
Andrii Kulian9ea12da2020-03-27 17:16:38 -07001093 // Note: since the traversing through the stacks is top down, the floating
1094 // tasks should always have lower priority than any affinity-matching tasks
1095 // in the fullscreen stacks
1096 result.setTo(mTmpFindTaskResult);
1097 }
1098 }
1099 }
1100 }
1101
1102 /**
1103 * Removes stacks in the input windowing modes from the system if they are of activity type
1104 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
1105 */
1106 void removeStacksInWindowingModes(int... windowingModes) {
1107 if (windowingModes == null || windowingModes.length == 0) {
1108 return;
1109 }
1110
1111 // Collect the stacks that are necessary to be removed instead of performing the removal
1112 // by looping mStacks, so that we don't miss any stacks after the stack size changed or
1113 // stacks reordered.
1114 final ArrayList<ActivityStack> stacks = new ArrayList<>();
1115 for (int j = windowingModes.length - 1; j >= 0; --j) {
1116 final int windowingMode = windowingModes[j];
1117 for (int i = getStackCount() - 1; i >= 0; --i) {
1118 final ActivityStack stack = getStackAt(i);
1119 if (!stack.isActivityTypeStandardOrUndefined()) {
1120 continue;
1121 }
1122 if (stack.getWindowingMode() != windowingMode) {
1123 continue;
1124 }
1125 stacks.add(stack);
1126 }
1127 }
1128
1129 for (int i = stacks.size() - 1; i >= 0; --i) {
1130 mRootWindowContainer.mStackSupervisor.removeStack(stacks.get(i));
1131 }
1132 }
1133
1134 void removeStacksWithActivityTypes(int... activityTypes) {
1135 if (activityTypes == null || activityTypes.length == 0) {
1136 return;
1137 }
1138
1139 // Collect the stacks that are necessary to be removed instead of performing the removal
1140 // by looping mStacks, so that we don't miss any stacks after the stack size changed or
1141 // stacks reordered.
1142 final ArrayList<ActivityStack> stacks = new ArrayList<>();
1143 for (int j = activityTypes.length - 1; j >= 0; --j) {
1144 final int activityType = activityTypes[j];
1145 for (int i = getStackCount() - 1; i >= 0; --i) {
1146 final ActivityStack stack = getStackAt(i);
1147 // Collect the root tasks that are currently being organized.
Evan Rosky50ea8c12020-04-02 20:49:05 -07001148 if (stack.mCreatedByOrganizer) {
Andrii Kulian9ea12da2020-03-27 17:16:38 -07001149 for (int k = stack.getChildCount() - 1; k >= 0; --k) {
1150 final ActivityStack childStack = (ActivityStack) stack.getChildAt(k);
1151 if (childStack.getActivityType() == activityType) {
1152 stacks.add(childStack);
1153 }
1154 }
1155 } else if (stack.getActivityType() == activityType) {
1156 stacks.add(stack);
1157 }
1158 }
1159 }
1160
1161 for (int i = stacks.size() - 1; i >= 0; --i) {
1162 mRootWindowContainer.mStackSupervisor.removeStack(stacks.get(i));
1163 }
1164 }
1165
1166 void onSplitScreenModeDismissed() {
Wale Ogunwalefbb81c92020-04-09 18:01:24 -07001167 onSplitScreenModeDismissed(null /* toTop */);
1168 }
1169
1170 void onSplitScreenModeDismissed(ActivityStack toTop) {
Andrii Kulian9ea12da2020-03-27 17:16:38 -07001171 mAtmService.deferWindowLayout();
1172 try {
1173 mLaunchRootTask = null;
1174 moveSplitScreenTasksToFullScreen();
1175 } finally {
Wale Ogunwalefbb81c92020-04-09 18:01:24 -07001176 final ActivityStack topFullscreenStack = toTop != null
1177 ? toTop : getTopStackInWindowingMode(WINDOWING_MODE_FULLSCREEN);
Andrii Kulian9ea12da2020-03-27 17:16:38 -07001178 final ActivityStack homeStack = getOrCreateRootHomeTask();
Wale Ogunwalefbb81c92020-04-09 18:01:24 -07001179 if (homeStack != null && ((topFullscreenStack != null && !isTopStack(homeStack))
1180 || toTop != null)) {
Andrii Kulian9ea12da2020-03-27 17:16:38 -07001181 // Whenever split-screen is dismissed we want the home stack directly behind the
1182 // current top fullscreen stack so it shows up when the top stack is finished.
Wale Ogunwalefbb81c92020-04-09 18:01:24 -07001183 // Or, if the caller specified a stack to be on top after split-screen is dismissed.
Andrii Kulian9ea12da2020-03-27 17:16:38 -07001184 // TODO: Would be better to use ActivityDisplay.positionChildAt() for this, however
1185 // ActivityDisplay doesn't have a direct controller to WM side yet. We can switch
1186 // once we have that.
1187 homeStack.moveToFront("onSplitScreenModeDismissed");
1188 topFullscreenStack.moveToFront("onSplitScreenModeDismissed");
1189 }
1190 mAtmService.continueWindowLayout();
1191 }
1192 }
1193
1194 private void moveSplitScreenTasksToFullScreen() {
1195 final WindowContainerTransaction wct = new WindowContainerTransaction();
1196 mTmpTasks.clear();
1197 forAllTasks(task -> {
1198 if (task.mCreatedByOrganizer && task.inSplitScreenWindowingMode() && task.hasChild()) {
1199 mTmpTasks.add(task);
1200 }
1201 });
1202
1203 for (int i = mTmpTasks.size() - 1; i >= 0; i--) {
1204 final Task root = mTmpTasks.get(i);
1205 for (int j = 0; j < root.getChildCount(); j++) {
Wale Ogunwaleadf116e2020-03-27 16:36:01 -07001206 wct.reparent(root.getChildAt(j).mRemoteToken.toWindowContainerToken(),
1207 null, true /* toTop */);
Andrii Kulian9ea12da2020-03-27 17:16:38 -07001208 }
1209 }
1210 mAtmService.mWindowOrganizerController.applyTransaction(wct);
1211 }
1212
1213 /**
1214 * Returns true if the {@param windowingMode} is supported based on other parameters passed in.
1215 * @param windowingMode The windowing mode we are checking support for.
1216 * @param supportsMultiWindow If we should consider support for multi-window mode in general.
1217 * @param supportsSplitScreen If we should consider support for split-screen multi-window.
1218 * @param supportsFreeform If we should consider support for freeform multi-window.
1219 * @param supportsPip If we should consider support for picture-in-picture mutli-window.
1220 * @param activityType The activity type under consideration.
1221 * @return true if the windowing mode is supported.
1222 */
1223 private boolean isWindowingModeSupported(int windowingMode, boolean supportsMultiWindow,
1224 boolean supportsSplitScreen, boolean supportsFreeform, boolean supportsPip,
1225 int activityType) {
1226
1227 if (windowingMode == WINDOWING_MODE_UNDEFINED
1228 || windowingMode == WINDOWING_MODE_FULLSCREEN) {
1229 return true;
1230 }
1231 if (!supportsMultiWindow) {
1232 return false;
1233 }
1234
1235 if (windowingMode == WINDOWING_MODE_MULTI_WINDOW) {
1236 return true;
1237 }
1238
1239 final int displayWindowingMode = getWindowingMode();
1240 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY
1241 || windowingMode == WINDOWING_MODE_SPLIT_SCREEN_SECONDARY) {
1242 return supportsSplitScreen
1243 && WindowConfiguration.supportSplitScreenWindowingMode(activityType)
1244 // Freeform windows and split-screen windows don't mix well, so prevent
1245 // split windowing modes on freeform displays.
1246 && displayWindowingMode != WINDOWING_MODE_FREEFORM;
1247 }
1248
1249 if (!supportsFreeform && windowingMode == WINDOWING_MODE_FREEFORM) {
1250 return false;
1251 }
1252
1253 if (!supportsPip && windowingMode == WINDOWING_MODE_PINNED) {
1254 return false;
1255 }
1256 return true;
1257 }
1258
1259 /**
1260 * Resolves the windowing mode that an {@link ActivityRecord} would be in if started on this
1261 * display with the provided parameters.
1262 *
1263 * @param r The ActivityRecord in question.
1264 * @param options Options to start with.
1265 * @param task The task within-which the activity would start.
1266 * @param activityType The type of activity to start.
1267 * @return The resolved (not UNDEFINED) windowing-mode that the activity would be in.
1268 */
1269 int resolveWindowingMode(@Nullable ActivityRecord r, @Nullable ActivityOptions options,
1270 @Nullable Task task, int activityType) {
1271
1272 // First preference if the windowing mode in the activity options if set.
1273 int windowingMode = (options != null)
1274 ? options.getLaunchWindowingMode() : WINDOWING_MODE_UNDEFINED;
1275
1276 // If windowing mode is unset, then next preference is the candidate task, then the
1277 // activity record.
1278 if (windowingMode == WINDOWING_MODE_UNDEFINED) {
1279 if (task != null) {
1280 windowingMode = task.getWindowingMode();
1281 }
1282 if (windowingMode == WINDOWING_MODE_UNDEFINED && r != null) {
1283 windowingMode = r.getWindowingMode();
1284 }
1285 if (windowingMode == WINDOWING_MODE_UNDEFINED) {
1286 // Use the display's windowing mode.
1287 windowingMode = getWindowingMode();
1288 }
1289 }
1290 windowingMode = validateWindowingMode(windowingMode, r, task, activityType);
1291 return windowingMode != WINDOWING_MODE_UNDEFINED
1292 ? windowingMode : WINDOWING_MODE_FULLSCREEN;
1293 }
1294
1295 /**
1296 * Check that the requested windowing-mode is appropriate for the specified task and/or activity
1297 * on this display.
1298 *
1299 * @param windowingMode The windowing-mode to validate.
1300 * @param r The {@link ActivityRecord} to check against.
1301 * @param task The {@link Task} to check against.
1302 * @param activityType An activity type.
1303 * @return The provided windowingMode or the closest valid mode which is appropriate.
1304 */
1305 int validateWindowingMode(int windowingMode, @Nullable ActivityRecord r, @Nullable Task task,
1306 int activityType) {
1307 // Make sure the windowing mode we are trying to use makes sense for what is supported.
1308 boolean supportsMultiWindow = mAtmService.mSupportsMultiWindow;
1309 boolean supportsSplitScreen = mAtmService.mSupportsSplitScreenMultiWindow;
1310 boolean supportsFreeform = mAtmService.mSupportsFreeformWindowManagement;
1311 boolean supportsPip = mAtmService.mSupportsPictureInPicture;
1312 if (supportsMultiWindow) {
1313 if (task != null) {
1314 supportsMultiWindow = task.isResizeable();
1315 supportsSplitScreen = task.supportsSplitScreenWindowingMode();
1316 // TODO: Do we need to check for freeform and Pip support here?
1317 } else if (r != null) {
1318 supportsMultiWindow = r.isResizeable();
1319 supportsSplitScreen = r.supportsSplitScreenWindowingMode();
1320 supportsFreeform = r.supportsFreeform();
1321 supportsPip = r.supportsPictureInPicture();
1322 }
1323 }
1324
1325 final boolean inSplitScreenMode = isSplitScreenModeActivated();
1326 if (!inSplitScreenMode
1327 && windowingMode == WINDOWING_MODE_FULLSCREEN_OR_SPLIT_SCREEN_SECONDARY) {
1328 // Switch to the display's windowing mode if we are not in split-screen mode and we are
1329 // trying to launch in split-screen secondary.
1330 windowingMode = WINDOWING_MODE_UNDEFINED;
1331 } else if (inSplitScreenMode && (windowingMode == WINDOWING_MODE_FULLSCREEN
1332 || windowingMode == WINDOWING_MODE_UNDEFINED)
1333 && supportsSplitScreen) {
1334 windowingMode = WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
1335 }
1336
1337 if (windowingMode != WINDOWING_MODE_UNDEFINED
1338 && isWindowingModeSupported(windowingMode, supportsMultiWindow, supportsSplitScreen,
1339 supportsFreeform, supportsPip, activityType)) {
1340 return windowingMode;
1341 }
1342 return WINDOWING_MODE_UNDEFINED;
1343 }
1344
1345 boolean isTopStack(ActivityStack stack) {
1346 return stack == getTopStack();
1347 }
1348
1349 boolean isTopNotPinnedStack(ActivityStack stack) {
1350 for (int i = getStackCount() - 1; i >= 0; --i) {
1351 final ActivityStack current = getStackAt(i);
1352 if (!current.inPinnedWindowingMode()) {
1353 return current == stack;
1354 }
1355 }
1356 return false;
1357 }
1358
Andrii Kulian86d676c2020-03-27 19:34:54 -07001359 ActivityRecord topRunningActivity() {
1360 return topRunningActivity(false /* considerKeyguardState */);
1361 }
1362
Andrii Kulian9ea12da2020-03-27 17:16:38 -07001363 /**
1364 * Returns the top running activity in the focused stack. In the case the focused stack has no
1365 * such activity, the next focusable stack on this display is returned.
1366 *
1367 * @param considerKeyguardState Indicates whether the locked state should be considered. if
1368 * {@code true} and the keyguard is locked, only activities that
1369 * can be shown on top of the keyguard will be considered.
1370 * @return The top running activity. {@code null} if none is available.
1371 */
1372 ActivityRecord topRunningActivity(boolean considerKeyguardState) {
1373 ActivityRecord topRunning = null;
1374 final ActivityStack focusedStack = getFocusedStack();
1375 if (focusedStack != null) {
1376 topRunning = focusedStack.topRunningActivity();
1377 }
1378
1379 // Look in other focusable stacks.
1380 if (topRunning == null) {
1381 for (int i = getStackCount() - 1; i >= 0; --i) {
1382 final ActivityStack stack = getStackAt(i);
1383 // Only consider focusable stacks other than the current focused one.
1384 if (stack == focusedStack || !stack.isTopActivityFocusable()) {
1385 continue;
1386 }
1387 topRunning = stack.topRunningActivity();
1388 if (topRunning != null) {
1389 break;
1390 }
1391 }
1392 }
1393
1394 // This activity can be considered the top running activity if we are not considering
1395 // the locked state, the keyguard isn't locked, or we can show when locked.
1396 if (topRunning != null && considerKeyguardState
1397 && mRootWindowContainer.mStackSupervisor.getKeyguardController()
1398 .isKeyguardLocked()
1399 && !topRunning.canShowWhenLocked()) {
1400 return null;
1401 }
1402
1403 return topRunning;
1404 }
1405
1406 protected int getStackCount() {
1407 return mChildren.size();
1408 }
1409
1410 protected ActivityStack getStackAt(int index) {
1411 return mChildren.get(index);
1412 }
1413
1414 /**
1415 * Returns the existing home stack or creates and returns a new one if it should exist for the
1416 * display.
1417 */
1418 @Nullable
1419 ActivityStack getOrCreateRootHomeTask() {
1420 ActivityStack homeTask = getRootHomeTask();
1421 if (homeTask == null && mDisplayContent.supportsSystemDecorations()
1422 && !mDisplayContent.isUntrustedVirtualDisplay()) {
Louis Changdff902b2020-03-31 13:32:47 +08001423 homeTask = createStack(WINDOWING_MODE_UNDEFINED, ACTIVITY_TYPE_HOME, false /* onTop */);
Andrii Kulian9ea12da2020-03-27 17:16:38 -07001424 }
1425 return homeTask;
1426 }
1427
1428 boolean isSplitScreenModeActivated() {
1429 Task task = getRootSplitScreenPrimaryTask();
1430 return task != null && task.hasChild();
1431 }
1432
1433 /**
1434 * Returns the topmost stack on the display that is compatible with the input windowing mode.
1435 * Null is no compatible stack on the display.
1436 */
1437 ActivityStack getTopStackInWindowingMode(int windowingMode) {
1438 return getStack(windowingMode, ACTIVITY_TYPE_UNDEFINED);
1439 }
1440
1441 void moveHomeStackToFront(String reason) {
1442 final ActivityStack homeStack = getOrCreateRootHomeTask();
1443 if (homeStack != null) {
1444 homeStack.moveToFront(reason);
1445 }
1446 }
1447
1448 /**
1449 * Moves the focusable home activity to top. If there is no such activity, the home stack will
1450 * still move to top.
1451 */
1452 void moveHomeActivityToTop(String reason) {
1453 final ActivityRecord top = getHomeActivity();
1454 if (top == null) {
1455 moveHomeStackToFront(reason);
1456 return;
1457 }
1458 top.moveFocusableActivityToTop(reason);
1459 }
1460
1461 @Nullable
1462 ActivityRecord getHomeActivity() {
1463 return getHomeActivityForUser(mRootWindowContainer.mCurrentUser);
1464 }
1465
1466 @Nullable
1467 ActivityRecord getHomeActivityForUser(int userId) {
1468 final ActivityStack homeStack = getRootHomeTask();
1469 if (homeStack == null) {
1470 return null;
1471 }
1472
1473 final PooledPredicate p = PooledLambda.obtainPredicate(
Andrii Kulian86d676c2020-03-27 19:34:54 -07001474 TaskDisplayArea::isHomeActivityForUser, PooledLambda.__(ActivityRecord.class),
Andrii Kulian9ea12da2020-03-27 17:16:38 -07001475 userId);
1476 final ActivityRecord r = homeStack.getActivity(p);
1477 p.recycle();
1478 return r;
1479 }
1480
1481 private static boolean isHomeActivityForUser(ActivityRecord r, int userId) {
1482 return r.isActivityTypeHome() && (userId == UserHandle.USER_ALL || r.mUserId == userId);
1483 }
1484
1485 /**
1486 * Adjusts the {@param stack} behind the last visible stack in the display if necessary.
1487 * Generally used in conjunction with {@link #moveStackBehindStack}.
1488 */
1489 // TODO(b/151575894): Remove special stack movement methods.
1490 void moveStackBehindBottomMostVisibleStack(ActivityStack stack) {
1491 if (stack.shouldBeVisible(null)) {
1492 // Skip if the stack is already visible
1493 return;
1494 }
1495
1496 final boolean isRootTask = stack.isRootTask();
1497 if (isRootTask) {
1498 // Move the stack to the bottom to not affect the following visibility checks
1499 positionStackAtBottom(stack);
1500 } else {
1501 stack.getParent().positionChildAt(POSITION_BOTTOM, stack, false /* includingParents */);
1502 }
1503
1504 // Find the next position where the stack should be placed
1505 final int numStacks = isRootTask ? getStackCount() : stack.getParent().getChildCount();
1506 for (int stackNdx = 0; stackNdx < numStacks; stackNdx++) {
1507 final ActivityStack s = isRootTask ? getStackAt(stackNdx)
1508 : (ActivityStack) stack.getParent().getChildAt(stackNdx);
1509 if (s == stack) {
1510 continue;
1511 }
1512 final int winMode = s.getWindowingMode();
1513 final boolean isValidWindowingMode = winMode == WINDOWING_MODE_FULLSCREEN
1514 || winMode == WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
1515 if (s.shouldBeVisible(null) && isValidWindowingMode) {
1516 // Move the provided stack to behind this stack
1517 final int position = Math.max(0, stackNdx - 1);
1518 if (isRootTask) {
1519 positionStackAt(stack, position);
1520 } else {
1521 stack.getParent().positionChildAt(position, stack, false /*includingParents */);
1522 }
1523 break;
1524 }
1525 }
1526 }
1527
1528 /**
1529 * Moves the {@param stack} behind the given {@param behindStack} if possible. If
1530 * {@param behindStack} is not currently in the display, then then the stack is moved to the
1531 * back. Generally used in conjunction with {@link #moveStackBehindBottomMostVisibleStack}.
1532 */
1533 void moveStackBehindStack(ActivityStack stack, ActivityStack behindStack) {
1534 if (behindStack == null || behindStack == stack) {
1535 return;
1536 }
1537
1538 final WindowContainer parent = stack.getParent();
1539 if (parent == null || parent != behindStack.getParent()) {
1540 return;
1541 }
1542
1543 // Note that positionChildAt will first remove the given stack before inserting into the
1544 // list, so we need to adjust the insertion index to account for the removed index
1545 // TODO: Remove this logic when WindowContainer.positionChildAt() is updated to adjust the
1546 // position internally
1547 final int stackIndex = parent.mChildren.indexOf(stack);
1548 final int behindStackIndex = parent.mChildren.indexOf(behindStack);
1549 final int insertIndex = stackIndex <= behindStackIndex
1550 ? behindStackIndex - 1 : behindStackIndex;
1551 final int position = Math.max(0, insertIndex);
1552 if (stack.isRootTask()) {
1553 positionStackAt(stack, position);
1554 } else {
1555 parent.positionChildAt(position, stack, false /* includingParents */);
1556 }
1557 }
Andrii Kulian86d676c2020-03-27 19:34:54 -07001558
1559 boolean hasPinnedTask() {
1560 return getRootPinnedTask() != null;
1561 }
1562
1563 /**
1564 * @return the stack currently above the {@param stack}. Can be null if the {@param stack} is
1565 * already top-most.
1566 */
1567 static ActivityStack getStackAbove(ActivityStack stack) {
1568 final WindowContainer wc = stack.getParent();
1569 final int index = wc.mChildren.indexOf(stack) + 1;
1570 return (index < wc.mChildren.size()) ? (ActivityStack) wc.mChildren.get(index) : null;
1571 }
1572
Andrii Kulian4c0fd0d2020-03-29 13:32:14 -07001573 /** Returns true if the stack in the windowing mode is visible. */
1574 boolean isStackVisible(int windowingMode) {
1575 final ActivityStack stack = getTopStackInWindowingMode(windowingMode);
1576 return stack != null && stack.isVisible();
1577 }
1578
1579 void removeStack(ActivityStack stack) {
1580 removeChild(stack);
1581 }
1582
Andrii Kulian86d676c2020-03-27 19:34:54 -07001583 int getDisplayId() {
1584 return mDisplayContent.getDisplayId();
1585 }
1586
1587 boolean isRemoved() {
Andrii Kulianf9df4a82020-03-31 12:09:27 -07001588 return mRemoved;
Andrii Kulian86d676c2020-03-27 19:34:54 -07001589 }
Andrii Kulian4c0fd0d2020-03-29 13:32:14 -07001590
1591 /**
1592 * Adds a listener to be notified whenever the stack order in the display changes. Currently
1593 * only used by the {@link RecentsAnimation} to determine whether to interrupt and cancel the
1594 * current animation when the system state changes.
1595 */
1596 void registerStackOrderChangedListener(OnStackOrderChangedListener listener) {
1597 if (!mStackOrderChangedCallbacks.contains(listener)) {
1598 mStackOrderChangedCallbacks.add(listener);
1599 }
1600 }
1601
1602 /**
1603 * Removes a previously registered stack order change listener.
1604 */
1605 void unregisterStackOrderChangedListener(OnStackOrderChangedListener listener) {
1606 mStackOrderChangedCallbacks.remove(listener);
1607 }
1608
1609 /**
1610 * Notifies of a stack order change
1611 * @param stack The stack which triggered the order change
1612 */
1613 void onStackOrderChanged(ActivityStack stack) {
1614 for (int i = mStackOrderChangedCallbacks.size() - 1; i >= 0; i--) {
1615 mStackOrderChangedCallbacks.get(i).onStackOrderChanged(stack);
1616 }
1617 }
1618
Evan Rosky0ad8d2c2020-03-16 12:09:58 -07001619 @Override
1620 boolean canCreateRemoteAnimationTarget() {
1621 return true;
1622 }
1623
Andrii Kulian4c0fd0d2020-03-29 13:32:14 -07001624 /**
1625 * Callback for when the order of the stacks in the display changes.
1626 */
1627 interface OnStackOrderChangedListener {
1628 void onStackOrderChanged(ActivityStack stack);
1629 }
Andrii Kulianf9df4a82020-03-31 12:09:27 -07001630
1631 void ensureActivitiesVisible(ActivityRecord starting, int configChanges,
1632 boolean preserveWindows, boolean notifyClients) {
1633 for (int stackNdx = getStackCount() - 1; stackNdx >= 0; --stackNdx) {
1634 final ActivityStack stack = getStackAt(stackNdx);
1635 stack.ensureActivitiesVisible(starting, configChanges, preserveWindows,
1636 notifyClients);
1637 }
1638 }
1639
1640 void prepareFreezingTaskBounds() {
1641 for (int stackNdx = getChildCount() - 1; stackNdx >= 0; --stackNdx) {
1642 final ActivityStack stack = getChildAt(stackNdx);
1643 stack.prepareFreezingTaskBounds();
1644 }
1645 }
1646
1647 /**
1648 * Removes the stacks in the node applying the content removal node from the display.
1649 * @return last reparented stack, or {@code null} if the stacks had to be destroyed.
1650 */
1651 ActivityStack remove() {
1652 mPreferredTopFocusableStack = null;
1653 // TODO(b/153090332): Allow setting content removal mode per task display area
1654 final boolean destroyContentOnRemoval = mDisplayContent.shouldDestroyContentOnRemove();
1655 final TaskDisplayArea toDisplayArea = mRootWindowContainer.getDefaultTaskDisplayArea();
1656 ActivityStack lastReparentedStack = null;
1657
1658 // Stacks could be reparented from the removed display area to other display area. After
1659 // reparenting the last stack of the removed display area, the display area becomes ready to
1660 // be released (no more ActivityStack-s). But, we cannot release it at that moment or the
1661 // related WindowContainer will also be removed. So, we set display area as removed after
1662 // reparenting stack finished.
1663 // Keep the order from bottom to top.
1664 int numStacks = getStackCount();
1665 for (int stackNdx = 0; stackNdx < numStacks; stackNdx++) {
1666 final ActivityStack stack = getStackAt(stackNdx);
1667 // Always finish non-standard type stacks.
1668 if (destroyContentOnRemoval || !stack.isActivityTypeStandardOrUndefined()) {
1669 stack.finishAllActivitiesImmediately();
1670 } else {
1671 // If default display is in split-window mode, set windowing mode of the
1672 // stack to split-screen secondary. Otherwise, set the windowing mode to
1673 // undefined by default to let stack inherited the windowing mode from the
1674 // new display.
1675 final int windowingMode = toDisplayArea.isSplitScreenModeActivated()
1676 ? WINDOWING_MODE_SPLIT_SCREEN_SECONDARY
1677 : WINDOWING_MODE_UNDEFINED;
1678 stack.reparent(toDisplayArea, true /* onTop */);
1679 stack.setWindowingMode(windowingMode);
1680 lastReparentedStack = stack;
1681 }
1682 // Stacks may be removed from this display. Ensure each stack will be processed
1683 // and the loop will end.
1684 stackNdx -= numStacks - getStackCount();
1685 numStacks = getStackCount();
1686 }
1687 mRemoved = true;
1688
1689 return lastReparentedStack;
1690 }
1691
1692
1693 @Override
1694 void dump(PrintWriter pw, String prefix, boolean dumpAll) {
1695 pw.println(prefix + "TaskDisplayArea " + getName());
1696 if (mPreferredTopFocusableStack != null) {
1697 pw.println(prefix + " mPreferredTopFocusableStack=" + mPreferredTopFocusableStack);
1698 }
1699 if (mLastFocusedStack != null) {
1700 pw.println(prefix + " mLastFocusedStack=" + mLastFocusedStack);
1701 }
1702 pw.println(prefix + " Application tokens in top down Z order:");
1703 for (int stackNdx = getChildCount() - 1; stackNdx >= 0; --stackNdx) {
1704 final ActivityStack stack = getChildAt(stackNdx);
1705 stack.dump(pw, prefix + " ", dumpAll);
1706 }
1707 }
Andrii Kulian526ad432020-03-27 12:19:51 -07001708}