blob: ac94125469ba64f03700bfcbc18c76f96e0ca505 [file] [log] [blame]
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001/*
2 * Copyright (C) 2010 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
Wale Ogunwale59507092018-10-29 09:00:30 -070017package com.android.server.wm;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070018
Louis Changdc077272019-11-12 16:52:56 +080019import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT;
20import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
Wale Ogunwale30e441d2017-11-09 08:28:45 -080021import static android.app.ITaskStackListener.FORCED_RESIZEABLE_REASON_SPLIT_SCREEN;
Matthew Nga51dcaa2018-05-07 15:36:06 -070022import static android.app.WindowConfiguration.ACTIVITY_TYPE_ASSISTANT;
Matthew Ng99b3cdc2018-05-01 14:24:38 -070023import static android.app.WindowConfiguration.ACTIVITY_TYPE_HOME;
Wale Ogunwale30e441d2017-11-09 08:28:45 -080024import static android.app.WindowConfiguration.ACTIVITY_TYPE_RECENTS;
Wale Ogunwale6fbde9f2017-08-24 07:24:12 -070025import static android.app.WindowConfiguration.ACTIVITY_TYPE_STANDARD;
26import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Louis Changdc077272019-11-12 16:52:56 +080027import static android.app.WindowConfiguration.PINNED_WINDOWING_MODE_ELEVATION_IN_DIP;
Wale Ogunwale44f036f2017-09-29 05:09:09 -070028import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
Wale Ogunwale68278562017-09-23 17:13:55 -070029import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale2b07da82017-11-08 14:52:40 -080030import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
Wale Ogunwale9dcf9462017-09-19 15:13:01 -070031import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale68278562017-09-23 17:13:55 -070032import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwalef75962a2017-08-23 14:58:04 -070033import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale44f036f2017-09-29 05:09:09 -070034import static android.app.WindowConfiguration.activityTypeToString;
35import static android.app.WindowConfiguration.windowingModeToString;
Filip Gruszczynski3c2db1d12016-01-06 17:39:14 -080036import static android.content.pm.ActivityInfo.CONFIG_SCREEN_LAYOUT;
Wale Ogunwale5658e4b2016-02-12 12:22:19 -080037import static android.content.pm.ActivityInfo.FLAG_RESUME_WHILE_PAUSING;
Wale Ogunwale6dfdfd62015-04-15 12:01:38 -070038import static android.content.pm.ActivityInfo.FLAG_SHOW_FOR_ALL_USERS;
Louis Changdc077272019-11-12 16:52:56 +080039import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_UNSET;
40import static android.content.res.Configuration.ORIENTATION_PORTRAIT;
Riddle Hsu2ca561b2019-10-08 21:58:58 +080041import static android.os.Trace.TRACE_TAG_WINDOW_MANAGER;
Wale Ogunwalef5d1e352016-09-22 08:34:42 -070042import static android.view.Display.DEFAULT_DISPLAY;
Andrii Kulian7211d2e2017-01-27 15:58:05 -080043import static android.view.Display.FLAG_CAN_SHOW_WITH_INSECURE_KEYGUARD;
Andrii Kulian94e82d9b02017-07-13 15:33:06 -070044import static android.view.Display.INVALID_DISPLAY;
Louis Changdc077272019-11-12 16:52:56 +080045import static android.view.WindowManager.DOCKED_BOTTOM;
46import static android.view.WindowManager.DOCKED_INVALID;
47import static android.view.WindowManager.DOCKED_LEFT;
48import static android.view.WindowManager.DOCKED_RIGHT;
49import static android.view.WindowManager.DOCKED_TOP;
Louis Chang7d0037c2018-08-13 12:42:06 +080050import static android.view.WindowManager.TRANSIT_ACTIVITY_CLOSE;
51import static android.view.WindowManager.TRANSIT_ACTIVITY_OPEN;
52import static android.view.WindowManager.TRANSIT_CRASHING_ACTIVITY_CLOSE;
53import static android.view.WindowManager.TRANSIT_NONE;
Issei Suzukicac2a502019-04-16 16:52:50 +020054import static android.view.WindowManager.TRANSIT_SHOW_SINGLE_TASK_DISPLAY;
Louis Chang7d0037c2018-08-13 12:42:06 +080055import static android.view.WindowManager.TRANSIT_TASK_CLOSE;
56import static android.view.WindowManager.TRANSIT_TASK_OPEN;
57import static android.view.WindowManager.TRANSIT_TASK_OPEN_BEHIND;
58import static android.view.WindowManager.TRANSIT_TASK_TO_BACK;
59import static android.view.WindowManager.TRANSIT_TASK_TO_FRONT;
Winson Chung1dbc8112017-09-28 18:05:31 -070060
Evan Roskye747c3e2018-10-30 20:06:41 -070061import static com.android.server.am.ActivityStackProto.DISPLAY_ID;
62import static com.android.server.am.ActivityStackProto.FULLSCREEN;
Evan Roskye747c3e2018-10-30 20:06:41 -070063import static com.android.server.am.ActivityStackProto.RESUMED_ACTIVITY;
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -070064import static com.android.server.am.ActivityStackProto.STACK;
Andrii Kulian057a6512019-07-15 16:15:51 -070065import static com.android.server.wm.ActivityRecord.FINISH_RESULT_REMOVED;
Wale Ogunwale59507092018-10-29 09:00:30 -070066import static com.android.server.wm.ActivityStack.ActivityState.PAUSED;
67import static com.android.server.wm.ActivityStack.ActivityState.PAUSING;
68import static com.android.server.wm.ActivityStack.ActivityState.RESUMED;
Louis Changeadb22f2019-06-19 12:09:23 +080069import static com.android.server.wm.ActivityStack.ActivityState.STARTED;
Wale Ogunwale59507092018-10-29 09:00:30 -070070import static com.android.server.wm.ActivityStack.ActivityState.STOPPED;
71import static com.android.server.wm.ActivityStack.ActivityState.STOPPING;
Wale Ogunwale59507092018-10-29 09:00:30 -070072import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
Garfield Tan347bd602018-12-21 15:11:12 -080073import static com.android.server.wm.ActivityStackSupervisor.dumpHistoryList;
74import static com.android.server.wm.ActivityStackSupervisor.printThisActivity;
Wale Ogunwale59507092018-10-29 09:00:30 -070075import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ADD_REMOVE;
76import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
77import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_APP;
78import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CLEANUP;
Wale Ogunwale59507092018-10-29 09:00:30 -070079import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_PAUSE;
80import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_RELEASE;
81import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_RESULTS;
Wale Ogunwale59507092018-10-29 09:00:30 -070082import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
83import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STATES;
84import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
85import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
86import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TRANSITION;
87import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_USER_LEAVING;
88import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
89import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_ADD_REMOVE;
90import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_APP;
91import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CLEANUP;
Wale Ogunwale59507092018-10-29 09:00:30 -070092import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_PAUSE;
93import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_RELEASE;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_RESULTS;
Wale Ogunwale59507092018-10-29 09:00:30 -070095import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STATES;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_TASKS;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_TRANSITION;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_USER_LEAVING;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
104import static com.android.server.wm.ActivityTaskManagerService.H.FIRST_ACTIVITY_STACK_MSG;
105import static com.android.server.wm.ActivityTaskManagerService.RELAUNCH_REASON_FREE_RESIZE;
106import static com.android.server.wm.ActivityTaskManagerService.RELAUNCH_REASON_WINDOWING_MODE_RESIZE;
Louis Changdc077272019-11-12 16:52:56 +0800107import static com.android.server.wm.BoundsAnimationController.FADE_IN;
108import static com.android.server.wm.BoundsAnimationController.NO_PIP_MODE_CHANGED_CALLBACKS;
109import static com.android.server.wm.BoundsAnimationController.SCHEDULE_PIP_MODE_CHANGED_ON_END;
110import static com.android.server.wm.BoundsAnimationController.SCHEDULE_PIP_MODE_CHANGED_ON_START;
111import static com.android.server.wm.DragResizeMode.DRAG_RESIZE_MODE_DOCKED_DIVIDER;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800112import static com.android.server.wm.RootActivityContainer.FindTaskResult;
Louis Changdc077272019-11-12 16:52:56 +0800113import static com.android.server.wm.StackProto.ADJUSTED_BOUNDS;
114import static com.android.server.wm.StackProto.ADJUSTED_FOR_IME;
115import static com.android.server.wm.StackProto.ADJUST_DIVIDER_AMOUNT;
116import static com.android.server.wm.StackProto.ADJUST_IME_AMOUNT;
117import static com.android.server.wm.StackProto.ANIMATING_BOUNDS;
118import static com.android.server.wm.StackProto.DEFER_REMOVAL;
119import static com.android.server.wm.StackProto.FILLS_PARENT;
120import static com.android.server.wm.StackProto.MINIMIZE_AMOUNT;
121import static com.android.server.wm.StackProto.WINDOW_CONTAINER;
Louis Changcdec0802019-11-11 11:45:07 +0800122import static com.android.server.wm.Task.REPARENT_LEAVE_STACK_IN_PLACE;
Louis Changdc077272019-11-12 16:52:56 +0800123import static com.android.server.wm.WindowContainer.AnimationFlags.CHILDREN;
124import static com.android.server.wm.WindowContainer.AnimationFlags.TRANSITION;
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -0700125import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_TASK_MOVEMENT;
126import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
Louis Changf2835df2018-10-17 15:14:45 +0800127
Wale Ogunwalec5cc3012017-01-13 13:26:16 -0800128import static java.lang.Integer.MAX_VALUE;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700129
Andrii Kulian0c869cc2019-02-06 19:50:32 -0800130import android.annotation.IntDef;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700131import android.app.Activity;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700132import android.app.ActivityManager;
Wale Ogunwale53783742018-09-16 10:21:51 -0700133import android.app.ActivityManagerInternal;
Dianne Hackborn7a2195c2012-03-19 17:38:00 -0700134import android.app.ActivityOptions;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700135import android.app.AppGlobals;
Craig Mautner05d6272ba2013-02-11 09:39:27 -0800136import android.app.IActivityController;
Louis Changdc077272019-11-12 16:52:56 +0800137import android.app.RemoteAction;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700138import android.app.ResultInfo;
Winson Chung61c9e5a2017-10-11 10:39:32 -0700139import android.app.WindowConfiguration.ActivityType;
140import android.app.WindowConfiguration.WindowingMode;
Andrii Kulian446e8242017-10-26 15:17:29 -0700141import android.app.servertransaction.ActivityResultItem;
Andrii Kulian9956d892018-02-14 13:48:56 -0800142import android.app.servertransaction.ClientTransaction;
Louis Chang7d0037c2018-08-13 12:42:06 +0800143import android.app.servertransaction.NewIntentItem;
Andrii Kulian446e8242017-10-26 15:17:29 -0700144import android.app.servertransaction.PauseActivityItem;
145import android.app.servertransaction.ResumeActivityItem;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700146import android.content.ComponentName;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700147import android.content.Intent;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700148import android.content.pm.ActivityInfo;
Todd Kennedy39bfee52016-02-24 10:28:21 -0800149import android.content.pm.ApplicationInfo;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700150import android.content.res.Configuration;
Louis Changdc077272019-11-12 16:52:56 +0800151import android.graphics.Point;
Jorim Jaggiaf80db42016-04-07 19:19:15 -0700152import android.graphics.Rect;
Louis Changdc077272019-11-12 16:52:56 +0800153import android.graphics.Region;
Santos Cordon73ff7d82013-03-06 17:24:11 -0800154import android.net.Uri;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700155import android.os.Binder;
Craig Mautner329f4122013-11-07 09:10:42 -0800156import android.os.Debug;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700157import android.os.Handler;
158import android.os.IBinder;
Zoran Marcetaf958b322012-08-09 20:27:12 +0900159import android.os.Looper;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700160import android.os.Message;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700161import android.os.RemoteException;
162import android.os.SystemClock;
Evan Roskydbe2ce52019-07-18 11:13:17 -0700163import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700164import android.os.UserHandle;
Craig Mautner4c07d022014-06-11 17:12:59 -0700165import android.service.voice.IVoiceInteractionSession;
Jorim Jaggiaf80db42016-04-07 19:19:15 -0700166import android.util.ArraySet;
Louis Changdc077272019-11-12 16:52:56 +0800167import android.util.DisplayMetrics;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700168import android.util.EventLog;
Andrii Kulianfb1bf692017-01-17 11:17:34 -0800169import android.util.IntArray;
Jorim Jaggi023da532016-04-20 22:42:32 -0700170import android.util.Log;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700171import android.util.Slog;
Steven Timotius4346f0a2017-09-12 11:07:21 -0700172import android.util.proto.ProtoOutputStream;
Craig Mautner59c00972012-07-30 12:10:24 -0700173import android.view.Display;
Louis Changdc077272019-11-12 16:52:56 +0800174import android.view.DisplayCutout;
175import android.view.DisplayInfo;
176import android.view.RemoteAnimationTarget;
177import android.view.SurfaceControl;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700178
Andreas Gampea36dc622018-02-05 17:19:22 -0800179import com.android.internal.annotations.GuardedBy;
Bryce Lee840c5662017-04-13 10:02:51 -0700180import com.android.internal.annotations.VisibleForTesting;
Jorim Jaggiaf80db42016-04-07 19:19:15 -0700181import com.android.internal.app.IVoiceInteractor;
Ben Lin6db8fb22019-10-18 16:03:44 -0700182import com.android.internal.os.logging.MetricsLoggerWrapper;
Louis Changdc077272019-11-12 16:52:56 +0800183import com.android.internal.policy.DividerSnapAlgorithm;
184import com.android.internal.policy.DockedDividerUtils;
Wale Ogunwale53783742018-09-16 10:21:51 -0700185import com.android.internal.util.function.pooled.PooledLambda;
Jorim Jaggiaf80db42016-04-07 19:19:15 -0700186import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700187import com.android.server.am.ActivityManagerService;
Jorim Jaggiaf80db42016-04-07 19:19:15 -0700188import com.android.server.am.ActivityManagerService.ItemMatcher;
Wale Ogunwale59507092018-10-29 09:00:30 -0700189import com.android.server.am.AppTimeTracker;
190import com.android.server.am.EventLogTags;
Jorim Jaggiaf80db42016-04-07 19:19:15 -0700191
Craig Mautnercae015f2013-02-08 14:31:27 -0800192import java.io.FileDescriptor;
Craig Mautnercae015f2013-02-08 14:31:27 -0800193import java.io.PrintWriter;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700194import java.util.ArrayList;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700195import java.util.List;
Kenny Roote6585b32013-12-13 12:00:26 -0800196import java.util.Objects;
Wale Ogunwale540e1232015-05-01 15:35:39 -0700197import java.util.Set;
Riddle Hsu13c27ae2019-10-05 23:10:15 +0800198import java.util.function.Consumer;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700199
200/**
201 * State and management of a single stack of activities.
202 */
Louis Changdc077272019-11-12 16:52:56 +0800203class ActivityStack extends WindowContainer<Task> implements BoundsAnimationTarget,
204 ConfigurationContainerListener {
Wale Ogunwale98875612018-10-12 07:53:02 -0700205 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityStack" : TAG_ATM;
Wale Ogunwale0fc365c2015-05-25 19:35:42 -0700206 private static final String TAG_ADD_REMOVE = TAG + POSTFIX_ADD_REMOVE;
207 private static final String TAG_APP = TAG + POSTFIX_APP;
Wale Ogunwalee23149f2015-03-06 15:39:44 -0800208 private static final String TAG_CLEANUP = TAG + POSTFIX_CLEANUP;
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700209 private static final String TAG_PAUSE = TAG + POSTFIX_PAUSE;
Wale Ogunwale0fc365c2015-05-25 19:35:42 -0700210 private static final String TAG_RELEASE = TAG + POSTFIX_RELEASE;
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700211 private static final String TAG_RESULTS = TAG + POSTFIX_RESULTS;
212 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale0fc365c2015-05-25 19:35:42 -0700213 private static final String TAG_STATES = TAG + POSTFIX_STATES;
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700214 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
215 private static final String TAG_TASKS = TAG + POSTFIX_TASKS;
216 private static final String TAG_TRANSITION = TAG + POSTFIX_TRANSITION;
217 private static final String TAG_USER_LEAVING = TAG + POSTFIX_USER_LEAVING;
218 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
Wale Ogunwale3ab9a272015-03-16 09:55:45 -0700219
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700220 // Ticks during which we check progress while waiting for an app to launch.
Andrii Kulian79d67982019-08-19 11:56:16 -0700221 private static final int LAUNCH_TICK = 500;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700222
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700223 // How long we wait until giving up on the last activity to pause. This
224 // is short because it directly impacts the responsiveness of starting the
225 // next activity.
Andrii Kulian21713ac2016-10-12 22:05:05 -0700226 private static final int PAUSE_TIMEOUT = 500;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700227
Dianne Hackborn162bc0e2012-04-09 14:06:16 -0700228 // How long we wait for the activity to tell us it has stopped before
229 // giving up. This is a good amount of time because we really need this
Robert Carr3406d462018-03-15 16:19:07 -0700230 // from the application in order to get its saved state. Once the stop
231 // is complete we may start destroying client resources triggering
232 // crashes if the UI thread was hung. We put this timeout one second behind
233 // the ANR timeout so these situations will generate ANR instead of
234 // Surface lost or other errors.
235 private static final int STOP_TIMEOUT = 11 * 1000;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -0700236
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700237 // How long we wait until giving up on an activity telling us it has
238 // finished destroying itself.
Andrii Kulian21713ac2016-10-12 22:05:05 -0700239 private static final int DESTROY_TIMEOUT = 10 * 1000;
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800240
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700241 // Set to false to disable the preview that is shown while a new activity
242 // is being started.
Andrii Kulian21713ac2016-10-12 22:05:05 -0700243 private static final boolean SHOW_APP_STARTING_PREVIEW = true;
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800244
Craig Mautner5eda9b32013-07-02 11:58:16 -0700245 // How long to wait for all background Activities to redraw following a call to
246 // convertToTranslucent().
Andrii Kulian21713ac2016-10-12 22:05:05 -0700247 private static final long TRANSLUCENT_CONVERSION_TIMEOUT = 2000;
Craig Mautner5eda9b32013-07-02 11:58:16 -0700248
Andrii Kulian0c869cc2019-02-06 19:50:32 -0800249 @IntDef(prefix = {"STACK_VISIBILITY"}, value = {
250 STACK_VISIBILITY_VISIBLE,
251 STACK_VISIBILITY_VISIBLE_BEHIND_TRANSLUCENT,
252 STACK_VISIBILITY_INVISIBLE,
253 })
254 @interface StackVisibility {}
255
256 /** Stack is visible. No other stacks on top that fully or partially occlude it. */
257 static final int STACK_VISIBILITY_VISIBLE = 0;
258
259 /** Stack is partially occluded by other translucent stack(s) on top of it. */
260 static final int STACK_VISIBILITY_VISIBLE_BEHIND_TRANSLUCENT = 1;
261
262 /** Stack is completely invisible. */
263 static final int STACK_VISIBILITY_INVISIBLE = 2;
264
Louis Changdc077272019-11-12 16:52:56 +0800265 /** Minimum size of an adjusted stack bounds relative to original stack bounds. Used to
266 * restrict IME adjustment so that a min portion of top stack remains visible.*/
267 private static final float ADJUSTED_STACK_FRACTION_MIN = 0.3f;
Evan Roskyc5abbd82018-10-05 16:02:19 -0700268
Louis Changdc077272019-11-12 16:52:56 +0800269 /** Dimming amount for non-focused stack when stacks are IME-adjusted. */
270 private static final float IME_ADJUST_DIM_AMOUNT = 0.25f;
Andrii Kulianfb1bf692017-01-17 11:17:34 -0800271
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700272 enum ActivityState {
273 INITIALIZING,
Louis Changeadb22f2019-06-19 12:09:23 +0800274 STARTED,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700275 RESUMED,
276 PAUSING,
277 PAUSED,
278 STOPPING,
279 STOPPED,
280 FINISHING,
281 DESTROYING,
Riddle Hsu7b766fd2019-01-28 21:14:59 +0800282 DESTROYED,
283 RESTARTING_PROCESS
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700284 }
285
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700286 final ActivityTaskManagerService mService;
Yunfan Chen279f5582018-12-12 15:24:50 -0800287 final WindowManagerService mWindowManager;
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800288
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700289 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700290 * List of running activities, sorted by recent usage.
291 * The first entry in the list is the least recently used.
292 * It contains HistoryRecord objects.
293 */
Riddle Hsu5477b572019-11-12 16:07:29 +0800294 private final ArrayList<ActivityRecord> mLruActivities = new ArrayList<>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700295
296 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700297 * When we are in the process of pausing an activity, before starting the
298 * next one, this variable holds the activity that is currently being paused.
299 */
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800300 ActivityRecord mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700301
302 /**
303 * This is the last activity that we put into the paused state. This is
304 * used to determine if we need to do an activity transition while sleeping,
305 * when we normally hold the top activity paused.
306 */
307 ActivityRecord mLastPausedActivity = null;
308
309 /**
Craig Mautner0f922742013-08-06 08:44:42 -0700310 * Activities that specify No History must be removed once the user navigates away from them.
311 * If the device goes to sleep with such an activity in the paused state then we save it here
312 * and finish it later if another activity replaces it on wakeup.
313 */
314 ActivityRecord mLastNoHistoryActivity = null;
315
316 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700317 * Current activity that is resumed, or null if there is none.
318 */
319 ActivityRecord mResumedActivity = null;
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800320
Craig Mautner5eda9b32013-07-02 11:58:16 -0700321 // The topmost Activity passed to convertToTranslucent(). When non-null it means we are
322 // waiting for all Activities in mUndrawnActivitiesBelowTopTranslucent to be removed as they
323 // are drawn. When the last member of mUndrawnActivitiesBelowTopTranslucent is removed the
324 // Activity in mTranslucentActivityWaiting is notified via
325 // Activity.onTranslucentConversionComplete(false). If a timeout occurs prior to the last
326 // background activity being drawn then the same call will be made with a true value.
327 ActivityRecord mTranslucentActivityWaiting = null;
Andrii Kulian21713ac2016-10-12 22:05:05 -0700328 ArrayList<ActivityRecord> mUndrawnActivitiesBelowTopTranslucent = new ArrayList<>();
Craig Mautner5eda9b32013-07-02 11:58:16 -0700329
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700330 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700331 * Set when we know we are going to be calling updateConfiguration()
332 * soon, so want to skip intermediate config checks.
333 */
334 boolean mConfigWillChange;
335
Winson Chung47900652017-04-06 18:44:25 -0700336 /**
337 * When set, will force the stack to report as invisible.
338 */
339 boolean mForceHidden = false;
340
Andrii Kulian6b321512019-01-23 06:37:00 +0000341 /**
342 * Used to keep resumeTopActivityUncheckedLocked() from being entered recursively
343 */
344 boolean mInResumeTopActivity = false;
345
Andrii Kulian21713ac2016-10-12 22:05:05 -0700346 private boolean mUpdateBoundsDeferred;
347 private boolean mUpdateBoundsDeferredCalled;
Evan Rosky1ac84462018-11-13 11:25:30 -0800348 private boolean mUpdateDisplayedBoundsDeferredCalled;
Andrii Kulian21713ac2016-10-12 22:05:05 -0700349 private final Rect mDeferredBounds = new Rect();
Evan Rosky1ac84462018-11-13 11:25:30 -0800350 private final Rect mDeferredDisplayedBounds = new Rect();
Jorim Jaggi192086e2016-03-11 17:17:03 +0100351
Craig Mautner858d8a62013-04-23 17:08:34 -0700352 int mCurrentUser;
Amith Yamasani742a6712011-05-04 14:49:28 -0700353
Craig Mautnere0a38842013-12-16 16:14:02 -0800354 /** The attached Display's unique identifier, or -1 if detached */
355 int mDisplayId;
Wale Ogunwale2322bed2019-10-10 17:24:19 +0200356 // Id of the previous display the stack was on.
357 int mPrevDisplayId = INVALID_DISPLAY;
Craig Mautner4a1cb222013-12-04 16:14:06 -0800358
Louis Changdc077272019-11-12 16:52:56 +0800359 /** Unique identifier */
360 final int mStackId;
361
362 /** For comparison with DisplayContent bounds. */
363 private Rect mTmpRect = new Rect();
364 private Rect mTmpRect2 = new Rect();
365 private Rect mTmpRect3 = new Rect();
366
367 /** For Pinned stack controlling. */
368 private Rect mTmpToBounds = new Rect();
369
370 /** Stack bounds adjusted to screen content area (taking into account IM windows, etc.) */
371 private final Rect mAdjustedBounds = new Rect();
372
373 /**
374 * Fully adjusted IME bounds. These are different from {@link #mAdjustedBounds} because they
375 * represent the state when the animation has ended.
376 */
377 private final Rect mFullyAdjustedImeBounds = new Rect();
378
379 /** ActivityRecords that are exiting, but still on screen for animations. */
380 final ArrayList<ActivityRecord> mExitingActivities = new ArrayList<>();
381
382 /** Detach this stack from its display when animation completes. */
383 // TODO: maybe tie this to WindowContainer#removeChild some how...
384 private boolean mDeferRemoval;
385
386 private final Rect mTmpAdjustedBounds = new Rect();
387 private boolean mAdjustedForIme;
388 private boolean mImeGoingAway;
389 private WindowState mImeWin;
390 private float mMinimizeAmount;
391 private float mAdjustImeAmount;
392 private float mAdjustDividerAmount;
393 private final int mDockedStackMinimizeThickness;
394
395 // If this is true, we are in the bounds animating mode. The task will be down or upscaled to
396 // perfectly fit the region it would have been cropped to. We may also avoid certain logic we
397 // would otherwise apply while resizing, while resizing in the bounds animating mode.
398 private boolean mBoundsAnimating = false;
399 // Set when an animation has been requested but has not yet started from the UI thread. This is
400 // cleared when the animation actually starts.
401 private boolean mBoundsAnimatingRequested = false;
402 private boolean mBoundsAnimatingToFullscreen = false;
403 private boolean mCancelCurrentBoundsAnimation = false;
404 private Rect mBoundsAnimationTarget = new Rect();
405 private Rect mBoundsAnimationSourceHintBounds = new Rect();
406 private @BoundsAnimationController.AnimationType int mAnimationType;
407
408 Rect mPreAnimationBounds = new Rect();
409
410 private Dimmer mDimmer = new Dimmer(this);
411
412 /**
413 * For {@link #prepareSurfaces}.
414 */
415 private final Rect mTmpDimBoundsRect = new Rect();
416 private final Point mLastSurfaceSize = new Point();
417
418 private final AnimatingActivityRegistry mAnimatingActivityRegistry =
419 new AnimatingActivityRegistry();
420
Evan Rosky10475742018-09-05 19:02:48 -0700421 /** Stores the override windowing-mode from before a transient mode change (eg. split) */
422 private int mRestoreOverrideWindowingMode = WINDOWING_MODE_UNDEFINED;
423
Bryce Leefbd263b42018-03-07 10:33:55 -0800424 /** List for processing through a set of activities */
425 private final ArrayList<ActivityRecord> mTmpActivities = new ArrayList<>();
426
Craig Mautner27084302013-03-25 08:05:25 -0700427 /** Run all ActivityStacks through this */
Winson Chung5af42fc2017-03-24 17:11:33 -0700428 protected final ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800429 protected final RootActivityContainer mRootActivityContainer;
Craig Mautner27084302013-03-25 08:05:25 -0700430
Jorim Jaggife762342016-10-13 14:33:27 +0200431 private boolean mTopActivityOccludesKeyguard;
432 private ActivityRecord mTopDismissingKeyguardActivity;
433
Andrii Kulian79d67982019-08-19 11:56:16 -0700434 private static final int PAUSE_TIMEOUT_MSG = FIRST_ACTIVITY_STACK_MSG + 1;
435 private static final int DESTROY_TIMEOUT_MSG = FIRST_ACTIVITY_STACK_MSG + 2;
436 private static final int LAUNCH_TICK_MSG = FIRST_ACTIVITY_STACK_MSG + 3;
437 private static final int STOP_TIMEOUT_MSG = FIRST_ACTIVITY_STACK_MSG + 4;
438 private static final int DESTROY_ACTIVITIES_MSG = FIRST_ACTIVITY_STACK_MSG + 5;
439 private static final int TRANSLUCENT_TIMEOUT_MSG = FIRST_ACTIVITY_STACK_MSG + 6;
Dianne Hackborn755c8bf2012-05-07 15:06:09 -0700440
Andrii Kulian21713ac2016-10-12 22:05:05 -0700441 private static class ScheduleDestroyArgs {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700442 final WindowProcessController mOwner;
Dianne Hackborn755c8bf2012-05-07 15:06:09 -0700443 final String mReason;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700444 ScheduleDestroyArgs(WindowProcessController owner, String reason) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -0700445 mOwner = owner;
Dianne Hackborn755c8bf2012-05-07 15:06:09 -0700446 mReason = reason;
447 }
448 }
449
Andrii Kulian79d67982019-08-19 11:56:16 -0700450 private final Handler mHandler;
Zoran Marcetaf958b322012-08-09 20:27:12 +0900451
Andrii Kulian21713ac2016-10-12 22:05:05 -0700452 private class ActivityStackHandler extends Handler {
Wale Ogunwalee23149f2015-03-06 15:39:44 -0800453
Craig Mautnerc8143c62013-09-03 12:15:57 -0700454 ActivityStackHandler(Looper looper) {
Zoran Marcetaf958b322012-08-09 20:27:12 +0900455 super(looper);
456 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700457
Zoran Marcetaf958b322012-08-09 20:27:12 +0900458 @Override
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700459 public void handleMessage(Message msg) {
460 switch (msg.what) {
461 case PAUSE_TIMEOUT_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800462 ActivityRecord r = (ActivityRecord)msg.obj;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700463 // We don't at this point know if the activity is fullscreen,
464 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800465 Slog.w(TAG, "Activity pause timeout for " + r);
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700466 synchronized (mService.mGlobalLock) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700467 if (r.hasProcess()) {
468 mService.logAppTooSlow(r.app, r.pauseTime, "pausing " + r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700469 }
Dianne Hackborna4e102e2014-09-04 22:52:27 -0700470 activityPausedLocked(r.appToken, true);
Craig Mautnerd2328952013-03-05 12:46:26 -0800471 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700472 } break;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700473 case LAUNCH_TICK_MSG: {
474 ActivityRecord r = (ActivityRecord)msg.obj;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700475 synchronized (mService.mGlobalLock) {
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700476 if (r.continueLaunchTickingLocked()) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700477 mService.logAppTooSlow(r.app, r.launchTickTime, "launching " + r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700478 }
479 }
480 } break;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700481 case DESTROY_TIMEOUT_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800482 ActivityRecord r = (ActivityRecord)msg.obj;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700483 // We don't at this point know if the activity is fullscreen,
484 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800485 Slog.w(TAG, "Activity destroy timeout for " + r);
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700486 synchronized (mService.mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -0700487 if (r != null) {
488 r.destroyed("destroyTimeout");
489 }
Craig Mautnerd2328952013-03-05 12:46:26 -0800490 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700491 } break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -0700492 case STOP_TIMEOUT_MSG: {
493 ActivityRecord r = (ActivityRecord)msg.obj;
494 // We don't at this point know if the activity is fullscreen,
495 // so we need to be conservative and assume it isn't.
496 Slog.w(TAG, "Activity stop timeout for " + r);
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700497 synchronized (mService.mGlobalLock) {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -0700498 if (r.isInHistory()) {
Andrii Kulian21713ac2016-10-12 22:05:05 -0700499 r.activityStoppedLocked(null /* icicle */,
500 null /* persistentState */, null /* description */);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -0700501 }
502 }
503 } break;
Dianne Hackborn755c8bf2012-05-07 15:06:09 -0700504 case DESTROY_ACTIVITIES_MSG: {
505 ScheduleDestroyArgs args = (ScheduleDestroyArgs)msg.obj;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700506 synchronized (mService.mGlobalLock) {
Craig Mautneree2e45a2014-06-27 12:10:03 -0700507 destroyActivitiesLocked(args.mOwner, args.mReason);
Dianne Hackborn755c8bf2012-05-07 15:06:09 -0700508 }
Craig Mautner5eda9b32013-07-02 11:58:16 -0700509 } break;
510 case TRANSLUCENT_TIMEOUT_MSG: {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700511 synchronized (mService.mGlobalLock) {
Craig Mautner5eda9b32013-07-02 11:58:16 -0700512 notifyActivityDrawnLocked(null);
513 }
514 } break;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700515 }
516 }
Craig Mautner4b71aa12012-12-27 17:20:01 -0800517 }
518
Craig Mautner34b73df2014-01-12 21:11:08 -0800519 int numActivities() {
Craig Mautner000f0022013-02-26 15:04:29 -0800520 int count = 0;
Wale Ogunwale2187b7c2019-10-26 21:38:43 -0700521 for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) {
522 count += getChildAt(taskNdx).getChildCount();
Craig Mautner000f0022013-02-26 15:04:29 -0800523 }
524 return count;
525 }
526
Wale Ogunwale9dcf9462017-09-19 15:13:01 -0700527 ActivityStack(ActivityDisplay display, int stackId, ActivityStackSupervisor supervisor,
Wale Ogunwale04a05ac2017-09-17 21:35:02 -0700528 int windowingMode, int activityType, boolean onTop) {
Louis Changdc077272019-11-12 16:52:56 +0800529 super(supervisor.mService.mWindowManager);
530 mStackId = stackId;
531 mDockedStackMinimizeThickness =
532 supervisor.mService.mWindowManager.mContext.getResources().getDimensionPixelSize(
533 com.android.internal.R.dimen.docked_stack_minimize_thickness);
534 EventLog.writeEvent(com.android.server.EventLogTags.WM_STACK_CREATED, stackId);
Andrii Kulian94e82d9b02017-07-13 15:33:06 -0700535 mStackSupervisor = supervisor;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700536 mService = supervisor.mService;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800537 mRootActivityContainer = mService.mRootActivityContainer;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700538 mHandler = new ActivityStackHandler(supervisor.mLooper);
Craig Mautner4a1cb222013-12-04 16:14:06 -0800539 mWindowManager = mService.mWindowManager;
Evan Rosky282ee672019-11-13 15:50:46 -0800540 mRemoteToken = new RemoteToken(this);
Wale Ogunwale86b74462018-07-02 08:42:43 -0700541 mCurrentUser = mService.mAmInternal.getCurrentUserId();
Andrii Kulian2fcc4512018-01-25 16:39:27 -0800542 // Set display id before setting activity and window type to make sure it won't affect
543 // stacks on a wrong display.
544 mDisplayId = display.mDisplayId;
Wale Ogunwale04a05ac2017-09-17 21:35:02 -0700545 setActivityType(activityType);
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -0700546 display.addChild(this, onTop ? POSITION_TOP : POSITION_BOTTOM);
Evan Roskyc5abbd82018-10-05 16:02:19 -0700547 setWindowingMode(windowingMode, false /* animate */, false /* showRecents */,
548 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
549 true /* creating */);
Filip Gruszczynskie5390e72015-08-18 16:39:00 -0700550 }
551
Bryce Leec4ab62a2018-03-05 14:19:26 -0800552 /**
553 * This should be called when an activity in a child task changes state. This should only
554 * be called from
Louis Changcdec0802019-11-11 11:45:07 +0800555 * {@link Task#onActivityStateChanged(ActivityRecord, ActivityState, String)}.
Bryce Leec4ab62a2018-03-05 14:19:26 -0800556 * @param record The {@link ActivityRecord} whose state has changed.
557 * @param state The new state.
558 * @param reason The reason for the change.
559 */
560 void onActivityStateChanged(ActivityRecord record, ActivityState state, String reason) {
561 if (record == mResumedActivity && state != RESUMED) {
Bryce Lee84730a02018-04-03 14:10:04 -0700562 setResumedActivity(null, reason + " - onActivityStateChanged");
Bryce Leec4ab62a2018-03-05 14:19:26 -0800563 }
564
565 if (state == RESUMED) {
566 if (DEBUG_STACK) Slog.v(TAG_STACK, "set resumed activity to:" + record + " reason:"
567 + reason);
Bryce Lee84730a02018-04-03 14:10:04 -0700568 setResumedActivity(record, reason + " - onActivityStateChanged");
Wale Ogunwaled32da472018-11-16 07:19:28 -0800569 if (record == mRootActivityContainer.getTopResumedActivity()) {
Andrii Kulianab132ee2018-07-24 22:10:21 +0800570 mService.setResumedActivityUncheckLocked(record, reason);
571 }
Louis Changcdec0802019-11-11 11:45:07 +0800572 mStackSupervisor.mRecentTasks.add(record.getTask());
Bryce Leec4ab62a2018-03-05 14:19:26 -0800573 }
574 }
575
Wale Ogunwalea0f5b5e2017-10-11 09:37:23 -0700576 @Override
577 public void onConfigurationChanged(Configuration newParentConfig) {
578 final int prevWindowingMode = getWindowingMode();
Kazuki Takise048e2662018-06-27 17:05:11 +0900579 final boolean prevIsAlwaysOnTop = isAlwaysOnTop();
Evan Roskyc5abbd82018-10-05 16:02:19 -0700580 final int prevRotation = getWindowConfiguration().getRotation();
581 final int prevDensity = getConfiguration().densityDpi;
582 final int prevScreenW = getConfiguration().screenWidthDp;
583 final int prevScreenH = getConfiguration().screenHeightDp;
Riddle Hsud1069732019-05-09 17:04:31 +0800584 final Rect newBounds = mTmpRect;
585 // Initialize the new bounds by previous bounds as the input and output for calculating
586 // override bounds in pinned (pip) or split-screen mode.
587 getBounds(newBounds);
Evan Roskye747c3e2018-10-30 20:06:41 -0700588
589 super.onConfigurationChanged(newParentConfig);
Louis Changdc077272019-11-12 16:52:56 +0800590
591 // Only need to update surface size here since the super method will handle updating
592 // surface position.
593 updateSurfaceSize(getPendingTransaction());
594
595 if (mDisplayContent == null) {
596 return;
597 }
598
599 if (prevWindowingMode != getWindowingMode()) {
600 mDisplayContent.onStackWindowingModeChanged(this);
601
602 if (inSplitScreenSecondaryWindowingMode()) {
603 // When the stack is resized due to entering split screen secondary, offset the
604 // windows to compensate for the new stack position.
605 forAllWindows(w -> {
606 w.mWinAnimator.setOffsetPositionForStackResize(true);
607 }, true);
608 }
609 }
610
Riddle Hsud1069732019-05-09 17:04:31 +0800611 final ActivityDisplay display = getDisplay();
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -0700612 if (display == null ) {
Yunfan Chen279f5582018-12-12 15:24:50 -0800613 return;
614 }
Evan Roskyc5abbd82018-10-05 16:02:19 -0700615
Riddle Hsud1069732019-05-09 17:04:31 +0800616 final boolean windowingModeChanged = prevWindowingMode != getWindowingMode();
617 final int overrideWindowingMode = getRequestedOverrideWindowingMode();
Evan Roskyc5abbd82018-10-05 16:02:19 -0700618 // Update bounds if applicable
619 boolean hasNewOverrideBounds = false;
620 // Use override windowing mode to prevent extra bounds changes if inheriting the mode.
Riddle Hsud1069732019-05-09 17:04:31 +0800621 if (overrideWindowingMode == WINDOWING_MODE_PINNED) {
Evan Roskyc5abbd82018-10-05 16:02:19 -0700622 // Pinned calculation already includes rotation
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -0700623 hasNewOverrideBounds = calculatePinnedBoundsForConfigChange(newBounds);
Riddle Hsud1069732019-05-09 17:04:31 +0800624 } else if (!matchParentBounds()) {
625 // If the parent (display) has rotated, rotate our bounds to best-fit where their
626 // bounds were on the pre-rotated display.
Evan Roskyc5abbd82018-10-05 16:02:19 -0700627 final int newRotation = getWindowConfiguration().getRotation();
Riddle Hsud1069732019-05-09 17:04:31 +0800628 final boolean rotationChanged = prevRotation != newRotation;
629 if (rotationChanged) {
630 display.mDisplayContent.rotateBounds(
631 newParentConfig.windowConfiguration.getBounds(), prevRotation, newRotation,
632 newBounds);
633 hasNewOverrideBounds = true;
634 }
Evan Roskyc5abbd82018-10-05 16:02:19 -0700635
Riddle Hsud1069732019-05-09 17:04:31 +0800636 // Use override windowing mode to prevent extra bounds changes if inheriting the mode.
637 if (overrideWindowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY
638 || overrideWindowingMode == WINDOWING_MODE_SPLIT_SCREEN_SECONDARY) {
Evan Roskyc5abbd82018-10-05 16:02:19 -0700639 // If entering split screen or if something about the available split area changes,
640 // recalculate the split windows to match the new configuration.
Riddle Hsud1069732019-05-09 17:04:31 +0800641 if (rotationChanged || windowingModeChanged
Evan Roskyc5abbd82018-10-05 16:02:19 -0700642 || prevDensity != getConfiguration().densityDpi
Evan Roskyc5abbd82018-10-05 16:02:19 -0700643 || prevScreenW != getConfiguration().screenWidthDp
644 || prevScreenH != getConfiguration().screenHeightDp) {
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -0700645 calculateDockedBoundsForConfigChange(newParentConfig, newBounds);
Riddle Hsud1069732019-05-09 17:04:31 +0800646 hasNewOverrideBounds = true;
Evan Roskyc5abbd82018-10-05 16:02:19 -0700647 }
648 }
649 }
Riddle Hsud1069732019-05-09 17:04:31 +0800650
651 if (windowingModeChanged) {
Evan Roskyc5abbd82018-10-05 16:02:19 -0700652 // Use override windowing mode to prevent extra bounds changes if inheriting the mode.
Riddle Hsud1069732019-05-09 17:04:31 +0800653 if (overrideWindowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
654 getStackDockedModeBounds(null /* dockedBounds */, null /* currentTempTaskBounds */,
655 newBounds /* outStackBounds */, mTmpRect2 /* outTempTaskBounds */);
Evan Roskyc5abbd82018-10-05 16:02:19 -0700656 // immediately resize so docked bounds are available in onSplitScreenModeActivated
Evan Rosky1ac84462018-11-13 11:25:30 -0800657 setTaskDisplayedBounds(null);
Riddle Hsud1069732019-05-09 17:04:31 +0800658 setTaskBounds(newBounds);
659 setBounds(newBounds);
660 newBounds.set(newBounds);
661 } else if (overrideWindowingMode == WINDOWING_MODE_SPLIT_SCREEN_SECONDARY) {
Evan Roskyc5abbd82018-10-05 16:02:19 -0700662 Rect dockedBounds = display.getSplitScreenPrimaryStack().getBounds();
Wale Ogunwale3a256e62018-12-06 14:41:18 -0800663 final boolean isMinimizedDock =
Riddle Hsud1069732019-05-09 17:04:31 +0800664 display.mDisplayContent.getDockedDividerController().isMinimizedDock();
Evan Roskyc5abbd82018-10-05 16:02:19 -0700665 if (isMinimizedDock) {
Louis Changcdec0802019-11-11 11:45:07 +0800666 Task topTask = display.getSplitScreenPrimaryStack().topTask();
Evan Roskyc5abbd82018-10-05 16:02:19 -0700667 if (topTask != null) {
668 dockedBounds = topTask.getBounds();
669 }
670 }
Riddle Hsud1069732019-05-09 17:04:31 +0800671 getStackDockedModeBounds(dockedBounds, null /* currentTempTaskBounds */,
672 newBounds /* outStackBounds */, mTmpRect2 /* outTempTaskBounds */);
Evan Roskyc5abbd82018-10-05 16:02:19 -0700673 hasNewOverrideBounds = true;
674 }
Wale Ogunwalea0f5b5e2017-10-11 09:37:23 -0700675 display.onStackWindowingModeChanged(this);
676 }
Evan Roskyc5abbd82018-10-05 16:02:19 -0700677 if (hasNewOverrideBounds) {
Evan Roskydbe2ce52019-07-18 11:13:17 -0700678 if (inSplitScreenPrimaryWindowingMode()) {
679 mStackSupervisor.resizeDockedStackLocked(new Rect(newBounds),
680 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
681 null /* tempOtherTaskBounds */, null /* tempOtherTaskInsetBounds */,
682 PRESERVE_WINDOWS, true /* deferResume */);
683 } else {
684 resize(new Rect(newBounds), null /* tempTaskBounds */,
685 null /* tempTaskInsetBounds */, PRESERVE_WINDOWS, true /* deferResume */);
686 }
Evan Roskye747c3e2018-10-30 20:06:41 -0700687 }
Kazuki Takise048e2662018-06-27 17:05:11 +0900688 if (prevIsAlwaysOnTop != isAlwaysOnTop()) {
689 // Since always on top is only on when the stack is freeform or pinned, the state
690 // can be toggled when the windowing mode changes. We must make sure the stack is
691 // placed properly when always on top state changes.
Riddle Hsu57831b52018-07-27 00:31:48 +0800692 display.positionChildAtTop(this, false /* includingParents */);
Kazuki Takise048e2662018-06-27 17:05:11 +0900693 }
Wale Ogunwalea0f5b5e2017-10-11 09:37:23 -0700694 }
695
Wale Ogunwaleab5de372017-10-18 06:46:31 -0700696 @Override
Wale Ogunwale30e441d2017-11-09 08:28:45 -0800697 public void setWindowingMode(int windowingMode) {
Winson Chung3e36f822018-01-16 12:06:04 -0800698 setWindowingMode(windowingMode, false /* animate */, false /* showRecents */,
Evan Roskyc5abbd82018-10-05 16:02:19 -0700699 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
700 false /* creating */);
Wale Ogunwale30e441d2017-11-09 08:28:45 -0800701 }
702
Evan Rosky10475742018-09-05 19:02:48 -0700703 /**
704 * A transient windowing mode is one which activities enter into temporarily. Examples of this
705 * are Split window modes and pip. Non-transient modes are modes that displays can adopt.
706 *
707 * @param windowingMode the windowingMode to test for transient-ness.
708 * @return {@code true} if the windowing mode is transient, {@code false} otherwise.
709 */
710 private static boolean isTransientWindowingMode(int windowingMode) {
711 // TODO(b/114842032): add PIP if/when it uses mode transitions instead of task reparenting
712 return windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY
713 || windowingMode == WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
714 }
715
716 /**
717 * Specialization of {@link #setWindowingMode(int)} for this subclass.
718 *
719 * @param preferredWindowingMode the preferred windowing mode. This may not be honored depending
720 * on the state of things. For example, WINDOWING_MODE_UNDEFINED will resolve to the
721 * previous non-transient mode if this stack is currently in a transient mode.
722 * @param animate Can be used to prevent animation.
723 * @param showRecents Controls whether recents is shown on the other side of a split while
724 * entering split mode.
725 * @param enteringSplitScreenMode {@code true} if entering split mode.
726 * @param deferEnsuringVisibility Whether visibility updates are deferred. This is set when
727 * many operations (which can effect visibility) are being performed in bulk.
Evan Roskyc5abbd82018-10-05 16:02:19 -0700728 * @param creating {@code true} if this is being run during ActivityStack construction.
Evan Rosky10475742018-09-05 19:02:48 -0700729 */
Wale Ogunwaledf262f52017-12-07 18:17:12 -0800730 void setWindowingMode(int preferredWindowingMode, boolean animate, boolean showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -0700731 boolean enteringSplitScreenMode, boolean deferEnsuringVisibility, boolean creating) {
Tiger Huang6dcbee62019-02-20 21:45:55 +0800732 mWindowManager.inSurfaceTransaction(() -> setWindowingModeInSurfaceTransaction(
733 preferredWindowingMode, animate, showRecents, enteringSplitScreenMode,
734 deferEnsuringVisibility, creating));
735 }
736
737 private void setWindowingModeInSurfaceTransaction(int preferredWindowingMode, boolean animate,
738 boolean showRecents, boolean enteringSplitScreenMode, boolean deferEnsuringVisibility,
739 boolean creating) {
Wale Ogunwale30e441d2017-11-09 08:28:45 -0800740 final int currentMode = getWindowingMode();
Evan Roskydfe3da72018-10-26 17:21:06 -0700741 final int currentOverrideMode = getRequestedOverrideWindowingMode();
Wale Ogunwale30e441d2017-11-09 08:28:45 -0800742 final ActivityDisplay display = getDisplay();
Louis Changcdec0802019-11-11 11:45:07 +0800743 final Task topTask = topTask();
Wale Ogunwale30e441d2017-11-09 08:28:45 -0800744 final ActivityStack splitScreenStack = display.getSplitScreenPrimaryStack();
Evan Rosky9ba524e2018-01-03 16:27:56 -0800745 int windowingMode = preferredWindowingMode;
Evan Rosky10475742018-09-05 19:02:48 -0700746 if (preferredWindowingMode == WINDOWING_MODE_UNDEFINED
747 && isTransientWindowingMode(currentMode)) {
748 // Leaving a transient mode. Interpret UNDEFINED as "restore"
749 windowingMode = mRestoreOverrideWindowingMode;
750 }
Evan Rosky10475742018-09-05 19:02:48 -0700751
Wale Ogunwale1dbc5c82017-12-08 08:12:20 -0800752 // Need to make sure windowing mode is supported. If we in the process of creating the stack
753 // no need to resolve the windowing mode again as it is already resolved to the right mode.
Evan Rosky9ba524e2018-01-03 16:27:56 -0800754 if (!creating) {
755 windowingMode = display.validateWindowingMode(windowingMode,
756 null /* ActivityRecord */, topTask, getActivityType());
757 }
758 if (splitScreenStack == this
759 && windowingMode == WINDOWING_MODE_SPLIT_SCREEN_SECONDARY) {
760 // Resolution to split-screen secondary for the primary split-screen stack means
Evan Rosky10475742018-09-05 19:02:48 -0700761 // we want to leave split-screen mode.
762 windowingMode = mRestoreOverrideWindowingMode;
Wale Ogunwale30e441d2017-11-09 08:28:45 -0800763 }
764
Wale Ogunwaleac36e4d2017-11-29 13:30:26 -0800765 final boolean alreadyInSplitScreenMode = display.hasSplitScreenPrimaryStack();
766
Wale Ogunwale1dbc5c82017-12-08 08:12:20 -0800767 // Don't send non-resizeable notifications if the windowing mode changed was a side effect
768 // of us entering split-screen mode.
769 final boolean sendNonResizeableNotification = !enteringSplitScreenMode;
Wale Ogunwale30e441d2017-11-09 08:28:45 -0800770 // Take any required action due to us not supporting the preferred windowing mode.
Wale Ogunwale1dbc5c82017-12-08 08:12:20 -0800771 if (alreadyInSplitScreenMode && windowingMode == WINDOWING_MODE_FULLSCREEN
772 && sendNonResizeableNotification && isActivityTypeStandardOrUndefined()) {
773 final boolean preferredSplitScreen =
774 preferredWindowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY
775 || preferredWindowingMode == WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
776 if (preferredSplitScreen || creating) {
777 // Looks like we can't launch in split screen mode or the stack we are launching
778 // doesn't support split-screen mode, go ahead an dismiss split-screen and display a
779 // warning toast about it.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700780 mService.getTaskChangeNotificationController().notifyActivityDismissingDockedStack();
Evan Roskyc5abbd82018-10-05 16:02:19 -0700781 final ActivityStack primarySplitStack = display.getSplitScreenPrimaryStack();
Tiger Huang6dcbee62019-02-20 21:45:55 +0800782 primarySplitStack.setWindowingModeInSurfaceTransaction(WINDOWING_MODE_UNDEFINED,
Andrii Kulian9da138a2018-04-24 17:12:44 -0700783 false /* animate */, false /* showRecents */,
Evan Roskyc5abbd82018-10-05 16:02:19 -0700784 false /* enteringSplitScreenMode */, true /* deferEnsuringVisibility */,
785 primarySplitStack == this ? creating : false);
Wale Ogunwale30e441d2017-11-09 08:28:45 -0800786 }
787 }
788
789 if (currentMode == windowingMode) {
Evan Rosky10475742018-09-05 19:02:48 -0700790 // You are already in the window mode, so we can skip most of the work below. However,
791 // it's possible that we have inherited the current windowing mode from a parent. So,
792 // fulfill this method's contract by setting the override mode directly.
Evan Roskydfe3da72018-10-26 17:21:06 -0700793 getRequestedOverrideConfiguration().windowConfiguration.setWindowingMode(windowingMode);
Wale Ogunwale30e441d2017-11-09 08:28:45 -0800794 return;
795 }
796
Wale Ogunwale21e06482019-11-18 05:14:15 -0800797 final ActivityRecord topActivity = getTopNonFinishingActivity();
Wale Ogunwale30e441d2017-11-09 08:28:45 -0800798
Evan Rosky10475742018-09-05 19:02:48 -0700799 // For now, assume that the Stack's windowing mode is what will actually be used
800 // by it's activities. In the future, there may be situations where this doesn't
801 // happen; so at that point, this message will need to handle that.
802 int likelyResolvedMode = windowingMode;
803 if (windowingMode == WINDOWING_MODE_UNDEFINED) {
804 final ConfigurationContainer parent = getParent();
805 likelyResolvedMode = parent != null ? parent.getWindowingMode()
806 : WINDOWING_MODE_FULLSCREEN;
807 }
808 if (sendNonResizeableNotification && likelyResolvedMode != WINDOWING_MODE_FULLSCREEN
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -0700809 && topActivity != null && !topActivity.noDisplay
810 && topActivity.isNonResizableOrForcedResizable(likelyResolvedMode)) {
Wale Ogunwale30e441d2017-11-09 08:28:45 -0800811 // Inform the user that they are starting an app that may not work correctly in
812 // multi-window mode.
Andrii Kulianeceebbf2019-06-26 17:36:51 -0700813 final String packageName = topActivity.info.applicationInfo.packageName;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700814 mService.getTaskChangeNotificationController().notifyActivityForcedResizable(
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -0700815 topTask.mTaskId, FORCED_RESIZEABLE_REASON_SPLIT_SCREEN, packageName);
Wale Ogunwale30e441d2017-11-09 08:28:45 -0800816 }
817
Riddle Hsua0022cd2019-09-09 21:12:41 +0800818 mService.deferWindowLayout();
Wale Ogunwale30e441d2017-11-09 08:28:45 -0800819 try {
820 if (!animate && topActivity != null) {
Jorim Jaggifa9ed962018-01-25 00:16:49 +0100821 mStackSupervisor.mNoAnimActivities.add(topActivity);
Wale Ogunwale30e441d2017-11-09 08:28:45 -0800822 }
823 super.setWindowingMode(windowingMode);
Evan Rosky7d0705f2018-07-30 12:30:13 -0700824 // setWindowingMode triggers an onConfigurationChanged cascade which can result in a
825 // different resolved windowing mode (usually when preferredWindowingMode is UNDEFINED).
Evan Rosky9ba524e2018-01-03 16:27:56 -0800826 windowingMode = getWindowingMode();
Wale Ogunwale30e441d2017-11-09 08:28:45 -0800827
Wale Ogunwale1dbc5c82017-12-08 08:12:20 -0800828 if (creating) {
Wale Ogunwale30e441d2017-11-09 08:28:45 -0800829 // Nothing else to do if we don't have a window container yet. E.g. call from ctor.
830 return;
831 }
832
Wale Ogunwale30e441d2017-11-09 08:28:45 -0800833 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY && splitScreenStack != null) {
834 // We already have a split-screen stack in this display, so just move the tasks over.
835 // TODO: Figure-out how to do all the stuff in
836 // AMS.setTaskWindowingModeSplitScreenPrimary
837 throw new IllegalArgumentException("Setting primary split-screen windowing mode"
838 + " while there is already one isn't currently supported");
839 //return;
840 }
Evan Rosky10475742018-09-05 19:02:48 -0700841 if (isTransientWindowingMode(windowingMode) && !isTransientWindowingMode(currentMode)) {
842 mRestoreOverrideWindowingMode = currentOverrideMode;
843 }
Wale Ogunwale30e441d2017-11-09 08:28:45 -0800844
845 mTmpRect2.setEmpty();
846 if (windowingMode != WINDOWING_MODE_FULLSCREEN) {
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -0700847 if (matchParentBounds()) {
Yunfan Chen279f5582018-12-12 15:24:50 -0800848 mTmpRect2.setEmpty();
849 } else {
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -0700850 getRawBounds(mTmpRect2);
Yunfan Chen279f5582018-12-12 15:24:50 -0800851 }
Wale Ogunwale30e441d2017-11-09 08:28:45 -0800852 }
853
Evan Roskydfe3da72018-10-26 17:21:06 -0700854 if (!Objects.equals(getRequestedOverrideBounds(), mTmpRect2)) {
Evan Roskydbe2ce52019-07-18 11:13:17 -0700855 resize(mTmpRect2, null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
856 false /* preserveWindows */, true /* deferResume */);
Wale Ogunwale30e441d2017-11-09 08:28:45 -0800857 }
858 } finally {
Wale Ogunwalec59b4f62017-11-30 11:05:43 -0800859 if (showRecents && !alreadyInSplitScreenMode && mDisplayId == DEFAULT_DISPLAY
Wale Ogunwale30e441d2017-11-09 08:28:45 -0800860 && windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
861 // Make sure recents stack exist when creating a dock stack as it normally needs to
862 // be on the other side of the docked stack and we make visibility decisions based
863 // on that.
864 // TODO: This is only here to help out with the case where recents stack doesn't
865 // exist yet. For that case the initial size of the split-screen stack will be the
866 // the one where the home stack is visible since recents isn't visible yet, but the
867 // divider will be off. I think we should just make the initial bounds that of home
868 // so that the divider matches and remove this logic.
Winson Chungc1674272018-02-21 10:15:17 -0800869 // TODO: This is currently only called when entering split-screen while in another
870 // task, and from the tests
Louis Changfe0dfcb2019-09-02 15:59:38 +0800871 // TODO (b/78247419): Fix the rotation animation from fullscreen to minimized mode
872 final boolean isRecentsComponentHome =
873 mService.getRecentTasks().isRecentsComponentHomeActivity(mCurrentUser);
Wale Ogunwale1dbc5c82017-12-08 08:12:20 -0800874 final ActivityStack recentStack = display.getOrCreateStack(
Louis Changfe0dfcb2019-09-02 15:59:38 +0800875 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY,
876 isRecentsComponentHome ? ACTIVITY_TYPE_HOME : ACTIVITY_TYPE_RECENTS,
Wale Ogunwale1dbc5c82017-12-08 08:12:20 -0800877 true /* onTop */);
878 recentStack.moveToFront("setWindowingMode");
Wale Ogunwale30e441d2017-11-09 08:28:45 -0800879 // If task moved to docked stack - show recents if needed.
Winson Chungdff7a732017-12-11 12:17:06 -0800880 mService.mWindowManager.showRecentApps();
Wale Ogunwale30e441d2017-11-09 08:28:45 -0800881 }
Riddle Hsua0022cd2019-09-09 21:12:41 +0800882 mService.continueWindowLayout();
Wale Ogunwale30e441d2017-11-09 08:28:45 -0800883 }
884
Andrii Kulian9da138a2018-04-24 17:12:44 -0700885 if (!deferEnsuringVisibility) {
Wale Ogunwaled32da472018-11-16 07:19:28 -0800886 mRootActivityContainer.ensureActivitiesVisible(null, 0, PRESERVE_WINDOWS);
887 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale1dbc5c82017-12-08 08:12:20 -0800888 }
Wale Ogunwale30e441d2017-11-09 08:28:45 -0800889 }
890
891 @Override
Wale Ogunwaleab5de372017-10-18 06:46:31 -0700892 public boolean isCompatible(int windowingMode, int activityType) {
893 // TODO: Should we just move this to ConfigurationContainer?
894 if (activityType == ACTIVITY_TYPE_UNDEFINED) {
895 // Undefined activity types end up in a standard stack once the stack is created on a
896 // display, so they should be considered compatible.
897 activityType = ACTIVITY_TYPE_STANDARD;
898 }
Wale Ogunwaleab5de372017-10-18 06:46:31 -0700899 return super.isCompatible(windowingMode, activityType);
900 }
901
Riddle Hsu402b4402018-11-06 17:23:15 +0800902 /** Resume next focusable stack after reparenting to another display. */
903 void postReparent() {
Wale Ogunwale66e16852017-10-19 13:35:52 -0700904 adjustFocusToNextFocusableStack("reparent", true /* allowFocusSelf */);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800905 mRootActivityContainer.resumeFocusedStacksTopActivities();
Andrii Kulian51c1b672017-04-07 18:39:32 -0700906 // Update visibility of activities before notifying WM. This way it won't try to resize
907 // windows that are no longer visible.
Wale Ogunwaled32da472018-11-16 07:19:28 -0800908 mRootActivityContainer.ensureActivitiesVisible(null /* starting */, 0 /* configChanges */,
Andrii Kulian51c1b672017-04-07 18:39:32 -0700909 !PRESERVE_WINDOWS);
Andrii Kulian839def92016-11-02 10:58:58 -0700910 }
911
Wale Ogunwale9dcf9462017-09-19 15:13:01 -0700912 ActivityDisplay getDisplay() {
Wale Ogunwaled32da472018-11-16 07:19:28 -0800913 return mRootActivityContainer.getActivityDisplay(mDisplayId);
Andrii Kulian94e82d9b02017-07-13 15:33:06 -0700914 }
915
Winson Chung8bca9e42017-04-16 15:59:43 -0700916 /**
Jorim Jaggi192086e2016-03-11 17:17:03 +0100917 * Defers updating the bounds of the stack. If the stack was resized/repositioned while
918 * deferring, the bounds will update in {@link #continueUpdateBounds()}.
919 */
920 void deferUpdateBounds() {
921 if (!mUpdateBoundsDeferred) {
922 mUpdateBoundsDeferred = true;
923 mUpdateBoundsDeferredCalled = false;
924 }
925 }
926
927 /**
928 * Continues updating bounds after updates have been deferred. If there was a resize attempt
929 * between {@link #deferUpdateBounds()} and {@link #continueUpdateBounds()}, the stack will
930 * be resized to that bounds.
931 */
932 void continueUpdateBounds() {
Evan Rosky1ac84462018-11-13 11:25:30 -0800933 if (mUpdateBoundsDeferred) {
934 mUpdateBoundsDeferred = false;
935 if (mUpdateBoundsDeferredCalled) {
936 setTaskBounds(mDeferredBounds);
937 setBounds(mDeferredBounds);
938 }
939 if (mUpdateDisplayedBoundsDeferredCalled) {
940 setTaskDisplayedBounds(mDeferredDisplayedBounds);
941 }
Jorim Jaggi192086e2016-03-11 17:17:03 +0100942 }
943 }
944
Evan Rosky1ac84462018-11-13 11:25:30 -0800945 boolean updateBoundsAllowed(Rect bounds) {
Jorim Jaggi192086e2016-03-11 17:17:03 +0100946 if (!mUpdateBoundsDeferred) {
947 return true;
948 }
949 if (bounds != null) {
950 mDeferredBounds.set(bounds);
951 } else {
952 mDeferredBounds.setEmpty();
953 }
Jorim Jaggi192086e2016-03-11 17:17:03 +0100954 mUpdateBoundsDeferredCalled = true;
955 return false;
956 }
957
Evan Rosky1ac84462018-11-13 11:25:30 -0800958 boolean updateDisplayedBoundsAllowed(Rect bounds) {
959 if (!mUpdateBoundsDeferred) {
960 return true;
961 }
962 if (bounds != null) {
963 mDeferredDisplayedBounds.set(bounds);
964 } else {
965 mDeferredDisplayedBounds.setEmpty();
966 }
967 mUpdateDisplayedBoundsDeferredCalled = true;
968 return false;
969 }
970
Wale Ogunwale42f07d92017-05-01 21:32:58 -0700971 ActivityRecord topRunningActivityLocked() {
Winson Chung3f103eb2017-04-12 21:53:59 -0700972 return topRunningActivityLocked(false /* focusableOnly */);
973 }
974
Jorim Jaggiea039a82017-08-02 14:37:49 +0200975 void getAllRunningVisibleActivitiesLocked(ArrayList<ActivityRecord> outActivities) {
976 outActivities.clear();
Wale Ogunwale2187b7c2019-10-26 21:38:43 -0700977 for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) {
978 getChildAt(taskNdx).getAllRunningVisibleActivitiesLocked(outActivities);
Jorim Jaggiea039a82017-08-02 14:37:49 +0200979 }
980 }
981
Andrii Kulian52d255c2018-07-13 11:32:19 -0700982 ActivityRecord topRunningActivityLocked(boolean focusableOnly) {
Wale Ogunwale2187b7c2019-10-26 21:38:43 -0700983 for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) {
984 ActivityRecord r = getChildAt(taskNdx).topRunningActivityLocked();
Winson Chung3f103eb2017-04-12 21:53:59 -0700985 if (r != null && (!focusableOnly || r.isFocusable())) {
Craig Mautner6b74cb52013-09-27 17:02:21 -0700986 return r;
Craig Mautner11bf9a52013-02-19 14:08:51 -0800987 }
988 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700989 return null;
990 }
991
Wale Ogunwale42f07d92017-05-01 21:32:58 -0700992 ActivityRecord topRunningNonOverlayTaskActivity() {
Wale Ogunwale2187b7c2019-10-26 21:38:43 -0700993 for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) {
Louis Changcdec0802019-11-11 11:45:07 +0800994 final Task task = getChildAt(taskNdx);
Wale Ogunwale1a06f152019-10-11 11:26:30 +0200995 for (int activityNdx = task.getChildCount() - 1; activityNdx >= 0; --activityNdx) {
996 final ActivityRecord r = task.getChildAt(activityNdx);
Wale Ogunwale42f07d92017-05-01 21:32:58 -0700997 if (!r.finishing && !r.mTaskOverlay) {
998 return r;
999 }
1000 }
1001 }
1002 return null;
1003 }
1004
1005 ActivityRecord topRunningNonDelayedActivityLocked(ActivityRecord notTop) {
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07001006 for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) {
Louis Changcdec0802019-11-11 11:45:07 +08001007 final Task task = getChildAt(taskNdx);
Wale Ogunwale1a06f152019-10-11 11:26:30 +02001008 for (int activityNdx = task.getChildCount() - 1; activityNdx >= 0; --activityNdx) {
1009 final ActivityRecord r = task.getChildAt(activityNdx);
Chong Zhang87761972016-08-22 13:53:24 -07001010 if (!r.finishing && !r.delayedResume && r != notTop && r.okToShowLocked()) {
Craig Mautner11bf9a52013-02-19 14:08:51 -08001011 return r;
1012 }
1013 }
1014 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001015 return null;
1016 }
1017
1018 /**
Wale Ogunwaled32da472018-11-16 07:19:28 -08001019 * This is a simplified version of topRunningActivity that provides a number of
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001020 * optional skip-over modes. It is intended for use with the ActivityController hook only.
Craig Mautner9658b312013-02-28 10:55:59 -08001021 *
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001022 * @param token If non-null, any history records matching this token will be skipped.
1023 * @param taskId If non-zero, we'll attempt to skip over records with the same task ID.
Craig Mautner9658b312013-02-28 10:55:59 -08001024 *
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001025 * @return Returns the HistoryRecord of the next activity on the stack.
1026 */
1027 final ActivityRecord topRunningActivityLocked(IBinder token, int taskId) {
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07001028 for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) {
Louis Changcdec0802019-11-11 11:45:07 +08001029 Task task = getChildAt(taskNdx);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07001030 if (task.mTaskId == taskId) {
Craig Mautner11bf9a52013-02-19 14:08:51 -08001031 continue;
1032 }
Wale Ogunwale1a06f152019-10-11 11:26:30 +02001033 for (int activityNdx = task.getChildCount() - 1; activityNdx >= 0; --activityNdx) {
1034 final ActivityRecord r = task.getChildAt(activityNdx);
Craig Mautner11bf9a52013-02-19 14:08:51 -08001035 // Note: the taskId check depends on real taskId fields being non-zero
Chong Zhang87761972016-08-22 13:53:24 -07001036 if (!r.finishing && (token != r.appToken) && r.okToShowLocked()) {
Craig Mautner11bf9a52013-02-19 14:08:51 -08001037 return r;
1038 }
1039 }
1040 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001041 return null;
1042 }
1043
Wale Ogunwale21e06482019-11-18 05:14:15 -08001044 ActivityRecord getTopNonFinishingActivity() {
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07001045 for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08001046 final ActivityRecord r = getChildAt(taskNdx).getTopNonFinishingActivity();
Wale Ogunwale30e441d2017-11-09 08:28:45 -08001047 if (r != null) {
1048 return r;
Craig Mautner8849a5e2013-04-02 16:41:03 -07001049 }
1050 }
Craig Mautnerde4ef022013-04-07 19:01:33 -07001051 return null;
Craig Mautner8849a5e2013-04-02 16:41:03 -07001052 }
1053
Louis Changcdec0802019-11-11 11:45:07 +08001054 final Task topTask() {
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07001055 final int size = getChildCount();
Craig Mautner9e14d0f2013-05-01 11:26:09 -07001056 if (size > 0) {
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07001057 return getChildAt(size - 1);
Craig Mautner9e14d0f2013-05-01 11:26:09 -07001058 }
1059 return null;
1060 }
1061
Louis Changcdec0802019-11-11 11:45:07 +08001062 Task taskForIdLocked(int id) {
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07001063 for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) {
Louis Changcdec0802019-11-11 11:45:07 +08001064 final Task task = getChildAt(taskNdx);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07001065 if (task.mTaskId == id) {
Craig Mautnerd2328952013-03-05 12:46:26 -08001066 return task;
Craig Mautner5d9c7be2013-02-15 14:02:56 -08001067 }
1068 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001069 return null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001070 }
1071
Craig Mautnerd2328952013-03-05 12:46:26 -08001072 ActivityRecord isInStackLocked(IBinder token) {
Wale Ogunwale7d701172015-03-11 15:36:30 -07001073 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale60454db2015-01-23 16:05:07 -08001074 return isInStackLocked(r);
1075 }
1076
1077 ActivityRecord isInStackLocked(ActivityRecord r) {
1078 if (r == null) {
1079 return null;
1080 }
Louis Changcdec0802019-11-11 11:45:07 +08001081 final Task task = r.getTask();
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001082 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07001083 if (stack != null && task.mChildren.contains(r) && mChildren.contains(task)) {
Andrii Kulian02b7a832016-10-06 23:11:56 -07001084 if (stack != this) Slog.w(TAG,
Craig Mautnerd2328952013-03-05 12:46:26 -08001085 "Illegal state! task does not point to stack it is in.");
Wale Ogunwale60454db2015-01-23 16:05:07 -08001086 return r;
Craig Mautner5d9c7be2013-02-15 14:02:56 -08001087 }
Craig Mautnerd2328952013-03-05 12:46:26 -08001088 return null;
Craig Mautner5d9c7be2013-02-15 14:02:56 -08001089 }
1090
Louis Changcdec0802019-11-11 11:45:07 +08001091 boolean isInStackLocked(Task task) {
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07001092 return mChildren.contains(task);
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001093 }
1094
1095 /** Checks if there are tasks with specific UID in the stack. */
1096 boolean isUidPresent(int uid) {
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07001097 for (int j = getChildCount() - 1; j >= 0; --j) {
Louis Changcdec0802019-11-11 11:45:07 +08001098 final Task task = getChildAt(j);
Wale Ogunwale2322bed2019-10-10 17:24:19 +02001099 for (int i = task.getChildCount() - 1; i >= 0 ; --i) {
1100 final ActivityRecord r = task.getChildAt(i);
David Stevens82ea6cb2017-03-03 16:18:50 -08001101 if (r.getUid() == uid) {
1102 return true;
1103 }
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001104 }
1105 }
1106 return false;
1107 }
1108
1109 /** Get all UIDs that are present in the stack. */
1110 void getPresentUIDs(IntArray presentUIDs) {
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07001111 for (int j = getChildCount() - 1; j >= 0; --j) {
Louis Changcdec0802019-11-11 11:45:07 +08001112 final Task task = getChildAt(j);
Wale Ogunwale2322bed2019-10-10 17:24:19 +02001113 for (int i = task.getChildCount() - 1; i >= 0 ; --i) {
1114 final ActivityRecord r = task.getChildAt(i);
David Stevens82ea6cb2017-03-03 16:18:50 -08001115 presentUIDs.add(r.getUid());
1116 }
Andrii Kulianfb1bf692017-01-17 11:17:34 -08001117 }
1118 }
1119
Wale Ogunwale9e737db2018-12-17 15:42:37 -08001120 /** @return true if the stack can only contain one task */
1121 boolean isSingleTaskInstance() {
1122 final ActivityDisplay display = getDisplay();
1123 return display != null && display.isSingleTaskInstance();
1124 }
1125
Andrii Kulian79d67982019-08-19 11:56:16 -07001126 /** @return {@code true} if LRU list contained the specified activity. */
Riddle Hsu5477b572019-11-12 16:07:29 +08001127 final boolean inLruList(ActivityRecord activity) {
1128 return mLruActivities.contains(activity);
Andrii Kulian79d67982019-08-19 11:56:16 -07001129 }
1130
Riddle Hsu5477b572019-11-12 16:07:29 +08001131 /** @return {@code true} if the given activity was contained in LRU list. */
1132 final boolean updateLruList(ActivityRecord r) {
1133 final boolean contained = mLruActivities.remove(r);
1134 mLruActivities.add(r);
1135 return contained;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001136 }
1137
Matthew Ngae1ff4f2016-11-10 15:49:14 -08001138 final boolean isHomeOrRecentsStack() {
Wale Ogunwale68278562017-09-23 17:13:55 -07001139 return isActivityTypeHome() || isActivityTypeRecents();
Matthew Ngae1ff4f2016-11-10 15:49:14 -08001140 }
1141
Craig Mautnere0a38842013-12-16 16:14:02 -08001142 final boolean isOnHomeDisplay() {
Wale Ogunwale9dcf9462017-09-19 15:13:01 -07001143 return mDisplayId == DEFAULT_DISPLAY;
Craig Mautnere0a38842013-12-16 16:14:02 -08001144 }
1145
Wale Ogunwale66e16852017-10-19 13:35:52 -07001146 private boolean returnsToHomeStack() {
1147 return !inMultiWindowMode()
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07001148 && hasChild()
1149 && getChildAt(0).returnsToHomeStack();
Wale Ogunwale66e16852017-10-19 13:35:52 -07001150 }
1151
Wale Ogunwaleeae451e2015-08-04 15:20:50 -07001152 void moveToFront(String reason) {
1153 moveToFront(reason, null);
1154 }
1155
1156 /**
1157 * @param reason The reason for moving the stack to the front.
1158 * @param task If non-null, the task will be moved to the top of the stack.
1159 * */
Louis Changcdec0802019-11-11 11:45:07 +08001160 void moveToFront(String reason, Task task) {
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -07001161 if (!isAttached()) {
1162 return;
1163 }
Wale Ogunwale925d0d12015-09-23 15:40:07 -07001164
Wale Ogunwalebb285872018-03-01 13:05:30 -08001165 final ActivityDisplay display = getDisplay();
1166
1167 if (inSplitScreenSecondaryWindowingMode()) {
1168 // If the stack is in split-screen seconardy mode, we need to make sure we move the
1169 // primary split-screen stack forward in the case it is currently behind a fullscreen
1170 // stack so both halves of the split-screen appear on-top and the fullscreen stack isn't
1171 // cutting between them.
1172 // TODO(b/70677280): This is a workaround until we can fix as part of b/70677280.
1173 final ActivityStack topFullScreenStack =
1174 display.getTopStackInWindowingMode(WINDOWING_MODE_FULLSCREEN);
1175 if (topFullScreenStack != null) {
1176 final ActivityStack primarySplitScreenStack = display.getSplitScreenPrimaryStack();
1177 if (display.getIndexOf(topFullScreenStack)
1178 > display.getIndexOf(primarySplitScreenStack)) {
1179 primarySplitScreenStack.moveToFront(reason + " splitScreenToTop");
1180 }
1181 }
1182 }
1183
Wale Ogunwale66e16852017-10-19 13:35:52 -07001184 if (!isActivityTypeHome() && returnsToHomeStack()) {
1185 // Make sure the home stack is behind this stack since that is where we should return to
1186 // when this stack is no longer visible.
Louis Changbd48dca2018-08-29 17:44:34 +08001187 display.moveHomeStackToFront(reason + " returnToHome");
Wale Ogunwale66e16852017-10-19 13:35:52 -07001188 }
1189
Riddle Hsubbb63c22018-10-03 12:28:29 +08001190 final boolean movingTask = task != null;
1191 display.positionChildAtTop(this, !movingTask /* includingParents */, reason);
1192 if (movingTask) {
Andrii Kulian52d255c2018-07-13 11:32:19 -07001193 // This also moves the entire hierarchy branch to top, including parents
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07001194 positionChildAtTop(task);
Wale Ogunwale1e60e0c2015-10-28 13:36:10 -07001195 }
Craig Mautnere0a38842013-12-16 16:14:02 -08001196 }
1197
Evan Rosky9c448172017-11-02 14:19:27 -07001198 /**
1199 * @param reason The reason for moving the stack to the back.
1200 * @param task If non-null, the task will be moved to the bottom of the stack.
1201 **/
Louis Changcdec0802019-11-11 11:45:07 +08001202 void moveToBack(String reason, Task task) {
Evan Rosky9c448172017-11-02 14:19:27 -07001203 if (!isAttached()) {
1204 return;
1205 }
1206
JinsungKim6e7fd3e2019-06-17 18:31:28 +09001207 getDisplay().positionChildAtBottom(this, reason);
1208 if (task != null) {
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07001209 positionChildAtBottom(task);
JinsungKim6e7fd3e2019-06-17 18:31:28 +09001210 }
1211
Bryce Lee8cab4a02018-01-05 09:00:49 -08001212 /**
1213 * The intent behind moving a primary split screen stack to the back is usually to hide
1214 * behind the home stack. Exit split screen in this case.
1215 */
1216 if (getWindowingMode() == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
Evan Rosky10475742018-09-05 19:02:48 -07001217 setWindowingMode(WINDOWING_MODE_UNDEFINED);
Bryce Lee8cab4a02018-01-05 09:00:49 -08001218 }
Evan Rosky9c448172017-11-02 14:19:27 -07001219 }
1220
Wale Ogunwaled046a012015-12-24 13:05:59 -08001221 boolean isFocusable() {
Wale Ogunwale4cea0f52015-12-25 06:30:31 -08001222 final ActivityRecord r = topRunningActivityLocked();
Wale Ogunwaled32da472018-11-16 07:19:28 -08001223 return mRootActivityContainer.isFocusable(this, r != null && r.isFocusable());
Wale Ogunwaled046a012015-12-24 13:05:59 -08001224 }
1225
Riddle Hsu75016992018-09-20 20:37:14 +08001226 boolean isFocusableAndVisible() {
1227 return isFocusable() && shouldBeVisible(null /* starting */);
1228 }
1229
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07001230 @Override
1231 public boolean isAttached() {
Riddle Hsu402b4402018-11-06 17:23:15 +08001232 final ActivityDisplay display = getDisplay();
1233 return display != null && !display.isRemoved();
Craig Mautner4a1cb222013-12-04 16:14:06 -08001234 }
1235
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001236 /**
Wale Ogunwale39381972015-12-17 17:15:29 -08001237 * Returns the top activity in any existing task matching the given Intent in the input result.
1238 * Returns null if no such task is found.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001239 */
Wale Ogunwale39381972015-12-17 17:15:29 -08001240 void findTaskLocked(ActivityRecord target, FindTaskResult result) {
Craig Mautnerac6f8432013-07-17 13:24:59 -07001241 Intent intent = target.intent;
1242 ActivityInfo info = target.info;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001243 ComponentName cls = intent.getComponent();
1244 if (info.targetActivity != null) {
1245 cls = new ComponentName(info.packageName, info.targetActivity);
1246 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001247 final int userId = UserHandle.getUserId(info.applicationInfo.uid);
Craig Mautnerd00f4742014-03-12 14:17:26 -07001248 boolean isDocument = intent != null & intent.isDocument();
1249 // If documentData is non-null then it must match the existing task data.
1250 Uri documentData = isDocument ? intent.getData() : null;
Craig Mautner000f0022013-02-26 15:04:29 -08001251
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001252 if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Looking for task of " + target + " in " + this);
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07001253 for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) {
Louis Changcdec0802019-11-11 11:45:07 +08001254 final Task task = getChildAt(taskNdx);
Dianne Hackborn91097de2014-04-04 18:02:06 -07001255 if (task.voiceSession != null) {
1256 // We never match voice sessions; those always run independently.
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001257 if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Skipping " + task + ": voice session");
Dianne Hackborn91097de2014-04-04 18:02:06 -07001258 continue;
1259 }
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07001260 if (task.mUserId != userId) {
Craig Mautnerac6f8432013-07-17 13:24:59 -07001261 // Looking for a different task.
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001262 if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Skipping " + task + ": different user");
Craig Mautnerac6f8432013-07-17 13:24:59 -07001263 continue;
1264 }
Bryce Lee9f6affd2017-09-01 09:18:35 -07001265
1266 // Overlays should not be considered as the task's logical top activity.
Wale Ogunwale21e06482019-11-18 05:14:15 -08001267 final ActivityRecord r = task.getTopNonFinishingActivity(false /* includeOverlays */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001268 if (r == null || r.finishing || r.mUserId != userId ||
Craig Mautner000f0022013-02-26 15:04:29 -08001269 r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001270 if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Skipping " + task + ": mismatch root " + r);
Craig Mautner000f0022013-02-26 15:04:29 -08001271 continue;
1272 }
Wale Ogunwale6fbde9f2017-08-24 07:24:12 -07001273 if (!r.hasCompatibleActivityType(target)) {
Chong Zhangb546f7e2015-08-05 14:21:36 -07001274 if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Skipping " + task + ": mismatch activity type");
1275 continue;
1276 }
Craig Mautner000f0022013-02-26 15:04:29 -08001277
Craig Mautnerd00f4742014-03-12 14:17:26 -07001278 final Intent taskIntent = task.intent;
1279 final Intent affinityIntent = task.affinityIntent;
1280 final boolean taskIsDocument;
1281 final Uri taskDocumentData;
1282 if (taskIntent != null && taskIntent.isDocument()) {
1283 taskIsDocument = true;
1284 taskDocumentData = taskIntent.getData();
1285 } else if (affinityIntent != null && affinityIntent.isDocument()) {
1286 taskIsDocument = true;
1287 taskDocumentData = affinityIntent.getData();
1288 } else {
1289 taskIsDocument = false;
1290 taskDocumentData = null;
1291 }
1292
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001293 if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Comparing existing cls="
Louis Changb05c8d82019-06-25 11:56:55 +08001294 + (task.realActivity != null ? task.realActivity.flattenToShortString() : "")
Louis Changcdec0802019-11-11 11:45:07 +08001295 + "/aff=" + r.getTask().rootAffinity + " to new cls="
Dianne Hackborn2a272d42013-10-16 13:34:33 -07001296 + intent.getComponent().flattenToShortString() + "/aff=" + info.taskAffinity);
Andrii Kulian206b9fa2016-06-02 13:18:01 -07001297 // TODO Refactor to remove duplications. Check if logic can be simplified.
Louis Changb05c8d82019-06-25 11:56:55 +08001298 if (task.realActivity != null && task.realActivity.compareTo(cls) == 0
1299 && Objects.equals(documentData, taskDocumentData)) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001300 if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Found matching class!");
Craig Mautner000f0022013-02-26 15:04:29 -08001301 //dump();
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001302 if (DEBUG_TASKS) Slog.d(TAG_TASKS,
1303 "For Intent " + intent + " bringing to top: " + r.intent);
Louis Changc85b1a32018-08-14 16:40:53 +08001304 result.mRecord = r;
1305 result.mIdealMatch = true;
Wale Ogunwale39381972015-12-17 17:15:29 -08001306 break;
Craig Mautnerffcfcaa2014-06-05 09:54:38 -07001307 } else if (affinityIntent != null && affinityIntent.getComponent() != null &&
1308 affinityIntent.getComponent().compareTo(cls) == 0 &&
Craig Mautnerd00f4742014-03-12 14:17:26 -07001309 Objects.equals(documentData, taskDocumentData)) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001310 if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Found matching class!");
Craig Mautner000f0022013-02-26 15:04:29 -08001311 //dump();
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001312 if (DEBUG_TASKS) Slog.d(TAG_TASKS,
1313 "For Intent " + intent + " bringing to top: " + r.intent);
Louis Changc85b1a32018-08-14 16:40:53 +08001314 result.mRecord = r;
1315 result.mIdealMatch = true;
Wale Ogunwale39381972015-12-17 17:15:29 -08001316 break;
Andrii Kulian206b9fa2016-06-02 13:18:01 -07001317 } else if (!isDocument && !taskIsDocument
Louis Changc85b1a32018-08-14 16:40:53 +08001318 && result.mRecord == null && task.rootAffinity != null) {
Andrii Kulian206b9fa2016-06-02 13:18:01 -07001319 if (task.rootAffinity.equals(target.taskAffinity)) {
1320 if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Found matching affinity candidate!");
1321 // It is possible for multiple tasks to have the same root affinity especially
1322 // if they are in separate stacks. We save off this candidate, but keep looking
1323 // to see if there is a better candidate.
Louis Changc85b1a32018-08-14 16:40:53 +08001324 result.mRecord = r;
1325 result.mIdealMatch = false;
Andrii Kulian206b9fa2016-06-02 13:18:01 -07001326 }
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001327 } else if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Not a match: " + task);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001328 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001329 }
1330
1331 /**
1332 * Returns the first activity (starting from the top of the stack) that
1333 * is the same as the given activity. Returns null if no such activity
1334 * is found.
1335 */
Andrii Kuliand3bbb132016-06-16 16:00:20 -07001336 ActivityRecord findActivityLocked(Intent intent, ActivityInfo info,
1337 boolean compareIntentFilters) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001338 ComponentName cls = intent.getComponent();
1339 if (info.targetActivity != null) {
1340 cls = new ComponentName(info.packageName, info.targetActivity);
1341 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001342 final int userId = UserHandle.getUserId(info.applicationInfo.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001343
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07001344 for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) {
Louis Changcdec0802019-11-11 11:45:07 +08001345 final Task task = getChildAt(taskNdx);
Wale Ogunwale1a06f152019-10-11 11:26:30 +02001346 for (int activityNdx = task.getChildCount() - 1; activityNdx >= 0; --activityNdx) {
1347 final ActivityRecord r = task.getChildAt(activityNdx);
Chong Zhang87761972016-08-22 13:53:24 -07001348 if (!r.okToShowLocked()) {
Wale Ogunwale25073dd2015-07-21 16:54:54 -07001349 continue;
Wale Ogunwale3fcb4a82015-04-06 14:00:13 -07001350 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001351 if (!r.finishing && r.mUserId == userId) {
Andrii Kuliand3bbb132016-06-16 16:00:20 -07001352 if (compareIntentFilters) {
1353 if (r.intent.filterEquals(intent)) {
1354 return r;
1355 }
1356 } else {
1357 if (r.intent.getComponent().equals(cls)) {
1358 return r;
1359 }
1360 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001361 }
1362 }
1363 }
1364
1365 return null;
1366 }
1367
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07001368 // TODO: Should each user have there own stacks?
1369 @Override
1370 void switchUser(int userId) {
Craig Mautner5d9c7be2013-02-15 14:02:56 -08001371 if (mCurrentUser == userId) {
Craig Mautner93529a42013-10-04 15:03:13 -07001372 return;
Craig Mautner5d9c7be2013-02-15 14:02:56 -08001373 }
1374 mCurrentUser = userId;
1375
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07001376 super.switchUser(userId);
1377 int top = mChildren.size();
1378 for (int taskNdx = 0; taskNdx < top; ++taskNdx) {
Louis Changcdec0802019-11-11 11:45:07 +08001379 Task task = mChildren.get(taskNdx);
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07001380 if (mWmService.isCurrentProfileLocked(task.mUserId) || task.showForAllUsers()) {
1381 mChildren.remove(taskNdx);
1382 mChildren.add(task);
1383 --top;
Craig Mautner5d9c7be2013-02-15 14:02:56 -08001384 }
1385 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001386 }
1387
Craig Mautner2420ead2013-04-01 17:13:20 -07001388 void minimalResumeActivityLocked(ActivityRecord r) {
Wale Ogunwale5658e4b2016-02-12 12:22:19 -08001389 if (DEBUG_STATES) Slog.v(TAG_STATES, "Moving to RESUMED: " + r + " (starting new instance)"
1390 + " callers=" + Debug.getCallers(5));
Bryce Leec4ab62a2018-03-05 14:19:26 -08001391 r.setState(RESUMED, "minimalResumeActivityLocked");
Andrii Kulian21713ac2016-10-12 22:05:05 -07001392 r.completeResumeLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001393 }
1394
Andrii Kulian21713ac2016-10-12 22:05:05 -07001395 private void clearLaunchTime(ActivityRecord r) {
Craig Mautner5c494542013-09-06 11:59:38 -07001396 // Make sure that there is no activity waiting for this to launch.
Vishnu Nair132ee832018-09-28 15:00:05 -07001397 if (!mStackSupervisor.mWaitingActivityLaunched.isEmpty()) {
Craig Mautner5c494542013-09-06 11:59:38 -07001398 mStackSupervisor.removeTimeoutsForActivityLocked(r);
1399 mStackSupervisor.scheduleIdleTimeoutLocked(r);
1400 }
Dianne Hackborn2286cdc2013-07-01 19:10:06 -07001401 }
1402
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001403 void awakeFromSleepingLocked() {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001404 // Ensure activities are no longer sleeping.
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07001405 for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) {
Louis Changcdec0802019-11-11 11:45:07 +08001406 final Task task = getChildAt(taskNdx);
Wale Ogunwale1a06f152019-10-11 11:26:30 +02001407 for (int activityNdx = task.getChildCount() - 1; activityNdx >= 0; --activityNdx) {
1408 final ActivityRecord r = task.getChildAt(activityNdx);
1409 r.setSleeping(false);
Craig Mautnerd44711d2013-02-23 11:24:36 -08001410 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001411 }
Craig Mautnerf49b0a42014-11-20 15:06:40 -08001412 if (mPausingActivity != null) {
1413 Slog.d(TAG, "awakeFromSleepingLocked: previously pausing activity didn't pause");
1414 activityPausedLocked(mPausingActivity.appToken, true);
1415 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001416 }
1417
Todd Kennedy39bfee52016-02-24 10:28:21 -08001418 void updateActivityApplicationInfoLocked(ApplicationInfo aInfo) {
1419 final String packageName = aInfo.packageName;
Makoto Onuki8b9963a2017-05-18 13:56:30 -07001420 final int userId = UserHandle.getUserId(aInfo.uid);
1421
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07001422 for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) {
Louis Changcdec0802019-11-11 11:45:07 +08001423 final Task task = getChildAt(taskNdx);
Wale Ogunwale1a06f152019-10-11 11:26:30 +02001424 for (int activityNdx = task.getChildCount() - 1; activityNdx >= 0; --activityNdx) {
1425 final ActivityRecord ar = task.getChildAt(activityNdx);
Makoto Onuki8b9963a2017-05-18 13:56:30 -07001426
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001427 if ((userId == ar.mUserId) && packageName.equals(ar.packageName)) {
Philip P. Moltmanncff8f0f2018-03-27 12:51:51 -07001428 ar.updateApplicationInfo(aInfo);
Todd Kennedy39bfee52016-02-24 10:28:21 -08001429 }
1430 }
1431 }
1432 }
1433
David Stevens9440dc82017-03-16 19:00:20 -07001434 void checkReadyForSleep() {
1435 if (shouldSleepActivities() && goToSleepIfPossible(false /* shuttingDown */)) {
1436 mStackSupervisor.checkReadyForSleepLocked(true /* allowDelay */);
1437 }
1438 }
1439
Craig Mautner0eea92c2013-05-16 13:35:39 -07001440 /**
David Stevens9440dc82017-03-16 19:00:20 -07001441 * Tries to put the activities in the stack to sleep.
1442 *
1443 * If the stack is not in a state where its activities can be put to sleep, this function will
1444 * start any necessary actions to move the stack into such a state. It is expected that this
1445 * function get called again when those actions complete.
1446 *
1447 * @param shuttingDown true when the called because the device is shutting down.
David Stevens18abd0e2017-08-17 14:55:47 -07001448 * @return true if the stack finished going to sleep, false if the stack only started the
1449 * process of going to sleep (checkReadyForSleep will be called when that process finishes).
Craig Mautner0eea92c2013-05-16 13:35:39 -07001450 */
David Stevens9440dc82017-03-16 19:00:20 -07001451 boolean goToSleepIfPossible(boolean shuttingDown) {
1452 boolean shouldSleep = true;
1453
Craig Mautner0eea92c2013-05-16 13:35:39 -07001454 if (mResumedActivity != null) {
1455 // Still have something resumed; can't sleep until it is paused.
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001456 if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Sleep needs to pause " + mResumedActivity);
1457 if (DEBUG_USER_LEAVING) Slog.v(TAG_USER_LEAVING,
1458 "Sleep => pause with userLeaving=false");
Bryce Lee5daa3122017-04-19 10:40:42 -07001459
Louis Chang7b03ad92019-08-21 12:32:33 +08001460 startPausingLocked(false /* userLeaving */, true /* uiSleeping */, null /* resuming */);
David Stevens9440dc82017-03-16 19:00:20 -07001461 shouldSleep = false ;
1462 } else if (mPausingActivity != null) {
Craig Mautner0eea92c2013-05-16 13:35:39 -07001463 // Still waiting for something to pause; can't sleep yet.
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001464 if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Sleep still waiting to pause " + mPausingActivity);
David Stevens9440dc82017-03-16 19:00:20 -07001465 shouldSleep = false;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001466 }
David Stevens9440dc82017-03-16 19:00:20 -07001467
1468 if (!shuttingDown) {
1469 if (containsActivityFromStack(mStackSupervisor.mStoppingActivities)) {
1470 // Still need to tell some activities to stop; can't sleep yet.
1471 if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Sleep still need to stop "
1472 + mStackSupervisor.mStoppingActivities.size() + " activities");
1473
1474 mStackSupervisor.scheduleIdleLocked();
1475 shouldSleep = false;
1476 }
1477
1478 if (containsActivityFromStack(mStackSupervisor.mGoingToSleepActivities)) {
1479 // Still need to tell some activities to sleep; can't sleep yet.
1480 if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Sleep still need to sleep "
1481 + mStackSupervisor.mGoingToSleepActivities.size() + " activities");
1482 shouldSleep = false;
1483 }
1484 }
1485
1486 if (shouldSleep) {
1487 goToSleep();
1488 }
1489
David Stevens18abd0e2017-08-17 14:55:47 -07001490 return shouldSleep;
Craig Mautner0eea92c2013-05-16 13:35:39 -07001491 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001492
David Stevens18abd0e2017-08-17 14:55:47 -07001493 void goToSleep() {
Andrii Kulianf4479ee2018-05-23 17:52:48 -07001494 // Ensure visibility without updating configuration, as activities are about to sleep.
Andrii Kuliana39ae3e2018-05-31 12:43:54 -07001495 ensureActivitiesVisibleLocked(null /* starting */, 0 /* configChanges */,
1496 !PRESERVE_WINDOWS);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001497
Andrii Kulianf9949d52016-05-06 12:53:25 -07001498 // Make sure any paused or stopped but visible activities are now sleeping.
Craig Mautner0eea92c2013-05-16 13:35:39 -07001499 // This ensures that the activity's onStop() is called.
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07001500 for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) {
Louis Changcdec0802019-11-11 11:45:07 +08001501 final Task task = getChildAt(taskNdx);
Wale Ogunwale1a06f152019-10-11 11:26:30 +02001502 for (int activityNdx = task.getChildCount() - 1; activityNdx >= 0; --activityNdx) {
1503 final ActivityRecord r = task.getChildAt(activityNdx);
Louis Changeadb22f2019-06-19 12:09:23 +08001504 if (r.isState(STARTED, STOPPING, STOPPED, PAUSED, PAUSING)) {
Craig Mautner0eea92c2013-05-16 13:35:39 -07001505 r.setSleeping(true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001506 }
1507 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001508 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001509 }
Craig Mautner59c00972012-07-30 12:10:24 -07001510
David Stevens9440dc82017-03-16 19:00:20 -07001511 private boolean containsActivityFromStack(List<ActivityRecord> rs) {
1512 for (ActivityRecord r : rs) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001513 if (r.getActivityStack() == this) {
David Stevens9440dc82017-03-16 19:00:20 -07001514 return true;
1515 }
1516 }
1517 return false;
1518 }
1519
Dianne Hackborna4e102e2014-09-04 22:52:27 -07001520 /**
1521 * Start pausing the currently resumed activity. It is an error to call this if there
1522 * is already an activity being paused or there is no resumed activity.
1523 *
1524 * @param userLeaving True if this should result in an onUserLeaving to the current activity.
1525 * @param uiSleeping True if this is happening with the user interface going to sleep (the
1526 * screen turning off).
Wale Ogunwale950faff2016-08-08 09:51:04 -07001527 * @param resuming The activity we are currently trying to resume or null if this is not being
1528 * called as part of resuming the top activity, so we shouldn't try to instigate
1529 * a resume here if not null.
Dianne Hackborna4e102e2014-09-04 22:52:27 -07001530 * @return Returns true if an activity now is in the PAUSING state, and we are waiting for
1531 * it to tell us when it is done.
1532 */
Wale Ogunwale950faff2016-08-08 09:51:04 -07001533 final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping,
Louis Chang7b03ad92019-08-21 12:32:33 +08001534 ActivityRecord resuming) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001535 if (mPausingActivity != null) {
riddle_hsu7dfe4d72015-02-16 18:43:49 +08001536 Slog.wtf(TAG, "Going to pause when pause is already pending for " + mPausingActivity
Bryce Lee7ace3952018-02-16 14:34:32 -08001537 + " state=" + mPausingActivity.getState());
David Stevens9440dc82017-03-16 19:00:20 -07001538 if (!shouldSleepActivities()) {
riddle_hsu7dfe4d72015-02-16 18:43:49 +08001539 // Avoid recursion among check for sleep and complete pause during sleeping.
1540 // Because activity will be paused immediately after resume, just let pause
1541 // be completed by the order of activity paused from clients.
Wale Ogunwale950faff2016-08-08 09:51:04 -07001542 completePauseLocked(false, resuming);
riddle_hsu7dfe4d72015-02-16 18:43:49 +08001543 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001544 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001545 ActivityRecord prev = mResumedActivity;
Bryce Lee5daa3122017-04-19 10:40:42 -07001546
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001547 if (prev == null) {
Wale Ogunwale950faff2016-08-08 09:51:04 -07001548 if (resuming == null) {
Dianne Hackborna4e102e2014-09-04 22:52:27 -07001549 Slog.wtf(TAG, "Trying to pause when nothing is resumed");
Wale Ogunwaled32da472018-11-16 07:19:28 -08001550 mRootActivityContainer.resumeFocusedStacksTopActivities();
Dianne Hackborna4e102e2014-09-04 22:52:27 -07001551 }
1552 return false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001553 }
Craig Mautnerdf88d732014-01-27 09:21:32 -08001554
Andrii Kulianb1888aa2018-02-16 14:40:42 -08001555 if (prev == resuming) {
1556 Slog.wtf(TAG, "Trying to pause activity that is in process of being resumed");
1557 return false;
1558 }
1559
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07001560 if (DEBUG_STATES) Slog.v(TAG_STATES, "Moving to PAUSING: " + prev);
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001561 else if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Start pausing: " + prev);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001562 mPausingActivity = prev;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001563 mLastPausedActivity = prev;
Craig Mautner0f922742013-08-06 08:44:42 -07001564 mLastNoHistoryActivity = (prev.intent.getFlags() & Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
1565 || (prev.info.flags & ActivityInfo.FLAG_NO_HISTORY) != 0 ? prev : null;
Bryce Lee7ace3952018-02-16 14:34:32 -08001566 prev.setState(PAUSING, "startPausingLocked");
Louis Changcdec0802019-11-11 11:45:07 +08001567 prev.getTask().touchActiveTime();
Dianne Hackborn2286cdc2013-07-01 19:10:06 -07001568 clearLaunchTime(prev);
Jorim Jaggie7d2b852017-08-28 17:55:15 +02001569
Wale Ogunwale53783742018-09-16 10:21:51 -07001570 mService.updateCpuStats();
Craig Mautneraab647e2013-02-28 16:31:36 -08001571
Louis Chang7b03ad92019-08-21 12:32:33 +08001572 boolean pauseImmediately = false;
1573 if (resuming != null && (resuming.info.flags & FLAG_RESUME_WHILE_PAUSING) != 0) {
1574 // If the flag RESUME_WHILE_PAUSING is set, then continue to schedule the previous
1575 // activity to be paused, while at the same time resuming the new resume activity
1576 // only if the previous activity can't go into Pip since we want to give Pip
1577 // activities a chance to enter Pip before resuming the next activity.
1578 final boolean lastResumedCanPip = prev != null && prev.checkEnterPictureInPictureState(
1579 "shouldResumeWhilePausing", userLeaving);
1580 if (!lastResumedCanPip) {
1581 pauseImmediately = true;
1582 }
1583 }
1584
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001585 if (prev.attachedToProcess()) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001586 if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Enqueueing pending pause: " + prev);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001587 try {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001588 EventLogTags.writeAmPauseActivity(prev.mUserId, System.identityHashCode(prev),
Wale Ogunwalec59b4f62017-11-30 11:05:43 -08001589 prev.shortComponentName, "userLeaving=" + userLeaving);
Andrii Kulian446e8242017-10-26 15:17:29 -07001590
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001591 mService.getLifecycleManager().scheduleTransaction(prev.app.getThread(),
1592 prev.appToken, PauseActivityItem.obtain(prev.finishing, userLeaving,
Bryce Lee1d0d5142018-04-12 10:35:07 -07001593 prev.configChangeFlags, pauseImmediately));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001594 } catch (Exception e) {
1595 // Ignore exception, if process died other code will cleanup.
1596 Slog.w(TAG, "Exception thrown during pause", e);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001597 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001598 mLastPausedActivity = null;
Craig Mautner0f922742013-08-06 08:44:42 -07001599 mLastNoHistoryActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001600 }
1601 } else {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001602 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001603 mLastPausedActivity = null;
Craig Mautner0f922742013-08-06 08:44:42 -07001604 mLastNoHistoryActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001605 }
1606
1607 // If we are not going to sleep, we want to ensure the device is
1608 // awake until the next activity is started.
Wale Ogunwalef6733932018-06-27 05:14:34 -07001609 if (!uiSleeping && !mService.isSleepingOrShuttingDownLocked()) {
Craig Mautner7ea5bd42013-07-05 15:27:08 -07001610 mStackSupervisor.acquireLaunchWakelock();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001611 }
1612
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001613 if (mPausingActivity != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001614 // Have the window manager pause its key dispatching until the new
1615 // activity has started. If we're pausing the activity just because
1616 // the screen is being turned off and the UI is sleeping, don't interrupt
1617 // key dispatch; the same activity will pick it up again on wakeup.
1618 if (!uiSleeping) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001619 prev.pauseKeyDispatchingLocked();
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001620 } else if (DEBUG_PAUSE) {
1621 Slog.v(TAG_PAUSE, "Key dispatch not paused for screen off");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001622 }
1623
Winson Chung6954fc92017-03-24 16:22:12 -07001624 if (pauseImmediately) {
Dianne Hackborna4e102e2014-09-04 22:52:27 -07001625 // If the caller said they don't want to wait for the pause, then complete
1626 // the pause now.
Wale Ogunwale950faff2016-08-08 09:51:04 -07001627 completePauseLocked(false, resuming);
Dianne Hackborna4e102e2014-09-04 22:52:27 -07001628 return false;
1629
1630 } else {
Andrii Kulian79d67982019-08-19 11:56:16 -07001631 schedulePauseTimeoutForActivity(prev);
Dianne Hackborna4e102e2014-09-04 22:52:27 -07001632 return true;
1633 }
1634
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001635 } else {
1636 // This activity failed to schedule the
1637 // pause, so just treat it as being paused now.
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001638 if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Activity not running, resuming next.");
Wale Ogunwale950faff2016-08-08 09:51:04 -07001639 if (resuming == null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001640 mRootActivityContainer.resumeFocusedStacksTopActivities();
Dianne Hackborna4e102e2014-09-04 22:52:27 -07001641 }
1642 return false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001643 }
1644 }
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001645
Dianne Hackborna4e102e2014-09-04 22:52:27 -07001646 final void activityPausedLocked(IBinder token, boolean timeout) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001647 if (DEBUG_PAUSE) Slog.v(TAG_PAUSE,
1648 "Activity paused: token=" + token + ", timeout=" + timeout);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001649
Craig Mautnerd2328952013-03-05 12:46:26 -08001650 final ActivityRecord r = isInStackLocked(token);
Andrii Kulian6b321512019-01-23 06:37:00 +00001651
Craig Mautnerd2328952013-03-05 12:46:26 -08001652 if (r != null) {
1653 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
1654 if (mPausingActivity == r) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07001655 if (DEBUG_STATES) Slog.v(TAG_STATES, "Moving to PAUSED: " + r
Craig Mautnerd2328952013-03-05 12:46:26 -08001656 + (timeout ? " (due to timeout)" : " (pause complete)"));
Riddle Hsua0022cd2019-09-09 21:12:41 +08001657 mService.deferWindowLayout();
Jorim Jaggife762342016-10-13 14:33:27 +02001658 try {
Winson Chung3f103eb2017-04-12 21:53:59 -07001659 completePauseLocked(true /* resumeNext */, null /* resumingActivity */);
Jorim Jaggife762342016-10-13 14:33:27 +02001660 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08001661 mService.continueWindowLayout();
Jorim Jaggife762342016-10-13 14:33:27 +02001662 }
Wale Ogunwale5658e4b2016-02-12 12:22:19 -08001663 return;
Craig Mautnerd2328952013-03-05 12:46:26 -08001664 } else {
1665 EventLog.writeEvent(EventLogTags.AM_FAILED_TO_PAUSE,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001666 r.mUserId, System.identityHashCode(r), r.shortComponentName,
Craig Mautnerd2328952013-03-05 12:46:26 -08001667 mPausingActivity != null
1668 ? mPausingActivity.shortComponentName : "(none)");
Bryce Lee7ace3952018-02-16 14:34:32 -08001669 if (r.isState(PAUSING)) {
1670 r.setState(PAUSED, "activityPausedLocked");
riddle_hsu9caeef72015-10-20 16:34:05 +08001671 if (r.finishing) {
1672 if (DEBUG_PAUSE) Slog.v(TAG,
1673 "Executing finish of failed to pause activity: " + r);
Andrii Kulian7dd39bb2019-07-22 13:11:10 -07001674 r.completeFinishing("activityPausedLocked");
riddle_hsu9caeef72015-10-20 16:34:05 +08001675 }
louis_chang047dfd42015-04-08 16:35:55 +08001676 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001677 }
1678 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001679 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001680 }
1681
Louis Chang7b03ad92019-08-21 12:32:33 +08001682 @VisibleForTesting
1683 void completePauseLocked(boolean resumeNext, ActivityRecord resuming) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001684 ActivityRecord prev = mPausingActivity;
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001685 if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Complete pause: " + prev);
Craig Mautneraab647e2013-02-28 16:31:36 -08001686
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001687 if (prev != null) {
chaviw4ad54912018-05-30 11:05:44 -07001688 prev.setWillCloseOrEnterPip(false);
Bryce Lee7ace3952018-02-16 14:34:32 -08001689 final boolean wasStopping = prev.isState(STOPPING);
1690 prev.setState(PAUSED, "completePausedLocked");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001691 if (prev.finishing) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001692 if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Executing finish of activity: " + prev);
Andrii Kulian7dd39bb2019-07-22 13:11:10 -07001693 prev = prev.completeFinishing("completePausedLocked");
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001694 } else if (prev.hasProcess()) {
Wale Ogunwaled8026642016-02-09 20:40:18 -08001695 if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Enqueue pending stop if needed: " + prev
Issei Suzuki1669ea42019-11-06 14:20:59 +01001696 + " wasStopping=" + wasStopping
1697 + " visibleRequested=" + prev.mVisibleRequested);
Wale Ogunwalef81c1d12016-01-12 12:20:18 -08001698 if (prev.deferRelaunchUntilPaused) {
1699 // Complete the deferred relaunch that was waiting for pause to complete.
1700 if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Re-launching after pause: " + prev);
wilsonshihb5d8f8b2019-10-23 13:01:40 +08001701 prev.relaunchActivityLocked(prev.preserveWindowOnDeferredRelaunch);
Filip Gruszczynskidba623a2015-12-04 15:45:35 -08001702 } else if (wasStopping) {
1703 // We are also stopping, the stop request must have gone soon after the pause.
1704 // We can't clobber it, because the stop confirmation will not be handled.
1705 // We don't need to schedule another stop, we only need to let it happen.
Bryce Lee7ace3952018-02-16 14:34:32 -08001706 prev.setState(STOPPING, "completePausedLocked");
Issei Suzuki1669ea42019-11-06 14:20:59 +01001707 } else if (!prev.mVisibleRequested || shouldSleepOrShutDownActivities()) {
Wale Ogunwaleec950642017-04-25 07:44:21 -07001708 // Clear out any deferred client hide we might currently have.
1709 prev.setDeferHidingClient(false);
Jose Lima4b6c6692014-08-12 17:41:12 -07001710 // If we were visible then resumeTopActivities will release resources before
Wale Ogunwaleec950642017-04-25 07:44:21 -07001711 // stopping.
Andrii Kulian79d67982019-08-19 11:56:16 -07001712 prev.addToStopping(true /* scheduleIdle */, false /* idleDelayed */,
wilsonshih401e50f2019-04-30 12:55:48 +08001713 "completePauseLocked");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001714 }
1715 } else {
Wale Ogunwaleee006da2015-03-30 14:49:25 -07001716 if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "App died during pause, not stopping: " + prev);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001717 prev = null;
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001718 }
Wale Ogunwale07927bf2015-03-28 17:21:05 -07001719 // It is possible the activity was freezing the screen before it was paused.
1720 // In that case go ahead and remove the freeze this activity has on the screen
1721 // since it is no longer visible.
Wale Ogunwalee8524002016-09-13 16:34:57 -07001722 if (prev != null) {
1723 prev.stopFreezingScreenLocked(true /*force*/);
1724 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001725 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001726 }
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001727
Dianne Hackborna4e102e2014-09-04 22:52:27 -07001728 if (resumeNext) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001729 final ActivityStack topStack = mRootActivityContainer.getTopDisplayFocusedStack();
David Stevens9440dc82017-03-16 19:00:20 -07001730 if (!topStack.shouldSleepOrShutDownActivities()) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001731 mRootActivityContainer.resumeFocusedStacksTopActivities(topStack, prev, null);
Dianne Hackborna4e102e2014-09-04 22:52:27 -07001732 } else {
David Stevens9440dc82017-03-16 19:00:20 -07001733 checkReadyForSleep();
Filip Gruszczynski3e85ba22015-10-05 22:48:30 -07001734 ActivityRecord top = topStack.topRunningActivityLocked();
Dianne Hackborna4e102e2014-09-04 22:52:27 -07001735 if (top == null || (prev != null && top != prev)) {
Wale Ogunwaled046a012015-12-24 13:05:59 -08001736 // If there are no more activities available to run, do resume anyway to start
1737 // something. Also if the top activity on the stack is not the just paused
1738 // activity, we need to go ahead and resume it to ensure we complete an
1739 // in-flight app switch.
Wale Ogunwaled32da472018-11-16 07:19:28 -08001740 mRootActivityContainer.resumeFocusedStacksTopActivities();
Dianne Hackborna4e102e2014-09-04 22:52:27 -07001741 }
Dianne Hackborn42e620c2012-06-24 13:20:51 -07001742 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001743 }
Craig Mautneraab647e2013-02-28 16:31:36 -08001744
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001745 if (prev != null) {
1746 prev.resumeKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001747
Louis Chang1bb884a2018-10-08 19:29:18 +08001748 if (prev.hasProcess() && prev.cpuTimeAtResume > 0) {
1749 final long diff = prev.app.getCpuTime() - prev.cpuTimeAtResume;
1750 if (diff > 0) {
1751 final Runnable r = PooledLambda.obtainRunnable(
1752 ActivityManagerInternal::updateForegroundTimeIfOnBattery,
1753 mService.mAmInternal, prev.info.packageName,
1754 prev.info.applicationInfo.uid,
1755 diff);
1756 mService.mH.post(r);
1757 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001758 }
Craig Mautner525f3d92013-05-07 14:01:50 -07001759 prev.cpuTimeAtResume = 0; // reset it
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001760 }
Winson Chung740c3ac2014-11-12 16:14:38 -08001761
Andrii Kulian8290f8f2016-06-30 17:51:32 -07001762 // Notify when the task stack has changed, but only if visibilities changed (not just
1763 // focus). Also if there is an active pinned stack - we always want to notify it about
1764 // task stack changes, because its positioning may depend on it.
1765 if (mStackSupervisor.mAppVisibilitiesChangedSinceLastPause
Louis Chang24f7a032018-12-11 10:49:48 +08001766 || (getDisplay() != null && getDisplay().hasPinnedStack())) {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001767 mService.getTaskChangeNotificationController().notifyTaskStackChanged();
Jorim Jaggia0fdeec2016-01-07 14:42:28 +01001768 mStackSupervisor.mAppVisibilitiesChangedSinceLastPause = false;
1769 }
Wale Ogunwale5658e4b2016-02-12 12:22:19 -08001770
Wale Ogunwaled32da472018-11-16 07:19:28 -08001771 mRootActivityContainer.ensureActivitiesVisible(resuming, 0, !PRESERVE_WINDOWS);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001772 }
1773
Wale Ogunwale8051c5c2016-03-04 10:27:32 -08001774 /**
1775 * Returns true if the stack is translucent and can have other contents visible behind it if
1776 * needed. A stack is considered translucent if it don't contain a visible or
1777 * starting (about to be visible) activity that is fullscreen (opaque).
1778 * @param starting The currently starting activity or null if there is none.
1779 */
Wale Ogunwale7e1f5f52017-10-18 15:19:59 -07001780 @VisibleForTesting
Wale Ogunwale66e16852017-10-19 13:35:52 -07001781 boolean isStackTranslucent(ActivityRecord starting) {
Wale Ogunwale7e1f5f52017-10-18 15:19:59 -07001782 if (!isAttached() || mForceHidden) {
1783 return true;
1784 }
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07001785 for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) {
Louis Changcdec0802019-11-11 11:45:07 +08001786 final Task task = getChildAt(taskNdx);
Wale Ogunwale1a06f152019-10-11 11:26:30 +02001787 for (int activityNdx = task.getChildCount() - 1; activityNdx >= 0; --activityNdx) {
1788 final ActivityRecord r = task.getChildAt(activityNdx);
Wale Ogunwaleb34a7ad2015-08-14 11:05:30 -07001789
Wale Ogunwale56d75cf2016-03-09 15:14:47 -08001790 if (r.finishing) {
1791 // We don't factor in finishing activities when determining translucency since
1792 // they will be gone soon.
1793 continue;
1794 }
1795
Wale Ogunwale2cca8622017-12-11 08:40:13 -08001796 if (!r.visibleIgnoringKeyguard && r != starting) {
Wale Ogunwale56d75cf2016-03-09 15:14:47 -08001797 // Also ignore invisible activities that are not the currently starting
1798 // activity (about to be visible).
1799 continue;
1800 }
1801
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08001802 if (r.occludesParent() || r.hasWallpaper) {
Wale Ogunwale56d75cf2016-03-09 15:14:47 -08001803 // Stack isn't translucent if it has at least one fullscreen activity
1804 // that is visible.
1805 return false;
1806 }
Wale Ogunwaleb34a7ad2015-08-14 11:05:30 -07001807 }
1808 }
Wale Ogunwale1e3523c2015-09-16 13:11:10 -07001809 return true;
Wale Ogunwaleb34a7ad2015-08-14 11:05:30 -07001810 }
1811
Wale Ogunwalea0f5b5e2017-10-11 09:37:23 -07001812 boolean isTopStackOnDisplay() {
Andrii Kulian52d255c2018-07-13 11:32:19 -07001813 final ActivityDisplay display = getDisplay();
1814 return display != null && display.isTopStack(this);
1815 }
1816
1817 /**
1818 * @return {@code true} if this is the focused stack on its current display, {@code false}
1819 * otherwise.
1820 */
1821 boolean isFocusedStackOnDisplay() {
1822 final ActivityDisplay display = getDisplay();
1823 return display != null && this == display.getFocusedStack();
Wale Ogunwalea0f5b5e2017-10-11 09:37:23 -07001824 }
1825
Adrian Roosa6d6aab2018-04-19 18:58:22 +02001826 boolean isTopActivityVisible() {
Wale Ogunwale21e06482019-11-18 05:14:15 -08001827 final ActivityRecord topActivity = getTopNonFinishingActivity();
Issei Suzuki1669ea42019-11-06 14:20:59 +01001828 return topActivity != null && topActivity.mVisibleRequested;
Adrian Roosa6d6aab2018-04-19 18:58:22 +02001829 }
1830
Filip Gruszczynski0e381e22016-01-14 16:31:33 -08001831 /**
Wale Ogunwale9dcf9462017-09-19 15:13:01 -07001832 * Returns true if the stack should be visible.
Wale Ogunwalecd501ec2017-04-07 08:53:41 -07001833 *
Wale Ogunwale8051c5c2016-03-04 10:27:32 -08001834 * @param starting The currently starting activity or null if there is none.
Filip Gruszczynski0e381e22016-01-14 16:31:33 -08001835 */
Wale Ogunwale9dcf9462017-09-19 15:13:01 -07001836 boolean shouldBeVisible(ActivityRecord starting) {
Andrii Kulian0c869cc2019-02-06 19:50:32 -08001837 return getVisibility(starting) != STACK_VISIBILITY_INVISIBLE;
1838 }
1839
1840 /**
1841 * Returns true if the stack should be visible.
1842 *
1843 * @param starting The currently starting activity or null if there is none.
1844 */
1845 @StackVisibility
1846 int getVisibility(ActivityRecord starting) {
Winson Chung47900652017-04-06 18:44:25 -07001847 if (!isAttached() || mForceHidden) {
Andrii Kulian0c869cc2019-02-06 19:50:32 -08001848 return STACK_VISIBILITY_INVISIBLE;
Jose Lima7ba71252014-04-30 12:59:27 -07001849 }
Wale Ogunwale99db1862015-10-23 20:08:22 -07001850
Wale Ogunwale7e1f5f52017-10-18 15:19:59 -07001851 final ActivityDisplay display = getDisplay();
Wale Ogunwale8e923af2018-03-23 08:48:11 -07001852 boolean gotSplitScreenStack = false;
Wale Ogunwale7e1f5f52017-10-18 15:19:59 -07001853 boolean gotOpaqueSplitScreenPrimary = false;
1854 boolean gotOpaqueSplitScreenSecondary = false;
Andrii Kulian0c869cc2019-02-06 19:50:32 -08001855 boolean gotTranslucentFullscreen = false;
1856 boolean gotTranslucentSplitScreenPrimary = false;
1857 boolean gotTranslucentSplitScreenSecondary = false;
1858 boolean shouldBeVisible = true;
Wale Ogunwale68278562017-09-23 17:13:55 -07001859 final int windowingMode = getWindowingMode();
Wale Ogunwale8e923af2018-03-23 08:48:11 -07001860 final boolean isAssistantType = isActivityTypeAssistant();
Wale Ogunwale7e1f5f52017-10-18 15:19:59 -07001861 for (int i = display.getChildCount() - 1; i >= 0; --i) {
1862 final ActivityStack other = display.getChildAt(i);
Louis Changf2835df2018-10-17 15:14:45 +08001863 final boolean hasRunningActivities = other.topRunningActivityLocked() != null;
Wale Ogunwale7e1f5f52017-10-18 15:19:59 -07001864 if (other == this) {
Louis Changf2835df2018-10-17 15:14:45 +08001865 // Should be visible if there is no other stack occluding it, unless it doesn't
1866 // have any running activities, not starting one and not home stack.
Andrii Kulian0c869cc2019-02-06 19:50:32 -08001867 shouldBeVisible = hasRunningActivities || isInStackLocked(starting) != null
Louis Changf2835df2018-10-17 15:14:45 +08001868 || isActivityTypeHome();
Andrii Kulian0c869cc2019-02-06 19:50:32 -08001869 break;
Louis Changf2835df2018-10-17 15:14:45 +08001870 }
1871
1872 if (!hasRunningActivities) {
1873 continue;
Wale Ogunwale7e1f5f52017-10-18 15:19:59 -07001874 }
Wale Ogunwale68278562017-09-23 17:13:55 -07001875
Wale Ogunwale7e1f5f52017-10-18 15:19:59 -07001876 final int otherWindowingMode = other.getWindowingMode();
Wale Ogunwale7e1f5f52017-10-18 15:19:59 -07001877
1878 if (otherWindowingMode == WINDOWING_MODE_FULLSCREEN) {
Matthew Ng99b3cdc2018-05-01 14:24:38 -07001879 // In this case the home stack isn't resizeable even though we are in split-screen
1880 // mode. We still want the primary splitscreen stack to be visible as there will be
1881 // a slight hint of it in the status bar area above the non-resizeable home
Matthew Nga51dcaa2018-05-07 15:36:06 -07001882 // activity. In addition, if the fullscreen assistant is over primary splitscreen
1883 // stack, the stack should still be visible in the background as long as the recents
1884 // animation is running.
1885 final int activityType = other.getActivityType();
1886 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
1887 if (activityType == ACTIVITY_TYPE_HOME
1888 || (activityType == ACTIVITY_TYPE_ASSISTANT
Andrii Kulian0c869cc2019-02-06 19:50:32 -08001889 && mWindowManager.getRecentsAnimationController() != null)) {
1890 break;
Matthew Nga51dcaa2018-05-07 15:36:06 -07001891 }
Matthew Ng99b3cdc2018-05-01 14:24:38 -07001892 }
Wale Ogunwale66e16852017-10-19 13:35:52 -07001893 if (other.isStackTranslucent(starting)) {
Wale Ogunwale7e1f5f52017-10-18 15:19:59 -07001894 // Can be visible behind a translucent fullscreen stack.
Andrii Kulian0c869cc2019-02-06 19:50:32 -08001895 gotTranslucentFullscreen = true;
Wale Ogunwale7e1f5f52017-10-18 15:19:59 -07001896 continue;
1897 }
Andrii Kulian0c869cc2019-02-06 19:50:32 -08001898 return STACK_VISIBILITY_INVISIBLE;
Wale Ogunwale7e1f5f52017-10-18 15:19:59 -07001899 } else if (otherWindowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY
1900 && !gotOpaqueSplitScreenPrimary) {
Wale Ogunwale8e923af2018-03-23 08:48:11 -07001901 gotSplitScreenStack = true;
Andrii Kulian0c869cc2019-02-06 19:50:32 -08001902 gotTranslucentSplitScreenPrimary = other.isStackTranslucent(starting);
1903 gotOpaqueSplitScreenPrimary = !gotTranslucentSplitScreenPrimary;
Wale Ogunwale7e1f5f52017-10-18 15:19:59 -07001904 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY
1905 && gotOpaqueSplitScreenPrimary) {
1906 // Can not be visible behind another opaque stack in split-screen-primary mode.
Andrii Kulian0c869cc2019-02-06 19:50:32 -08001907 return STACK_VISIBILITY_INVISIBLE;
Wale Ogunwale7e1f5f52017-10-18 15:19:59 -07001908 }
1909 } else if (otherWindowingMode == WINDOWING_MODE_SPLIT_SCREEN_SECONDARY
1910 && !gotOpaqueSplitScreenSecondary) {
Wale Ogunwale8e923af2018-03-23 08:48:11 -07001911 gotSplitScreenStack = true;
Andrii Kulian0c869cc2019-02-06 19:50:32 -08001912 gotTranslucentSplitScreenSecondary = other.isStackTranslucent(starting);
1913 gotOpaqueSplitScreenSecondary = !gotTranslucentSplitScreenSecondary;
Wale Ogunwale7e1f5f52017-10-18 15:19:59 -07001914 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_SECONDARY
1915 && gotOpaqueSplitScreenSecondary) {
1916 // Can not be visible behind another opaque stack in split-screen-secondary mode.
Andrii Kulian0c869cc2019-02-06 19:50:32 -08001917 return STACK_VISIBILITY_INVISIBLE;
Wale Ogunwale7e1f5f52017-10-18 15:19:59 -07001918 }
1919 }
1920 if (gotOpaqueSplitScreenPrimary && gotOpaqueSplitScreenSecondary) {
1921 // Can not be visible if we are in split-screen windowing mode and both halves of
1922 // the screen are opaque.
Andrii Kulian0c869cc2019-02-06 19:50:32 -08001923 return STACK_VISIBILITY_INVISIBLE;
Wale Ogunwale7e1f5f52017-10-18 15:19:59 -07001924 }
Wale Ogunwale8e923af2018-03-23 08:48:11 -07001925 if (isAssistantType && gotSplitScreenStack) {
1926 // Assistant stack can't be visible behind split-screen. In addition to this not
1927 // making sense, it also works around an issue here we boost the z-order of the
1928 // assistant window surfaces in window manager whenever it is visible.
Andrii Kulian0c869cc2019-02-06 19:50:32 -08001929 return STACK_VISIBILITY_INVISIBLE;
Wale Ogunwale8e923af2018-03-23 08:48:11 -07001930 }
Wale Ogunwale7e1f5f52017-10-18 15:19:59 -07001931 }
1932
Andrii Kulian0c869cc2019-02-06 19:50:32 -08001933 if (!shouldBeVisible) {
1934 return STACK_VISIBILITY_INVISIBLE;
1935 }
1936
1937 // Handle cases when there can be a translucent split-screen stack on top.
1938 switch (windowingMode) {
1939 case WINDOWING_MODE_FULLSCREEN:
1940 if (gotTranslucentSplitScreenPrimary || gotTranslucentSplitScreenSecondary) {
1941 // At least one of the split-screen stacks that covers this one is translucent.
1942 return STACK_VISIBILITY_VISIBLE_BEHIND_TRANSLUCENT;
1943 }
1944 break;
1945 case WINDOWING_MODE_SPLIT_SCREEN_PRIMARY:
1946 if (gotTranslucentSplitScreenPrimary) {
1947 // Covered by translucent primary split-screen on top.
1948 return STACK_VISIBILITY_VISIBLE_BEHIND_TRANSLUCENT;
1949 }
1950 break;
1951 case WINDOWING_MODE_SPLIT_SCREEN_SECONDARY:
1952 if (gotTranslucentSplitScreenSecondary) {
1953 // Covered by translucent secondary split-screen on top.
1954 return STACK_VISIBILITY_VISIBLE_BEHIND_TRANSLUCENT;
1955 }
1956 break;
1957 }
1958
1959 // Lastly - check if there is a translucent fullscreen stack on top.
1960 return gotTranslucentFullscreen ? STACK_VISIBILITY_VISIBLE_BEHIND_TRANSLUCENT
1961 : STACK_VISIBILITY_VISIBLE;
Wale Ogunwale68278562017-09-23 17:13:55 -07001962 }
1963
Chong Zhangfdcc4d42015-10-14 16:50:12 -07001964 final int rankTaskLayers(int baseLayer) {
1965 int layer = 0;
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07001966 for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) {
Louis Changcdec0802019-11-11 11:45:07 +08001967 final Task task = getChildAt(taskNdx);
Chong Zhangfdcc4d42015-10-14 16:50:12 -07001968 ActivityRecord r = task.topRunningActivityLocked();
Issei Suzuki1669ea42019-11-06 14:20:59 +01001969 if (r == null || r.finishing || !r.mVisibleRequested) {
Chong Zhangfdcc4d42015-10-14 16:50:12 -07001970 task.mLayerRank = -1;
1971 } else {
1972 task.mLayerRank = baseLayer + layer++;
1973 }
1974 }
1975 return layer;
1976 }
1977
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001978 /**
Andrii Kulianf4479ee2018-05-23 17:52:48 -07001979 * Make sure that all activities that need to be visible in the stack (that is, they
1980 * currently can be seen by the user) actually are and update their configuration.
1981 */
1982 final void ensureActivitiesVisibleLocked(ActivityRecord starting, int configChanges,
1983 boolean preserveWindows) {
1984 ensureActivitiesVisibleLocked(starting, configChanges, preserveWindows,
Andrii Kuliana39ae3e2018-05-31 12:43:54 -07001985 true /* notifyClients */);
Andrii Kulianf4479ee2018-05-23 17:52:48 -07001986 }
1987
1988 /**
1989 * Ensure visibility with an option to also update the configuration of visible activities.
1990 * @see #ensureActivitiesVisibleLocked(ActivityRecord, int, boolean)
Wale Ogunwaled32da472018-11-16 07:19:28 -08001991 * @see RootActivityContainer#ensureActivitiesVisible(ActivityRecord, int, boolean)
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001992 */
Wale Ogunwale66e16852017-10-19 13:35:52 -07001993 // TODO: Should be re-worked based on the fact that each task as a stack in most cases.
Filip Gruszczynskibc5a6c52015-09-22 13:13:24 -07001994 final void ensureActivitiesVisibleLocked(ActivityRecord starting, int configChanges,
Andrii Kuliana39ae3e2018-05-31 12:43:54 -07001995 boolean preserveWindows, boolean notifyClients) {
Jorim Jaggife762342016-10-13 14:33:27 +02001996 mTopActivityOccludesKeyguard = false;
1997 mTopDismissingKeyguardActivity = null;
Bryce Lee2a3cc462017-10-27 10:57:35 -07001998 mStackSupervisor.getKeyguardController().beginActivityVisibilityUpdate();
Jorim Jaggife762342016-10-13 14:33:27 +02001999 try {
2000 ActivityRecord top = topRunningActivityLocked();
2001 if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY, "ensureActivitiesVisible behind " + top
2002 + " configChanges=0x" + Integer.toHexString(configChanges));
2003 if (top != null) {
2004 checkTranslucentActivityWaiting(top);
2005 }
Craig Mautner5eda9b32013-07-02 11:58:16 -07002006
Jorim Jaggife762342016-10-13 14:33:27 +02002007 // If the top activity is not fullscreen, then we need to
2008 // make sure any activities under it are now visible.
2009 boolean aboveTop = top != null;
Wale Ogunwale04a05ac2017-09-17 21:35:02 -07002010 final boolean stackShouldBeVisible = shouldBeVisible(starting);
2011 boolean behindFullscreenActivity = !stackShouldBeVisible;
Louis Changb7eb3cf2019-09-30 21:41:52 +08002012 // We should not resume activities that being launched behind because these
2013 // activities are actually behind other fullscreen activities, but still required
2014 // to be visible (such as performing Recents animation).
2015 final boolean resumeTopActivity = isFocusable() && isInStackLocked(starting) == null
2016 && top != null && !top.mLaunchTaskBehind;
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07002017 for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) {
Louis Changcdec0802019-11-11 11:45:07 +08002018 final Task task = getChildAt(taskNdx);
Wale Ogunwale1a06f152019-10-11 11:26:30 +02002019 for (int activityNdx = task.getChildCount() - 1; activityNdx >= 0; --activityNdx) {
2020 final ActivityRecord r = task.getChildAt(activityNdx);
Jorim Jaggife762342016-10-13 14:33:27 +02002021 final boolean isTop = r == top;
2022 if (aboveTop && !isTop) {
2023 continue;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002024 }
Jorim Jaggife762342016-10-13 14:33:27 +02002025 aboveTop = false;
Craig Mautnerd44711d2013-02-23 11:24:36 -08002026
Riddle Hsu13c27ae2019-10-05 23:10:15 +08002027 final boolean reallyVisible = r.shouldBeVisible(behindFullscreenActivity,
2028 false /* ignoringKeyguard */);
Jorim Jaggife762342016-10-13 14:33:27 +02002029 // Check whether activity should be visible without Keyguard influence
Riddle Hsu13c27ae2019-10-05 23:10:15 +08002030 if (r.visibleIgnoringKeyguard) {
2031 if (r.occludesParent()) {
2032 // At this point, nothing else needs to be shown in this task.
2033 if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY, "Fullscreen: at " + r
2034 + " stackVisible=" + stackShouldBeVisible
2035 + " behindFullscreen=" + behindFullscreenActivity);
2036 behindFullscreenActivity = true;
2037 } else {
2038 behindFullscreenActivity = false;
2039 }
Jorim Jaggife762342016-10-13 14:33:27 +02002040 }
Riddle Hsu13c27ae2019-10-05 23:10:15 +08002041
Jorim Jaggife762342016-10-13 14:33:27 +02002042 if (reallyVisible) {
Andrii Kulian149d9ad32019-08-23 15:04:17 -07002043 if (r.finishing) {
2044 continue;
2045 }
Jorim Jaggife762342016-10-13 14:33:27 +02002046 if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY, "Make visible? " + r
Bryce Lee7ace3952018-02-16 14:34:32 -08002047 + " finishing=" + r.finishing + " state=" + r.getState());
Jorim Jaggife762342016-10-13 14:33:27 +02002048 // First: if this is not the current activity being started, make
2049 // sure it matches the current configuration.
Andrii Kuliana39ae3e2018-05-31 12:43:54 -07002050 if (r != starting && notifyClients) {
Wale Ogunwaleb6d75f32018-02-22 20:44:56 -08002051 r.ensureActivityConfiguration(0 /* globalChanges */, preserveWindows,
Riddle Hsu609a8e22019-06-27 16:46:29 -06002052 true /* ignoreVisibility */);
Jorim Jaggife762342016-10-13 14:33:27 +02002053 }
2054
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002055 if (!r.attachedToProcess()) {
Louis Changcfe46212019-07-30 10:34:18 +08002056 makeVisibleAndRestartIfNeeded(starting, configChanges, isTop,
2057 resumeTopActivity && isTop, r);
Issei Suzuki1669ea42019-11-06 14:20:59 +01002058 } else if (r.mVisibleRequested) {
Jorim Jaggife762342016-10-13 14:33:27 +02002059 // If this activity is already visible, then there is nothing to do here.
2060 if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY,
2061 "Skipping: already visible at " + r);
2062
Andrii Kuliana39ae3e2018-05-31 12:43:54 -07002063 if (r.mClientVisibilityDeferred && notifyClients) {
2064 r.makeClientVisible();
2065 }
2066
Louis Changcfe46212019-07-30 10:34:18 +08002067 r.handleAlreadyVisible();
Andrii Kulian6b321512019-01-23 06:37:00 +00002068 if (notifyClients) {
2069 r.makeActiveIfNeeded(starting);
2070 }
Jorim Jaggife762342016-10-13 14:33:27 +02002071 } else {
Andrii Kuliana39ae3e2018-05-31 12:43:54 -07002072 r.makeVisibleIfNeeded(starting, notifyClients);
Craig Mautnerd44711d2013-02-23 11:24:36 -08002073 }
Jorim Jaggife762342016-10-13 14:33:27 +02002074 // Aggregate current change flags.
2075 configChanges |= r.configChangeFlags;
Craig Mautnerbb742462014-07-07 15:28:55 -07002076 } else {
Jorim Jaggife762342016-10-13 14:33:27 +02002077 if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY, "Make invisible? " + r
Bryce Lee7ace3952018-02-16 14:34:32 -08002078 + " finishing=" + r.finishing + " state=" + r.getState()
Wale Ogunwale04a05ac2017-09-17 21:35:02 -07002079 + " stackShouldBeVisible=" + stackShouldBeVisible
Wale Ogunwale9dcf9462017-09-19 15:13:01 -07002080 + " behindFullscreenActivity=" + behindFullscreenActivity
2081 + " mLaunchTaskBehind=" + r.mLaunchTaskBehind);
Andrii Kulian79d67982019-08-19 11:56:16 -07002082 r.makeInvisible();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002083 }
Jorim Jaggife762342016-10-13 14:33:27 +02002084 }
Wale Ogunwale44f036f2017-09-29 05:09:09 -07002085 final int windowingMode = getWindowingMode();
2086 if (windowingMode == WINDOWING_MODE_FREEFORM) {
Jorim Jaggife762342016-10-13 14:33:27 +02002087 // The visibility of tasks and the activities they contain in freeform stack are
2088 // determined individually unlike other stacks where the visibility or fullscreen
2089 // status of an activity in a previous task affects other.
Wale Ogunwale04a05ac2017-09-17 21:35:02 -07002090 behindFullscreenActivity = !stackShouldBeVisible;
Wale Ogunwale68278562017-09-23 17:13:55 -07002091 } else if (isActivityTypeHome()) {
Wale Ogunwale6fbde9f2017-08-24 07:24:12 -07002092 if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY, "Home task: at " + task
Wale Ogunwale04a05ac2017-09-17 21:35:02 -07002093 + " stackShouldBeVisible=" + stackShouldBeVisible
Wale Ogunwale6fbde9f2017-08-24 07:24:12 -07002094 + " behindFullscreenActivity=" + behindFullscreenActivity);
2095 // No other task in the home stack should be visible behind the home activity.
2096 // Home activities is usually a translucent activity with the wallpaper behind
2097 // them. However, when they don't have the wallpaper behind them, we want to
2098 // show activities in the next application stack behind them vs. another
2099 // task in the home stack like recents.
2100 behindFullscreenActivity = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002101 }
2102 }
Wale Ogunwale74e26592016-02-05 11:48:37 -08002103
Jorim Jaggife762342016-10-13 14:33:27 +02002104 if (mTranslucentActivityWaiting != null &&
2105 mUndrawnActivitiesBelowTopTranslucent.isEmpty()) {
2106 // Nothing is getting drawn or everything was already visible, don't wait for timeout.
2107 notifyActivityDrawnLocked(null);
2108 }
2109 } finally {
Bryce Lee2a3cc462017-10-27 10:57:35 -07002110 mStackSupervisor.getKeyguardController().endActivityVisibilityUpdate();
Jorim Jaggife762342016-10-13 14:33:27 +02002111 }
2112 }
2113
Jorim Jaggi8b702ed2017-01-20 16:59:03 +01002114 void addStartingWindowsForVisibleActivities(boolean taskSwitch) {
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07002115 for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) {
2116 getChildAt(taskNdx).addStartingWindowsForVisibleActivities(taskSwitch);
Jorim Jaggi8b702ed2017-01-20 16:59:03 +01002117 }
2118 }
2119
Jorim Jaggife762342016-10-13 14:33:27 +02002120 /**
2121 * @return true if the top visible activity wants to occlude the Keyguard, false otherwise
2122 */
2123 boolean topActivityOccludesKeyguard() {
2124 return mTopActivityOccludesKeyguard;
2125 }
2126
2127 /**
Wale Ogunwale44f036f2017-09-29 05:09:09 -07002128 * Returns true if this stack should be resized to match the bounds specified by
2129 * {@link ActivityOptions#setLaunchBounds} when launching an activity into the stack.
2130 */
Evan Roskydbe2ce52019-07-18 11:13:17 -07002131 boolean shouldResizeStackWithLaunchBounds() {
Wale Ogunwale44f036f2017-09-29 05:09:09 -07002132 return inPinnedWindowingMode();
2133 }
2134
Wale Ogunwale30e441d2017-11-09 08:28:45 -08002135 @Override
2136 public boolean supportsSplitScreenWindowingMode() {
Louis Changcdec0802019-11-11 11:45:07 +08002137 final Task topTask = topTask();
Wale Ogunwale30e441d2017-11-09 08:28:45 -08002138 return super.supportsSplitScreenWindowingMode()
2139 && (topTask == null || topTask.supportsSplitScreenWindowingMode());
2140 }
2141
Wale Ogunwale2b07da82017-11-08 14:52:40 -08002142 /** @return True if the resizing of the primary-split-screen stack affects this stack size. */
2143 boolean affectedBySplitScreenResize() {
2144 if (!supportsSplitScreenWindowingMode()) {
2145 return false;
2146 }
2147 final int windowingMode = getWindowingMode();
2148 return windowingMode != WINDOWING_MODE_FREEFORM && windowingMode != WINDOWING_MODE_PINNED;
2149 }
2150
Wale Ogunwale44f036f2017-09-29 05:09:09 -07002151 /**
Jorim Jaggife762342016-10-13 14:33:27 +02002152 * @return the top most visible activity that wants to dismiss Keyguard
2153 */
2154 ActivityRecord getTopDismissingKeyguardActivity() {
2155 return mTopDismissingKeyguardActivity;
2156 }
2157
2158 /**
2159 * Checks whether {@param r} should be visible depending on Keyguard state and updates
2160 * {@link #mTopActivityOccludesKeyguard} and {@link #mTopDismissingKeyguardActivity} if
2161 * necessary.
2162 *
2163 * @return true if {@param r} is visible taken Keyguard state into account, false otherwise
2164 */
Wale Ogunwale2cca8622017-12-11 08:40:13 -08002165 boolean checkKeyguardVisibility(ActivityRecord r, boolean shouldBeVisible, boolean isTop) {
Lucas Dupin47a65c72018-02-15 14:16:18 -08002166 final int displayId = mDisplayId != INVALID_DISPLAY ? mDisplayId : DEFAULT_DISPLAY;
2167 final boolean keyguardOrAodShowing = mStackSupervisor.getKeyguardController()
2168 .isKeyguardOrAodShowing(displayId);
Bryce Lee2a3cc462017-10-27 10:57:35 -07002169 final boolean keyguardLocked = mStackSupervisor.getKeyguardController().isKeyguardLocked();
Wale Ogunwale2cca8622017-12-11 08:40:13 -08002170 final boolean showWhenLocked = r.canShowWhenLocked();
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08002171 final boolean dismissKeyguard = r.containsDismissKeyguardWindow();
Jorim Jaggife762342016-10-13 14:33:27 +02002172 if (shouldBeVisible) {
Jorim Jaggie69c9312016-10-31 18:24:38 -07002173 if (dismissKeyguard && mTopDismissingKeyguardActivity == null) {
Jorim Jaggife762342016-10-13 14:33:27 +02002174 mTopDismissingKeyguardActivity = r;
2175 }
2176
2177 // Only the top activity may control occluded, as we can't occlude the Keyguard if the
2178 // top app doesn't want to occlude it.
2179 if (isTop) {
2180 mTopActivityOccludesKeyguard |= showWhenLocked;
Wale Ogunwalec219c0b2015-09-12 09:18:07 -07002181 }
Andrii Kulianfc8f82b2017-01-26 13:17:27 -08002182
Andrii Kulian7211d2e2017-01-27 15:58:05 -08002183 final boolean canShowWithKeyguard = canShowWithInsecureKeyguard()
Bryce Lee2a3cc462017-10-27 10:57:35 -07002184 && mStackSupervisor.getKeyguardController().canDismissKeyguard();
Andrii Kulianfc8f82b2017-01-26 13:17:27 -08002185 if (canShowWithKeyguard) {
2186 return true;
2187 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002188 }
Lucas Dupin47a65c72018-02-15 14:16:18 -08002189 if (keyguardOrAodShowing) {
Jorim Jaggie69c9312016-10-31 18:24:38 -07002190 // If keyguard is showing, nothing is visible, except if we are able to dismiss Keyguard
Lucas Dupin47a65c72018-02-15 14:16:18 -08002191 // right away and AOD isn't visible.
Bryce Lee2a3cc462017-10-27 10:57:35 -07002192 return shouldBeVisible && mStackSupervisor.getKeyguardController()
Jorim Jaggi07961872016-11-23 11:28:57 +01002193 .canShowActivityWhileKeyguardShowing(r, dismissKeyguard);
Jorim Jaggife762342016-10-13 14:33:27 +02002194 } else if (keyguardLocked) {
Bryce Lee2a3cc462017-10-27 10:57:35 -07002195 return shouldBeVisible && mStackSupervisor.getKeyguardController().canShowWhileOccluded(
Jorim Jaggi07961872016-11-23 11:28:57 +01002196 dismissKeyguard, showWhenLocked);
Jorim Jaggife762342016-10-13 14:33:27 +02002197 } else {
2198 return shouldBeVisible;
Craig Mautnereb8abf72014-07-02 15:04:09 -07002199 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002200 }
Craig Mautner58547802013-03-05 08:23:53 -08002201
Andrii Kulianfc8f82b2017-01-26 13:17:27 -08002202 /**
2203 * Check if the display to which this stack is attached has
Andrii Kulian7211d2e2017-01-27 15:58:05 -08002204 * {@link Display#FLAG_CAN_SHOW_WITH_INSECURE_KEYGUARD} applied.
Andrii Kulianfc8f82b2017-01-26 13:17:27 -08002205 */
wilsonshih498a4b82018-12-11 16:10:16 +08002206 boolean canShowWithInsecureKeyguard() {
Wale Ogunwale9dcf9462017-09-19 15:13:01 -07002207 final ActivityDisplay activityDisplay = getDisplay();
Andrii Kulianfc8f82b2017-01-26 13:17:27 -08002208 if (activityDisplay == null) {
2209 throw new IllegalStateException("Stack is not attached to any display, stackId="
2210 + mStackId);
2211 }
2212
2213 final int flags = activityDisplay.mDisplay.getFlags();
Andrii Kulian7211d2e2017-01-27 15:58:05 -08002214 return (flags & FLAG_CAN_SHOW_WITH_INSECURE_KEYGUARD) != 0;
Andrii Kulianfc8f82b2017-01-26 13:17:27 -08002215 }
2216
Filip Gruszczynski9104aea2015-11-13 16:42:05 -08002217 private void checkTranslucentActivityWaiting(ActivityRecord top) {
2218 if (mTranslucentActivityWaiting != top) {
2219 mUndrawnActivitiesBelowTopTranslucent.clear();
2220 if (mTranslucentActivityWaiting != null) {
2221 // Call the callback with a timeout indication.
2222 notifyActivityDrawnLocked(null);
2223 mTranslucentActivityWaiting = null;
2224 }
2225 mHandler.removeMessages(TRANSLUCENT_TIMEOUT_MSG);
2226 }
2227 }
2228
2229 private boolean makeVisibleAndRestartIfNeeded(ActivityRecord starting, int configChanges,
Wale Ogunwaled046a012015-12-24 13:05:59 -08002230 boolean isTop, boolean andResume, ActivityRecord r) {
Filip Gruszczynski9104aea2015-11-13 16:42:05 -08002231 // We need to make sure the app is running if it's the top, or it is just made visible from
2232 // invisible. If the app is already visible, it must have died while it was visible. In this
2233 // case, we'll show the dead window but will not restart the app. Otherwise we could end up
2234 // thrashing.
Issei Suzuki1669ea42019-11-06 14:20:59 +01002235 if (isTop || !r.mVisibleRequested) {
Filip Gruszczynski9104aea2015-11-13 16:42:05 -08002236 // This activity needs to be visible, but isn't even running...
2237 // get it started and resume if no other stack in this stack is resumed.
2238 if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY, "Start and freeze screen for " + r);
2239 if (r != starting) {
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08002240 r.startFreezingScreenLocked(configChanges);
Filip Gruszczynski9104aea2015-11-13 16:42:05 -08002241 }
Issei Suzuki1669ea42019-11-06 14:20:59 +01002242 if (!r.mVisibleRequested || r.mLaunchTaskBehind) {
Filip Gruszczynski9104aea2015-11-13 16:42:05 -08002243 if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY, "Starting and making visible: " + r);
Issei Suzuki1669ea42019-11-06 14:20:59 +01002244 r.setVisibility(true);
Filip Gruszczynski9104aea2015-11-13 16:42:05 -08002245 }
2246 if (r != starting) {
Louis Changb7eb3cf2019-09-30 21:41:52 +08002247 mStackSupervisor.startSpecificActivityLocked(r, andResume, true /* checkConfig */);
Filip Gruszczynski9104aea2015-11-13 16:42:05 -08002248 return true;
2249 }
2250 }
2251 return false;
2252 }
2253
Todd Kennedyaab56db2015-01-30 09:39:53 -08002254 void convertActivityToTranslucent(ActivityRecord r) {
Craig Mautner5eda9b32013-07-02 11:58:16 -07002255 mTranslucentActivityWaiting = r;
2256 mUndrawnActivitiesBelowTopTranslucent.clear();
2257 mHandler.sendEmptyMessageDelayed(TRANSLUCENT_TIMEOUT_MSG, TRANSLUCENT_CONVERSION_TIMEOUT);
2258 }
2259
Dianne Hackbornb5a380d2015-05-20 18:18:46 -07002260 void clearOtherAppTimeTrackers(AppTimeTracker except) {
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07002261 for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) {
Louis Changcdec0802019-11-11 11:45:07 +08002262 final Task task = getChildAt(taskNdx);
Wale Ogunwale1a06f152019-10-11 11:26:30 +02002263 for (int activityNdx = task.getChildCount() - 1; activityNdx >= 0; --activityNdx) {
2264 final ActivityRecord r = task.getChildAt(activityNdx);
Dianne Hackbornb5a380d2015-05-20 18:18:46 -07002265 if ( r.appTimeTracker != except) {
2266 r.appTimeTracker = null;
2267 }
2268 }
2269 }
2270 }
2271
Craig Mautner5eda9b32013-07-02 11:58:16 -07002272 /**
2273 * Called as activities below the top translucent activity are redrawn. When the last one is
2274 * redrawn notify the top activity by calling
2275 * {@link Activity#onTranslucentConversionComplete}.
2276 *
2277 * @param r The most recent background activity to be drawn. Or, if r is null then a timeout
2278 * occurred and the activity will be notified immediately.
2279 */
2280 void notifyActivityDrawnLocked(ActivityRecord r) {
2281 if ((r == null)
2282 || (mUndrawnActivitiesBelowTopTranslucent.remove(r) &&
2283 mUndrawnActivitiesBelowTopTranslucent.isEmpty())) {
2284 // The last undrawn activity below the top has just been drawn. If there is an
2285 // opaque activity at the top, notify it that it can become translucent safely now.
2286 final ActivityRecord waitingActivity = mTranslucentActivityWaiting;
2287 mTranslucentActivityWaiting = null;
2288 mUndrawnActivitiesBelowTopTranslucent.clear();
2289 mHandler.removeMessages(TRANSLUCENT_TIMEOUT_MSG);
2290
Craig Mautner71dd1b62014-02-18 15:48:52 -08002291 if (waitingActivity != null) {
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002292 mWindowManager.setWindowOpaqueLocked(waitingActivity.appToken, false);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002293 if (waitingActivity.attachedToProcess()) {
Craig Mautner71dd1b62014-02-18 15:48:52 -08002294 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002295 waitingActivity.app.getThread().scheduleTranslucentConversionComplete(
Craig Mautner71dd1b62014-02-18 15:48:52 -08002296 waitingActivity.appToken, r != null);
2297 } catch (RemoteException e) {
2298 }
Craig Mautner5eda9b32013-07-02 11:58:16 -07002299 }
2300 }
2301 }
2302 }
2303
Riddle Hsu13c27ae2019-10-05 23:10:15 +08002304 /** @see ActivityRecord#cancelInitializing() */
Craig Mautnera61bc652013-10-28 15:43:18 -07002305 void cancelInitializingActivities() {
Wale Ogunwale68741142016-05-17 09:40:02 -07002306 // We don't want to clear starting window for activities that aren't behind fullscreen
2307 // activities as we need to display their starting window until they are done initializing.
Riddle Hsu13c27ae2019-10-05 23:10:15 +08002308 checkBehindFullscreenActivity(null /* toCheck */, ActivityRecord::cancelInitializing);
2309 }
2310
2311 /**
2312 * If an activity {@param toCheck} is given, this method returns {@code true} if the activity
2313 * is occluded by any fullscreen activity. If there is no {@param toCheck} and the handling
2314 * function {@param handleBehindFullscreenActivity} is given, this method will pass all occluded
2315 * activities to the function.
2316 */
2317 boolean checkBehindFullscreenActivity(ActivityRecord toCheck,
2318 Consumer<ActivityRecord> handleBehindFullscreenActivity) {
2319 boolean aboveTop = true;
Wale Ogunwale68741142016-05-17 09:40:02 -07002320 boolean behindFullscreenActivity = false;
Wale Ogunwale98742a52016-07-12 10:29:12 -07002321
Wale Ogunwale9dcf9462017-09-19 15:13:01 -07002322 if (!shouldBeVisible(null)) {
Wale Ogunwale98742a52016-07-12 10:29:12 -07002323 // The stack is not visible, so no activity in it should be displaying a starting
2324 // window. Mark all activities below top and behind fullscreen.
2325 aboveTop = false;
2326 behindFullscreenActivity = true;
2327 }
2328
Riddle Hsu13c27ae2019-10-05 23:10:15 +08002329 final boolean handlingOccluded = toCheck == null && handleBehindFullscreenActivity != null;
2330 if (!handlingOccluded && behindFullscreenActivity) {
2331 return true;
2332 }
2333
2334 final ActivityRecord topActivity = topRunningActivityLocked();
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07002335 for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) {
Louis Changcdec0802019-11-11 11:45:07 +08002336 final Task task = getChildAt(taskNdx);
Wale Ogunwale1a06f152019-10-11 11:26:30 +02002337 for (int activityNdx = task.getChildCount() - 1; activityNdx >= 0; --activityNdx) {
2338 final ActivityRecord r = task.getChildAt(activityNdx);
Craig Mautnera61bc652013-10-28 15:43:18 -07002339 if (aboveTop) {
2340 if (r == topActivity) {
Riddle Hsu13c27ae2019-10-05 23:10:15 +08002341 if (r == toCheck) {
2342 // It is the top activity in a visible stack.
2343 return false;
2344 }
Craig Mautnera61bc652013-10-28 15:43:18 -07002345 aboveTop = false;
2346 }
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08002347 behindFullscreenActivity |= r.occludesParent();
Craig Mautnera61bc652013-10-28 15:43:18 -07002348 continue;
2349 }
2350
Riddle Hsu13c27ae2019-10-05 23:10:15 +08002351 if (handlingOccluded) {
2352 handleBehindFullscreenActivity.accept(r);
2353 } else if (r == toCheck) {
2354 return behindFullscreenActivity;
2355 } else if (behindFullscreenActivity) {
2356 // It is occluded before {@param toCheck} is found.
2357 return true;
2358 }
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08002359 behindFullscreenActivity |= r.occludesParent();
Craig Mautnera61bc652013-10-28 15:43:18 -07002360 }
2361 }
Riddle Hsu13c27ae2019-10-05 23:10:15 +08002362 return behindFullscreenActivity;
Craig Mautnera61bc652013-10-28 15:43:18 -07002363 }
2364
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002365 /**
2366 * Ensure that the top activity in the stack is resumed.
2367 *
2368 * @param prev The previously resumed activity, for when in the process
2369 * of pausing; can be null to call from elsewhere.
Wale Ogunwaled046a012015-12-24 13:05:59 -08002370 * @param options Activity options.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002371 *
2372 * @return Returns true if something is being resumed, or false if
2373 * nothing happened.
Wale Ogunwaled046a012015-12-24 13:05:59 -08002374 *
2375 * NOTE: It is not safe to call this method directly as it can cause an activity in a
2376 * non-focused stack to be resumed.
Wale Ogunwaled32da472018-11-16 07:19:28 -08002377 * Use {@link RootActivityContainer#resumeFocusedStacksTopActivities} to resume the
Wale Ogunwaled046a012015-12-24 13:05:59 -08002378 * right activity for the current system state.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002379 */
Andreas Gampea36dc622018-02-05 17:19:22 -08002380 @GuardedBy("mService")
Wale Ogunwaled046a012015-12-24 13:05:59 -08002381 boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
Andrii Kulian6b321512019-01-23 06:37:00 +00002382 if (mInResumeTopActivity) {
Craig Mautner544efa72014-09-04 16:41:20 -07002383 // Don't even start recursing.
2384 return false;
2385 }
2386
2387 boolean result = false;
2388 try {
2389 // Protect against recursion.
Andrii Kulian6b321512019-01-23 06:37:00 +00002390 mInResumeTopActivity = true;
Bryce Lee69ad8182017-09-28 10:01:36 -07002391 result = resumeTopActivityInnerLocked(prev, options);
Bryce Leefc7cedd2018-03-01 15:38:07 -08002392
2393 // When resuming the top activity, it may be necessary to pause the top activity (for
2394 // example, returning to the lock screen. We suppress the normal pause logic in
2395 // {@link #resumeTopActivityUncheckedLocked}, since the top activity is resumed at the
2396 // end. We call the {@link ActivityStackSupervisor#checkReadyForSleepLocked} again here
2397 // to ensure any necessary pause logic occurs. In the case where the Activity will be
2398 // shown regardless of the lock screen, the call to
2399 // {@link ActivityStackSupervisor#checkReadyForSleepLocked} is skipped.
2400 final ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */);
2401 if (next == null || !next.canTurnScreenOn()) {
2402 checkReadyForSleep();
2403 }
Craig Mautner544efa72014-09-04 16:41:20 -07002404 } finally {
Andrii Kulian6b321512019-01-23 06:37:00 +00002405 mInResumeTopActivity = false;
Craig Mautner544efa72014-09-04 16:41:20 -07002406 }
chaviw59b98852017-06-13 12:05:44 -07002407
Craig Mautner544efa72014-09-04 16:41:20 -07002408 return result;
2409 }
2410
Bryce Leec4ab62a2018-03-05 14:19:26 -08002411 /**
2412 * Returns the currently resumed activity.
2413 */
2414 protected ActivityRecord getResumedActivity() {
2415 return mResumedActivity;
2416 }
2417
Bryce Lee84730a02018-04-03 14:10:04 -07002418 private void setResumedActivity(ActivityRecord r, String reason) {
2419 if (mResumedActivity == r) {
2420 return;
2421 }
Bryce Leec4ab62a2018-03-05 14:19:26 -08002422
Bryce Lee84730a02018-04-03 14:10:04 -07002423 if (DEBUG_STACK) Slog.d(TAG_STACK, "setResumedActivity stack:" + this + " + from: "
2424 + mResumedActivity + " to:" + r + " reason:" + reason);
2425 mResumedActivity = r;
Louis Chang3b21bdc2019-03-25 15:49:14 +08002426 mStackSupervisor.updateTopResumedActivityIfNeeded();
Chong Zhang6cda19c2016-06-14 19:07:56 -07002427 }
2428
Andreas Gampea36dc622018-02-05 17:19:22 -08002429 @GuardedBy("mService")
Chong Zhang280d3322015-11-03 17:27:26 -08002430 private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
Wale Ogunwale53783742018-09-16 10:21:51 -07002431 if (!mService.isBooting() && !mService.isBooted()) {
Dianne Hackborn7622a0f2014-09-30 14:31:42 -07002432 // Not ready yet!
2433 return false;
2434 }
2435
Winson Chung3f103eb2017-04-12 21:53:59 -07002436 // Find the next top-most activity to resume in this stack that is not finishing and is
2437 // focusable. If it is not focusable, we will fall into the case below to resume the
2438 // top activity in the next focusable task.
Andrii Kulian6b321512019-01-23 06:37:00 +00002439 ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */);
Andrii Kulian7fc22812016-12-28 13:04:11 -08002440
2441 final boolean hasRunningActivity = next != null;
2442
Andrii Kulian94e82d9b02017-07-13 15:33:06 -07002443 // TODO: Maybe this entire condition can get removed?
Wale Ogunwale66e16852017-10-19 13:35:52 -07002444 if (hasRunningActivity && !isAttached()) {
Craig Mautnerdf88d732014-01-27 09:21:32 -08002445 return false;
2446 }
2447
Wale Ogunwaled32da472018-11-16 07:19:28 -08002448 mRootActivityContainer.cancelInitializingActivities();
Craig Mautnera61bc652013-10-28 15:43:18 -07002449
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002450 // Remember how we'll process this pause/resume situation, and ensure
2451 // that the state is reset however we wind up proceeding.
Wale Ogunwalec59b4f62017-11-30 11:05:43 -08002452 boolean userLeaving = mStackSupervisor.mUserLeaving;
Craig Mautnerde4ef022013-04-07 19:01:33 -07002453 mStackSupervisor.mUserLeaving = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002454
Andrii Kulian7fc22812016-12-28 13:04:11 -08002455 if (!hasRunningActivity) {
2456 // There are no activities left in the stack, let's look somewhere else.
Andrii Kulian3ff5a0b2019-05-16 13:18:04 -07002457 return resumeNextFocusableActivityWhenStackIsEmpty(prev, options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002458 }
2459
2460 next.delayedResume = false;
Riddle Hsubbb63c22018-10-03 12:28:29 +08002461 final ActivityDisplay display = getDisplay();
Craig Mautner58547802013-03-05 08:23:53 -08002462
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002463 // If the top activity is the resumed one, nothing to do.
Bryce Lee7ace3952018-02-16 14:34:32 -08002464 if (mResumedActivity == next && next.isState(RESUMED)
Riddle Hsubbb63c22018-10-03 12:28:29 +08002465 && display.allResumedActivitiesComplete()) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002466 // Make sure we have executed any pending transitions, since there
2467 // should be nothing left to do at this point.
skuhne@google.com1b974dc2016-12-09 13:41:29 -08002468 executeAppTransition(options);
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07002469 if (DEBUG_STATES) Slog.d(TAG_STATES,
2470 "resumeTopActivityLocked: Top activity resumed " + next);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002471 return false;
2472 }
2473
Louis Chang77ce34d2019-01-03 15:45:12 +08002474 if (!next.canResumeByCompat()) {
2475 return false;
2476 }
2477
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002478 // If we are sleeping, and there is no resumed activity, and the top
2479 // activity is paused, well that is the state we want.
David Stevens9440dc82017-03-16 19:00:20 -07002480 if (shouldSleepOrShutDownActivities()
p13451dbad2872012-04-18 11:39:23 +09002481 && mLastPausedActivity == next
Wale Ogunwaled32da472018-11-16 07:19:28 -08002482 && mRootActivityContainer.allPausedActivitiesComplete()) {
Riddle Hsuef713772018-09-18 01:28:53 +08002483 // If the current top activity may be able to occlude keyguard but the occluded state
2484 // has not been set, update visibility and check again if we should continue to resume.
2485 boolean nothingToResume = true;
Riddle Hsu32a87b82018-11-21 00:08:19 +08002486 if (!mService.mShuttingDown) {
2487 final boolean canShowWhenLocked = !mTopActivityOccludesKeyguard
2488 && next.canShowWhenLocked();
2489 final boolean mayDismissKeyguard = mTopDismissingKeyguardActivity != next
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08002490 && next.containsDismissKeyguardWindow();
Issei Suzuki74e1eb22018-12-20 17:42:52 +01002491
Riddle Hsu32a87b82018-11-21 00:08:19 +08002492 if (canShowWhenLocked || mayDismissKeyguard) {
2493 ensureActivitiesVisibleLocked(null /* starting */, 0 /* configChanges */,
2494 !PRESERVE_WINDOWS);
2495 nothingToResume = shouldSleepActivities();
2496 }
Riddle Hsuef713772018-09-18 01:28:53 +08002497 }
2498 if (nothingToResume) {
2499 // Make sure we have executed any pending transitions, since there
2500 // should be nothing left to do at this point.
2501 executeAppTransition(options);
2502 if (DEBUG_STATES) Slog.d(TAG_STATES,
2503 "resumeTopActivityLocked: Going to sleep and all paused");
Riddle Hsuef713772018-09-18 01:28:53 +08002504 return false;
2505 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002506 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002507
2508 // Make sure that the user who owns this activity is started. If not,
2509 // we will just leave it as is because someone should be bringing
2510 // another user's activities to the top of the stack.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002511 if (!mService.mAmInternal.hasStartedUserState(next.mUserId)) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002512 Slog.w(TAG, "Skipping resume of top activity " + next
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002513 + ": user " + next.mUserId + " is stopped");
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002514 return false;
2515 }
2516
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002517 // The activity may be waiting for stop, but that is no longer
2518 // appropriate for it.
Craig Mautnerde4ef022013-04-07 19:01:33 -07002519 mStackSupervisor.mStoppingActivities.remove(next);
Craig Mautner0eea92c2013-05-16 13:35:39 -07002520 mStackSupervisor.mGoingToSleepActivities.remove(next);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08002521 next.sleeping = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002522
Wale Ogunwaleee006da2015-03-30 14:49:25 -07002523 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "Resuming " + next);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002524
Wale Ogunwale5658e4b2016-02-12 12:22:19 -08002525 // If we are currently pausing an activity, then don't do anything until that is done.
Wale Ogunwaled32da472018-11-16 07:19:28 -08002526 if (!mRootActivityContainer.allPausedActivitiesComplete()) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -07002527 if (DEBUG_SWITCH || DEBUG_PAUSE || DEBUG_STATES) Slog.v(TAG_PAUSE,
Craig Mautnerac6f8432013-07-17 13:24:59 -07002528 "resumeTopActivityLocked: Skip resume: some activity pausing.");
Andrii Kulian6b321512019-01-23 06:37:00 +00002529
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002530 return false;
2531 }
2532
Dianne Hackborn3d07c942015-03-13 18:02:54 -07002533 mStackSupervisor.setLaunchSource(next.info.applicationInfo.uid);
2534
chaviw4ad54912018-05-30 11:05:44 -07002535 ActivityRecord lastResumed = null;
Riddle Hsubbb63c22018-10-03 12:28:29 +08002536 final ActivityStack lastFocusedStack = display.getLastFocusedStack();
Wale Ogunwale89973222017-04-23 18:39:45 -07002537 if (lastFocusedStack != null && lastFocusedStack != this) {
2538 // So, why aren't we using prev here??? See the param comment on the method. prev doesn't
2539 // represent the last resumed activity. However, the last focus stack does if it isn't null.
chaviw4ad54912018-05-30 11:05:44 -07002540 lastResumed = lastFocusedStack.mResumedActivity;
Wale Ogunwalec59b4f62017-11-30 11:05:43 -08002541 if (userLeaving && inMultiWindowMode() && lastFocusedStack.shouldBeVisible(next)) {
2542 // The user isn't leaving if this stack is the multi-window mode and the last
2543 // focused stack should still be visible.
2544 if(DEBUG_USER_LEAVING) Slog.i(TAG_USER_LEAVING, "Overriding userLeaving to false"
2545 + " next=" + next + " lastResumed=" + lastResumed);
2546 userLeaving = false;
2547 }
Wale Ogunwale89973222017-04-23 18:39:45 -07002548 }
Wale Ogunwale89973222017-04-23 18:39:45 -07002549
Louis Chang7b03ad92019-08-21 12:32:33 +08002550 boolean pausing = display.pauseBackStacks(userLeaving, next);
Craig Mautnereb957862013-04-24 15:34:32 -07002551 if (mResumedActivity != null) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07002552 if (DEBUG_STATES) Slog.d(TAG_STATES,
2553 "resumeTopActivityLocked: Pausing " + mResumedActivity);
Louis Chang7b03ad92019-08-21 12:32:33 +08002554 pausing |= startPausingLocked(userLeaving, false /* uiSleeping */, next);
Craig Mautnereb957862013-04-24 15:34:32 -07002555 }
Louis Chang7b03ad92019-08-21 12:32:33 +08002556 if (pausing) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07002557 if (DEBUG_SWITCH || DEBUG_STATES) Slog.v(TAG_STATES,
Craig Mautnerac6f8432013-07-17 13:24:59 -07002558 "resumeTopActivityLocked: Skip resume: need to start pausing");
Dianne Hackbornad9b32112012-09-17 15:35:01 -07002559 // At this point we want to put the upcoming activity's process
2560 // at the top of the LRU list, since we know we will be needing it
2561 // very soon and it would be a waste to let it get killed if it
2562 // happens to be sitting towards the end.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002563 if (next.attachedToProcess()) {
2564 next.app.updateProcessInfo(false /* updateServiceConnectionActivities */,
Riddle Hsu17e38422019-04-12 16:55:11 +08002565 true /* activityChange */, false /* updateOomAdj */);
Riddle Hsu32dbdca2019-05-17 23:10:16 -06002566 } else if (!next.isProcessRunning()) {
2567 // Since the start-process is asynchronous, if we already know the process of next
2568 // activity isn't running, we can start the process earlier to save the time to wait
2569 // for the current activity to be paused.
2570 final boolean isTop = this == display.getFocusedStack();
2571 mService.startProcessAsync(next, false /* knownToBeDead */, isTop,
2572 isTop ? "pre-top-activity" : "pre-activity");
Dianne Hackbornad9b32112012-09-17 15:35:01 -07002573 }
chaviw4ad54912018-05-30 11:05:44 -07002574 if (lastResumed != null) {
2575 lastResumed.setWillCloseOrEnterPip(true);
2576 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002577 return true;
Bryce Lee7ace3952018-02-16 14:34:32 -08002578 } else if (mResumedActivity == next && next.isState(RESUMED)
Riddle Hsubbb63c22018-10-03 12:28:29 +08002579 && display.allResumedActivitiesComplete()) {
Wale Ogunwalecac5c322016-05-23 10:56:33 -07002580 // It is possible for the activity to be resumed when we paused back stacks above if the
2581 // next activity doesn't have to wait for pause to complete.
2582 // So, nothing else to-do except:
2583 // Make sure we have executed any pending transitions, since there
2584 // should be nothing left to do at this point.
skuhne@google.com1b974dc2016-12-09 13:41:29 -08002585 executeAppTransition(options);
Wale Ogunwalecac5c322016-05-23 10:56:33 -07002586 if (DEBUG_STATES) Slog.d(TAG_STATES,
2587 "resumeTopActivityLocked: Top activity resumed (dontWaitForPause) " + next);
Wale Ogunwalecac5c322016-05-23 10:56:33 -07002588 return true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002589 }
2590
Christopher Tated3f175c2012-06-14 14:16:54 -07002591 // If the most recent activity was noHistory but was only stopped rather
2592 // than stopped+finished because the device went to sleep, we need to make
2593 // sure to finish it as we're making a new activity topmost.
David Stevens9440dc82017-03-16 19:00:20 -07002594 if (shouldSleepActivities() && mLastNoHistoryActivity != null &&
Craig Mautner0f922742013-08-06 08:44:42 -07002595 !mLastNoHistoryActivity.finishing) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07002596 if (DEBUG_STATES) Slog.d(TAG_STATES,
2597 "no-history finish of " + mLastNoHistoryActivity + " on new resume");
Andrii Kulian7dd39bb2019-07-22 13:11:10 -07002598 mLastNoHistoryActivity.finishIfPossible("resume-no-history", false /* oomAdj */);
Craig Mautner0f922742013-08-06 08:44:42 -07002599 mLastNoHistoryActivity = null;
Christopher Tated3f175c2012-06-14 14:16:54 -07002600 }
2601
Jorim Jaggi9b5e3312019-03-01 18:08:00 +01002602 if (prev != null && prev != next && next.nowVisible) {
2603
2604 // The next activity is already visible, so hide the previous
2605 // activity's windows right now so we can show the new one ASAP.
2606 // We only do this if the previous is finishing, which should mean
2607 // it is on top of the one being resumed so hiding it quickly
2608 // is good. Otherwise, we want to do the normal route of allowing
2609 // the resumed activity to be shown so we can decide if the
2610 // previous should actually be hidden depending on whether the
2611 // new one is found to be full-screen or not.
2612 if (prev.finishing) {
2613 prev.setVisibility(false);
Wale Ogunwaleee006da2015-03-30 14:49:25 -07002614 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH,
Jorim Jaggi9b5e3312019-03-01 18:08:00 +01002615 "Not waiting for visible to hide: " + prev
2616 + ", nowVisible=" + next.nowVisible);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002617 } else {
Jorim Jaggi9b5e3312019-03-01 18:08:00 +01002618 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH,
2619 "Previous already visible but still waiting to hide: " + prev
2620 + ", nowVisible=" + next.nowVisible);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002621 }
Jorim Jaggi9b5e3312019-03-01 18:08:00 +01002622
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002623 }
2624
Dianne Hackborne7f97212011-02-24 14:40:20 -08002625 // Launching this app's activity, make sure the app is no longer
2626 // considered stopped.
2627 try {
Wale Ogunwale8a1860a2019-06-05 08:57:19 -07002628 mService.getPackageManager().setPackageStoppedState(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002629 next.packageName, false, next.mUserId); /* TODO: Verify if correct userid */
Dianne Hackborne7f97212011-02-24 14:40:20 -08002630 } catch (RemoteException e1) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08002631 } catch (IllegalArgumentException e) {
2632 Slog.w(TAG, "Failed trying to unstop package "
2633 + next.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08002634 }
2635
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002636 // We are starting up the next activity, so tell the window manager
2637 // that the previous one will be hidden soon. This way it can know
2638 // to ignore it when computing the desired screen orientation.
Craig Mautner525f3d92013-05-07 14:01:50 -07002639 boolean anim = true;
Riddle Hsu32dbdca2019-05-17 23:10:16 -06002640 final DisplayContent dc = display.mDisplayContent;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002641 if (prev != null) {
2642 if (prev.finishing) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -07002643 if (DEBUG_TRANSITION) Slog.v(TAG_TRANSITION,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002644 "Prepare close transition: prev=" + prev);
Jorim Jaggifa9ed962018-01-25 00:16:49 +01002645 if (mStackSupervisor.mNoAnimActivities.contains(prev)) {
Craig Mautner525f3d92013-05-07 14:01:50 -07002646 anim = false;
Wale Ogunwale3a256e62018-12-06 14:41:18 -08002647 dc.prepareAppTransition(TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002648 } else {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08002649 dc.prepareAppTransition(
Louis Changcdec0802019-11-11 11:45:07 +08002650 prev.getTask() == next.getTask() ? TRANSIT_ACTIVITY_CLOSE
lumark588a3e82018-07-20 18:53:54 +08002651 : TRANSIT_TASK_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002652 }
Wale Ogunwale26c0dfe2016-12-14 14:42:30 -08002653 prev.setVisibility(false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002654 } else {
Wale Ogunwaleee006da2015-03-30 14:49:25 -07002655 if (DEBUG_TRANSITION) Slog.v(TAG_TRANSITION,
2656 "Prepare open transition: prev=" + prev);
Jorim Jaggifa9ed962018-01-25 00:16:49 +01002657 if (mStackSupervisor.mNoAnimActivities.contains(next)) {
Craig Mautner525f3d92013-05-07 14:01:50 -07002658 anim = false;
Wale Ogunwale3a256e62018-12-06 14:41:18 -08002659 dc.prepareAppTransition(TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002660 } else {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08002661 dc.prepareAppTransition(
Louis Changcdec0802019-11-11 11:45:07 +08002662 prev.getTask() == next.getTask() ? TRANSIT_ACTIVITY_OPEN
lumark588a3e82018-07-20 18:53:54 +08002663 : next.mLaunchTaskBehind ? TRANSIT_TASK_OPEN_BEHIND
2664 : TRANSIT_TASK_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002665 }
2666 }
Craig Mautner967212c2013-04-13 21:10:58 -07002667 } else {
Wale Ogunwaleee006da2015-03-30 14:49:25 -07002668 if (DEBUG_TRANSITION) Slog.v(TAG_TRANSITION, "Prepare open transition: no previous");
Jorim Jaggifa9ed962018-01-25 00:16:49 +01002669 if (mStackSupervisor.mNoAnimActivities.contains(next)) {
Craig Mautner525f3d92013-05-07 14:01:50 -07002670 anim = false;
Wale Ogunwale3a256e62018-12-06 14:41:18 -08002671 dc.prepareAppTransition(TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002672 } else {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08002673 dc.prepareAppTransition(TRANSIT_ACTIVITY_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002674 }
2675 }
Adam Powellcfbe9be2013-11-06 14:58:58 -08002676
Craig Mautner525f3d92013-05-07 14:01:50 -07002677 if (anim) {
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002678 next.applyOptionsLocked();
2679 } else {
2680 next.clearOptionsLocked();
2681 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002682
Jorim Jaggifa9ed962018-01-25 00:16:49 +01002683 mStackSupervisor.mNoAnimActivities.clear();
2684
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002685 if (next.attachedToProcess()) {
Chong Zhangdea4bd92016-03-15 12:50:03 -07002686 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "Resume running: " + next
Issei Suzuki1669ea42019-11-06 14:20:59 +01002687 + " stopped=" + next.stopped
2688 + " visibleRequested=" + next.mVisibleRequested);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002689
Chong Zhangd127c6d2016-05-02 16:36:41 -07002690 // If the previous activity is translucent, force a visibility update of
2691 // the next activity, so that it's added to WM's opening app list, and
2692 // transition animation can be set up properly.
2693 // For example, pressing Home button with a translucent activity in focus.
2694 // Launcher is already visible in this case. If we don't add it to opening
2695 // apps, maybeUpdateTransitToWallpaper() will fail to identify this as a
2696 // TRANSIT_WALLPAPER_OPEN animation, and run some funny animation.
Riddle Hsubbb63c22018-10-03 12:28:29 +08002697 final boolean lastActivityTranslucent = lastFocusedStack != null
2698 && (lastFocusedStack.inMultiWindowMode()
2699 || (lastFocusedStack.mLastPausedActivity != null
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08002700 && !lastFocusedStack.mLastPausedActivity.occludesParent()));
Chong Zhangd127c6d2016-05-02 16:36:41 -07002701
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08002702 // This activity is now becoming visible.
Issei Suzuki1669ea42019-11-06 14:20:59 +01002703 if (!next.mVisibleRequested || next.stopped || lastActivityTranslucent) {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08002704 next.setVisibility(true);
2705 }
2706
2707 // schedule launch ticks to collect information about slow apps.
2708 next.startLaunchTickingLocked();
2709
2710 ActivityRecord lastResumedActivity =
2711 lastFocusedStack == null ? null : lastFocusedStack.mResumedActivity;
2712 final ActivityState lastState = next.getState();
2713
2714 mService.updateCpuStats();
2715
2716 if (DEBUG_STATES) Slog.v(TAG_STATES, "Moving to RESUMED: " + next
2717 + " (in existing)");
2718
2719 next.setState(RESUMED, "resumeTopActivityInnerLocked");
2720
2721 next.app.updateProcessInfo(false /* updateServiceConnectionActivities */,
Riddle Hsu17e38422019-04-12 16:55:11 +08002722 true /* activityChange */, true /* updateOomAdj */);
Riddle Hsu5477b572019-11-12 16:07:29 +08002723 updateLruList(next);
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08002724
2725 // Have the window manager re-evaluate the orientation of
2726 // the screen based on the new activity order.
2727 boolean notUpdated = true;
2728
Andrii Kulian6b321512019-01-23 06:37:00 +00002729 // Activity should also be visible if set mLaunchTaskBehind to true (see
2730 // ActivityRecord#shouldBeVisibleIgnoringKeyguard()).
2731 if (shouldBeVisible(next)) {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08002732 // We have special rotation behavior when here is some active activity that
2733 // requests specific orientation or Keyguard is locked. Make sure all activity
2734 // visibilities are set correctly as well as the transition is updated if needed
2735 // to get the correct rotation behavior. Otherwise the following call to update
2736 // the orientation may cause incorrect configurations delivered to client as a
2737 // result of invisible window resize.
2738 // TODO: Remove this once visibilities are set correctly immediately when
2739 // starting an activity.
Wale Ogunwaled32da472018-11-16 07:19:28 -08002740 notUpdated = !mRootActivityContainer.ensureVisibilityAndConfig(next, mDisplayId,
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08002741 true /* markFrozenIfConfigChanged */, false /* deferResume */);
2742 }
2743
2744 if (notUpdated) {
2745 // The configuration update wasn't able to keep the existing
2746 // instance of the activity, and instead started a new one.
2747 // We should be all done, but let's just make sure our activity
2748 // is still at the top and schedule another run if something
2749 // weird happened.
2750 ActivityRecord nextNext = topRunningActivityLocked();
2751 if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG_STATES,
2752 "Activity config changed during resume: " + next
2753 + ", new next: " + nextNext);
2754 if (nextNext != next) {
2755 // Do over!
2756 mStackSupervisor.scheduleResumeTopActivities();
2757 }
Issei Suzuki1669ea42019-11-06 14:20:59 +01002758 if (!next.mVisibleRequested || next.stopped) {
Wale Ogunwale26c0dfe2016-12-14 14:42:30 -08002759 next.setVisibility(true);
Craig Mautnerde4ef022013-04-07 19:01:33 -07002760 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08002761 next.completeResumeLocked();
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08002762 return true;
2763 }
Craig Mautner58547802013-03-05 08:23:53 -08002764
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08002765 try {
2766 final ClientTransaction transaction =
2767 ClientTransaction.obtain(next.app.getThread(), next.appToken);
2768 // Deliver all pending results.
2769 ArrayList<ResultInfo> a = next.results;
2770 if (a != null) {
2771 final int N = a.size();
2772 if (!next.finishing && N > 0) {
2773 if (DEBUG_RESULTS) Slog.v(TAG_RESULTS,
2774 "Delivering results to " + next + ": " + a);
2775 transaction.addCallback(ActivityResultItem.obtain(a));
2776 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002777 }
2778
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08002779 if (next.newIntents != null) {
Louis Changea203cd2019-07-01 12:39:31 +08002780 transaction.addCallback(
2781 NewIntentItem.obtain(next.newIntents, true /* resume */));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002782 }
2783
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08002784 // Well the app will no longer be stopped.
2785 // Clear app token stopped state in window manager if needed.
2786 next.notifyAppResumed(next.stopped);
Wale Ogunwale8d5a5422016-03-03 18:28:21 -08002787
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002788 EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY, next.mUserId,
Louis Changcdec0802019-11-11 11:45:07 +08002789 System.identityHashCode(next), next.getTask().mTaskId,
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08002790 next.shortComponentName);
Craig Mautner58547802013-03-05 08:23:53 -08002791
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08002792 next.sleeping = false;
2793 mService.getAppWarningsLocked().onResumeActivity(next);
2794 next.app.setPendingUiCleanAndForceProcessStateUpTo(mService.mTopProcessState);
2795 next.clearOptionsLocked();
2796 transaction.setLifecycleStateRequest(
2797 ResumeActivityItem.obtain(next.app.getReportedProcState(),
Riddle Hsu32dbdca2019-05-17 23:10:16 -06002798 dc.isNextTransitionForward()));
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08002799 mService.getLifecycleManager().scheduleTransaction(transaction);
Craig Mautner58547802013-03-05 08:23:53 -08002800
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08002801 if (DEBUG_STATES) Slog.d(TAG_STATES, "resumeTopActivityLocked: Resumed "
2802 + next);
2803 } catch (Exception e) {
2804 // Whoops, need to restart this activity!
2805 if (DEBUG_STATES) Slog.v(TAG_STATES, "Resume failed; resetting state to "
2806 + lastState + ": " + next);
2807 next.setState(lastState, "resumeTopActivityInnerLocked");
Bryce Lee69ad8182017-09-28 10:01:36 -07002808
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08002809 // lastResumedActivity being non-null implies there is a lastStack present.
2810 if (lastResumedActivity != null) {
2811 lastResumedActivity.setState(RESUMED, "resumeTopActivityInnerLocked");
Craig Mautnerf88c50f2013-04-18 19:25:12 -07002812 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08002813
2814 Slog.i(TAG, "Restarting because process died: " + next);
2815 if (!next.hasBeenLaunched) {
2816 next.hasBeenLaunched = true;
2817 } else if (SHOW_APP_STARTING_PREVIEW && lastFocusedStack != null
2818 && lastFocusedStack.isTopStackOnDisplay()) {
2819 next.showStartingWindow(null /* prev */, false /* newTask */,
2820 false /* taskSwitch */);
2821 }
2822 mStackSupervisor.startSpecificActivityLocked(next, true, false);
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08002823 return true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002824 }
2825
2826 // From this point on, if something goes wrong there is no way
2827 // to recover the activity.
2828 try {
Andrii Kulian21713ac2016-10-12 22:05:05 -07002829 next.completeResumeLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002830 } catch (Exception e) {
2831 // If any exception gets thrown, toss away this
2832 // activity and try the next one.
2833 Slog.w(TAG, "Exception thrown during resume of " + next, e);
Andrii Kulian7dd39bb2019-07-22 13:11:10 -07002834 next.finishIfPossible("resume-exception", true /* oomAdj */);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002835 return true;
2836 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002837 } else {
2838 // Whoops, need to restart this activity!
2839 if (!next.hasBeenLaunched) {
2840 next.hasBeenLaunched = true;
2841 } else {
2842 if (SHOW_APP_STARTING_PREVIEW) {
Jorim Jaggi02886a82016-12-06 09:10:06 -08002843 next.showStartingWindow(null /* prev */, false /* newTask */,
2844 false /* taskSwich */);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002845 }
Wale Ogunwaleee006da2015-03-30 14:49:25 -07002846 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "Restarting: " + next);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002847 }
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07002848 if (DEBUG_STATES) Slog.d(TAG_STATES, "resumeTopActivityLocked: Restarting " + next);
George Mount2c92c972014-03-20 09:38:23 -07002849 mStackSupervisor.startSpecificActivityLocked(next, true, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002850 }
2851
2852 return true;
2853 }
2854
Andrii Kulian3ff5a0b2019-05-16 13:18:04 -07002855 /**
2856 * Resume the next eligible activity in a focusable stack when this one does not have any
2857 * running activities left. The focus will be adjusted to the next focusable stack and
2858 * top running activities will be resumed in all focusable stacks. However, if the current stack
2859 * is a home stack - we have to keep it focused, start and resume a home activity on the current
2860 * display instead to make sure that the display is not empty.
2861 */
2862 private boolean resumeNextFocusableActivityWhenStackIsEmpty(ActivityRecord prev,
2863 ActivityOptions options) {
2864 final String reason = "noMoreActivities";
2865
2866 if (!isActivityTypeHome()) {
2867 final ActivityStack nextFocusedStack = adjustFocusToNextFocusableStack(reason);
2868 if (nextFocusedStack != null) {
2869 // Try to move focus to the next visible stack with a running activity if this
2870 // stack is not covering the entire screen or is on a secondary display with no home
2871 // stack.
2872 return mRootActivityContainer.resumeFocusedStacksTopActivities(nextFocusedStack,
2873 prev, null /* targetOptions */);
2874 }
Andrii Kulian7fc22812016-12-28 13:04:11 -08002875 }
2876
Andrii Kulian3ff5a0b2019-05-16 13:18:04 -07002877 // If the current stack is a home stack, or if focus didn't switch to a different stack -
2878 // just start up the Launcher...
Andrii Kulian7fc22812016-12-28 13:04:11 -08002879 ActivityOptions.abort(options);
2880 if (DEBUG_STATES) Slog.d(TAG_STATES,
Andrii Kulian3ff5a0b2019-05-16 13:18:04 -07002881 "resumeNextFocusableActivityWhenStackIsEmpty: " + reason + ", go home");
Louis Chang77551ed2019-04-29 12:42:19 +08002882 return mRootActivityContainer.resumeHomeActivity(prev, reason, mDisplayId);
Andrii Kulian7fc22812016-12-28 13:04:11 -08002883 }
2884
Bryce Leead5b8322018-03-08 14:28:52 -08002885 void startActivityLocked(ActivityRecord r, ActivityRecord focusedTopActivity,
Winson Chungb5c41b72016-12-07 15:00:47 -08002886 boolean newTask, boolean keepCurTransition, ActivityOptions options) {
Louis Changcdec0802019-11-11 11:45:07 +08002887 Task rTask = r.getTask();
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07002888 final int taskId = rTask.mTaskId;
Riddle Hsu609a8e22019-06-27 16:46:29 -06002889 final boolean allowMoveToFront = options == null || !options.getAvoidMoveToFront();
Craig Mautnerbb742462014-07-07 15:28:55 -07002890 // mLaunchTaskBehind tasks get placed at the back of the task stack.
Riddle Hsu609a8e22019-06-27 16:46:29 -06002891 if (!r.mLaunchTaskBehind && allowMoveToFront
2892 && (taskForIdLocked(taskId) == null || newTask)) {
Craig Mautner77878772013-03-04 19:46:24 -08002893 // Last activity in task had been removed or ActivityManagerService is reusing task.
2894 // Insert or replace.
Craig Mautner77878772013-03-04 19:46:24 -08002895 // Might not even be in.
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07002896 positionChildAtTop(rTask);
Craig Mautner77878772013-03-04 19:46:24 -08002897 }
Louis Changcdec0802019-11-11 11:45:07 +08002898 Task task = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002899 if (!newTask) {
2900 // If starting in an existing task, find where that is...
Wale Ogunwale7a8889a2019-11-16 08:23:42 -08002901 boolean isOccluded = false;
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07002902 for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) {
2903 task = getChildAt(taskNdx);
Wale Ogunwale21e06482019-11-18 05:14:15 -08002904 if (task.getTopNonFinishingActivity() == null) {
riddle_hsu9bcc6e82014-07-31 00:26:51 +08002905 // All activities in task are finishing.
2906 continue;
2907 }
Bryce Leeaf691c02017-03-20 14:20:22 -07002908 if (task == rTask) {
Wale Ogunwale7a8889a2019-11-16 08:23:42 -08002909 // Here it is! Now, if this is not yet visible (occluded by another task) to
2910 // the user, then just add it without starting; it will get started when the
2911 // user navigates back to it.
2912 if (isOccluded) {
Craig Mautner70a86932013-02-28 22:37:44 -08002913 if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Adding activity " + r + " to task "
2914 + task, new RuntimeException("here").fillInStackTrace());
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002915 rTask.positionChildAtTop(r);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002916 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002917 return;
2918 }
2919 break;
Wale Ogunwale7a8889a2019-11-16 08:23:42 -08002920 } else if (!isOccluded) {
2921 isOccluded = task.forAllActivities(ActivityRecord::occludesParent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002922 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002923 }
2924 }
2925
Wale Ogunwale26c0dfe2016-12-14 14:42:30 -08002926 // Place a new activity at top of stack, so it is next to interact with the user.
Craig Mautner70a86932013-02-28 22:37:44 -08002927
Wale Ogunwale26c0dfe2016-12-14 14:42:30 -08002928 // If we are not placing the new activity frontmost, we do not want to deliver the
2929 // onUserLeaving callback to the actual frontmost activity
Louis Changcdec0802019-11-11 11:45:07 +08002930 final Task activityTask = r.getTask();
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07002931 if (task == activityTask && mChildren.indexOf(task) != (getChildCount() - 1)) {
Craig Mautnerde4ef022013-04-07 19:01:33 -07002932 mStackSupervisor.mUserLeaving = false;
Wale Ogunwaleee006da2015-03-30 14:49:25 -07002933 if (DEBUG_USER_LEAVING) Slog.v(TAG_USER_LEAVING,
Craig Mautner70a86932013-02-28 22:37:44 -08002934 "startActivity() behind front, mUserLeaving=false");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002935 }
Craig Mautner70a86932013-02-28 22:37:44 -08002936
Bryce Leeaf691c02017-03-20 14:20:22 -07002937 task = activityTask;
Craig Mautner70a86932013-02-28 22:37:44 -08002938
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002939 // Slot the activity into the history stack and proceed
Craig Mautner70a86932013-02-28 22:37:44 -08002940 if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Adding activity " + r + " to stack to task " + task,
Craig Mautner56f52db2013-02-25 10:03:01 -08002941 new RuntimeException("here").fillInStackTrace());
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002942 task.positionChildAtTop(r);
Yunfan Chen1ee84ea2018-11-13 16:03:37 -08002943
Riddle Hsu609a8e22019-06-27 16:46:29 -06002944 // The transition animation and starting window are not needed if {@code allowMoveToFront}
2945 // is false, because the activity won't be visible.
2946 if ((!isHomeOrRecentsStack() || numActivities() > 0) && allowMoveToFront) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08002947 final DisplayContent dc = getDisplay().mDisplayContent;
Wale Ogunwaleee006da2015-03-30 14:49:25 -07002948 if (DEBUG_TRANSITION) Slog.v(TAG_TRANSITION,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002949 "Prepare open transition: starting " + r);
Wale Ogunwaleee006da2015-03-30 14:49:25 -07002950 if ((r.intent.getFlags() & Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08002951 dc.prepareAppTransition(TRANSIT_NONE, keepCurTransition);
Jorim Jaggifa9ed962018-01-25 00:16:49 +01002952 mStackSupervisor.mNoAnimActivities.add(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002953 } else {
Winson Chungb5c41b72016-12-07 15:00:47 -08002954 int transit = TRANSIT_ACTIVITY_OPEN;
2955 if (newTask) {
2956 if (r.mLaunchTaskBehind) {
2957 transit = TRANSIT_TASK_OPEN_BEHIND;
Issei Suzukicac2a502019-04-16 16:52:50 +02002958 } else if (getDisplay().isSingleTaskInstance()) {
2959 transit = TRANSIT_SHOW_SINGLE_TASK_DISPLAY;
Winson Chungb5c41b72016-12-07 15:00:47 -08002960 } else {
Winson Chungc2baac02017-01-11 13:34:47 -08002961 // If a new task is being launched, then mark the existing top activity as
Winson Chung942a85c2017-07-11 15:07:45 -07002962 // supporting picture-in-picture while pausing only if the starting activity
2963 // would not be considered an overlay on top of the current activity
2964 // (eg. not fullscreen, or the assistant)
Winson Chungf7e03e12017-08-22 11:32:16 -07002965 if (canEnterPipOnTaskSwitch(focusedTopActivity,
2966 null /* toFrontTask */, r, options)) {
2967 focusedTopActivity.supportsEnterPipOnTaskSwitch = true;
Winson Chungb5c41b72016-12-07 15:00:47 -08002968 }
2969 transit = TRANSIT_TASK_OPEN;
2970 }
2971 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08002972 dc.prepareAppTransition(transit, keepCurTransition);
Jorim Jaggifa9ed962018-01-25 00:16:49 +01002973 mStackSupervisor.mNoAnimActivities.remove(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002974 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002975 boolean doShow = true;
2976 if (newTask) {
2977 // Even though this activity is starting fresh, we still need
2978 // to reset it to make sure we apply affinities to move any
2979 // existing activities from other tasks in to it.
2980 // If the caller has requested that the target task be
2981 // reset, then do so.
Craig Mautner9d4e9bc2014-06-18 18:34:56 -07002982 if ((r.intent.getFlags() & Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002983 resetTaskIfNeededLocked(r, r);
2984 doShow = topRunningNonDelayedActivityLocked(null) == r;
2985 }
Chong Zhang280d3322015-11-03 17:27:26 -08002986 } else if (options != null && options.getAnimationType()
George Mount70778d72014-07-01 16:33:45 -07002987 == ActivityOptions.ANIM_SCENE_TRANSITION) {
2988 doShow = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002989 }
Craig Mautnerbb742462014-07-07 15:28:55 -07002990 if (r.mLaunchTaskBehind) {
2991 // Don't do a starting window for mLaunchTaskBehind. More importantly make sure we
2992 // tell WindowManager that r is visible even though it is at the back of the stack.
Wale Ogunwale26c0dfe2016-12-14 14:42:30 -08002993 r.setVisibility(true);
Filip Gruszczynskibc5a6c52015-09-22 13:13:24 -07002994 ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
Louis Chang37317152019-05-09 09:53:58 +08002995 // Go ahead to execute app transition for this activity since the app transition
2996 // will not be triggered through the resume channel.
2997 getDisplay().mDisplayContent.executeAppTransition();
Craig Mautnerbb742462014-07-07 15:28:55 -07002998 } else if (SHOW_APP_STARTING_PREVIEW && doShow) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002999 // Figure out if we are transitioning from another activity that is
3000 // "has the same starting icon" as the next one. This allows the
3001 // window manager to keep the previous window it had previously
3002 // created, if it still had one.
Louis Changcdec0802019-11-11 11:45:07 +08003003 Task prevTask = r.getTask();
Bryce Leeaf691c02017-03-20 14:20:22 -07003004 ActivityRecord prev = prevTask.topRunningActivityWithStartingWindowLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003005 if (prev != null) {
3006 // We don't want to reuse the previous starting preview if:
3007 // (1) The current activity is in a different task.
Louis Changcdec0802019-11-11 11:45:07 +08003008 if (prev.getTask() != prevTask) {
Craig Mautner29219d92013-04-16 20:19:12 -07003009 prev = null;
3010 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003011 // (2) The current activity is already displayed.
Craig Mautner29219d92013-04-16 20:19:12 -07003012 else if (prev.nowVisible) {
3013 prev = null;
3014 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003015 }
Jorim Jaggi02886a82016-12-06 09:10:06 -08003016 r.showStartingWindow(prev, newTask, isTaskSwitch(r, focusedTopActivity));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003017 }
3018 } else {
3019 // If this is the first activity, don't do any fancy animations,
3020 // because there is nothing for it to animate on top of.
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003021 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003022 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08003023 }
3024
Winson Chungf7e03e12017-08-22 11:32:16 -07003025 /**
3026 * @return Whether the switch to another task can trigger the currently running activity to
3027 * enter PiP while it is pausing (if supported). Only one of {@param toFrontTask} or
3028 * {@param toFrontActivity} should be set.
3029 */
3030 private boolean canEnterPipOnTaskSwitch(ActivityRecord pipCandidate,
Louis Changcdec0802019-11-11 11:45:07 +08003031 Task toFrontTask, ActivityRecord toFrontActivity, ActivityOptions opts) {
Winson Chungf7e03e12017-08-22 11:32:16 -07003032 if (opts != null && opts.disallowEnterPictureInPictureWhileLaunching()) {
3033 // Ensure the caller has requested not to trigger auto-enter PiP
3034 return false;
3035 }
Wale Ogunwale44f036f2017-09-29 05:09:09 -07003036 if (pipCandidate == null || pipCandidate.inPinnedWindowingMode()) {
Winson Chungf7e03e12017-08-22 11:32:16 -07003037 // Ensure that we do not trigger entering PiP an activity on the pinned stack
3038 return false;
3039 }
Wale Ogunwale68278562017-09-23 17:13:55 -07003040 final ActivityStack targetStack = toFrontTask != null
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003041 ? toFrontTask.getStack() : toFrontActivity.getActivityStack();
Wale Ogunwale68278562017-09-23 17:13:55 -07003042 if (targetStack != null && targetStack.isActivityTypeAssistant()) {
Winson Chungf7e03e12017-08-22 11:32:16 -07003043 // Ensure the task/activity being brought forward is not the assistant
3044 return false;
3045 }
Winson Chungf7e03e12017-08-22 11:32:16 -07003046 return true;
3047 }
3048
Jorim Jaggi02886a82016-12-06 09:10:06 -08003049 private boolean isTaskSwitch(ActivityRecord r,
3050 ActivityRecord topFocusedActivity) {
Louis Changcdec0802019-11-11 11:45:07 +08003051 return topFocusedActivity != null && r.getTask() != topFocusedActivity.getTask();
Jorim Jaggi02886a82016-12-06 09:10:06 -08003052 }
3053
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003054 /**
Andrii Kulian39f27442019-06-26 19:09:19 -07003055 * Helper method for {@link #resetTaskIfNeededLocked(ActivityRecord, ActivityRecord)}.
3056 * Performs a reset of the given task, if needed for new activity start.
Craig Mautnere3a74d52013-02-22 14:14:58 -08003057 * @param task The task containing the Activity (taskTop) that might be reset.
Andrii Kulian39f27442019-06-26 19:09:19 -07003058 * @param forceReset Flag indicating if clear task was requested
Craig Mautnere3a74d52013-02-22 14:14:58 -08003059 * @return An ActivityOptions that needs to be processed.
3060 */
Louis Changcdec0802019-11-11 11:45:07 +08003061 private ActivityOptions resetTargetTaskIfNeededLocked(Task task, boolean forceReset) {
Craig Mautnere3a74d52013-02-22 14:14:58 -08003062 ActivityOptions topOptions = null;
3063
Andrii Kulian39f27442019-06-26 19:09:19 -07003064 // Tracker of the end of currently handled reply chain (sublist) of activities. What happens
3065 // to activities in the same chain will depend on what the end activity of the chain needs.
Craig Mautnere3a74d52013-02-22 14:14:58 -08003066 int replyChainEnd = -1;
3067 boolean canMoveOptions = true;
Louis Chang9d6ba282019-02-20 17:22:10 +08003068 int numTasksCreated = 0;
Craig Mautnere3a74d52013-02-22 14:14:58 -08003069
3070 // We only do this for activities that are not the root of the task (since if we finish
3071 // the root, we may no longer have the task!).
Wale Ogunwale1a06f152019-10-11 11:26:30 +02003072 final int numActivities = task.getChildCount();
Andrii Kulian39f27442019-06-26 19:09:19 -07003073 int lastActivityNdx = task.findRootIndex(true /* effectiveRoot */);
3074 if (lastActivityNdx == -1) {
3075 lastActivityNdx = 0;
3076 }
3077 for (int i = numActivities - 1; i > lastActivityNdx; --i) {
Wale Ogunwale1a06f152019-10-11 11:26:30 +02003078 ActivityRecord target = task.getChildAt(i);
Andrii Kulian39f27442019-06-26 19:09:19 -07003079 // TODO: Why is this needed? Looks like we're breaking the loop before we reach the root
3080 if (target.isRootOfTask()) break;
Craig Mautnere3a74d52013-02-22 14:14:58 -08003081
3082 final int flags = target.info.flags;
3083 final boolean finishOnTaskLaunch =
3084 (flags & ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
3085 final boolean allowTaskReparenting =
3086 (flags & ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
3087 final boolean clearWhenTaskReset =
3088 (target.intent.getFlags() & Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0;
3089
3090 if (!finishOnTaskLaunch
3091 && !clearWhenTaskReset
3092 && target.resultTo != null) {
3093 // If this activity is sending a reply to a previous
3094 // activity, we can't do anything with it now until
3095 // we reach the start of the reply chain.
3096 // XXX note that we are assuming the result is always
3097 // to the previous activity, which is almost always
3098 // the case but we really shouldn't count on.
3099 if (replyChainEnd < 0) {
3100 replyChainEnd = i;
3101 }
3102 } else if (!finishOnTaskLaunch
3103 && !clearWhenTaskReset
3104 && allowTaskReparenting
3105 && target.taskAffinity != null
3106 && !target.taskAffinity.equals(task.affinity)) {
3107 // If this activity has an affinity for another
3108 // task, then we need to move it out of here. We will
3109 // move it as far out of the way as possible, to the
3110 // bottom of the activity stack. This also keeps it
3111 // correctly ordered with any activities we previously
3112 // moved.
Andrii Kulian39f27442019-06-26 19:09:19 -07003113 // TODO: We should probably look for other stacks also, since corresponding task
3114 // with the same affinity is unlikely to be in the same stack.
Louis Changcdec0802019-11-11 11:45:07 +08003115 final Task targetTask;
Craig Mautnerdccb7702013-09-17 15:53:34 -07003116 final ActivityRecord bottom =
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07003117 hasChild() && getChildAt(0).hasChild() ?
3118 getChildAt(0).getChildAt(0) : null;
Louis Changcdec0802019-11-11 11:45:07 +08003119 if (bottom != null && target.taskAffinity.equals(bottom.getTask().affinity)) {
Craig Mautnere3a74d52013-02-22 14:14:58 -08003120 // If the activity currently at the bottom has the
3121 // same task affinity as the one we are moving,
3122 // then merge it into the same task.
Louis Changcdec0802019-11-11 11:45:07 +08003123 targetTask = bottom.getTask();
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003124 if (DEBUG_TASKS) Slog.v(TAG_TASKS, "Start pushing activity " + target
Bryce Leeaf691c02017-03-20 14:20:22 -07003125 + " out to bottom task " + targetTask);
Craig Mautnere3a74d52013-02-22 14:14:58 -08003126 } else {
Louis Changcdec0802019-11-11 11:45:07 +08003127 targetTask = createTask(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003128 mStackSupervisor.getNextTaskIdForUserLocked(target.mUserId),
Andrii Kulian39f27442019-06-26 19:09:19 -07003129 target.info, null /* intent */, null /* voiceSession */,
3130 null /* voiceInteractor */, false /* toTop */);
Craig Mautner329f4122013-11-07 09:10:42 -08003131 targetTask.affinityIntent = target.intent;
Louis Chang9d6ba282019-02-20 17:22:10 +08003132 numTasksCreated++;
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003133 if (DEBUG_TASKS) Slog.v(TAG_TASKS, "Start pushing activity " + target
Bryce Leeaf691c02017-03-20 14:20:22 -07003134 + " out to new task " + targetTask);
Craig Mautnere3a74d52013-02-22 14:14:58 -08003135 }
3136
Craig Mautner525f3d92013-05-07 14:01:50 -07003137 boolean noOptions = canMoveOptions;
Craig Mautnere3a74d52013-02-22 14:14:58 -08003138 final int start = replyChainEnd < 0 ? i : replyChainEnd;
3139 for (int srcPos = start; srcPos >= i; --srcPos) {
Wale Ogunwale1a06f152019-10-11 11:26:30 +02003140 final ActivityRecord p = task.getChildAt(srcPos);
Craig Mautnere3a74d52013-02-22 14:14:58 -08003141 if (p.finishing) {
3142 continue;
3143 }
3144
Craig Mautnere3a74d52013-02-22 14:14:58 -08003145 canMoveOptions = false;
Craig Mautner525f3d92013-05-07 14:01:50 -07003146 if (noOptions && topOptions == null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02003147 topOptions = p.takeOptionsLocked(false /* fromClient */);
Craig Mautnere3a74d52013-02-22 14:14:58 -08003148 if (topOptions != null) {
Craig Mautner525f3d92013-05-07 14:01:50 -07003149 noOptions = false;
Craig Mautnere3a74d52013-02-22 14:14:58 -08003150 }
3151 }
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003152 if (DEBUG_ADD_REMOVE) Slog.i(TAG_ADD_REMOVE,
3153 "Removing activity " + p + " from task=" + task + " adding to task="
3154 + targetTask + " Callers=" + Debug.getCallers(4));
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003155 if (DEBUG_TASKS) Slog.v(TAG_TASKS,
Bryce Leeaf691c02017-03-20 14:20:22 -07003156 "Pushing next activity " + p + " out to target's task " + target);
Wale Ogunwalea0cd15e2017-02-01 15:33:08 -08003157 p.reparent(targetTask, 0 /* position - bottom */, "resetTargetTaskIfNeeded");
Craig Mautnere3a74d52013-02-22 14:14:58 -08003158 }
3159
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07003160 positionChildAtBottom(targetTask);
Louis Chang9d6ba282019-02-20 17:22:10 +08003161 mStackSupervisor.mRecentTasks.add(targetTask);
Craig Mautnere3a74d52013-02-22 14:14:58 -08003162 replyChainEnd = -1;
3163 } else if (forceReset || finishOnTaskLaunch || clearWhenTaskReset) {
3164 // If the activity should just be removed -- either
3165 // because it asks for it, or the task should be
3166 // cleared -- then finish it and anything that is
3167 // part of its reply chain.
3168 int end;
3169 if (clearWhenTaskReset) {
3170 // In this case, we want to finish this activity
3171 // and everything above it, so be sneaky and pretend
3172 // like these are all in the reply chain.
Wale Ogunwale1a06f152019-10-11 11:26:30 +02003173 end = task.getChildCount() - 1;
Craig Mautnere3a74d52013-02-22 14:14:58 -08003174 } else if (replyChainEnd < 0) {
3175 end = i;
3176 } else {
3177 end = replyChainEnd;
3178 }
Craig Mautner525f3d92013-05-07 14:01:50 -07003179 boolean noOptions = canMoveOptions;
Craig Mautnere3a74d52013-02-22 14:14:58 -08003180 for (int srcPos = i; srcPos <= end; srcPos++) {
Wale Ogunwale1a06f152019-10-11 11:26:30 +02003181 ActivityRecord p = task.getChildAt(srcPos);
Craig Mautnere3a74d52013-02-22 14:14:58 -08003182 if (p.finishing) {
3183 continue;
3184 }
3185 canMoveOptions = false;
Craig Mautner525f3d92013-05-07 14:01:50 -07003186 if (noOptions && topOptions == null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02003187 topOptions = p.takeOptionsLocked(false /* fromClient */);
Craig Mautnere3a74d52013-02-22 14:14:58 -08003188 if (topOptions != null) {
Craig Mautner525f3d92013-05-07 14:01:50 -07003189 noOptions = false;
Craig Mautnere3a74d52013-02-22 14:14:58 -08003190 }
3191 }
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003192 if (DEBUG_TASKS) Slog.w(TAG_TASKS,
Craig Mautner58547802013-03-05 08:23:53 -08003193 "resetTaskIntendedTask: calling finishActivity on " + p);
Andrii Kulian7dd39bb2019-07-22 13:11:10 -07003194 if (p.finishIfPossible("reset-task", false /* oomAdj */)
3195 == FINISH_RESULT_REMOVED) {
Craig Mautnere3a74d52013-02-22 14:14:58 -08003196 end--;
3197 srcPos--;
3198 }
3199 }
3200 replyChainEnd = -1;
3201 } else {
3202 // If we were in the middle of a chain, well the
3203 // activity that started it all doesn't want anything
3204 // special, so leave it all as-is.
3205 replyChainEnd = -1;
3206 }
3207 }
3208
Louis Chang9d6ba282019-02-20 17:22:10 +08003209 // Create target stack for the newly created tasks if necessary
3210 if (numTasksCreated > 0) {
3211 ActivityDisplay display = getDisplay();
3212 final boolean singleTaskInstanceDisplay = display.isSingleTaskInstance();
3213 if (singleTaskInstanceDisplay) {
3214 display = mRootActivityContainer.getDefaultDisplay();
3215 }
3216
3217 if (singleTaskInstanceDisplay || display.alwaysCreateStack(getWindowingMode(),
3218 getActivityType())) {
3219 for (int index = numTasksCreated - 1; index >= 0; index--) {
Louis Changcdec0802019-11-11 11:45:07 +08003220 final Task targetTask = getChildAt(index);
Louis Chang9d6ba282019-02-20 17:22:10 +08003221 final ActivityStack targetStack = display.getOrCreateStack(getWindowingMode(),
3222 getActivityType(), false /* onTop */);
3223 targetTask.reparent(targetStack, false /* toTop */,
3224 REPARENT_LEAVE_STACK_IN_PLACE, false /* animate */,
3225 true /* deferResume */, "resetTargetTask");
3226 }
3227 }
3228 }
3229
Craig Mautnere3a74d52013-02-22 14:14:58 -08003230 return topOptions;
3231 }
3232
3233 /**
Andrii Kulian39f27442019-06-26 19:09:19 -07003234 * Helper method for {@link #resetTaskIfNeededLocked(ActivityRecord, ActivityRecord)}.
Louis Changcdec0802019-11-11 11:45:07 +08003235 * Processes all of the activities in a given Task looking for an affinity with the task
Andrii Kulian39f27442019-06-26 19:09:19 -07003236 * of resetTaskIfNeededLocked.taskTop.
Craig Mautnere3a74d52013-02-22 14:14:58 -08003237 * @param affinityTask The task we are looking for an affinity to.
3238 * @param task Task that resetTaskIfNeededLocked.taskTop belongs to.
3239 * @param topTaskIsHigher True if #task has already been processed by resetTaskIfNeededLocked.
Andrii Kulian39f27442019-06-26 19:09:19 -07003240 * @param forceReset Flag indicating if clear task was requested
Craig Mautnere3a74d52013-02-22 14:14:58 -08003241 */
Andrii Kulian39f27442019-06-26 19:09:19 -07003242 // TODO: Consider merging with #resetTargetTaskIfNeededLocked() above
Louis Changcdec0802019-11-11 11:45:07 +08003243 private int resetAffinityTaskIfNeededLocked(Task affinityTask, Task task,
Craig Mautner77878772013-03-04 19:46:24 -08003244 boolean topTaskIsHigher, boolean forceReset, int taskInsertionPoint) {
Andrii Kulian39f27442019-06-26 19:09:19 -07003245 // Tracker of the end of currently handled reply chain (sublist) of activities. What happens
3246 // to activities in the same chain will depend on what the end activity of the chain needs.
Craig Mautnere3a74d52013-02-22 14:14:58 -08003247 int replyChainEnd = -1;
Craig Mautnere3a74d52013-02-22 14:14:58 -08003248 final String taskAffinity = task.affinity;
3249
Wale Ogunwale1a06f152019-10-11 11:26:30 +02003250 final int numActivities = task.getChildCount();
Craig Mautner9d4e9bc2014-06-18 18:34:56 -07003251
3252 // Do not operate on or below the effective root Activity.
Andrii Kulian39f27442019-06-26 19:09:19 -07003253 int lastActivityNdx = affinityTask.findRootIndex(true /* effectiveRoot */);
3254 if (lastActivityNdx == -1) {
3255 lastActivityNdx = 0;
3256 }
3257 for (int i = numActivities - 1; i > lastActivityNdx; --i) {
Wale Ogunwale1a06f152019-10-11 11:26:30 +02003258 ActivityRecord target = task.getChildAt(i);
Andrii Kulian39f27442019-06-26 19:09:19 -07003259 // TODO: Why is this needed? Looks like we're breaking the loop before we reach the root
3260 if (target.isRootOfTask()) break;
Craig Mautnere3a74d52013-02-22 14:14:58 -08003261
3262 final int flags = target.info.flags;
3263 boolean finishOnTaskLaunch = (flags & ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
3264 boolean allowTaskReparenting = (flags & ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
3265
3266 if (target.resultTo != null) {
3267 // If this activity is sending a reply to a previous
3268 // activity, we can't do anything with it now until
3269 // we reach the start of the reply chain.
3270 // XXX note that we are assuming the result is always
3271 // to the previous activity, which is almost always
3272 // the case but we really shouldn't count on.
3273 if (replyChainEnd < 0) {
3274 replyChainEnd = i;
3275 }
3276 } else if (topTaskIsHigher
3277 && allowTaskReparenting
3278 && taskAffinity != null
3279 && taskAffinity.equals(target.taskAffinity)) {
3280 // This activity has an affinity for our task. Either remove it if we are
3281 // clearing or move it over to our task. Note that
3282 // we currently punt on the case where we are resetting a
3283 // task that is not at the top but who has activities above
3284 // with an affinity to it... this is really not a normal
3285 // case, and we will need to later pull that task to the front
3286 // and usually at that point we will do the reset and pick
3287 // up those remaining activities. (This only happens if
3288 // someone starts an activity in a new task from an activity
3289 // in a task that is not currently on top.)
3290 if (forceReset || finishOnTaskLaunch) {
3291 final int start = replyChainEnd >= 0 ? replyChainEnd : i;
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003292 if (DEBUG_TASKS) Slog.v(TAG_TASKS,
3293 "Finishing task at index " + start + " to " + i);
Craig Mautnere3a74d52013-02-22 14:14:58 -08003294 for (int srcPos = start; srcPos >= i; --srcPos) {
Wale Ogunwale1a06f152019-10-11 11:26:30 +02003295 final ActivityRecord p = task.getChildAt(srcPos);
Craig Mautnere3a74d52013-02-22 14:14:58 -08003296 if (p.finishing) {
3297 continue;
3298 }
Andrii Kulian7dd39bb2019-07-22 13:11:10 -07003299 p.finishIfPossible("move-affinity", false /* oomAdj */);
Craig Mautnere3a74d52013-02-22 14:14:58 -08003300 }
3301 } else {
Craig Mautner77878772013-03-04 19:46:24 -08003302 if (taskInsertionPoint < 0) {
Wale Ogunwale1a06f152019-10-11 11:26:30 +02003303 taskInsertionPoint = task.getChildCount();
Craig Mautnerd2328952013-03-05 12:46:26 -08003304
Craig Mautner77878772013-03-04 19:46:24 -08003305 }
Craig Mautner77878772013-03-04 19:46:24 -08003306
3307 final int start = replyChainEnd >= 0 ? replyChainEnd : i;
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003308 if (DEBUG_TASKS) Slog.v(TAG_TASKS,
3309 "Reparenting from task=" + affinityTask + ":" + start + "-" + i
3310 + " to task=" + task + ":" + taskInsertionPoint);
Craig Mautner77878772013-03-04 19:46:24 -08003311 for (int srcPos = start; srcPos >= i; --srcPos) {
Wale Ogunwale1a06f152019-10-11 11:26:30 +02003312 final ActivityRecord p = task.getChildAt(srcPos);
Winson Chung30480042017-01-26 10:55:34 -08003313 p.reparent(task, taskInsertionPoint, "resetAffinityTaskIfNeededLocked");
Craig Mautnere3a74d52013-02-22 14:14:58 -08003314
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003315 if (DEBUG_ADD_REMOVE) Slog.i(TAG_ADD_REMOVE,
3316 "Removing and adding activity " + p + " to stack at " + task
3317 + " callers=" + Debug.getCallers(3));
Wale Ogunwaleee006da2015-03-30 14:49:25 -07003318 if (DEBUG_TASKS) Slog.v(TAG_TASKS, "Pulling activity " + p
3319 + " from " + srcPos + " in to resetting task " + task);
Craig Mautnere3a74d52013-02-22 14:14:58 -08003320 }
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07003321 positionChildAtTop(task);
Craig Mautnere3a74d52013-02-22 14:14:58 -08003322
3323 // Now we've moved it in to place... but what if this is
3324 // a singleTop activity and we have put it on top of another
3325 // instance of the same activity? Then we drop the instance
3326 // below so it remains singleTop.
3327 if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003328 final ArrayList<ActivityRecord> taskActivities = task.mChildren;
Andrii Kuliande93eff2019-07-12 12:21:27 -07003329 final int targetNdx = taskActivities.indexOf(target);
Craig Mautnere3a74d52013-02-22 14:14:58 -08003330 if (targetNdx > 0) {
Andrii Kuliande93eff2019-07-12 12:21:27 -07003331 final ActivityRecord p = taskActivities.get(targetNdx - 1);
Craig Mautnere3a74d52013-02-22 14:14:58 -08003332 if (p.intent.getComponent().equals(target.intent.getComponent())) {
Andrii Kulian7dd39bb2019-07-22 13:11:10 -07003333 p.finishIfPossible("replace", false /* oomAdj */);
Craig Mautnere3a74d52013-02-22 14:14:58 -08003334 }
3335 }
3336 }
3337 }
3338
3339 replyChainEnd = -1;
3340 }
3341 }
Craig Mautner77878772013-03-04 19:46:24 -08003342 return taskInsertionPoint;
Craig Mautnere3a74d52013-02-22 14:14:58 -08003343 }
3344
Louis Changf7f7f9c2019-06-18 16:47:51 +08003345 /**
3346 * Reset the task by reparenting the activities that have same affinity to the task or
3347 * reparenting the activities that have different affinityies out of the task, while these
3348 * activities allow task reparenting.
3349 *
3350 * @param taskTop Top activity of the task might be reset.
3351 * @param newActivity The activity that going to be started.
3352 * @return The non-finishing top activity of the task after reset or the original task top
3353 * activity if all activities within the task are finishing.
3354 */
Craig Mautner8849a5e2013-04-02 16:41:03 -07003355 final ActivityRecord resetTaskIfNeededLocked(ActivityRecord taskTop,
Craig Mautnere3a74d52013-02-22 14:14:58 -08003356 ActivityRecord newActivity) {
Winson Chung5fa39752017-10-04 14:50:15 -07003357 final boolean forceReset =
Craig Mautnere3a74d52013-02-22 14:14:58 -08003358 (newActivity.info.flags & ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0;
Louis Changcdec0802019-11-11 11:45:07 +08003359 final Task task = taskTop.getTask();
Craig Mautnere3a74d52013-02-22 14:14:58 -08003360
Louis Changcdec0802019-11-11 11:45:07 +08003361 // False until we evaluate the Task associated with taskTop. Switches to true
Andrii Kulian39f27442019-06-26 19:09:19 -07003362 // for remaining tasks. Used for later tasks to reparent to task.
Craig Mautnere3a74d52013-02-22 14:14:58 -08003363 boolean taskFound = false;
3364
Andrii Kulian39f27442019-06-26 19:09:19 -07003365 // If ActivityOptions are moved out and need to be aborted or moved to taskTop.
Craig Mautnere3a74d52013-02-22 14:14:58 -08003366 ActivityOptions topOptions = null;
3367
Craig Mautner77878772013-03-04 19:46:24 -08003368 // Preserve the location for reparenting in the new task.
3369 int reparentInsertionPoint = -1;
3370
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07003371 for (int i = getChildCount() - 1; i >= 0; --i) {
Louis Changcdec0802019-11-11 11:45:07 +08003372 final Task targetTask = getChildAt(i);
Craig Mautnere3a74d52013-02-22 14:14:58 -08003373
3374 if (targetTask == task) {
3375 topOptions = resetTargetTaskIfNeededLocked(task, forceReset);
3376 taskFound = true;
3377 } else {
Craig Mautner77878772013-03-04 19:46:24 -08003378 reparentInsertionPoint = resetAffinityTaskIfNeededLocked(targetTask, task,
3379 taskFound, forceReset, reparentInsertionPoint);
Craig Mautnere3a74d52013-02-22 14:14:58 -08003380 }
3381 }
3382
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07003383 int taskNdx = mChildren.indexOf(task);
riddle_hsu1d7919a2015-03-11 17:09:50 +08003384 if (taskNdx >= 0) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08003385 ActivityRecord newTop = getChildAt(taskNdx).getTopNonFinishingActivity();
Louis Changf7f7f9c2019-06-18 16:47:51 +08003386 if (newTop != null) {
3387 taskTop = newTop;
3388 }
riddle_hsu1d7919a2015-03-11 17:09:50 +08003389 }
Craig Mautner70a86932013-02-28 22:37:44 -08003390
Craig Mautnere3a74d52013-02-22 14:14:58 -08003391 if (topOptions != null) {
3392 // If we got some ActivityOptions from an activity on top that
3393 // was removed from the task, propagate them to the new real top.
3394 if (taskTop != null) {
Craig Mautnere3a74d52013-02-22 14:14:58 -08003395 taskTop.updateOptionsLocked(topOptions);
3396 } else {
Craig Mautnere3a74d52013-02-22 14:14:58 -08003397 topOptions.abort();
3398 }
3399 }
3400
3401 return taskTop;
3402 }
3403
Andrii Kulianab132ee2018-07-24 22:10:21 +08003404 /**
3405 * Find next proper focusable stack and make it focused.
3406 * @return The stack that now got the focus, {@code null} if none found.
3407 */
3408 ActivityStack adjustFocusToNextFocusableStack(String reason) {
Wale Ogunwale66e16852017-10-19 13:35:52 -07003409 return adjustFocusToNextFocusableStack(reason, false /* allowFocusSelf */);
Andrii Kulian250d6532017-02-08 23:30:45 -08003410 }
3411
3412 /**
3413 * Find next proper focusable stack and make it focused.
3414 * @param allowFocusSelf Is the focus allowed to remain on the same stack.
Andrii Kulianab132ee2018-07-24 22:10:21 +08003415 * @return The stack that now got the focus, {@code null} if none found.
Andrii Kulian250d6532017-02-08 23:30:45 -08003416 */
Andrii Kulianab132ee2018-07-24 22:10:21 +08003417 private ActivityStack adjustFocusToNextFocusableStack(String reason, boolean allowFocusSelf) {
Wale Ogunwalee1f68ce2018-03-09 08:58:54 -08003418 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003419 mRootActivityContainer.getNextFocusableStack(this, !allowFocusSelf);
Wale Ogunwale4cea0f52015-12-25 06:30:31 -08003420 final String myReason = reason + " adjustFocusToNextFocusableStack";
Wale Ogunwaled697cea2015-02-20 17:19:49 -08003421 if (stack == null) {
Andrii Kulianab132ee2018-07-24 22:10:21 +08003422 return null;
Wale Ogunwaled697cea2015-02-20 17:19:49 -08003423 }
Wale Ogunwaled34e80c2016-03-23 17:08:44 -07003424
Wale Ogunwalec750f5f2016-03-28 07:43:51 -07003425 final ActivityRecord top = stack.topRunningActivityLocked();
3426
Issei Suzuki1669ea42019-11-06 14:20:59 +01003427 if (stack.isActivityTypeHome() && (top == null || !top.mVisibleRequested)) {
Wale Ogunwalec750f5f2016-03-28 07:43:51 -07003428 // If we will be focusing on the home stack next and its current top activity isn't
Wale Ogunwale66e16852017-10-19 13:35:52 -07003429 // visible, then use the move the home stack task to top to make the activity visible.
Louis Changbd48dca2018-08-29 17:44:34 +08003430 stack.getDisplay().moveHomeActivityToTop(reason);
Andrii Kulianab132ee2018-07-24 22:10:21 +08003431 return stack;
Wale Ogunwaled34e80c2016-03-23 17:08:44 -07003432 }
Chong Zhang6cda19c2016-06-14 19:07:56 -07003433
3434 stack.moveToFront(myReason);
wilsonshihfdfd4572019-08-28 21:04:43 +08003435 // Top display focused stack is changed, update top resumed activity if needed.
3436 if (stack.mResumedActivity != null) {
3437 mStackSupervisor.updateTopResumedActivityIfNeeded();
Riddle Hsu1e7ba582019-08-26 19:18:34 +08003438 // Set focused app directly because if the next focused activity is already resumed
3439 // (e.g. the next top activity is on a different display), there won't have activity
3440 // state change to update it.
3441 mService.setResumedActivityUncheckLocked(stack.mResumedActivity, reason);
wilsonshihfdfd4572019-08-28 21:04:43 +08003442 }
Andrii Kulianab132ee2018-07-24 22:10:21 +08003443 return stack;
Wale Ogunwaled697cea2015-02-20 17:19:49 -08003444 }
3445
Andrii Kulian057a6512019-07-15 16:15:51 -07003446 /** Finish all activities that were started for result from the specified activity. */
Craig Mautnerd2328952013-03-05 12:46:26 -08003447 final void finishSubActivityLocked(ActivityRecord self, String resultWho, int requestCode) {
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07003448 for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) {
Louis Changcdec0802019-11-11 11:45:07 +08003449 final Task task = getChildAt(taskNdx);
Wale Ogunwale1a06f152019-10-11 11:26:30 +02003450 for (int activityNdx = task.getChildCount() - 1; activityNdx >= 0; --activityNdx) {
3451 final ActivityRecord r = task.getChildAt(activityNdx);
Craig Mautner9658b312013-02-28 10:55:59 -08003452 if (r.resultTo == self && r.requestCode == requestCode) {
3453 if ((r.resultWho == null && resultWho == null) ||
3454 (r.resultWho != null && r.resultWho.equals(resultWho))) {
Andrii Kulian7dd39bb2019-07-22 13:11:10 -07003455 r.finishIfPossible("request-sub", false /* oomAdj */);
Craig Mautner9658b312013-02-28 10:55:59 -08003456 }
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003457 }
3458 }
3459 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07003460 mService.updateOomAdj();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003461 }
3462
Andrii Kulian8cc92ac62018-04-02 23:14:18 -07003463 /**
3464 * Finish the topmost activity that belongs to the crashed app. We may also finish the activity
3465 * that requested launch of the crashed one to prevent launch-crash loop.
3466 * @param app The app that crashed.
3467 * @param reason Reason to perform this action.
3468 * @return The task that was finished in this stack, {@code null} if top running activity does
3469 * not belong to the crashed app.
3470 */
Louis Changcdec0802019-11-11 11:45:07 +08003471 final Task finishTopCrashedActivityLocked(WindowProcessController app, String reason) {
Filip Gruszczynski3e85ba22015-10-05 22:48:30 -07003472 ActivityRecord r = topRunningActivityLocked();
Louis Changcdec0802019-11-11 11:45:07 +08003473 Task finishedTask = null;
Adrian Roos20d7df32016-01-12 18:59:43 +01003474 if (r == null || r.app != app) {
3475 return null;
3476 }
3477 Slog.w(TAG, " Force finishing activity "
3478 + r.intent.getComponent().flattenToShortString());
Louis Changcdec0802019-11-11 11:45:07 +08003479 finishedTask = r.getTask();
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07003480 int taskNdx = mChildren.indexOf(finishedTask);
Louis Changcdec0802019-11-11 11:45:07 +08003481 final Task task = finishedTask;
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003482 int activityNdx = task.mChildren.indexOf(r);
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003483 getDisplay().mDisplayContent.prepareAppTransition(
lumark588a3e82018-07-20 18:53:54 +08003484 TRANSIT_CRASHING_ACTIVITY_CLOSE, false /* alwaysKeepCurrent */);
Andrii Kulian7dd39bb2019-07-22 13:11:10 -07003485 r.finishIfPossible(reason, false /* oomAdj */);
Bryce Leeaf691c02017-03-20 14:20:22 -07003486 finishedTask = task;
Adrian Roos20d7df32016-01-12 18:59:43 +01003487 // Also terminate any activities below it that aren't yet
3488 // stopped, to avoid a situation where one will get
3489 // re-start our crashing activity once it gets resumed again.
3490 --activityNdx;
3491 if (activityNdx < 0) {
3492 do {
3493 --taskNdx;
3494 if (taskNdx < 0) {
3495 break;
3496 }
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07003497 activityNdx = getChildAt(taskNdx).getChildCount() - 1;
Adrian Roos20d7df32016-01-12 18:59:43 +01003498 } while (activityNdx < 0);
3499 }
3500 if (activityNdx >= 0) {
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07003501 r = getChildAt(taskNdx).getChildAt(activityNdx);
Louis Changeadb22f2019-06-19 12:09:23 +08003502 if (r.isState(STARTED, RESUMED, PAUSING, PAUSED)) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003503 if (!r.isActivityTypeHome() || mService.mHomeProcess != r.app) {
Adrian Roos20d7df32016-01-12 18:59:43 +01003504 Slog.w(TAG, " Force finishing activity "
3505 + r.intent.getComponent().flattenToShortString());
Andrii Kulian7dd39bb2019-07-22 13:11:10 -07003506 r.finishIfPossible(reason, false /* oomAdj */);
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003507 }
3508 }
3509 }
Adrian Roos20d7df32016-01-12 18:59:43 +01003510 return finishedTask;
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003511 }
3512
Dianne Hackborn6ea0d0a2014-07-02 16:23:21 -07003513 final void finishVoiceTask(IVoiceInteractionSession session) {
3514 IBinder sessionBinder = session.asBinder();
3515 boolean didOne = false;
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07003516 for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) {
Louis Changcdec0802019-11-11 11:45:07 +08003517 Task tr = getChildAt(taskNdx);
Dianne Hackborn6ea0d0a2014-07-02 16:23:21 -07003518 if (tr.voiceSession != null && tr.voiceSession.asBinder() == sessionBinder) {
Wale Ogunwale1a06f152019-10-11 11:26:30 +02003519 for (int activityNdx = tr.getChildCount() - 1; activityNdx >= 0; --activityNdx) {
3520 ActivityRecord r = tr.getChildAt(activityNdx);
Dianne Hackborn6ea0d0a2014-07-02 16:23:21 -07003521 if (!r.finishing) {
Andrii Kulian7dd39bb2019-07-22 13:11:10 -07003522 r.finishIfPossible("finish-voice", false /* oomAdj */);
Dianne Hackborn6ea0d0a2014-07-02 16:23:21 -07003523 didOne = true;
3524 }
3525 }
Amith Yamasani0af6fa72016-01-17 15:36:19 -08003526 } else {
3527 // Check if any of the activities are using voice
Wale Ogunwale1a06f152019-10-11 11:26:30 +02003528 for (int activityNdx = tr.getChildCount() - 1; activityNdx >= 0; --activityNdx) {
3529 ActivityRecord r = tr.getChildAt(activityNdx);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003530 if (r.voiceSession != null && r.voiceSession.asBinder() == sessionBinder) {
Amith Yamasani0af6fa72016-01-17 15:36:19 -08003531 // Inform of cancellation
3532 r.clearVoiceSessionLocked();
3533 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003534 r.app.getThread().scheduleLocalVoiceInteractionStarted(
3535 r.appToken, null);
Amith Yamasani0af6fa72016-01-17 15:36:19 -08003536 } catch (RemoteException re) {
3537 // Ok
3538 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07003539 mService.finishRunningVoiceLocked();
Amith Yamasani0af6fa72016-01-17 15:36:19 -08003540 break;
3541 }
3542 }
Dianne Hackborn6ea0d0a2014-07-02 16:23:21 -07003543 }
3544 }
Amith Yamasani0af6fa72016-01-17 15:36:19 -08003545
Dianne Hackborn6ea0d0a2014-07-02 16:23:21 -07003546 if (didOne) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07003547 mService.updateOomAdj();
Dianne Hackborn6ea0d0a2014-07-02 16:23:21 -07003548 }
3549 }
3550
Andrii Kuliande93eff2019-07-12 12:21:27 -07003551 /** Finish all activities in the stack without waiting. */
3552 void finishAllActivitiesImmediately() {
Craig Mautneree36c772014-07-16 14:56:05 -07003553 boolean noActivitiesInStack = true;
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07003554 for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) {
Louis Changcdec0802019-11-11 11:45:07 +08003555 final Task task = getChildAt(taskNdx);
Wale Ogunwale1a06f152019-10-11 11:26:30 +02003556 for (int activityNdx = task.getChildCount() - 1; activityNdx >= 0; --activityNdx) {
3557 final ActivityRecord r = task.getChildAt(activityNdx);
Craig Mautneree36c772014-07-16 14:56:05 -07003558 noActivitiesInStack = false;
Andrii Kuliande93eff2019-07-12 12:21:27 -07003559 Slog.d(TAG, "finishAllActivitiesImmediatelyLocked: finishing " + r);
Andrii Kulian7dd39bb2019-07-22 13:11:10 -07003560 r.destroyIfPossible("finishAllActivitiesImmediatelyLocked");
Craig Mautnerf4c909b2014-04-17 18:39:38 -07003561 }
3562 }
Craig Mautneree36c772014-07-16 14:56:05 -07003563 if (noActivitiesInStack) {
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07003564 removeIfPossible();
Craig Mautneree36c772014-07-16 14:56:05 -07003565 }
Craig Mautnerf4c909b2014-04-17 18:39:38 -07003566 }
3567
Wale Ogunwale66e16852017-10-19 13:35:52 -07003568 /** @return true if the stack behind this one is a standard activity type. */
3569 boolean inFrontOfStandardStack() {
3570 final ActivityDisplay display = getDisplay();
3571 if (display == null) {
3572 return false;
3573 }
3574 final int index = display.getIndexOf(this);
3575 if (index == 0) {
3576 return false;
3577 }
3578 final ActivityStack stackBehind = display.getChildAt(index - 1);
3579 return stackBehind.isActivityTypeStandard();
3580 }
3581
3582 boolean shouldUpRecreateTaskLocked(ActivityRecord srec, String destAffinity) {
Dianne Hackborn6f4d61f2014-08-21 17:50:42 -07003583 // Basic case: for simple app-centric recents, we need to recreate
3584 // the task if the affinity has changed.
Louis Changcdec0802019-11-11 11:45:07 +08003585 if (srec == null || srec.getTask().affinity == null
3586 || !srec.getTask().affinity.equals(destAffinity)) {
Dianne Hackborn6f4d61f2014-08-21 17:50:42 -07003587 return true;
3588 }
3589 // Document-centric case: an app may be split in to multiple documents;
3590 // they need to re-create their task if this current activity is the root
3591 // of a document, unless simply finishing it will return them to the the
3592 // correct app behind.
Louis Changcdec0802019-11-11 11:45:07 +08003593 final Task task = srec.getTask();
Andrii Kulian39f27442019-06-26 19:09:19 -07003594 if (srec.isRootOfTask() && task.getBaseIntent() != null
3595 && task.getBaseIntent().isDocument()) {
Dianne Hackborn6f4d61f2014-08-21 17:50:42 -07003596 // Okay, this activity is at the root of its task. What to do, what to do...
Wale Ogunwale66e16852017-10-19 13:35:52 -07003597 if (!inFrontOfStandardStack()) {
Dianne Hackborn6f4d61f2014-08-21 17:50:42 -07003598 // Finishing won't return to an application, so we need to recreate.
3599 return true;
3600 }
3601 // We now need to get the task below it to determine what to do.
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07003602 int taskIdx = mChildren.indexOf(task);
Dianne Hackborn6f4d61f2014-08-21 17:50:42 -07003603 if (taskIdx <= 0) {
3604 Slog.w(TAG, "shouldUpRecreateTask: task not in history for " + srec);
3605 return false;
3606 }
Louis Changcdec0802019-11-11 11:45:07 +08003607 final Task prevTask = getChildAt(taskIdx);
Bryce Leeaf691c02017-03-20 14:20:22 -07003608 if (!task.affinity.equals(prevTask.affinity)) {
Dianne Hackborn6f4d61f2014-08-21 17:50:42 -07003609 // These are different apps, so need to recreate.
3610 return true;
3611 }
3612 }
3613 return false;
3614 }
3615
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00003616 final boolean navigateUpToLocked(ActivityRecord srec, Intent destIntent, int resultCode,
3617 Intent resultData) {
Louis Changcdec0802019-11-11 11:45:07 +08003618 final Task task = srec.getTask();
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003619 final ArrayList<ActivityRecord> activities = task.mChildren;
Craig Mautner0247fc82013-02-28 14:32:06 -08003620 final int start = activities.indexOf(srec);
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07003621 if (!mChildren.contains(task) || (start < 0)) {
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003622 return false;
3623 }
3624 int finishTo = start - 1;
Wale Ogunwale1a06f152019-10-11 11:26:30 +02003625 ActivityRecord parent = finishTo < 0 ? null : task.getChildAt(finishTo);
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003626 boolean foundParentInTask = false;
Craig Mautner0247fc82013-02-28 14:32:06 -08003627 final ComponentName dest = destIntent.getComponent();
3628 if (start > 0 && dest != null) {
3629 for (int i = finishTo; i >= 0; i--) {
Wale Ogunwale1a06f152019-10-11 11:26:30 +02003630 ActivityRecord r = task.getChildAt(i);
Craig Mautner0247fc82013-02-28 14:32:06 -08003631 if (r.info.packageName.equals(dest.getPackageName()) &&
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003632 r.info.name.equals(dest.getClassName())) {
3633 finishTo = i;
3634 parent = r;
3635 foundParentInTask = true;
3636 break;
3637 }
3638 }
3639 }
3640
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003641 // TODO: There is a dup. of this block of code in ActivityTaskManagerService.finishActivity
3642 // We should consolidate.
3643 IActivityController controller = mService.mController;
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003644 if (controller != null) {
3645 ActivityRecord next = topRunningActivityLocked(srec.appToken, 0);
3646 if (next != null) {
3647 // ask watcher if this is allowed
3648 boolean resumeOK = true;
3649 try {
3650 resumeOK = controller.activityResuming(next.packageName);
3651 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003652 mService.mController = null;
Kenny Rootadd58212013-05-07 09:47:34 -07003653 Watchdog.getInstance().setActivityController(null);
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003654 }
3655
3656 if (!resumeOK) {
3657 return false;
3658 }
3659 }
3660 }
3661 final long origId = Binder.clearCallingIdentity();
3662 for (int i = start; i > finishTo; i--) {
Andrii Kulian057a6512019-07-15 16:15:51 -07003663 final ActivityRecord r = activities.get(i);
Louis Chang7b03ad92019-08-21 12:32:33 +08003664 r.finishIfPossible(resultCode, resultData, "navigate-up", true /* oomAdj */);
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003665 // Only return the supplied result for the first activity finished
3666 resultCode = Activity.RESULT_CANCELED;
3667 resultData = null;
3668 }
3669
3670 if (parent != null && foundParentInTask) {
3671 final int parentLaunchMode = parent.info.launchMode;
3672 final int destIntentFlags = destIntent.getFlags();
3673 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
3674 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
3675 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
3676 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
Dianne Hackborn85d558c2014-11-04 10:31:54 -08003677 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00003678 srec.packageName);
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003679 } else {
3680 try {
3681 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
Philip P. Moltmanncff8f0f2018-03-27 12:51:51 -07003682 destIntent.getComponent(), ActivityManagerService.STOCK_PM_FLAGS,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003683 srec.mUserId);
Bryce Lee4c9a5972017-12-01 22:14:24 -08003684 // TODO(b/64750076): Check if calling pid should really be -1.
3685 final int res = mService.getActivityStartController()
3686 .obtainStarter(destIntent, "navigateUpTo")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003687 .setCaller(srec.app.getThread())
Bryce Lee4c9a5972017-12-01 22:14:24 -08003688 .setActivityInfo(aInfo)
3689 .setResultTo(parent.appToken)
3690 .setCallingPid(-1)
3691 .setCallingUid(parent.launchedFromUid)
3692 .setCallingPackage(parent.launchedFromPackage)
3693 .setRealCallingPid(-1)
3694 .setRealCallingUid(parent.launchedFromUid)
3695 .setComponentSpecified(true)
3696 .execute();
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003697 foundParentInTask = res == ActivityManager.START_SUCCESS;
3698 } catch (RemoteException e) {
3699 foundParentInTask = false;
3700 }
Louis Chang7b03ad92019-08-21 12:32:33 +08003701 parent.finishIfPossible(resultCode, resultData, "navigate-top", true /* oomAdj */);
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003702 }
3703 }
3704 Binder.restoreCallingIdentity(origId);
3705 return foundParentInTask;
3706 }
Bryce Leeaf691c02017-03-20 14:20:22 -07003707
3708 /**
3709 * Remove any state associated with the {@link ActivityRecord}. This should be called whenever
3710 * an activity moves away from the stack.
3711 */
3712 void onActivityRemovedFromStack(ActivityRecord r) {
Andrii Kulian79d67982019-08-19 11:56:16 -07003713 removeTimeoutsForActivity(r);
Bryce Lee84730a02018-04-03 14:10:04 -07003714
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07003715 mExitingActivities.remove(r);
Riddle Hsu5477b572019-11-12 16:07:29 +08003716 mLruActivities.remove(r);
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003717
Bryce Lee84730a02018-04-03 14:10:04 -07003718 if (mResumedActivity != null && mResumedActivity == r) {
3719 setResumedActivity(null, "onActivityRemovedFromStack");
Bryce Leeaf691c02017-03-20 14:20:22 -07003720 }
Bryce Lee84730a02018-04-03 14:10:04 -07003721 if (mPausingActivity != null && mPausingActivity == r) {
Bryce Leeaf691c02017-03-20 14:20:22 -07003722 mPausingActivity = null;
3723 }
Bryce Lee84730a02018-04-03 14:10:04 -07003724 }
Bryce Leeaf691c02017-03-20 14:20:22 -07003725
Bryce Lee84730a02018-04-03 14:10:04 -07003726 void onActivityAddedToStack(ActivityRecord r) {
Riddle Hsu5477b572019-11-12 16:07:29 +08003727 if (r.isState(RESUMED)) {
Bryce Lee84730a02018-04-03 14:10:04 -07003728 setResumedActivity(r, "onActivityAddedToStack");
3729 }
Riddle Hsu5477b572019-11-12 16:07:29 +08003730 if (r.hasProcess()) {
3731 updateLruList(r);
3732 }
Bryce Leeaf691c02017-03-20 14:20:22 -07003733 }
3734
Andrii Kulian79d67982019-08-19 11:56:16 -07003735 /// HANDLER INTERFACE BEGIN
3736 void removeTimeoutsForActivity(ActivityRecord r) {
Craig Mautnerf3333272013-04-22 10:55:53 -07003737 mStackSupervisor.removeTimeoutsForActivityLocked(r);
Andrii Kulian79d67982019-08-19 11:56:16 -07003738 removePauseTimeoutForActivity(r);
3739 removeStopTimeoutForActivity(r);
3740 removeDestroyTimeoutForActivity(r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003741 r.finishLaunchTickingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003742 }
3743
Andrii Kulian79d67982019-08-19 11:56:16 -07003744 void scheduleDestroyActivities(WindowProcessController owner, String reason) {
3745 final Message msg = mHandler.obtainMessage(DESTROY_ACTIVITIES_MSG);
Craig Mautneree2e45a2014-06-27 12:10:03 -07003746 msg.obj = new ScheduleDestroyArgs(owner, reason);
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07003747 mHandler.sendMessage(msg);
3748 }
3749
Andrii Kulian79d67982019-08-19 11:56:16 -07003750 void scheduleDestroyTimeoutForActivity(ActivityRecord r) {
3751 final Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG, r);
3752 mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT);
3753 }
3754
3755 void removeDestroyTimeoutForActivity(ActivityRecord r) {
3756 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
3757 }
3758
3759 void scheduleStopTimeoutForActivity(ActivityRecord r) {
3760 final Message msg = mHandler.obtainMessage(STOP_TIMEOUT_MSG, r);
3761 mHandler.sendMessageDelayed(msg, STOP_TIMEOUT);
3762 }
3763
3764 void removeStopTimeoutForActivity(ActivityRecord r) {
3765 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
3766 }
3767
3768 /**
3769 * Schedule a pause timeout in case the app doesn't respond. We don't give it much time because
3770 * this directly impacts the responsiveness seen by the user.
3771 */
3772 private void schedulePauseTimeoutForActivity(ActivityRecord r) {
3773 final Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG, r);
3774 r.pauseTime = SystemClock.uptimeMillis();
3775 mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT);
3776 if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Waiting for pause to complete...");
3777 }
3778
3779 void removePauseTimeoutForActivity(ActivityRecord r) {
3780 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
3781 }
3782
3783 void scheduleLaunchTickForActivity(ActivityRecord r) {
3784 final Message msg = mHandler.obtainMessage(LAUNCH_TICK_MSG, r);
3785 mHandler.sendMessageDelayed(msg, LAUNCH_TICK);
3786 }
3787
3788 void removeLaunchTickMessages() {
3789 mHandler.removeMessages(LAUNCH_TICK_MSG);
3790 }
3791 /// HANDLER INTERFACE END
3792
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003793 private void destroyActivitiesLocked(WindowProcessController owner, String reason) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07003794 boolean lastIsOpaque = false;
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003795 boolean activityRemoved = false;
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07003796 for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) {
Louis Changcdec0802019-11-11 11:45:07 +08003797 final Task task = getChildAt(taskNdx);
Wale Ogunwale1a06f152019-10-11 11:26:30 +02003798 for (int activityNdx = task.getChildCount() - 1; activityNdx >= 0; --activityNdx) {
3799 final ActivityRecord r = task.getChildAt(activityNdx);
Craig Mautnerd44711d2013-02-23 11:24:36 -08003800 if (r.finishing) {
3801 continue;
3802 }
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08003803 if (r.occludesParent()) {
Craig Mautnerd44711d2013-02-23 11:24:36 -08003804 lastIsOpaque = true;
3805 }
3806 if (owner != null && r.app != owner) {
3807 continue;
3808 }
3809 if (!lastIsOpaque) {
3810 continue;
3811 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003812 if (r.isDestroyable()) {
Bryce Lee7ace3952018-02-16 14:34:32 -08003813 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "Destroying " + r
3814 + " in state " + r.getState()
Craig Mautnerd44711d2013-02-23 11:24:36 -08003815 + " resumed=" + mResumedActivity
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003816 + " pausing=" + mPausingActivity + " for reason " + reason);
Andrii Kulian79d67982019-08-19 11:56:16 -07003817 if (r.destroyImmediately(true /* removeFromTask */, reason)) {
Craig Mautnerd44711d2013-02-23 11:24:36 -08003818 activityRemoved = true;
3819 }
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003820 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003821 }
3822 }
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003823 if (activityRemoved) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003824 mRootActivityContainer.resumeFocusedStacksTopActivities();
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003825 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003826 }
3827
Louis Changcdec0802019-11-11 11:45:07 +08003828 final int releaseSomeActivitiesLocked(WindowProcessController app, ArraySet<Task> tasks,
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003829 String reason) {
3830 // Iterate over tasks starting at the back (oldest) first.
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003831 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Trying to release some activities in " + app);
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003832 int maxTasks = tasks.size() / 4;
3833 if (maxTasks < 1) {
3834 maxTasks = 1;
3835 }
3836 int numReleased = 0;
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07003837 for (int taskNdx = 0; taskNdx < getChildCount() && maxTasks > 0; taskNdx++) {
Louis Changcdec0802019-11-11 11:45:07 +08003838 final Task task = getChildAt(taskNdx);
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003839 if (!tasks.contains(task)) {
3840 continue;
3841 }
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003842 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Looking for activities to release in " + task);
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003843 int curNum = 0;
Wale Ogunwale1a06f152019-10-11 11:26:30 +02003844 for (int actNdx = 0; actNdx < task.getChildCount(); actNdx++) {
3845 final ActivityRecord activity = task.getChildAt(actNdx);
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003846 if (activity.app == app && activity.isDestroyable()) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003847 if (DEBUG_RELEASE) Slog.v(TAG_RELEASE, "Destroying " + activity
Bryce Lee7ace3952018-02-16 14:34:32 -08003848 + " in state " + activity.getState() + " resumed=" + mResumedActivity
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003849 + " pausing=" + mPausingActivity + " for reason " + reason);
Andrii Kulian79d67982019-08-19 11:56:16 -07003850 activity.destroyImmediately(true /* removeFromApp */, reason);
Wale Ogunwale1a06f152019-10-11 11:26:30 +02003851 if (task.getChildAt(actNdx) != activity) {
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003852 // Was removed from list, back up so we don't miss the next one.
3853 actNdx--;
3854 }
3855 curNum++;
3856 }
3857 }
3858 if (curNum > 0) {
3859 numReleased += curNum;
3860 maxTasks--;
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07003861 if (getChildAt(taskNdx) != task) {
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003862 // The entire task got removed, back up so we don't miss the next one.
3863 taskNdx--;
3864 }
3865 }
3866 }
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003867 if (DEBUG_RELEASE) Slog.d(TAG_RELEASE,
3868 "Done releasing: did " + numReleased + " activities");
Dianne Hackborn89ad4562014-08-24 16:45:38 -07003869 return numReleased;
3870 }
3871
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003872 private void removeHistoryRecordsForAppLocked(ArrayList<ActivityRecord> list,
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003873 WindowProcessController app, String listName) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003874 int i = list.size();
Wale Ogunwalee23149f2015-03-06 15:39:44 -08003875 if (DEBUG_CLEANUP) Slog.v(TAG_CLEANUP,
3876 "Removing app " + app + " from list " + listName + " with " + i + " entries");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003877 while (i > 0) {
3878 i--;
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003879 ActivityRecord r = list.get(i);
Wale Ogunwalee23149f2015-03-06 15:39:44 -08003880 if (DEBUG_CLEANUP) Slog.v(TAG_CLEANUP, "Record #" + i + " " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003881 if (r.app == app) {
Wale Ogunwalee23149f2015-03-06 15:39:44 -08003882 if (DEBUG_CLEANUP) Slog.v(TAG_CLEANUP, "---> REMOVING this entry!");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003883 list.remove(i);
Andrii Kulian79d67982019-08-19 11:56:16 -07003884 removeTimeoutsForActivity(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003885 }
3886 }
3887 }
3888
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003889 private boolean removeHistoryRecordsForAppLocked(WindowProcessController app) {
Riddle Hsu5477b572019-11-12 16:07:29 +08003890 removeHistoryRecordsForAppLocked(mLruActivities, app, "mLruActivities");
Craig Mautnerde4ef022013-04-07 19:01:33 -07003891 removeHistoryRecordsForAppLocked(mStackSupervisor.mStoppingActivities, app,
3892 "mStoppingActivities");
Craig Mautner0eea92c2013-05-16 13:35:39 -07003893 removeHistoryRecordsForAppLocked(mStackSupervisor.mGoingToSleepActivities, app,
3894 "mGoingToSleepActivities");
Craig Mautnerf3333272013-04-22 10:55:53 -07003895 removeHistoryRecordsForAppLocked(mStackSupervisor.mFinishingActivities, app,
3896 "mFinishingActivities");
Dianne Hackborncc5a0552012-10-01 16:32:39 -07003897
Riddle Hsuaaef7312019-01-24 19:00:58 +08003898 final boolean isProcessRemoved = app.isRemoved();
3899 if (isProcessRemoved) {
3900 // The package of the died process should be force-stopped, so make its activities as
3901 // finishing to prevent the process from being started again if the next top (or being
3902 // visible) activity also resides in the same process.
3903 app.makeFinishingForProcessRemoved();
3904 }
3905
Dianne Hackborncc5a0552012-10-01 16:32:39 -07003906 boolean hasVisibleActivities = false;
3907
3908 // Clean out the history list.
Craig Mautner0247fc82013-02-28 14:32:06 -08003909 int i = numActivities();
Wale Ogunwalee23149f2015-03-06 15:39:44 -08003910 if (DEBUG_CLEANUP) Slog.v(TAG_CLEANUP,
3911 "Removing app " + app + " from history with " + i + " entries");
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07003912 for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) {
3913 final ArrayList<ActivityRecord> activities = getChildAt(taskNdx).mChildren;
Bryce Leefbd263b42018-03-07 10:33:55 -08003914 mTmpActivities.clear();
3915 mTmpActivities.addAll(activities);
3916
3917 while (!mTmpActivities.isEmpty()) {
3918 final int targetIndex = mTmpActivities.size() - 1;
3919 final ActivityRecord r = mTmpActivities.remove(targetIndex);
Wale Ogunwalee23149f2015-03-06 15:39:44 -08003920 if (DEBUG_CLEANUP) Slog.v(TAG_CLEANUP,
Bryce Leefbd263b42018-03-07 10:33:55 -08003921 "Record #" + targetIndex + " " + r + ": app=" + r.app);
3922
Craig Mautner0247fc82013-02-28 14:32:06 -08003923 if (r.app == app) {
Issei Suzuki1669ea42019-11-06 14:20:59 +01003924 if (r.isVisible() || r.mVisibleRequested) {
3925 // While an activity launches a new activity, it's possible that the old
3926 // activity is already requested to be hidden (mVisibleRequested=false), but
3927 // this visibility is not yet committed, so isVisible()=true.
riddle_hsu558e8492015-04-02 16:43:13 +08003928 hasVisibleActivities = true;
3929 }
Craig Mautneracebdc82015-02-24 10:53:03 -08003930 final boolean remove;
Garfield Tan2746ab52018-07-25 12:33:01 -07003931 if ((r.mRelaunchReason == RELAUNCH_REASON_WINDOWING_MODE_RESIZE
3932 || r.mRelaunchReason == RELAUNCH_REASON_FREE_RESIZE)
3933 && r.launchCount < 3 && !r.finishing) {
3934 // If the process crashed during a resize, always try to relaunch it, unless
3935 // it has failed more than twice. Skip activities that's already finishing
3936 // cleanly by itself.
3937 remove = false;
Andrii Kulian06b8dcb2019-07-10 21:09:38 -07003938 } else if ((!r.hasSavedState() && !r.stateNotNeeded
Riddle Hsu7b766fd2019-01-28 21:14:59 +08003939 && !r.isState(ActivityState.RESTARTING_PROCESS)) || r.finishing) {
Craig Mautner0247fc82013-02-28 14:32:06 -08003940 // Don't currently have state for the activity, or
3941 // it is finishing -- always remove it.
3942 remove = true;
Issei Suzuki1669ea42019-11-06 14:20:59 +01003943 } else if (!r.mVisibleRequested && r.launchCount > 2
3944 && r.lastLaunchTime > (SystemClock.uptimeMillis() - 60000)) {
Craig Mautner0247fc82013-02-28 14:32:06 -08003945 // We have launched this activity too many times since it was
3946 // able to run, so give up and remove it.
Chong Zhang112eb8c2015-11-02 11:17:00 -08003947 // (Note if the activity is visible, we don't remove the record.
3948 // We leave the dead window on the screen but the process will
3949 // not be restarted unless user explicitly tap on it.)
Craig Mautner0247fc82013-02-28 14:32:06 -08003950 remove = true;
3951 } else {
3952 // The process may be gone, but the activity lives on!
3953 remove = false;
Dianne Hackborncc5a0552012-10-01 16:32:39 -07003954 }
Craig Mautner0247fc82013-02-28 14:32:06 -08003955 if (remove) {
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003956 if (DEBUG_ADD_REMOVE || DEBUG_CLEANUP) Slog.i(TAG_ADD_REMOVE,
3957 "Removing activity " + r + " from stack at " + i
Andrii Kulian06b8dcb2019-07-10 21:09:38 -07003958 + ": hasSavedState=" + r.hasSavedState()
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003959 + " stateNotNeeded=" + r.stateNotNeeded
3960 + " finishing=" + r.finishing
Bryce Lee7ace3952018-02-16 14:34:32 -08003961 + " state=" + r.getState() + " callers=" + Debug.getCallers(5));
Riddle Hsuaaef7312019-01-24 19:00:58 +08003962 if (!r.finishing || isProcessRemoved) {
Craig Mautner0247fc82013-02-28 14:32:06 -08003963 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
3964 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003965 r.mUserId, System.identityHashCode(r),
Louis Changcdec0802019-11-11 11:45:07 +08003966 r.getTask().mTaskId, r.shortComponentName,
Craig Mautner0247fc82013-02-28 14:32:06 -08003967 "proc died without state saved");
3968 }
Craig Mautner0247fc82013-02-28 14:32:06 -08003969 } else {
3970 // We have the current state for this activity, so
3971 // it can be restarted later when needed.
Wale Ogunwale0fc365c2015-05-25 19:35:42 -07003972 if (DEBUG_ALL) Slog.v(TAG, "Keeping entry, setting app to null");
3973 if (DEBUG_APP) Slog.v(TAG_APP,
3974 "Clearing app during removeHistory for activity " + r);
Craig Mautner0247fc82013-02-28 14:32:06 -08003975 r.app = null;
Chong Zhang112eb8c2015-11-02 11:17:00 -08003976 // Set nowVisible to previous visible state. If the app was visible while
3977 // it died, we leave the dead window on screen so it's basically visible.
3978 // This is needed when user later tap on the dead window, we need to stop
3979 // other apps when user transfers focus to the restarted activity.
Issei Suzuki1669ea42019-11-06 14:20:59 +01003980 r.nowVisible = r.mVisibleRequested;
Dianne Hackborncc5a0552012-10-01 16:32:39 -07003981 }
Andrii Kulian79d67982019-08-19 11:56:16 -07003982 r.cleanUp(true /* cleanServices */, true /* setState */);
Craig Mautneracebdc82015-02-24 10:53:03 -08003983 if (remove) {
Andrii Kulian79d67982019-08-19 11:56:16 -07003984 r.removeFromHistory("appDied");
Craig Mautneracebdc82015-02-24 10:53:03 -08003985 }
Craig Mautner0247fc82013-02-28 14:32:06 -08003986 }
Dianne Hackborncc5a0552012-10-01 16:32:39 -07003987 }
3988 }
3989
3990 return hasVisibleActivities;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003991 }
Craig Mautner0247fc82013-02-28 14:32:06 -08003992
chaviw0d562bf2018-03-15 14:24:14 -07003993 private void updateTransitLocked(int transit, ActivityOptions options) {
Dianne Hackborn7f58b952012-04-18 12:59:29 -07003994 if (options != null) {
chaviw0d562bf2018-03-15 14:24:14 -07003995 ActivityRecord r = topRunningActivityLocked();
3996 if (r != null && !r.isState(RESUMED)) {
3997 r.updateOptionsLocked(options);
Dianne Hackborn7f58b952012-04-18 12:59:29 -07003998 } else {
3999 ActivityOptions.abort(options);
4000 }
4001 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08004002 getDisplay().mDisplayContent.prepareAppTransition(transit, false);
Dianne Hackborn7f58b952012-04-18 12:59:29 -07004003 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004004
Louis Changcdec0802019-11-11 11:45:07 +08004005 final void moveTaskToFrontLocked(Task tr, boolean noAnimation, ActivityOptions options,
chaviw0d562bf2018-03-15 14:24:14 -07004006 AppTimeTracker timeTracker, String reason) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -07004007 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "moveTaskToFront: " + tr);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004008
Wale Ogunwalea0f5b5e2017-10-11 09:37:23 -07004009 final ActivityStack topStack = getDisplay().getTopStack();
Wale Ogunwale21e06482019-11-18 05:14:15 -08004010 final ActivityRecord topActivity = topStack != null
4011 ? topStack.getTopNonFinishingActivity() : null;
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07004012 final int numTasks = getChildCount();
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004013 final int index = mChildren.indexOf(tr);
Craig Mautner86d67a42013-05-14 10:34:38 -07004014 if (numTasks == 0 || index < 0) {
Craig Mautner11bf9a52013-02-19 14:08:51 -08004015 // nothing to do!
Craig Mautner8f5f7e92015-01-26 18:03:13 -08004016 if (noAnimation) {
Craig Mautner11bf9a52013-02-19 14:08:51 -08004017 ActivityOptions.abort(options);
4018 } else {
chaviw0d562bf2018-03-15 14:24:14 -07004019 updateTransitLocked(TRANSIT_TASK_TO_FRONT, options);
Craig Mautner11bf9a52013-02-19 14:08:51 -08004020 }
4021 return;
4022 }
4023
Dianne Hackbornb5a380d2015-05-20 18:18:46 -07004024 if (timeTracker != null) {
4025 // The caller wants a time tracker associated with this task.
Wale Ogunwale1a06f152019-10-11 11:26:30 +02004026 for (int i = tr.getChildCount() - 1; i >= 0; i--) {
4027 tr.getChildAt(i).appTimeTracker = timeTracker;
Dianne Hackbornb5a380d2015-05-20 18:18:46 -07004028 }
4029 }
4030
Chavi Weingarten3a748552018-05-14 17:32:42 +00004031 try {
4032 // Defer updating the IME target since the new IME target will try to get computed
4033 // before updating all closing and opening apps, which can cause the ime target to
4034 // get calculated incorrectly.
4035 getDisplay().deferUpdateImeTarget();
Wale Ogunwaled80c2632015-03-13 10:26:26 -07004036
Chavi Weingarten3a748552018-05-14 17:32:42 +00004037 // Shift all activities with this task up to the top
4038 // of the stack, keeping them in the same internal order.
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004039 positionChildAtTop(tr);
Chavi Weingarten3a748552018-05-14 17:32:42 +00004040
4041 // Don't refocus if invisible to current user
Wale Ogunwale21e06482019-11-18 05:14:15 -08004042 final ActivityRecord top = tr.getTopNonFinishingActivity();
Chavi Weingarten3a748552018-05-14 17:32:42 +00004043 if (top == null || !top.okToShowLocked()) {
4044 if (top != null) {
Louis Changcdec0802019-11-11 11:45:07 +08004045 mStackSupervisor.mRecentTasks.add(top.getTask());
Chavi Weingarten3a748552018-05-14 17:32:42 +00004046 }
4047 ActivityOptions.abort(options);
4048 return;
Winson Chung1dbc8112017-09-28 18:05:31 -07004049 }
Chavi Weingarten9e875b62018-05-14 16:10:59 +00004050
Chavi Weingarten3a748552018-05-14 17:32:42 +00004051 // Set focus to the top running activity of this stack.
4052 final ActivityRecord r = topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08004053 if (r != null) {
4054 r.moveFocusableActivityToTop(reason);
4055 }
Chavi Weingarten9e875b62018-05-14 16:10:59 +00004056
Chavi Weingarten3a748552018-05-14 17:32:42 +00004057 if (DEBUG_TRANSITION) Slog.v(TAG_TRANSITION, "Prepare to front transition: task=" + tr);
4058 if (noAnimation) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08004059 getDisplay().mDisplayContent.prepareAppTransition(TRANSIT_NONE, false);
Chavi Weingarten3a748552018-05-14 17:32:42 +00004060 if (r != null) {
4061 mStackSupervisor.mNoAnimActivities.add(r);
4062 }
4063 ActivityOptions.abort(options);
4064 } else {
4065 updateTransitLocked(TRANSIT_TASK_TO_FRONT, options);
Chavi Weingarten9e875b62018-05-14 16:10:59 +00004066 }
Chavi Weingarten3a748552018-05-14 17:32:42 +00004067 // If a new task is moved to the front, then mark the existing top activity as
4068 // supporting
Chavi Weingarten9e875b62018-05-14 16:10:59 +00004069
Chavi Weingarten3a748552018-05-14 17:32:42 +00004070 // picture-in-picture while paused only if the task would not be considered an oerlay
4071 // on top
4072 // of the current activity (eg. not fullscreen, or the assistant)
4073 if (canEnterPipOnTaskSwitch(topActivity, tr, null /* toFrontActivity */,
4074 options)) {
4075 topActivity.supportsEnterPipOnTaskSwitch = true;
4076 }
Chavi Weingarten9e875b62018-05-14 16:10:59 +00004077
Wale Ogunwaled32da472018-11-16 07:19:28 -08004078 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07004079 EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, tr.mUserId, tr.mTaskId);
Mark Renoufc808f062019-02-07 15:20:37 -05004080 mService.getTaskChangeNotificationController().notifyTaskMovedToFront(tr.getTaskInfo());
Chavi Weingarten3a748552018-05-14 17:32:42 +00004081 } finally {
4082 getDisplay().continueUpdateImeTarget();
4083 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004084 }
4085
4086 /**
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07004087 * Worker method for rearranging history stack. Implements the function of moving all
4088 * activities for a specific task (gathering them if disjoint) into a single group at the
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004089 * bottom of the stack.
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07004090 *
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004091 * If a watcher is installed, the action is preflighted and the watcher has an opportunity
4092 * to premeptively cancel the move.
Craig Mautnerce5f3cb2013-04-22 08:58:54 -07004093 *
Craig Mautnerae7ecab2013-09-18 11:48:14 -07004094 * @param taskId The taskId to collect and move to the bottom.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004095 * @return Returns true if the move completed, false if not.
4096 */
Craig Mautner299f9602015-01-26 09:47:33 -08004097 final boolean moveTaskToBackLocked(int taskId) {
Louis Changcdec0802019-11-11 11:45:07 +08004098 final Task tr = taskForIdLocked(taskId);
Craig Mautneraea74a52014-03-08 14:23:10 -08004099 if (tr == null) {
4100 Slog.i(TAG, "moveTaskToBack: bad taskId=" + taskId);
4101 return false;
4102 }
Craig Mautneraea74a52014-03-08 14:23:10 -08004103 Slog.i(TAG, "moveTaskToBack: " + tr);
Winson Chung261c0f32017-03-07 16:54:31 -08004104
Charles Heff9b4dff2017-09-22 10:18:37 +01004105 // In LockTask mode, moving a locked task to the back of the stack may expose unlocked
4106 // ones. Therefore we need to check if this operation is allowed.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004107 if (!mService.getLockTaskController().canMoveTaskToBack(tr)) {
Winson Chung261c0f32017-03-07 16:54:31 -08004108 return false;
4109 }
Craig Mautnerb44de0d2013-02-21 20:00:58 -08004110
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004111 // If we have a watcher, preflight the move before committing to it. First check
4112 // for *other* available tasks, but if none are available, then try again allowing the
4113 // current task to be selected.
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004114 if (isTopStackOnDisplay() && mService.mController != null) {
Craig Mautnerae7ecab2013-09-18 11:48:14 -07004115 ActivityRecord next = topRunningActivityLocked(null, taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004116 if (next == null) {
4117 next = topRunningActivityLocked(null, 0);
4118 }
4119 if (next != null) {
4120 // ask watcher if this is allowed
4121 boolean moveOK = true;
4122 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004123 moveOK = mService.mController.activityResuming(next.packageName);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004124 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004125 mService.mController = null;
Kenny Rootadd58212013-05-07 09:47:34 -07004126 Watchdog.getInstance().setActivityController(null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004127 }
4128 if (!moveOK) {
4129 return false;
4130 }
4131 }
4132 }
4133
Wale Ogunwaleee006da2015-03-30 14:49:25 -07004134 if (DEBUG_TRANSITION) Slog.v(TAG_TRANSITION, "Prepare to back transition: task=" + taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004135
Wale Ogunwale3a256e62018-12-06 14:41:18 -08004136 getDisplay().mDisplayContent.prepareAppTransition(TRANSIT_TASK_TO_BACK, false);
Evan Rosky9c448172017-11-02 14:19:27 -07004137 moveToBack("moveTaskToBackLocked", tr);
Winson Chung261c0f32017-03-07 16:54:31 -08004138
Wale Ogunwale44f036f2017-09-29 05:09:09 -07004139 if (inPinnedWindowingMode()) {
Wale Ogunwalea0f5b5e2017-10-11 09:37:23 -07004140 mStackSupervisor.removeStack(this);
Winson Chung261c0f32017-03-07 16:54:31 -08004141 return true;
4142 }
4143
Evan Rosky80b2cb72019-05-31 20:18:02 -07004144 ActivityRecord topActivity = getDisplay().topRunningActivity();
4145 ActivityStack topStack = topActivity.getActivityStack();
4146 if (topStack != null && topStack != this && topActivity.isState(RESUMED)) {
4147 // The new top activity is already resumed, so there's a good chance that nothing will
4148 // get resumed below. So, update visibility now in case the transition is closed
4149 // prematurely.
4150 mRootActivityContainer.ensureVisibilityAndConfig(null /* starting */,
4151 getDisplay().mDisplayId, false /* markFrozenIfConfigChanged */,
4152 false /* deferResume */);
4153 }
4154
Wale Ogunwaled32da472018-11-16 07:19:28 -08004155 mRootActivityContainer.resumeFocusedStacksTopActivities();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004156 return true;
4157 }
Dianne Hackborn15491c62012-09-19 10:59:14 -07004158
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004159 /**
Wale Ogunwaledb0fa122016-05-16 15:12:03 -07004160 * Ensures all visible activities at or below the input activity have the right configuration.
4161 */
4162 void ensureVisibleActivitiesConfigurationLocked(ActivityRecord start, boolean preserveWindow) {
Issei Suzuki1669ea42019-11-06 14:20:59 +01004163 if (start == null || !start.mVisibleRequested) {
Wale Ogunwaledb0fa122016-05-16 15:12:03 -07004164 return;
4165 }
4166
Louis Changcdec0802019-11-11 11:45:07 +08004167 final Task startTask = start.getTask();
Wale Ogunwaledb0fa122016-05-16 15:12:03 -07004168 boolean behindFullscreen = false;
4169 boolean updatedConfig = false;
4170
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004171 for (int taskIndex = mChildren.indexOf(startTask); taskIndex >= 0; --taskIndex) {
Louis Changcdec0802019-11-11 11:45:07 +08004172 final Task task = getChildAt(taskIndex);
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004173 final ArrayList<ActivityRecord> activities = task.mChildren;
Louis Changcdec0802019-11-11 11:45:07 +08004174 int activityIndex = (start.getTask() == task)
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004175 ? activities.indexOf(start) : activities.size() - 1;
Wale Ogunwaledb0fa122016-05-16 15:12:03 -07004176 for (; activityIndex >= 0; --activityIndex) {
4177 final ActivityRecord r = activities.get(activityIndex);
Wale Ogunwaleb6d75f32018-02-22 20:44:56 -08004178 updatedConfig |= r.ensureActivityConfiguration(0 /* globalChanges */,
Andrii Kulian21713ac2016-10-12 22:05:05 -07004179 preserveWindow);
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08004180 if (r.occludesParent()) {
Wale Ogunwaledb0fa122016-05-16 15:12:03 -07004181 behindFullscreen = true;
4182 break;
4183 }
4184 }
4185 if (behindFullscreen) {
4186 break;
4187 }
4188 }
4189 if (updatedConfig) {
Wale Ogunwale089586f2016-06-20 14:16:22 -07004190 // Ensure the resumed state of the focus activity if we updated the configuration of
Wale Ogunwaledb0fa122016-05-16 15:12:03 -07004191 // any activity.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004192 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwaledb0fa122016-05-16 15:12:03 -07004193 }
4194 }
4195
Wale Ogunwale1666e312016-12-16 11:27:18 -08004196 // TODO: Can only be called from special methods in ActivityStackSupervisor.
4197 // Need to consolidate those calls points into this resize method so anyone can call directly.
Evan Roskydbe2ce52019-07-18 11:13:17 -07004198 void resize(Rect bounds, Rect tempTaskBounds, Rect tempTaskInsetBounds,
4199 boolean preserveWindows, boolean deferResume) {
Evan Rosky1ac84462018-11-13 11:25:30 -08004200 if (!updateBoundsAllowed(bounds)) {
Wale Ogunwale1666e312016-12-16 11:27:18 -08004201 return;
4202 }
4203
Riddle Hsu2ca561b2019-10-08 21:58:58 +08004204 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "stack.resize_" + mStackId);
Riddle Hsua0022cd2019-09-09 21:12:41 +08004205 mService.deferWindowLayout();
Evan Roskydbe2ce52019-07-18 11:13:17 -07004206 try {
4207 // Update override configurations of all tasks in the stack.
4208 final Rect taskBounds = tempTaskBounds != null ? tempTaskBounds : bounds;
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07004209 for (int i = getChildCount() - 1; i >= 0; i--) {
Louis Changcdec0802019-11-11 11:45:07 +08004210 final Task task = getChildAt(i);
Evan Roskydbe2ce52019-07-18 11:13:17 -07004211 if (task.isResizeable()) {
4212 if (tempTaskInsetBounds != null && !tempTaskInsetBounds.isEmpty()) {
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004213 task.setOverrideDisplayedBounds(taskBounds);
Evan Roskydbe2ce52019-07-18 11:13:17 -07004214 task.setBounds(tempTaskInsetBounds);
4215 } else {
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004216 task.setOverrideDisplayedBounds(null);
Evan Roskydbe2ce52019-07-18 11:13:17 -07004217 task.setBounds(taskBounds);
4218 }
Evan Roskya4cc3a92019-06-28 13:25:01 -07004219 }
Andrii Kulian1e32e022016-09-16 15:29:34 -07004220 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08004221
Evan Roskydbe2ce52019-07-18 11:13:17 -07004222 setBounds(bounds);
4223
4224 if (!deferResume) {
4225 ensureVisibleActivitiesConfigurationLocked(
4226 topRunningActivityLocked(), preserveWindows);
4227 }
4228 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004229 mService.continueWindowLayout();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08004230 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Evan Roskydbe2ce52019-07-18 11:13:17 -07004231 }
Andrii Kulian1e32e022016-09-16 15:29:34 -07004232 }
4233
Andrii Kulian1e32e022016-09-16 15:29:34 -07004234 /**
Evan Rosky1ac84462018-11-13 11:25:30 -08004235 * Until we can break this "set task bounds to same as stack bounds" behavior, this
4236 * basically resizes both stack and task bounds to the same bounds.
Andrii Kulian1e32e022016-09-16 15:29:34 -07004237 */
Evan Rosky1ac84462018-11-13 11:25:30 -08004238 void setTaskBounds(Rect bounds) {
4239 if (!updateBoundsAllowed(bounds)) {
Andrii Kulian1e32e022016-09-16 15:29:34 -07004240 return;
4241 }
4242
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07004243 for (int i = getChildCount() - 1; i >= 0; i--) {
Louis Changcdec0802019-11-11 11:45:07 +08004244 final Task task = getChildAt(i);
Evan Rosky1ac84462018-11-13 11:25:30 -08004245 if (task.isResizeable()) {
4246 task.setBounds(bounds);
4247 } else {
4248 task.setBounds(null);
Andrii Kulian1e32e022016-09-16 15:29:34 -07004249 }
Evan Rosky1ac84462018-11-13 11:25:30 -08004250 }
4251 }
4252
4253 /** Helper to setDisplayedBounds on all child tasks */
4254 void setTaskDisplayedBounds(Rect bounds) {
4255 if (!updateDisplayedBoundsAllowed(bounds)) {
4256 return;
Andrii Kulian1e32e022016-09-16 15:29:34 -07004257 }
4258
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07004259 for (int i = getChildCount() - 1; i >= 0; i--) {
Louis Changcdec0802019-11-11 11:45:07 +08004260 final Task task = getChildAt(i);
Evan Rosky1ac84462018-11-13 11:25:30 -08004261 if (bounds == null || bounds.isEmpty()) {
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004262 task.setOverrideDisplayedBounds(null);
Evan Rosky1ac84462018-11-13 11:25:30 -08004263 } else if (task.isResizeable()) {
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004264 task.setOverrideDisplayedBounds(bounds);
Andrii Kulian1e32e022016-09-16 15:29:34 -07004265 }
Andrii Kulian1e32e022016-09-16 15:29:34 -07004266 }
4267 }
4268
Craig Mautnercae015f2013-02-08 14:31:27 -08004269 boolean willActivityBeVisibleLocked(IBinder token) {
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07004270 for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) {
Louis Changcdec0802019-11-11 11:45:07 +08004271 final Task task = getChildAt(taskNdx);
Wale Ogunwale1a06f152019-10-11 11:26:30 +02004272 for (int activityNdx = task.getChildCount() - 1; activityNdx >= 0; --activityNdx) {
4273 final ActivityRecord r = task.getChildAt(activityNdx);
Craig Mautnerd44711d2013-02-23 11:24:36 -08004274 if (r.appToken == token) {
Craig Mautner34b73df2014-01-12 21:11:08 -08004275 return true;
Craig Mautnerd44711d2013-02-23 11:24:36 -08004276 }
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08004277 if (r.occludesParent() && !r.finishing) {
Craig Mautnerd44711d2013-02-23 11:24:36 -08004278 return false;
4279 }
Craig Mautnercae015f2013-02-08 14:31:27 -08004280 }
4281 }
Wale Ogunwale7d701172015-03-11 15:36:30 -07004282 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
Craig Mautner34b73df2014-01-12 21:11:08 -08004283 if (r == null) {
4284 return false;
4285 }
4286 if (r.finishing) Slog.e(TAG, "willActivityBeVisibleLocked: Returning false,"
4287 + " would have returned true for r=" + r);
4288 return !r.finishing;
Craig Mautnercae015f2013-02-08 14:31:27 -08004289 }
4290
4291 void closeSystemDialogsLocked() {
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07004292 for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) {
Louis Changcdec0802019-11-11 11:45:07 +08004293 final Task task = getChildAt(taskNdx);
Wale Ogunwale1a06f152019-10-11 11:26:30 +02004294 for (int activityNdx = task.getChildCount() - 1; activityNdx >= 0; --activityNdx) {
4295 final ActivityRecord r = task.getChildAt(activityNdx);
Craig Mautnerd44711d2013-02-23 11:24:36 -08004296 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Andrii Kulian7dd39bb2019-07-22 13:11:10 -07004297 r.finishIfPossible("close-sys", true /* oomAdj */);
Craig Mautnerd44711d2013-02-23 11:24:36 -08004298 }
Craig Mautnercae015f2013-02-08 14:31:27 -08004299 }
4300 }
4301 }
4302
Wale Ogunwale540e1232015-05-01 15:35:39 -07004303 boolean finishDisabledPackageActivitiesLocked(String packageName, Set<String> filterByClasses,
4304 boolean doit, boolean evenPersistent, int userId) {
Craig Mautnercae015f2013-02-08 14:31:27 -08004305 boolean didSomething = false;
Louis Changcdec0802019-11-11 11:45:07 +08004306 Task lastTask = null;
Craig Mautner9d8a30d2014-07-07 17:26:20 +00004307 ComponentName homeActivity = null;
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07004308 for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) {
4309 final ArrayList<ActivityRecord> activities = getChildAt(taskNdx).mChildren;
Bryce Leefbd263b42018-03-07 10:33:55 -08004310 mTmpActivities.clear();
4311 mTmpActivities.addAll(activities);
4312
4313 while (!mTmpActivities.isEmpty()) {
4314 ActivityRecord r = mTmpActivities.remove(0);
Wale Ogunwale540e1232015-05-01 15:35:39 -07004315 final boolean sameComponent =
4316 (r.packageName.equals(packageName) && (filterByClasses == null
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004317 || filterByClasses.contains(r.mActivityComponent.getClassName())))
4318 || (packageName == null && r.mUserId == userId);
4319 if ((userId == UserHandle.USER_ALL || r.mUserId == userId)
Louis Changcdec0802019-11-11 11:45:07 +08004320 && (sameComponent || r.getTask() == lastTask)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07004321 && (r.app == null || evenPersistent || !r.app.isPersistent())) {
Craig Mautner56f52db2013-02-25 10:03:01 -08004322 if (!doit) {
4323 if (r.finishing) {
4324 // If this activity is just finishing, then it is not
4325 // interesting as far as something to stop.
4326 continue;
4327 }
4328 return true;
Craig Mautnercae015f2013-02-08 14:31:27 -08004329 }
Wale Ogunwale6fbde9f2017-08-24 07:24:12 -07004330 if (r.isActivityTypeHome()) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004331 if (homeActivity != null && homeActivity.equals(r.mActivityComponent)) {
Craig Mautner9d8a30d2014-07-07 17:26:20 +00004332 Slog.i(TAG, "Skip force-stop again " + r);
4333 continue;
4334 } else {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004335 homeActivity = r.mActivityComponent;
Craig Mautner9d8a30d2014-07-07 17:26:20 +00004336 }
4337 }
Craig Mautner56f52db2013-02-25 10:03:01 -08004338 didSomething = true;
4339 Slog.i(TAG, " Force finishing activity " + r);
Louis Changcdec0802019-11-11 11:45:07 +08004340 lastTask = r.getTask();
Andrii Kulian7dd39bb2019-07-22 13:11:10 -07004341 r.finishIfPossible("force-stop", true);
Craig Mautnercae015f2013-02-08 14:31:27 -08004342 }
4343 }
4344 }
4345 return didSomething;
4346 }
4347
Winson Chung61c9e5a2017-10-11 10:39:32 -07004348 /**
4349 * @return The set of running tasks through {@param tasksOut} that are available to the caller.
4350 * If {@param ignoreActivityType} or {@param ignoreWindowingMode} are not undefined,
4351 * then skip running tasks that match those types.
4352 */
Louis Changcdec0802019-11-11 11:45:07 +08004353 void getRunningTasks(List<Task> tasksOut, @ActivityType int ignoreActivityType,
Nicholas Sauer0259e532019-08-30 08:24:55 -07004354 @WindowingMode int ignoreWindowingMode, int callingUid, boolean allowed,
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07004355 boolean crossUser, ArraySet<Integer> profileIds) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004356 boolean focusedStack = mRootActivityContainer.getTopDisplayFocusedStack() == this;
riddle_hsuddc74152015-04-07 11:30:09 +08004357 boolean topTask = true;
Nicholas Sauer0259e532019-08-30 08:24:55 -07004358 int userId = UserHandle.getUserId(callingUid);
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07004359 for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) {
Louis Changcdec0802019-11-11 11:45:07 +08004360 final Task task = getChildAt(taskNdx);
Wale Ogunwale21e06482019-11-18 05:14:15 -08004361 if (task.getTopNonFinishingActivity() == null) {
Winson Chung61c9e5a2017-10-11 10:39:32 -07004362 // Skip if there are no activities in the task
riddle_hsuddc74152015-04-07 11:30:09 +08004363 continue;
4364 }
Nicholas Sauer0259e532019-08-30 08:24:55 -07004365 if (task.effectiveUid != callingUid) {
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07004366 if (task.mUserId != userId && !crossUser && !profileIds.contains(task.mUserId)) {
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07004367 // Skip if the caller does not have cross user permission or cannot access
4368 // the task's profile
Nicholas Sauer0259e532019-08-30 08:24:55 -07004369 continue;
4370 }
4371 if (!allowed && !task.isActivityTypeHome()) {
4372 // Skip if the caller isn't allowed to fetch this task, except for the home
4373 // task which we always return.
4374 continue;
4375 }
Dianne Hackborn09233282014-04-30 11:33:59 -07004376 }
Winson Chung61c9e5a2017-10-11 10:39:32 -07004377 if (ignoreActivityType != ACTIVITY_TYPE_UNDEFINED
4378 && task.getActivityType() == ignoreActivityType) {
4379 // Skip ignored activity type
4380 continue;
Craig Mautneraab647e2013-02-28 16:31:36 -08004381 }
Winson Chung61c9e5a2017-10-11 10:39:32 -07004382 if (ignoreWindowingMode != WINDOWING_MODE_UNDEFINED
4383 && task.getWindowingMode() == ignoreWindowingMode) {
4384 // Skip ignored windowing mode
4385 continue;
4386 }
riddle_hsuddc74152015-04-07 11:30:09 +08004387 if (focusedStack && topTask) {
Winson Chung61c9e5a2017-10-11 10:39:32 -07004388 // For the focused stack top task, update the last stack active time so that it can
4389 // be used to determine the order of the tasks (it may not be set for newly created
4390 // tasks)
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07004391 task.touchActiveTime();
riddle_hsuddc74152015-04-07 11:30:09 +08004392 topTask = false;
4393 }
Winson Chung61c9e5a2017-10-11 10:39:32 -07004394 tasksOut.add(task);
Craig Mautnercae015f2013-02-08 14:31:27 -08004395 }
Craig Mautnercae015f2013-02-08 14:31:27 -08004396 }
4397
Andrii Kulian21713ac2016-10-12 22:05:05 -07004398 void unhandledBackLocked() {
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07004399 final int top = getChildCount() - 1;
Wale Ogunwaleee006da2015-03-30 14:49:25 -07004400 if (DEBUG_SWITCH) Slog.d(TAG_SWITCH, "Performing unhandledBack(): top activity at " + top);
Craig Mautneraab647e2013-02-28 16:31:36 -08004401 if (top >= 0) {
Louis Changcdec0802019-11-11 11:45:07 +08004402 final Task task = getChildAt(top);
Wale Ogunwale1a06f152019-10-11 11:26:30 +02004403 int activityTop = task.getChildCount() - 1;
Dianne Hackborn354736e2016-08-22 17:00:05 -07004404 if (activityTop >= 0) {
Wale Ogunwale1a06f152019-10-11 11:26:30 +02004405 task.getChildAt(activityTop).finishIfPossible("unhandled-back", true /* oomAdj */);
Craig Mautneraab647e2013-02-28 16:31:36 -08004406 }
Craig Mautnercae015f2013-02-08 14:31:27 -08004407 }
4408 }
4409
Craig Mautner6b74cb52013-09-27 17:02:21 -07004410 /**
4411 * Reset local parameters because an app's activity died.
4412 * @param app The app of the activity that died.
Craig Mautner19091252013-10-05 00:03:53 -07004413 * @return result from removeHistoryRecordsForAppLocked.
Craig Mautner6b74cb52013-09-27 17:02:21 -07004414 */
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07004415 boolean handleAppDiedLocked(WindowProcessController app) {
Craig Mautnere79d42682013-04-01 19:01:53 -07004416 if (mPausingActivity != null && mPausingActivity.app == app) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -07004417 if (DEBUG_PAUSE || DEBUG_CLEANUP) Slog.v(TAG_PAUSE,
Craig Mautnere79d42682013-04-01 19:01:53 -07004418 "App died while pausing: " + mPausingActivity);
4419 mPausingActivity = null;
4420 }
4421 if (mLastPausedActivity != null && mLastPausedActivity.app == app) {
4422 mLastPausedActivity = null;
Craig Mautner0f922742013-08-06 08:44:42 -07004423 mLastNoHistoryActivity = null;
Craig Mautnere79d42682013-04-01 19:01:53 -07004424 }
4425
Craig Mautner19091252013-10-05 00:03:53 -07004426 return removeHistoryRecordsForAppLocked(app);
Craig Mautnere79d42682013-04-01 19:01:53 -07004427 }
4428
Wale Ogunwaled32da472018-11-16 07:19:28 -08004429 void handleAppCrash(WindowProcessController app) {
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07004430 for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) {
Louis Changcdec0802019-11-11 11:45:07 +08004431 final Task task = getChildAt(taskNdx);
Wale Ogunwale1a06f152019-10-11 11:26:30 +02004432 for (int activityNdx = task.getChildCount() - 1; activityNdx >= 0; --activityNdx) {
4433 final ActivityRecord r = task.getChildAt(activityNdx);
Craig Mautnerd44711d2013-02-23 11:24:36 -08004434 if (r.app == app) {
4435 Slog.w(TAG, " Force finishing activity "
4436 + r.intent.getComponent().flattenToShortString());
Craig Mautner8e5b1332014-07-24 13:32:37 -07004437 // Force the destroy to skip right to removal.
4438 r.app = null;
Wale Ogunwale3a256e62018-12-06 14:41:18 -08004439 getDisplay().mDisplayContent.prepareAppTransition(
lumark588a3e82018-07-20 18:53:54 +08004440 TRANSIT_CRASHING_ACTIVITY_CLOSE, false /* alwaysKeepCurrent */);
Andrii Kulian7dd39bb2019-07-22 13:11:10 -07004441 r.destroyIfPossible("handleAppCrashedLocked");
Craig Mautnerd44711d2013-02-23 11:24:36 -08004442 }
Craig Mautnercae015f2013-02-08 14:31:27 -08004443 }
4444 }
4445 }
4446
Garfield Tan347bd602018-12-21 15:11:12 -08004447 boolean dump(FileDescriptor fd, PrintWriter pw, boolean dumpAll, boolean dumpClient,
4448 String dumpPackage, boolean needSep) {
4449 pw.println(" Stack #" + mStackId
4450 + ": type=" + activityTypeToString(getActivityType())
4451 + " mode=" + windowingModeToString(getWindowingMode()));
4452 pw.println(" isSleeping=" + shouldSleepActivities());
4453 pw.println(" mBounds=" + getRequestedOverrideBounds());
4454
4455 boolean printed = dumpActivitiesLocked(fd, pw, dumpAll, dumpClient, dumpPackage,
4456 needSep);
4457
Riddle Hsu5477b572019-11-12 16:07:29 +08004458 printed |= dumpHistoryList(fd, pw, mLruActivities, " ", "Run", false,
Garfield Tan347bd602018-12-21 15:11:12 -08004459 !dumpAll, false, dumpPackage, true,
4460 " Running activities (most recent first):", null);
4461
4462 needSep = printed;
4463 boolean pr = printThisActivity(pw, mPausingActivity, dumpPackage, needSep,
4464 " mPausingActivity: ");
4465 if (pr) {
4466 printed = true;
4467 needSep = false;
4468 }
4469 pr = printThisActivity(pw, getResumedActivity(), dumpPackage, needSep,
4470 " mResumedActivity: ");
4471 if (pr) {
4472 printed = true;
4473 needSep = false;
4474 }
4475 if (dumpAll) {
4476 pr = printThisActivity(pw, mLastPausedActivity, dumpPackage, needSep,
4477 " mLastPausedActivity: ");
4478 if (pr) {
4479 printed = true;
4480 needSep = true;
4481 }
4482 printed |= printThisActivity(pw, mLastNoHistoryActivity, dumpPackage,
4483 needSep, " mLastNoHistoryActivity: ");
4484 }
4485 return printed;
4486 }
4487
Dianne Hackborn390517b2013-05-30 15:03:32 -07004488 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
Wale Ogunwale34a5b572017-08-31 08:29:41 -07004489 boolean dumpClient, String dumpPackage, boolean needSep) {
4490
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07004491 if (!hasChild()) {
Wale Ogunwale34a5b572017-08-31 08:29:41 -07004492 return false;
4493 }
4494 final String prefix = " ";
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07004495 for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) {
Louis Changcdec0802019-11-11 11:45:07 +08004496 final Task task = getChildAt(taskNdx);
Wale Ogunwale34a5b572017-08-31 08:29:41 -07004497 if (needSep) {
4498 pw.println("");
Dianne Hackborn7ad34e52013-06-05 18:41:45 -07004499 }
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07004500 pw.println(prefix + "Task id #" + task.mTaskId);
Evan Roskydfe3da72018-10-26 17:21:06 -07004501 pw.println(prefix + "mBounds=" + task.getRequestedOverrideBounds());
Wale Ogunwale34a5b572017-08-31 08:29:41 -07004502 pw.println(prefix + "mMinWidth=" + task.mMinWidth);
4503 pw.println(prefix + "mMinHeight=" + task.mMinHeight);
4504 pw.println(prefix + "mLastNonFullscreenBounds=" + task.mLastNonFullscreenBounds);
4505 pw.println(prefix + "* " + task);
4506 task.dump(pw, prefix + " ");
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07004507 dumpHistoryList(fd, pw, getChildAt(taskNdx).mChildren,
Wale Ogunwale34a5b572017-08-31 08:29:41 -07004508 prefix, "Hist", true, !dumpAll, dumpClient, dumpPackage, false, null, task);
Craig Mautneraab647e2013-02-28 16:31:36 -08004509 }
Wale Ogunwale34a5b572017-08-31 08:29:41 -07004510 return true;
Craig Mautnercae015f2013-02-08 14:31:27 -08004511 }
4512
4513 ArrayList<ActivityRecord> getDumpActivitiesLocked(String name) {
Winson Chung6998bc42017-02-28 17:07:05 -08004514 ArrayList<ActivityRecord> activities = new ArrayList<>();
Craig Mautnercae015f2013-02-08 14:31:27 -08004515
4516 if ("all".equals(name)) {
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07004517 for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) {
4518 activities.addAll(getChildAt(taskNdx).mChildren);
Craig Mautnercae015f2013-02-08 14:31:27 -08004519 }
4520 } else if ("top".equals(name)) {
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07004521 final int top = getChildCount() - 1;
Craig Mautneraab647e2013-02-28 16:31:36 -08004522 if (top >= 0) {
Louis Changcdec0802019-11-11 11:45:07 +08004523 final Task task = getChildAt(top);
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004524 int listTop = task.getChildCount() - 1;
Craig Mautneraab647e2013-02-28 16:31:36 -08004525 if (listTop >= 0) {
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004526 activities.add(task.getChildAt(listTop));
Craig Mautneraab647e2013-02-28 16:31:36 -08004527 }
Craig Mautnercae015f2013-02-08 14:31:27 -08004528 }
4529 } else {
4530 ItemMatcher matcher = new ItemMatcher();
4531 matcher.build(name);
4532
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07004533 for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) {
Louis Changcdec0802019-11-11 11:45:07 +08004534 final Task task = getChildAt(taskNdx);
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004535 for (int activityNdx = task.getChildCount() - 1; activityNdx >= 0; --activityNdx) {
4536 final ActivityRecord r1 = task.getChildAt(activityNdx);
Craig Mautneraab647e2013-02-28 16:31:36 -08004537 if (matcher.match(r1, r1.intent.getComponent())) {
4538 activities.add(r1);
4539 }
Craig Mautnercae015f2013-02-08 14:31:27 -08004540 }
4541 }
4542 }
4543
4544 return activities;
4545 }
4546
4547 ActivityRecord restartPackage(String packageName) {
Filip Gruszczynski3e85ba22015-10-05 22:48:30 -07004548 ActivityRecord starting = topRunningActivityLocked();
Craig Mautnercae015f2013-02-08 14:31:27 -08004549
4550 // All activities that came from the package must be
4551 // restarted as if there was a config change.
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07004552 for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) {
Louis Changcdec0802019-11-11 11:45:07 +08004553 final Task task = getChildAt(taskNdx);
Wale Ogunwale1a06f152019-10-11 11:26:30 +02004554 for (int activityNdx = task.getChildCount() - 1; activityNdx >= 0; --activityNdx) {
4555 final ActivityRecord a = task.getChildAt(activityNdx);
Craig Mautneraab647e2013-02-28 16:31:36 -08004556 if (a.info.packageName.equals(packageName)) {
4557 a.forceNewConfig = true;
Issei Suzuki1669ea42019-11-06 14:20:59 +01004558 if (starting != null && a == starting && a.mVisibleRequested) {
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08004559 a.startFreezingScreenLocked(CONFIG_SCREEN_LAYOUT);
Craig Mautneraab647e2013-02-28 16:31:36 -08004560 }
Craig Mautnercae015f2013-02-08 14:31:27 -08004561 }
4562 }
4563 }
4564
4565 return starting;
4566 }
Craig Mautner5d9c7be2013-02-15 14:02:56 -08004567
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004568 /**
4569 * Removes the input task from this stack.
4570 *
4571 * @param child to remove.
4572 * @param reason for removal.
4573 */
Louis Changcdec0802019-11-11 11:45:07 +08004574 void removeChild(Task child, String reason) {
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004575 if (!mChildren.contains(child)) {
4576 // Not really in this stack anymore...
4577 return;
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004578 }
4579
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004580 final ActivityDisplay display = getDisplay();
4581 final boolean topFocused = mRootActivityContainer.isTopDisplayFocusedStack(this);
4582 if (DEBUG_TASK_MOVEMENT) Slog.d(TAG_WM, "removeChild: task=" + child);
4583
4584 super.removeChild(child);
4585
4586 EventLog.writeEvent(EventLogTags.AM_REMOVE_TASK, child.mTaskId, mStackId);
4587
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004588 if (display.isSingleTaskInstance()) {
4589 mService.notifySingleTaskDisplayEmpty(display.mDisplayId);
4590 }
4591
4592 display.mDisplayContent.setLayoutNeeded();
4593
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07004594 if (!hasChild()) {
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004595 // Stack is now empty...
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004596 removeIfPossible();
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004597 }
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004598
4599 moveHomeStackToFrontIfNeeded(topFocused, display, reason);
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004600 }
4601
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004602 @Override
Louis Changcdec0802019-11-11 11:45:07 +08004603 void removeChild(Task task) {
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004604 removeChild(task, "removeChild");
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004605 }
4606
4607 void moveHomeStackToFrontIfNeeded(
4608 boolean wasTopFocusedStack, ActivityDisplay display, String reason) {
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07004609 if (!hasChild() && wasTopFocusedStack) {
Wale Ogunwale06579d62016-04-30 15:29:06 -07004610 // We only need to adjust focused stack if this stack is in focus and we are not in the
4611 // process of moving the task to the top of the stack that will be focused.
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004612 String myReason = reason + " leftTaskHistoryEmpty";
4613 if (!inMultiWindowMode() || adjustFocusToNextFocusableStack(myReason) == null) {
4614 display.moveHomeStackToFront(myReason);
Craig Mautner04a0ea62014-01-13 12:51:26 -08004615 }
Issei Suzuki734bc942019-06-05 13:59:52 +02004616 }
Craig Mautner0247fc82013-02-28 14:32:06 -08004617 }
4618
Louis Changcdec0802019-11-11 11:45:07 +08004619 Task createTask(int taskId, ActivityInfo info, Intent intent,
Dianne Hackborn91097de2014-04-04 18:02:06 -07004620 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
Wale Ogunwale6fbde9f2017-08-24 07:24:12 -07004621 boolean toTop) {
Louis Changcdec0802019-11-11 11:45:07 +08004622 return createTask(taskId, info, intent, voiceSession, voiceInteractor, toTop,
Bryce Leeb802ea12017-11-15 21:25:03 -08004623 null /*activity*/, null /*source*/, null /*options*/);
4624 }
4625
Louis Changcdec0802019-11-11 11:45:07 +08004626 Task createTask(int taskId, ActivityInfo info, Intent intent,
Bryce Leeb802ea12017-11-15 21:25:03 -08004627 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
4628 boolean toTop, ActivityRecord activity, ActivityRecord source,
4629 ActivityOptions options) {
Louis Changcdec0802019-11-11 11:45:07 +08004630 final Task task = Task.create(
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004631 mService, taskId, info, intent, voiceSession, voiceInteractor, this);
Chong Zhang0fa656b2015-08-31 15:17:21 -07004632 // add the task to stack first, mTaskPositioner might need the stack association
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004633 addChild(task, toTop, (info.flags & FLAG_SHOW_FOR_ALL_USERS) != 0);
Lucas Dupin47a65c72018-02-15 14:16:18 -08004634 final int displayId = mDisplayId != INVALID_DISPLAY ? mDisplayId : DEFAULT_DISPLAY;
Bryce Lee2a3cc462017-10-27 10:57:35 -07004635 final boolean isLockscreenShown = mService.mStackSupervisor.getKeyguardController()
Lucas Dupin47a65c72018-02-15 14:16:18 -08004636 .isKeyguardOrAodShowing(displayId);
Bryce Leeec55eb02017-12-05 20:51:27 -08004637 if (!mStackSupervisor.getLaunchParamsController()
Bryce Leeb802ea12017-11-15 21:25:03 -08004638 .layoutTask(task, info.windowLayout, activity, source, options)
Bryce Leef3c6a472017-11-14 14:53:06 -08004639 && !matchParentBounds() && task.isResizeable() && !isLockscreenShown) {
Evan Roskya4cc3a92019-06-28 13:25:01 -07004640 task.setBounds(getRequestedOverrideBounds());
Filip Gruszczynskie5390e72015-08-18 16:39:00 -07004641 }
Craig Mautner5d9c7be2013-02-15 14:02:56 -08004642 return task;
4643 }
Craig Mautnerc00204b2013-03-05 15:02:14 -08004644
Louis Changcdec0802019-11-11 11:45:07 +08004645 ArrayList<Task> getAllTasks() {
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004646 return new ArrayList<>(mChildren);
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08004647 }
4648
Louis Changcdec0802019-11-11 11:45:07 +08004649 void addChild(final Task task, final boolean toTop, boolean showForAllUsers) {
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07004650 if (isSingleTaskInstance() && hasChild()) {
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004651 throw new IllegalStateException("Can only have one child on stack=" + this);
4652 }
4653
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004654 // We only want to move the parents to the parents if we are creating this task at the
4655 // top of its stack.
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004656 addChild(task, toTop ? MAX_VALUE : 0, showForAllUsers, toTop /*moveParents*/);
Craig Mautnerc00204b2013-03-05 15:02:14 -08004657 }
4658
Louis Changcdec0802019-11-11 11:45:07 +08004659 void positionChildAt(Task task, int position) {
Wale Ogunwalec5cc3012017-01-13 13:26:16 -08004660 if (task.getStack() != this) {
4661 throw new IllegalArgumentException("AS.positionChildAt: task=" + task
4662 + " is not a child of stack=" + this + " current parent=" + task.getStack());
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08004663 }
4664
4665 task.updateOverrideConfigurationForStack(this);
4666
Jorim Jaggi023da532016-04-20 22:42:32 -07004667 final ActivityRecord topRunningActivity = task.topRunningActivityLocked();
Andrii Kulian02b7a832016-10-06 23:11:56 -07004668 final boolean wasResumed = topRunningActivity == task.getStack().mResumedActivity;
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004669
Louis Changdc077272019-11-12 16:52:56 +08004670 boolean toTop = position >= getChildCount();
4671 boolean includingParents = toTop || getDisplay().getNextFocusableStack(this,
4672 true /* ignoreCurrent */) == null;
4673 if (WindowManagerDebugConfig.DEBUG_STACK) {
4674 Slog.i(TAG_WM, "positionChildAt: positioning task=" + task + " at " + position);
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004675 }
Louis Changdc077272019-11-12 16:52:56 +08004676 positionChildAt(position, task, includingParents);
4677 task.updateTaskMovement(toTop);
Louis Changdc077272019-11-12 16:52:56 +08004678 getDisplayContent().layoutAndAssignWindowLayersIfNeeded();
4679
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004680
4681 // TODO: Investigate if this random code is really needed.
4682 if (task.voiceSession != null) {
4683 try {
4684 task.voiceSession.taskStarted(task.intent, task.mTaskId);
4685 } catch (RemoteException e) {
4686 }
4687 }
Wale Ogunwalec5cc3012017-01-13 13:26:16 -08004688
Jorim Jaggi023da532016-04-20 22:42:32 -07004689 if (wasResumed) {
4690 if (mResumedActivity != null) {
4691 Log.wtf(TAG, "mResumedActivity was already set when moving mResumedActivity from"
4692 + " other stack to this stack mResumedActivity=" + mResumedActivity
4693 + " other mResumedActivity=" + topRunningActivity);
4694 }
Bryce Leec4ab62a2018-03-05 14:19:26 -08004695 topRunningActivity.setState(RESUMED, "positionChildAt");
Jorim Jaggi023da532016-04-20 22:42:32 -07004696 }
Wale Ogunwalee1fe7fa22016-12-15 18:27:00 -08004697
4698 // The task might have already been running and its visibility needs to be synchronized with
4699 // the visibility of the stack / windows.
4700 ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwaled32da472018-11-16 07:19:28 -08004701 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale5f986092015-12-04 15:35:38 -08004702 }
4703
Kazuki Takisef85197b2018-06-18 18:18:36 +09004704 public void setAlwaysOnTop(boolean alwaysOnTop) {
4705 if (isAlwaysOnTop() == alwaysOnTop) {
4706 return;
4707 }
4708 super.setAlwaysOnTop(alwaysOnTop);
4709 final ActivityDisplay display = getDisplay();
4710 // positionChildAtTop() must be called even when always on top gets turned off because we
4711 // need to make sure that the stack is moved from among always on top windows to below other
4712 // always on top windows. Since the position the stack should be inserted into is calculated
4713 // properly in {@link ActivityDisplay#getTopInsertPosition()} in both cases, we can just
4714 // request that the stack is put at top here.
Riddle Hsu57831b52018-07-27 00:31:48 +08004715 display.positionChildAtTop(this, false /* includingParents */);
Kazuki Takisef85197b2018-06-18 18:18:36 +09004716 }
4717
Louis Changcdec0802019-11-11 11:45:07 +08004718 /** NOTE: Should only be called from {@link Task#reparent}. */
Winson Chungc2baac02017-01-11 13:34:47 -08004719 void moveToFrontAndResumeStateIfNeeded(ActivityRecord r, boolean moveToFront, boolean setResume,
4720 boolean setPause, String reason) {
Wale Ogunwaled046a012015-12-24 13:05:59 -08004721 if (!moveToFront) {
4722 return;
Wale Ogunwale079a0042015-10-24 11:44:07 -07004723 }
Wale Ogunwaled046a012015-12-24 13:05:59 -08004724
Riddle Hsu16567132018-08-16 21:37:47 +08004725 final ActivityState origState = r.getState();
Wale Ogunwaled046a012015-12-24 13:05:59 -08004726 // If the activity owns the last resumed activity, transfer that together,
4727 // so that we don't resume the same activity again in the new stack.
4728 // Apps may depend on onResume()/onPause() being called in pairs.
4729 if (setResume) {
Bryce Leec4ab62a2018-03-05 14:19:26 -08004730 r.setState(RESUMED, "moveToFrontAndResumeStateIfNeeded");
Riddle Hsu5477b572019-11-12 16:07:29 +08004731 updateLruList(r);
Wale Ogunwaled046a012015-12-24 13:05:59 -08004732 }
Winson Chungc2baac02017-01-11 13:34:47 -08004733 // If the activity was previously pausing, then ensure we transfer that as well
4734 if (setPause) {
4735 mPausingActivity = r;
Andrii Kulian79d67982019-08-19 11:56:16 -07004736 schedulePauseTimeoutForActivity(r);
Winson Chungc2baac02017-01-11 13:34:47 -08004737 }
Riddle Hsu16567132018-08-16 21:37:47 +08004738 // Move the stack in which we are placing the activity to the front.
Wale Ogunwaled046a012015-12-24 13:05:59 -08004739 moveToFront(reason);
Riddle Hsu16567132018-08-16 21:37:47 +08004740 // If the original state is resumed, there is no state change to update focused app.
4741 // So here makes sure the activity focus is set if it is the top.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004742 if (origState == RESUMED && r == mRootActivityContainer.getTopResumedActivity()) {
Riddle Hsu16567132018-08-16 21:37:47 +08004743 mService.setResumedActivityUncheckLocked(r, reason);
4744 }
Wale Ogunwale079a0042015-10-24 11:44:07 -07004745 }
4746
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004747 void animateResizePinnedStack(Rect toBounds, Rect sourceHintBounds, int animationDuration,
Yunfan Chen279f5582018-12-12 15:24:50 -08004748 boolean fromFullscreen) {
4749 if (!inPinnedWindowingMode()) return;
wilsonshih73b6e262019-08-08 17:48:46 +08004750 if (toBounds == null /* toFullscreen */) {
4751 final Configuration parentConfig = getParent().getConfiguration();
4752 final ActivityRecord top = topRunningNonOverlayTaskActivity();
4753 if (top != null && !top.isConfigurationCompatible(parentConfig)) {
4754 // The final orientation of this activity will change after moving to full screen.
4755 // Start freezing screen here to prevent showing a temporary full screen window.
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08004756 top.startFreezingScreenLocked(CONFIG_SCREEN_LAYOUT);
Ben Lin6db8fb22019-10-18 16:03:44 -07004757 dismissPip();
wilsonshih73b6e262019-08-08 17:48:46 +08004758 return;
4759 }
Yunfan Chen279f5582018-12-12 15:24:50 -08004760 }
Louis Changdc077272019-11-12 16:52:56 +08004761
4762 // Get the from-bounds
4763 final Rect fromBounds = new Rect();
4764 getBounds(fromBounds);
4765
4766 // Get non-null fullscreen to-bounds for animating if the bounds are null
4767 @BoundsAnimationController.SchedulePipModeChangedState int schedulePipModeChangedState =
4768 NO_PIP_MODE_CHANGED_CALLBACKS;
4769 final boolean toFullscreen = toBounds == null;
4770 if (toFullscreen) {
4771 if (fromFullscreen) {
4772 throw new IllegalArgumentException("Should not defer scheduling PiP mode"
4773 + " change on animation to fullscreen.");
4774 }
4775 schedulePipModeChangedState = SCHEDULE_PIP_MODE_CHANGED_ON_START;
4776
4777 mWmService.getStackBounds(
4778 WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, mTmpToBounds);
4779 if (!mTmpToBounds.isEmpty()) {
4780 // If there is a fullscreen bounds, use that
4781 toBounds = new Rect(mTmpToBounds);
4782 } else {
4783 // Otherwise, use the display bounds
4784 toBounds = new Rect();
4785 getDisplayContent().getBounds(toBounds);
4786 }
4787 } else if (fromFullscreen) {
4788 schedulePipModeChangedState = SCHEDULE_PIP_MODE_CHANGED_ON_END;
4789 }
4790
4791 setAnimationFinalBounds(sourceHintBounds, toBounds, toFullscreen);
4792
4793 final Rect finalToBounds = toBounds;
4794 final @BoundsAnimationController.SchedulePipModeChangedState int
4795 finalSchedulePipModeChangedState = schedulePipModeChangedState;
4796 final DisplayContent displayContent = getDisplayContent();
4797 @BoundsAnimationController.AnimationType int intendedAnimationType =
4798 displayContent.mBoundsAnimationController.getAnimationType();
4799 if (intendedAnimationType == FADE_IN) {
4800 if (fromFullscreen) {
4801 setPinnedStackAlpha(0f);
4802 }
4803 if (toBounds.width() == fromBounds.width()
4804 && toBounds.height() == fromBounds.height()) {
4805 intendedAnimationType = BoundsAnimationController.BOUNDS;
4806 } else if (!fromFullscreen && !toBounds.equals(fromBounds)) {
4807 // intendedAnimationType may have been reset at the end of RecentsAnimation,
4808 // force it to BOUNDS type if we know for certain we're animating to
4809 // a different bounds, especially for expand and collapse of PiP window.
4810 intendedAnimationType = BoundsAnimationController.BOUNDS;
4811 }
4812 }
4813
4814 final @BoundsAnimationController.AnimationType int animationType = intendedAnimationType;
4815 mCancelCurrentBoundsAnimation = false;
4816 displayContent.mBoundsAnimationController.getHandler().post(() -> {
4817 displayContent.mBoundsAnimationController.animateBounds(this, fromBounds,
4818 finalToBounds, animationDuration, finalSchedulePipModeChangedState,
4819 fromFullscreen, toFullscreen, animationType);
4820 });
Yunfan Chen279f5582018-12-12 15:24:50 -08004821 }
4822
Ben Lin6db8fb22019-10-18 16:03:44 -07004823 void dismissPip() {
4824 if (!isActivityTypeStandardOrUndefined()) {
4825 throw new IllegalArgumentException(
4826 "You can't move tasks from non-standard stacks.");
4827 }
4828 if (getWindowingMode() != WINDOWING_MODE_PINNED) {
4829 throw new IllegalArgumentException(
4830 "Can't exit pinned mode if it's not pinned already.");
4831 }
4832
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004833 if (mChildren.size() != 1) {
Ben Lin6db8fb22019-10-18 16:03:44 -07004834 throw new RuntimeException("There should be only one task in a pinned stack.");
4835 }
4836
Hongwei Wang7d0c2c02019-11-12 14:55:44 -08004837 // give pinned stack a chance to save current bounds, this should happen before reparent.
4838 final ActivityRecord top = topRunningNonOverlayTaskActivity();
4839 if (top != null && top.isVisible()) {
4840 top.savePinnedStackBounds();
4841 }
4842
Ben Lin6db8fb22019-10-18 16:03:44 -07004843 mWindowManager.inSurfaceTransaction(() -> {
Louis Changcdec0802019-11-11 11:45:07 +08004844 final Task task = mChildren.get(0);
Ben Lin6db8fb22019-10-18 16:03:44 -07004845 setWindowingMode(WINDOWING_MODE_UNDEFINED);
4846
4847 getDisplay().positionChildAtTop(this, false /* includingParents */);
4848
4849 mStackSupervisor.scheduleUpdatePictureInPictureModeIfNeeded(task, this);
4850 MetricsLoggerWrapper.logPictureInPictureFullScreen(mService.mContext,
4851 task.effectiveUid, task.realActivity.flattenToString());
4852 });
4853 }
4854
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004855 void updatePictureInPictureModeForPinnedStackAnimation(Rect targetStackBounds,
Yunfan Chen279f5582018-12-12 15:24:50 -08004856 boolean forceUpdate) {
4857 // It is guaranteed that the activities requiring the update will be in the pinned stack at
4858 // this point (either reparented before the animation into PiP, or before reparenting after
4859 // the animation out of PiP)
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004860 if (!isAttached()) {
4861 return;
4862 }
Louis Changcdec0802019-11-11 11:45:07 +08004863 ArrayList<Task> tasks = getAllTasks();
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004864 for (int i = 0; i < tasks.size(); i++) {
4865 mStackSupervisor.updatePictureInPictureMode(tasks.get(i), targetStackBounds,
4866 forceUpdate);
Yunfan Chen279f5582018-12-12 15:24:50 -08004867 }
4868 }
4869
Craig Mautnerc00204b2013-03-05 15:02:14 -08004870 public int getStackId() {
4871 return mStackId;
4872 }
Craig Mautnerde4ef022013-04-07 19:01:33 -07004873
Louis Changdc077272019-11-12 16:52:56 +08004874 Task findHomeTask() {
4875 if (!isActivityTypeHome() || mChildren.isEmpty()) {
4876 return null;
4877 }
4878 return mChildren.get(mChildren.size() - 1);
4879 }
4880
4881 void prepareFreezingTaskBounds() {
4882 for (int taskNdx = mChildren.size() - 1; taskNdx >= 0; --taskNdx) {
4883 final Task task = mChildren.get(taskNdx);
4884 task.prepareFreezingBounds();
4885 }
4886 }
4887
4888 /**
4889 * Overrides the adjusted bounds, i.e. sets temporary layout bounds which are different from
4890 * the normal task bounds.
4891 *
4892 * @param bounds The adjusted bounds.
4893 */
4894 private void setAdjustedBounds(Rect bounds) {
4895 if (mAdjustedBounds.equals(bounds) && !isAnimatingForIme()) {
4896 return;
4897 }
4898
4899 mAdjustedBounds.set(bounds);
4900 final boolean adjusted = !mAdjustedBounds.isEmpty();
4901 Rect insetBounds = null;
4902 if (adjusted && isAdjustedForMinimizedDockedStack()) {
4903 insetBounds = getRawBounds();
4904 } else if (adjusted && mAdjustedForIme) {
4905 if (mImeGoingAway) {
4906 insetBounds = getRawBounds();
4907 } else {
4908 insetBounds = mFullyAdjustedImeBounds;
4909 }
4910 }
4911 alignTasksToAdjustedBounds(adjusted ? mAdjustedBounds : getRawBounds(), insetBounds);
4912 mDisplayContent.setLayoutNeeded();
4913
4914 updateSurfaceBounds();
4915 }
4916
4917 private void alignTasksToAdjustedBounds(Rect adjustedBounds, Rect tempInsetBounds) {
4918 if (matchParentBounds()) {
4919 return;
4920 }
4921
4922 final boolean alignBottom = mAdjustedForIme && getDockSide() == DOCKED_TOP;
4923
4924 // Update bounds of containing tasks.
4925 for (int taskNdx = mChildren.size() - 1; taskNdx >= 0; --taskNdx) {
4926 final Task task = mChildren.get(taskNdx);
4927 task.alignToAdjustedBounds(adjustedBounds, tempInsetBounds, alignBottom);
4928 }
4929 }
4930
4931 @Override
4932 public int setBounds(Rect bounds) {
4933 return setBounds(getRequestedOverrideBounds(), bounds);
4934 }
4935
4936 private int setBounds(Rect existing, Rect bounds) {
4937 if (equivalentBounds(existing, bounds)) {
4938 return BOUNDS_CHANGE_NONE;
4939 }
4940
4941 final int result = super.setBounds(!inMultiWindowMode() ? null : bounds);
4942
4943 updateAdjustedBounds();
4944
4945 updateSurfaceBounds();
4946 return result;
4947 }
4948
4949 /** Bounds of the stack without adjusting for other factors in the system like visibility
4950 * of docked stack.
4951 * Most callers should be using {@link ConfigurationContainer#getRequestedOverrideBounds} a
4952 * it takes into consideration other system factors. */
4953 void getRawBounds(Rect out) {
4954 out.set(getRawBounds());
4955 }
4956
4957 private Rect getRawBounds() {
4958 return super.getBounds();
4959 }
4960
4961 @Override
4962 public void getBounds(Rect bounds) {
4963 bounds.set(getBounds());
4964 }
4965
4966 @Override
4967 public Rect getBounds() {
4968 // If we're currently adjusting for IME or minimized docked stack, we use the adjusted
4969 // bounds; otherwise, no need to adjust the output bounds if fullscreen or the docked
4970 // stack is visible since it is already what we want to represent to the rest of the
4971 // system.
4972 if (!mAdjustedBounds.isEmpty()) {
4973 return mAdjustedBounds;
4974 } else {
4975 return super.getBounds();
4976 }
4977 }
4978
4979 /**
4980 * Sets the bounds animation target bounds ahead of an animation. This can't currently be done
4981 * in onAnimationStart() since that is started on the UiThread.
4982 */
4983 private void setAnimationFinalBounds(Rect sourceHintBounds, Rect destBounds,
4984 boolean toFullscreen) {
4985 if (mAnimationType == BoundsAnimationController.BOUNDS) {
4986 mBoundsAnimatingRequested = true;
4987 }
4988 mBoundsAnimatingToFullscreen = toFullscreen;
4989 if (destBounds != null) {
4990 mBoundsAnimationTarget.set(destBounds);
4991 } else {
4992 mBoundsAnimationTarget.setEmpty();
4993 }
4994 if (sourceHintBounds != null) {
4995 mBoundsAnimationSourceHintBounds.set(sourceHintBounds);
4996 } else if (!mBoundsAnimating) {
4997 // If the bounds are already animating, we don't want to reset the source hint. This is
4998 // because the source hint is sent when starting the animation from the client that
4999 // requested to enter pip. Other requests can adjust the pip bounds during an animation,
5000 // but could accidentally reset the source hint bounds.
5001 mBoundsAnimationSourceHintBounds.setEmpty();
5002 }
5003
5004 mPreAnimationBounds.set(getRawBounds());
5005 }
5006
5007 /**
5008 * @return the final bounds for the bounds animation.
5009 */
5010 void getFinalAnimationBounds(Rect outBounds) {
5011 outBounds.set(mBoundsAnimationTarget);
5012 }
5013
5014 /**
5015 * @return the final source bounds for the bounds animation.
5016 */
5017 void getFinalAnimationSourceHintBounds(Rect outBounds) {
5018 outBounds.set(mBoundsAnimationSourceHintBounds);
5019 }
5020
5021 /**
5022 * @return the final animation bounds if the task stack is currently being animated, or the
5023 * current stack bounds otherwise.
5024 */
5025 void getAnimationOrCurrentBounds(Rect outBounds) {
5026 if ((mBoundsAnimatingRequested || mBoundsAnimating) && !mBoundsAnimationTarget.isEmpty()) {
5027 getFinalAnimationBounds(outBounds);
5028 return;
5029 }
5030 getBounds(outBounds);
5031 }
5032
5033 /** Bounds of the stack with other system factors taken into consideration. */
5034 void getDimBounds(Rect out) {
5035 getBounds(out);
5036 }
5037
5038 /**
5039 * Updates the passed-in {@code inOutBounds} based on the current state of the
5040 * pinned controller. This gets run *after* the override configuration is updated, so it's
5041 * safe to rely on the controller's state in here (though eventually this dependence should
5042 * be removed).
5043 *
5044 * This does NOT modify this TaskStack's configuration. However, it does, for the time-being,
5045 * update pinned controller state.
5046 *
5047 * @param inOutBounds the bounds to update (both input and output).
5048 * @return true if bounds were updated to some non-empty value.
5049 */
5050 boolean calculatePinnedBoundsForConfigChange(Rect inOutBounds) {
5051 boolean animating = false;
5052 if ((mBoundsAnimatingRequested || mBoundsAnimating) && !mBoundsAnimationTarget.isEmpty()) {
5053 animating = true;
5054 getFinalAnimationBounds(mTmpRect2);
5055 } else {
5056 mTmpRect2.set(inOutBounds);
5057 }
5058 boolean updated = mDisplayContent.mPinnedStackControllerLocked.onTaskStackBoundsChanged(
5059 mTmpRect2, mTmpRect3);
5060 if (updated) {
5061 inOutBounds.set(mTmpRect3);
5062
5063 // The final boundary is updated while there is an existing boundary animation. Let's
5064 // cancel this animation to prevent the obsolete animation overwritten updated bounds.
5065 if (animating && !inOutBounds.equals(mBoundsAnimationTarget)) {
5066 final DisplayContent displayContent = getDisplayContent();
5067 displayContent.mBoundsAnimationController.getHandler().post(() ->
5068 displayContent.mBoundsAnimationController.cancel(this));
5069 }
5070 // Once we've set the bounds based on the rotation of the old bounds in the new
5071 // orientation, clear the animation target bounds since they are obsolete, and
5072 // cancel any currently running animations
5073 mBoundsAnimationTarget.setEmpty();
5074 mBoundsAnimationSourceHintBounds.setEmpty();
5075 mCancelCurrentBoundsAnimation = true;
5076 }
5077 return updated;
5078 }
5079
5080 /**
5081 * Updates the passed-in {@code inOutBounds} based on the current state of the
5082 * docked controller. This gets run *after* the override configuration is updated, so it's
5083 * safe to rely on the controller's state in here (though eventually this dependence should
5084 * be removed).
5085 *
5086 * This does NOT modify this TaskStack's configuration. However, it does, for the time-being,
5087 * update docked controller state.
5088 *
5089 * @param parentConfig the parent configuration for reference.
5090 * @param inOutBounds the bounds to update (both input and output).
5091 */
5092 void calculateDockedBoundsForConfigChange(Configuration parentConfig, Rect inOutBounds) {
5093 final boolean primary =
5094 getRequestedOverrideWindowingMode() == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
5095 repositionSplitScreenStackAfterRotation(parentConfig, primary, inOutBounds);
5096 final DisplayCutout cutout = mDisplayContent.getDisplayInfo().displayCutout;
5097 snapDockedStackAfterRotation(parentConfig, cutout, inOutBounds);
5098 if (primary) {
5099 final int newDockSide = getDockSide(parentConfig, inOutBounds);
5100 // Update the dock create mode and clear the dock create bounds, these
5101 // might change after a rotation and the original values will be invalid.
5102 mWmService.setDockedStackCreateStateLocked(
5103 (newDockSide == DOCKED_LEFT || newDockSide == DOCKED_TOP)
5104 ? SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT
5105 : SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT,
5106 null);
5107 mDisplayContent.getDockedDividerController().notifyDockSideChanged(newDockSide);
5108 }
5109 }
5110
5111 /**
5112 * Some primary split screen sides are not allowed by the policy. This method queries the policy
5113 * and moves the primary stack around if needed.
5114 *
5115 * @param parentConfig the configuration of the stack's parent.
5116 * @param primary true if adjusting the primary docked stack, false for secondary.
5117 * @param inOutBounds the bounds of the stack to adjust.
5118 */
5119 void repositionSplitScreenStackAfterRotation(Configuration parentConfig, boolean primary,
5120 Rect inOutBounds) {
5121 final int dockSide = getDockSide(mDisplayContent, parentConfig, inOutBounds);
5122 final int otherDockSide = DockedDividerUtils.invertDockSide(dockSide);
5123 final int primaryDockSide = primary ? dockSide : otherDockSide;
5124 if (mDisplayContent.getDockedDividerController()
5125 .canPrimaryStackDockTo(primaryDockSide,
5126 parentConfig.windowConfiguration.getBounds(),
5127 parentConfig.windowConfiguration.getRotation())) {
5128 return;
5129 }
5130 final Rect parentBounds = parentConfig.windowConfiguration.getBounds();
5131 switch (otherDockSide) {
5132 case DOCKED_LEFT:
5133 int movement = inOutBounds.left;
5134 inOutBounds.left -= movement;
5135 inOutBounds.right -= movement;
5136 break;
5137 case DOCKED_RIGHT:
5138 movement = parentBounds.right - inOutBounds.right;
5139 inOutBounds.left += movement;
5140 inOutBounds.right += movement;
5141 break;
5142 case DOCKED_TOP:
5143 movement = inOutBounds.top;
5144 inOutBounds.top -= movement;
5145 inOutBounds.bottom -= movement;
5146 break;
5147 case DOCKED_BOTTOM:
5148 movement = parentBounds.bottom - inOutBounds.bottom;
5149 inOutBounds.top += movement;
5150 inOutBounds.bottom += movement;
5151 break;
5152 }
5153 }
5154
5155 /**
5156 * Snaps the bounds after rotation to the closest snap target for the docked stack.
5157 */
5158 void snapDockedStackAfterRotation(Configuration parentConfig, DisplayCutout displayCutout,
5159 Rect outBounds) {
5160
5161 // Calculate the current position.
5162 final int dividerSize = mDisplayContent.getDockedDividerController().getContentWidth();
5163 final int dockSide = getDockSide(parentConfig, outBounds);
5164 final int dividerPosition = DockedDividerUtils.calculatePositionForBounds(outBounds,
5165 dockSide, dividerSize);
5166 final int displayWidth = parentConfig.windowConfiguration.getBounds().width();
5167 final int displayHeight = parentConfig.windowConfiguration.getBounds().height();
5168
5169 // Snap the position to a target.
5170 final int rotation = parentConfig.windowConfiguration.getRotation();
5171 final int orientation = parentConfig.orientation;
5172 mDisplayContent.getDisplayPolicy().getStableInsetsLw(rotation, displayWidth, displayHeight,
5173 displayCutout, outBounds);
5174 final DividerSnapAlgorithm algorithm = new DividerSnapAlgorithm(
5175 mWmService.mContext.getResources(), displayWidth, displayHeight,
5176 dividerSize, orientation == Configuration.ORIENTATION_PORTRAIT, outBounds,
5177 getDockSide(), isMinimizedDockAndHomeStackResizable());
5178 final DividerSnapAlgorithm.SnapTarget target =
5179 algorithm.calculateNonDismissingSnapTarget(dividerPosition);
5180
5181 // Recalculate the bounds based on the position of the target.
5182 DockedDividerUtils.calculateBoundsForPosition(target.position, dockSide,
5183 outBounds, displayWidth, displayHeight,
5184 dividerSize);
5185 }
5186
5187 /**
5188 * Put a Task in this stack. Used for adding only.
5189 * When task is added to top of the stack, the entire branch of the hierarchy (including stack
5190 * and display) will be brought to top.
5191 * @param task The task to add.
5192 * @param position Target position to add the task to.
5193 * @param showForAllUsers Whether to show the task regardless of the current user.
5194 */
5195 void addChild(Task task, int position, boolean showForAllUsers, boolean moveParents) {
5196 // Add child task.
5197 addChild(task, null);
5198
5199 // Move child to a proper position, as some restriction for position might apply.
5200 position = positionChildAt(
5201 position, task, moveParents /* includingParents */, showForAllUsers);
5202 }
5203
5204 @Override
5205 void addChild(Task task, int position) {
5206 addChild(task, position, task.showForAllUsers(), false /* includingParents */);
5207 }
5208
5209 void positionChildAtTop(Task child) {
5210 if (child == null) {
5211 // TODO: Fix the call-points that cause this to happen.
5212 return;
5213 }
5214
5215 positionChildAt(POSITION_TOP, child, true /* includingParents */);
5216 child.updateTaskMovement(true);
5217
5218 final DisplayContent displayContent = getDisplayContent();
Louis Changdc077272019-11-12 16:52:56 +08005219 displayContent.layoutAndAssignWindowLayersIfNeeded();
5220 }
5221
5222 private void positionChildAtBottom(Task child) {
5223 // If there are other focusable stacks on the display, the z-order of the display should not
5224 // be changed just because a task was placed at the bottom. E.g. if it is moving the topmost
5225 // task to bottom, the next focusable stack on the same display should be focused.
5226 final ActivityStack nextFocusableStack = getDisplay().getNextFocusableStack(
5227 child.getStack(), true /* ignoreCurrent */);
5228 positionChildAtBottom(child, nextFocusableStack == null /* includingParents */);
5229 child.updateTaskMovement(true);
5230 }
5231
5232 @VisibleForTesting
5233 void positionChildAtBottom(Task child, boolean includingParents) {
5234 if (child == null) {
5235 // TODO: Fix the call-points that cause this to happen.
5236 return;
5237 }
5238
5239 positionChildAt(POSITION_BOTTOM, child, includingParents);
Louis Changdc077272019-11-12 16:52:56 +08005240 getDisplayContent().layoutAndAssignWindowLayersIfNeeded();
5241 }
5242
5243 @Override
5244 void positionChildAt(int position, Task child, boolean includingParents) {
5245 positionChildAt(position, child, includingParents, child.showForAllUsers());
5246 }
5247
5248 /**
5249 * Overridden version of {@link ActivityStack#positionChildAt(int, Task, boolean)}. Used in
5250 * {@link ActivityStack#addChild(Task, int, boolean showForAllUsers, boolean)}, as it can
5251 * receive showForAllUsers param from {@link ActivityRecord} instead of
5252 * {@link Task#showForAllUsers()}.
5253 */
5254 private int positionChildAt(int position, Task child, boolean includingParents,
5255 boolean showForAllUsers) {
5256 final int targetPosition = findPositionForTask(child, position, showForAllUsers);
5257 super.positionChildAt(targetPosition, child, includingParents);
5258
5259 // Log positioning.
5260 if (DEBUG_TASK_MOVEMENT) {
5261 Slog.d(TAG_WM, "positionTask: task=" + this + " position=" + position);
5262 }
5263
5264 final int toTop = targetPosition == mChildren.size() - 1 ? 1 : 0;
5265 EventLog.writeEvent(com.android.server.EventLogTags.WM_TASK_MOVED, child.mTaskId, toTop,
5266 targetPosition);
5267
5268 return targetPosition;
5269 }
5270
5271 @Override
5272 void onChildPositionChanged(WindowContainer child) {
5273 if (!mChildren.contains(child)) {
5274 return;
5275 }
5276
5277 final Task task = (Task) child;
5278 final boolean isTop = getTopChild() == task;
5279 task.updateTaskMovement(isTop);
5280 if (isTop) {
5281 final DisplayContent displayContent = getDisplayContent();
Louis Changdc077272019-11-12 16:52:56 +08005282 displayContent.layoutAndAssignWindowLayersIfNeeded();
5283 }
5284 }
5285
5286 // TODO(display-unify): Remove after display unification.
5287 protected void onParentChanged(ActivityDisplay newParent, ActivityDisplay oldParent) {
5288 onParentChanged(
5289 newParent != null ? newParent.mDisplayContent : null,
5290 oldParent != null ? oldParent.mDisplayContent : null);
5291 }
5292
5293 @Override
5294 protected void onParentChanged(
5295 ConfigurationContainer newParent, ConfigurationContainer oldParent) {
5296 final ActivityDisplay display = newParent != null
5297 ? ((WindowContainer) newParent).getDisplayContent().mActivityDisplay : null;
5298 final ActivityDisplay oldDisplay = oldParent != null
5299 ? ((WindowContainer) oldParent).getDisplayContent().mActivityDisplay : null;
5300
5301 mDisplayId = (display != null) ? display.mDisplayId : INVALID_DISPLAY;
5302 mPrevDisplayId = (oldDisplay != null) ? oldDisplay.mDisplayId : INVALID_DISPLAY;
5303
5304 if (display != null) {
5305 // Rotations are relative to the display. This means if there are 2 displays rotated
5306 // differently (eg. 2 monitors with one landscape and one portrait), moving a stack
5307 // from one to the other could look like a rotation change. To prevent this
5308 // apparent rotation change (and corresponding bounds rotation), pretend like our
5309 // current rotation is already the same as the new display.
5310 // Note, if ActivityStack or related logic ever gets nested, this logic will need
5311 // to move to onConfigurationChanged.
5312 getConfiguration().windowConfiguration.setRotation(
5313 display.getWindowConfiguration().getRotation());
5314 }
5315 super.onParentChanged(newParent, oldParent);
5316 if (getParent() == null && mDisplayContent != null) {
5317 EventLog.writeEvent(com.android.server.EventLogTags.WM_STACK_REMOVED, mStackId);
5318
5319 mDisplayContent = null;
5320 mWmService.mWindowPlacerLocked.requestTraversal();
5321 }
5322 if (display != null && inSplitScreenPrimaryWindowingMode()) {
5323 // If we created a docked stack we want to resize it so it resizes all other stacks
5324 // in the system.
5325 getStackDockedModeBounds(null /* dockedBounds */, null /* currentTempTaskBounds */,
5326 mTmpRect /* outStackBounds */, mTmpRect2 /* outTempTaskBounds */);
5327 mStackSupervisor.resizeDockedStackLocked(getRequestedOverrideBounds(), mTmpRect,
5328 mTmpRect2, null, null, PRESERVE_WINDOWS);
5329 }
5330 mRootActivityContainer.updateUIDsPresentOnDisplay();
5331
5332 // Resume next focusable stack after reparenting to another display if we aren't removing
5333 // the prevous display.
5334 if (oldDisplay != null && oldDisplay.isRemoving()) {
5335 postReparent();
5336 }
5337 }
5338
5339 void reparent(DisplayContent newParent, boolean onTop) {
5340 // Real parent of stack is within display object, so we have to delegate re-parenting there.
5341 newParent.moveStackToDisplay(this, onTop);
5342 }
5343
5344 // TODO: We should really have users as a window container in the hierarchy so that we don't
5345 // have to do complicated things like we are doing in this method.
5346 int findPositionForTask(Task task, int targetPosition, boolean showForAllUsers) {
5347 final boolean canShowTask =
5348 showForAllUsers || mWmService.isCurrentProfileLocked(task.mUserId);
5349
5350 final int stackSize = mChildren.size();
5351 int minPosition = 0;
5352 int maxPosition = stackSize - 1;
5353
5354 if (canShowTask) {
5355 minPosition = computeMinPosition(minPosition, stackSize);
5356 } else {
5357 maxPosition = computeMaxPosition(maxPosition);
5358 }
5359
5360 // preserve POSITION_BOTTOM/POSITION_TOP positions if they are still valid.
5361 if (targetPosition == POSITION_BOTTOM && minPosition == 0) {
5362 return POSITION_BOTTOM;
5363 } else if (targetPosition == POSITION_TOP && maxPosition == (stackSize - 1)) {
5364 return POSITION_TOP;
5365 }
5366 // Reset position based on minimum/maximum possible positions.
5367 return Math.min(Math.max(targetPosition, minPosition), maxPosition);
5368 }
5369
5370 /** Calculate the minimum possible position for a task that can be shown to the user.
5371 * The minimum position will be above all other tasks that can't be shown.
5372 * @param minPosition The minimum position the caller is suggesting.
5373 * We will start adjusting up from here.
5374 * @param size The size of the current task list.
5375 */
5376 private int computeMinPosition(int minPosition, int size) {
5377 while (minPosition < size) {
5378 final Task tmpTask = mChildren.get(minPosition);
5379 final boolean canShowTmpTask =
5380 tmpTask.showForAllUsers()
5381 || mWmService.isCurrentProfileLocked(tmpTask.mUserId);
5382 if (canShowTmpTask) {
5383 break;
5384 }
5385 minPosition++;
5386 }
5387 return minPosition;
5388 }
5389
5390 /** Calculate the maximum possible position for a task that can't be shown to the user.
5391 * The maximum position will be below all other tasks that can be shown.
5392 * @param maxPosition The maximum position the caller is suggesting.
5393 * We will start adjusting down from here.
5394 */
5395 private int computeMaxPosition(int maxPosition) {
5396 while (maxPosition > 0) {
5397 final Task tmpTask = mChildren.get(maxPosition);
5398 final boolean canShowTmpTask =
5399 tmpTask.showForAllUsers()
5400 || mWmService.isCurrentProfileLocked(tmpTask.mUserId);
5401 if (!canShowTmpTask) {
5402 break;
5403 }
5404 maxPosition--;
5405 }
5406 return maxPosition;
5407 }
5408
5409 private void updateSurfaceBounds() {
5410 updateSurfaceSize(getPendingTransaction());
5411 updateSurfacePosition();
5412 scheduleAnimation();
5413 }
5414
5415 /**
5416 * Calculate an amount by which to expand the stack bounds in each direction.
5417 * Used to make room for shadows in the pinned windowing mode.
5418 */
5419 int getStackOutset() {
5420 DisplayContent displayContent = getDisplayContent();
5421 if (inPinnedWindowingMode() && displayContent != null) {
5422 final DisplayMetrics displayMetrics = displayContent.getDisplayMetrics();
5423
5424 // We multiply by two to match the client logic for converting view elevation
5425 // to insets, as in {@link WindowManager.LayoutParams#setSurfaceInsets}
5426 return (int) Math.ceil(
5427 mWmService.dipToPixel(PINNED_WINDOWING_MODE_ELEVATION_IN_DIP, displayMetrics)
5428 * 2);
5429 }
5430 return 0;
5431 }
5432
5433 @Override
5434 void getRelativeDisplayedPosition(Point outPos) {
5435 super.getRelativeDisplayedPosition(outPos);
5436 final int outset = getStackOutset();
5437 outPos.x -= outset;
5438 outPos.y -= outset;
5439 }
5440
5441 private void updateSurfaceSize(SurfaceControl.Transaction transaction) {
5442 if (mSurfaceControl == null) {
5443 return;
5444 }
5445
5446 final Rect stackBounds = getDisplayedBounds();
5447 int width = stackBounds.width();
5448 int height = stackBounds.height();
5449
5450 final int outset = getStackOutset();
5451 width += 2 * outset;
5452 height += 2 * outset;
5453
5454 if (width == mLastSurfaceSize.x && height == mLastSurfaceSize.y) {
5455 return;
5456 }
5457 transaction.setWindowCrop(mSurfaceControl, width, height);
5458 mLastSurfaceSize.set(width, height);
5459 }
5460
5461 @VisibleForTesting
5462 Point getLastSurfaceSize() {
5463 return mLastSurfaceSize;
5464 }
5465
5466 @Override
5467 void onDisplayChanged(DisplayContent dc) {
5468 super.onDisplayChanged(dc);
5469 updateSurfaceBounds();
5470 }
5471
5472 /**
5473 * Determines the stack and task bounds of the other stack when in docked mode. The current task
5474 * bounds is passed in but depending on the stack, the task and stack must match. Only in
5475 * minimized mode with resizable launcher, the other stack ignores calculating the stack bounds
5476 * and uses the task bounds passed in as the stack and task bounds, otherwise the stack bounds
5477 * is calculated and is also used for its task bounds.
5478 * If any of the out bounds are empty, it represents default bounds
5479 *
5480 * @param currentTempTaskBounds the current task bounds of the other stack
5481 * @param outStackBounds the calculated stack bounds of the other stack
5482 * @param outTempTaskBounds the calculated task bounds of the other stack
5483 */
5484 void getStackDockedModeBounds(Rect dockedBounds,
5485 Rect currentTempTaskBounds, Rect outStackBounds, Rect outTempTaskBounds) {
5486 final Configuration parentConfig = getParent().getConfiguration();
5487 outTempTaskBounds.setEmpty();
5488
5489 if (dockedBounds == null || dockedBounds.isEmpty()) {
5490 // Calculate the primary docked bounds.
5491 final boolean dockedOnTopOrLeft = mWmService.mDockedStackCreateMode
5492 == SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
5493 getStackDockedModeBounds(parentConfig,
5494 true /* primary */, outStackBounds, dockedBounds,
5495 mDisplayContent.mDividerControllerLocked.getContentWidth(), dockedOnTopOrLeft);
5496 return;
5497 }
5498 final int dockedSide = getDockSide(parentConfig, dockedBounds);
5499
5500 // When the home stack is resizable, should always have the same stack and task bounds
5501 if (isActivityTypeHome()) {
5502 final Task homeTask = findHomeTask();
5503 if (homeTask == null || homeTask.isResizeable()) {
5504 // Calculate the home stack bounds when in docked mode and the home stack is
5505 // resizeable.
5506 getDisplayContent().mDividerControllerLocked
5507 .getHomeStackBoundsInDockedMode(parentConfig,
5508 dockedSide, outStackBounds);
5509 } else {
5510 // Home stack isn't resizeable, so don't specify stack bounds.
5511 outStackBounds.setEmpty();
5512 }
5513
5514 outTempTaskBounds.set(outStackBounds);
5515 return;
5516 }
5517
5518 // When minimized state, the stack bounds for all non-home and docked stack bounds should
5519 // match the passed task bounds
5520 if (isMinimizedDockAndHomeStackResizable() && currentTempTaskBounds != null) {
5521 outStackBounds.set(currentTempTaskBounds);
5522 return;
5523 }
5524
5525 if (dockedSide == DOCKED_INVALID) {
5526 // Not sure how you got here...Only thing we can do is return current bounds.
5527 Slog.e(TAG_WM, "Failed to get valid docked side for docked stack");
5528 outStackBounds.set(getRawBounds());
5529 return;
5530 }
5531
5532 final boolean dockedOnTopOrLeft = dockedSide == DOCKED_TOP || dockedSide == DOCKED_LEFT;
5533 getStackDockedModeBounds(parentConfig,
5534 false /* primary */, outStackBounds, dockedBounds,
5535 mDisplayContent.mDividerControllerLocked.getContentWidth(), dockedOnTopOrLeft);
5536 }
5537
5538 /**
5539 * Outputs the bounds a stack should be given the presence of a docked stack on the display.
5540 * @param parentConfig The parent configuration.
5541 * @param primary {@code true} if getting the primary stack bounds.
5542 * @param outBounds Output bounds that should be used for the stack.
5543 * @param dockedBounds Bounds of the docked stack.
5544 * @param dockDividerWidth We need to know the width of the divider make to the output bounds
5545 * close to the side of the dock.
5546 * @param dockOnTopOrLeft If the docked stack is on the top or left side of the screen.
5547 */
5548 private void getStackDockedModeBounds(Configuration parentConfig, boolean primary,
5549 Rect outBounds, Rect dockedBounds, int dockDividerWidth,
5550 boolean dockOnTopOrLeft) {
5551 final Rect displayRect = parentConfig.windowConfiguration.getBounds();
5552 final boolean splitHorizontally = displayRect.width() > displayRect.height();
5553
5554 outBounds.set(displayRect);
5555 if (primary) {
5556 if (mWmService.mDockedStackCreateBounds != null) {
5557 outBounds.set(mWmService.mDockedStackCreateBounds);
5558 return;
5559 }
5560
5561 // The initial bounds of the docked stack when it is created about half the screen space
5562 // and its bounds can be adjusted after that. The bounds of all other stacks are
5563 // adjusted to occupy whatever screen space the docked stack isn't occupying.
5564 final DisplayCutout displayCutout = mDisplayContent.getDisplayInfo().displayCutout;
5565 mDisplayContent.getDisplayPolicy().getStableInsetsLw(
5566 parentConfig.windowConfiguration.getRotation(),
5567 displayRect.width(), displayRect.height(), displayCutout, mTmpRect2);
5568 final int position = new DividerSnapAlgorithm(mWmService.mContext.getResources(),
5569 displayRect.width(),
5570 displayRect.height(),
5571 dockDividerWidth,
5572 parentConfig.orientation == ORIENTATION_PORTRAIT,
5573 mTmpRect2).getMiddleTarget().position;
5574
5575 if (dockOnTopOrLeft) {
5576 if (splitHorizontally) {
5577 outBounds.right = position;
5578 } else {
5579 outBounds.bottom = position;
5580 }
5581 } else {
5582 if (splitHorizontally) {
5583 outBounds.left = position + dockDividerWidth;
5584 } else {
5585 outBounds.top = position + dockDividerWidth;
5586 }
5587 }
5588 return;
5589 }
5590
5591 // Other stacks occupy whatever space is left by the docked stack.
5592 if (!dockOnTopOrLeft) {
5593 if (splitHorizontally) {
5594 outBounds.right = dockedBounds.left - dockDividerWidth;
5595 } else {
5596 outBounds.bottom = dockedBounds.top - dockDividerWidth;
5597 }
5598 } else {
5599 if (splitHorizontally) {
5600 outBounds.left = dockedBounds.right + dockDividerWidth;
5601 } else {
5602 outBounds.top = dockedBounds.bottom + dockDividerWidth;
5603 }
5604 }
5605 DockedDividerUtils.sanitizeStackBounds(outBounds, !dockOnTopOrLeft);
5606 }
5607
5608 void resetDockedStackToMiddle() {
5609 if (!inSplitScreenPrimaryWindowingMode()) {
5610 throw new IllegalStateException("Not a docked stack=" + this);
5611 }
5612
5613 mWmService.mDockedStackCreateBounds = null;
5614
5615 final Rect bounds = new Rect();
5616 final Rect tempBounds = new Rect();
5617 getStackDockedModeBounds(null /* dockedBounds */, null /* currentTempTaskBounds */,
5618 bounds, tempBounds);
5619 mStackSupervisor.resizeDockedStackLocked(bounds, null /* tempTaskBounds */,
5620 null /* tempTaskInsetBounds */, null /* tempOtherTaskBounds */,
5621 null /* tempOtherTaskInsetBounds */, false /* preserveWindows */,
5622 false /* deferResume */);
5623 }
5624
5625 @Override
5626 void removeIfPossible() {
5627 if (isAnimating(TRANSITION | CHILDREN)) {
5628 mDeferRemoval = true;
5629 return;
5630 }
5631 removeImmediately();
5632 }
5633
5634 /**
5635 * Adjusts the stack bounds if the IME is visible.
5636 *
5637 * @param imeWin The IME window.
5638 * @param keepLastAmount Use {@code true} to keep the last adjusted amount from
5639 * {@link DockedStackDividerController} for adjusting the stack bounds,
5640 * Use {@code false} to reset adjusted amount as 0.
5641 * @see #updateAdjustForIme(float, float, boolean)
5642 */
5643 void setAdjustedForIme(WindowState imeWin, boolean keepLastAmount) {
5644 mImeWin = imeWin;
5645 mImeGoingAway = false;
5646 if (!mAdjustedForIme || keepLastAmount) {
5647 mAdjustedForIme = true;
5648 DockedStackDividerController controller = getDisplayContent().mDividerControllerLocked;
5649 final float adjustImeAmount = keepLastAmount ? controller.mLastAnimationProgress : 0f;
5650 final float adjustDividerAmount = keepLastAmount ? controller.mLastDividerProgress : 0f;
5651 updateAdjustForIme(adjustImeAmount, adjustDividerAmount, true /* force */);
5652 }
5653 }
5654
5655 boolean isAdjustedForIme() {
5656 return mAdjustedForIme;
5657 }
5658
5659 boolean isAnimatingForIme() {
5660 return mImeWin != null && mImeWin.isAnimatingLw();
5661 }
5662
5663 /**
5664 * Update the stack's bounds (crop or position) according to the IME window's
5665 * current position. When IME window is animated, the bottom stack is animated
5666 * together to track the IME window's current position, and the top stack is
5667 * cropped as necessary.
5668 *
5669 * @return true if a traversal should be performed after the adjustment.
5670 */
5671 boolean updateAdjustForIme(float adjustAmount, float adjustDividerAmount, boolean force) {
5672 if (adjustAmount != mAdjustImeAmount
5673 || adjustDividerAmount != mAdjustDividerAmount || force) {
5674 mAdjustImeAmount = adjustAmount;
5675 mAdjustDividerAmount = adjustDividerAmount;
5676 updateAdjustedBounds();
5677 return isVisible();
5678 } else {
5679 return false;
5680 }
5681 }
5682
5683 /**
5684 * Resets the adjustment after it got adjusted for the IME.
5685 * @param adjustBoundsNow if true, reset and update the bounds immediately and forget about
5686 * animations; otherwise, set flag and animates the window away together
5687 * with IME window.
5688 */
5689 void resetAdjustedForIme(boolean adjustBoundsNow) {
5690 if (adjustBoundsNow) {
5691 mImeWin = null;
5692 mImeGoingAway = false;
5693 mAdjustImeAmount = 0f;
5694 mAdjustDividerAmount = 0f;
5695 if (!mAdjustedForIme) {
5696 return;
5697 }
5698 mAdjustedForIme = false;
5699 updateAdjustedBounds();
5700 mWmService.setResizeDimLayer(false, getWindowingMode(), 1.0f);
5701 } else {
5702 mImeGoingAway |= mAdjustedForIme;
5703 }
5704 }
5705
5706 /**
5707 * Sets the amount how much we currently minimize our stack.
5708 *
5709 * @param minimizeAmount The amount, between 0 and 1.
5710 * @return Whether the amount has changed and a layout is needed.
5711 */
5712 boolean setAdjustedForMinimizedDock(float minimizeAmount) {
5713 if (minimizeAmount != mMinimizeAmount) {
5714 mMinimizeAmount = minimizeAmount;
5715 updateAdjustedBounds();
5716 return isVisible();
5717 } else {
5718 return false;
5719 }
5720 }
5721
5722 boolean shouldIgnoreInput() {
5723 return isAdjustedForMinimizedDockedStack()
5724 || (inSplitScreenPrimaryWindowingMode() && isMinimizedDockAndHomeStackResizable());
5725 }
5726
5727 /**
5728 * Puts all visible tasks that are adjusted for IME into resizing mode and adds the windows
5729 * to the list of to be drawn windows the service is waiting for.
5730 */
5731 void beginImeAdjustAnimation() {
5732 for (int j = mChildren.size() - 1; j >= 0; j--) {
5733 final Task task = mChildren.get(j);
5734 if (task.hasContentToDisplay()) {
5735 task.setDragResizing(true, DRAG_RESIZE_MODE_DOCKED_DIVIDER);
5736 task.setWaitingForDrawnIfResizingChanged();
5737 }
5738 }
5739 }
5740
5741 /**
5742 * Resets the resizing state of all windows.
5743 */
5744 void endImeAdjustAnimation() {
5745 for (int j = mChildren.size() - 1; j >= 0; j--) {
5746 mChildren.get(j).setDragResizing(false, DRAG_RESIZE_MODE_DOCKED_DIVIDER);
5747 }
5748 }
5749
5750 int getMinTopStackBottom(final Rect displayContentRect, int originalStackBottom) {
5751 return displayContentRect.top + (int)
5752 ((originalStackBottom - displayContentRect.top) * ADJUSTED_STACK_FRACTION_MIN);
5753 }
5754
5755 private boolean adjustForIME(final WindowState imeWin) {
5756 // To prevent task stack resize animation may flicking when playing app transition
5757 // animation & IME window enter animation in parallel, we need to make sure app
5758 // transition is done and then adjust task size for IME, skip the new adjusted frame when
5759 // app transition is still running.
5760 if (getDisplayContent().mAppTransition.isRunning()) {
5761 return false;
5762 }
5763
5764 final int dockedSide = getDockSide();
5765 final boolean dockedTopOrBottom = dockedSide == DOCKED_TOP || dockedSide == DOCKED_BOTTOM;
5766 if (imeWin == null || !dockedTopOrBottom) {
5767 return false;
5768 }
5769
5770 final Rect displayStableRect = mTmpRect;
5771 final Rect contentBounds = mTmpRect2;
5772
5773 // Calculate the content bounds excluding the area occupied by IME
5774 getDisplayContent().getStableRect(displayStableRect);
5775 contentBounds.set(displayStableRect);
5776 int imeTop = Math.max(imeWin.getFrameLw().top, contentBounds.top);
5777
5778 imeTop += imeWin.getGivenContentInsetsLw().top;
5779 if (contentBounds.bottom > imeTop) {
5780 contentBounds.bottom = imeTop;
5781 }
5782
5783 final int yOffset = displayStableRect.bottom - contentBounds.bottom;
5784
5785 final int dividerWidth =
5786 getDisplayContent().mDividerControllerLocked.getContentWidth();
5787 final int dividerWidthInactive =
5788 getDisplayContent().mDividerControllerLocked.getContentWidthInactive();
5789
5790 if (dockedSide == DOCKED_TOP) {
5791 // If this stack is docked on top, we make it smaller so the bottom stack is not
5792 // occluded by IME. We shift its bottom up by the height of the IME, but
5793 // leaves at least 30% of the top stack visible.
5794 final int minTopStackBottom =
5795 getMinTopStackBottom(displayStableRect, getRawBounds().bottom);
5796 final int bottom = Math.max(
5797 getRawBounds().bottom - yOffset + dividerWidth - dividerWidthInactive,
5798 minTopStackBottom);
5799 mTmpAdjustedBounds.set(getRawBounds());
5800 mTmpAdjustedBounds.bottom = (int) (mAdjustImeAmount * bottom + (1 - mAdjustImeAmount)
5801 * getRawBounds().bottom);
5802 mFullyAdjustedImeBounds.set(getRawBounds());
5803 } else {
5804 // When the stack is on bottom and has no focus, it's only adjusted for divider width.
5805 final int dividerWidthDelta = dividerWidthInactive - dividerWidth;
5806
5807 // When the stack is on bottom and has focus, it needs to be moved up so as to
5808 // not occluded by IME, and at the same time adjusted for divider width.
5809 // We try to move it up by the height of the IME window, but only to the extent
5810 // that leaves at least 30% of the top stack visible.
5811 // 'top' is where the top of bottom stack will move to in this case.
5812 final int topBeforeImeAdjust =
5813 getRawBounds().top - dividerWidth + dividerWidthInactive;
5814 final int minTopStackBottom =
5815 getMinTopStackBottom(displayStableRect,
5816 getRawBounds().top - dividerWidth);
5817 final int top = Math.max(
5818 getRawBounds().top - yOffset, minTopStackBottom + dividerWidthInactive);
5819
5820 mTmpAdjustedBounds.set(getRawBounds());
5821 // Account for the adjustment for IME and divider width separately.
5822 // (top - topBeforeImeAdjust) is the amount of movement due to IME only,
5823 // and dividerWidthDelta is due to divider width change only.
5824 mTmpAdjustedBounds.top =
5825 getRawBounds().top + (int) (mAdjustImeAmount * (top - topBeforeImeAdjust)
5826 + mAdjustDividerAmount * dividerWidthDelta);
5827 mFullyAdjustedImeBounds.set(getRawBounds());
5828 mFullyAdjustedImeBounds.top = top;
5829 mFullyAdjustedImeBounds.bottom = top + getRawBounds().height();
5830 }
5831 return true;
5832 }
5833
5834 private boolean adjustForMinimizedDockedStack(float minimizeAmount) {
5835 final int dockSide = getDockSide();
5836 if (dockSide == DOCKED_INVALID && !mTmpAdjustedBounds.isEmpty()) {
5837 return false;
5838 }
5839
5840 if (dockSide == DOCKED_TOP) {
5841 mWmService.getStableInsetsLocked(DEFAULT_DISPLAY, mTmpRect);
5842 int topInset = mTmpRect.top;
5843 mTmpAdjustedBounds.set(getRawBounds());
5844 mTmpAdjustedBounds.bottom = (int) (minimizeAmount * topInset + (1 - minimizeAmount)
5845 * getRawBounds().bottom);
5846 } else if (dockSide == DOCKED_LEFT) {
5847 mTmpAdjustedBounds.set(getRawBounds());
5848 final int width = getRawBounds().width();
5849 mTmpAdjustedBounds.right =
5850 (int) (minimizeAmount * mDockedStackMinimizeThickness
5851 + (1 - minimizeAmount) * getRawBounds().right);
5852 mTmpAdjustedBounds.left = mTmpAdjustedBounds.right - width;
5853 } else if (dockSide == DOCKED_RIGHT) {
5854 mTmpAdjustedBounds.set(getRawBounds());
5855 mTmpAdjustedBounds.left =
5856 (int) (minimizeAmount * (getRawBounds().right - mDockedStackMinimizeThickness)
5857 + (1 - minimizeAmount) * getRawBounds().left);
5858 }
5859 return true;
5860 }
5861
5862 private boolean isMinimizedDockAndHomeStackResizable() {
5863 return mDisplayContent.mDividerControllerLocked.isMinimizedDock()
5864 && mDisplayContent.mDividerControllerLocked.isHomeStackResizable();
5865 }
5866
5867 /**
5868 * @return the distance in pixels how much the stack gets minimized from it's original size
5869 */
5870 int getMinimizeDistance() {
5871 final int dockSide = getDockSide();
5872 if (dockSide == DOCKED_INVALID) {
5873 return 0;
5874 }
5875
5876 if (dockSide == DOCKED_TOP) {
5877 mWmService.getStableInsetsLocked(DEFAULT_DISPLAY, mTmpRect);
5878 int topInset = mTmpRect.top;
5879 return getRawBounds().bottom - topInset;
5880 } else if (dockSide == DOCKED_LEFT || dockSide == DOCKED_RIGHT) {
5881 return getRawBounds().width() - mDockedStackMinimizeThickness;
5882 } else {
5883 return 0;
5884 }
5885 }
5886
5887 /**
5888 * Updates the adjustment depending on it's current state.
5889 */
5890 private void updateAdjustedBounds() {
5891 boolean adjust = false;
5892 if (mMinimizeAmount != 0f) {
5893 adjust = adjustForMinimizedDockedStack(mMinimizeAmount);
5894 } else if (mAdjustedForIme) {
5895 adjust = adjustForIME(mImeWin);
5896 }
5897 if (!adjust) {
5898 mTmpAdjustedBounds.setEmpty();
5899 }
5900 setAdjustedBounds(mTmpAdjustedBounds);
5901
5902 final boolean isImeTarget = (mWmService.getImeFocusStackLocked() == this);
5903 if (mAdjustedForIme && adjust && !isImeTarget) {
5904 final float alpha = Math.max(mAdjustImeAmount, mAdjustDividerAmount)
5905 * IME_ADJUST_DIM_AMOUNT;
5906 mWmService.setResizeDimLayer(true, getWindowingMode(), alpha);
5907 }
5908 }
5909
5910 void applyAdjustForImeIfNeeded(Task task) {
5911 if (mMinimizeAmount != 0f || !mAdjustedForIme || mAdjustedBounds.isEmpty()) {
5912 return;
5913 }
5914
5915 final Rect insetBounds = mImeGoingAway ? getRawBounds() : mFullyAdjustedImeBounds;
5916 task.alignToAdjustedBounds(mAdjustedBounds, insetBounds, getDockSide() == DOCKED_TOP);
5917 mDisplayContent.setLayoutNeeded();
5918 }
5919
5920
5921 boolean isAdjustedForMinimizedDockedStack() {
5922 return mMinimizeAmount != 0f;
5923 }
5924
5925 /**
5926 * @return {@code true} if we have a {@link Task} that is animating (currently only used for the
5927 * recents animation); {@code false} otherwise.
5928 */
5929 boolean isTaskAnimating() {
5930 for (int j = mChildren.size() - 1; j >= 0; j--) {
5931 final Task task = mChildren.get(j);
5932 if (task.isTaskAnimating()) {
5933 return true;
5934 }
5935 }
5936 return false;
5937 }
5938
5939 @Override
5940 void dump(PrintWriter pw, String prefix, boolean dumpAll) {
5941 pw.println(prefix + "mStackId=" + mStackId);
5942 pw.println(prefix + "mDeferRemoval=" + mDeferRemoval);
5943 pw.println(prefix + "mBounds=" + getRawBounds().toShortString());
5944 if (mMinimizeAmount != 0f) {
5945 pw.println(prefix + "mMinimizeAmount=" + mMinimizeAmount);
5946 }
5947 if (mAdjustedForIme) {
5948 pw.println(prefix + "mAdjustedForIme=true");
5949 pw.println(prefix + "mAdjustImeAmount=" + mAdjustImeAmount);
5950 pw.println(prefix + "mAdjustDividerAmount=" + mAdjustDividerAmount);
5951 }
5952 if (!mAdjustedBounds.isEmpty()) {
5953 pw.println(prefix + "mAdjustedBounds=" + mAdjustedBounds.toShortString());
5954 }
5955 for (int taskNdx = mChildren.size() - 1; taskNdx >= 0; taskNdx--) {
5956 mChildren.get(taskNdx).dump(pw, prefix + " ", dumpAll);
5957 }
5958 if (!mExitingActivities.isEmpty()) {
5959 pw.println();
5960 pw.println(" Exiting application tokens:");
5961 for (int i = mExitingActivities.size() - 1; i >= 0; i--) {
5962 WindowToken token = mExitingActivities.get(i);
5963 pw.print(" Exiting App #"); pw.print(i);
5964 pw.print(' '); pw.print(token);
5965 pw.println(':');
5966 token.dump(pw, " ", dumpAll);
5967 }
5968 }
5969 mAnimatingActivityRegistry.dump(pw, "AnimatingApps:", prefix);
5970 }
5971
5972 @Override
5973 boolean fillsParent() {
5974 return matchParentBounds();
5975 }
5976
5977 String getName() {
5978 return toShortString();
5979 }
5980
5981 public String toShortString() {
5982 return "Stack=" + mStackId;
5983 }
5984
5985 /**
5986 * For docked workspace (or workspace that's side-by-side to the docked), provides
5987 * information which side of the screen was the dock anchored.
5988 */
5989 int getDockSide() {
5990 return getDockSide(mDisplayContent.getConfiguration(), getRawBounds());
5991 }
5992
5993 int getDockSideForDisplay(DisplayContent dc) {
5994 return getDockSide(dc, dc.getConfiguration(), getRawBounds());
5995 }
5996
5997 int getDockSide(Configuration parentConfig, Rect bounds) {
5998 if (mDisplayContent == null) {
5999 return DOCKED_INVALID;
6000 }
6001 return getDockSide(mDisplayContent, parentConfig, bounds);
6002 }
6003
6004 private int getDockSide(DisplayContent dc, Configuration parentConfig, Rect bounds) {
6005 return dc.getDockedDividerController().getDockSide(bounds,
6006 parentConfig.windowConfiguration.getBounds(),
6007 parentConfig.orientation, parentConfig.windowConfiguration.getRotation());
6008 }
6009
6010 boolean hasTaskForUser(int userId) {
6011 for (int i = mChildren.size() - 1; i >= 0; i--) {
6012 final Task task = mChildren.get(i);
6013 if (task.mUserId == userId) {
6014 return true;
6015 }
6016 }
6017 return false;
6018 }
6019
6020 void findTaskForResizePoint(int x, int y, int delta,
6021 DisplayContent.TaskForResizePointSearchResult results) {
6022 if (!getWindowConfiguration().canResizeTask()) {
6023 results.searchDone = true;
6024 return;
6025 }
6026
6027 for (int i = mChildren.size() - 1; i >= 0; --i) {
6028 final Task task = mChildren.get(i);
6029 if (task.getWindowingMode() == WINDOWING_MODE_FULLSCREEN) {
6030 results.searchDone = true;
6031 return;
6032 }
6033
6034 // We need to use the task's dim bounds (which is derived from the visible bounds of
6035 // its apps windows) for any touch-related tests. Can't use the task's original
6036 // bounds because it might be adjusted to fit the content frame. One example is when
6037 // the task is put to top-left quadrant, the actual visible area would not start at
6038 // (0,0) after it's adjusted for the status bar.
6039 task.getDimBounds(mTmpRect);
6040 mTmpRect.inset(-delta, -delta);
6041 if (mTmpRect.contains(x, y)) {
6042 mTmpRect.inset(delta, delta);
6043
6044 results.searchDone = true;
6045
6046 if (!mTmpRect.contains(x, y)) {
6047 results.taskForResize = task;
6048 return;
6049 }
6050 // User touched inside the task. No need to look further,
6051 // focus transfer will be handled in ACTION_UP.
6052 return;
6053 }
6054 }
6055 }
6056
6057 void setTouchExcludeRegion(Task focusedTask, int delta, Region touchExcludeRegion,
6058 Rect contentRect, Rect postExclude) {
6059 for (int i = mChildren.size() - 1; i >= 0; --i) {
6060 final Task task = mChildren.get(i);
6061 ActivityRecord topVisibleActivity = task.getTopVisibleActivity();
6062 if (topVisibleActivity == null || !topVisibleActivity.hasContentToDisplay()) {
6063 continue;
6064 }
6065
6066 /**
6067 * Exclusion region is the region that TapDetector doesn't care about.
6068 * Here we want to remove all non-focused tasks from the exclusion region.
6069 * We also remove the outside touch area for resizing for all freeform
6070 * tasks (including the focused).
6071 *
6072 * We save the focused task region once we find it, and add it back at the end.
6073 *
6074 * If the task is home stack and it is resizable in the minimized state, we want to
6075 * exclude the docked stack from touch so we need the entire screen area and not just a
6076 * small portion which the home stack currently is resized to.
6077 */
6078
6079 if (task.isActivityTypeHome() && isMinimizedDockAndHomeStackResizable()) {
6080 mDisplayContent.getBounds(mTmpRect);
6081 } else {
6082 task.getDimBounds(mTmpRect);
6083 }
6084
6085 if (task == focusedTask) {
6086 // Add the focused task rect back into the exclude region once we are done
6087 // processing stacks.
6088 postExclude.set(mTmpRect);
6089 }
6090
6091 final boolean isFreeformed = task.inFreeformWindowingMode();
6092 if (task != focusedTask || isFreeformed) {
6093 if (isFreeformed) {
6094 // If the task is freeformed, enlarge the area to account for outside
6095 // touch area for resize.
6096 mTmpRect.inset(-delta, -delta);
6097 // Intersect with display content rect. If we have system decor (status bar/
6098 // navigation bar), we want to exclude that from the tap detection.
6099 // Otherwise, if the app is partially placed under some system button (eg.
6100 // Recents, Home), pressing that button would cause a full series of
6101 // unwanted transfer focus/resume/pause, before we could go home.
6102 mTmpRect.intersect(contentRect);
6103 }
6104 touchExcludeRegion.op(mTmpRect, Region.Op.DIFFERENCE);
6105 }
6106 }
6107 }
6108
6109 public boolean setPinnedStackSize(Rect stackBounds, Rect tempTaskBounds) {
6110 // Hold the lock since this is called from the BoundsAnimator running on the UiThread
6111 synchronized (mWmService.mGlobalLock) {
6112 if (mCancelCurrentBoundsAnimation) {
6113 return false;
6114 }
6115 }
6116
6117 try {
6118 mWmService.mActivityTaskManager.resizePinnedStack(stackBounds, tempTaskBounds);
6119 } catch (RemoteException e) {
6120 // I don't believe you.
6121 }
6122 return true;
6123 }
6124
6125 void onAllWindowsDrawn() {
6126 if (!mBoundsAnimating && !mBoundsAnimatingRequested) {
6127 return;
6128 }
6129
6130 getDisplayContent().mBoundsAnimationController.onAllWindowsDrawn();
6131 }
6132
6133 @Override // AnimatesBounds
6134 public boolean onAnimationStart(boolean schedulePipModeChangedCallback, boolean forceUpdate,
6135 @BoundsAnimationController.AnimationType int animationType) {
6136 // Hold the lock since this is called from the BoundsAnimator running on the UiThread
6137 synchronized (mWmService.mGlobalLock) {
6138 if (!isAttached()) {
6139 // Don't run the animation if the stack is already detached
6140 return false;
6141 }
6142
6143 if (animationType == BoundsAnimationController.BOUNDS) {
6144 mBoundsAnimatingRequested = false;
6145 mBoundsAnimating = true;
6146 }
6147 mAnimationType = animationType;
6148
6149 // If we are changing UI mode, as in the PiP to fullscreen
6150 // transition, then we need to wait for the window to draw.
6151 if (schedulePipModeChangedCallback) {
6152 forAllWindows((w) -> {
6153 w.mWinAnimator.resetDrawState();
6154 }, false /* traverseTopToBottom */);
6155 }
6156 }
6157
6158 if (inPinnedWindowingMode()) {
6159 try {
6160 mWmService.mActivityTaskManager.notifyPinnedStackAnimationStarted();
6161 } catch (RemoteException e) {
6162 // I don't believe you...
6163 }
6164
6165 if ((schedulePipModeChangedCallback || animationType == FADE_IN)) {
6166 // We need to schedule the PiP mode change before the animation up. It is possible
6167 // in this case for the animation down to not have been completed, so always
6168 // force-schedule and update to the client to ensure that it is notified that it
6169 // is no longer in picture-in-picture mode
6170 updatePictureInPictureModeForPinnedStackAnimation(null, forceUpdate);
6171 }
6172 }
6173 return true;
6174 }
6175
6176 @Override // AnimatesBounds
6177 public void onAnimationEnd(boolean schedulePipModeChangedCallback, Rect finalStackSize,
6178 boolean moveToFullscreen) {
6179 synchronized (mWmService.mGlobalLock) {
6180 if (inPinnedWindowingMode()) {
6181 // Update to the final bounds if requested. This is done here instead of in the
6182 // bounds animator to allow us to coordinate this after we notify the PiP mode
6183 // changed
6184
6185 if (schedulePipModeChangedCallback) {
6186 // We need to schedule the PiP mode change after the animation down, so use the
6187 // final bounds
6188 updatePictureInPictureModeForPinnedStackAnimation(mBoundsAnimationTarget,
6189 false /* forceUpdate */);
6190 }
6191
6192 if (mAnimationType == BoundsAnimationController.FADE_IN) {
6193 setPinnedStackAlpha(1f);
6194 mWmService.mAtmService.notifyPinnedStackAnimationEnded();
6195 return;
6196 }
6197
6198 if (finalStackSize != null && !mCancelCurrentBoundsAnimation) {
6199 setPinnedStackSize(finalStackSize, null);
6200 } else {
6201 // We have been canceled, so the final stack size is null, still run the
6202 // animation-end logic
6203 onPipAnimationEndResize();
6204 }
6205
6206 mWmService.mAtmService.notifyPinnedStackAnimationEnded();
6207 if (moveToFullscreen) {
6208 ((ActivityStack) this).dismissPip();
6209 }
6210 } else {
6211 // No PiP animation, just run the normal animation-end logic
6212 onPipAnimationEndResize();
6213 }
6214 }
6215 }
6216
6217 /**
6218 * Sets the current picture-in-picture aspect ratio.
6219 */
6220 void setPictureInPictureAspectRatio(float aspectRatio) {
6221 if (!mWmService.mAtmService.mSupportsPictureInPicture) {
6222 return;
6223 }
6224
6225 final DisplayContent displayContent = getDisplayContent();
6226 if (displayContent == null) {
6227 return;
6228 }
6229
6230 if (!inPinnedWindowingMode()) {
6231 return;
6232 }
6233
6234 final PinnedStackController pinnedStackController =
6235 getDisplayContent().getPinnedStackController();
6236
6237 if (Float.compare(aspectRatio, pinnedStackController.getAspectRatio()) == 0) {
6238 return;
6239 }
6240
6241 // Notify the pinned stack controller about aspect ratio change.
6242 // This would result a callback delivered from SystemUI to WM to start animation,
6243 // if the bounds are ought to be altered due to aspect ratio change.
6244 pinnedStackController.setAspectRatio(
6245 pinnedStackController.isValidPictureInPictureAspectRatio(aspectRatio)
6246 ? aspectRatio : -1f);
6247 }
6248
6249 /**
6250 * Sets the current picture-in-picture actions.
6251 */
6252 void setPictureInPictureActions(List<RemoteAction> actions) {
6253 if (!mWmService.mAtmService.mSupportsPictureInPicture) {
6254 return;
6255 }
6256
6257 if (!inPinnedWindowingMode()) {
6258 return;
6259 }
6260
6261 getDisplayContent().getPinnedStackController().setActions(actions);
6262 }
6263
6264 /** Called immediately prior to resizing the tasks at the end of the pinned stack animation. */
6265 void onPipAnimationEndResize() {
6266 mBoundsAnimating = false;
6267 for (int i = 0; i < mChildren.size(); i++) {
6268 final Task t = mChildren.get(i);
6269 t.clearPreserveNonFloatingState();
6270 }
6271 mWmService.requestTraversal();
6272 }
6273
6274 @Override
6275 public boolean shouldDeferStartOnMoveToFullscreen() {
6276 synchronized (mWmService.mGlobalLock) {
6277 if (!isAttached()) {
6278 // Unnecessary to pause the animation because the stack is detached.
6279 return false;
6280 }
6281
6282 // Workaround for the recents animation -- normally we need to wait for the new activity
6283 // to show before starting the PiP animation, but because we start and show the home
6284 // activity early for the recents animation prior to the PiP animation starting, there
6285 // is no subsequent all-drawn signal. In this case, we can skip the pause when the home
6286 // stack is already visible and drawn.
6287 final ActivityStack homeStack = mDisplayContent.getHomeStack();
6288 if (homeStack == null) {
6289 return true;
6290 }
6291 final Task homeTask = homeStack.getTopChild();
6292 if (homeTask == null) {
6293 return true;
6294 }
6295 final ActivityRecord homeApp = homeTask.getTopVisibleActivity();
6296 if (!homeTask.isVisible() || homeApp == null) {
6297 return true;
6298 }
6299 return !homeApp.allDrawn;
6300 }
6301 }
6302
6303 /**
6304 * @return True if we are currently animating the pinned stack from fullscreen to non-fullscreen
6305 * bounds and we have a deferred PiP mode changed callback set with the animation.
6306 */
6307 public boolean deferScheduleMultiWindowModeChanged() {
6308 if (inPinnedWindowingMode()) {
6309 // For the pinned stack, the deferring of the multi-window mode changed is tied to the
6310 // transition animation into picture-in-picture, and is called once the animation
6311 // completes, or is interrupted in a way that would leave the stack in a non-fullscreen
6312 // state.
6313 // @see BoundsAnimationController
6314 // @see BoundsAnimationControllerTests
6315 return (mBoundsAnimatingRequested || mBoundsAnimating);
6316 }
6317 return false;
6318 }
6319
6320 public boolean isForceScaled() {
6321 return mBoundsAnimating;
6322 }
6323
6324 public boolean isAnimatingBounds() {
6325 return mBoundsAnimating;
6326 }
6327
6328 public boolean lastAnimatingBoundsWasToFullscreen() {
6329 return mBoundsAnimatingToFullscreen;
6330 }
6331
6332 public boolean isAnimatingBoundsToFullscreen() {
6333 return isAnimatingBounds() && lastAnimatingBoundsWasToFullscreen();
6334 }
6335
6336 public boolean pinnedStackResizeDisallowed() {
6337 if (mBoundsAnimating && mCancelCurrentBoundsAnimation) {
6338 return true;
6339 }
6340 return false;
6341 }
6342
6343 /** Returns true if a removal action is still being deferred. */
6344 boolean checkCompleteDeferredRemoval() {
6345 if (isAnimating(TRANSITION | CHILDREN)) {
6346 return true;
6347 }
6348 if (mDeferRemoval) {
6349 removeImmediately();
6350 }
6351
6352 return super.checkCompleteDeferredRemoval();
6353 }
6354
6355 @Override
6356 int getOrientation() {
6357 return (canSpecifyOrientation()) ? super.getOrientation() : SCREEN_ORIENTATION_UNSET;
6358 }
6359
6360 private boolean canSpecifyOrientation() {
6361 final int windowingMode = getWindowingMode();
6362 final int activityType = getActivityType();
6363 return windowingMode == WINDOWING_MODE_FULLSCREEN
6364 || activityType == ACTIVITY_TYPE_HOME
6365 || activityType == ACTIVITY_TYPE_RECENTS
6366 || activityType == ACTIVITY_TYPE_ASSISTANT;
6367 }
6368
6369 @Override
6370 Dimmer getDimmer() {
6371 return mDimmer;
6372 }
6373
6374 @Override
6375 void prepareSurfaces() {
6376 mDimmer.resetDimStates();
6377 super.prepareSurfaces();
6378 getDimBounds(mTmpDimBoundsRect);
6379
6380 // Bounds need to be relative, as the dim layer is a child.
6381 mTmpDimBoundsRect.offsetTo(0, 0);
6382 if (mDimmer.updateDims(getPendingTransaction(), mTmpDimBoundsRect)) {
6383 scheduleAnimation();
6384 }
6385 }
6386
6387 @Override
6388 public boolean setPinnedStackAlpha(float alpha) {
6389 // Hold the lock since this is called from the BoundsAnimator running on the UiThread
6390 synchronized (mWmService.mGlobalLock) {
6391 final SurfaceControl sc = getSurfaceControl();
6392 if (sc == null || !sc.isValid()) {
6393 // If the stack is already removed, don't bother updating any stack animation
6394 return false;
6395 }
6396 getPendingTransaction().setAlpha(sc, mCancelCurrentBoundsAnimation ? 1 : alpha);
6397 scheduleAnimation();
6398 return !mCancelCurrentBoundsAnimation;
6399 }
6400 }
6401
6402 public DisplayInfo getDisplayInfo() {
6403 return mDisplayContent.getDisplayInfo();
6404 }
6405
6406 void dim(float alpha) {
6407 mDimmer.dimAbove(getPendingTransaction(), alpha);
6408 scheduleAnimation();
6409 }
6410
6411 void stopDimming() {
6412 mDimmer.stopDim(getPendingTransaction());
6413 scheduleAnimation();
6414 }
6415
6416 AnimatingActivityRegistry getAnimatingActivityRegistry() {
6417 return mAnimatingActivityRegistry;
6418 }
6419
6420 @Override
6421 void getAnimationFrames(Rect outFrame, Rect outInsets, Rect outStableInsets,
6422 Rect outSurfaceInsets) {
6423 final Task task = getTopChild();
6424 if (task != null) {
6425 task.getAnimationFrames(outFrame, outInsets, outStableInsets, outSurfaceInsets);
6426 } else {
6427 super.getAnimationFrames(outFrame, outInsets, outStableInsets, outSurfaceInsets);
6428 }
6429 }
6430
6431 @Override
6432 RemoteAnimationTarget createRemoteAnimationTarget(
6433 RemoteAnimationController.RemoteAnimationRecord record) {
6434 final Task task = getTopChild();
6435 return task != null ? task.createRemoteAnimationTarget(record) : null;
6436 }
6437
Craig Mautnerde4ef022013-04-07 19:01:33 -07006438 @Override
6439 public String toString() {
Dianne Hackborn2a272d42013-10-16 13:34:33 -07006440 return "ActivityStack{" + Integer.toHexString(System.identityHashCode(this))
Wale Ogunwale44f036f2017-09-29 05:09:09 -07006441 + " stackId=" + mStackId + " type=" + activityTypeToString(getActivityType())
Wale Ogunwale7e1f5f52017-10-18 15:19:59 -07006442 + " mode=" + windowingModeToString(getWindowingMode())
Wale Ogunwale8e923af2018-03-23 08:48:11 -07006443 + " visible=" + shouldBeVisible(null /* starting */)
6444 + " translucent=" + isStackTranslucent(null /* starting */)
6445 + ", "
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07006446 + getChildCount() + " tasks}";
Craig Mautnerde4ef022013-04-07 19:01:33 -07006447 }
Wale Ogunwale60454db2015-01-23 16:05:07 -08006448
Wale Ogunwalea0f5b5e2017-10-11 09:37:23 -07006449 void onLockTaskPackagesUpdated() {
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07006450 for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) {
6451 getChildAt(taskNdx).setLockTaskAuth();
Craig Mautner15df08a2015-04-01 12:17:18 -07006452 }
6453 }
skuhne@google.com1b974dc2016-12-09 13:41:29 -08006454
6455 void executeAppTransition(ActivityOptions options) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006456 getDisplay().mDisplayContent.executeAppTransition();
skuhne@google.com1b974dc2016-12-09 13:41:29 -08006457 ActivityOptions.abort(options);
6458 }
David Stevens9440dc82017-03-16 19:00:20 -07006459
6460 boolean shouldSleepActivities() {
Wale Ogunwale9dcf9462017-09-19 15:13:01 -07006461 final ActivityDisplay display = getDisplay();
Bryce Lee271617a2018-03-15 10:39:12 -07006462
6463 // Do not sleep activities in this stack if we're marked as focused and the keyguard
6464 // is in the process of going away.
Tiger Huang1e5b10a2018-07-30 20:19:51 +08006465 if (isFocusedStackOnDisplay()
Bryce Lee271617a2018-03-15 10:39:12 -07006466 && mStackSupervisor.getKeyguardController().isKeyguardGoingAway()) {
6467 return false;
6468 }
6469
Wale Ogunwalef6733932018-06-27 05:14:34 -07006470 return display != null ? display.isSleeping() : mService.isSleepingLocked();
David Stevens9440dc82017-03-16 19:00:20 -07006471 }
6472
6473 boolean shouldSleepOrShutDownActivities() {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006474 return shouldSleepActivities() || mService.mShuttingDown;
David Stevens9440dc82017-03-16 19:00:20 -07006475 }
Steven Timotius4346f0a2017-09-12 11:07:21 -07006476
Nataniel Borges023ecb52019-01-16 14:15:43 -08006477 public void writeToProto(ProtoOutputStream proto, long fieldId,
6478 @WindowTraceLogLevel int logLevel) {
Steven Timotius4346f0a2017-09-12 11:07:21 -07006479 final long token = proto.start(fieldId);
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07006480 writeToProtoInnerStackOnly(proto, STACK, logLevel);
Louis Changdc077272019-11-12 16:52:56 +08006481 proto.write(com.android.server.am.ActivityStackProto.ID, mStackId);
Wale Ogunwale2187b7c2019-10-26 21:38:43 -07006482 for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) {
Louis Changcdec0802019-11-11 11:45:07 +08006483 final Task task = getChildAt(taskNdx);
Louis Changdc077272019-11-12 16:52:56 +08006484 task.writeToProto(proto, com.android.server.am.ActivityStackProto.TASKS, logLevel);
Steven Timotius4346f0a2017-09-12 11:07:21 -07006485 }
6486 if (mResumedActivity != null) {
6487 mResumedActivity.writeIdentifierToProto(proto, RESUMED_ACTIVITY);
6488 }
6489 proto.write(DISPLAY_ID, mDisplayId);
Bryce Leef3c6a472017-11-14 14:53:06 -08006490 if (!matchParentBounds()) {
Evan Roskydfe3da72018-10-26 17:21:06 -07006491 final Rect bounds = getRequestedOverrideBounds();
Louis Changdc077272019-11-12 16:52:56 +08006492 bounds.writeToProto(proto, com.android.server.am.ActivityStackProto.BOUNDS);
Steven Timotius4346f0a2017-09-12 11:07:21 -07006493 }
Bryce Leef3c6a472017-11-14 14:53:06 -08006494
6495 // TODO: Remove, no longer needed with windowingMode.
6496 proto.write(FULLSCREEN, matchParentBounds());
Steven Timotius4346f0a2017-09-12 11:07:21 -07006497 proto.end(token);
6498 }
Louis Changdc077272019-11-12 16:52:56 +08006499
6500 // TODO(proto-merge): Remove once protos for ActivityStack and TaskStack are merged.
6501 void writeToProtoInnerStackOnly(ProtoOutputStream proto, long fieldId,
6502 @WindowTraceLogLevel int logLevel) {
6503 if (logLevel == WindowTraceLogLevel.CRITICAL && !isVisible()) {
6504 return;
6505 }
6506
6507 final long token = proto.start(fieldId);
6508 super.writeToProto(proto, WINDOW_CONTAINER, logLevel);
6509 proto.write(StackProto.ID, mStackId);
6510 for (int taskNdx = mChildren.size() - 1; taskNdx >= 0; taskNdx--) {
6511 mChildren.get(taskNdx).writeToProtoInnerTaskOnly(proto, StackProto.TASKS, logLevel);
6512 }
6513 proto.write(FILLS_PARENT, matchParentBounds());
6514 getRawBounds().writeToProto(proto, StackProto.BOUNDS);
6515 proto.write(DEFER_REMOVAL, mDeferRemoval);
6516 proto.write(MINIMIZE_AMOUNT, mMinimizeAmount);
6517 proto.write(ADJUSTED_FOR_IME, mAdjustedForIme);
6518 proto.write(ADJUST_IME_AMOUNT, mAdjustImeAmount);
6519 proto.write(ADJUST_DIVIDER_AMOUNT, mAdjustDividerAmount);
6520 mAdjustedBounds.writeToProto(proto, ADJUSTED_BOUNDS);
6521 proto.write(ANIMATING_BOUNDS, mBoundsAnimating);
6522 proto.end(token);
6523 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006524}