1 /* 2 * Copyright (C) 2016 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 17 package com.android.server.wm; 18 19 import static android.app.ActivityTaskManager.INVALID_TASK_ID; 20 import static android.app.KeyguardManager.ACTION_CONFIRM_DEVICE_CREDENTIAL_WITH_USER; 21 import static android.app.WindowConfiguration.ACTIVITY_TYPE_STANDARD; 22 import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED; 23 import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED; 24 import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK; 25 import static android.content.pm.ActivityInfo.LAUNCH_SINGLE_INSTANCE; 26 import static android.content.pm.ActivityInfo.LAUNCH_SINGLE_TASK; 27 import static android.content.res.Configuration.EMPTY; 28 import static android.os.Trace.TRACE_TAG_WINDOW_MANAGER; 29 import static android.view.Display.DEFAULT_DISPLAY; 30 import static android.view.Display.INVALID_DISPLAY; 31 import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_SUSTAINED_PERFORMANCE_MODE; 32 import static android.view.WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG; 33 import static android.view.WindowManager.LayoutParams.TYPE_NOTIFICATION_SHADE; 34 import static android.view.WindowManager.TRANSIT_NONE; 35 import static android.view.WindowManager.TRANSIT_PIP; 36 import static android.view.WindowManager.TRANSIT_SLEEP; 37 import static android.view.WindowManager.TRANSIT_TO_BACK; 38 import static android.view.WindowManager.TRANSIT_WAKE; 39 40 import static com.android.internal.protolog.ProtoLogGroup.WM_DEBUG_FOCUS_LIGHT; 41 import static com.android.internal.protolog.ProtoLogGroup.WM_DEBUG_KEEP_SCREEN_ON; 42 import static com.android.internal.protolog.ProtoLogGroup.WM_DEBUG_ORIENTATION; 43 import static com.android.internal.protolog.ProtoLogGroup.WM_DEBUG_STATES; 44 import static com.android.internal.protolog.ProtoLogGroup.WM_DEBUG_TASKS; 45 import static com.android.internal.protolog.ProtoLogGroup.WM_DEBUG_WALLPAPER; 46 import static com.android.internal.protolog.ProtoLogGroup.WM_SHOW_SURFACE_ALLOC; 47 import static com.android.server.policy.PhoneWindowManager.SYSTEM_DIALOG_REASON_ASSIST; 48 import static com.android.server.policy.WindowManagerPolicy.FINISH_LAYOUT_REDO_LAYOUT; 49 import static com.android.server.policy.WindowManagerPolicy.FINISH_LAYOUT_REDO_WALLPAPER; 50 import static com.android.server.wm.ActivityRecord.State.FINISHING; 51 import static com.android.server.wm.ActivityRecord.State.PAUSED; 52 import static com.android.server.wm.ActivityRecord.State.RESUMED; 53 import static com.android.server.wm.ActivityRecord.State.STOPPED; 54 import static com.android.server.wm.ActivityRecord.State.STOPPING; 55 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_RECENTS; 56 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ROOT_TASK; 57 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH; 58 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_RECENTS; 59 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STATES; 60 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_TASKS; 61 import static com.android.server.wm.ActivityTaskManagerService.ANIMATE; 62 import static com.android.server.wm.ActivityTaskManagerService.TAG_SWITCH; 63 import static com.android.server.wm.ActivityTaskSupervisor.DEFER_RESUME; 64 import static com.android.server.wm.ActivityTaskSupervisor.ON_TOP; 65 import static com.android.server.wm.ActivityTaskSupervisor.PRESERVE_WINDOWS; 66 import static com.android.server.wm.ActivityTaskSupervisor.dumpHistoryList; 67 import static com.android.server.wm.ActivityTaskSupervisor.printThisActivity; 68 import static com.android.server.wm.KeyguardController.KEYGUARD_SLEEP_TOKEN_TAG; 69 import static com.android.server.wm.RootWindowContainerProto.IS_HOME_RECENTS_COMPONENT; 70 import static com.android.server.wm.RootWindowContainerProto.KEYGUARD_CONTROLLER; 71 import static com.android.server.wm.RootWindowContainerProto.WINDOW_CONTAINER; 72 import static com.android.server.wm.Task.REPARENT_LEAVE_ROOT_TASK_IN_PLACE; 73 import static com.android.server.wm.Task.REPARENT_MOVE_ROOT_TASK_TO_FRONT; 74 import static com.android.server.wm.TaskFragment.TASK_FRAGMENT_VISIBILITY_INVISIBLE; 75 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_LAYOUT_REPEATS; 76 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_WINDOW_TRACE; 77 import static com.android.server.wm.WindowManagerDebugConfig.SHOW_LIGHT_TRANSACTIONS; 78 import static com.android.server.wm.WindowManagerDebugConfig.TAG_WITH_CLASS_NAME; 79 import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM; 80 import static com.android.server.wm.WindowManagerService.H.WINDOW_FREEZE_TIMEOUT; 81 import static com.android.server.wm.WindowManagerService.UPDATE_FOCUS_NORMAL; 82 import static com.android.server.wm.WindowManagerService.UPDATE_FOCUS_PLACING_SURFACES; 83 import static com.android.server.wm.WindowManagerService.UPDATE_FOCUS_WILL_PLACE_SURFACES; 84 import static com.android.server.wm.WindowManagerService.WINDOWS_FREEZING_SCREENS_NONE; 85 import static com.android.server.wm.WindowSurfacePlacer.SET_UPDATE_ROTATION; 86 import static com.android.server.wm.WindowSurfacePlacer.SET_WALLPAPER_ACTION_PENDING; 87 88 import static java.lang.Integer.MAX_VALUE; 89 90 import android.annotation.IntDef; 91 import android.annotation.NonNull; 92 import android.annotation.Nullable; 93 import android.annotation.UserIdInt; 94 import android.app.ActivityManager; 95 import android.app.ActivityOptions; 96 import android.app.ActivityTaskManager.RootTaskInfo; 97 import android.app.AppGlobals; 98 import android.app.WindowConfiguration; 99 import android.content.ComponentName; 100 import android.content.Context; 101 import android.content.Intent; 102 import android.content.pm.ActivityInfo; 103 import android.content.pm.ApplicationInfo; 104 import android.content.pm.ResolveInfo; 105 import android.content.res.Configuration; 106 import android.graphics.Rect; 107 import android.hardware.display.DisplayManager; 108 import android.hardware.display.DisplayManagerInternal; 109 import android.hardware.power.Mode; 110 import android.net.Uri; 111 import android.os.Binder; 112 import android.os.Debug; 113 import android.os.FactoryTest; 114 import android.os.Handler; 115 import android.os.IBinder; 116 import android.os.Looper; 117 import android.os.Message; 118 import android.os.PowerManager; 119 import android.os.RemoteException; 120 import android.os.SystemClock; 121 import android.os.Trace; 122 import android.os.UserHandle; 123 import android.os.storage.StorageManager; 124 import android.provider.Settings; 125 import android.service.voice.IVoiceInteractionSession; 126 import android.util.ArrayMap; 127 import android.util.ArraySet; 128 import android.util.IntArray; 129 import android.util.Pair; 130 import android.util.Slog; 131 import android.util.SparseArray; 132 import android.util.SparseIntArray; 133 import android.util.TimeUtils; 134 import android.util.proto.ProtoOutputStream; 135 import android.view.Display; 136 import android.view.DisplayInfo; 137 import android.view.SurfaceControl; 138 import android.view.WindowManager; 139 import android.window.TaskFragmentAnimationParams; 140 import android.window.WindowContainerToken; 141 142 import com.android.internal.annotations.VisibleForTesting; 143 import com.android.internal.app.ResolverActivity; 144 import com.android.internal.protolog.common.ProtoLog; 145 import com.android.internal.util.function.pooled.PooledLambda; 146 import com.android.internal.util.function.pooled.PooledPredicate; 147 import com.android.server.LocalServices; 148 import com.android.server.am.ActivityManagerService; 149 import com.android.server.am.AppTimeTracker; 150 import com.android.server.am.UserState; 151 import com.android.server.policy.PermissionPolicyInternal; 152 import com.android.server.policy.WindowManagerPolicy; 153 import com.android.server.utils.Slogf; 154 155 import java.io.FileDescriptor; 156 import java.io.PrintWriter; 157 import java.lang.annotation.Retention; 158 import java.lang.annotation.RetentionPolicy; 159 import java.util.ArrayList; 160 import java.util.Collections; 161 import java.util.List; 162 import java.util.Objects; 163 import java.util.Set; 164 import java.util.function.Consumer; 165 import java.util.function.Predicate; 166 167 /** Root {@link WindowContainer} for the device. */ 168 class RootWindowContainer extends WindowContainer<DisplayContent> 169 implements DisplayManager.DisplayListener { 170 private static final String TAG = TAG_WITH_CLASS_NAME ? "RootWindowContainer" : TAG_WM; 171 172 private static final int SET_SCREEN_BRIGHTNESS_OVERRIDE = 1; 173 private static final int SET_USER_ACTIVITY_TIMEOUT = 2; 174 static final String TAG_TASKS = TAG + POSTFIX_TASKS; 175 static final String TAG_STATES = TAG + POSTFIX_STATES; 176 private static final String TAG_RECENTS = TAG + POSTFIX_RECENTS; 177 178 private Object mLastWindowFreezeSource = null; 179 private float mScreenBrightnessOverride = PowerManager.BRIGHTNESS_INVALID_FLOAT; 180 private long mUserActivityTimeout = -1; 181 private boolean mUpdateRotation = false; 182 // Only set while traversing the default display based on its content. 183 // Affects the behavior of mirroring on secondary displays. 184 private boolean mObscureApplicationContentOnSecondaryDisplays = false; 185 186 private boolean mSustainedPerformanceModeEnabled = false; 187 private boolean mSustainedPerformanceModeCurrent = false; 188 189 // During an orientation change, we track whether all windows have rendered 190 // at the new orientation, and this will be false from changing orientation until that occurs. 191 // For seamless rotation cases this always stays true, as the windows complete their orientation 192 // changes 1 by 1 without disturbing global state. 193 boolean mOrientationChangeComplete = true; 194 boolean mWallpaperActionPending = false; 195 196 private final Handler mHandler; 197 198 private String mCloseSystemDialogsReason; 199 200 // The ID of the display which is responsible for receiving display-unspecified key and pointer 201 // events. 202 private int mTopFocusedDisplayId = INVALID_DISPLAY; 203 204 // Map from the PID to the top most app which has a focused window of the process. 205 final ArrayMap<Integer, ActivityRecord> mTopFocusedAppByProcess = new ArrayMap<>(); 206 207 // The tag for the token to put root tasks on the displays to sleep. 208 private static final String DISPLAY_OFF_SLEEP_TOKEN_TAG = "Display-off"; 209 210 /** The token acquirer to put root tasks on the displays to sleep */ 211 final ActivityTaskManagerInternal.SleepTokenAcquirer mDisplayOffTokenAcquirer; 212 213 /** 214 * The modes which affect which tasks are returned when calling 215 * {@link RootWindowContainer#anyTaskForId(int)}. 216 */ 217 @Retention(RetentionPolicy.SOURCE) 218 @IntDef({ 219 MATCH_ATTACHED_TASK_ONLY, 220 MATCH_ATTACHED_TASK_OR_RECENT_TASKS, 221 MATCH_ATTACHED_TASK_OR_RECENT_TASKS_AND_RESTORE 222 }) 223 public @interface AnyTaskForIdMatchTaskMode { 224 } 225 226 // Match only tasks that are attached to the hierarchy 227 static final int MATCH_ATTACHED_TASK_ONLY = 0; 228 // Match either attached tasks, or in the recent tasks if the tasks are detached 229 static final int MATCH_ATTACHED_TASK_OR_RECENT_TASKS = 1; 230 // Match either attached tasks, or in the recent tasks, restoring it to the provided task id 231 static final int MATCH_ATTACHED_TASK_OR_RECENT_TASKS_AND_RESTORE = 2; 232 233 ActivityTaskManagerService mService; 234 ActivityTaskSupervisor mTaskSupervisor; 235 WindowManagerService mWindowManager; 236 DisplayManager mDisplayManager; 237 private DisplayManagerInternal mDisplayManagerInternal; 238 @NonNull 239 private final DeviceStateController mDeviceStateController; 240 @NonNull 241 private final DisplayRotationCoordinator mDisplayRotationCoordinator; 242 243 /** Reference to default display so we can quickly look it up. */ 244 private DisplayContent mDefaultDisplay; 245 private final SparseArray<IntArray> mDisplayAccessUIDs = new SparseArray<>(); 246 247 /** The current user */ 248 int mCurrentUser; 249 /** Root task id of the front root task when user switched, indexed by userId. */ 250 SparseIntArray mUserRootTaskInFront = new SparseIntArray(2); 251 252 /** 253 * A list of tokens that cause the top activity to be put to sleep. 254 * They are used by components that may hide and block interaction with underlying 255 * activities. 256 */ 257 final SparseArray<SleepToken> mSleepTokens = new SparseArray<>(); 258 259 // The default minimal size that will be used if the activity doesn't specify its minimal size. 260 // It will be calculated when the default display gets added. 261 int mDefaultMinSizeOfResizeableTaskDp = -1; 262 263 // Whether tasks have moved and we need to rank the tasks before next OOM scoring 264 private boolean mTaskLayersChanged = true; 265 private int mTmpTaskLayerRank; 266 private final RankTaskLayersRunnable mRankTaskLayersRunnable = new RankTaskLayersRunnable(); 267 268 private final AttachApplicationHelper mAttachApplicationHelper = new AttachApplicationHelper(); 269 270 private String mDestroyAllActivitiesReason; 271 private final Runnable mDestroyAllActivitiesRunnable = new Runnable() { 272 @Override 273 public void run() { 274 synchronized (mService.mGlobalLock) { 275 try { 276 mTaskSupervisor.beginDeferResume(); 277 forAllActivities(r -> { 278 if (r.finishing || !r.isDestroyable()) return; 279 if (DEBUG_SWITCH) { 280 Slog.v(TAG_SWITCH, "Destroying " + r + " in state " + r.getState() 281 + " resumed=" + r.getTask().getTopResumedActivity() 282 + " pausing=" + r.getTask().getTopPausingActivity() 283 + " for reason " + mDestroyAllActivitiesReason); 284 } 285 r.destroyImmediately(mDestroyAllActivitiesReason); 286 }); 287 } finally { 288 mTaskSupervisor.endDeferResume(); 289 resumeFocusedTasksTopActivities(); 290 } 291 } 292 } 293 294 }; 295 296 private final FindTaskResult mTmpFindTaskResult = new FindTaskResult(); 297 298 static class FindTaskResult implements Predicate<Task> { 299 ActivityRecord mIdealRecord; 300 ActivityRecord mCandidateRecord; 301 302 private int mActivityType; 303 private String mTaskAffinity; 304 private Intent mIntent; 305 private ActivityInfo mInfo; 306 private ComponentName cls; 307 private int userId; 308 private boolean isDocument; 309 private Uri documentData; 310 init(int activityType, String taskAffinity, Intent intent, ActivityInfo info)311 void init(int activityType, String taskAffinity, Intent intent, ActivityInfo info) { 312 mActivityType = activityType; 313 mTaskAffinity = taskAffinity; 314 mIntent = intent; 315 mInfo = info; 316 mIdealRecord = null; 317 mCandidateRecord = null; 318 } 319 320 /** 321 * Returns the top activity in any existing task matching the given Intent in the input 322 * result. Returns null if no such task is found. 323 */ process(WindowContainer parent)324 void process(WindowContainer parent) { 325 cls = mIntent.getComponent(); 326 if (mInfo.targetActivity != null) { 327 cls = new ComponentName(mInfo.packageName, mInfo.targetActivity); 328 } 329 userId = UserHandle.getUserId(mInfo.applicationInfo.uid); 330 isDocument = mIntent != null & mIntent.isDocument(); 331 // If documentData is non-null then it must match the existing task data. 332 documentData = isDocument ? mIntent.getData() : null; 333 334 ProtoLog.d(WM_DEBUG_TASKS, "Looking for task of %s in %s", mInfo, 335 parent); 336 parent.forAllLeafTasks(this); 337 } 338 339 @Override test(Task task)340 public boolean test(Task task) { 341 if (!ConfigurationContainer.isCompatibleActivityType(mActivityType, 342 task.getActivityType())) { 343 ProtoLog.d(WM_DEBUG_TASKS, "Skipping task: (mismatch activity/task) %s", task); 344 return false; 345 } 346 347 if (task.voiceSession != null) { 348 // We never match voice sessions; those always run independently. 349 ProtoLog.d(WM_DEBUG_TASKS, "Skipping %s: voice session", task); 350 return false; 351 } 352 if (task.mUserId != userId) { 353 // Looking for a different task. 354 ProtoLog.d(WM_DEBUG_TASKS, "Skipping %s: different user", task); 355 return false; 356 } 357 358 // Overlays should not be considered as the task's logical top activity. 359 final ActivityRecord r = task.getTopNonFinishingActivity(false /* includeOverlays */); 360 361 if (r == null || r.finishing || r.mUserId != userId 362 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) { 363 ProtoLog.d(WM_DEBUG_TASKS, "Skipping %s: mismatch root %s", task, r); 364 return false; 365 } 366 if (!ConfigurationContainer.isCompatibleActivityType(r.getActivityType(), 367 mActivityType)) { 368 ProtoLog.d(WM_DEBUG_TASKS, "Skipping %s: mismatch activity type", task); 369 return false; 370 } 371 372 final Intent taskIntent = task.intent; 373 final Intent affinityIntent = task.affinityIntent; 374 final boolean taskIsDocument; 375 final Uri taskDocumentData; 376 if (taskIntent != null && taskIntent.isDocument()) { 377 taskIsDocument = true; 378 taskDocumentData = taskIntent.getData(); 379 } else if (affinityIntent != null && affinityIntent.isDocument()) { 380 taskIsDocument = true; 381 taskDocumentData = affinityIntent.getData(); 382 } else { 383 taskIsDocument = false; 384 taskDocumentData = null; 385 } 386 387 ProtoLog.d(WM_DEBUG_TASKS, "Comparing existing cls=%s /aff=%s to new cls=%s /aff=%s", 388 (task.realActivity != null ? task.realActivity.flattenToShortString() : ""), 389 task.rootAffinity, mIntent.getComponent().flattenToShortString(), 390 mTaskAffinity); 391 // TODO Refactor to remove duplications. Check if logic can be simplified. 392 if (task.realActivity != null && task.realActivity.compareTo(cls) == 0 393 && Objects.equals(documentData, taskDocumentData)) { 394 ProtoLog.d(WM_DEBUG_TASKS, "Found matching class!"); 395 //dump(); 396 ProtoLog.d(WM_DEBUG_TASKS, "For Intent %s bringing to top: %s", mIntent, r.intent); 397 mIdealRecord = r; 398 return true; 399 } else if (affinityIntent != null && affinityIntent.getComponent() != null 400 && affinityIntent.getComponent().compareTo(cls) == 0 && 401 Objects.equals(documentData, taskDocumentData)) { 402 ProtoLog.d(WM_DEBUG_TASKS, "Found matching class!"); 403 ProtoLog.d(WM_DEBUG_TASKS, "For Intent %s bringing to top: %s", mIntent, r.intent); 404 mIdealRecord = r; 405 return true; 406 } else if (!isDocument && !taskIsDocument 407 && mIdealRecord == null && mCandidateRecord == null 408 && task.rootAffinity != null) { 409 if (task.rootAffinity.equals(mTaskAffinity) 410 && task.isSameRequiredDisplayCategory(mInfo)) { 411 ProtoLog.d(WM_DEBUG_TASKS, "Found matching affinity candidate!"); 412 // It is possible for multiple tasks to have the same root affinity especially 413 // if they are in separate root tasks. We save off this candidate, but keep 414 // looking to see if there is a better candidate. 415 mCandidateRecord = r; 416 } 417 } else { 418 ProtoLog.d(WM_DEBUG_TASKS, "Not a match: %s", task); 419 } 420 421 return false; 422 } 423 } 424 425 private final Consumer<WindowState> mCloseSystemDialogsConsumer = w -> { 426 if (w.mHasSurface) { 427 try { 428 w.mClient.closeSystemDialogs(mCloseSystemDialogsReason); 429 } catch (RemoteException e) { 430 } 431 } 432 }; 433 RootWindowContainer(WindowManagerService service)434 RootWindowContainer(WindowManagerService service) { 435 super(service); 436 mHandler = new MyHandler(service.mH.getLooper()); 437 mService = service.mAtmService; 438 mTaskSupervisor = mService.mTaskSupervisor; 439 mTaskSupervisor.mRootWindowContainer = this; 440 mDisplayOffTokenAcquirer = mService.new SleepTokenAcquirerImpl(DISPLAY_OFF_SLEEP_TOKEN_TAG); 441 mDeviceStateController = new DeviceStateController(service.mContext, service.mGlobalLock); 442 mDisplayRotationCoordinator = new DisplayRotationCoordinator(); 443 } 444 445 /** 446 * Updates the children's focused window and the top focused display if needed. 447 */ updateFocusedWindowLocked(int mode, boolean updateInputWindows)448 boolean updateFocusedWindowLocked(int mode, boolean updateInputWindows) { 449 mTopFocusedAppByProcess.clear(); 450 boolean changed = false; 451 int topFocusedDisplayId = INVALID_DISPLAY; 452 // Go through the children in z-order starting at the top-most 453 for (int i = mChildren.size() - 1; i >= 0; --i) { 454 final DisplayContent dc = mChildren.get(i); 455 changed |= dc.updateFocusedWindowLocked(mode, updateInputWindows, topFocusedDisplayId); 456 final WindowState newFocus = dc.mCurrentFocus; 457 if (newFocus != null) { 458 final int pidOfNewFocus = newFocus.mSession.mPid; 459 if (mTopFocusedAppByProcess.get(pidOfNewFocus) == null) { 460 mTopFocusedAppByProcess.put(pidOfNewFocus, newFocus.mActivityRecord); 461 } 462 if (topFocusedDisplayId == INVALID_DISPLAY) { 463 topFocusedDisplayId = dc.getDisplayId(); 464 } 465 } else if (topFocusedDisplayId == INVALID_DISPLAY && dc.mFocusedApp != null) { 466 // The top-most display that has a focused app should still be the top focused 467 // display even when the app window is not ready yet (process not attached or 468 // window not added yet). 469 topFocusedDisplayId = dc.getDisplayId(); 470 } 471 } 472 if (topFocusedDisplayId == INVALID_DISPLAY) { 473 topFocusedDisplayId = DEFAULT_DISPLAY; 474 } 475 if (mTopFocusedDisplayId != topFocusedDisplayId) { 476 mTopFocusedDisplayId = topFocusedDisplayId; 477 mWmService.mInputManager.setFocusedDisplay(topFocusedDisplayId); 478 mWmService.mPolicy.setTopFocusedDisplay(topFocusedDisplayId); 479 mWmService.mAccessibilityController.setFocusedDisplay(topFocusedDisplayId); 480 ProtoLog.d(WM_DEBUG_FOCUS_LIGHT, "New topFocusedDisplayId=%d", topFocusedDisplayId); 481 } 482 return changed; 483 } 484 getTopFocusedDisplayContent()485 DisplayContent getTopFocusedDisplayContent() { 486 final DisplayContent dc = getDisplayContent(mTopFocusedDisplayId); 487 return dc != null ? dc : getDisplayContent(DEFAULT_DISPLAY); 488 } 489 490 @Override isOnTop()491 boolean isOnTop() { 492 // Considered always on top 493 return true; 494 } 495 496 @Override onChildPositionChanged(WindowContainer child)497 void onChildPositionChanged(WindowContainer child) { 498 mWmService.updateFocusedWindowLocked(UPDATE_FOCUS_NORMAL, 499 !mWmService.mPerDisplayFocusEnabled /* updateInputWindows */); 500 mTaskSupervisor.updateTopResumedActivityIfNeeded("onChildPositionChanged"); 501 } 502 503 @Override isAttached()504 boolean isAttached() { 505 return true; 506 } 507 508 /** 509 * Called when DisplayWindowSettings values may change. 510 */ onSettingsRetrieved()511 void onSettingsRetrieved() { 512 final int numDisplays = mChildren.size(); 513 for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) { 514 final DisplayContent displayContent = mChildren.get(displayNdx); 515 final boolean changed = mWmService.mDisplayWindowSettings.updateSettingsForDisplay( 516 displayContent); 517 if (!changed) { 518 continue; 519 } 520 521 displayContent.reconfigureDisplayLocked(); 522 523 // We need to update global configuration as well if config of default display has 524 // changed. Do it inline because ATMS#retrieveSettings() will soon update the 525 // configuration inline, which will overwrite the new windowing mode. 526 if (displayContent.isDefaultDisplay) { 527 final Configuration newConfig = mWmService.computeNewConfiguration( 528 displayContent.getDisplayId()); 529 mWmService.mAtmService.updateConfigurationLocked(newConfig, null /* starting */, 530 false /* initLocale */); 531 } 532 } 533 } 534 isLayoutNeeded()535 boolean isLayoutNeeded() { 536 final int numDisplays = mChildren.size(); 537 for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) { 538 final DisplayContent displayContent = mChildren.get(displayNdx); 539 if (displayContent.isLayoutNeeded()) { 540 return true; 541 } 542 } 543 return false; 544 } 545 getWindowsByName(ArrayList<WindowState> output, String name)546 void getWindowsByName(ArrayList<WindowState> output, String name) { 547 int objectId = 0; 548 // See if this is an object ID. 549 try { 550 objectId = Integer.parseInt(name, 16); 551 name = null; 552 } catch (RuntimeException e) { 553 } 554 555 getWindowsByName(output, name, objectId); 556 } 557 getWindowsByName(ArrayList<WindowState> output, String name, int objectId)558 private void getWindowsByName(ArrayList<WindowState> output, String name, int objectId) { 559 forAllWindows((w) -> { 560 if (name != null) { 561 if (w.mAttrs.getTitle().toString().contains(name)) { 562 output.add(w); 563 } 564 } else if (System.identityHashCode(w) == objectId) { 565 output.add(w); 566 } 567 }, true /* traverseTopToBottom */); 568 } 569 570 /** 571 * Returns the app window token for the input binder if it exist in the system. 572 * NOTE: Only one AppWindowToken is allowed to exist in the system for a binder token, since 573 * AppWindowToken represents an activity which can only exist on one display. 574 */ getActivityRecord(IBinder binder)575 ActivityRecord getActivityRecord(IBinder binder) { 576 for (int i = mChildren.size() - 1; i >= 0; --i) { 577 final DisplayContent dc = mChildren.get(i); 578 final ActivityRecord activity = dc.getActivityRecord(binder); 579 if (activity != null) { 580 return activity; 581 } 582 } 583 return null; 584 } 585 586 /** Returns the window token for the input binder if it exist in the system. */ getWindowToken(IBinder binder)587 WindowToken getWindowToken(IBinder binder) { 588 for (int i = mChildren.size() - 1; i >= 0; --i) { 589 final DisplayContent dc = mChildren.get(i); 590 final WindowToken wtoken = dc.getWindowToken(binder); 591 if (wtoken != null) { 592 return wtoken; 593 } 594 } 595 return null; 596 } 597 598 /** Returns the display object the input window token is currently mapped on. */ getWindowTokenDisplay(WindowToken token)599 DisplayContent getWindowTokenDisplay(WindowToken token) { 600 if (token == null) { 601 return null; 602 } 603 604 for (int i = mChildren.size() - 1; i >= 0; --i) { 605 final DisplayContent dc = mChildren.get(i); 606 final WindowToken current = dc.getWindowToken(token.token); 607 if (current == token) { 608 return dc; 609 } 610 } 611 612 return null; 613 } 614 615 @Override dispatchConfigurationToChild(DisplayContent child, Configuration config)616 void dispatchConfigurationToChild(DisplayContent child, Configuration config) { 617 if (child.isDefaultDisplay) { 618 // The global configuration is also the override configuration of default display. 619 child.performDisplayOverrideConfigUpdate(config); 620 } else { 621 child.onConfigurationChanged(config); 622 } 623 } 624 refreshSecureSurfaceState()625 void refreshSecureSurfaceState() { 626 forAllWindows((w) -> { 627 if (w.mHasSurface) { 628 w.mWinAnimator.setSecureLocked(w.isSecureLocked()); 629 } 630 }, true /* traverseTopToBottom */); 631 } 632 updateHiddenWhileSuspendedState(final ArraySet<String> packages, final boolean suspended)633 void updateHiddenWhileSuspendedState(final ArraySet<String> packages, final boolean suspended) { 634 forAllWindows((w) -> { 635 if (packages.contains(w.getOwningPackage())) { 636 w.setHiddenWhileSuspended(suspended); 637 } 638 }, false); 639 } 640 updateAppOpsState()641 void updateAppOpsState() { 642 forAllWindows((w) -> { 643 w.updateAppOpsState(); 644 }, false /* traverseTopToBottom */); 645 } 646 canShowStrictModeViolation(int pid)647 boolean canShowStrictModeViolation(int pid) { 648 final WindowState win = getWindow((w) -> w.mSession.mPid == pid && w.isVisible()); 649 return win != null; 650 } 651 closeSystemDialogs(String reason)652 void closeSystemDialogs(String reason) { 653 mCloseSystemDialogsReason = reason; 654 forAllWindows(mCloseSystemDialogsConsumer, false /* traverseTopToBottom */); 655 } 656 hasPendingLayoutChanges(WindowAnimator animator)657 boolean hasPendingLayoutChanges(WindowAnimator animator) { 658 boolean hasChanges = false; 659 660 final int count = mChildren.size(); 661 for (int i = 0; i < count; ++i) { 662 final int pendingChanges = mChildren.get(i).pendingLayoutChanges; 663 if ((pendingChanges & FINISH_LAYOUT_REDO_WALLPAPER) != 0) { 664 animator.mBulkUpdateParams |= SET_WALLPAPER_ACTION_PENDING; 665 } 666 if (pendingChanges != 0) { 667 hasChanges = true; 668 } 669 } 670 671 return hasChanges; 672 } 673 reclaimSomeSurfaceMemory(WindowStateAnimator winAnimator, String operation, boolean secure)674 boolean reclaimSomeSurfaceMemory(WindowStateAnimator winAnimator, String operation, 675 boolean secure) { 676 final WindowSurfaceController surfaceController = winAnimator.mSurfaceController; 677 boolean leakedSurface = false; 678 boolean killedApps = false; 679 EventLogTags.writeWmNoSurfaceMemory(winAnimator.mWin.toString(), 680 winAnimator.mSession.mPid, operation); 681 final long callingIdentity = Binder.clearCallingIdentity(); 682 try { 683 // There was some problem...first, do a validity check of the window list to make sure 684 // we haven't left any dangling surfaces around. 685 686 Slog.i(TAG_WM, "Out of memory for surface! Looking for leaks..."); 687 final int numDisplays = mChildren.size(); 688 for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) { 689 leakedSurface |= mChildren.get(displayNdx).destroyLeakedSurfaces(); 690 } 691 692 if (!leakedSurface) { 693 Slog.w(TAG_WM, "No leaked surfaces; killing applications!"); 694 final SparseIntArray pidCandidates = new SparseIntArray(); 695 for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) { 696 mChildren.get(displayNdx).forAllWindows((w) -> { 697 if (mWmService.mForceRemoves.contains(w)) { 698 return; 699 } 700 final WindowStateAnimator wsa = w.mWinAnimator; 701 if (wsa.mSurfaceController != null) { 702 pidCandidates.append(wsa.mSession.mPid, wsa.mSession.mPid); 703 } 704 }, false /* traverseTopToBottom */); 705 706 if (pidCandidates.size() > 0) { 707 int[] pids = new int[pidCandidates.size()]; 708 for (int i = 0; i < pids.length; i++) { 709 pids[i] = pidCandidates.keyAt(i); 710 } 711 try { 712 if (mWmService.mActivityManager.killPids(pids, "Free memory", secure)) { 713 killedApps = true; 714 } 715 } catch (RemoteException e) { 716 } 717 } 718 } 719 } 720 721 if (leakedSurface || killedApps) { 722 // We managed to reclaim some memory, so get rid of the trouble surface and ask the 723 // app to request another one. 724 Slog.w(TAG_WM, 725 "Looks like we have reclaimed some memory, clearing surface for retry."); 726 if (surfaceController != null) { 727 ProtoLog.i(WM_SHOW_SURFACE_ALLOC, 728 "SURFACE RECOVER DESTROY: %s", winAnimator.mWin); 729 SurfaceControl.Transaction t = mWmService.mTransactionFactory.get(); 730 winAnimator.destroySurface(t); 731 t.apply(); 732 if (winAnimator.mWin.mActivityRecord != null) { 733 winAnimator.mWin.mActivityRecord.removeStartingWindow(); 734 } 735 } 736 737 try { 738 winAnimator.mWin.mClient.dispatchGetNewSurface(); 739 } catch (RemoteException e) { 740 } 741 } 742 } finally { 743 Binder.restoreCallingIdentity(callingIdentity); 744 } 745 746 return leakedSurface || killedApps; 747 } 748 749 /** 750 * This method should only be called from {@link WindowSurfacePlacer}. Otherwise the recursion 751 * check and {@link WindowSurfacePlacer#isInLayout()} won't take effect. 752 */ performSurfacePlacement()753 void performSurfacePlacement() { 754 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "performSurfacePlacement"); 755 try { 756 performSurfacePlacementNoTrace(); 757 } finally { 758 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER); 759 } 760 } 761 762 // "Something has changed! Let's make it correct now." 763 // TODO: Super long method that should be broken down... performSurfacePlacementNoTrace()764 void performSurfacePlacementNoTrace() { 765 if (DEBUG_WINDOW_TRACE) { 766 Slog.v(TAG, "performSurfacePlacementInner: entry. Called by " 767 + Debug.getCallers(3)); 768 } 769 770 int i; 771 772 if (mWmService.mFocusMayChange) { 773 mWmService.mFocusMayChange = false; 774 mWmService.updateFocusedWindowLocked( 775 UPDATE_FOCUS_WILL_PLACE_SURFACES, false /*updateInputWindows*/); 776 } 777 778 mScreenBrightnessOverride = PowerManager.BRIGHTNESS_INVALID_FLOAT; 779 mUserActivityTimeout = -1; 780 mObscureApplicationContentOnSecondaryDisplays = false; 781 mSustainedPerformanceModeCurrent = false; 782 mWmService.mTransactionSequence++; 783 784 // TODO(multi-display): recents animation & wallpaper need support multi-display. 785 final DisplayContent defaultDisplay = mWmService.getDefaultDisplayContentLocked(); 786 final WindowSurfacePlacer surfacePlacer = mWmService.mWindowPlacerLocked; 787 788 if (SHOW_LIGHT_TRANSACTIONS) { 789 Slog.i(TAG, 790 ">>> OPEN TRANSACTION performLayoutAndPlaceSurfaces"); 791 } 792 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "applySurfaceChanges"); 793 mWmService.openSurfaceTransaction(); 794 try { 795 applySurfaceChangesTransaction(); 796 } catch (RuntimeException e) { 797 Slog.wtf(TAG, "Unhandled exception in Window Manager", e); 798 } finally { 799 mWmService.closeSurfaceTransaction("performLayoutAndPlaceSurfaces"); 800 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER); 801 if (SHOW_LIGHT_TRANSACTIONS) { 802 Slog.i(TAG, 803 "<<< CLOSE TRANSACTION performLayoutAndPlaceSurfaces"); 804 } 805 } 806 807 // Send any pending task-info changes that were queued-up during a layout deferment 808 mWmService.mAtmService.mTaskOrganizerController.dispatchPendingEvents(); 809 mWmService.mAtmService.mTaskFragmentOrganizerController.dispatchPendingEvents(); 810 mWmService.mSyncEngine.onSurfacePlacement(); 811 mWmService.mAnimator.executeAfterPrepareSurfacesRunnables(); 812 813 checkAppTransitionReady(surfacePlacer); 814 815 // Defer starting the recents animation until the wallpaper has drawn 816 final RecentsAnimationController recentsAnimationController = 817 mWmService.getRecentsAnimationController(); 818 if (recentsAnimationController != null) { 819 recentsAnimationController.checkAnimationReady(defaultDisplay.mWallpaperController); 820 } 821 mWmService.mAtmService.mBackNavigationController 822 .checkAnimationReady(defaultDisplay.mWallpaperController); 823 824 for (int displayNdx = 0; displayNdx < mChildren.size(); ++displayNdx) { 825 final DisplayContent displayContent = mChildren.get(displayNdx); 826 if (displayContent.mWallpaperMayChange) { 827 ProtoLog.v(WM_DEBUG_WALLPAPER, "Wallpaper may change! Adjusting"); 828 displayContent.pendingLayoutChanges |= FINISH_LAYOUT_REDO_WALLPAPER; 829 if (DEBUG_LAYOUT_REPEATS) { 830 surfacePlacer.debugLayoutRepeats("WallpaperMayChange", 831 displayContent.pendingLayoutChanges); 832 } 833 } 834 } 835 836 if (mWmService.mFocusMayChange) { 837 mWmService.mFocusMayChange = false; 838 mWmService.updateFocusedWindowLocked(UPDATE_FOCUS_PLACING_SURFACES, 839 false /*updateInputWindows*/); 840 } 841 842 if (isLayoutNeeded()) { 843 defaultDisplay.pendingLayoutChanges |= FINISH_LAYOUT_REDO_LAYOUT; 844 if (DEBUG_LAYOUT_REPEATS) { 845 surfacePlacer.debugLayoutRepeats("mLayoutNeeded", 846 defaultDisplay.pendingLayoutChanges); 847 } 848 } 849 850 handleResizingWindows(); 851 852 if (mWmService.mDisplayFrozen) { 853 ProtoLog.v(WM_DEBUG_ORIENTATION, 854 "With display frozen, orientationChangeComplete=%b", 855 mOrientationChangeComplete); 856 } 857 if (mOrientationChangeComplete) { 858 if (mWmService.mWindowsFreezingScreen != WINDOWS_FREEZING_SCREENS_NONE) { 859 mWmService.mWindowsFreezingScreen = WINDOWS_FREEZING_SCREENS_NONE; 860 mWmService.mLastFinishedFreezeSource = mLastWindowFreezeSource; 861 mWmService.mH.removeMessages(WINDOW_FREEZE_TIMEOUT); 862 } 863 mWmService.stopFreezingDisplayLocked(); 864 } 865 866 // Destroy the surface of any windows that are no longer visible. 867 i = mWmService.mDestroySurface.size(); 868 if (i > 0) { 869 do { 870 i--; 871 WindowState win = mWmService.mDestroySurface.get(i); 872 win.mDestroying = false; 873 final DisplayContent displayContent = win.getDisplayContent(); 874 if (displayContent.mInputMethodWindow == win) { 875 displayContent.setInputMethodWindowLocked(null); 876 } 877 if (displayContent.mWallpaperController.isWallpaperTarget(win)) { 878 displayContent.pendingLayoutChanges |= FINISH_LAYOUT_REDO_WALLPAPER; 879 } 880 win.destroySurfaceUnchecked(); 881 } while (i > 0); 882 mWmService.mDestroySurface.clear(); 883 } 884 885 for (int displayNdx = 0; displayNdx < mChildren.size(); ++displayNdx) { 886 final DisplayContent displayContent = mChildren.get(displayNdx); 887 if (displayContent.pendingLayoutChanges != 0) { 888 displayContent.setLayoutNeeded(); 889 } 890 } 891 892 if (!mWmService.mDisplayFrozen) { 893 final float brightnessOverride = mScreenBrightnessOverride < PowerManager.BRIGHTNESS_MIN 894 || mScreenBrightnessOverride > PowerManager.BRIGHTNESS_MAX 895 ? PowerManager.BRIGHTNESS_INVALID_FLOAT : mScreenBrightnessOverride; 896 int brightnessFloatAsIntBits = Float.floatToIntBits(brightnessOverride); 897 // Post these on a handler such that we don't call into power manager service while 898 // holding the window manager lock to avoid lock contention with power manager lock. 899 mHandler.obtainMessage(SET_SCREEN_BRIGHTNESS_OVERRIDE, brightnessFloatAsIntBits, 900 0).sendToTarget(); 901 mHandler.obtainMessage(SET_USER_ACTIVITY_TIMEOUT, mUserActivityTimeout).sendToTarget(); 902 } 903 904 if (mSustainedPerformanceModeCurrent != mSustainedPerformanceModeEnabled) { 905 mSustainedPerformanceModeEnabled = mSustainedPerformanceModeCurrent; 906 mWmService.mPowerManagerInternal.setPowerMode( 907 Mode.SUSTAINED_PERFORMANCE, 908 mSustainedPerformanceModeEnabled); 909 } 910 911 if (mUpdateRotation) { 912 ProtoLog.d(WM_DEBUG_ORIENTATION, "Performing post-rotate rotation"); 913 mUpdateRotation = updateRotationUnchecked(); 914 } 915 916 if (!mWmService.mWaitingForDrawnCallbacks.isEmpty() 917 || (mOrientationChangeComplete && !isLayoutNeeded() 918 && !mUpdateRotation)) { 919 mWmService.checkDrawnWindowsLocked(); 920 } 921 922 forAllDisplays(dc -> { 923 dc.getInputMonitor().updateInputWindowsLw(true /*force*/); 924 dc.updateSystemGestureExclusion(); 925 dc.updateKeepClearAreas(); 926 dc.updateTouchExcludeRegion(); 927 }); 928 929 // Check to see if we are now in a state where the screen should 930 // be enabled, because the window obscured flags have changed. 931 mWmService.enableScreenIfNeededLocked(); 932 933 mWmService.scheduleAnimationLocked(); 934 935 if (DEBUG_WINDOW_TRACE) Slog.e(TAG, "performSurfacePlacementInner exit"); 936 } 937 checkAppTransitionReady(WindowSurfacePlacer surfacePlacer)938 private void checkAppTransitionReady(WindowSurfacePlacer surfacePlacer) { 939 // Trace all displays app transition by Z-order for pending layout change. 940 for (int i = mChildren.size() - 1; i >= 0; --i) { 941 final DisplayContent curDisplay = mChildren.get(i); 942 943 // If we are ready to perform an app transition, check through all of the app tokens 944 // to be shown and see if they are ready to go. 945 if (curDisplay.mAppTransition.isReady()) { 946 // handleAppTransitionReady may modify curDisplay.pendingLayoutChanges. 947 curDisplay.mAppTransitionController.handleAppTransitionReady(); 948 if (DEBUG_LAYOUT_REPEATS) { 949 surfacePlacer.debugLayoutRepeats("after handleAppTransitionReady", 950 curDisplay.pendingLayoutChanges); 951 } 952 } 953 954 if (curDisplay.mAppTransition.isRunning() && !curDisplay.isAppTransitioning()) { 955 // We have finished the animation of an app transition. To do this, we have 956 // delayed a lot of operations like showing and hiding apps, moving apps in 957 // Z-order, etc. 958 // The app token list reflects the correct Z-order, but the window list may now 959 // be out of sync with it. So here we will just rebuild the entire app window 960 // list. Fun! 961 curDisplay.handleAnimatingStoppedAndTransition(); 962 if (DEBUG_LAYOUT_REPEATS) { 963 surfacePlacer.debugLayoutRepeats("after handleAnimStopAndXitionLock", 964 curDisplay.pendingLayoutChanges); 965 } 966 } 967 } 968 } 969 applySurfaceChangesTransaction()970 private void applySurfaceChangesTransaction() { 971 // TODO(multi-display): Support these features on secondary screens. 972 final DisplayContent defaultDc = mDefaultDisplay; 973 final DisplayInfo defaultInfo = defaultDc.getDisplayInfo(); 974 final int defaultDw = defaultInfo.logicalWidth; 975 final int defaultDh = defaultInfo.logicalHeight; 976 final SurfaceControl.Transaction t = defaultDc.getSyncTransaction(); 977 if (mWmService.mWatermark != null) { 978 mWmService.mWatermark.positionSurface(defaultDw, defaultDh, t); 979 } 980 if (mWmService.mStrictModeFlash != null) { 981 mWmService.mStrictModeFlash.positionSurface(defaultDw, defaultDh, t); 982 } 983 if (mWmService.mEmulatorDisplayOverlay != null) { 984 mWmService.mEmulatorDisplayOverlay.positionSurface(defaultDw, defaultDh, 985 defaultDc.getRotation(), t); 986 } 987 988 final int count = mChildren.size(); 989 for (int j = 0; j < count; ++j) { 990 final DisplayContent dc = mChildren.get(j); 991 dc.applySurfaceChangesTransaction(); 992 } 993 994 // Give the display manager a chance to adjust properties like display rotation if it needs 995 // to. 996 mWmService.mDisplayManagerInternal.performTraversal(t); 997 if (t != defaultDc.mSyncTransaction) { 998 SurfaceControl.mergeToGlobalTransaction(t); 999 } 1000 } 1001 1002 /** 1003 * Handles resizing windows during surface placement. 1004 */ handleResizingWindows()1005 private void handleResizingWindows() { 1006 for (int i = mWmService.mResizingWindows.size() - 1; i >= 0; i--) { 1007 WindowState win = mWmService.mResizingWindows.get(i); 1008 if (win.mAppFreezing || win.getDisplayContent().mWaitingForConfig) { 1009 // Don't remove this window until rotation has completed and is not waiting for the 1010 // complete configuration. 1011 continue; 1012 } 1013 win.reportResized(); 1014 mWmService.mResizingWindows.remove(i); 1015 } 1016 } 1017 1018 /** 1019 * @param w WindowState this method is applied to. 1020 * @param obscured True if there is a window on top of this obscuring the display. 1021 * @param syswin System window? 1022 * @return True when the display contains content to show the user. When false, the display 1023 * manager may choose to mirror or blank the display. 1024 */ handleNotObscuredLocked(WindowState w, boolean obscured, boolean syswin)1025 boolean handleNotObscuredLocked(WindowState w, boolean obscured, boolean syswin) { 1026 final WindowManager.LayoutParams attrs = w.mAttrs; 1027 final int attrFlags = attrs.flags; 1028 final boolean onScreen = w.isOnScreen(); 1029 final boolean canBeSeen = w.isDisplayed(); 1030 final int privateflags = attrs.privateFlags; 1031 boolean displayHasContent = false; 1032 1033 ProtoLog.d(WM_DEBUG_KEEP_SCREEN_ON, 1034 "handleNotObscuredLocked w: %s, w.mHasSurface: %b, w.isOnScreen(): %b, w" 1035 + ".isDisplayedLw(): %b, w.mAttrs.userActivityTimeout: %d", 1036 w, w.mHasSurface, onScreen, w.isDisplayed(), w.mAttrs.userActivityTimeout); 1037 if (w.mHasSurface && onScreen) { 1038 if (!syswin && w.mAttrs.userActivityTimeout >= 0 && mUserActivityTimeout < 0) { 1039 mUserActivityTimeout = w.mAttrs.userActivityTimeout; 1040 ProtoLog.d(WM_DEBUG_KEEP_SCREEN_ON, "mUserActivityTimeout set to %d", 1041 mUserActivityTimeout); 1042 } 1043 } 1044 if (w.mHasSurface && canBeSeen) { 1045 if (!syswin && w.mAttrs.screenBrightness >= 0 1046 && Float.isNaN(mScreenBrightnessOverride)) { 1047 mScreenBrightnessOverride = w.mAttrs.screenBrightness; 1048 } 1049 1050 final int type = attrs.type; 1051 // This function assumes that the contents of the default display are processed first 1052 // before secondary displays. 1053 final DisplayContent displayContent = w.getDisplayContent(); 1054 if (displayContent != null && displayContent.isDefaultDisplay) { 1055 // While a dream or keyguard is showing, obscure ordinary application content on 1056 // secondary displays (by forcibly enabling mirroring unless there is other content 1057 // we want to show) but still allow opaque keyguard dialogs to be shown. 1058 if (w.isDreamWindow() || mWmService.mPolicy.isKeyguardShowing()) { 1059 mObscureApplicationContentOnSecondaryDisplays = true; 1060 } 1061 displayHasContent = true; 1062 } else if (displayContent != null && 1063 (!mObscureApplicationContentOnSecondaryDisplays 1064 || displayContent.isKeyguardAlwaysUnlocked() 1065 || (obscured && type == TYPE_KEYGUARD_DIALOG))) { 1066 // Allow full screen keyguard presentation dialogs to be seen, or simply ignore the 1067 // keyguard if this display is always unlocked. 1068 displayHasContent = true; 1069 } 1070 if ((privateflags & PRIVATE_FLAG_SUSTAINED_PERFORMANCE_MODE) != 0) { 1071 mSustainedPerformanceModeCurrent = true; 1072 } 1073 } 1074 1075 return displayHasContent; 1076 } 1077 updateRotationUnchecked()1078 boolean updateRotationUnchecked() { 1079 boolean changed = false; 1080 for (int i = mChildren.size() - 1; i >= 0; i--) { 1081 if (mChildren.get(i).getDisplayRotation().updateRotationAndSendNewConfigIfChanged()) { 1082 changed = true; 1083 } 1084 } 1085 return changed; 1086 } 1087 copyAnimToLayoutParams()1088 boolean copyAnimToLayoutParams() { 1089 boolean doRequest = false; 1090 1091 final int bulkUpdateParams = mWmService.mAnimator.mBulkUpdateParams; 1092 if ((bulkUpdateParams & SET_UPDATE_ROTATION) != 0) { 1093 mUpdateRotation = true; 1094 doRequest = true; 1095 } 1096 if (mOrientationChangeComplete) { 1097 mLastWindowFreezeSource = mWmService.mAnimator.mLastWindowFreezeSource; 1098 if (mWmService.mWindowsFreezingScreen != WINDOWS_FREEZING_SCREENS_NONE) { 1099 doRequest = true; 1100 } 1101 } 1102 1103 if ((bulkUpdateParams & SET_WALLPAPER_ACTION_PENDING) != 0) { 1104 mWallpaperActionPending = true; 1105 } 1106 1107 return doRequest; 1108 } 1109 1110 private final class MyHandler extends Handler { 1111 MyHandler(Looper looper)1112 public MyHandler(Looper looper) { 1113 super(looper); 1114 } 1115 1116 @Override handleMessage(Message msg)1117 public void handleMessage(Message msg) { 1118 switch (msg.what) { 1119 case SET_SCREEN_BRIGHTNESS_OVERRIDE: 1120 mWmService.mPowerManagerInternal.setScreenBrightnessOverrideFromWindowManager( 1121 Float.intBitsToFloat(msg.arg1)); 1122 break; 1123 case SET_USER_ACTIVITY_TIMEOUT: 1124 mWmService.mPowerManagerInternal. 1125 setUserActivityTimeoutOverrideFromWindowManager((Long) msg.obj); 1126 break; 1127 default: 1128 break; 1129 } 1130 } 1131 } 1132 dumpDisplayContents(PrintWriter pw)1133 void dumpDisplayContents(PrintWriter pw) { 1134 pw.println("WINDOW MANAGER DISPLAY CONTENTS (dumpsys window displays)"); 1135 if (mWmService.mDisplayReady) { 1136 final int count = mChildren.size(); 1137 for (int i = 0; i < count; ++i) { 1138 final DisplayContent displayContent = mChildren.get(i); 1139 displayContent.dump(pw, " ", true /* dumpAll */); 1140 } 1141 } else { 1142 pw.println(" NO DISPLAY"); 1143 } 1144 } 1145 dumpTopFocusedDisplayId(PrintWriter pw)1146 void dumpTopFocusedDisplayId(PrintWriter pw) { 1147 pw.print(" mTopFocusedDisplayId="); 1148 pw.println(mTopFocusedDisplayId); 1149 } 1150 dumpLayoutNeededDisplayIds(PrintWriter pw)1151 void dumpLayoutNeededDisplayIds(PrintWriter pw) { 1152 if (!isLayoutNeeded()) { 1153 return; 1154 } 1155 pw.print(" mLayoutNeeded on displays="); 1156 final int count = mChildren.size(); 1157 for (int displayNdx = 0; displayNdx < count; ++displayNdx) { 1158 final DisplayContent displayContent = mChildren.get(displayNdx); 1159 if (displayContent.isLayoutNeeded()) { 1160 pw.print(displayContent.getDisplayId()); 1161 } 1162 } 1163 pw.println(); 1164 } 1165 dumpWindowsNoHeader(PrintWriter pw, boolean dumpAll, ArrayList<WindowState> windows)1166 void dumpWindowsNoHeader(PrintWriter pw, boolean dumpAll, ArrayList<WindowState> windows) { 1167 final int[] index = new int[1]; 1168 forAllWindows((w) -> { 1169 if (windows == null || windows.contains(w)) { 1170 pw.println(" Window #" + index[0] + " " + w + ":"); 1171 w.dump(pw, " ", dumpAll || windows != null); 1172 index[0] = index[0] + 1; 1173 } 1174 }, true /* traverseTopToBottom */); 1175 } 1176 dumpTokens(PrintWriter pw, boolean dumpAll)1177 void dumpTokens(PrintWriter pw, boolean dumpAll) { 1178 pw.println(" All tokens:"); 1179 for (int i = mChildren.size() - 1; i >= 0; --i) { 1180 mChildren.get(i).dumpTokens(pw, dumpAll); 1181 } 1182 } 1183 1184 @Override dumpDebug(ProtoOutputStream proto, long fieldId, @WindowTraceLogLevel int logLevel)1185 public void dumpDebug(ProtoOutputStream proto, long fieldId, 1186 @WindowTraceLogLevel int logLevel) { 1187 if (logLevel == WindowTraceLogLevel.CRITICAL && !isVisible()) { 1188 return; 1189 } 1190 1191 final long token = proto.start(fieldId); 1192 super.dumpDebug(proto, WINDOW_CONTAINER, logLevel); 1193 1194 mTaskSupervisor.getKeyguardController().dumpDebug(proto, KEYGUARD_CONTROLLER); 1195 proto.write(IS_HOME_RECENTS_COMPONENT, 1196 mTaskSupervisor.mRecentTasks.isRecentsComponentHomeActivity(mCurrentUser)); 1197 proto.end(token); 1198 } 1199 1200 @Override getName()1201 String getName() { 1202 return "ROOT"; 1203 } 1204 1205 @Override removeChild(DisplayContent dc)1206 protected void removeChild(DisplayContent dc) { 1207 super.removeChild(dc); 1208 if (mTopFocusedDisplayId == dc.getDisplayId()) { 1209 mWmService.updateFocusedWindowLocked( 1210 UPDATE_FOCUS_NORMAL, true /* updateInputWindows */); 1211 } 1212 } 1213 1214 /** 1215 * For all display at or below this call the callback. 1216 * 1217 * @param callback Callback to be called for every display. 1218 */ forAllDisplays(Consumer<DisplayContent> callback)1219 void forAllDisplays(Consumer<DisplayContent> callback) { 1220 for (int i = mChildren.size() - 1; i >= 0; --i) { 1221 callback.accept(mChildren.get(i)); 1222 } 1223 } 1224 forAllDisplayPolicies(Consumer<DisplayPolicy> callback)1225 void forAllDisplayPolicies(Consumer<DisplayPolicy> callback) { 1226 for (int i = mChildren.size() - 1; i >= 0; --i) { 1227 callback.accept(mChildren.get(i).getDisplayPolicy()); 1228 } 1229 } 1230 1231 /** 1232 * Get current topmost focused IME window in system. 1233 * Will look on all displays in current Z-order. 1234 */ getCurrentInputMethodWindow()1235 WindowState getCurrentInputMethodWindow() { 1236 for (int i = mChildren.size() - 1; i >= 0; --i) { 1237 final DisplayContent displayContent = mChildren.get(i); 1238 if (displayContent.mInputMethodWindow != null) { 1239 return displayContent.mInputMethodWindow; 1240 } 1241 } 1242 return null; 1243 } 1244 getDisplayContextsWithNonToastVisibleWindows(int pid, List<Context> outContexts)1245 void getDisplayContextsWithNonToastVisibleWindows(int pid, List<Context> outContexts) { 1246 if (outContexts == null) { 1247 return; 1248 } 1249 for (int i = mChildren.size() - 1; i >= 0; --i) { 1250 DisplayContent dc = mChildren.get(i); 1251 if (dc.getWindow(w -> pid == w.mSession.mPid && w.isVisibleNow() 1252 && w.mAttrs.type != WindowManager.LayoutParams.TYPE_TOAST) != null) { 1253 outContexts.add(dc.getDisplayUiContext()); 1254 } 1255 } 1256 } 1257 1258 @Nullable getDisplayUiContext(int displayId)1259 Context getDisplayUiContext(int displayId) { 1260 return getDisplayContent(displayId) != null 1261 ? getDisplayContent(displayId).getDisplayUiContext() : null; 1262 } 1263 setWindowManager(WindowManagerService wm)1264 void setWindowManager(WindowManagerService wm) { 1265 mWindowManager = wm; 1266 mDisplayManager = mService.mContext.getSystemService(DisplayManager.class); 1267 mDisplayManager.registerDisplayListener(this, mService.mUiHandler); 1268 mDisplayManagerInternal = LocalServices.getService(DisplayManagerInternal.class); 1269 1270 final Display[] displays = mDisplayManager.getDisplays(); 1271 for (int displayNdx = 0; displayNdx < displays.length; ++displayNdx) { 1272 final Display display = displays[displayNdx]; 1273 final DisplayContent displayContent = 1274 new DisplayContent(display, this, mDeviceStateController); 1275 addChild(displayContent, POSITION_BOTTOM); 1276 if (displayContent.mDisplayId == DEFAULT_DISPLAY) { 1277 mDefaultDisplay = displayContent; 1278 } 1279 } 1280 1281 final TaskDisplayArea defaultTaskDisplayArea = getDefaultTaskDisplayArea(); 1282 defaultTaskDisplayArea.getOrCreateRootHomeTask(ON_TOP); 1283 positionChildAt(POSITION_TOP, defaultTaskDisplayArea.mDisplayContent, 1284 false /* includingParents */); 1285 } 1286 1287 /** 1288 * Called just before display manager has applied the device state to the displays 1289 * @param deviceState device state as defined by 1290 * {@link android.hardware.devicestate.DeviceStateManager} 1291 */ onDisplayManagerReceivedDeviceState(int deviceState)1292 void onDisplayManagerReceivedDeviceState(int deviceState) { 1293 mDeviceStateController.onDeviceStateReceivedByDisplayManager(deviceState); 1294 } 1295 1296 // TODO(multi-display): Look at all callpoints to make sure they make sense in multi-display. getDefaultDisplay()1297 DisplayContent getDefaultDisplay() { 1298 return mDefaultDisplay; 1299 } 1300 1301 @NonNull getDisplayRotationCoordinator()1302 DisplayRotationCoordinator getDisplayRotationCoordinator() { 1303 return mDisplayRotationCoordinator; 1304 } 1305 1306 /** 1307 * Get the default display area on the device dedicated to app windows. This one should be used 1308 * only as a fallback location for activity launches when no target display area is specified, 1309 * or for cases when multi-instance is not supported yet (like Split-screen, Freeform, PiP or 1310 * Recents). 1311 */ getDefaultTaskDisplayArea()1312 TaskDisplayArea getDefaultTaskDisplayArea() { 1313 return mDefaultDisplay.getDefaultTaskDisplayArea(); 1314 } 1315 1316 /** 1317 * Get an existing instance of {@link DisplayContent} that has the given uniqueId. Unique ID is 1318 * defined in {@link DisplayInfo#uniqueId}. 1319 * 1320 * @param uniqueId the unique ID of the display 1321 * @return the {@link DisplayContent} or {@code null} if nothing is found. 1322 */ getDisplayContent(String uniqueId)1323 DisplayContent getDisplayContent(String uniqueId) { 1324 for (int i = getChildCount() - 1; i >= 0; --i) { 1325 final DisplayContent display = getChildAt(i); 1326 final boolean isValid = display.mDisplay.isValid(); 1327 if (isValid && display.mDisplay.getUniqueId().equals(uniqueId)) { 1328 return display; 1329 } 1330 } 1331 1332 return null; 1333 } 1334 1335 // TODO: Look into consolidating with getDisplayContentOrCreate() getDisplayContent(int displayId)1336 DisplayContent getDisplayContent(int displayId) { 1337 for (int i = getChildCount() - 1; i >= 0; --i) { 1338 final DisplayContent displayContent = getChildAt(i); 1339 if (displayContent.mDisplayId == displayId) { 1340 return displayContent; 1341 } 1342 } 1343 return null; 1344 } 1345 1346 /** 1347 * Get an existing instance of {@link DisplayContent} or create new if there is a 1348 * corresponding record in display manager. 1349 */ 1350 // TODO: Look into consolidating with getDisplayContent() 1351 @Nullable getDisplayContentOrCreate(int displayId)1352 DisplayContent getDisplayContentOrCreate(int displayId) { 1353 DisplayContent displayContent = getDisplayContent(displayId); 1354 if (displayContent != null) { 1355 return displayContent; 1356 } 1357 if (mDisplayManager == null) { 1358 // The system isn't fully initialized yet. 1359 return null; 1360 } 1361 final Display display = mDisplayManager.getDisplay(displayId); 1362 if (display == null) { 1363 // The display is not registered in DisplayManager. 1364 return null; 1365 } 1366 // The display hasn't been added to ActivityManager yet, create a new record now. 1367 displayContent = new DisplayContent(display, this, mDeviceStateController); 1368 addChild(displayContent, POSITION_BOTTOM); 1369 return displayContent; 1370 } 1371 getDefaultDisplayHomeActivityForUser(int userId)1372 ActivityRecord getDefaultDisplayHomeActivityForUser(int userId) { 1373 return getDefaultTaskDisplayArea().getHomeActivityForUser(userId); 1374 } 1375 startHomeOnAllDisplays(int userId, String reason)1376 boolean startHomeOnAllDisplays(int userId, String reason) { 1377 boolean homeStarted = false; 1378 for (int i = getChildCount() - 1; i >= 0; i--) { 1379 final int displayId = getChildAt(i).mDisplayId; 1380 homeStarted |= startHomeOnDisplay(userId, reason, displayId); 1381 } 1382 return homeStarted; 1383 } 1384 startHomeOnEmptyDisplays(String reason)1385 void startHomeOnEmptyDisplays(String reason) { 1386 forAllTaskDisplayAreas(taskDisplayArea -> { 1387 if (taskDisplayArea.topRunningActivity() == null) { 1388 int userId = mWmService.getUserAssignedToDisplay(taskDisplayArea.getDisplayId()); 1389 startHomeOnTaskDisplayArea(userId, reason, taskDisplayArea, 1390 false /* allowInstrumenting */, false /* fromHomeKey */); 1391 } 1392 }); 1393 } 1394 startHomeOnDisplay(int userId, String reason, int displayId)1395 boolean startHomeOnDisplay(int userId, String reason, int displayId) { 1396 return startHomeOnDisplay(userId, reason, displayId, false /* allowInstrumenting */, 1397 false /* fromHomeKey */); 1398 } 1399 startHomeOnDisplay(int userId, String reason, int displayId, boolean allowInstrumenting, boolean fromHomeKey)1400 boolean startHomeOnDisplay(int userId, String reason, int displayId, boolean allowInstrumenting, 1401 boolean fromHomeKey) { 1402 // Fallback to top focused display or default display if the displayId is invalid. 1403 if (displayId == INVALID_DISPLAY) { 1404 final Task rootTask = getTopDisplayFocusedRootTask(); 1405 displayId = rootTask != null ? rootTask.getDisplayId() : DEFAULT_DISPLAY; 1406 } 1407 1408 final DisplayContent display = getDisplayContent(displayId); 1409 return display.reduceOnAllTaskDisplayAreas((taskDisplayArea, result) -> 1410 result | startHomeOnTaskDisplayArea(userId, reason, taskDisplayArea, 1411 allowInstrumenting, fromHomeKey), 1412 false /* initValue */); 1413 } 1414 1415 /** 1416 * This starts home activity on display areas that can have system decorations based on 1417 * displayId - default display area always uses primary home component. 1418 * For secondary display areas, the home activity must have category SECONDARY_HOME and then 1419 * resolves according to the priorities listed below. 1420 * - If default home is not set, always use the secondary home defined in the config. 1421 * - Use currently selected primary home activity. 1422 * - Use the activity in the same package as currently selected primary home activity. 1423 * If there are multiple activities matched, use first one. 1424 * - Use the secondary home defined in the config. 1425 */ startHomeOnTaskDisplayArea(int userId, String reason, TaskDisplayArea taskDisplayArea, boolean allowInstrumenting, boolean fromHomeKey)1426 boolean startHomeOnTaskDisplayArea(int userId, String reason, TaskDisplayArea taskDisplayArea, 1427 boolean allowInstrumenting, boolean fromHomeKey) { 1428 // Fallback to top focused display area if the provided one is invalid. 1429 if (taskDisplayArea == null) { 1430 final Task rootTask = getTopDisplayFocusedRootTask(); 1431 taskDisplayArea = rootTask != null ? rootTask.getDisplayArea() 1432 : getDefaultTaskDisplayArea(); 1433 } 1434 1435 Intent homeIntent = null; 1436 ActivityInfo aInfo = null; 1437 if (taskDisplayArea == getDefaultTaskDisplayArea() 1438 || mWmService.shouldPlacePrimaryHomeOnDisplay( 1439 taskDisplayArea.getDisplayId(), userId)) { 1440 homeIntent = mService.getHomeIntent(); 1441 aInfo = resolveHomeActivity(userId, homeIntent); 1442 } else if (shouldPlaceSecondaryHomeOnDisplayArea(taskDisplayArea)) { 1443 Pair<ActivityInfo, Intent> info = resolveSecondaryHomeActivity(userId, taskDisplayArea); 1444 aInfo = info.first; 1445 homeIntent = info.second; 1446 } 1447 if (aInfo == null || homeIntent == null) { 1448 return false; 1449 } 1450 1451 if (!canStartHomeOnDisplayArea(aInfo, taskDisplayArea, allowInstrumenting)) { 1452 return false; 1453 } 1454 1455 // Updates the home component of the intent. 1456 homeIntent.setComponent(new ComponentName(aInfo.applicationInfo.packageName, aInfo.name)); 1457 homeIntent.setFlags(homeIntent.getFlags() | FLAG_ACTIVITY_NEW_TASK); 1458 // Updates the extra information of the intent. 1459 if (fromHomeKey) { 1460 homeIntent.putExtra(WindowManagerPolicy.EXTRA_FROM_HOME_KEY, true); 1461 if (mWindowManager.getRecentsAnimationController() != null) { 1462 mWindowManager.getRecentsAnimationController().cancelAnimationForHomeStart(); 1463 } 1464 } 1465 homeIntent.putExtra(WindowManagerPolicy.EXTRA_START_REASON, reason); 1466 1467 // Update the reason for ANR debugging to verify if the user activity is the one that 1468 // actually launched. 1469 final String myReason = reason + ":" + userId + ":" + UserHandle.getUserId( 1470 aInfo.applicationInfo.uid) + ":" + taskDisplayArea.getDisplayId(); 1471 mService.getActivityStartController().startHomeActivity(homeIntent, aInfo, myReason, 1472 taskDisplayArea); 1473 return true; 1474 } 1475 1476 /** 1477 * This resolves the home activity info. 1478 * 1479 * @return the home activity info if any. 1480 */ 1481 @VisibleForTesting resolveHomeActivity(int userId, Intent homeIntent)1482 ActivityInfo resolveHomeActivity(int userId, Intent homeIntent) { 1483 final int flags = ActivityManagerService.STOCK_PM_FLAGS; 1484 final ComponentName comp = homeIntent.getComponent(); 1485 ActivityInfo aInfo = null; 1486 try { 1487 if (comp != null) { 1488 // Factory test. 1489 aInfo = AppGlobals.getPackageManager().getActivityInfo(comp, flags, userId); 1490 } else { 1491 final String resolvedType = 1492 homeIntent.resolveTypeIfNeeded(mService.mContext.getContentResolver()); 1493 final ResolveInfo info = mTaskSupervisor.resolveIntent(homeIntent, resolvedType, 1494 userId, flags, Binder.getCallingUid(), Binder.getCallingPid()); 1495 if (info != null) { 1496 aInfo = info.activityInfo; 1497 } 1498 } 1499 } catch (RemoteException e) { 1500 // ignore 1501 } 1502 1503 if (aInfo == null) { 1504 Slogf.wtf(TAG, new Exception(), "No home screen found for %s and user %d", homeIntent, 1505 userId); 1506 return null; 1507 } 1508 1509 aInfo = new ActivityInfo(aInfo); 1510 aInfo.applicationInfo = mService.getAppInfoForUser(aInfo.applicationInfo, userId); 1511 return aInfo; 1512 } 1513 1514 @VisibleForTesting resolveSecondaryHomeActivity(int userId, @NonNull TaskDisplayArea taskDisplayArea)1515 Pair<ActivityInfo, Intent> resolveSecondaryHomeActivity(int userId, 1516 @NonNull TaskDisplayArea taskDisplayArea) { 1517 if (taskDisplayArea == getDefaultTaskDisplayArea()) { 1518 throw new IllegalArgumentException( 1519 "resolveSecondaryHomeActivity: Should not be default task container"); 1520 } 1521 // Resolve activities in the same package as currently selected primary home activity. 1522 Intent homeIntent = mService.getHomeIntent(); 1523 ActivityInfo aInfo = resolveHomeActivity(userId, homeIntent); 1524 if (aInfo != null) { 1525 if (ResolverActivity.class.getName().equals(aInfo.name)) { 1526 // Always fallback to secondary home component if default home is not set. 1527 aInfo = null; 1528 } else { 1529 // Look for secondary home activities in the currently selected default home 1530 // package. 1531 homeIntent = mService.getSecondaryHomeIntent(aInfo.applicationInfo.packageName); 1532 final List<ResolveInfo> resolutions = resolveActivities(userId, homeIntent); 1533 final int size = resolutions.size(); 1534 final String targetName = aInfo.name; 1535 aInfo = null; 1536 for (int i = 0; i < size; i++) { 1537 ResolveInfo resolveInfo = resolutions.get(i); 1538 // We need to traverse all resolutions to check if the currently selected 1539 // default home activity is present. 1540 if (resolveInfo.activityInfo.name.equals(targetName)) { 1541 aInfo = resolveInfo.activityInfo; 1542 break; 1543 } 1544 } 1545 if (aInfo == null && size > 0) { 1546 // First one is the best. 1547 aInfo = resolutions.get(0).activityInfo; 1548 } 1549 } 1550 } 1551 1552 if (aInfo != null) { 1553 if (!canStartHomeOnDisplayArea(aInfo, taskDisplayArea, 1554 false /* allowInstrumenting */)) { 1555 aInfo = null; 1556 } 1557 } 1558 1559 // Fallback to secondary home component. 1560 if (aInfo == null) { 1561 homeIntent = mService.getSecondaryHomeIntent(null); 1562 aInfo = resolveHomeActivity(userId, homeIntent); 1563 } 1564 return Pair.create(aInfo, homeIntent); 1565 } 1566 1567 /** 1568 * Retrieve all activities that match the given intent. 1569 * The list should already ordered from best to worst matched. 1570 * {@link android.content.pm.PackageManager#queryIntentActivities} 1571 */ 1572 @VisibleForTesting resolveActivities(int userId, Intent homeIntent)1573 List<ResolveInfo> resolveActivities(int userId, Intent homeIntent) { 1574 List<ResolveInfo> resolutions; 1575 try { 1576 final String resolvedType = 1577 homeIntent.resolveTypeIfNeeded(mService.mContext.getContentResolver()); 1578 resolutions = AppGlobals.getPackageManager().queryIntentActivities(homeIntent, 1579 resolvedType, ActivityManagerService.STOCK_PM_FLAGS, userId).getList(); 1580 1581 } catch (RemoteException e) { 1582 resolutions = new ArrayList<>(); 1583 } 1584 return resolutions; 1585 } 1586 resumeHomeActivity(ActivityRecord prev, String reason, TaskDisplayArea taskDisplayArea)1587 boolean resumeHomeActivity(ActivityRecord prev, String reason, 1588 TaskDisplayArea taskDisplayArea) { 1589 if (!mService.isBooting() && !mService.isBooted()) { 1590 // Not ready yet! 1591 return false; 1592 } 1593 1594 if (taskDisplayArea == null) { 1595 taskDisplayArea = getDefaultTaskDisplayArea(); 1596 } 1597 1598 final ActivityRecord r = taskDisplayArea.getHomeActivity(); 1599 final String myReason = reason + " resumeHomeActivity"; 1600 1601 // Only resume home activity if isn't finishing. 1602 if (r != null && !r.finishing) { 1603 r.moveFocusableActivityToTop(myReason); 1604 return resumeFocusedTasksTopActivities(r.getRootTask(), prev, null); 1605 } 1606 int userId = mWmService.getUserAssignedToDisplay(taskDisplayArea.getDisplayId()); 1607 return startHomeOnTaskDisplayArea(userId, myReason, taskDisplayArea, 1608 false /* allowInstrumenting */, false /* fromHomeKey */); 1609 } 1610 1611 /** 1612 * Check if the display area is valid for secondary home activity. 1613 * 1614 * @param taskDisplayArea The target display area. 1615 * @return {@code true} if allow to launch, {@code false} otherwise. 1616 */ shouldPlaceSecondaryHomeOnDisplayArea(TaskDisplayArea taskDisplayArea)1617 boolean shouldPlaceSecondaryHomeOnDisplayArea(TaskDisplayArea taskDisplayArea) { 1618 if (getDefaultTaskDisplayArea() == taskDisplayArea) { 1619 throw new IllegalArgumentException( 1620 "shouldPlaceSecondaryHomeOnDisplay: Should not be on default task container"); 1621 } else if (taskDisplayArea == null) { 1622 return false; 1623 } 1624 1625 if (!taskDisplayArea.canHostHomeTask()) { 1626 // Can't launch home on a TaskDisplayArea that does not support root home task 1627 return false; 1628 } 1629 1630 if (taskDisplayArea.getDisplayId() != DEFAULT_DISPLAY && !mService.mSupportsMultiDisplay) { 1631 // Can't launch home on secondary display if device does not support multi-display. 1632 return false; 1633 } 1634 1635 final boolean deviceProvisioned = Settings.Global.getInt( 1636 mService.mContext.getContentResolver(), 1637 Settings.Global.DEVICE_PROVISIONED, 0) != 0; 1638 if (!deviceProvisioned) { 1639 // Can't launch home on secondary display areas before device is provisioned. 1640 return false; 1641 } 1642 1643 if (!StorageManager.isUserKeyUnlocked(mCurrentUser)) { 1644 // Can't launch home on secondary display areas if device is still locked. 1645 return false; 1646 } 1647 1648 final DisplayContent display = taskDisplayArea.getDisplayContent(); 1649 if (display == null || display.isRemoved() || !display.supportsSystemDecorations()) { 1650 // Can't launch home on display that doesn't support system decorations. 1651 return false; 1652 } 1653 1654 return true; 1655 } 1656 1657 /** 1658 * Check if home activity start should be allowed on a display. 1659 * 1660 * @param homeInfo {@code ActivityInfo} of the home activity that is going to be 1661 * launched. 1662 * @param taskDisplayArea The target display area. 1663 * @param allowInstrumenting Whether launching home should be allowed if being instrumented. 1664 * @return {@code true} if allow to launch, {@code false} otherwise. 1665 */ canStartHomeOnDisplayArea(ActivityInfo homeInfo, TaskDisplayArea taskDisplayArea, boolean allowInstrumenting)1666 boolean canStartHomeOnDisplayArea(ActivityInfo homeInfo, TaskDisplayArea taskDisplayArea, 1667 boolean allowInstrumenting) { 1668 if (mService.mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL 1669 && mService.mTopAction == null) { 1670 // We are running in factory test mode, but unable to find the factory test app, so 1671 // just sit around displaying the error message and don't try to start anything. 1672 return false; 1673 } 1674 1675 final WindowProcessController app = 1676 mService.getProcessController(homeInfo.processName, homeInfo.applicationInfo.uid); 1677 if (!allowInstrumenting && app != null && app.isInstrumenting()) { 1678 // Don't do this if the home app is currently being instrumented. 1679 return false; 1680 } 1681 1682 final int displayId = taskDisplayArea != null ? taskDisplayArea.getDisplayId() 1683 : INVALID_DISPLAY; 1684 if (displayId == DEFAULT_DISPLAY || (displayId != INVALID_DISPLAY 1685 && (displayId == mService.mVr2dDisplayId 1686 || mWmService.shouldPlacePrimaryHomeOnDisplay(displayId)))) { 1687 // No restrictions to default display, vr 2d display or main display for visible users. 1688 return true; 1689 } 1690 1691 if (!shouldPlaceSecondaryHomeOnDisplayArea(taskDisplayArea)) { 1692 return false; 1693 } 1694 1695 final boolean supportMultipleInstance = homeInfo.launchMode != LAUNCH_SINGLE_TASK 1696 && homeInfo.launchMode != LAUNCH_SINGLE_INSTANCE; 1697 if (!supportMultipleInstance) { 1698 // Can't launch home on secondary displays if it requested to be single instance. 1699 return false; 1700 } 1701 1702 return true; 1703 } 1704 1705 /** 1706 * Ensure all activities visibility, update orientation and configuration. 1707 * 1708 * @param starting The currently starting activity or {@code null} if there is 1709 * none. 1710 * @param displayId The id of the display where operation is executed. 1711 * @param markFrozenIfConfigChanged Whether to set {@link ActivityRecord#frozenBeforeDestroy} to 1712 * {@code true} if config changed. 1713 * @param deferResume Whether to defer resume while updating config. 1714 * @return 'true' if starting activity was kept or wasn't provided, 'false' if it was relaunched 1715 * because of configuration update. 1716 */ ensureVisibilityAndConfig(ActivityRecord starting, int displayId, boolean markFrozenIfConfigChanged, boolean deferResume)1717 boolean ensureVisibilityAndConfig(ActivityRecord starting, int displayId, 1718 boolean markFrozenIfConfigChanged, boolean deferResume) { 1719 // First ensure visibility without updating the config just yet. We need this to know what 1720 // activities are affecting configuration now. 1721 // Passing null here for 'starting' param value, so that visibility of actual starting 1722 // activity will be properly updated. 1723 ensureActivitiesVisible(null /* starting */, 0 /* configChanges */, 1724 false /* preserveWindows */, false /* notifyClients */); 1725 1726 if (displayId == INVALID_DISPLAY) { 1727 // The caller didn't provide a valid display id, skip updating config. 1728 return true; 1729 } 1730 1731 // Force-update the orientation from the WindowManager, since we need the true configuration 1732 // to send to the client now. 1733 final DisplayContent displayContent = getDisplayContent(displayId); 1734 Configuration config = null; 1735 if (displayContent != null) { 1736 config = displayContent.updateOrientation(starting, true /* forceUpdate */); 1737 } 1738 // Visibilities may change so let the starting activity have a chance to report. Can't do it 1739 // when visibility is changed in each AppWindowToken because it may trigger wrong 1740 // configuration push because the visibility of some activities may not be updated yet. 1741 if (starting != null) { 1742 starting.reportDescendantOrientationChangeIfNeeded(); 1743 } 1744 if (starting != null && markFrozenIfConfigChanged && config != null) { 1745 starting.frozenBeforeDestroy = true; 1746 } 1747 1748 if (displayContent != null) { 1749 // Update the configuration of the activities on the display. 1750 return displayContent.updateDisplayOverrideConfigurationLocked(config, starting, 1751 deferResume, null /* result */); 1752 } else { 1753 return true; 1754 } 1755 } 1756 1757 /** 1758 * @return a list of pairs, containing activities and their task id which are the top ones in 1759 * each visible root task. The first entry will be the focused activity. 1760 * 1761 * <p>NOTE: If the top activity is in the split screen, the other activities in the same split 1762 * screen will also be returned. 1763 */ getTopVisibleActivities()1764 List<ActivityAssistInfo> getTopVisibleActivities() { 1765 final ArrayList<ActivityAssistInfo> topVisibleActivities = new ArrayList<>(); 1766 final ArrayList<ActivityAssistInfo> activityAssistInfos = new ArrayList<>(); 1767 final Task topFocusedRootTask = getTopDisplayFocusedRootTask(); 1768 // Traverse all displays. 1769 forAllRootTasks(rootTask -> { 1770 // Get top activity from a visible root task and add it to the list. 1771 if (rootTask.shouldBeVisible(null /* starting */)) { 1772 final ActivityRecord top = rootTask.getTopNonFinishingActivity(); 1773 if (top != null) { 1774 activityAssistInfos.clear(); 1775 activityAssistInfos.add(new ActivityAssistInfo(top)); 1776 // Check if the activity on the split screen. 1777 final Task adjacentTask = top.getTask().getAdjacentTask(); 1778 if (adjacentTask != null) { 1779 final ActivityRecord adjacentActivityRecord = 1780 adjacentTask.getTopNonFinishingActivity(); 1781 if (adjacentActivityRecord != null) { 1782 activityAssistInfos.add(new ActivityAssistInfo(adjacentActivityRecord)); 1783 } 1784 } 1785 if (rootTask == topFocusedRootTask) { 1786 topVisibleActivities.addAll(0, activityAssistInfos); 1787 } else { 1788 topVisibleActivities.addAll(activityAssistInfos); 1789 } 1790 } 1791 } 1792 }); 1793 return topVisibleActivities; 1794 } 1795 1796 @Nullable getTopDisplayFocusedRootTask()1797 Task getTopDisplayFocusedRootTask() { 1798 for (int i = getChildCount() - 1; i >= 0; --i) { 1799 final Task focusedRootTask = getChildAt(i).getFocusedRootTask(); 1800 if (focusedRootTask != null) { 1801 return focusedRootTask; 1802 } 1803 } 1804 return null; 1805 } 1806 1807 @Nullable getTopResumedActivity()1808 ActivityRecord getTopResumedActivity() { 1809 final Task focusedRootTask = getTopDisplayFocusedRootTask(); 1810 if (focusedRootTask == null) { 1811 return null; 1812 } 1813 final ActivityRecord resumedActivity = focusedRootTask.getTopResumedActivity(); 1814 if (resumedActivity != null && resumedActivity.app != null) { 1815 return resumedActivity; 1816 } 1817 // The top focused root task might not have a resumed activity yet - look on all displays in 1818 // focus order. 1819 return getItemFromTaskDisplayAreas(TaskDisplayArea::getFocusedActivity); 1820 } 1821 isTopDisplayFocusedRootTask(Task task)1822 boolean isTopDisplayFocusedRootTask(Task task) { 1823 return task != null && task == getTopDisplayFocusedRootTask(); 1824 } 1825 attachApplication(WindowProcessController app)1826 boolean attachApplication(WindowProcessController app) throws RemoteException { 1827 try { 1828 return mAttachApplicationHelper.process(app); 1829 } finally { 1830 mAttachApplicationHelper.reset(); 1831 } 1832 } 1833 1834 /** 1835 * Make sure that all activities that need to be visible in the system actually are and update 1836 * their configuration. 1837 */ ensureActivitiesVisible(ActivityRecord starting, int configChanges, boolean preserveWindows)1838 void ensureActivitiesVisible(ActivityRecord starting, int configChanges, 1839 boolean preserveWindows) { 1840 ensureActivitiesVisible(starting, configChanges, preserveWindows, true /* notifyClients */); 1841 } 1842 1843 /** 1844 * @see #ensureActivitiesVisible(ActivityRecord, int, boolean) 1845 */ ensureActivitiesVisible(ActivityRecord starting, int configChanges, boolean preserveWindows, boolean notifyClients)1846 void ensureActivitiesVisible(ActivityRecord starting, int configChanges, 1847 boolean preserveWindows, boolean notifyClients) { 1848 if (mTaskSupervisor.inActivityVisibilityUpdate() 1849 || mTaskSupervisor.isRootVisibilityUpdateDeferred()) { 1850 // Don't do recursive work. 1851 return; 1852 } 1853 1854 try { 1855 mTaskSupervisor.beginActivityVisibilityUpdate(); 1856 // First the front root tasks. In case any are not fullscreen and are in front of home. 1857 for (int displayNdx = getChildCount() - 1; displayNdx >= 0; --displayNdx) { 1858 final DisplayContent display = getChildAt(displayNdx); 1859 display.ensureActivitiesVisible(starting, configChanges, preserveWindows, 1860 notifyClients); 1861 } 1862 } finally { 1863 mTaskSupervisor.endActivityVisibilityUpdate(); 1864 } 1865 } 1866 switchUser(int userId, UserState uss)1867 boolean switchUser(int userId, UserState uss) { 1868 final Task topFocusedRootTask = getTopDisplayFocusedRootTask(); 1869 final int focusRootTaskId = topFocusedRootTask != null 1870 ? topFocusedRootTask.getRootTaskId() : INVALID_TASK_ID; 1871 // Also dismiss the pinned root task whenever we switch users. Removing the pinned root task 1872 // will also cause all tasks to be moved to the fullscreen root task at a position that is 1873 // appropriate. 1874 removeRootTasksInWindowingModes(WINDOWING_MODE_PINNED); 1875 1876 mUserRootTaskInFront.put(mCurrentUser, focusRootTaskId); 1877 mCurrentUser = userId; 1878 1879 mTaskSupervisor.mStartingUsers.add(uss); 1880 forAllRootTasks(rootTask -> { 1881 rootTask.switchUser(userId); 1882 }); 1883 1884 final int restoreRootTaskId = mUserRootTaskInFront.get(userId); 1885 Task rootTask = getRootTask(restoreRootTaskId); 1886 if (rootTask == null) { 1887 rootTask = getDefaultTaskDisplayArea().getOrCreateRootHomeTask(); 1888 } 1889 final boolean homeInFront = rootTask.isActivityTypeHome(); 1890 if (rootTask.isOnHomeDisplay()) { 1891 rootTask.moveToFront("switchUserOnHomeDisplay"); 1892 } else { 1893 // Root task was moved to another display while user was swapped out. 1894 resumeHomeActivity(null, "switchUserOnOtherDisplay", getDefaultTaskDisplayArea()); 1895 } 1896 return homeInFront; 1897 } 1898 removeUser(int userId)1899 void removeUser(int userId) { 1900 mUserRootTaskInFront.delete(userId); 1901 } 1902 1903 /** 1904 * Update the last used root task id for non-current user (current user's last 1905 * used root task is the focused root task) 1906 */ updateUserRootTask(int userId, Task rootTask)1907 void updateUserRootTask(int userId, Task rootTask) { 1908 if (userId != mCurrentUser) { 1909 if (rootTask == null) { 1910 rootTask = getDefaultTaskDisplayArea().getOrCreateRootHomeTask(); 1911 } 1912 1913 mUserRootTaskInFront.put(userId, rootTask.getRootTaskId()); 1914 } 1915 } 1916 1917 /** 1918 * Move root task with all its existing content to specified task display area. 1919 * 1920 * @param rootTaskId Id of root task to move. 1921 * @param taskDisplayArea The task display area to move root task to. 1922 * @param onTop Indicates whether container should be place on top or on bottom. 1923 */ moveRootTaskToTaskDisplayArea(int rootTaskId, TaskDisplayArea taskDisplayArea, boolean onTop)1924 void moveRootTaskToTaskDisplayArea(int rootTaskId, TaskDisplayArea taskDisplayArea, 1925 boolean onTop) { 1926 final Task rootTask = getRootTask(rootTaskId); 1927 if (rootTask == null) { 1928 throw new IllegalArgumentException("moveRootTaskToTaskDisplayArea: Unknown rootTaskId=" 1929 + rootTaskId); 1930 } 1931 1932 final TaskDisplayArea currentTaskDisplayArea = rootTask.getDisplayArea(); 1933 if (currentTaskDisplayArea == null) { 1934 throw new IllegalStateException("moveRootTaskToTaskDisplayArea: rootTask=" + rootTask 1935 + " is not attached to any task display area."); 1936 } 1937 1938 if (taskDisplayArea == null) { 1939 throw new IllegalArgumentException( 1940 "moveRootTaskToTaskDisplayArea: Unknown taskDisplayArea=" + taskDisplayArea); 1941 } 1942 1943 if (currentTaskDisplayArea == taskDisplayArea) { 1944 throw new IllegalArgumentException("Trying to move rootTask=" + rootTask 1945 + " to its current taskDisplayArea=" + taskDisplayArea); 1946 } 1947 rootTask.reparent(taskDisplayArea, onTop); 1948 1949 // Resume focusable root task after reparenting to another display area. 1950 rootTask.resumeNextFocusAfterReparent(); 1951 1952 // TODO(multi-display): resize rootTasks properly if moved from split-screen. 1953 } 1954 1955 /** 1956 * Move root task with all its existing content to specified display. 1957 * 1958 * @param rootTaskId Id of root task to move. 1959 * @param displayId Id of display to move root task to. 1960 * @param onTop Indicates whether container should be place on top or on bottom. 1961 */ moveRootTaskToDisplay(int rootTaskId, int displayId, boolean onTop)1962 void moveRootTaskToDisplay(int rootTaskId, int displayId, boolean onTop) { 1963 final DisplayContent displayContent = getDisplayContentOrCreate(displayId); 1964 if (displayContent == null) { 1965 throw new IllegalArgumentException("moveRootTaskToDisplay: Unknown displayId=" 1966 + displayId); 1967 } 1968 1969 moveRootTaskToTaskDisplayArea(rootTaskId, displayContent.getDefaultTaskDisplayArea(), 1970 onTop); 1971 } 1972 moveActivityToPinnedRootTask(@onNull ActivityRecord r, @Nullable ActivityRecord launchIntoPipHostActivity, String reason)1973 void moveActivityToPinnedRootTask(@NonNull ActivityRecord r, 1974 @Nullable ActivityRecord launchIntoPipHostActivity, String reason) { 1975 moveActivityToPinnedRootTask(r, launchIntoPipHostActivity, reason, null /* transition */); 1976 } 1977 moveActivityToPinnedRootTask(@onNull ActivityRecord r, @Nullable ActivityRecord launchIntoPipHostActivity, String reason, @Nullable Transition transition)1978 void moveActivityToPinnedRootTask(@NonNull ActivityRecord r, 1979 @Nullable ActivityRecord launchIntoPipHostActivity, String reason, 1980 @Nullable Transition transition) { 1981 final TaskDisplayArea taskDisplayArea = r.getDisplayArea(); 1982 final Task task = r.getTask(); 1983 final Task rootTask; 1984 1985 Transition newTransition = transition; 1986 // Create a transition now (if not provided) to collect the current pinned Task dismiss. 1987 // Only do the create here as the Task (trigger) to enter PIP is not ready yet. 1988 final TransitionController transitionController = task.mTransitionController; 1989 if (newTransition == null && !transitionController.isCollecting() 1990 && transitionController.getTransitionPlayer() != null) { 1991 newTransition = transitionController.createTransition(TRANSIT_PIP); 1992 } 1993 1994 transitionController.deferTransitionReady(); 1995 mService.deferWindowLayout(); 1996 try { 1997 // This will change the root pinned task's windowing mode to its original mode, ensuring 1998 // we only have one root task that is in pinned mode. 1999 final Task rootPinnedTask = taskDisplayArea.getRootPinnedTask(); 2000 if (rootPinnedTask != null) { 2001 transitionController.collect(rootPinnedTask); 2002 // The new ActivityRecord should replace the existing PiP, so it's more desirable 2003 // that the old PiP disappears instead of turning to full-screen at the same time, 2004 // as the Task#dismissPip is trying to do. 2005 removeRootTasksInWindowingModes(WINDOWING_MODE_PINNED); 2006 } 2007 2008 // Set a transition to ensure that we don't immediately try and update the visibility 2009 // of the activity entering PIP 2010 r.getDisplayContent().prepareAppTransition(TRANSIT_NONE); 2011 2012 transitionController.collect(task); 2013 2014 // Defer the windowing mode change until after the transition to prevent the activity 2015 // from doing work and changing the activity visuals while animating 2016 // TODO(task-org): Figure-out more structured way to do this long term. 2017 r.setWindowingMode(r.getWindowingMode()); 2018 2019 final TaskFragment organizedTf = r.getOrganizedTaskFragment(); 2020 final boolean singleActivity = task.getNonFinishingActivityCount() == 1; 2021 if (singleActivity) { 2022 rootTask = task; 2023 2024 // Apply the last recents animation leash transform to the task entering PIP 2025 rootTask.maybeApplyLastRecentsAnimationTransaction(); 2026 2027 if (rootTask.getParent() != taskDisplayArea) { 2028 // root task is nested, but pinned tasks need to be direct children of their 2029 // display area, so reparent. 2030 rootTask.reparent(taskDisplayArea, true /* onTop */); 2031 } 2032 2033 rootTask.forAllTaskFragments(tf -> { 2034 if (!tf.isOrganizedTaskFragment()) { 2035 return; 2036 } 2037 tf.resetAdjacentTaskFragment(); 2038 tf.setCompanionTaskFragment(null /* companionTaskFragment */); 2039 tf.setAnimationParams(TaskFragmentAnimationParams.DEFAULT); 2040 if (tf.getTopNonFinishingActivity() != null) { 2041 // When the Task is entering picture-in-picture, we should clear all 2042 // override from the client organizer, so the PIP activity can get the 2043 // correct config from the Task, and prevent conflict with the 2044 // PipTaskOrganizer. TaskFragmentOrganizer may have requested relative 2045 // bounds, so reset the relative bounds before update configuration. 2046 tf.setRelativeEmbeddedBounds(new Rect()); 2047 tf.updateRequestedOverrideConfiguration(EMPTY); 2048 } 2049 }); 2050 } else { 2051 // In the case of multiple activities, we will create a new task for it and then 2052 // move the PIP activity into the task. Note that we explicitly defer the task 2053 // appear being sent in this case and mark this newly created task to been visible. 2054 rootTask = new Task.Builder(mService) 2055 .setActivityType(r.getActivityType()) 2056 .setOnTop(true) 2057 .setActivityInfo(r.info) 2058 .setParent(taskDisplayArea) 2059 .setIntent(r.intent) 2060 .setDeferTaskAppear(true) 2061 .setHasBeenVisible(true) 2062 .setWindowingMode(task.getRequestedOverrideWindowingMode()) 2063 .build(); 2064 // Establish bi-directional link between the original and pinned task. 2065 r.setLastParentBeforePip(launchIntoPipHostActivity); 2066 // It's possible the task entering PIP is in freeform, so save the last 2067 // non-fullscreen bounds. Then when this new PIP task exits PIP, it can restore 2068 // to its previous freeform bounds. 2069 rootTask.setLastNonFullscreenBounds(task.mLastNonFullscreenBounds); 2070 // When creating a new Task for PiP, set its initial bounds as the TaskFragment in 2071 // case the activity is embedded, so that it can be animated to PiP window from the 2072 // current bounds. 2073 // Use Task#setBoundsUnchecked to skip checking windowing mode as the windowing mode 2074 // will be updated later after this is collected in transition. 2075 rootTask.setBoundsUnchecked(r.getTaskFragment().getBounds()); 2076 2077 // Move the last recents animation transaction from original task to the new one. 2078 if (task.mLastRecentsAnimationTransaction != null) { 2079 rootTask.setLastRecentsAnimationTransaction( 2080 task.mLastRecentsAnimationTransaction, 2081 task.mLastRecentsAnimationOverlay); 2082 task.clearLastRecentsAnimationTransaction(false /* forceRemoveOverlay */); 2083 } else { 2084 // Reset the original task surface 2085 task.resetSurfaceControlTransforms(); 2086 } 2087 2088 // The organized TaskFragment is becoming empty because this activity is reparented 2089 // to a new PIP Task. In this case, we should notify the organizer about why the 2090 // TaskFragment becomes empty. 2091 if (organizedTf != null && organizedTf.getNonFinishingActivityCount() == 1 2092 && organizedTf.getTopNonFinishingActivity() == r) { 2093 organizedTf.mClearedTaskFragmentForPip = true; 2094 } 2095 2096 transitionController.collect(rootTask); 2097 2098 if (transitionController.isShellTransitionsEnabled()) { 2099 // set mode NOW so that when we reparent the activity, it won't be resumed. 2100 // During recents animations, the original task is "occluded" by launcher but 2101 // it wasn't paused (due to transient-launch). If we reparent to the (top) task 2102 // now, it will take focus briefly which confuses the RecentTasks tracker. 2103 rootTask.setWindowingMode(WINDOWING_MODE_PINNED); 2104 } 2105 2106 // There are multiple activities in the task and moving the top activity should 2107 // reveal/leave the other activities in their original task. 2108 // On the other hand, ActivityRecord#onParentChanged takes care of setting the 2109 // up-to-dated root pinned task information on this newly created root task. 2110 r.reparent(rootTask, MAX_VALUE, reason); 2111 2112 // Ensure the leash of new task is in sync with its current bounds after reparent. 2113 rootTask.maybeApplyLastRecentsAnimationTransaction(); 2114 2115 // In the case of this activity entering PIP due to it being moved to the back, 2116 // the old activity would have a TRANSIT_TASK_TO_BACK transition that needs to be 2117 // ran. But, since its visibility did not change (note how it was STOPPED/not 2118 // visible, and with it now at the back stack, it remains not visible), the logic to 2119 // add the transition is automatically skipped. We then add this activity manually 2120 // to the list of apps being closed, and request its transition to be ran. 2121 final ActivityRecord oldTopActivity = task.getTopMostActivity(); 2122 if (oldTopActivity != null && oldTopActivity.isState(STOPPED) 2123 && task.getDisplayContent().mAppTransition.containsTransitRequest( 2124 TRANSIT_TO_BACK)) { 2125 task.getDisplayContent().mClosingApps.add(oldTopActivity); 2126 oldTopActivity.mRequestForceTransition = true; 2127 } 2128 } 2129 2130 // TODO(remove-legacy-transit): Move this to the `singleActivity` case when removing 2131 // legacy transit. 2132 rootTask.setWindowingMode(WINDOWING_MODE_PINNED); 2133 // Set the launch bounds for launch-into-pip Activity on the root task. 2134 if (r.getOptions() != null && r.getOptions().isLaunchIntoPip()) { 2135 // Record the snapshot now, it will be later fetched for content-pip animation. 2136 // We do this early in the process to make sure the right snapshot is used for 2137 // entering content-pip animation. 2138 mWindowManager.mTaskSnapshotController.recordSnapshot( 2139 task, false /* allowSnapshotHome */); 2140 rootTask.setBounds(r.pictureInPictureArgs.getSourceRectHint()); 2141 } 2142 rootTask.setDeferTaskAppear(false); 2143 2144 // After setting this, it is not expected to change activity configuration until the 2145 // transition animation is finished. So the activity can keep consistent appearance 2146 // when animating. 2147 r.mWaitForEnteringPinnedMode = true; 2148 // Reset the state that indicates it can enter PiP while pausing after we've moved it 2149 // to the root pinned task 2150 r.supportsEnterPipOnTaskSwitch = false; 2151 2152 if (organizedTf != null && organizedTf.mClearedTaskFragmentForPip 2153 && organizedTf.isTaskVisibleRequested()) { 2154 // Dispatch the pending info to TaskFragmentOrganizer before PIP animation. 2155 // Otherwise, it will keep waiting for the empty TaskFragment to be non-empty. 2156 mService.mTaskFragmentOrganizerController.dispatchPendingInfoChangedEvent( 2157 organizedTf); 2158 } 2159 } finally { 2160 mService.continueWindowLayout(); 2161 try { 2162 ensureActivitiesVisible(null, 0, false /* preserveWindows */); 2163 } finally { 2164 transitionController.continueTransitionReady(); 2165 } 2166 } 2167 2168 if (newTransition != null) { 2169 // Request at end since we want task-organizer events from ensureActivitiesVisible 2170 // to be recognized. 2171 transitionController.requestStartTransition(newTransition, rootTask, 2172 null /* remoteTransition */, null /* displayChange */); 2173 // A new transition was created just for this operations. Since the operation is 2174 // complete, mark it as ready. 2175 newTransition.setReady(rootTask, true /* ready */); 2176 } 2177 2178 resumeFocusedTasksTopActivities(); 2179 2180 notifyActivityPipModeChanged(r.getTask(), r); 2181 } 2182 2183 /** 2184 * Notifies when an activity enters or leaves PIP mode. 2185 * 2186 * @param task the task of {@param r} 2187 * @param r indicates the activity currently in PIP, can be null to indicate no activity is 2188 * currently in PIP mode. 2189 */ notifyActivityPipModeChanged(@onNull Task task, @Nullable ActivityRecord r)2190 void notifyActivityPipModeChanged(@NonNull Task task, @Nullable ActivityRecord r) { 2191 final boolean inPip = r != null; 2192 if (inPip) { 2193 mService.getTaskChangeNotificationController().notifyActivityPinned(r); 2194 } else { 2195 mService.getTaskChangeNotificationController().notifyActivityUnpinned(); 2196 } 2197 mWindowManager.mPolicy.setPipVisibilityLw(inPip); 2198 mWmService.mTransactionFactory.get() 2199 .setTrustedOverlay(task.getSurfaceControl(), inPip) 2200 .apply(); 2201 } 2202 executeAppTransitionForAllDisplay()2203 void executeAppTransitionForAllDisplay() { 2204 for (int displayNdx = getChildCount() - 1; displayNdx >= 0; --displayNdx) { 2205 final DisplayContent display = getChildAt(displayNdx); 2206 display.mDisplayContent.executeAppTransition(); 2207 } 2208 } 2209 2210 @Nullable findTask(ActivityRecord r, TaskDisplayArea preferredTaskDisplayArea)2211 ActivityRecord findTask(ActivityRecord r, TaskDisplayArea preferredTaskDisplayArea) { 2212 return findTask(r.getActivityType(), r.taskAffinity, r.intent, r.info, 2213 preferredTaskDisplayArea); 2214 } 2215 2216 @Nullable findTask(int activityType, String taskAffinity, Intent intent, ActivityInfo info, TaskDisplayArea preferredTaskDisplayArea)2217 ActivityRecord findTask(int activityType, String taskAffinity, Intent intent, ActivityInfo info, 2218 TaskDisplayArea preferredTaskDisplayArea) { 2219 ProtoLog.d(WM_DEBUG_TASKS, "Looking for task of type=%s, taskAffinity=%s, intent=%s" 2220 + ", info=%s, preferredTDA=%s", activityType, taskAffinity, intent, info, 2221 preferredTaskDisplayArea); 2222 mTmpFindTaskResult.init(activityType, taskAffinity, intent, info); 2223 2224 // Looking up task on preferred display area first 2225 ActivityRecord candidateActivity = null; 2226 if (preferredTaskDisplayArea != null) { 2227 mTmpFindTaskResult.process(preferredTaskDisplayArea); 2228 if (mTmpFindTaskResult.mIdealRecord != null) { 2229 return mTmpFindTaskResult.mIdealRecord; 2230 } else if (mTmpFindTaskResult.mCandidateRecord != null) { 2231 candidateActivity = mTmpFindTaskResult.mCandidateRecord; 2232 } 2233 } 2234 2235 final ActivityRecord idealMatchActivity = getItemFromTaskDisplayAreas(taskDisplayArea -> { 2236 if (taskDisplayArea == preferredTaskDisplayArea) { 2237 return null; 2238 } 2239 2240 mTmpFindTaskResult.process(taskDisplayArea); 2241 if (mTmpFindTaskResult.mIdealRecord != null) { 2242 return mTmpFindTaskResult.mIdealRecord; 2243 } 2244 return null; 2245 }); 2246 if (idealMatchActivity != null) { 2247 return idealMatchActivity; 2248 } 2249 2250 if (WM_DEBUG_TASKS.isEnabled() && candidateActivity == null) { 2251 ProtoLog.d(WM_DEBUG_TASKS, "No task found"); 2252 } 2253 return candidateActivity; 2254 } 2255 2256 /** 2257 * Finish the topmost activities in all root tasks that belong to the crashed app. 2258 * 2259 * @param app The app that crashed. 2260 * @param reason Reason to perform this action. 2261 * @return The task id that was finished in this root task, or INVALID_TASK_ID if none was 2262 * finished. 2263 */ finishTopCrashedActivities(WindowProcessController app, String reason)2264 int finishTopCrashedActivities(WindowProcessController app, String reason) { 2265 Task focusedRootTask = getTopDisplayFocusedRootTask(); 2266 final Task[] finishedTask = new Task[1]; 2267 forAllRootTasks(rootTask -> { 2268 final Task t = rootTask.finishTopCrashedActivityLocked(app, reason); 2269 if (rootTask == focusedRootTask || finishedTask[0] == null) { 2270 finishedTask[0] = t; 2271 } 2272 }); 2273 return finishedTask[0] != null ? finishedTask[0].mTaskId : INVALID_TASK_ID; 2274 } 2275 resumeFocusedTasksTopActivities()2276 boolean resumeFocusedTasksTopActivities() { 2277 return resumeFocusedTasksTopActivities(null, null, null); 2278 } 2279 resumeFocusedTasksTopActivities( Task targetRootTask, ActivityRecord target, ActivityOptions targetOptions)2280 boolean resumeFocusedTasksTopActivities( 2281 Task targetRootTask, ActivityRecord target, ActivityOptions targetOptions) { 2282 return resumeFocusedTasksTopActivities(targetRootTask, target, targetOptions, 2283 false /* deferPause */); 2284 } 2285 resumeFocusedTasksTopActivities( Task targetRootTask, ActivityRecord target, ActivityOptions targetOptions, boolean deferPause)2286 boolean resumeFocusedTasksTopActivities( 2287 Task targetRootTask, ActivityRecord target, ActivityOptions targetOptions, 2288 boolean deferPause) { 2289 if (!mTaskSupervisor.readyToResume()) { 2290 return false; 2291 } 2292 2293 boolean result = false; 2294 if (targetRootTask != null && (targetRootTask.isTopRootTaskInDisplayArea() 2295 || getTopDisplayFocusedRootTask() == targetRootTask)) { 2296 result = targetRootTask.resumeTopActivityUncheckedLocked(target, targetOptions, 2297 deferPause); 2298 } 2299 2300 for (int displayNdx = getChildCount() - 1; displayNdx >= 0; --displayNdx) { 2301 final DisplayContent display = getChildAt(displayNdx); 2302 final boolean curResult = result; 2303 boolean[] resumedOnDisplay = new boolean[1]; 2304 display.forAllRootTasks(rootTask -> { 2305 final ActivityRecord topRunningActivity = rootTask.topRunningActivity(); 2306 if (!rootTask.isFocusableAndVisible() || topRunningActivity == null) { 2307 return; 2308 } 2309 if (rootTask == targetRootTask) { 2310 // Simply update the result for targetRootTask because the targetRootTask 2311 // had already resumed in above. We don't want to resume it again, 2312 // especially in some cases, it would cause a second launch failure 2313 // if app process was dead. 2314 resumedOnDisplay[0] |= curResult; 2315 return; 2316 } 2317 if (topRunningActivity.isState(RESUMED) 2318 && topRunningActivity == rootTask.getDisplayArea().topRunningActivity()) { 2319 // Kick off any lingering app transitions form the MoveTaskToFront operation, 2320 // but only consider the top activity on that display. 2321 rootTask.executeAppTransition(targetOptions); 2322 } else { 2323 resumedOnDisplay[0] |= topRunningActivity.makeActiveIfNeeded(target); 2324 } 2325 }); 2326 result |= resumedOnDisplay[0]; 2327 if (!resumedOnDisplay[0]) { 2328 // In cases when there are no valid activities (e.g. device just booted or launcher 2329 // crashed) it's possible that nothing was resumed on a display. Requesting resume 2330 // of top activity in focused root task explicitly will make sure that at least home 2331 // activity is started and resumed, and no recursion occurs. 2332 final Task focusedRoot = display.getFocusedRootTask(); 2333 if (focusedRoot != null) { 2334 result |= focusedRoot.resumeTopActivityUncheckedLocked(target, targetOptions); 2335 } else if (targetRootTask == null) { 2336 result |= resumeHomeActivity(null /* prev */, "no-focusable-task", 2337 display.getDefaultTaskDisplayArea()); 2338 } 2339 } 2340 } 2341 2342 return result; 2343 } 2344 applySleepTokens(boolean applyToRootTasks)2345 void applySleepTokens(boolean applyToRootTasks) { 2346 boolean builtSleepTransition = false; 2347 for (int displayNdx = getChildCount() - 1; displayNdx >= 0; --displayNdx) { 2348 // Set the sleeping state of the display. 2349 final DisplayContent display = getChildAt(displayNdx); 2350 final boolean displayShouldSleep = display.shouldSleep(); 2351 if (displayShouldSleep == display.isSleeping()) { 2352 continue; 2353 } 2354 display.setIsSleeping(displayShouldSleep); 2355 2356 if (display.mTransitionController.isShellTransitionsEnabled() && !builtSleepTransition 2357 // Only care if there are actual sleep tokens. 2358 && displayShouldSleep && !display.mAllSleepTokens.isEmpty()) { 2359 builtSleepTransition = true; 2360 // We don't actually care about collecting anything here. We really just want 2361 // this as a signal to the transition-player. 2362 final Transition transition = new Transition(TRANSIT_SLEEP, 0 /* flags */, 2363 display.mTransitionController, mWmService.mSyncEngine); 2364 final TransitionController.OnStartCollect sendSleepTransition = (deferred) -> { 2365 if (deferred && !display.shouldSleep()) { 2366 transition.abort(); 2367 } else { 2368 display.mTransitionController.requestStartTransition(transition, 2369 null /* trigger */, null /* remote */, null /* display */); 2370 // Force playing immediately so that unrelated ops can't be collected. 2371 transition.playNow(); 2372 } 2373 }; 2374 if (!display.mTransitionController.isCollecting()) { 2375 // Since this bypasses sync, submit directly ignoring whether sync-engine 2376 // is active. 2377 if (mWindowManager.mSyncEngine.hasActiveSync()) { 2378 Slog.w(TAG, "Ongoing sync outside of a transition."); 2379 } 2380 display.mTransitionController.moveToCollecting(transition); 2381 sendSleepTransition.onCollectStarted(false /* deferred */); 2382 } else { 2383 display.mTransitionController.startCollectOrQueue(transition, 2384 sendSleepTransition); 2385 } 2386 } 2387 2388 if (!applyToRootTasks) { 2389 continue; 2390 } 2391 2392 // Prepare transition before resume top activity, so it can be collected. 2393 if (!displayShouldSleep && display.mTransitionController.isShellTransitionsEnabled() 2394 && !display.mTransitionController.isCollecting()) { 2395 int transit = TRANSIT_NONE; 2396 Task startTask = null; 2397 if (!display.getDisplayPolicy().isAwake()) { 2398 // Note that currently this only happens on default display because non-default 2399 // display is always awake. 2400 transit = TRANSIT_WAKE; 2401 } else if (display.isKeyguardOccluded()) { 2402 // The display was awake so this is resuming activity for occluding keyguard. 2403 transit = WindowManager.TRANSIT_KEYGUARD_OCCLUDE; 2404 startTask = display.getTaskOccludingKeyguard(); 2405 } 2406 if (transit != TRANSIT_NONE) { 2407 display.mTransitionController.requestStartTransition( 2408 display.mTransitionController.createTransition(transit), 2409 startTask, null /* remoteTransition */, null /* displayChange */); 2410 } 2411 } 2412 // Set the sleeping state of the root tasks on the display. 2413 display.forAllRootTasks(rootTask -> { 2414 if (displayShouldSleep) { 2415 rootTask.goToSleepIfPossible(false /* shuttingDown */); 2416 } else { 2417 rootTask.forAllLeafTasksAndLeafTaskFragments( 2418 taskFragment -> taskFragment.awakeFromSleeping(), 2419 true /* traverseTopToBottom */); 2420 if (rootTask.isFocusedRootTaskOnDisplay() 2421 && !mTaskSupervisor.getKeyguardController() 2422 .isKeyguardOrAodShowing(display.mDisplayId)) { 2423 // If the keyguard is unlocked - resume immediately. 2424 // It is possible that the display will not be awake at the time we 2425 // process the keyguard going away, which can happen before the sleep 2426 // token is released. As a result, it is important we resume the 2427 // activity here. 2428 rootTask.resumeTopActivityUncheckedLocked(null, null); 2429 } 2430 // The visibility update must not be called before resuming the top, so the 2431 // display orientation can be updated first if needed. Otherwise there may 2432 // have redundant configuration changes due to apply outdated display 2433 // orientation (from keyguard) to activity. 2434 rootTask.ensureActivitiesVisible(null /* starting */, 0 /* configChanges */, 2435 false /* preserveWindows */); 2436 } 2437 }); 2438 } 2439 } 2440 getRootTask(int rooTaskId)2441 protected Task getRootTask(int rooTaskId) { 2442 for (int i = getChildCount() - 1; i >= 0; --i) { 2443 final Task rootTask = getChildAt(i).getRootTask(rooTaskId); 2444 if (rootTask != null) { 2445 return rootTask; 2446 } 2447 } 2448 return null; 2449 } 2450 2451 /** @see DisplayContent#getRootTask(int, int) */ getRootTask(int windowingMode, int activityType)2452 Task getRootTask(int windowingMode, int activityType) { 2453 for (int i = getChildCount() - 1; i >= 0; --i) { 2454 final Task rootTask = getChildAt(i).getRootTask(windowingMode, activityType); 2455 if (rootTask != null) { 2456 return rootTask; 2457 } 2458 } 2459 return null; 2460 } 2461 getRootTask(int windowingMode, int activityType, int displayId)2462 private Task getRootTask(int windowingMode, int activityType, 2463 int displayId) { 2464 DisplayContent display = getDisplayContent(displayId); 2465 if (display == null) { 2466 return null; 2467 } 2468 return display.getRootTask(windowingMode, activityType); 2469 } 2470 getRootTaskInfo(Task task)2471 private RootTaskInfo getRootTaskInfo(Task task) { 2472 RootTaskInfo info = new RootTaskInfo(); 2473 task.fillTaskInfo(info); 2474 2475 final DisplayContent displayContent = task.getDisplayContent(); 2476 if (displayContent == null) { 2477 // A task might be not attached to a display. 2478 info.position = -1; 2479 } else { 2480 // Find the task z-order among all root tasks on the display from bottom to top. 2481 final int[] taskIndex = new int[1]; 2482 final boolean[] hasFound = new boolean[1]; 2483 displayContent.forAllRootTasks(rootTask -> { 2484 if (task == rootTask) { 2485 hasFound[0] = true; 2486 return true; 2487 } 2488 taskIndex[0]++; 2489 return false; 2490 }, false /* traverseTopToBottom */); 2491 info.position = hasFound[0] ? taskIndex[0] : -1; 2492 } 2493 info.visible = task.shouldBeVisible(null); 2494 task.getBounds(info.bounds); 2495 2496 final int numTasks = task.getDescendantTaskCount(); 2497 info.childTaskIds = new int[numTasks]; 2498 info.childTaskNames = new String[numTasks]; 2499 info.childTaskBounds = new Rect[numTasks]; 2500 info.childTaskUserIds = new int[numTasks]; 2501 final int[] currentIndex = {0}; 2502 2503 task.forAllLeafTasks(t -> { 2504 int i = currentIndex[0]; 2505 info.childTaskIds[i] = t.mTaskId; 2506 info.childTaskNames[i] = t.origActivity != null ? t.origActivity.flattenToString() 2507 : t.realActivity != null ? t.realActivity.flattenToString() 2508 : t.getTopNonFinishingActivity() != null 2509 ? t.getTopNonFinishingActivity().packageName : "unknown"; 2510 info.childTaskBounds[i] = t.mAtmService.getTaskBounds(t.mTaskId); 2511 info.childTaskUserIds[i] = t.mUserId; 2512 currentIndex[0] = ++i; 2513 }, false /* traverseTopToBottom */); 2514 2515 final ActivityRecord top = task.topRunningActivity(); 2516 info.topActivity = top != null ? top.intent.getComponent() : null; 2517 return info; 2518 } 2519 getRootTaskInfo(int taskId)2520 RootTaskInfo getRootTaskInfo(int taskId) { 2521 Task task = getRootTask(taskId); 2522 if (task != null) { 2523 return getRootTaskInfo(task); 2524 } 2525 return null; 2526 } 2527 getRootTaskInfo(int windowingMode, int activityType)2528 RootTaskInfo getRootTaskInfo(int windowingMode, int activityType) { 2529 final Task rootTask = getRootTask(windowingMode, activityType); 2530 return (rootTask != null) ? getRootTaskInfo(rootTask) : null; 2531 } 2532 getRootTaskInfo(int windowingMode, int activityType, int displayId)2533 RootTaskInfo getRootTaskInfo(int windowingMode, int activityType, int displayId) { 2534 final Task rootTask = getRootTask(windowingMode, activityType, displayId); 2535 return (rootTask != null) ? getRootTaskInfo(rootTask) : null; 2536 } 2537 2538 /** If displayId == INVALID_DISPLAY, this will get root task infos on all displays */ getAllRootTaskInfos(int displayId)2539 ArrayList<RootTaskInfo> getAllRootTaskInfos(int displayId) { 2540 final ArrayList<RootTaskInfo> list = new ArrayList<>(); 2541 if (displayId == INVALID_DISPLAY) { 2542 forAllRootTasks(rootTask -> { 2543 list.add(getRootTaskInfo(rootTask)); 2544 }); 2545 return list; 2546 } 2547 final DisplayContent display = getDisplayContent(displayId); 2548 if (display == null) { 2549 return list; 2550 } 2551 display.forAllRootTasks(rootTask -> { 2552 list.add(getRootTaskInfo(rootTask)); 2553 }); 2554 return list; 2555 } 2556 2557 @Override onDisplayAdded(int displayId)2558 public void onDisplayAdded(int displayId) { 2559 if (DEBUG_ROOT_TASK) Slog.v(TAG, "Display added displayId=" + displayId); 2560 synchronized (mService.mGlobalLock) { 2561 final DisplayContent display = getDisplayContentOrCreate(displayId); 2562 if (display == null) { 2563 return; 2564 } 2565 // Do not start home before booting, or it may accidentally finish booting before it 2566 // starts. Instead, we expect home activities to be launched when the system is ready 2567 // (ActivityManagerService#systemReady). 2568 if (mService.isBooted() || mService.isBooting()) { 2569 startSystemDecorations(display); 2570 } 2571 // Drop any cached DisplayInfos associated with this display id - the values are now 2572 // out of date given this display added event. 2573 mWmService.mPossibleDisplayInfoMapper.removePossibleDisplayInfos(displayId); 2574 } 2575 } 2576 startSystemDecorations(final DisplayContent displayContent)2577 private void startSystemDecorations(final DisplayContent displayContent) { 2578 startHomeOnDisplay(mCurrentUser, "displayAdded", displayContent.getDisplayId()); 2579 displayContent.getDisplayPolicy().notifyDisplayReady(); 2580 } 2581 2582 @Override onDisplayRemoved(int displayId)2583 public void onDisplayRemoved(int displayId) { 2584 if (DEBUG_ROOT_TASK) Slog.v(TAG, "Display removed displayId=" + displayId); 2585 if (displayId == DEFAULT_DISPLAY) { 2586 throw new IllegalArgumentException("Can't remove the primary display."); 2587 } 2588 2589 synchronized (mService.mGlobalLock) { 2590 final DisplayContent displayContent = getDisplayContent(displayId); 2591 if (displayContent == null) { 2592 return; 2593 } 2594 displayContent.remove(); 2595 mWmService.mPossibleDisplayInfoMapper.removePossibleDisplayInfos(displayId); 2596 } 2597 } 2598 2599 @Override onDisplayChanged(int displayId)2600 public void onDisplayChanged(int displayId) { 2601 if (DEBUG_ROOT_TASK) Slog.v(TAG, "Display changed displayId=" + displayId); 2602 synchronized (mService.mGlobalLock) { 2603 final DisplayContent displayContent = getDisplayContent(displayId); 2604 if (displayContent != null) { 2605 displayContent.onDisplayChanged(); 2606 } 2607 // Drop any cached DisplayInfos associated with this display id - the values are now 2608 // out of date given this display changed event. 2609 mWmService.mPossibleDisplayInfoMapper.removePossibleDisplayInfos(displayId); 2610 updateDisplayImePolicyCache(); 2611 } 2612 } 2613 updateDisplayImePolicyCache()2614 void updateDisplayImePolicyCache() { 2615 ArrayMap<Integer, Integer> displayImePolicyMap = new ArrayMap<>(); 2616 forAllDisplays(dc -> displayImePolicyMap.put(dc.getDisplayId(), dc.getImePolicy())); 2617 mWmService.mDisplayImePolicyCache = Collections.unmodifiableMap(displayImePolicyMap); 2618 } 2619 2620 /** Update lists of UIDs that are present on displays and have access to them. */ updateUIDsPresentOnDisplay()2621 void updateUIDsPresentOnDisplay() { 2622 mDisplayAccessUIDs.clear(); 2623 for (int displayNdx = getChildCount() - 1; displayNdx >= 0; --displayNdx) { 2624 final DisplayContent displayContent = getChildAt(displayNdx); 2625 // Only bother calculating the allowlist for private displays 2626 if (displayContent.isPrivate()) { 2627 mDisplayAccessUIDs.append( 2628 displayContent.mDisplayId, displayContent.getPresentUIDs()); 2629 } 2630 } 2631 // Store updated lists in DisplayManager. Callers from outside of AM should get them there. 2632 mDisplayManagerInternal.setDisplayAccessUIDs(mDisplayAccessUIDs); 2633 } 2634 prepareForShutdown()2635 void prepareForShutdown() { 2636 for (int i = 0; i < getChildCount(); i++) { 2637 createSleepToken("shutdown", getChildAt(i).mDisplayId); 2638 } 2639 } 2640 createSleepToken(String tag, int displayId)2641 SleepToken createSleepToken(String tag, int displayId) { 2642 return createSleepToken(tag, displayId, false /* isSwappingDisplay */); 2643 } 2644 createSleepToken(String tag, int displayId, boolean isSwappingDisplay)2645 SleepToken createSleepToken(String tag, int displayId, boolean isSwappingDisplay) { 2646 final DisplayContent display = getDisplayContent(displayId); 2647 if (display == null) { 2648 throw new IllegalArgumentException("Invalid display: " + displayId); 2649 } 2650 2651 final int tokenKey = makeSleepTokenKey(tag, displayId); 2652 SleepToken token = mSleepTokens.get(tokenKey); 2653 if (token == null) { 2654 token = new SleepToken(tag, displayId, isSwappingDisplay); 2655 mSleepTokens.put(tokenKey, token); 2656 display.mAllSleepTokens.add(token); 2657 ProtoLog.d(WM_DEBUG_STATES, "Create sleep token: tag=%s, displayId=%d", tag, displayId); 2658 } else { 2659 throw new RuntimeException("Create the same sleep token twice: " + token); 2660 } 2661 return token; 2662 } 2663 removeSleepToken(SleepToken token)2664 void removeSleepToken(SleepToken token) { 2665 if (!mSleepTokens.contains(token.mHashKey)) { 2666 Slog.d(TAG, "Remove non-exist sleep token: " + token + " from " + Debug.getCallers(6)); 2667 } 2668 mSleepTokens.remove(token.mHashKey); 2669 final DisplayContent display = getDisplayContent(token.mDisplayId); 2670 if (display == null) { 2671 Slog.d(TAG, "Remove sleep token for non-existing display: " + token + " from " 2672 + Debug.getCallers(6)); 2673 return; 2674 } 2675 2676 ProtoLog.d(WM_DEBUG_STATES, "Remove sleep token: tag=%s, displayId=%d", token.mTag, 2677 token.mDisplayId); 2678 display.mAllSleepTokens.remove(token); 2679 if (display.mAllSleepTokens.isEmpty()) { 2680 mService.updateSleepIfNeededLocked(); 2681 // Assuming no lock screen is set and a user launches an activity, turns off the screen 2682 // and turn on the screen again, then the launched activity should be displayed on the 2683 // screen without app transition animation. When the screen turns on, both keyguard 2684 // sleep token and display off sleep token are removed, but the order is 2685 // non-deterministic. 2686 // Note: Display#mSkipAppTransitionAnimation will be ignored when keyguard related 2687 // transition exists, so this affects only when no lock screen is set. Otherwise 2688 // keyguard going away animation will be played. 2689 // See also AppTransitionController#getTransitCompatType for more details. 2690 if ((!mTaskSupervisor.getKeyguardController().isDisplayOccluded(display.mDisplayId) 2691 && token.mTag.equals(KEYGUARD_SLEEP_TOKEN_TAG)) 2692 || token.mTag.equals(DISPLAY_OFF_SLEEP_TOKEN_TAG)) { 2693 display.mSkipAppTransitionAnimation = true; 2694 } 2695 } 2696 } 2697 addStartingWindowsForVisibleActivities()2698 void addStartingWindowsForVisibleActivities() { 2699 final ArrayList<Task> addedTasks = new ArrayList<>(); 2700 forAllActivities((r) -> { 2701 final Task task = r.getTask(); 2702 if (r.isVisibleRequested() && r.mStartingData == null && !addedTasks.contains(task)) { 2703 r.showStartingWindow(true /*taskSwitch*/); 2704 addedTasks.add(task); 2705 } 2706 }); 2707 } 2708 invalidateTaskLayers()2709 void invalidateTaskLayers() { 2710 if (!mTaskLayersChanged) { 2711 mTaskLayersChanged = true; 2712 mService.mH.post(mRankTaskLayersRunnable); 2713 } 2714 } 2715 2716 /** Generate oom-score-adjustment rank for all tasks in the system based on z-order. */ rankTaskLayers()2717 void rankTaskLayers() { 2718 if (mTaskLayersChanged) { 2719 mTaskLayersChanged = false; 2720 mService.mH.removeCallbacks(mRankTaskLayersRunnable); 2721 } 2722 mTmpTaskLayerRank = 0; 2723 // Only rank for leaf tasks because the score of activity is based on immediate parent. 2724 forAllLeafTasks(task -> { 2725 final int oldRank = task.mLayerRank; 2726 final ActivityRecord r = task.topRunningActivityLocked(); 2727 if (r != null && r.isVisibleRequested()) { 2728 task.mLayerRank = ++mTmpTaskLayerRank; 2729 } else { 2730 task.mLayerRank = Task.LAYER_RANK_INVISIBLE; 2731 } 2732 if (task.mLayerRank != oldRank) { 2733 task.forAllActivities(activity -> { 2734 if (activity.hasProcess()) { 2735 mTaskSupervisor.onProcessActivityStateChanged(activity.app, 2736 true /* forceBatch */); 2737 } 2738 }); 2739 } 2740 }, true /* traverseTopToBottom */); 2741 2742 if (!mTaskSupervisor.inActivityVisibilityUpdate()) { 2743 mTaskSupervisor.computeProcessActivityStateBatch(); 2744 } 2745 } 2746 clearOtherAppTimeTrackers(AppTimeTracker except)2747 void clearOtherAppTimeTrackers(AppTimeTracker except) { 2748 forAllActivities(r -> { 2749 if (r.appTimeTracker != except) { 2750 r.appTimeTracker = null; 2751 } 2752 }); 2753 } 2754 scheduleDestroyAllActivities(String reason)2755 void scheduleDestroyAllActivities(String reason) { 2756 mDestroyAllActivitiesReason = reason; 2757 mService.mH.post(mDestroyAllActivitiesRunnable); 2758 } 2759 2760 // Tries to put all activity tasks to sleep. Returns true if all tasks were 2761 // successfully put to sleep. putTasksToSleep(boolean allowDelay, boolean shuttingDown)2762 boolean putTasksToSleep(boolean allowDelay, boolean shuttingDown) { 2763 final boolean[] result = {true}; 2764 forAllRootTasks(task -> { 2765 if (allowDelay) { 2766 result[0] &= task.goToSleepIfPossible(shuttingDown); 2767 } else { 2768 task.ensureActivitiesVisible(null /* starting */, 0 /* configChanges */, 2769 !PRESERVE_WINDOWS); 2770 } 2771 }); 2772 return result[0]; 2773 } 2774 findActivity(Intent intent, ActivityInfo info, boolean compareIntentFilters)2775 ActivityRecord findActivity(Intent intent, ActivityInfo info, boolean compareIntentFilters) { 2776 ComponentName cls = intent.getComponent(); 2777 if (info.targetActivity != null) { 2778 cls = new ComponentName(info.packageName, info.targetActivity); 2779 } 2780 final int userId = UserHandle.getUserId(info.applicationInfo.uid); 2781 2782 final PooledPredicate p = PooledLambda.obtainPredicate( 2783 RootWindowContainer::matchesActivity, PooledLambda.__(ActivityRecord.class), 2784 userId, compareIntentFilters, intent, cls); 2785 final ActivityRecord r = getActivity(p); 2786 p.recycle(); 2787 return r; 2788 } 2789 matchesActivity(ActivityRecord r, int userId, boolean compareIntentFilters, Intent intent, ComponentName cls)2790 private static boolean matchesActivity(ActivityRecord r, int userId, 2791 boolean compareIntentFilters, Intent intent, ComponentName cls) { 2792 if (!r.canBeTopRunning() || r.mUserId != userId) return false; 2793 2794 if (compareIntentFilters) { 2795 if (r.intent.filterEquals(intent)) { 2796 return true; 2797 } 2798 } else { 2799 // Compare the target component instead of intent component so we don't miss if the 2800 // activity uses alias. 2801 if (r.mActivityComponent.equals(cls)) { 2802 return true; 2803 } 2804 } 2805 return false; 2806 } 2807 hasAwakeDisplay()2808 boolean hasAwakeDisplay() { 2809 for (int displayNdx = getChildCount() - 1; displayNdx >= 0; --displayNdx) { 2810 final DisplayContent display = getChildAt(displayNdx); 2811 if (!display.shouldSleep()) { 2812 return true; 2813 } 2814 } 2815 return false; 2816 } 2817 getOrCreateRootTask(@ullable ActivityRecord r, @Nullable ActivityOptions options, @Nullable Task candidateTask, boolean onTop)2818 Task getOrCreateRootTask(@Nullable ActivityRecord r, @Nullable ActivityOptions options, 2819 @Nullable Task candidateTask, boolean onTop) { 2820 return getOrCreateRootTask(r, options, candidateTask, null /* sourceTask */, onTop, 2821 null /* launchParams */, 0 /* launchFlags */); 2822 } 2823 2824 /** 2825 * Returns the right root task to use for launching factoring in all the input parameters. 2826 * 2827 * @param r The activity we are trying to launch. Can be null. 2828 * @param options The activity options used to the launch. Can be null. 2829 * @param candidateTask The possible task the activity might be launched in. Can be null. 2830 * @param sourceTask The task requesting to start activity. Can be null. 2831 * @param launchParams The resolved launch params to use. 2832 * @param launchFlags The launch flags for this launch. 2833 * @param realCallingPid The pid from {@link ActivityStarter#setRealCallingPid} 2834 * @param realCallingUid The uid from {@link ActivityStarter#setRealCallingUid} 2835 * @return The root task to use for the launch. 2836 */ getOrCreateRootTask(@ullable ActivityRecord r, @Nullable ActivityOptions options, @Nullable Task candidateTask, @Nullable Task sourceTask, boolean onTop, @Nullable LaunchParamsController.LaunchParams launchParams, int launchFlags)2837 Task getOrCreateRootTask(@Nullable ActivityRecord r, 2838 @Nullable ActivityOptions options, @Nullable Task candidateTask, 2839 @Nullable Task sourceTask, boolean onTop, 2840 @Nullable LaunchParamsController.LaunchParams launchParams, int launchFlags) { 2841 // First preference goes to the launch root task set in the activity options. 2842 if (options != null) { 2843 final Task candidateRoot = Task.fromWindowContainerToken(options.getLaunchRootTask()); 2844 if (candidateRoot != null && canLaunchOnDisplay(r, candidateRoot)) { 2845 return candidateRoot; 2846 } 2847 } 2848 2849 // Next preference goes to the task id set in the activity options. 2850 if (options != null) { 2851 final int candidateTaskId = options.getLaunchTaskId(); 2852 if (candidateTaskId != INVALID_TASK_ID) { 2853 // Temporarily set the task id to invalid in case in re-entry. 2854 options.setLaunchTaskId(INVALID_TASK_ID); 2855 final Task task = anyTaskForId(candidateTaskId, 2856 MATCH_ATTACHED_TASK_OR_RECENT_TASKS_AND_RESTORE, options, onTop); 2857 options.setLaunchTaskId(candidateTaskId); 2858 if (canLaunchOnDisplay(r, task)) { 2859 return task.getRootTask(); 2860 } 2861 } 2862 } 2863 2864 // Next preference goes to the TaskDisplayArea candidate from launchParams 2865 // or activity options. 2866 TaskDisplayArea taskDisplayArea = null; 2867 if (launchParams != null && launchParams.mPreferredTaskDisplayArea != null) { 2868 taskDisplayArea = launchParams.mPreferredTaskDisplayArea; 2869 } else if (options != null) { 2870 final WindowContainerToken daToken = options.getLaunchTaskDisplayArea(); 2871 taskDisplayArea = daToken != null 2872 ? (TaskDisplayArea) WindowContainer.fromBinder(daToken.asBinder()) : null; 2873 if (taskDisplayArea == null) { 2874 final int launchDisplayId = options.getLaunchDisplayId(); 2875 if (launchDisplayId != INVALID_DISPLAY) { 2876 final DisplayContent displayContent = getDisplayContent(launchDisplayId); 2877 if (displayContent != null) { 2878 taskDisplayArea = displayContent.getDefaultTaskDisplayArea(); 2879 } 2880 } 2881 } 2882 } 2883 2884 final int activityType = resolveActivityType(r, options, candidateTask); 2885 if (taskDisplayArea != null) { 2886 if (canLaunchOnDisplay(r, taskDisplayArea.getDisplayId())) { 2887 return taskDisplayArea.getOrCreateRootTask(r, options, candidateTask, 2888 sourceTask, launchParams, launchFlags, activityType, onTop); 2889 } else { 2890 taskDisplayArea = null; 2891 } 2892 } 2893 2894 // Give preference to the root task and display of the input task and activity if they 2895 // match the mode we want to launch into. 2896 Task rootTask = null; 2897 if (candidateTask != null) { 2898 rootTask = candidateTask.getRootTask(); 2899 } 2900 if (rootTask == null && r != null) { 2901 rootTask = r.getRootTask(); 2902 } 2903 int windowingMode = launchParams != null ? launchParams.mWindowingMode 2904 : WindowConfiguration.WINDOWING_MODE_UNDEFINED; 2905 if (rootTask != null) { 2906 taskDisplayArea = rootTask.getDisplayArea(); 2907 if (taskDisplayArea != null 2908 && canLaunchOnDisplay(r, taskDisplayArea.mDisplayContent.mDisplayId)) { 2909 if (windowingMode == WindowConfiguration.WINDOWING_MODE_UNDEFINED) { 2910 windowingMode = taskDisplayArea.resolveWindowingMode(r, options, candidateTask); 2911 } 2912 // Always allow organized tasks that created by organizer since the activity type 2913 // of an organized task is decided by the activity type of its top child, which 2914 // could be incompatible with the given windowing mode and activity type. 2915 if (rootTask.isCompatible(windowingMode, activityType) 2916 || rootTask.mCreatedByOrganizer) { 2917 return rootTask; 2918 } 2919 } else { 2920 taskDisplayArea = null; 2921 } 2922 2923 } 2924 2925 // Falling back to default task container 2926 if (taskDisplayArea == null) { 2927 taskDisplayArea = getDefaultTaskDisplayArea(); 2928 } 2929 return taskDisplayArea.getOrCreateRootTask(r, options, candidateTask, sourceTask, 2930 launchParams, launchFlags, activityType, onTop); 2931 } 2932 canLaunchOnDisplay(ActivityRecord r, Task task)2933 private boolean canLaunchOnDisplay(ActivityRecord r, Task task) { 2934 if (task == null) { 2935 Slog.w(TAG, "canLaunchOnDisplay(), invalid task: " + task); 2936 return false; 2937 } 2938 2939 if (!task.isAttached()) { 2940 Slog.w(TAG, "canLaunchOnDisplay(), Task is not attached: " + task); 2941 return false; 2942 } 2943 2944 return canLaunchOnDisplay(r, task.getTaskDisplayArea().getDisplayId()); 2945 } 2946 2947 /** @return true if activity record is null or can be launched on provided display. */ canLaunchOnDisplay(ActivityRecord r, int displayId)2948 private boolean canLaunchOnDisplay(ActivityRecord r, int displayId) { 2949 if (r == null) { 2950 return true; 2951 } 2952 if (!r.canBeLaunchedOnDisplay(displayId)) { 2953 Slog.w(TAG, "Not allow to launch " + r + " on display " + displayId); 2954 return false; 2955 } 2956 return true; 2957 } 2958 resolveActivityType(@ullable ActivityRecord r, @Nullable ActivityOptions options, @Nullable Task task)2959 int resolveActivityType(@Nullable ActivityRecord r, @Nullable ActivityOptions options, 2960 @Nullable Task task) { 2961 // Preference is given to the activity type for the activity then the task since the type 2962 // once set shouldn't change. 2963 int activityType = r != null ? r.getActivityType() : ACTIVITY_TYPE_UNDEFINED; 2964 if (activityType == ACTIVITY_TYPE_UNDEFINED && task != null) { 2965 activityType = task.getActivityType(); 2966 } 2967 if (activityType != ACTIVITY_TYPE_UNDEFINED) { 2968 return activityType; 2969 } 2970 if (options != null) { 2971 activityType = options.getLaunchActivityType(); 2972 } 2973 return activityType != ACTIVITY_TYPE_UNDEFINED ? activityType : ACTIVITY_TYPE_STANDARD; 2974 } 2975 2976 /** 2977 * Get next focusable root task in the system. This will search through the root task on the 2978 * same display as the current focused root task, looking for a focusable and visible root task, 2979 * different from the target root task. If no valid candidates will be found, it will then go 2980 * through all displays and root tasks in last-focused order. 2981 * 2982 * @param currentFocus The root task that previously had focus. 2983 * @param ignoreCurrent If we should ignore {@param currentFocus} when searching for next 2984 * candidate. 2985 * @return Next focusable {@link Task}, {@code null} if not found. 2986 */ getNextFocusableRootTask(@onNull Task currentFocus, boolean ignoreCurrent)2987 Task getNextFocusableRootTask(@NonNull Task currentFocus, boolean ignoreCurrent) { 2988 // First look for next focusable root task on the same display 2989 TaskDisplayArea preferredDisplayArea = currentFocus.getDisplayArea(); 2990 if (preferredDisplayArea == null) { 2991 // Root task is currently detached because it is being removed. Use the previous 2992 // display it was on. 2993 preferredDisplayArea = getDisplayContent(currentFocus.mPrevDisplayId) 2994 .getDefaultTaskDisplayArea(); 2995 } 2996 final Task preferredFocusableRootTask = preferredDisplayArea.getNextFocusableRootTask( 2997 currentFocus, ignoreCurrent); 2998 if (preferredFocusableRootTask != null) { 2999 return preferredFocusableRootTask; 3000 } 3001 if (preferredDisplayArea.mDisplayContent.supportsSystemDecorations()) { 3002 // Stop looking for focusable root task on other displays because the preferred display 3003 // supports system decorations. Home activity would be launched on the same display if 3004 // no focusable root task found. 3005 return null; 3006 } 3007 3008 // Now look through all displays 3009 for (int i = getChildCount() - 1; i >= 0; --i) { 3010 final DisplayContent display = getChildAt(i); 3011 if (display == preferredDisplayArea.mDisplayContent) { 3012 // We've already checked this one 3013 continue; 3014 } 3015 final Task nextFocusableRootTask = display.getDefaultTaskDisplayArea() 3016 .getNextFocusableRootTask(currentFocus, ignoreCurrent); 3017 if (nextFocusableRootTask != null) { 3018 return nextFocusableRootTask; 3019 } 3020 } 3021 3022 return null; 3023 } 3024 closeSystemDialogActivities(String reason)3025 void closeSystemDialogActivities(String reason) { 3026 forAllActivities((r) -> { 3027 if ((r.info.flags & ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0 3028 || shouldCloseAssistant(r, reason)) { 3029 r.finishIfPossible(reason, true /* oomAdj */); 3030 } 3031 }); 3032 } 3033 3034 /** 3035 * Returns {@code true} if {@code uid} has a visible window that's above the window of type 3036 * {@link WindowManager.LayoutParams#TYPE_NOTIFICATION_SHADE} and {@code uid} is not owner of 3037 * the window of type {@link WindowManager.LayoutParams#TYPE_NOTIFICATION_SHADE}. 3038 * 3039 * If there is no window with type {@link WindowManager.LayoutParams#TYPE_NOTIFICATION_SHADE}, 3040 * it returns {@code false}. 3041 */ hasVisibleWindowAboveButDoesNotOwnNotificationShade(int uid)3042 boolean hasVisibleWindowAboveButDoesNotOwnNotificationShade(int uid) { 3043 boolean[] visibleWindowFound = {false}; 3044 // We only return true if we found the notification shade (ie. window of type 3045 // TYPE_NOTIFICATION_SHADE). Usually, it should always be there, but if for some reason 3046 // it isn't, we should better be on the safe side and return false for this. 3047 return forAllWindows(w -> { 3048 if (w.mOwnerUid == uid && w.isVisible()) { 3049 visibleWindowFound[0] = true; 3050 } 3051 if (w.mAttrs.type == TYPE_NOTIFICATION_SHADE) { 3052 return visibleWindowFound[0] && w.mOwnerUid != uid; 3053 } 3054 return false; 3055 }, true /* traverseTopToBottom */); 3056 } 3057 3058 private boolean shouldCloseAssistant(ActivityRecord r, String reason) { 3059 if (!r.isActivityTypeAssistant()) return false; 3060 if (reason == SYSTEM_DIALOG_REASON_ASSIST) return false; 3061 // When the assistant is configured to be on top of the dream, it will have higher z-order 3062 // than other activities. If it is also opaque, it will prevent other activities from 3063 // starting. We want to close the assistant on closeSystemDialogs to allow other activities 3064 // to start, e.g. on home button press. 3065 return mWmService.mAssistantOnTopOfDream; 3066 } 3067 3068 FinishDisabledPackageActivitiesHelper mFinishDisabledPackageActivitiesHelper = 3069 new FinishDisabledPackageActivitiesHelper(); 3070 3071 class FinishDisabledPackageActivitiesHelper implements Predicate<ActivityRecord> { 3072 private String mPackageName; 3073 private Set<String> mFilterByClasses; 3074 private boolean mDoit; 3075 private boolean mEvenPersistent; 3076 private int mUserId; 3077 private boolean mOnlyRemoveNoProcess; 3078 private Task mLastTask; 3079 private final ArrayList<ActivityRecord> mCollectedActivities = new ArrayList<>(); 3080 3081 private void reset(String packageName, Set<String> filterByClasses, 3082 boolean doit, boolean evenPersistent, int userId, boolean onlyRemoveNoProcess) { 3083 mPackageName = packageName; 3084 mFilterByClasses = filterByClasses; 3085 mDoit = doit; 3086 mEvenPersistent = evenPersistent; 3087 mUserId = userId; 3088 mOnlyRemoveNoProcess = onlyRemoveNoProcess; 3089 mLastTask = null; 3090 } 3091 3092 boolean process(String packageName, Set<String> filterByClasses, 3093 boolean doit, boolean evenPersistent, int userId, boolean onlyRemoveNoProcess) { 3094 reset(packageName, filterByClasses, doit, evenPersistent, userId, onlyRemoveNoProcess); 3095 forAllActivities(this); 3096 3097 boolean didSomething = false; 3098 final int size = mCollectedActivities.size(); 3099 // Keep the finishing order from top to bottom. 3100 for (int i = 0; i < size; i++) { 3101 final ActivityRecord r = mCollectedActivities.get(i); 3102 if (mOnlyRemoveNoProcess) { 3103 if (!r.hasProcess()) { 3104 didSomething = true; 3105 Slog.i(TAG, " Force removing " + r); 3106 r.cleanUp(false /* cleanServices */, false /* setState */); 3107 r.removeFromHistory("force-stop"); 3108 } 3109 } else { 3110 didSomething = true; 3111 Slog.i(TAG, " Force finishing " + r); 3112 r.finishIfPossible("force-stop", true /* oomAdj */); 3113 } 3114 } 3115 mCollectedActivities.clear(); 3116 3117 return didSomething; 3118 } 3119 3120 @Override 3121 public boolean test(ActivityRecord r) { 3122 final boolean sameComponent = 3123 (r.packageName.equals(mPackageName) && (mFilterByClasses == null 3124 || mFilterByClasses.contains(r.mActivityComponent.getClassName()))) 3125 || (mPackageName == null && r.mUserId == mUserId); 3126 final boolean noProcess = !r.hasProcess(); 3127 if ((mUserId == UserHandle.USER_ALL || r.mUserId == mUserId) 3128 && (sameComponent || r.getTask() == mLastTask) 3129 && (noProcess || mEvenPersistent || !r.app.isPersistent())) { 3130 if (!mDoit) { 3131 if (r.finishing) { 3132 // If this activity is just finishing, then it is not 3133 // interesting as far as something to stop. 3134 return false; 3135 } 3136 return true; 3137 } 3138 mCollectedActivities.add(r); 3139 mLastTask = r.getTask(); 3140 } 3141 3142 return false; 3143 } 3144 } 3145 3146 /** @return true if some activity was finished (or would have finished if doit were true). */ 3147 boolean finishDisabledPackageActivities(String packageName, Set<String> filterByClasses, 3148 boolean doit, boolean evenPersistent, int userId, boolean onlyRemoveNoProcess) { 3149 return mFinishDisabledPackageActivitiesHelper.process(packageName, filterByClasses, doit, 3150 evenPersistent, userId, onlyRemoveNoProcess); 3151 } 3152 3153 void updateActivityApplicationInfo(ApplicationInfo aInfo) { 3154 final String packageName = aInfo.packageName; 3155 final int userId = UserHandle.getUserId(aInfo.uid); 3156 forAllActivities(r -> { 3157 if (r.mUserId == userId && packageName.equals(r.packageName)) { 3158 r.updateApplicationInfo(aInfo); 3159 } 3160 }); 3161 } 3162 3163 void finishVoiceTask(IVoiceInteractionSession session) { 3164 final IBinder binder = session.asBinder(); 3165 forAllLeafTasks(t -> t.finishIfVoiceTask(binder), true /* traverseTopToBottom */); 3166 } 3167 3168 /** 3169 * Removes root tasks in the input windowing modes from the system if they are of activity type 3170 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED 3171 */ 3172 void removeRootTasksInWindowingModes(int... windowingModes) { 3173 for (int i = getChildCount() - 1; i >= 0; --i) { 3174 getChildAt(i).removeRootTasksInWindowingModes(windowingModes); 3175 } 3176 } 3177 3178 void removeRootTasksWithActivityTypes(int... activityTypes) { 3179 for (int i = getChildCount() - 1; i >= 0; --i) { 3180 getChildAt(i).removeRootTasksWithActivityTypes(activityTypes); 3181 } 3182 } 3183 3184 ActivityRecord topRunningActivity() { 3185 for (int i = getChildCount() - 1; i >= 0; --i) { 3186 final ActivityRecord topActivity = getChildAt(i).topRunningActivity(); 3187 if (topActivity != null) { 3188 return topActivity; 3189 } 3190 } 3191 return null; 3192 } 3193 3194 boolean allResumedActivitiesIdle() { 3195 for (int displayNdx = getChildCount() - 1; displayNdx >= 0; --displayNdx) { 3196 // TODO(b/117135575): Check resumed activities on all visible root tasks. 3197 final DisplayContent display = getChildAt(displayNdx); 3198 if (display.isSleeping()) { 3199 // No resumed activities while display is sleeping. 3200 continue; 3201 } 3202 3203 // If the focused root task is not null or not empty, there should have some activities 3204 // resuming or resumed. Make sure these activities are idle. 3205 final Task rootTask = display.getFocusedRootTask(); 3206 if (rootTask == null || !rootTask.hasActivity()) { 3207 continue; 3208 } 3209 final ActivityRecord resumedActivity = rootTask.getTopResumedActivity(); 3210 if (resumedActivity == null || !resumedActivity.idle) { 3211 ProtoLog.d(WM_DEBUG_STATES, "allResumedActivitiesIdle: rootTask=%d %s " 3212 + "not idle", rootTask.getRootTaskId(), resumedActivity); 3213 return false; 3214 } 3215 if (mTransitionController.isTransientLaunch(resumedActivity)) { 3216 // Not idle if the transient transition animation is running. 3217 return false; 3218 } 3219 } 3220 // End power mode launch when idle. 3221 mService.endLaunchPowerMode(ActivityTaskManagerService.POWER_MODE_REASON_START_ACTIVITY); 3222 return true; 3223 } 3224 3225 boolean allResumedActivitiesVisible() { 3226 boolean[] foundResumed = {false}; 3227 final boolean foundInvisibleResumedActivity = forAllRootTasks(rootTask -> { 3228 final ActivityRecord r = rootTask.getTopResumedActivity(); 3229 if (r != null) { 3230 if (!r.nowVisible) { 3231 return true; 3232 } 3233 foundResumed[0] = true; 3234 } 3235 return false; 3236 }); 3237 if (foundInvisibleResumedActivity) { 3238 return false; 3239 } 3240 return foundResumed[0]; 3241 } 3242 3243 boolean allPausedActivitiesComplete() { 3244 boolean[] pausing = {true}; 3245 final boolean hasActivityNotCompleted = forAllLeafTasks(task -> { 3246 final ActivityRecord r = task.getTopPausingActivity(); 3247 if (r != null && !r.isState(PAUSED, STOPPED, STOPPING, FINISHING)) { 3248 ProtoLog.d(WM_DEBUG_STATES, "allPausedActivitiesComplete: " 3249 + "r=%s state=%s", r, r.getState()); 3250 if (WM_DEBUG_STATES.isEnabled()) { 3251 pausing[0] = false; 3252 } else { 3253 return true; 3254 } 3255 } 3256 return false; 3257 }); 3258 if (hasActivityNotCompleted) { 3259 return false; 3260 } 3261 return pausing[0]; 3262 } 3263 3264 /** 3265 * Find all tasks containing {@param userId} and intercept them with an activity 3266 * to block out the contents and possibly start a credential-confirming intent. 3267 * 3268 * @param userId user handle for the locked managed profile. 3269 */ 3270 void lockAllProfileTasks(@UserIdInt int userId) { 3271 forAllLeafTasks(task -> { 3272 final ActivityRecord top = task.topRunningActivity(); 3273 if (top != null && !top.finishing 3274 && ACTION_CONFIRM_DEVICE_CREDENTIAL_WITH_USER.equals(top.intent.getAction()) 3275 && top.packageName.equals( 3276 mService.getSysUiServiceComponentLocked().getPackageName())) { 3277 // Do nothing since the task is already secure by sysui. 3278 return; 3279 } 3280 3281 if (task.getActivity(activity -> !activity.finishing && activity.mUserId == userId) 3282 != null) { 3283 mService.getTaskChangeNotificationController().notifyTaskProfileLocked( 3284 task.getTaskInfo(), userId); 3285 } 3286 }, true /* traverseTopToBottom */); 3287 } 3288 3289 Task anyTaskForId(int id) { 3290 return anyTaskForId(id, MATCH_ATTACHED_TASK_OR_RECENT_TASKS_AND_RESTORE); 3291 } 3292 3293 Task anyTaskForId(int id, @RootWindowContainer.AnyTaskForIdMatchTaskMode int matchMode) { 3294 return anyTaskForId(id, matchMode, null, !ON_TOP); 3295 } 3296 3297 /** 3298 * Returns a {@link Task} for the input id if available. {@code null} otherwise. 3299 * 3300 * @param id Id of the task we would like returned. 3301 * @param matchMode The mode to match the given task id in. 3302 * @param aOptions The activity options to use for restoration. Can be null. 3303 * @param onTop If the root task for the task should be the topmost on the display. 3304 */ 3305 Task anyTaskForId(int id, @RootWindowContainer.AnyTaskForIdMatchTaskMode int matchMode, 3306 @Nullable ActivityOptions aOptions, boolean onTop) { 3307 // If options are set, ensure that we are attempting to actually restore a task 3308 if (matchMode != MATCH_ATTACHED_TASK_OR_RECENT_TASKS_AND_RESTORE && aOptions != null) { 3309 throw new IllegalArgumentException("Should not specify activity options for non-restore" 3310 + " lookup"); 3311 } 3312 3313 final PooledPredicate p = PooledLambda.obtainPredicate( 3314 Task::isTaskId, PooledLambda.__(Task.class), id); 3315 Task task = getTask(p); 3316 p.recycle(); 3317 3318 if (task != null) { 3319 if (aOptions != null) { 3320 // Resolve the root task the task should be placed in now based on options 3321 // and reparent if needed. 3322 // TODO(b/229927851) For split-screen, setLaunchRootTask is no longer the "root" 3323 // task, consider to rename methods like "parentTask" instead of "rootTask". 3324 final Task targetRootTask = 3325 getOrCreateRootTask(null, aOptions, task, onTop); 3326 // When launch with ActivityOptions#getLaunchRootTask, the "root task" just mean the 3327 // parent of current launch, not the "root task" in hierarchy. 3328 if (targetRootTask != null && task.getRootTask() != targetRootTask 3329 && task.getParent() != targetRootTask) { 3330 final int reparentMode = onTop 3331 ? REPARENT_MOVE_ROOT_TASK_TO_FRONT : REPARENT_LEAVE_ROOT_TASK_IN_PLACE; 3332 task.reparent(targetRootTask, onTop, reparentMode, ANIMATE, DEFER_RESUME, 3333 "anyTaskForId"); 3334 } 3335 } 3336 return task; 3337 } 3338 3339 // If we are matching root task tasks only, return now 3340 if (matchMode == MATCH_ATTACHED_TASK_ONLY) { 3341 return null; 3342 } 3343 3344 // Otherwise, check the recent tasks and return if we find it there and we are not restoring 3345 // the task from recents 3346 if (DEBUG_RECENTS) Slog.v(TAG_RECENTS, "Looking for task id=" + id + " in recents"); 3347 task = mTaskSupervisor.mRecentTasks.getTask(id); 3348 3349 if (task == null) { 3350 if (DEBUG_RECENTS) { 3351 Slog.d(TAG_RECENTS, "\tDidn't find task id=" + id + " in recents"); 3352 } 3353 3354 return null; 3355 } 3356 3357 if (matchMode == MATCH_ATTACHED_TASK_OR_RECENT_TASKS) { 3358 return task; 3359 } 3360 3361 // Implicitly, this case is MATCH_ATTACHED_TASK_OR_RECENT_TASKS_AND_RESTORE 3362 if (!mTaskSupervisor.restoreRecentTaskLocked(task, aOptions, onTop)) { 3363 if (DEBUG_RECENTS) { 3364 Slog.w(TAG_RECENTS, 3365 "Couldn't restore task id=" + id + " found in recents"); 3366 } 3367 return null; 3368 } 3369 if (DEBUG_RECENTS) Slog.w(TAG_RECENTS, "Restored task id=" + id + " from in recents"); 3370 return task; 3371 } 3372 3373 @VisibleForTesting 3374 void getRunningTasks(int maxNum, List<ActivityManager.RunningTaskInfo> list, 3375 int flags, int callingUid, ArraySet<Integer> profileIds, int displayId) { 3376 WindowContainer root = this; 3377 if (displayId != INVALID_DISPLAY) { 3378 root = getDisplayContent(displayId); 3379 if (root == null) { 3380 return; 3381 } 3382 } 3383 mTaskSupervisor.getRunningTasks().getTasks(maxNum, list, flags, mService.getRecentTasks(), 3384 root, callingUid, profileIds); 3385 } 3386 3387 void startPowerModeLaunchIfNeeded(boolean forceSend, ActivityRecord targetActivity) { 3388 if (!forceSend && targetActivity != null && targetActivity.app != null) { 3389 // Set power mode when the activity's process is different than the current top resumed 3390 // activity on all display areas, or if there are no resumed activities in the system. 3391 boolean[] noResumedActivities = {true}; 3392 boolean[] allFocusedProcessesDiffer = {true}; 3393 forAllTaskDisplayAreas(taskDisplayArea -> { 3394 final ActivityRecord resumedActivity = taskDisplayArea.getFocusedActivity(); 3395 final WindowProcessController resumedActivityProcess = 3396 resumedActivity == null ? null : resumedActivity.app; 3397 3398 noResumedActivities[0] &= resumedActivityProcess == null; 3399 if (resumedActivityProcess != null) { 3400 allFocusedProcessesDiffer[0] &= 3401 !resumedActivityProcess.equals(targetActivity.app); 3402 } 3403 }); 3404 if (!noResumedActivities[0] && !allFocusedProcessesDiffer[0]) { 3405 // All focused activities are resumed and the process of the target activity is 3406 // the same as them, e.g. delivering new intent to the current top. 3407 return; 3408 } 3409 } 3410 3411 int reason = ActivityTaskManagerService.POWER_MODE_REASON_START_ACTIVITY; 3412 // If the activity is launching while keyguard is locked (including occluded), the activity 3413 // may be visible until its first relayout is done (e.g. apply show-when-lock flag). To 3414 // avoid power mode from being cleared before that, add a special reason to consider whether 3415 // the unknown visibility is resolved. The case from SystemUI is excluded because it should 3416 // rely on keyguard-going-away. 3417 final boolean isKeyguardLocked = (targetActivity != null) 3418 ? targetActivity.isKeyguardLocked() : mDefaultDisplay.isKeyguardLocked(); 3419 if (isKeyguardLocked && targetActivity != null 3420 && !targetActivity.isLaunchSourceType(ActivityRecord.LAUNCH_SOURCE_TYPE_SYSTEMUI)) { 3421 final ActivityOptions opts = targetActivity.getOptions(); 3422 if (opts == null || opts.getSourceInfo() == null 3423 || opts.getSourceInfo().type != ActivityOptions.SourceInfo.TYPE_LOCKSCREEN) { 3424 reason |= ActivityTaskManagerService.POWER_MODE_REASON_UNKNOWN_VISIBILITY; 3425 } 3426 } 3427 mService.startLaunchPowerMode(reason); 3428 } 3429 3430 /** 3431 * Iterate over all task fragments, to see if there exists one that meets the 3432 * PermissionPolicyService's criteria to show a permission dialog. 3433 */ 3434 public int getTaskToShowPermissionDialogOn(String pkgName, int uid) { 3435 PermissionPolicyInternal pPi = mService.getPermissionPolicyInternal(); 3436 if (pPi == null) { 3437 return INVALID_TASK_ID; 3438 } 3439 3440 final int[] validTaskId = {INVALID_TASK_ID}; 3441 forAllLeafTaskFragments(fragment -> { 3442 ActivityRecord record = fragment.getActivity((r) -> { 3443 // skip hidden (or about to hide) apps, or the permission dialog 3444 return r.canBeTopRunning() && r.isVisibleRequested() 3445 && !pPi.isIntentToPermissionDialog(r.intent); 3446 }); 3447 if (record != null && record.isUid(uid) 3448 && Objects.equals(pkgName, record.packageName) 3449 && pPi.shouldShowNotificationDialogForTask(record.getTask().getTaskInfo(), 3450 pkgName, record.launchedFromPackage, record.intent, record.getName())) { 3451 validTaskId[0] = record.getTask().mTaskId; 3452 return true; 3453 } 3454 return false; 3455 }); 3456 3457 return validTaskId[0]; 3458 } 3459 3460 /** 3461 * Dumps the activities matching the given {@param name} in the either the focused root task 3462 * or all visible root tasks if {@param dumpVisibleRootTasksOnly} is true. 3463 */ 3464 ArrayList<ActivityRecord> getDumpActivities(String name, boolean dumpVisibleRootTasksOnly, 3465 boolean dumpFocusedRootTaskOnly, @UserIdInt int userId) { 3466 if (dumpFocusedRootTaskOnly) { 3467 final Task topFocusedRootTask = getTopDisplayFocusedRootTask(); 3468 if (topFocusedRootTask != null) { 3469 return topFocusedRootTask.getDumpActivitiesLocked(name, userId); 3470 } else { 3471 return new ArrayList<>(); 3472 } 3473 } else { 3474 final RecentTasks recentTasks = mWindowManager.mAtmService.getRecentTasks(); 3475 final int recentsComponentUid = recentTasks != null 3476 ? recentTasks.getRecentsComponentUid() 3477 : -1; 3478 final ArrayList<ActivityRecord> activities = new ArrayList<>(); 3479 forAllLeafTasks(task -> { 3480 final boolean isRecents = (task.effectiveUid == recentsComponentUid); 3481 if (!dumpVisibleRootTasksOnly || task.shouldBeVisible(null) || isRecents) { 3482 activities.addAll(task.getDumpActivitiesLocked(name, userId)); 3483 } 3484 return false; 3485 }); 3486 return activities; 3487 } 3488 } 3489 3490 @Override 3491 public void dump(PrintWriter pw, String prefix, boolean dumpAll) { 3492 super.dump(pw, prefix, dumpAll); 3493 pw.print(prefix); 3494 pw.println("topDisplayFocusedRootTask=" + getTopDisplayFocusedRootTask()); 3495 for (int i = getChildCount() - 1; i >= 0; --i) { 3496 final DisplayContent display = getChildAt(i); 3497 display.dump(pw, prefix, dumpAll); 3498 } 3499 } 3500 3501 /** 3502 * Dump all connected displays' configurations. 3503 * 3504 * @param prefix Prefix to apply to each line of the dump. 3505 */ 3506 void dumpDisplayConfigs(PrintWriter pw, String prefix) { 3507 pw.print(prefix); 3508 pw.println("Display override configurations:"); 3509 final int displayCount = getChildCount(); 3510 for (int i = 0; i < displayCount; i++) { 3511 final DisplayContent displayContent = getChildAt(i); 3512 pw.print(prefix); 3513 pw.print(" "); 3514 pw.print(displayContent.mDisplayId); 3515 pw.print(": "); 3516 pw.println(displayContent.getRequestedOverrideConfiguration()); 3517 } 3518 } 3519 3520 boolean dumpActivities(FileDescriptor fd, PrintWriter pw, boolean dumpAll, boolean dumpClient, 3521 String dumpPackage, int displayIdFilter) { 3522 boolean[] printed = {false}; 3523 boolean[] needSep = {false}; 3524 for (int displayNdx = getChildCount() - 1; displayNdx >= 0; --displayNdx) { 3525 DisplayContent displayContent = getChildAt(displayNdx); 3526 if (printed[0]) { 3527 pw.println(); 3528 } 3529 if (displayIdFilter != Display.INVALID_DISPLAY 3530 && displayContent.mDisplayId != displayIdFilter) { 3531 continue; 3532 } 3533 pw.print("Display #"); 3534 pw.print(displayContent.mDisplayId); 3535 pw.println(" (activities from top to bottom):"); 3536 displayContent.forAllRootTasks(rootTask -> { 3537 if (needSep[0]) { 3538 pw.println(); 3539 } 3540 needSep[0] = rootTask.dump(fd, pw, dumpAll, dumpClient, dumpPackage, false); 3541 printed[0] |= needSep[0]; 3542 }); 3543 displayContent.forAllTaskDisplayAreas(taskDisplayArea -> { 3544 printed[0] |= printThisActivity(pw, taskDisplayArea.getFocusedActivity(), 3545 dumpPackage, needSep[0], " Resumed: ", () -> 3546 pw.println(" Resumed activities in task display areas" 3547 + " (from top to bottom):")); 3548 }); 3549 } 3550 3551 printed[0] |= dumpHistoryList(fd, pw, mTaskSupervisor.mFinishingActivities, " ", 3552 "Fin", false, !dumpAll, 3553 false, dumpPackage, true, 3554 () -> pw.println(" Activities waiting to finish:"), null); 3555 printed[0] |= dumpHistoryList(fd, pw, mTaskSupervisor.mStoppingActivities, " ", 3556 "Stop", false, !dumpAll, 3557 false, dumpPackage, true, 3558 () -> pw.println(" Activities waiting to stop:"), null); 3559 3560 return printed[0]; 3561 } 3562 3563 private static int makeSleepTokenKey(String tag, int displayId) { 3564 final String tokenKey = tag + displayId; 3565 return tokenKey.hashCode(); 3566 } 3567 3568 static final class SleepToken { 3569 private final String mTag; 3570 private final long mAcquireTime; 3571 private final int mDisplayId; 3572 private final boolean mIsSwappingDisplay; 3573 final int mHashKey; 3574 3575 // The display could remain in sleep after the physical display swapped, adding a 1 3576 // seconds display swap timeout to prevent activities staying in PAUSED state. 3577 // Otherwise, the sleep token should be removed once display turns back on after swapped. 3578 private static final long DISPLAY_SWAP_TIMEOUT = 1000; 3579 3580 SleepToken(String tag, int displayId, boolean isSwappingDisplay) { 3581 mTag = tag; 3582 mDisplayId = displayId; 3583 mAcquireTime = SystemClock.uptimeMillis(); 3584 mIsSwappingDisplay = isSwappingDisplay; 3585 mHashKey = makeSleepTokenKey(mTag, mDisplayId); 3586 } 3587 3588 public boolean isDisplaySwapping() { 3589 long now = SystemClock.uptimeMillis(); 3590 if (now - mAcquireTime > DISPLAY_SWAP_TIMEOUT) { 3591 return false; 3592 } 3593 return mIsSwappingDisplay; 3594 } 3595 3596 @Override 3597 public String toString() { 3598 return "{\"" + mTag + "\", display " + mDisplayId 3599 + (mIsSwappingDisplay ? " is swapping " : "") 3600 + ", acquire at " + TimeUtils.formatUptime(mAcquireTime) + "}"; 3601 } 3602 3603 void writeTagToProto(ProtoOutputStream proto, long fieldId) { 3604 proto.write(fieldId, mTag); 3605 } 3606 } 3607 3608 private class RankTaskLayersRunnable implements Runnable { 3609 @Override 3610 public void run() { 3611 synchronized (mService.mGlobalLock) { 3612 if (mTaskLayersChanged) { 3613 mTaskLayersChanged = false; 3614 rankTaskLayers(); 3615 } 3616 } 3617 } 3618 } 3619 3620 private class AttachApplicationHelper implements Consumer<Task>, Predicate<ActivityRecord> { 3621 private boolean mHasActivityStarted; 3622 private RemoteException mRemoteException; 3623 private WindowProcessController mApp; 3624 private ActivityRecord mTop; 3625 3626 void reset() { 3627 mHasActivityStarted = false; 3628 mRemoteException = null; 3629 mApp = null; 3630 mTop = null; 3631 } 3632 3633 boolean process(WindowProcessController app) throws RemoteException { 3634 mApp = app; 3635 for (int displayNdx = getChildCount() - 1; displayNdx >= 0; --displayNdx) { 3636 getChildAt(displayNdx).forAllRootTasks(this); 3637 if (mRemoteException != null) { 3638 throw mRemoteException; 3639 } 3640 } 3641 if (!mHasActivityStarted) { 3642 ensureActivitiesVisible(null /* starting */, 0 /* configChanges */, 3643 false /* preserveWindows */); 3644 } 3645 return mHasActivityStarted; 3646 } 3647 3648 @Override 3649 public void accept(Task rootTask) { 3650 if (mRemoteException != null) { 3651 return; 3652 } 3653 if (rootTask.getVisibility(null /* starting */) 3654 == TASK_FRAGMENT_VISIBILITY_INVISIBLE) { 3655 return; 3656 } 3657 mTop = rootTask.topRunningActivity(); 3658 rootTask.forAllActivities(this); 3659 } 3660 3661 @Override 3662 public boolean test(ActivityRecord r) { 3663 if (r.finishing || !r.showToCurrentUser() || !r.visibleIgnoringKeyguard 3664 || r.app != null || mApp.mUid != r.info.applicationInfo.uid 3665 || !mApp.mName.equals(r.processName)) { 3666 return false; 3667 } 3668 3669 try { 3670 if (mTaskSupervisor.realStartActivityLocked(r, mApp, 3671 mTop == r && r.getTask().canBeResumed(r) /* andResume */, 3672 true /* checkConfig */)) { 3673 mHasActivityStarted = true; 3674 } 3675 } catch (RemoteException e) { 3676 Slog.w(TAG, "Exception in new application when starting activity " + mTop, e); 3677 mRemoteException = e; 3678 return true; 3679 } 3680 return false; 3681 } 3682 } 3683 } 3684