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