blob: 540bc9bbf997a8d13f0c12930b3f58f4ac9c6670 [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;
34import static android.window.WindowOrganizer.DisplayAreaOrganizer.FEATURE_TASK_CONTAINER;
35
Andrii Kulian9ea12da2020-03-27 17:16:38 -070036import static com.android.server.wm.ActivityStack.ActivityState.RESUMED;
37import static com.android.server.wm.ActivityStack.STACK_VISIBILITY_VISIBLE;
38import static com.android.server.wm.ActivityStackSupervisor.TAG_TASKS;
39import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STATES;
40import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
41import static com.android.server.wm.ActivityTaskManagerService.TAG_STACK;
42import static com.android.server.wm.DisplayContent.alwaysCreateStack;
Andrii Kulian526ad432020-03-27 12:19:51 -070043import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_ADD_REMOVE;
44import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_ORIENTATION;
Andrii Kulian9ea12da2020-03-27 17:16:38 -070045import static com.android.server.wm.RootWindowContainer.TAG_STATES;
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
65import java.util.ArrayList;
66import java.util.List;
67
68/**
69 * Window container class that contains all containers on this display relating to Apps.
70 * I.e Activities.
71 */
72final class TaskContainers extends DisplayArea<ActivityStack> {
73 private DisplayContent mDisplayContent;
74 /**
75 * A control placed at the appropriate level for transitions to occur.
76 */
77 private SurfaceControl mAppAnimationLayer;
78 private SurfaceControl mBoostedAppAnimationLayer;
79 private SurfaceControl mHomeAppAnimationLayer;
80
81 /**
82 * Given that the split-screen divider does not have an AppWindowToken, it
83 * will have to live inside of a "NonAppWindowContainer". However, in visual Z order
84 * it will need to be interleaved with some of our children, appearing on top of
85 * both docked stacks but underneath any assistant stacks.
86 *
87 * To solve this problem we have this anchor control, which will always exist so
88 * we can always assign it the correct value in our {@link #assignChildLayers}.
89 * Likewise since it always exists, we can always
90 * assign the divider a layer relative to it. This way we prevent linking lifecycle
91 * events between tasks and the divider window.
92 */
93 private SurfaceControl mSplitScreenDividerAnchor;
94
95 // Cached reference to some special tasks we tend to get a lot so we don't need to loop
96 // through the list to find them.
97 private ActivityStack mRootHomeTask;
98 private ActivityStack mRootPinnedTask;
99 private ActivityStack mRootSplitScreenPrimaryTask;
100
101 private final ArrayList<ActivityStack> mTmpAlwaysOnTopStacks = new ArrayList<>();
102 private final ArrayList<ActivityStack> mTmpNormalStacks = new ArrayList<>();
103 private final ArrayList<ActivityStack> mTmpHomeStacks = new ArrayList<>();
104
Andrii Kulian9ea12da2020-03-27 17:16:38 -0700105 private ArrayList<Task> mTmpTasks = new ArrayList<>();
106
107 private ActivityTaskManagerService mAtmService;
108
109 private RootWindowContainer mRootWindowContainer;
110
111 // When non-null, new tasks get put into this root task.
112 private Task mLaunchRootTask = null;
113
114 /**
115 * A focusable stack that is purposely to be positioned at the top. Although the stack may not
116 * have the topmost index, it is used as a preferred candidate to prevent being unable to resume
117 * target stack properly when there are other focusable always-on-top stacks.
118 */
119 private ActivityStack mPreferredTopFocusableStack;
120
121 private final RootWindowContainer.FindTaskResult
122 mTmpFindTaskResult = new RootWindowContainer.FindTaskResult();
123
124 /**
125 * If this is the same as {@link #getFocusedStack} then the activity on the top of the focused
126 * stack has been resumed. If stacks are changing position this will hold the old stack until
127 * the new stack becomes resumed after which it will be set to current focused stack.
128 */
129 ActivityStack mLastFocusedStack;
130
Andrii Kulian526ad432020-03-27 12:19:51 -0700131 TaskContainers(DisplayContent displayContent, WindowManagerService service) {
132 super(service, Type.ANY, "TaskContainers", FEATURE_TASK_CONTAINER);
133 mDisplayContent = displayContent;
Andrii Kulian9ea12da2020-03-27 17:16:38 -0700134 mRootWindowContainer = service.mRoot;
135 mAtmService = service.mAtmService;
Andrii Kulian526ad432020-03-27 12:19:51 -0700136 }
137
138 /**
139 * Returns the topmost stack on the display that is compatible with the input windowing mode
140 * and activity type. Null is no compatible stack on the display.
141 */
142 ActivityStack getStack(int windowingMode, int activityType) {
143 if (activityType == ACTIVITY_TYPE_HOME) {
144 return mRootHomeTask;
145 }
146 if (windowingMode == WINDOWING_MODE_PINNED) {
147 return mRootPinnedTask;
148 } else if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
149 return mRootSplitScreenPrimaryTask;
150 }
151 for (int i = getChildCount() - 1; i >= 0; --i) {
152 final ActivityStack stack = getChildAt(i);
153 if (activityType == ACTIVITY_TYPE_UNDEFINED
154 && windowingMode == stack.getWindowingMode()) {
155 // Passing in undefined type means we want to match the topmost stack with the
156 // windowing mode.
157 return stack;
158 }
159 if (stack.isCompatible(windowingMode, activityType)) {
160 return stack;
161 }
162 }
163 return null;
164 }
165
166 @VisibleForTesting
167 ActivityStack getTopStack() {
168 final int count = getChildCount();
169 return count > 0 ? getChildAt(count - 1) : null;
170 }
171
172 int getIndexOf(ActivityStack stack) {
173 return mChildren.indexOf(stack);
174 }
175
176 ActivityStack getRootHomeTask() {
177 return mRootHomeTask;
178 }
179
180 ActivityStack getRootPinnedTask() {
181 return mRootPinnedTask;
182 }
183
184 ActivityStack getRootSplitScreenPrimaryTask() {
185 return mRootSplitScreenPrimaryTask;
186 }
187
188 ArrayList<Task> getVisibleTasks() {
189 final ArrayList<Task> visibleTasks = new ArrayList<>();
190 forAllTasks(task -> {
191 if (task.isLeafTask() && task.isVisible()) {
192 visibleTasks.add(task);
193 }
194 });
195 return visibleTasks;
196 }
197
198 void onStackWindowingModeChanged(ActivityStack stack) {
199 removeStackReferenceIfNeeded(stack);
200 addStackReferenceIfNeeded(stack);
201 if (stack == mRootPinnedTask && getTopStack() != stack) {
202 // Looks like this stack changed windowing mode to pinned. Move it to the top.
203 positionChildAt(POSITION_TOP, stack, false /* includingParents */);
204 }
205 }
206
207 void addStackReferenceIfNeeded(ActivityStack stack) {
208 if (stack.isActivityTypeHome()) {
209 if (mRootHomeTask != null) {
210 if (!stack.isDescendantOf(mRootHomeTask)) {
211 throw new IllegalArgumentException("addStackReferenceIfNeeded: home stack="
212 + mRootHomeTask + " already exist on display=" + this
213 + " stack=" + stack);
214 }
215 } else {
216 mRootHomeTask = stack;
217 }
218 }
219
220 if (!stack.isRootTask()) {
221 return;
222 }
223 final int windowingMode = stack.getWindowingMode();
224 if (windowingMode == WINDOWING_MODE_PINNED) {
225 if (mRootPinnedTask != null) {
226 throw new IllegalArgumentException(
227 "addStackReferenceIfNeeded: pinned stack=" + mRootPinnedTask
228 + " already exist on display=" + this + " stack=" + stack);
229 }
230 mRootPinnedTask = stack;
231 } else if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
232 if (mRootSplitScreenPrimaryTask != null) {
233 throw new IllegalArgumentException(
234 "addStackReferenceIfNeeded: split screen primary stack="
235 + mRootSplitScreenPrimaryTask
236 + " already exist on display=" + this + " stack=" + stack);
237 }
238 mRootSplitScreenPrimaryTask = stack;
239 }
240 }
241
242 void removeStackReferenceIfNeeded(ActivityStack stack) {
243 if (stack == mRootHomeTask) {
244 mRootHomeTask = null;
245 } else if (stack == mRootPinnedTask) {
246 mRootPinnedTask = null;
247 } else if (stack == mRootSplitScreenPrimaryTask) {
248 mRootSplitScreenPrimaryTask = null;
249 }
250 }
251
252 @Override
253 void addChild(ActivityStack stack, int position) {
254 addStackReferenceIfNeeded(stack);
255 position = findPositionForStack(position, stack, true /* adding */);
256
257 super.addChild(stack, position);
Andrii Kulian9ea12da2020-03-27 17:16:38 -0700258 mAtmService.updateSleepIfNeededLocked();
Andrii Kulian526ad432020-03-27 12:19:51 -0700259
260 // The reparenting case is handled in WindowContainer.
261 if (!stack.mReparenting) {
262 mDisplayContent.setLayoutNeeded();
263 }
264 }
265
266 @Override
267 protected void removeChild(ActivityStack stack) {
268 super.removeChild(stack);
Andrii Kulian9ea12da2020-03-27 17:16:38 -0700269 onStackRemoved(stack);
270 mAtmService.updateSleepIfNeededLocked();
Andrii Kulian526ad432020-03-27 12:19:51 -0700271 removeStackReferenceIfNeeded(stack);
272 }
273
274 @Override
275 boolean isOnTop() {
276 // Considered always on top
277 return true;
278 }
279
280 @Override
281 void positionChildAt(int position, ActivityStack child, boolean includingParents) {
282 final boolean moveToTop = (position == POSITION_TOP || position == getChildCount());
283 final boolean moveToBottom = (position == POSITION_BOTTOM || position == 0);
284 if (child.getWindowConfiguration().isAlwaysOnTop() && !moveToTop) {
285 // This stack is always-on-top, override the default behavior.
286 Slog.w(TAG_WM, "Ignoring move of always-on-top stack=" + this + " to bottom");
287
288 // Moving to its current position, as we must call super but we don't want to
289 // perform any meaningful action.
290 final int currentPosition = mChildren.indexOf(child);
291 super.positionChildAt(currentPosition, child, false /* includingParents */);
292 return;
293 }
294 // We don't allow untrusted display to top when task stack moves to top,
295 // until user tapping this display to change display position as top intentionally.
296 if (mDisplayContent.isUntrustedVirtualDisplay() && !getParent().isOnTop()) {
297 includingParents = false;
298 }
299 final int targetPosition = findPositionForStack(position, child, false /* adding */);
300 super.positionChildAt(targetPosition, child, false /* includingParents */);
301
302 if (includingParents && (moveToTop || moveToBottom)) {
303 // The DisplayContent children do not re-order, but we still want to move the
304 // display of this stack container because the intention of positioning is to have
305 // higher z-order to gain focus.
306 mDisplayContent.positionDisplayAt(moveToTop ? POSITION_TOP : POSITION_BOTTOM,
307 true /* includingParents */);
308 }
309
310 child.updateTaskMovement(moveToTop);
311
312 mDisplayContent.setLayoutNeeded();
313 }
314
315 /**
316 * When stack is added or repositioned, find a proper position for it.
317 * This will make sure that pinned stack always stays on top.
318 * @param requestedPosition Position requested by caller.
319 * @param stack Stack to be added or positioned.
320 * @param adding Flag indicates whether we're adding a new stack or positioning an existing.
321 * @return The proper position for the stack.
322 */
323 private int findPositionForStack(int requestedPosition, ActivityStack stack,
324 boolean adding) {
325 if (stack.isActivityTypeDream()) {
326 return POSITION_TOP;
327 }
328
329 if (stack.inPinnedWindowingMode()) {
330 return POSITION_TOP;
331 }
332
333 final int topChildPosition = mChildren.size() - 1;
334 int belowAlwaysOnTopPosition = POSITION_BOTTOM;
335 for (int i = topChildPosition; i >= 0; --i) {
336 // Since a stack could be repositioned while being one of the child, return
337 // current index if that's the same stack we are positioning and it is always on
338 // top.
339 final boolean sameStack = mDisplayContent.getStacks().get(i) == stack;
340 if ((sameStack && stack.isAlwaysOnTop())
341 || (!sameStack && !mDisplayContent.getStacks().get(i).isAlwaysOnTop())) {
342 belowAlwaysOnTopPosition = i;
343 break;
344 }
345 }
346
347 // The max possible position we can insert the stack at.
348 int maxPosition = POSITION_TOP;
349 // The min possible position we can insert the stack at.
350 int minPosition = POSITION_BOTTOM;
351
352 if (stack.isAlwaysOnTop()) {
353 if (mDisplayContent.hasPinnedTask()) {
354 // Always-on-top stacks go below the pinned stack.
355 maxPosition = mDisplayContent.getStacks().indexOf(mRootPinnedTask) - 1;
356 }
357 // Always-on-top stacks need to be above all other stacks.
358 minPosition = belowAlwaysOnTopPosition
359 != POSITION_BOTTOM ? belowAlwaysOnTopPosition : topChildPosition;
360 } else {
361 // Other stacks need to be below the always-on-top stacks.
362 maxPosition = belowAlwaysOnTopPosition
363 != POSITION_BOTTOM ? belowAlwaysOnTopPosition : 0;
364 }
365
366 // Cap the requested position to something reasonable for the previous position check
367 // below.
368 if (requestedPosition == POSITION_TOP) {
369 requestedPosition = mChildren.size();
370 } else if (requestedPosition == POSITION_BOTTOM) {
371 requestedPosition = 0;
372 }
373
374 int targetPosition = requestedPosition;
375 targetPosition = Math.min(targetPosition, maxPosition);
376 targetPosition = Math.max(targetPosition, minPosition);
377
378 int prevPosition = mDisplayContent.getStacks().indexOf(stack);
379 // The positions we calculated above (maxPosition, minPosition) do not take into
380 // consideration the following edge cases.
381 // 1) We need to adjust the position depending on the value "adding".
382 // 2) When we are moving a stack to another position, we also need to adjust the
383 // position depending on whether the stack is moving to a higher or lower position.
384 if ((targetPosition != requestedPosition) && (adding || targetPosition < prevPosition)) {
385 targetPosition++;
386 }
387
388 return targetPosition;
389 }
390
391 @Override
392 boolean forAllWindows(ToBooleanFunction<WindowState> callback,
393 boolean traverseTopToBottom) {
394 if (traverseTopToBottom) {
395 if (super.forAllWindows(callback, traverseTopToBottom)) {
396 return true;
397 }
398 if (forAllExitingAppTokenWindows(callback, traverseTopToBottom)) {
399 return true;
400 }
401 } else {
402 if (forAllExitingAppTokenWindows(callback, traverseTopToBottom)) {
403 return true;
404 }
405 if (super.forAllWindows(callback, traverseTopToBottom)) {
406 return true;
407 }
408 }
409 return false;
410 }
411
412 private boolean forAllExitingAppTokenWindows(ToBooleanFunction<WindowState> callback,
413 boolean traverseTopToBottom) {
414 // For legacy reasons we process the TaskStack.mExitingActivities first here before the
415 // app tokens.
416 // TODO: Investigate if we need to continue to do this or if we can just process them
417 // in-order.
418 if (traverseTopToBottom) {
419 for (int i = mChildren.size() - 1; i >= 0; --i) {
420 final List<ActivityRecord> activities = mChildren.get(i).mExitingActivities;
421 for (int j = activities.size() - 1; j >= 0; --j) {
422 if (activities.get(j).forAllWindowsUnchecked(callback,
423 traverseTopToBottom)) {
424 return true;
425 }
426 }
427 }
428 } else {
429 final int count = mChildren.size();
430 for (int i = 0; i < count; ++i) {
431 final List<ActivityRecord> activities = mChildren.get(i).mExitingActivities;
432 final int appTokensCount = activities.size();
433 for (int j = 0; j < appTokensCount; j++) {
434 if (activities.get(j).forAllWindowsUnchecked(callback,
435 traverseTopToBottom)) {
436 return true;
437 }
438 }
439 }
440 }
441 return false;
442 }
443
444 void setExitingTokensHasVisible(boolean hasVisible) {
445 for (int i = mChildren.size() - 1; i >= 0; --i) {
446 final ArrayList<ActivityRecord> activities = mChildren.get(i).mExitingActivities;
447 for (int j = activities.size() - 1; j >= 0; --j) {
448 activities.get(j).hasVisible = hasVisible;
449 }
450 }
451 }
452
453 void removeExistingAppTokensIfPossible() {
454 for (int i = mChildren.size() - 1; i >= 0; --i) {
455 final ArrayList<ActivityRecord> activities = mChildren.get(i).mExitingActivities;
456 for (int j = activities.size() - 1; j >= 0; --j) {
457 final ActivityRecord activity = activities.get(j);
458 if (!activity.hasVisible && !mDisplayContent.mClosingApps.contains(activity)
459 && (!activity.mIsExiting || activity.isEmpty())) {
460 // Make sure there is no animation running on this activity, so any windows
461 // associated with it will be removed as soon as their animations are
462 // complete.
463 cancelAnimation();
464 ProtoLog.v(WM_DEBUG_ADD_REMOVE,
465 "performLayout: Activity exiting now removed %s", activity);
466 activity.removeIfPossible();
467 }
468 }
469 }
470 }
471
472 @Override
473 int getOrientation(int candidate) {
474 if (mDisplayContent.isStackVisible(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY)) {
475 // Apps and their containers are not allowed to specify an orientation while using
476 // root tasks...except for the home stack if it is not resizable and currently
477 // visible (top of) its root task.
478 if (mRootHomeTask != null && mRootHomeTask.isVisible()) {
479 final Task topMost = mRootHomeTask.getTopMostTask();
480 final boolean resizable = topMost != null && topMost.isResizeable();
481 if (!(resizable && mRootHomeTask.matchParentBounds())) {
482 final int orientation = mRootHomeTask.getOrientation();
483 if (orientation != SCREEN_ORIENTATION_UNSET) {
484 return orientation;
485 }
486 }
487 }
488 return SCREEN_ORIENTATION_UNSPECIFIED;
489 }
490
491 final int orientation = super.getOrientation(candidate);
492 if (orientation != SCREEN_ORIENTATION_UNSET
493 && orientation != SCREEN_ORIENTATION_BEHIND) {
494 ProtoLog.v(WM_DEBUG_ORIENTATION,
495 "App is requesting an orientation, return %d for display id=%d",
496 orientation, mDisplayContent.mDisplayId);
497 return orientation;
498 }
499
500 ProtoLog.v(WM_DEBUG_ORIENTATION,
501 "No app is requesting an orientation, return %d for display id=%d",
502 mDisplayContent.getLastOrientation(), mDisplayContent.mDisplayId);
503 // The next app has not been requested to be visible, so we keep the current orientation
504 // to prevent freezing/unfreezing the display too early.
505 return mDisplayContent.getLastOrientation();
506 }
507
508 @Override
509 void assignChildLayers(SurfaceControl.Transaction t) {
510 assignStackOrdering(t);
511
512 for (int i = 0; i < mChildren.size(); i++) {
513 final ActivityStack s = mChildren.get(i);
514 s.assignChildLayers(t);
515 }
516 }
517
518 void assignStackOrdering(SurfaceControl.Transaction t) {
519 if (getParent() == null) {
520 return;
521 }
522 mTmpAlwaysOnTopStacks.clear();
523 mTmpHomeStacks.clear();
524 mTmpNormalStacks.clear();
525 for (int i = 0; i < mChildren.size(); ++i) {
526 final ActivityStack s = mChildren.get(i);
527 if (s.isAlwaysOnTop()) {
528 mTmpAlwaysOnTopStacks.add(s);
529 } else if (s.isActivityTypeHome()) {
530 mTmpHomeStacks.add(s);
531 } else {
532 mTmpNormalStacks.add(s);
533 }
534 }
535
536 int layer = 0;
537 // Place home stacks to the bottom.
538 for (int i = 0; i < mTmpHomeStacks.size(); i++) {
539 mTmpHomeStacks.get(i).assignLayer(t, layer++);
540 }
541 // The home animation layer is between the home stacks and the normal stacks.
542 final int layerForHomeAnimationLayer = layer++;
543 int layerForSplitScreenDividerAnchor = layer++;
544 int layerForAnimationLayer = layer++;
545 for (int i = 0; i < mTmpNormalStacks.size(); i++) {
546 final ActivityStack s = mTmpNormalStacks.get(i);
547 s.assignLayer(t, layer++);
548 if (s.inSplitScreenWindowingMode()) {
549 // The split screen divider anchor is located above the split screen window.
550 layerForSplitScreenDividerAnchor = layer++;
551 }
552 if (s.isTaskAnimating() || s.isAppTransitioning()) {
553 // The animation layer is located above the highest animating stack and no
554 // higher.
555 layerForAnimationLayer = layer++;
556 }
557 }
558 // The boosted animation layer is between the normal stacks and the always on top
559 // stacks.
560 final int layerForBoostedAnimationLayer = layer++;
561 for (int i = 0; i < mTmpAlwaysOnTopStacks.size(); i++) {
562 mTmpAlwaysOnTopStacks.get(i).assignLayer(t, layer++);
563 }
564
565 t.setLayer(mHomeAppAnimationLayer, layerForHomeAnimationLayer);
566 t.setLayer(mAppAnimationLayer, layerForAnimationLayer);
567 t.setLayer(mSplitScreenDividerAnchor, layerForSplitScreenDividerAnchor);
568 t.setLayer(mBoostedAppAnimationLayer, layerForBoostedAnimationLayer);
569 }
570
571 @Override
572 SurfaceControl getAppAnimationLayer(@AnimationLayer int animationLayer) {
573 switch (animationLayer) {
574 case ANIMATION_LAYER_BOOSTED:
575 return mBoostedAppAnimationLayer;
576 case ANIMATION_LAYER_HOME:
577 return mHomeAppAnimationLayer;
578 case ANIMATION_LAYER_STANDARD:
579 default:
580 return mAppAnimationLayer;
581 }
582 }
583
584 SurfaceControl getSplitScreenDividerAnchor() {
585 return mSplitScreenDividerAnchor;
586 }
587
588 @Override
589 void onParentChanged(ConfigurationContainer newParent, ConfigurationContainer oldParent) {
590 if (getParent() != null) {
591 super.onParentChanged(newParent, oldParent, () -> {
592 mAppAnimationLayer = makeChildSurface(null)
593 .setName("animationLayer")
594 .build();
595 mBoostedAppAnimationLayer = makeChildSurface(null)
596 .setName("boostedAnimationLayer")
597 .build();
598 mHomeAppAnimationLayer = makeChildSurface(null)
599 .setName("homeAnimationLayer")
600 .build();
601 mSplitScreenDividerAnchor = makeChildSurface(null)
602 .setName("splitScreenDividerAnchor")
603 .build();
604 getPendingTransaction()
605 .show(mAppAnimationLayer)
606 .show(mBoostedAppAnimationLayer)
607 .show(mHomeAppAnimationLayer)
608 .show(mSplitScreenDividerAnchor);
609 });
610 } else {
611 super.onParentChanged(newParent, oldParent);
612 mWmService.mTransactionFactory.get()
613 .remove(mAppAnimationLayer)
614 .remove(mBoostedAppAnimationLayer)
615 .remove(mHomeAppAnimationLayer)
616 .remove(mSplitScreenDividerAnchor)
617 .apply();
618 mAppAnimationLayer = null;
619 mBoostedAppAnimationLayer = null;
620 mHomeAppAnimationLayer = null;
621 mSplitScreenDividerAnchor = null;
622 }
623 }
Andrii Kulian9ea12da2020-03-27 17:16:38 -0700624
625 void addStack(ActivityStack stack, int position) {
626 mDisplayContent.setStackOnDisplay(stack, position);
627 positionStackAt(stack, position);
628 }
629
630 void onStackRemoved(ActivityStack stack) {
631 if (ActivityTaskManagerDebugConfig.DEBUG_STACK) {
632 Slog.v(TAG_STACK, "removeStack: detaching " + stack + " from displayId="
633 + mDisplayContent.mDisplayId);
634 }
635 if (mPreferredTopFocusableStack == stack) {
636 mPreferredTopFocusableStack = null;
637 }
638 mDisplayContent.releaseSelfIfNeeded();
639 mDisplayContent.onStackOrderChanged(stack);
640 }
641
642 void positionStackAt(int position, ActivityStack child, boolean includingParents) {
643 positionChildAt(position, child, includingParents);
644 mDisplayContent.layoutAndAssignWindowLayersIfNeeded();
645 }
646
647 void positionStackAtTop(ActivityStack stack, boolean includingParents) {
648 positionStackAtTop(stack, includingParents, null /* updateLastFocusedStackReason */);
649 }
650
651 void positionStackAtTop(ActivityStack stack, boolean includingParents,
652 String updateLastFocusedStackReason) {
653 positionStackAt(stack, getStackCount(), includingParents,
654 updateLastFocusedStackReason);
655 }
656
657 void positionStackAtBottom(ActivityStack stack) {
658 positionStackAtBottom(stack, null /* updateLastFocusedStackReason */);
659 }
660
661 void positionStackAtBottom(ActivityStack stack, String updateLastFocusedStackReason) {
662 positionStackAt(stack, 0, false /* includingParents */,
663 updateLastFocusedStackReason);
664 }
665
666 void positionStackAt(ActivityStack stack, int position) {
667 positionStackAt(stack, position, false /* includingParents */,
668 null /* updateLastFocusedStackReason */);
669 }
670
671 void positionStackAt(ActivityStack stack, int position, boolean includingParents,
672 String updateLastFocusedStackReason) {
673 // TODO: Keep in sync with WindowContainer.positionChildAt(), once we change that to adjust
674 // the position internally, also update the logic here
675 final ActivityStack prevFocusedStack = updateLastFocusedStackReason != null
676 ? getFocusedStack() : null;
677 final boolean wasContained = getIndexOf(stack) >= 0;
678 if (mDisplayContent.mSingleTaskInstance && getStackCount() == 1 && !wasContained) {
679 throw new IllegalStateException(
680 "positionStackAt: Can only have one task on display=" + this);
681 }
682
683 final boolean movingToTop = wasContained && position >= getStackCount() - 1;
684 // Reset mPreferredTopFocusableStack before positioning to top or {@link
685 // ActivityStackSupervisor#updateTopResumedActivityIfNeeded()} won't update the top
686 // resumed activity.
687 if (movingToTop && stack.isFocusable()) {
688 mPreferredTopFocusableStack = null;
689 }
690
691 // Since positionChildAt() is called during the creation process of pinned stacks,
692 // ActivityStack#getStack() can be null.
693 positionStackAt(position, stack, includingParents);
694
695 // The insert position may be adjusted to non-top when there is always-on-top stack. Since
696 // the original position is preferred to be top, the stack should have higher priority when
697 // we are looking for top focusable stack. The condition {@code wasContained} restricts the
698 // preferred stack is set only when moving an existing stack to top instead of adding a new
699 // stack that may be too early (e.g. in the middle of launching or reparenting).
700 if (movingToTop && stack.isFocusableAndVisible()) {
701 mPreferredTopFocusableStack = stack;
702 } else if (mPreferredTopFocusableStack == stack) {
703 mPreferredTopFocusableStack = null;
704 }
705
706 if (updateLastFocusedStackReason != null) {
707 final ActivityStack currentFocusedStack = getFocusedStack();
708 if (currentFocusedStack != prevFocusedStack) {
709 mLastFocusedStack = prevFocusedStack;
710 EventLogTags.writeWmFocusedStack(mRootWindowContainer.mCurrentUser,
711 mDisplayContent.mDisplayId,
712 currentFocusedStack == null ? -1 : currentFocusedStack.getRootTaskId(),
713 mLastFocusedStack == null ? -1 : mLastFocusedStack.getRootTaskId(),
714 updateLastFocusedStackReason);
715 }
716 }
717
718 mDisplayContent.onStackOrderChanged(stack);
719 }
720
721 ActivityStack getStack(int rootTaskId) {
722 for (int i = getStackCount() - 1; i >= 0; --i) {
723 final ActivityStack stack = getStackAt(i);
724 if (stack.getRootTaskId() == rootTaskId) {
725 return stack;
726 }
727 }
728 return null;
729 }
730
731 /**
732 * Returns an existing stack compatible with the windowing mode and activity type or creates one
733 * if a compatible stack doesn't exist.
734 * @see #getOrCreateStack(int, int, boolean, Intent, Task, boolean)
735 */
736 ActivityStack getOrCreateStack(int windowingMode, int activityType, boolean onTop) {
737 return getOrCreateStack(windowingMode, activityType, onTop, null /* intent */,
738 null /* candidateTask */, false /* createdByOrganizer */);
739 }
740
741 /**
742 * When two level tasks are required for given windowing mode and activity type, returns an
743 * existing compatible root task or creates a new one.
744 * For one level task, the candidate task would be reused to also be the root task or create
745 * a new root task if no candidate task.
746 * @see #getStack(int, int)
747 * @see #createStack(int, int, boolean)
748 */
749 ActivityStack getOrCreateStack(int windowingMode, int activityType, boolean onTop,
750 Intent intent, Task candidateTask, boolean createdByOrganizer) {
751 if (!alwaysCreateStack(windowingMode, activityType)) {
752 ActivityStack stack = getStack(windowingMode, activityType);
753 if (stack != null) {
754 return stack;
755 }
756 } else if (candidateTask != null) {
757 final ActivityStack stack = (ActivityStack) candidateTask;
758 final int position = onTop ? POSITION_TOP : POSITION_BOTTOM;
759 if (isSplitScreenModeActivated()) {
760 final Task splitRootSecondary = getTask(t -> t.mCreatedByOrganizer && t.isRootTask()
761 && t.inSplitScreenSecondaryWindowingMode());
762 if (stack.getParent() == null) {
763 splitRootSecondary.addChild(stack, position);
764 } else if (stack.getParent() != splitRootSecondary) {
765 stack.reparent(splitRootSecondary, position);
766 }
767 } else if (stack.getDisplay() != mDisplayContent || !stack.isRootTask()) {
768 if (stack.getParent() == null) {
769 addStack(stack, position);
770 } else {
771 stack.reparent(mDisplayContent, onTop);
772 }
773 }
774 // Update windowing mode if necessary, e.g. moving a pinned task to fullscreen.
775 if (candidateTask.getWindowingMode() != windowingMode) {
776 candidateTask.setWindowingMode(windowingMode);
777 }
778 return stack;
779 }
780 return createStack(windowingMode, activityType, onTop, null /*info*/, intent,
781 createdByOrganizer);
782 }
783
784 /**
785 * Returns an existing stack compatible with the input params or creates one
786 * if a compatible stack doesn't exist.
787 * @see #getOrCreateStack(int, int, boolean)
788 */
789 ActivityStack getOrCreateStack(@Nullable ActivityRecord r,
790 @Nullable ActivityOptions options, @Nullable Task candidateTask, int activityType,
791 boolean onTop) {
792 // First preference is the windowing mode in the activity options if set.
793 int windowingMode = (options != null)
794 ? options.getLaunchWindowingMode() : WINDOWING_MODE_UNDEFINED;
795 // Validate that our desired windowingMode will work under the current conditions.
796 // UNDEFINED windowing mode is a valid result and means that the new stack will inherit
797 // it's display's windowing mode.
798 windowingMode = validateWindowingMode(windowingMode, r, candidateTask, activityType);
799 return getOrCreateStack(windowingMode, activityType, onTop, null /* intent */,
800 candidateTask, false /* createdByOrganizer */);
801 }
802
803 @VisibleForTesting
804 int getNextStackId() {
805 return mAtmService.mStackSupervisor.getNextTaskIdForUser();
806 }
807
808 ActivityStack createStack(int windowingMode, int activityType, boolean onTop) {
809 return createStack(windowingMode, activityType, onTop, null /* info */, null /* intent */,
810 false /* createdByOrganizer */);
811 }
812
813 /**
814 * Creates a stack matching the input windowing mode and activity type on this display.
815 * @param windowingMode The windowing mode the stack should be created in. If
816 * {@link WindowConfiguration#WINDOWING_MODE_UNDEFINED} then the stack will
817 * inherit its parent's windowing mode.
818 * @param activityType The activityType the stack should be created in. If
819 * {@link WindowConfiguration#ACTIVITY_TYPE_UNDEFINED} then the stack will
820 * be created in {@link WindowConfiguration#ACTIVITY_TYPE_STANDARD}.
821 * @param onTop If true the stack will be created at the top of the display, else at the bottom.
822 * @param info The started activity info.
823 * @param intent The intent that started this task.
824 * @param createdByOrganizer @{code true} if this is created by task organizer, @{code false}
825 * otherwise.
826 * @return The newly created stack.
827 */
828 ActivityStack createStack(int windowingMode, int activityType, boolean onTop, ActivityInfo info,
829 Intent intent, boolean createdByOrganizer) {
830 if (mDisplayContent.mSingleTaskInstance && getStackCount() > 0) {
831 // Create stack on default display instead since this display can only contain 1 stack.
832 // TODO: Kinda a hack, but better that having the decision at each call point. Hoping
833 // this goes away once ActivityView is no longer using virtual displays.
834 return mRootWindowContainer.getDefaultDisplay().mTaskContainers.createStack(
835 windowingMode, activityType, onTop, info, intent, createdByOrganizer);
836 }
837
838 if (activityType == ACTIVITY_TYPE_UNDEFINED && !createdByOrganizer) {
839 // Can't have an undefined stack type yet...so re-map to standard. Anyone that wants
840 // anything else should be passing it in anyways...except for the task organizer.
841 activityType = ACTIVITY_TYPE_STANDARD;
842 }
843
844 if (activityType != ACTIVITY_TYPE_STANDARD && activityType != ACTIVITY_TYPE_UNDEFINED) {
845 // For now there can be only one stack of a particular non-standard activity type on a
846 // display. So, get that ignoring whatever windowing mode it is currently in.
847 ActivityStack stack = getStack(WINDOWING_MODE_UNDEFINED, activityType);
848 if (stack != null) {
849 throw new IllegalArgumentException("Stack=" + stack + " of activityType="
850 + activityType + " already on display=" + this + ". Can't have multiple.");
851 }
852 }
853
854 if (!isWindowingModeSupported(windowingMode, mAtmService.mSupportsMultiWindow,
855 mAtmService.mSupportsSplitScreenMultiWindow,
856 mAtmService.mSupportsFreeformWindowManagement,
857 mAtmService.mSupportsPictureInPicture, activityType)) {
858 throw new IllegalArgumentException("Can't create stack for unsupported windowingMode="
859 + windowingMode);
860 }
861
862 final int stackId = getNextStackId();
863 return createStackUnchecked(windowingMode, activityType, stackId, onTop, info, intent,
864 createdByOrganizer);
865 }
866
867 /** @return the root task to create the next task in. */
868 private Task updateLaunchRootTask(int windowingMode) {
869 if (!isSplitScreenWindowingMode(windowingMode)) {
870 // Only split-screen windowing modes can do this currently...
871 return null;
872 }
873 for (int i = getStackCount() - 1; i >= 0; --i) {
874 final Task t = getStackAt(i);
875 if (!t.mCreatedByOrganizer || t.getRequestedOverrideWindowingMode() != windowingMode) {
876 continue;
877 }
878 // If not already set, pick a launch root which is not the one we are launching into.
879 if (mLaunchRootTask == null) {
880 for (int j = 0, n = getStackCount(); j < n; ++j) {
881 final Task tt = getStackAt(j);
882 if (tt.mCreatedByOrganizer && tt != t) {
883 mLaunchRootTask = tt;
884 break;
885 }
886 }
887 }
888 return t;
889 }
890 return mLaunchRootTask;
891 }
892
893 @VisibleForTesting
894 ActivityStack createStackUnchecked(int windowingMode, int activityType, int stackId,
895 boolean onTop, ActivityInfo info, Intent intent, boolean createdByOrganizer) {
896 if (windowingMode == WINDOWING_MODE_PINNED && activityType != ACTIVITY_TYPE_STANDARD) {
897 throw new IllegalArgumentException("Stack with windowing mode cannot with non standard "
898 + "activity type.");
899 }
900 if (info == null) {
901 info = new ActivityInfo();
902 info.applicationInfo = new ApplicationInfo();
903 }
904
905 // Task created by organizer are added as root.
906 Task launchRootTask = createdByOrganizer ? null : updateLaunchRootTask(windowingMode);
907 if (launchRootTask != null) {
908 // Since this stack will be put into a root task, its windowingMode will be inherited.
909 windowingMode = WINDOWING_MODE_UNDEFINED;
910 }
911
912 final ActivityStack stack = (ActivityStack) Task.create(mAtmService, stackId, activityType,
913 info, intent, createdByOrganizer);
914 if (launchRootTask != null) {
915 launchRootTask.addChild(stack, onTop ? POSITION_TOP : POSITION_BOTTOM);
916 if (onTop) {
917 positionStackAtTop((ActivityStack) launchRootTask, false /* includingParents */);
918 }
919 } else {
920 addStack(stack, onTop ? POSITION_TOP : POSITION_BOTTOM);
921 stack.setWindowingMode(windowingMode, false /* animate */, false /* showRecents */,
922 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
923 true /* creating */);
924 }
925 return stack;
926 }
927
928 /**
929 * Get the preferred focusable stack in priority. If the preferred stack does not exist, find a
930 * focusable and visible stack from the top of stacks in this display.
931 */
932 ActivityStack getFocusedStack() {
933 if (mPreferredTopFocusableStack != null) {
934 return mPreferredTopFocusableStack;
935 }
936
937 for (int i = getStackCount() - 1; i >= 0; --i) {
938 final ActivityStack stack = getStackAt(i);
939 if (stack.isFocusableAndVisible()) {
940 return stack;
941 }
942 }
943
944 return null;
945 }
946
947 ActivityStack getNextFocusableStack(ActivityStack currentFocus, boolean ignoreCurrent) {
948 final int currentWindowingMode = currentFocus != null
949 ? currentFocus.getWindowingMode() : WINDOWING_MODE_UNDEFINED;
950
951 ActivityStack candidate = null;
952 for (int i = getStackCount() - 1; i >= 0; --i) {
953 final ActivityStack stack = getStackAt(i);
954 if (ignoreCurrent && stack == currentFocus) {
955 continue;
956 }
957 if (!stack.isFocusableAndVisible()) {
958 continue;
959 }
960
961 if (currentWindowingMode == WINDOWING_MODE_SPLIT_SCREEN_SECONDARY
962 && candidate == null && stack.inSplitScreenPrimaryWindowingMode()) {
963 // If the currently focused stack is in split-screen secondary we save off the
964 // top primary split-screen stack as a candidate for focus because we might
965 // prefer focus to move to an other stack to avoid primary split-screen stack
966 // overlapping with a fullscreen stack when a fullscreen stack is higher in z
967 // than the next split-screen stack. Assistant stack, I am looking at you...
968 // We only move the focus to the primary-split screen stack if there isn't a
969 // better alternative.
970 candidate = stack;
971 continue;
972 }
973 if (candidate != null && stack.inSplitScreenSecondaryWindowingMode()) {
974 // Use the candidate stack since we are now at the secondary split-screen.
975 return candidate;
976 }
977 return stack;
978 }
979 return candidate;
980 }
981
982 ActivityRecord getResumedActivity() {
983 final ActivityStack focusedStack = getFocusedStack();
984 if (focusedStack == null) {
985 return null;
986 }
987 // TODO(b/111541062): Move this into ActivityStack#getResumedActivity()
988 // Check if the focused stack has the resumed activity
989 ActivityRecord resumedActivity = focusedStack.getResumedActivity();
990 if (resumedActivity == null || resumedActivity.app == null) {
991 // If there is no registered resumed activity in the stack or it is not running -
992 // try to use previously resumed one.
993 resumedActivity = focusedStack.mPausingActivity;
994 if (resumedActivity == null || resumedActivity.app == null) {
995 // If previously resumed activity doesn't work either - find the topmost running
996 // activity that can be focused.
997 resumedActivity = focusedStack.topRunningActivity(true /* focusableOnly */);
998 }
999 }
1000 return resumedActivity;
1001 }
1002
1003 ActivityStack getLastFocusedStack() {
1004 return mLastFocusedStack;
1005 }
1006
1007 boolean allResumedActivitiesComplete() {
1008 for (int stackNdx = getStackCount() - 1; stackNdx >= 0; --stackNdx) {
1009 final ActivityRecord r = getStackAt(stackNdx).getResumedActivity();
1010 if (r != null && !r.isState(RESUMED)) {
1011 return false;
1012 }
1013 }
1014 final ActivityStack currentFocusedStack = getFocusedStack();
1015 if (ActivityTaskManagerDebugConfig.DEBUG_STACK) {
1016 Slog.d(TAG_STACK, "allResumedActivitiesComplete: mLastFocusedStack changing from="
1017 + mLastFocusedStack + " to=" + currentFocusedStack);
1018 }
1019 mLastFocusedStack = currentFocusedStack;
1020 return true;
1021 }
1022
1023 /**
1024 * Pause all activities in either all of the stacks or just the back stacks. This is done before
1025 * resuming a new activity and to make sure that previously active activities are
1026 * paused in stacks that are no longer visible or in pinned windowing mode. This does not
1027 * pause activities in visible stacks, so if an activity is launched within the same stack/task,
1028 * then we should explicitly pause that stack's top activity.
1029 * @param userLeaving Passed to pauseActivity() to indicate whether to call onUserLeaving().
1030 * @param resuming The resuming activity.
1031 * @return {@code true} if any activity was paused as a result of this call.
1032 */
1033 boolean pauseBackStacks(boolean userLeaving, ActivityRecord resuming) {
1034 boolean someActivityPaused = false;
1035 for (int stackNdx = getStackCount() - 1; stackNdx >= 0; --stackNdx) {
1036 final ActivityStack stack = getStackAt(stackNdx);
1037 final ActivityRecord resumedActivity = stack.getResumedActivity();
1038 if (resumedActivity != null
1039 && (stack.getVisibility(resuming) != STACK_VISIBILITY_VISIBLE
1040 || !stack.isTopActivityFocusable())) {
1041 if (DEBUG_STATES) {
1042 Slog.d(TAG_STATES, "pauseBackStacks: stack=" + stack
1043 + " mResumedActivity=" + resumedActivity);
1044 }
1045 someActivityPaused |= stack.startPausingLocked(userLeaving, false /* uiSleeping*/,
1046 resuming);
1047 }
1048 }
1049 return someActivityPaused;
1050 }
1051
1052 /**
1053 * Find task for putting the Activity in.
1054 */
1055 void findTaskLocked(final ActivityRecord r, final boolean isPreferredDisplay,
1056 RootWindowContainer.FindTaskResult result) {
1057 mTmpFindTaskResult.clear();
1058 for (int stackNdx = getStackCount() - 1; stackNdx >= 0; --stackNdx) {
1059 final ActivityStack stack = getStackAt(stackNdx);
1060 if (!r.hasCompatibleActivityType(stack) && stack.isLeafTask()) {
1061 if (DEBUG_TASKS) {
1062 Slog.d(TAG_TASKS, "Skipping stack: (mismatch activity/stack) " + stack);
1063 }
1064 continue;
1065 }
1066
1067 mTmpFindTaskResult.process(r, stack);
1068 // It is possible to have tasks in multiple stacks with the same root affinity, so
1069 // we should keep looking after finding an affinity match to see if there is a
1070 // better match in another stack. Also, task affinity isn't a good enough reason
1071 // to target a display which isn't the source of the intent, so skip any affinity
1072 // matches not on the specified display.
1073 if (mTmpFindTaskResult.mRecord != null) {
1074 if (mTmpFindTaskResult.mIdealMatch) {
1075 result.setTo(mTmpFindTaskResult);
1076 return;
1077 } else if (isPreferredDisplay) {
1078 // Note: since the traversing through the stacks is top down, the floating
1079 // tasks should always have lower priority than any affinity-matching tasks
1080 // in the fullscreen stacks
1081 result.setTo(mTmpFindTaskResult);
1082 }
1083 }
1084 }
1085 }
1086
1087 /**
1088 * Removes stacks in the input windowing modes from the system if they are of activity type
1089 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
1090 */
1091 void removeStacksInWindowingModes(int... windowingModes) {
1092 if (windowingModes == null || windowingModes.length == 0) {
1093 return;
1094 }
1095
1096 // Collect the stacks that are necessary to be removed instead of performing the removal
1097 // by looping mStacks, so that we don't miss any stacks after the stack size changed or
1098 // stacks reordered.
1099 final ArrayList<ActivityStack> stacks = new ArrayList<>();
1100 for (int j = windowingModes.length - 1; j >= 0; --j) {
1101 final int windowingMode = windowingModes[j];
1102 for (int i = getStackCount() - 1; i >= 0; --i) {
1103 final ActivityStack stack = getStackAt(i);
1104 if (!stack.isActivityTypeStandardOrUndefined()) {
1105 continue;
1106 }
1107 if (stack.getWindowingMode() != windowingMode) {
1108 continue;
1109 }
1110 stacks.add(stack);
1111 }
1112 }
1113
1114 for (int i = stacks.size() - 1; i >= 0; --i) {
1115 mRootWindowContainer.mStackSupervisor.removeStack(stacks.get(i));
1116 }
1117 }
1118
1119 void removeStacksWithActivityTypes(int... activityTypes) {
1120 if (activityTypes == null || activityTypes.length == 0) {
1121 return;
1122 }
1123
1124 // Collect the stacks that are necessary to be removed instead of performing the removal
1125 // by looping mStacks, so that we don't miss any stacks after the stack size changed or
1126 // stacks reordered.
1127 final ArrayList<ActivityStack> stacks = new ArrayList<>();
1128 for (int j = activityTypes.length - 1; j >= 0; --j) {
1129 final int activityType = activityTypes[j];
1130 for (int i = getStackCount() - 1; i >= 0; --i) {
1131 final ActivityStack stack = getStackAt(i);
1132 // Collect the root tasks that are currently being organized.
1133 if (stack.isOrganized()) {
1134 for (int k = stack.getChildCount() - 1; k >= 0; --k) {
1135 final ActivityStack childStack = (ActivityStack) stack.getChildAt(k);
1136 if (childStack.getActivityType() == activityType) {
1137 stacks.add(childStack);
1138 }
1139 }
1140 } else if (stack.getActivityType() == activityType) {
1141 stacks.add(stack);
1142 }
1143 }
1144 }
1145
1146 for (int i = stacks.size() - 1; i >= 0; --i) {
1147 mRootWindowContainer.mStackSupervisor.removeStack(stacks.get(i));
1148 }
1149 }
1150
1151 void onSplitScreenModeDismissed() {
1152 mAtmService.deferWindowLayout();
1153 try {
1154 mLaunchRootTask = null;
1155 moveSplitScreenTasksToFullScreen();
1156 } finally {
1157 final ActivityStack topFullscreenStack =
1158 getTopStackInWindowingMode(WINDOWING_MODE_FULLSCREEN);
1159 final ActivityStack homeStack = getOrCreateRootHomeTask();
1160 if (topFullscreenStack != null && homeStack != null && !isTopStack(homeStack)) {
1161 // Whenever split-screen is dismissed we want the home stack directly behind the
1162 // current top fullscreen stack so it shows up when the top stack is finished.
1163 // TODO: Would be better to use ActivityDisplay.positionChildAt() for this, however
1164 // ActivityDisplay doesn't have a direct controller to WM side yet. We can switch
1165 // once we have that.
1166 homeStack.moveToFront("onSplitScreenModeDismissed");
1167 topFullscreenStack.moveToFront("onSplitScreenModeDismissed");
1168 }
1169 mAtmService.continueWindowLayout();
1170 }
1171 }
1172
1173 private void moveSplitScreenTasksToFullScreen() {
1174 final WindowContainerTransaction wct = new WindowContainerTransaction();
1175 mTmpTasks.clear();
1176 forAllTasks(task -> {
1177 if (task.mCreatedByOrganizer && task.inSplitScreenWindowingMode() && task.hasChild()) {
1178 mTmpTasks.add(task);
1179 }
1180 });
1181
1182 for (int i = mTmpTasks.size() - 1; i >= 0; i--) {
1183 final Task root = mTmpTasks.get(i);
1184 for (int j = 0; j < root.getChildCount(); j++) {
1185 wct.reparent(root.getChildAt(j).mRemoteToken, null, true /* toTop */);
1186 }
1187 }
1188 mAtmService.mWindowOrganizerController.applyTransaction(wct);
1189 }
1190
1191 /**
1192 * Returns true if the {@param windowingMode} is supported based on other parameters passed in.
1193 * @param windowingMode The windowing mode we are checking support for.
1194 * @param supportsMultiWindow If we should consider support for multi-window mode in general.
1195 * @param supportsSplitScreen If we should consider support for split-screen multi-window.
1196 * @param supportsFreeform If we should consider support for freeform multi-window.
1197 * @param supportsPip If we should consider support for picture-in-picture mutli-window.
1198 * @param activityType The activity type under consideration.
1199 * @return true if the windowing mode is supported.
1200 */
1201 private boolean isWindowingModeSupported(int windowingMode, boolean supportsMultiWindow,
1202 boolean supportsSplitScreen, boolean supportsFreeform, boolean supportsPip,
1203 int activityType) {
1204
1205 if (windowingMode == WINDOWING_MODE_UNDEFINED
1206 || windowingMode == WINDOWING_MODE_FULLSCREEN) {
1207 return true;
1208 }
1209 if (!supportsMultiWindow) {
1210 return false;
1211 }
1212
1213 if (windowingMode == WINDOWING_MODE_MULTI_WINDOW) {
1214 return true;
1215 }
1216
1217 final int displayWindowingMode = getWindowingMode();
1218 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY
1219 || windowingMode == WINDOWING_MODE_SPLIT_SCREEN_SECONDARY) {
1220 return supportsSplitScreen
1221 && WindowConfiguration.supportSplitScreenWindowingMode(activityType)
1222 // Freeform windows and split-screen windows don't mix well, so prevent
1223 // split windowing modes on freeform displays.
1224 && displayWindowingMode != WINDOWING_MODE_FREEFORM;
1225 }
1226
1227 if (!supportsFreeform && windowingMode == WINDOWING_MODE_FREEFORM) {
1228 return false;
1229 }
1230
1231 if (!supportsPip && windowingMode == WINDOWING_MODE_PINNED) {
1232 return false;
1233 }
1234 return true;
1235 }
1236
1237 /**
1238 * Resolves the windowing mode that an {@link ActivityRecord} would be in if started on this
1239 * display with the provided parameters.
1240 *
1241 * @param r The ActivityRecord in question.
1242 * @param options Options to start with.
1243 * @param task The task within-which the activity would start.
1244 * @param activityType The type of activity to start.
1245 * @return The resolved (not UNDEFINED) windowing-mode that the activity would be in.
1246 */
1247 int resolveWindowingMode(@Nullable ActivityRecord r, @Nullable ActivityOptions options,
1248 @Nullable Task task, int activityType) {
1249
1250 // First preference if the windowing mode in the activity options if set.
1251 int windowingMode = (options != null)
1252 ? options.getLaunchWindowingMode() : WINDOWING_MODE_UNDEFINED;
1253
1254 // If windowing mode is unset, then next preference is the candidate task, then the
1255 // activity record.
1256 if (windowingMode == WINDOWING_MODE_UNDEFINED) {
1257 if (task != null) {
1258 windowingMode = task.getWindowingMode();
1259 }
1260 if (windowingMode == WINDOWING_MODE_UNDEFINED && r != null) {
1261 windowingMode = r.getWindowingMode();
1262 }
1263 if (windowingMode == WINDOWING_MODE_UNDEFINED) {
1264 // Use the display's windowing mode.
1265 windowingMode = getWindowingMode();
1266 }
1267 }
1268 windowingMode = validateWindowingMode(windowingMode, r, task, activityType);
1269 return windowingMode != WINDOWING_MODE_UNDEFINED
1270 ? windowingMode : WINDOWING_MODE_FULLSCREEN;
1271 }
1272
1273 /**
1274 * Check that the requested windowing-mode is appropriate for the specified task and/or activity
1275 * on this display.
1276 *
1277 * @param windowingMode The windowing-mode to validate.
1278 * @param r The {@link ActivityRecord} to check against.
1279 * @param task The {@link Task} to check against.
1280 * @param activityType An activity type.
1281 * @return The provided windowingMode or the closest valid mode which is appropriate.
1282 */
1283 int validateWindowingMode(int windowingMode, @Nullable ActivityRecord r, @Nullable Task task,
1284 int activityType) {
1285 // Make sure the windowing mode we are trying to use makes sense for what is supported.
1286 boolean supportsMultiWindow = mAtmService.mSupportsMultiWindow;
1287 boolean supportsSplitScreen = mAtmService.mSupportsSplitScreenMultiWindow;
1288 boolean supportsFreeform = mAtmService.mSupportsFreeformWindowManagement;
1289 boolean supportsPip = mAtmService.mSupportsPictureInPicture;
1290 if (supportsMultiWindow) {
1291 if (task != null) {
1292 supportsMultiWindow = task.isResizeable();
1293 supportsSplitScreen = task.supportsSplitScreenWindowingMode();
1294 // TODO: Do we need to check for freeform and Pip support here?
1295 } else if (r != null) {
1296 supportsMultiWindow = r.isResizeable();
1297 supportsSplitScreen = r.supportsSplitScreenWindowingMode();
1298 supportsFreeform = r.supportsFreeform();
1299 supportsPip = r.supportsPictureInPicture();
1300 }
1301 }
1302
1303 final boolean inSplitScreenMode = isSplitScreenModeActivated();
1304 if (!inSplitScreenMode
1305 && windowingMode == WINDOWING_MODE_FULLSCREEN_OR_SPLIT_SCREEN_SECONDARY) {
1306 // Switch to the display's windowing mode if we are not in split-screen mode and we are
1307 // trying to launch in split-screen secondary.
1308 windowingMode = WINDOWING_MODE_UNDEFINED;
1309 } else if (inSplitScreenMode && (windowingMode == WINDOWING_MODE_FULLSCREEN
1310 || windowingMode == WINDOWING_MODE_UNDEFINED)
1311 && supportsSplitScreen) {
1312 windowingMode = WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
1313 }
1314
1315 if (windowingMode != WINDOWING_MODE_UNDEFINED
1316 && isWindowingModeSupported(windowingMode, supportsMultiWindow, supportsSplitScreen,
1317 supportsFreeform, supportsPip, activityType)) {
1318 return windowingMode;
1319 }
1320 return WINDOWING_MODE_UNDEFINED;
1321 }
1322
1323 boolean isTopStack(ActivityStack stack) {
1324 return stack == getTopStack();
1325 }
1326
1327 boolean isTopNotPinnedStack(ActivityStack stack) {
1328 for (int i = getStackCount() - 1; i >= 0; --i) {
1329 final ActivityStack current = getStackAt(i);
1330 if (!current.inPinnedWindowingMode()) {
1331 return current == stack;
1332 }
1333 }
1334 return false;
1335 }
1336
1337 /**
1338 * Returns the top running activity in the focused stack. In the case the focused stack has no
1339 * such activity, the next focusable stack on this display is returned.
1340 *
1341 * @param considerKeyguardState Indicates whether the locked state should be considered. if
1342 * {@code true} and the keyguard is locked, only activities that
1343 * can be shown on top of the keyguard will be considered.
1344 * @return The top running activity. {@code null} if none is available.
1345 */
1346 ActivityRecord topRunningActivity(boolean considerKeyguardState) {
1347 ActivityRecord topRunning = null;
1348 final ActivityStack focusedStack = getFocusedStack();
1349 if (focusedStack != null) {
1350 topRunning = focusedStack.topRunningActivity();
1351 }
1352
1353 // Look in other focusable stacks.
1354 if (topRunning == null) {
1355 for (int i = getStackCount() - 1; i >= 0; --i) {
1356 final ActivityStack stack = getStackAt(i);
1357 // Only consider focusable stacks other than the current focused one.
1358 if (stack == focusedStack || !stack.isTopActivityFocusable()) {
1359 continue;
1360 }
1361 topRunning = stack.topRunningActivity();
1362 if (topRunning != null) {
1363 break;
1364 }
1365 }
1366 }
1367
1368 // This activity can be considered the top running activity if we are not considering
1369 // the locked state, the keyguard isn't locked, or we can show when locked.
1370 if (topRunning != null && considerKeyguardState
1371 && mRootWindowContainer.mStackSupervisor.getKeyguardController()
1372 .isKeyguardLocked()
1373 && !topRunning.canShowWhenLocked()) {
1374 return null;
1375 }
1376
1377 return topRunning;
1378 }
1379
1380 protected int getStackCount() {
1381 return mChildren.size();
1382 }
1383
1384 protected ActivityStack getStackAt(int index) {
1385 return mChildren.get(index);
1386 }
1387
1388 /**
1389 * Returns the existing home stack or creates and returns a new one if it should exist for the
1390 * display.
1391 */
1392 @Nullable
1393 ActivityStack getOrCreateRootHomeTask() {
1394 ActivityStack homeTask = getRootHomeTask();
1395 if (homeTask == null && mDisplayContent.supportsSystemDecorations()
1396 && !mDisplayContent.isUntrustedVirtualDisplay()) {
1397 homeTask = createStack(WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_HOME,
1398 false /* onTop */);
1399 }
1400 return homeTask;
1401 }
1402
1403 boolean isSplitScreenModeActivated() {
1404 Task task = getRootSplitScreenPrimaryTask();
1405 return task != null && task.hasChild();
1406 }
1407
1408 /**
1409 * Returns the topmost stack on the display that is compatible with the input windowing mode.
1410 * Null is no compatible stack on the display.
1411 */
1412 ActivityStack getTopStackInWindowingMode(int windowingMode) {
1413 return getStack(windowingMode, ACTIVITY_TYPE_UNDEFINED);
1414 }
1415
1416 void moveHomeStackToFront(String reason) {
1417 final ActivityStack homeStack = getOrCreateRootHomeTask();
1418 if (homeStack != null) {
1419 homeStack.moveToFront(reason);
1420 }
1421 }
1422
1423 /**
1424 * Moves the focusable home activity to top. If there is no such activity, the home stack will
1425 * still move to top.
1426 */
1427 void moveHomeActivityToTop(String reason) {
1428 final ActivityRecord top = getHomeActivity();
1429 if (top == null) {
1430 moveHomeStackToFront(reason);
1431 return;
1432 }
1433 top.moveFocusableActivityToTop(reason);
1434 }
1435
1436 @Nullable
1437 ActivityRecord getHomeActivity() {
1438 return getHomeActivityForUser(mRootWindowContainer.mCurrentUser);
1439 }
1440
1441 @Nullable
1442 ActivityRecord getHomeActivityForUser(int userId) {
1443 final ActivityStack homeStack = getRootHomeTask();
1444 if (homeStack == null) {
1445 return null;
1446 }
1447
1448 final PooledPredicate p = PooledLambda.obtainPredicate(
1449 TaskContainers::isHomeActivityForUser, PooledLambda.__(ActivityRecord.class),
1450 userId);
1451 final ActivityRecord r = homeStack.getActivity(p);
1452 p.recycle();
1453 return r;
1454 }
1455
1456 private static boolean isHomeActivityForUser(ActivityRecord r, int userId) {
1457 return r.isActivityTypeHome() && (userId == UserHandle.USER_ALL || r.mUserId == userId);
1458 }
1459
1460 /**
1461 * Adjusts the {@param stack} behind the last visible stack in the display if necessary.
1462 * Generally used in conjunction with {@link #moveStackBehindStack}.
1463 */
1464 // TODO(b/151575894): Remove special stack movement methods.
1465 void moveStackBehindBottomMostVisibleStack(ActivityStack stack) {
1466 if (stack.shouldBeVisible(null)) {
1467 // Skip if the stack is already visible
1468 return;
1469 }
1470
1471 final boolean isRootTask = stack.isRootTask();
1472 if (isRootTask) {
1473 // Move the stack to the bottom to not affect the following visibility checks
1474 positionStackAtBottom(stack);
1475 } else {
1476 stack.getParent().positionChildAt(POSITION_BOTTOM, stack, false /* includingParents */);
1477 }
1478
1479 // Find the next position where the stack should be placed
1480 final int numStacks = isRootTask ? getStackCount() : stack.getParent().getChildCount();
1481 for (int stackNdx = 0; stackNdx < numStacks; stackNdx++) {
1482 final ActivityStack s = isRootTask ? getStackAt(stackNdx)
1483 : (ActivityStack) stack.getParent().getChildAt(stackNdx);
1484 if (s == stack) {
1485 continue;
1486 }
1487 final int winMode = s.getWindowingMode();
1488 final boolean isValidWindowingMode = winMode == WINDOWING_MODE_FULLSCREEN
1489 || winMode == WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
1490 if (s.shouldBeVisible(null) && isValidWindowingMode) {
1491 // Move the provided stack to behind this stack
1492 final int position = Math.max(0, stackNdx - 1);
1493 if (isRootTask) {
1494 positionStackAt(stack, position);
1495 } else {
1496 stack.getParent().positionChildAt(position, stack, false /*includingParents */);
1497 }
1498 break;
1499 }
1500 }
1501 }
1502
1503 /**
1504 * Moves the {@param stack} behind the given {@param behindStack} if possible. If
1505 * {@param behindStack} is not currently in the display, then then the stack is moved to the
1506 * back. Generally used in conjunction with {@link #moveStackBehindBottomMostVisibleStack}.
1507 */
1508 void moveStackBehindStack(ActivityStack stack, ActivityStack behindStack) {
1509 if (behindStack == null || behindStack == stack) {
1510 return;
1511 }
1512
1513 final WindowContainer parent = stack.getParent();
1514 if (parent == null || parent != behindStack.getParent()) {
1515 return;
1516 }
1517
1518 // Note that positionChildAt will first remove the given stack before inserting into the
1519 // list, so we need to adjust the insertion index to account for the removed index
1520 // TODO: Remove this logic when WindowContainer.positionChildAt() is updated to adjust the
1521 // position internally
1522 final int stackIndex = parent.mChildren.indexOf(stack);
1523 final int behindStackIndex = parent.mChildren.indexOf(behindStack);
1524 final int insertIndex = stackIndex <= behindStackIndex
1525 ? behindStackIndex - 1 : behindStackIndex;
1526 final int position = Math.max(0, insertIndex);
1527 if (stack.isRootTask()) {
1528 positionStackAt(stack, position);
1529 } else {
1530 parent.positionChildAt(position, stack, false /* includingParents */);
1531 }
1532 }
Andrii Kulian526ad432020-03-27 12:19:51 -07001533}