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