diff --git a/core/java/android/app/ActivityManagerInternal.java b/core/java/android/app/ActivityManagerInternal.java index 92aabb591e037..de7cc9d53f2fc 100644 --- a/core/java/android/app/ActivityManagerInternal.java +++ b/core/java/android/app/ActivityManagerInternal.java @@ -219,7 +219,7 @@ public abstract class ActivityManagerInternal { * @param userId * @param event * @param appToken ActivityRecord's appToken. - * @param taskRoot TaskRecord's root + * @param taskRoot Task's root */ public abstract void updateActivityUsageStats( ComponentName activity, @UserIdInt int userId, int event, IBinder appToken, diff --git a/data/etc/services.core.protolog.json b/data/etc/services.core.protolog.json index 5b9b703468070..456f69845e5e7 100644 --- a/data/etc/services.core.protolog.json +++ b/data/etc/services.core.protolog.json @@ -1345,12 +1345,6 @@ "group": "WM_SHOW_TRANSACTIONS", "at": "com\/android\/server\/wm\/Session.java" }, - "609651209": { - "message": "addChild: %s at top.", - "level": "VERBOSE", - "group": "WM_DEBUG_ADD_REMOVE", - "at": "com\/android\/server\/wm\/TaskRecord.java" - }, "620368427": { "message": "******* TELLING SURFACE FLINGER WE ARE BOOTED!", "level": "INFO", @@ -1669,6 +1663,12 @@ "group": "WM_DEBUG_ORIENTATION", "at": "com\/android\/server\/wm\/WindowState.java" }, + "1330804250": { + "message": "addChild: %s at top.", + "level": "VERBOSE", + "group": "WM_DEBUG_ADD_REMOVE", + "at": "com\/android\/server\/wm\/Task.java" + }, "1331177619": { "message": "Attempted to add a toast window with unknown token %s. Aborting.", "level": "WARN", diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java index a6d216fea7e2a..aeff9ea50b111 100644 --- a/services/core/java/com/android/server/am/ActivityManagerService.java +++ b/services/core/java/com/android/server/am/ActivityManagerService.java @@ -3054,7 +3054,7 @@ public class ActivityManagerService extends IActivityManager.Stub * @param userId * @param event * @param appToken ActivityRecord's appToken. - * @param taskRoot TaskRecord's root + * @param taskRoot Task's root */ public void updateActivityUsageStats(ComponentName activity, int userId, int event, IBinder appToken, ComponentName taskRoot) { diff --git a/services/core/java/com/android/server/wm/ActivityDisplay.java b/services/core/java/com/android/server/wm/ActivityDisplay.java index 86c8dc57557cf..73c20a7f8387b 100644 --- a/services/core/java/com/android/server/wm/ActivityDisplay.java +++ b/services/core/java/com/android/server/wm/ActivityDisplay.java @@ -403,7 +403,7 @@ class ActivityDisplay extends ConfigurationContainer { * @see #getOrCreateStack(int, int, boolean) */ T getOrCreateStack(@Nullable ActivityRecord r, - @Nullable ActivityOptions options, @Nullable TaskRecord candidateTask, int activityType, + @Nullable ActivityOptions options, @Nullable Task candidateTask, int activityType, boolean onTop) { // First preference is the windowing mode in the activity options if set. int windowingMode = (options != null) @@ -850,7 +850,7 @@ class ActivityDisplay extends ConfigurationContainer { * @return The resolved (not UNDEFINED) windowing-mode that the activity would be in. */ int resolveWindowingMode(@Nullable ActivityRecord r, @Nullable ActivityOptions options, - @Nullable TaskRecord task, int activityType) { + @Nullable Task task, int activityType) { // First preference if the windowing mode in the activity options if set. int windowingMode = (options != null) @@ -881,12 +881,12 @@ class ActivityDisplay extends ConfigurationContainer { * * @param windowingMode The windowing-mode to validate. * @param r The {@link ActivityRecord} to check against. - * @param task The {@link TaskRecord} to check against. + * @param task The {@link Task} to check against. * @param activityType An activity type. * @return The provided windowingMode or the closest valid mode which is appropriate. */ - int validateWindowingMode(int windowingMode, @Nullable ActivityRecord r, - @Nullable TaskRecord task, int activityType) { + int validateWindowingMode(int windowingMode, @Nullable ActivityRecord r, @Nullable Task task, + int activityType) { // Make sure the windowing mode we are trying to use makes sense for what is supported. boolean supportsMultiWindow = mService.mSupportsMultiWindow; boolean supportsSplitScreen = mService.mSupportsSplitScreenMultiWindow; @@ -1447,9 +1447,9 @@ class ActivityDisplay extends ConfigurationContainer { return null; } - final ArrayList tasks = mHomeStack.getAllTasks(); + final ArrayList tasks = mHomeStack.getAllTasks(); for (int taskNdx = tasks.size() - 1; taskNdx >= 0; --taskNdx) { - final TaskRecord task = tasks.get(taskNdx); + final Task task = tasks.get(taskNdx); if (!task.isActivityTypeHome()) { continue; } @@ -1545,7 +1545,7 @@ class ActivityDisplay extends ConfigurationContainer { void removeAllTasks() { for (int i = getChildCount() - 1; i >= 0; --i) { final ActivityStack stack = getChildAt(i); - final ArrayList tasks = stack.getAllTasks(); + final ArrayList tasks = stack.getAllTasks(); for (int j = tasks.size() - 1; j >= 0; --j) { stack.removeChild(tasks.get(j), "removeAllTasks"); } diff --git a/services/core/java/com/android/server/wm/ActivityMetricsLogger.java b/services/core/java/com/android/server/wm/ActivityMetricsLogger.java index c506e274ef645..73034b020a76d 100644 --- a/services/core/java/com/android/server/wm/ActivityMetricsLogger.java +++ b/services/core/java/com/android/server/wm/ActivityMetricsLogger.java @@ -92,6 +92,7 @@ import com.android.internal.logging.MetricsLogger; import com.android.internal.os.BackgroundThread; import com.android.internal.os.SomeArgs; import com.android.server.LocalServices; + import java.util.concurrent.TimeUnit; /** @@ -171,7 +172,7 @@ class ActivityMetricsLogger { switch (msg.what) { case MSG_CHECK_VISIBILITY: final SomeArgs args = (SomeArgs) msg.obj; - checkVisibility((TaskRecord) args.arg1, (ActivityRecord) args.arg2); + checkVisibility((Task) args.arg1, (ActivityRecord) args.arg2); break; } } @@ -536,7 +537,7 @@ class ActivityMetricsLogger { if (info.launchedActivity != activityRecord) { return; } - final TaskRecord t = activityRecord.getTaskRecord(); + final Task t = activityRecord.getTask(); final SomeArgs args = SomeArgs.obtain(); args.arg1 = t; args.arg2 = activityRecord; @@ -544,7 +545,7 @@ class ActivityMetricsLogger { } /** @return {@code true} if the given task has an activity will be drawn. */ - private static boolean hasActivityToBeDrawn(TaskRecord t) { + private static boolean hasActivityToBeDrawn(Task t) { for (int i = t.getChildCount() - 1; i >= 0; --i) { final ActivityRecord r = t.getChildAt(i); if (r.visible && !r.mDrawn && !r.finishing) { @@ -554,7 +555,7 @@ class ActivityMetricsLogger { return false; } - private void checkVisibility(TaskRecord t, ActivityRecord r) { + private void checkVisibility(Task t, ActivityRecord r) { synchronized (mSupervisor.mService.mGlobalLock) { final WindowingModeTransitionInfo info = mWindowingModeTransitionInfo.get( @@ -984,7 +985,7 @@ class ActivityMetricsLogger { } } else if (info.startResult == START_SUCCESS || (info.startResult == START_TASK_TO_FRONT)) { - // TaskRecord may still exist when cold launching an activity and the start + // Task may still exist when cold launching an activity and the start // result will be set to START_TASK_TO_FRONT. Treat this as a COLD launch. return TYPE_TRANSITION_COLD_LAUNCH; } diff --git a/services/core/java/com/android/server/wm/ActivityRecord.java b/services/core/java/com/android/server/wm/ActivityRecord.java index 708e5a19bb0c2..39432f5f0f4d0 100644 --- a/services/core/java/com/android/server/wm/ActivityRecord.java +++ b/services/core/java/com/android/server/wm/ActivityRecord.java @@ -42,7 +42,6 @@ import static android.app.WindowConfiguration.ACTIVITY_TYPE_RECENTS; import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED; import static android.app.WindowConfiguration.ROTATION_UNDEFINED; import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM; -import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN; import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED; import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY; import static android.app.WindowConfiguration.activityTypeToString; @@ -417,7 +416,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A private int logo; // resource identifier of activity's logo. private int theme; // resource identifier of activity's theme. private int windowFlags; // custom window flags for preview window. - private TaskRecord task; // the task this is in. + private Task task; // the task this is in. private long createTime = System.currentTimeMillis(); long lastVisibleTime; // last time this activity became visible long cpuTimeAtResume; // the cpu time of host process at the time of resuming activity @@ -1148,7 +1147,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A } } - TaskRecord getTaskRecord() { + Task getTask() { return task; } @@ -1156,33 +1155,22 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A * Sets the Task on this activity for the purposes of re-use during launch where we will * re-use another activity instead of this one for the launch. */ - void setTaskForReuse(TaskRecord task) { + void setTaskForReuse(Task task) { this.task = task; } - Task getTask() { - return (Task) getParent(); - } - TaskStack getStack() { - final Task task = getTask(); - if (task != null) { - return task.getTaskStack(); - } else { - return null; - } + return task != null ? task.getTaskStack() : null; } @Override void onParentChanged(ConfigurationContainer newParent, ConfigurationContainer oldParent) { - final TaskRecord oldTask = oldParent != null ? (TaskRecord) oldParent : null; - final TaskRecord newTask = newParent != null ? (TaskRecord) newParent : null; + final Task oldTask = oldParent != null ? (Task) oldParent : null; + final Task newTask = newParent != null ? (Task) newParent : null; this.task = newTask; super.onParentChanged(newParent, oldParent); - final Task task = getTask(); - if (oldParent == null && newParent != null) { // First time we are adding the activity to the system. mVoiceInteraction = newTask.voiceSession != null; @@ -1311,7 +1299,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A // represents this. In fullscreen-mode, the stack does (since the orientation letterbox // is also applied to the task). Rect spaceToFill = (inMultiWindowMode() || getStack() == null) - ? getTask().getDisplayedBounds() : getStack().getDisplayedBounds(); + ? task.getDisplayedBounds() : getStack().getDisplayedBounds(); mLetterbox.layout(spaceToFill, w.getFrameLw(), mTmpPoint); } else if (mLetterbox != null) { mLetterbox.hide(); @@ -1637,8 +1625,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A } final ActivityManager.TaskSnapshot snapshot = - mWmService.mTaskSnapshotController.getSnapshot( - getTask().mTaskId, getTask().mUserId, + mWmService.mTaskSnapshotController.getSnapshot(task.mTaskId, task.mUserId, false /* restoreFromDisk */, false /* reducedResolution */); final int type = getStartingWindowType(newTask, taskSwitch, processRunning, allowTaskSnapshot, activityCreated, fromRecents, snapshot); @@ -1823,7 +1810,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A if (snapshot == null) { return false; } - return getTask().getConfiguration().orientation == snapshot.getOrientation(); + return task.getConfiguration().orientation == snapshot.getOrientation(); } void removeStartingWindow() { @@ -1893,12 +1880,12 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A * Reparents this activity into {@param newTask} at the provided {@param position}. The caller * should ensure that the {@param newTask} is not already the parent of this activity. */ - void reparent(TaskRecord newTask, int position, String reason) { + void reparent(Task newTask, int position, String reason) { if (getParent() == null) { Slog.w(TAG, "reparent: Attempted to reparent non-existing app token: " + appToken); return; } - final TaskRecord prevTask = task; + final Task prevTask = task; if (prevTask == newTask) { throw new IllegalArgumentException(reason + ": task=" + newTask + " is already the parent of r=" + this); @@ -1985,7 +1972,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A setActivityType(activityType); } - void setTaskToAffiliateWith(TaskRecord taskToAffiliateWith) { + void setTaskToAffiliateWith(Task taskToAffiliateWith) { if (launchMode != LAUNCH_SINGLE_INSTANCE && launchMode != LAUNCH_SINGLE_TASK) { task.setTaskToAffiliateWith(taskToAffiliateWith); } @@ -2253,7 +2240,6 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A return false; } - final TaskRecord task = getTaskRecord(); final ActivityStack stack = getActivityStack(); if (stack == null) { Slog.w(TAG, "moveActivityStackToFront: invalid task or stack: activity=" @@ -2282,7 +2268,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A /** Finish all activities in the task with the same affinity as this one. */ void finishActivityAffinity() { - final ArrayList activities = getTaskRecord().mChildren; + final ArrayList activities = task.mChildren; for (int index = activities.indexOf(this); index >= 0; --index) { final ActivityRecord cur = activities.get(index); if (!Objects.equals(cur.taskAffinity, taskAffinity)) { @@ -2390,7 +2376,9 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A mAtmService.deferWindowLayout(); try { makeFinishingLocked(); - final TaskRecord task = getTaskRecord(); + // Make a local reference to its task since this.task could be set to null once this + // activity is destroyed and detached from task. + final Task task = getTask(); EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY, mUserId, System.identityHashCode(this), task.mTaskId, shortComponentName, reason); @@ -2667,7 +2655,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A } EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY, mUserId, - System.identityHashCode(this), getTaskRecord().mTaskId, shortComponentName, reason); + System.identityHashCode(this), task.mTaskId, shortComponentName, reason); boolean removedFromHistory = false; @@ -2870,8 +2858,6 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A } boolean shouldFreezeBounds() { - final Task task = getTask(); - // For freeform windows, we can't freeze the bounds at the moment because this would make // the resizing unresponsive. if (task == null || task.inFreeformWindowingMode()) { @@ -2882,7 +2868,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A // the divider/drag handle being released, and the handling it's new // configuration. If we are relaunched outside of the drag resizing state, // we need to be careful not to do this. - return getTask().isDragResizing(); + return task.isDragResizing(); } void startRelaunching() { @@ -2906,7 +2892,6 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A * with a queue. */ private void freezeBounds() { - final Task task = getTask(); mFrozenBounds.offer(new Rect(task.mPreparedFrozenBounds)); if (task.mPreparedFrozenMergedConfig.equals(Configuration.EMPTY)) { @@ -3286,7 +3271,6 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A * immediately finishes after, so we have to transfer T to M. */ void transferStartingWindowFromHiddenAboveTokenIfNeeded() { - final Task task = getTask(); for (int i = task.mChildren.size() - 1; i >= 0; i--) { final ActivityRecord fromActivity = task.mChildren.get(i); if (fromActivity == this) { @@ -3398,7 +3382,6 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A */ @Nullable private ActivityRecord getActivityBelow() { - final Task task = getTask(); final int pos = task.mChildren.indexOf(this); if (pos == -1) { throw new IllegalStateException("Activity not found in its task"); @@ -3474,7 +3457,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A } } - void logStartActivity(int tag, TaskRecord task) { + void logStartActivity(int tag, Task task) { final Uri data = intent.getData(); final String strData = data != null ? data.toSafeString() : null; @@ -4211,10 +4194,8 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A mState = state; - final TaskRecord parent = getTaskRecord(); - - if (parent != null) { - parent.onActivityStateChanged(this, state, reason); + if (task != null) { + task.onActivityStateChanged(this, state, reason); } // The WindowManager interprets the app stopping signal as @@ -5337,7 +5318,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A if (r == null) { return INVALID_TASK_ID; } - final TaskRecord task = r.task; + final Task task = r.task; final int activityNdx = task.mChildren.indexOf(r); if (activityNdx < 0 || (onlyRoot && activityNdx > task.findRootIndex(true /* effectiveRoot */))) { @@ -5631,7 +5612,6 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A @VisibleForTesting boolean shouldAnimate(int transit) { - final Task task = getTask(); if (task != null && !task.shouldAnimate()) { return false; } @@ -5647,11 +5627,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A @Override boolean isChangingAppTransition() { - final Task task = getTask(); - if (task != null) { - return task.isChangingAppTransition(); - } - return super.isChangingAppTransition(); + return task != null ? task.isChangingAppTransition() : super.isChangingAppTransition(); } @Override @@ -5751,7 +5727,6 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A return; } - Task task = getTask(); if (mThumbnail == null && task != null && !hasCommittedReparentToAnimationLeash()) { SurfaceControl.ScreenshotGraphicBuffer snapshot = mWmService.mTaskSnapshotController.createTaskSnapshot( @@ -5803,7 +5778,6 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A // of the pinned stack or animation layer. The leash is then reparented to this new layer. if (mNeedsAnimationBoundsLayer) { mTmpRect.setEmpty(); - final Task task = getTask(); if (getDisplayContent().mAppTransitionController.isTransitWithinTask( getTransit(), task)) { task.getBounds(mTmpRect); @@ -5860,9 +5834,9 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A return; } final GraphicBuffer thumbnailHeader = - getDisplayContent().mAppTransition.getAppTransitionThumbnailHeader(getTask()); + getDisplayContent().mAppTransition.getAppTransitionThumbnailHeader(task); if (thumbnailHeader == null) { - ProtoLog.d(WM_DEBUG_APP_TRANSITIONS, "No thumbnail header bitmap for: %s", getTask()); + ProtoLog.d(WM_DEBUG_APP_TRANSITIONS, "No thumbnail header bitmap for: %s", task); return; } clearThumbnail(); @@ -5886,7 +5860,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A return; } final Rect frame = win.getFrameLw(); - final int thumbnailDrawableRes = getTask().mUserId == mWmService.mCurrentUserId + final int thumbnailDrawableRes = task.mUserId == mWmService.mCurrentUserId ? R.drawable.ic_account_circle : R.drawable.ic_corp_badge; final GraphicBuffer thumbnail = @@ -5916,7 +5890,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A final Rect insets = win != null ? win.getContentInsets() : null; final Configuration displayConfig = mDisplayContent.getConfiguration(); return getDisplayContent().mAppTransition.createThumbnailAspectScaleAnimationLocked( - appRect, insets, thumbnailHeader, getTask(), displayConfig.uiMode, + appRect, insets, thumbnailHeader, task, displayConfig.uiMode, displayConfig.orientation); } @@ -6256,7 +6230,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A // Ensure the screen related fields are set. It is used to prevent activity relaunch // when moving between displays. For screenWidthDp and screenWidthDp, because they // are relative to bounds and density, they will be calculated in - // {@link TaskRecord#computeConfigResourceOverrides} and the result will also be + // {@link Task#computeConfigResourceOverrides} and the result will also be // relatively fixed. overrideConfig.colorMode = fullConfig.colorMode; overrideConfig.densityDpi = fullConfig.densityDpi; @@ -6366,9 +6340,9 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A if (rotation != ROTATION_UNDEFINED) { // Ensure the parent and container bounds won't overlap with insets. - TaskRecord.intersectWithInsetsIfFits(containingAppBounds, compatDisplayBounds, + Task.intersectWithInsetsIfFits(containingAppBounds, compatDisplayBounds, mCompatDisplayInsets.mNonDecorInsets[rotation]); - TaskRecord.intersectWithInsetsIfFits(parentBounds, compatDisplayBounds, + Task.intersectWithInsetsIfFits(parentBounds, compatDisplayBounds, mCompatDisplayInsets.mNonDecorInsets[rotation]); } @@ -6415,7 +6389,6 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A @Override Rect getDisplayedBounds() { - final Task task = getTask(); if (task != null) { final Rect overrideDisplayedBounds = task.getOverrideDisplayedBounds(); if (!overrideDisplayedBounds.isEmpty()) { @@ -6434,7 +6407,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A } // Use task-bounds if available so that activity-level letterbox (maxAspectRatio) is // included in the animation. - return getTask() != null ? getTask().getBounds() : getBounds(); + return task != null ? task.getBounds() : getBounds(); } /** @@ -6504,7 +6477,6 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A mTmpPrevBounds.set(getBounds()); super.onConfigurationChanged(newParentConfig); - final Task task = getTask(); final Rect overrideBounds = getResolvedOverrideBounds(); if (task != null && !overrideBounds.isEmpty() // If the changes come from change-listener, the incoming parent configuration is @@ -6680,7 +6652,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A // Compute configuration based on max supported width and height. // Also account for the left / top insets (e.g. from display cutouts), which will be clipped - // away later in {@link TaskRecord#computeConfigResourceOverrides()}. Otherwise, the app + // away later in {@link Task#computeConfigResourceOverrides()}. Otherwise, the app // bounds would end up too small. outBounds.set(containingBounds.left, containingBounds.top, activityWidth + containingAppBounds.left, @@ -6822,7 +6794,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A preserveWindow &= isResizeOnlyChange(changes); final boolean hasResizeChange = hasResizeChange(changes & ~info.getRealConfigChanged()); if (hasResizeChange) { - final boolean isDragResizing = getTaskRecord().isDragResizing(); + final boolean isDragResizing = task.isDragResizing(); mRelaunchReason = isDragResizing ? RELAUNCH_REASON_FREE_RESIZE : RELAUNCH_REASON_WINDOWING_MODE_RESIZE; } else { @@ -7429,7 +7401,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A final Rect[] mStableInsets = new Rect[4]; /** - * Sets bounds to {@link TaskRecord} bounds. For apps in freeform, the task bounds are the + * Sets bounds to {@link Task} bounds. For apps in freeform, the task bounds are the * parent bounds from the app's perspective. No insets because within a window. */ CompatDisplayInsets(DisplayContent display, Rect activityBounds, boolean isFloating) { @@ -7489,7 +7461,6 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A @Override RemoteAnimationTarget createRemoteAnimationTarget( RemoteAnimationController.RemoteAnimationRecord record) { - final Task task = getTask(); final WindowState mainWindow = findMainWindow(); if (task == null || mainWindow == null) { return null; diff --git a/services/core/java/com/android/server/wm/ActivityStack.java b/services/core/java/com/android/server/wm/ActivityStack.java index ef7e4dc4c8a5f..8d90d6d283c58 100644 --- a/services/core/java/com/android/server/wm/ActivityStack.java +++ b/services/core/java/com/android/server/wm/ActivityStack.java @@ -98,7 +98,7 @@ import static com.android.server.wm.ActivityTaskManagerService.H.FIRST_ACTIVITY_ import static com.android.server.wm.ActivityTaskManagerService.RELAUNCH_REASON_FREE_RESIZE; import static com.android.server.wm.ActivityTaskManagerService.RELAUNCH_REASON_WINDOWING_MODE_RESIZE; import static com.android.server.wm.RootActivityContainer.FindTaskResult; -import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE; +import static com.android.server.wm.Task.REPARENT_LEAVE_STACK_IN_PLACE; import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_TASK_MOVEMENT; import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM; @@ -494,7 +494,7 @@ class ActivityStack extends TaskStack { /** * This should be called when an activity in a child task changes state. This should only * be called from - * {@link TaskRecord#onActivityStateChanged(ActivityRecord, ActivityState, String)}. + * {@link Task#onActivityStateChanged(ActivityRecord, ActivityState, String)}. * @param record The {@link ActivityRecord} whose state has changed. * @param state The new state. * @param reason The reason for the change. @@ -511,7 +511,7 @@ class ActivityStack extends TaskStack { if (record == mRootActivityContainer.getTopResumedActivity()) { mService.setResumedActivityUncheckLocked(record, reason); } - mStackSupervisor.mRecentTasks.add(record.getTaskRecord()); + mStackSupervisor.mRecentTasks.add(record.getTask()); } } @@ -584,7 +584,7 @@ class ActivityStack extends TaskStack { final boolean isMinimizedDock = display.mDisplayContent.getDockedDividerController().isMinimizedDock(); if (isMinimizedDock) { - TaskRecord topTask = display.getSplitScreenPrimaryStack().topTask(); + Task topTask = display.getSplitScreenPrimaryStack().topTask(); if (topTask != null) { dockedBounds = topTask.getBounds(); } @@ -661,7 +661,7 @@ class ActivityStack extends TaskStack { final int currentMode = getWindowingMode(); final int currentOverrideMode = getRequestedOverrideWindowingMode(); final ActivityDisplay display = getDisplay(); - final TaskRecord topTask = topTask(); + final Task topTask = topTask(); final ActivityStack splitScreenStack = display.getSplitScreenPrimaryStack(); int windowingMode = preferredWindowingMode; if (preferredWindowingMode == WINDOWING_MODE_UNDEFINED @@ -835,11 +835,11 @@ class ActivityStack extends TaskStack { return mRootActivityContainer.getActivityDisplay(mDisplayId); } - void positionChildAtTop(TaskRecord child) { + void positionChildAtTop(Task child) { positionChildAtTop(child, true /* includingParents */); } - private void positionChildAtBottom(TaskRecord child) { + private void positionChildAtBottom(Task child) { // If there are other focusable stacks on the display, the z-order of the display should not // be changed just because a task was placed at the bottom. E.g. if it is moving the topmost // task to bottom, the next focusable stack on the same display should be focused. @@ -927,7 +927,7 @@ class ActivityStack extends TaskStack { ActivityRecord topRunningNonOverlayTaskActivity() { for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) { - final TaskRecord task = getChildAt(taskNdx); + final Task task = getChildAt(taskNdx); for (int activityNdx = task.getChildCount() - 1; activityNdx >= 0; --activityNdx) { final ActivityRecord r = task.getChildAt(activityNdx); if (!r.finishing && !r.mTaskOverlay) { @@ -940,7 +940,7 @@ class ActivityStack extends TaskStack { ActivityRecord topRunningNonDelayedActivityLocked(ActivityRecord notTop) { for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) { - final TaskRecord task = getChildAt(taskNdx); + final Task task = getChildAt(taskNdx); for (int activityNdx = task.getChildCount() - 1; activityNdx >= 0; --activityNdx) { final ActivityRecord r = task.getChildAt(activityNdx); if (!r.finishing && !r.delayedResume && r != notTop && r.okToShowLocked()) { @@ -962,7 +962,7 @@ class ActivityStack extends TaskStack { */ final ActivityRecord topRunningActivityLocked(IBinder token, int taskId) { for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) { - TaskRecord task = getChildAt(taskNdx); + Task task = getChildAt(taskNdx); if (task.mTaskId == taskId) { continue; } @@ -987,7 +987,7 @@ class ActivityStack extends TaskStack { return null; } - final TaskRecord topTask() { + final Task topTask() { final int size = getChildCount(); if (size > 0) { return getChildAt(size - 1); @@ -995,9 +995,9 @@ class ActivityStack extends TaskStack { return null; } - TaskRecord taskForIdLocked(int id) { + Task taskForIdLocked(int id) { for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) { - final TaskRecord task = getChildAt(taskNdx); + final Task task = getChildAt(taskNdx); if (task.mTaskId == id) { return task; } @@ -1014,7 +1014,7 @@ class ActivityStack extends TaskStack { if (r == null) { return null; } - final TaskRecord task = r.getTaskRecord(); + final Task task = r.getTask(); final ActivityStack stack = r.getActivityStack(); if (stack != null && task.mChildren.contains(r) && mChildren.contains(task)) { if (stack != this) Slog.w(TAG, @@ -1024,14 +1024,14 @@ class ActivityStack extends TaskStack { return null; } - boolean isInStackLocked(TaskRecord task) { + boolean isInStackLocked(Task task) { return mChildren.contains(task); } /** Checks if there are tasks with specific UID in the stack. */ boolean isUidPresent(int uid) { for (int j = getChildCount() - 1; j >= 0; --j) { - final TaskRecord task = getChildAt(j); + final Task task = getChildAt(j); for (int i = task.getChildCount() - 1; i >= 0 ; --i) { final ActivityRecord r = task.getChildAt(i); if (r.getUid() == uid) { @@ -1045,7 +1045,7 @@ class ActivityStack extends TaskStack { /** Get all UIDs that are present in the stack. */ void getPresentUIDs(IntArray presentUIDs) { for (int j = getChildCount() - 1; j >= 0; --j) { - final TaskRecord task = getChildAt(j); + final Task task = getChildAt(j); for (int i = task.getChildCount() - 1; i >= 0 ; --i) { final ActivityRecord r = task.getChildAt(i); presentUIDs.add(r.getUid()); @@ -1092,7 +1092,7 @@ class ActivityStack extends TaskStack { * @param reason The reason for moving the stack to the front. * @param task If non-null, the task will be moved to the top of the stack. * */ - void moveToFront(String reason, TaskRecord task) { + void moveToFront(String reason, Task task) { if (!isAttached()) { return; } @@ -1134,7 +1134,7 @@ class ActivityStack extends TaskStack { * @param reason The reason for moving the stack to the back. * @param task If non-null, the task will be moved to the bottom of the stack. **/ - void moveToBack(String reason, TaskRecord task) { + void moveToBack(String reason, Task task) { if (!isAttached()) { return; } @@ -1186,7 +1186,7 @@ class ActivityStack extends TaskStack { if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Looking for task of " + target + " in " + this); for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) { - final TaskRecord task = getChildAt(taskNdx); + final Task task = getChildAt(taskNdx); if (task.voiceSession != null) { // We never match voice sessions; those always run independently. if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Skipping " + task + ": voice session"); @@ -1227,7 +1227,7 @@ class ActivityStack extends TaskStack { if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Comparing existing cls=" + (task.realActivity != null ? task.realActivity.flattenToShortString() : "") - + "/aff=" + r.getTaskRecord().rootAffinity + " to new cls=" + + "/aff=" + r.getTask().rootAffinity + " to new cls=" + intent.getComponent().flattenToShortString() + "/aff=" + info.taskAffinity); // TODO Refactor to remove duplications. Check if logic can be simplified. if (task.realActivity != null && task.realActivity.compareTo(cls) == 0 @@ -1277,7 +1277,7 @@ class ActivityStack extends TaskStack { final int userId = UserHandle.getUserId(info.applicationInfo.uid); for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) { - final TaskRecord task = getChildAt(taskNdx); + final Task task = getChildAt(taskNdx); for (int activityNdx = task.getChildCount() - 1; activityNdx >= 0; --activityNdx) { final ActivityRecord r = task.getChildAt(activityNdx); if (!r.okToShowLocked()) { @@ -1311,7 +1311,7 @@ class ActivityStack extends TaskStack { super.switchUser(userId); int top = mChildren.size(); for (int taskNdx = 0; taskNdx < top; ++taskNdx) { - TaskRecord task = mChildren.get(taskNdx); + Task task = mChildren.get(taskNdx); if (mWmService.isCurrentProfileLocked(task.mUserId) || task.showForAllUsers()) { mChildren.remove(taskNdx); mChildren.add(task); @@ -1338,7 +1338,7 @@ class ActivityStack extends TaskStack { void awakeFromSleepingLocked() { // Ensure activities are no longer sleeping. for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) { - final TaskRecord task = getChildAt(taskNdx); + final Task task = getChildAt(taskNdx); for (int activityNdx = task.getChildCount() - 1; activityNdx >= 0; --activityNdx) { final ActivityRecord r = task.getChildAt(activityNdx); r.setSleeping(false); @@ -1355,7 +1355,7 @@ class ActivityStack extends TaskStack { final int userId = UserHandle.getUserId(aInfo.uid); for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) { - final TaskRecord task = getChildAt(taskNdx); + final Task task = getChildAt(taskNdx); for (int activityNdx = task.getChildCount() - 1; activityNdx >= 0; --activityNdx) { final ActivityRecord ar = task.getChildAt(activityNdx); @@ -1433,7 +1433,7 @@ class ActivityStack extends TaskStack { // Make sure any paused or stopped but visible activities are now sleeping. // This ensures that the activity's onStop() is called. for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) { - final TaskRecord task = getChildAt(taskNdx); + final Task task = getChildAt(taskNdx); for (int activityNdx = task.getChildCount() - 1; activityNdx >= 0; --activityNdx) { final ActivityRecord r = task.getChildAt(activityNdx); if (r.isState(STARTED, STOPPING, STOPPED, PAUSED, PAUSING)) { @@ -1499,7 +1499,7 @@ class ActivityStack extends TaskStack { mLastNoHistoryActivity = (prev.intent.getFlags() & Intent.FLAG_ACTIVITY_NO_HISTORY) != 0 || (prev.info.flags & ActivityInfo.FLAG_NO_HISTORY) != 0 ? prev : null; prev.setState(PAUSING, "startPausingLocked"); - prev.getTaskRecord().touchActiveTime(); + prev.getTask().touchActiveTime(); clearLaunchTime(prev); mService.updateCpuStats(); @@ -1717,7 +1717,7 @@ class ActivityStack extends TaskStack { return true; } for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) { - final TaskRecord task = getChildAt(taskNdx); + final Task task = getChildAt(taskNdx); for (int activityNdx = task.getChildCount() - 1; activityNdx >= 0; --activityNdx) { final ActivityRecord r = task.getChildAt(activityNdx); @@ -1898,7 +1898,7 @@ class ActivityStack extends TaskStack { final int rankTaskLayers(int baseLayer) { int layer = 0; for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) { - final TaskRecord task = getChildAt(taskNdx); + final Task task = getChildAt(taskNdx); ActivityRecord r = task.topRunningActivityLocked(); if (r == null || r.finishing || !r.visible) { task.mLayerRank = -1; @@ -1949,7 +1949,7 @@ class ActivityStack extends TaskStack { final boolean resumeTopActivity = isFocusable() && isInStackLocked(starting) == null && top != null && !top.mLaunchTaskBehind; for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) { - final TaskRecord task = getChildAt(taskNdx); + final Task task = getChildAt(taskNdx); for (int activityNdx = task.getChildCount() - 1; activityNdx >= 0; --activityNdx) { final ActivityRecord r = task.getChildAt(activityNdx); final boolean isTop = r == top; @@ -2068,7 +2068,7 @@ class ActivityStack extends TaskStack { @Override public boolean supportsSplitScreenWindowingMode() { - final TaskRecord topTask = topTask(); + final Task topTask = topTask(); return super.supportsSplitScreenWindowingMode() && (topTask == null || topTask.supportsSplitScreenWindowingMode()); } @@ -2193,7 +2193,7 @@ class ActivityStack extends TaskStack { void clearOtherAppTimeTrackers(AppTimeTracker except) { for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) { - final TaskRecord task = getChildAt(taskNdx); + final Task task = getChildAt(taskNdx); for (int activityNdx = task.getChildCount() - 1; activityNdx >= 0; --activityNdx) { final ActivityRecord r = task.getChildAt(activityNdx); if ( r.appTimeTracker != except) { @@ -2267,7 +2267,7 @@ class ActivityStack extends TaskStack { final ActivityRecord topActivity = topRunningActivityLocked(); for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) { - final TaskRecord task = getChildAt(taskNdx); + final Task task = getChildAt(taskNdx); for (int activityNdx = task.getChildCount() - 1; activityNdx >= 0; --activityNdx) { final ActivityRecord r = task.getChildAt(activityNdx); if (aboveTop) { @@ -2581,7 +2581,7 @@ class ActivityStack extends TaskStack { dc.prepareAppTransition(TRANSIT_NONE, false); } else { dc.prepareAppTransition( - prev.getTaskRecord() == next.getTaskRecord() ? TRANSIT_ACTIVITY_CLOSE + prev.getTask() == next.getTask() ? TRANSIT_ACTIVITY_CLOSE : TRANSIT_TASK_CLOSE, false); } prev.setVisibility(false); @@ -2593,7 +2593,7 @@ class ActivityStack extends TaskStack { dc.prepareAppTransition(TRANSIT_NONE, false); } else { dc.prepareAppTransition( - prev.getTaskRecord() == next.getTaskRecord() ? TRANSIT_ACTIVITY_OPEN + prev.getTask() == next.getTask() ? TRANSIT_ACTIVITY_OPEN : next.mLaunchTaskBehind ? TRANSIT_TASK_OPEN_BEHIND : TRANSIT_TASK_OPEN, false); } @@ -2719,7 +2719,7 @@ class ActivityStack extends TaskStack { next.notifyAppResumed(next.stopped); EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY, next.mUserId, - System.identityHashCode(next), next.getTaskRecord().mTaskId, + System.identityHashCode(next), next.getTask().mTaskId, next.shortComponentName); next.sleeping = false; @@ -2817,7 +2817,7 @@ class ActivityStack extends TaskStack { void startActivityLocked(ActivityRecord r, ActivityRecord focusedTopActivity, boolean newTask, boolean keepCurTransition, ActivityOptions options) { - TaskRecord rTask = r.getTaskRecord(); + Task rTask = r.getTask(); final int taskId = rTask.mTaskId; final boolean allowMoveToFront = options == null || !options.getAvoidMoveToFront(); // mLaunchTaskBehind tasks get placed at the back of the task stack. @@ -2828,7 +2828,7 @@ class ActivityStack extends TaskStack { // Might not even be in. positionChildAtTop(rTask); } - TaskRecord task = null; + Task task = null; if (!newTask) { // If starting in an existing task, find where that is... boolean startIt = true; @@ -2860,7 +2860,7 @@ class ActivityStack extends TaskStack { // If we are not placing the new activity frontmost, we do not want to deliver the // onUserLeaving callback to the actual frontmost activity - final TaskRecord activityTask = r.getTaskRecord(); + final Task activityTask = r.getTask(); if (task == activityTask && mChildren.indexOf(task) != (getChildCount() - 1)) { mStackSupervisor.mUserLeaving = false; if (DEBUG_USER_LEAVING) Slog.v(TAG_USER_LEAVING, @@ -2933,12 +2933,12 @@ class ActivityStack extends TaskStack { // "has the same starting icon" as the next one. This allows the // window manager to keep the previous window it had previously // created, if it still had one. - TaskRecord prevTask = r.getTaskRecord(); + Task prevTask = r.getTask(); ActivityRecord prev = prevTask.topRunningActivityWithStartingWindowLocked(); if (prev != null) { // We don't want to reuse the previous starting preview if: // (1) The current activity is in a different task. - if (prev.getTaskRecord() != prevTask) { + if (prev.getTask() != prevTask) { prev = null; } // (2) The current activity is already displayed. @@ -2961,7 +2961,7 @@ class ActivityStack extends TaskStack { * {@param toFrontActivity} should be set. */ private boolean canEnterPipOnTaskSwitch(ActivityRecord pipCandidate, - TaskRecord toFrontTask, ActivityRecord toFrontActivity, ActivityOptions opts) { + Task toFrontTask, ActivityRecord toFrontActivity, ActivityOptions opts) { if (opts != null && opts.disallowEnterPictureInPictureWhileLaunching()) { // Ensure the caller has requested not to trigger auto-enter PiP return false; @@ -2981,7 +2981,7 @@ class ActivityStack extends TaskStack { private boolean isTaskSwitch(ActivityRecord r, ActivityRecord topFocusedActivity) { - return topFocusedActivity != null && r.getTaskRecord() != topFocusedActivity.getTaskRecord(); + return topFocusedActivity != null && r.getTask() != topFocusedActivity.getTask(); } /** @@ -2991,7 +2991,7 @@ class ActivityStack extends TaskStack { * @param forceReset Flag indicating if clear task was requested * @return An ActivityOptions that needs to be processed. */ - private ActivityOptions resetTargetTaskIfNeededLocked(TaskRecord task, boolean forceReset) { + private ActivityOptions resetTargetTaskIfNeededLocked(Task task, boolean forceReset) { ActivityOptions topOptions = null; // Tracker of the end of currently handled reply chain (sublist) of activities. What happens @@ -3045,19 +3045,19 @@ class ActivityStack extends TaskStack { // moved. // TODO: We should probably look for other stacks also, since corresponding task // with the same affinity is unlikely to be in the same stack. - final TaskRecord targetTask; + final Task targetTask; final ActivityRecord bottom = hasChild() && getChildAt(0).hasChild() ? getChildAt(0).getChildAt(0) : null; - if (bottom != null && target.taskAffinity.equals(bottom.getTaskRecord().affinity)) { + if (bottom != null && target.taskAffinity.equals(bottom.getTask().affinity)) { // If the activity currently at the bottom has the // same task affinity as the one we are moving, // then merge it into the same task. - targetTask = bottom.getTaskRecord(); + targetTask = bottom.getTask(); if (DEBUG_TASKS) Slog.v(TAG_TASKS, "Start pushing activity " + target + " out to bottom task " + targetTask); } else { - targetTask = createTaskRecord( + targetTask = createTask( mStackSupervisor.getNextTaskIdForUserLocked(target.mUserId), target.info, null /* intent */, null /* voiceSession */, null /* voiceInteractor */, false /* toTop */); @@ -3150,7 +3150,7 @@ class ActivityStack extends TaskStack { if (singleTaskInstanceDisplay || display.alwaysCreateStack(getWindowingMode(), getActivityType())) { for (int index = numTasksCreated - 1; index >= 0; index--) { - final TaskRecord targetTask = getChildAt(index); + final Task targetTask = getChildAt(index); final ActivityStack targetStack = display.getOrCreateStack(getWindowingMode(), getActivityType(), false /* onTop */); targetTask.reparent(targetStack, false /* toTop */, @@ -3165,7 +3165,7 @@ class ActivityStack extends TaskStack { /** * Helper method for {@link #resetTaskIfNeededLocked(ActivityRecord, ActivityRecord)}. - * Processes all of the activities in a given TaskRecord looking for an affinity with the task + * Processes all of the activities in a given Task looking for an affinity with the task * of resetTaskIfNeededLocked.taskTop. * @param affinityTask The task we are looking for an affinity to. * @param task Task that resetTaskIfNeededLocked.taskTop belongs to. @@ -3173,7 +3173,7 @@ class ActivityStack extends TaskStack { * @param forceReset Flag indicating if clear task was requested */ // TODO: Consider merging with #resetTargetTaskIfNeededLocked() above - private int resetAffinityTaskIfNeededLocked(TaskRecord affinityTask, TaskRecord task, + private int resetAffinityTaskIfNeededLocked(Task affinityTask, Task task, boolean topTaskIsHigher, boolean forceReset, int taskInsertionPoint) { // Tracker of the end of currently handled reply chain (sublist) of activities. What happens // to activities in the same chain will depend on what the end activity of the chain needs. @@ -3289,9 +3289,9 @@ class ActivityStack extends TaskStack { ActivityRecord newActivity) { final boolean forceReset = (newActivity.info.flags & ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0; - final TaskRecord task = taskTop.getTaskRecord(); + final Task task = taskTop.getTask(); - // False until we evaluate the TaskRecord associated with taskTop. Switches to true + // False until we evaluate the Task associated with taskTop. Switches to true // for remaining tasks. Used for later tasks to reparent to task. boolean taskFound = false; @@ -3302,7 +3302,7 @@ class ActivityStack extends TaskStack { int reparentInsertionPoint = -1; for (int i = getChildCount() - 1; i >= 0; --i) { - final TaskRecord targetTask = getChildAt(i); + final Task targetTask = getChildAt(i); if (targetTask == task) { topOptions = resetTargetTaskIfNeededLocked(task, forceReset); @@ -3379,7 +3379,7 @@ class ActivityStack extends TaskStack { /** Finish all activities that were started for result from the specified activity. */ final void finishSubActivityLocked(ActivityRecord self, String resultWho, int requestCode) { for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) { - final TaskRecord task = getChildAt(taskNdx); + final Task task = getChildAt(taskNdx); for (int activityNdx = task.getChildCount() - 1; activityNdx >= 0; --activityNdx) { final ActivityRecord r = task.getChildAt(activityNdx); if (r.resultTo == self && r.requestCode == requestCode) { @@ -3401,17 +3401,17 @@ class ActivityStack extends TaskStack { * @return The task that was finished in this stack, {@code null} if top running activity does * not belong to the crashed app. */ - final TaskRecord finishTopCrashedActivityLocked(WindowProcessController app, String reason) { + final Task finishTopCrashedActivityLocked(WindowProcessController app, String reason) { ActivityRecord r = topRunningActivityLocked(); - TaskRecord finishedTask = null; + Task finishedTask = null; if (r == null || r.app != app) { return null; } Slog.w(TAG, " Force finishing activity " + r.intent.getComponent().flattenToShortString()); - finishedTask = r.getTaskRecord(); + finishedTask = r.getTask(); int taskNdx = mChildren.indexOf(finishedTask); - final TaskRecord task = finishedTask; + final Task task = finishedTask; int activityNdx = task.mChildren.indexOf(r); getDisplay().mDisplayContent.prepareAppTransition( TRANSIT_CRASHING_ACTIVITY_CLOSE, false /* alwaysKeepCurrent */); @@ -3447,7 +3447,7 @@ class ActivityStack extends TaskStack { IBinder sessionBinder = session.asBinder(); boolean didOne = false; for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) { - TaskRecord tr = getChildAt(taskNdx); + Task tr = getChildAt(taskNdx); if (tr.voiceSession != null && tr.voiceSession.asBinder() == sessionBinder) { for (int activityNdx = tr.getChildCount() - 1; activityNdx >= 0; --activityNdx) { ActivityRecord r = tr.getChildAt(activityNdx); @@ -3485,7 +3485,7 @@ class ActivityStack extends TaskStack { void finishAllActivitiesImmediately() { boolean noActivitiesInStack = true; for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) { - final TaskRecord task = getChildAt(taskNdx); + final Task task = getChildAt(taskNdx); for (int activityNdx = task.getChildCount() - 1; activityNdx >= 0; --activityNdx) { final ActivityRecord r = task.getChildAt(activityNdx); noActivitiesInStack = false; @@ -3515,15 +3515,15 @@ class ActivityStack extends TaskStack { boolean shouldUpRecreateTaskLocked(ActivityRecord srec, String destAffinity) { // Basic case: for simple app-centric recents, we need to recreate // the task if the affinity has changed. - if (srec == null || srec.getTaskRecord().affinity == null || - !srec.getTaskRecord().affinity.equals(destAffinity)) { + if (srec == null || srec.getTask().affinity == null + || !srec.getTask().affinity.equals(destAffinity)) { return true; } // Document-centric case: an app may be split in to multiple documents; // they need to re-create their task if this current activity is the root // of a document, unless simply finishing it will return them to the the // correct app behind. - final TaskRecord task = srec.getTaskRecord(); + final Task task = srec.getTask(); if (srec.isRootOfTask() && task.getBaseIntent() != null && task.getBaseIntent().isDocument()) { // Okay, this activity is at the root of its task. What to do, what to do... @@ -3537,7 +3537,7 @@ class ActivityStack extends TaskStack { Slog.w(TAG, "shouldUpRecreateTask: task not in history for " + srec); return false; } - final TaskRecord prevTask = getChildAt(taskIdx); + final Task prevTask = getChildAt(taskIdx); if (!task.affinity.equals(prevTask.affinity)) { // These are different apps, so need to recreate. return true; @@ -3548,7 +3548,7 @@ class ActivityStack extends TaskStack { final boolean navigateUpToLocked(ActivityRecord srec, Intent destIntent, int resultCode, Intent resultData) { - final TaskRecord task = srec.getTaskRecord(); + final Task task = srec.getTask(); final ArrayList activities = task.mChildren; final int start = activities.indexOf(srec); if (!mChildren.contains(task) || (start < 0)) { @@ -3724,7 +3724,7 @@ class ActivityStack extends TaskStack { boolean lastIsOpaque = false; boolean activityRemoved = false; for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) { - final TaskRecord task = getChildAt(taskNdx); + final Task task = getChildAt(taskNdx); for (int activityNdx = task.getChildCount() - 1; activityNdx >= 0; --activityNdx) { final ActivityRecord r = task.getChildAt(activityNdx); if (r.finishing) { @@ -3755,7 +3755,7 @@ class ActivityStack extends TaskStack { } } - final int releaseSomeActivitiesLocked(WindowProcessController app, ArraySet tasks, + final int releaseSomeActivitiesLocked(WindowProcessController app, ArraySet tasks, String reason) { // Iterate over tasks starting at the back (oldest) first. if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Trying to release some activities in " + app); @@ -3765,7 +3765,7 @@ class ActivityStack extends TaskStack { } int numReleased = 0; for (int taskNdx = 0; taskNdx < getChildCount() && maxTasks > 0; taskNdx++) { - final TaskRecord task = getChildAt(taskNdx); + final Task task = getChildAt(taskNdx); if (!tasks.contains(task)) { continue; } @@ -3890,7 +3890,7 @@ class ActivityStack extends TaskStack { Slog.w(TAG, "Force removing " + r + ": app died, no saved state"); EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY, r.mUserId, System.identityHashCode(r), - r.getTaskRecord().mTaskId, r.shortComponentName, + r.getTask().mTaskId, r.shortComponentName, "proc died without state saved"); } } else { @@ -3929,7 +3929,7 @@ class ActivityStack extends TaskStack { getDisplay().mDisplayContent.prepareAppTransition(transit, false); } - final void moveTaskToFrontLocked(TaskRecord tr, boolean noAnimation, ActivityOptions options, + final void moveTaskToFrontLocked(Task tr, boolean noAnimation, ActivityOptions options, AppTimeTracker timeTracker, String reason) { if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "moveTaskToFront: " + tr); @@ -3968,7 +3968,7 @@ class ActivityStack extends TaskStack { final ActivityRecord top = tr.getTopActivity(); if (top == null || !top.okToShowLocked()) { if (top != null) { - mStackSupervisor.mRecentTasks.add(top.getTaskRecord()); + mStackSupervisor.mRecentTasks.add(top.getTask()); } ActivityOptions.abort(options); return; @@ -4021,7 +4021,7 @@ class ActivityStack extends TaskStack { * @return Returns true if the move completed, false if not. */ final boolean moveTaskToBackLocked(int taskId) { - final TaskRecord tr = taskForIdLocked(taskId); + final Task tr = taskForIdLocked(taskId); if (tr == null) { Slog.i(TAG, "moveTaskToBack: bad taskId=" + taskId); return false; @@ -4090,14 +4090,14 @@ class ActivityStack extends TaskStack { return; } - final TaskRecord startTask = start.getTaskRecord(); + final Task startTask = start.getTask(); boolean behindFullscreen = false; boolean updatedConfig = false; for (int taskIndex = mChildren.indexOf(startTask); taskIndex >= 0; --taskIndex) { - final TaskRecord task = getChildAt(taskIndex); + final Task task = getChildAt(taskIndex); final ArrayList activities = task.mChildren; - int activityIndex = (start.getTaskRecord() == task) + int activityIndex = (start.getTask() == task) ? activities.indexOf(start) : activities.size() - 1; for (; activityIndex >= 0; --activityIndex) { final ActivityRecord r = activities.get(activityIndex); @@ -4133,7 +4133,7 @@ class ActivityStack extends TaskStack { // Update override configurations of all tasks in the stack. final Rect taskBounds = tempTaskBounds != null ? tempTaskBounds : bounds; for (int i = getChildCount() - 1; i >= 0; i--) { - final TaskRecord task = getChildAt(i); + final Task task = getChildAt(i); if (task.isResizeable()) { if (tempTaskInsetBounds != null && !tempTaskInsetBounds.isEmpty()) { task.setOverrideDisplayedBounds(taskBounds); @@ -4167,7 +4167,7 @@ class ActivityStack extends TaskStack { } for (int i = getChildCount() - 1; i >= 0; i--) { - final TaskRecord task = getChildAt(i); + final Task task = getChildAt(i); if (task.isResizeable()) { task.setBounds(bounds); } else { @@ -4183,7 +4183,7 @@ class ActivityStack extends TaskStack { } for (int i = getChildCount() - 1; i >= 0; i--) { - final TaskRecord task = getChildAt(i); + final Task task = getChildAt(i); if (bounds == null || bounds.isEmpty()) { task.setOverrideDisplayedBounds(null); } else if (task.isResizeable()) { @@ -4194,7 +4194,7 @@ class ActivityStack extends TaskStack { boolean willActivityBeVisibleLocked(IBinder token) { for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) { - final TaskRecord task = getChildAt(taskNdx); + final Task task = getChildAt(taskNdx); for (int activityNdx = task.getChildCount() - 1; activityNdx >= 0; --activityNdx) { final ActivityRecord r = task.getChildAt(activityNdx); if (r.appToken == token) { @@ -4216,7 +4216,7 @@ class ActivityStack extends TaskStack { void closeSystemDialogsLocked() { for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) { - final TaskRecord task = getChildAt(taskNdx); + final Task task = getChildAt(taskNdx); for (int activityNdx = task.getChildCount() - 1; activityNdx >= 0; --activityNdx) { final ActivityRecord r = task.getChildAt(activityNdx); if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) { @@ -4229,7 +4229,7 @@ class ActivityStack extends TaskStack { boolean finishDisabledPackageActivitiesLocked(String packageName, Set filterByClasses, boolean doit, boolean evenPersistent, int userId) { boolean didSomething = false; - TaskRecord lastTask = null; + Task lastTask = null; ComponentName homeActivity = null; for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) { final ArrayList activities = getChildAt(taskNdx).mChildren; @@ -4243,7 +4243,7 @@ class ActivityStack extends TaskStack { || filterByClasses.contains(r.mActivityComponent.getClassName()))) || (packageName == null && r.mUserId == userId); if ((userId == UserHandle.USER_ALL || r.mUserId == userId) - && (sameComponent || r.getTaskRecord() == lastTask) + && (sameComponent || r.getTask() == lastTask) && (r.app == null || evenPersistent || !r.app.isPersistent())) { if (!doit) { if (r.finishing) { @@ -4263,7 +4263,7 @@ class ActivityStack extends TaskStack { } didSomething = true; Slog.i(TAG, " Force finishing activity " + r); - lastTask = r.getTaskRecord(); + lastTask = r.getTask(); r.finishIfPossible("force-stop", true); } } @@ -4276,14 +4276,14 @@ class ActivityStack extends TaskStack { * If {@param ignoreActivityType} or {@param ignoreWindowingMode} are not undefined, * then skip running tasks that match those types. */ - void getRunningTasks(List tasksOut, @ActivityType int ignoreActivityType, + void getRunningTasks(List tasksOut, @ActivityType int ignoreActivityType, @WindowingMode int ignoreWindowingMode, int callingUid, boolean allowed, boolean crossUser, ArraySet profileIds) { boolean focusedStack = mRootActivityContainer.getTopDisplayFocusedStack() == this; boolean topTask = true; int userId = UserHandle.getUserId(callingUid); for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) { - final TaskRecord task = getChildAt(taskNdx); + final Task task = getChildAt(taskNdx); if (task.getTopActivity() == null) { // Skip if there are no activities in the task continue; @@ -4325,7 +4325,7 @@ class ActivityStack extends TaskStack { final int top = getChildCount() - 1; if (DEBUG_SWITCH) Slog.d(TAG_SWITCH, "Performing unhandledBack(): top activity at " + top); if (top >= 0) { - final TaskRecord task = getChildAt(top); + final Task task = getChildAt(top); int activityTop = task.getChildCount() - 1; if (activityTop >= 0) { task.getChildAt(activityTop).finishIfPossible("unhandled-back", true /* oomAdj */); @@ -4354,7 +4354,7 @@ class ActivityStack extends TaskStack { void handleAppCrash(WindowProcessController app) { for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) { - final TaskRecord task = getChildAt(taskNdx); + final Task task = getChildAt(taskNdx); for (int activityNdx = task.getChildCount() - 1; activityNdx >= 0; --activityNdx) { final ActivityRecord r = task.getChildAt(activityNdx); if (r.app == app) { @@ -4419,7 +4419,7 @@ class ActivityStack extends TaskStack { } final String prefix = " "; for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) { - final TaskRecord task = getChildAt(taskNdx); + final Task task = getChildAt(taskNdx); if (needSep) { pw.println(""); } @@ -4446,7 +4446,7 @@ class ActivityStack extends TaskStack { } else if ("top".equals(name)) { final int top = getChildCount() - 1; if (top >= 0) { - final TaskRecord task = getChildAt(top); + final Task task = getChildAt(top); int listTop = task.getChildCount() - 1; if (listTop >= 0) { activities.add(task.getChildAt(listTop)); @@ -4457,7 +4457,7 @@ class ActivityStack extends TaskStack { matcher.build(name); for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) { - final TaskRecord task = getChildAt(taskNdx); + final Task task = getChildAt(taskNdx); for (int activityNdx = task.getChildCount() - 1; activityNdx >= 0; --activityNdx) { final ActivityRecord r1 = task.getChildAt(activityNdx); if (matcher.match(r1, r1.intent.getComponent())) { @@ -4476,7 +4476,7 @@ class ActivityStack extends TaskStack { // All activities that came from the package must be // restarted as if there was a config change. for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) { - final TaskRecord task = getChildAt(taskNdx); + final Task task = getChildAt(taskNdx); for (int activityNdx = task.getChildCount() - 1; activityNdx >= 0; --activityNdx) { final ActivityRecord a = task.getChildAt(activityNdx); if (a.info.packageName.equals(packageName)) { @@ -4497,7 +4497,7 @@ class ActivityStack extends TaskStack { * @param child to remove. * @param reason for removal. */ - void removeChild(TaskRecord child, String reason) { + void removeChild(Task child, String reason) { if (!mChildren.contains(child)) { // Not really in this stack anymore... return; @@ -4526,7 +4526,7 @@ class ActivityStack extends TaskStack { } @Override - void removeChild(TaskRecord task) { + void removeChild(Task task) { removeChild(task, "removeChild"); } @@ -4542,18 +4542,18 @@ class ActivityStack extends TaskStack { } } - TaskRecord createTaskRecord(int taskId, ActivityInfo info, Intent intent, + Task createTask(int taskId, ActivityInfo info, Intent intent, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, boolean toTop) { - return createTaskRecord(taskId, info, intent, voiceSession, voiceInteractor, toTop, + return createTask(taskId, info, intent, voiceSession, voiceInteractor, toTop, null /*activity*/, null /*source*/, null /*options*/); } - TaskRecord createTaskRecord(int taskId, ActivityInfo info, Intent intent, + Task createTask(int taskId, ActivityInfo info, Intent intent, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, boolean toTop, ActivityRecord activity, ActivityRecord source, ActivityOptions options) { - final TaskRecord task = TaskRecord.create( + final Task task = Task.create( mService, taskId, info, intent, voiceSession, voiceInteractor, this); // add the task to stack first, mTaskPositioner might need the stack association addChild(task, toTop, (info.flags & FLAG_SHOW_FOR_ALL_USERS) != 0); @@ -4568,11 +4568,11 @@ class ActivityStack extends TaskStack { return task; } - ArrayList getAllTasks() { + ArrayList getAllTasks() { return new ArrayList<>(mChildren); } - void addChild(final TaskRecord task, final boolean toTop, boolean showForAllUsers) { + void addChild(final Task task, final boolean toTop, boolean showForAllUsers) { if (isSingleTaskInstance() && hasChild()) { throw new IllegalStateException("Can only have one child on stack=" + this); } @@ -4587,8 +4587,7 @@ class ActivityStack extends TaskStack { } } - void positionChildAt(TaskRecord task, int position) { - + void positionChildAt(Task task, int position) { if (task.getStack() != this) { throw new IllegalArgumentException("AS.positionChildAt: task=" + task + " is not a child of stack=" + this + " current parent=" + task.getStack()); @@ -4646,7 +4645,7 @@ class ActivityStack extends TaskStack { display.positionChildAtTop(this, false /* includingParents */); } - /** NOTE: Should only be called from {@link TaskRecord#reparent}. */ + /** NOTE: Should only be called from {@link Task#reparent}. */ void moveToFrontAndResumeStateIfNeeded(ActivityRecord r, boolean moveToFront, boolean setResume, boolean setPause, String reason) { if (!moveToFront) { @@ -4708,7 +4707,7 @@ class ActivityStack extends TaskStack { } mWindowManager.inSurfaceTransaction(() -> { - final TaskRecord task = mChildren.get(0); + final Task task = mChildren.get(0); setWindowingMode(WINDOWING_MODE_UNDEFINED); getDisplay().positionChildAtTop(this, false /* includingParents */); @@ -4727,7 +4726,7 @@ class ActivityStack extends TaskStack { if (!isAttached()) { return; } - ArrayList tasks = getAllTasks(); + ArrayList tasks = getAllTasks(); for (int i = 0; i < tasks.size(); i++) { mStackSupervisor.updatePictureInPictureMode(tasks.get(i), targetStackBounds, forceUpdate); @@ -4783,7 +4782,7 @@ class ActivityStack extends TaskStack { writeToProtoInnerStackOnly(proto, STACK, logLevel); proto.write(ID, mStackId); for (int taskNdx = getChildCount() - 1; taskNdx >= 0; --taskNdx) { - final TaskRecord task = getChildAt(taskNdx); + final Task task = getChildAt(taskNdx); task.writeToProto(proto, TASKS, logLevel); } if (mResumedActivity != null) { diff --git a/services/core/java/com/android/server/wm/ActivityStackSupervisor.java b/services/core/java/com/android/server/wm/ActivityStackSupervisor.java index e34006665864f..79fae068e720d 100644 --- a/services/core/java/com/android/server/wm/ActivityStackSupervisor.java +++ b/services/core/java/com/android/server/wm/ActivityStackSupervisor.java @@ -75,12 +75,12 @@ import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_O import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS; import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE; import static com.android.server.wm.RootActivityContainer.TAG_STATES; -import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_LAUNCHABLE; -import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_LAUNCHABLE_PRIV; -import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_WHITELISTED; -import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT; -import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE; -import static com.android.server.wm.TaskRecord.REPARENT_MOVE_STACK_TO_FRONT; +import static com.android.server.wm.Task.LOCK_TASK_AUTH_LAUNCHABLE; +import static com.android.server.wm.Task.LOCK_TASK_AUTH_LAUNCHABLE_PRIV; +import static com.android.server.wm.Task.LOCK_TASK_AUTH_WHITELISTED; +import static com.android.server.wm.Task.REPARENT_KEEP_STACK_AT_FRONT; +import static com.android.server.wm.Task.REPARENT_LEAVE_STACK_IN_PLACE; +import static com.android.server.wm.Task.REPARENT_MOVE_STACK_TO_FRONT; import static com.android.server.wm.WindowContainer.AnimationFlags.TRANSITION; import static com.android.server.wm.WindowContainer.POSITION_TOP; @@ -740,7 +740,7 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks { return false; } - final TaskRecord task = r.getTaskRecord(); + final Task task = r.getTask(); final ActivityStack stack = task.getStack(); beginDeferResume(); @@ -1382,7 +1382,7 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks { } /** This doesn't just find a task, it also moves the task to front. */ - void findTaskToMoveToFront(TaskRecord task, int flags, ActivityOptions options, String reason, + void findTaskToMoveToFront(Task task, int flags, ActivityOptions options, String reason, boolean forceNonResizeable) { ActivityStack currentStack = task.getStack(); if (currentStack == null) { @@ -1480,7 +1480,7 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks { continueUpdateRecentsHomeStackBounds(); for (int i = mResizingTasksDuringAnimation.size() - 1; i >= 0; i--) { final int taskId = mResizingTasksDuringAnimation.valueAt(i); - final TaskRecord task = + final Task task = mRootActivityContainer.anyTaskForId(taskId, MATCH_TASK_IN_STACKS_ONLY); if (task != null) { task.setTaskDockedResizing(false); @@ -1527,13 +1527,13 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks { // the picture-in-picture mode. final boolean schedulePictureInPictureModeChange = windowingMode == WINDOWING_MODE_PINNED; - final ArrayList tasks = fromStack.getAllTasks(); + final ArrayList tasks = fromStack.getAllTasks(); if (!tasks.isEmpty()) { mTmpOptions.setLaunchWindowingMode(WINDOWING_MODE_FULLSCREEN); final int size = tasks.size(); for (int i = 0; i < size; ++i) { - final TaskRecord task = tasks.get(i); + final Task task = tasks.get(i); final ActivityStack toStack = toDisplay.getOrCreateStack( null, mTmpOptions, task, task.getActivityType(), onTop); @@ -1745,7 +1745,7 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks { } private void removeStackInSurfaceTransaction(ActivityStack stack) { - final ArrayList tasks = stack.getAllTasks(); + final ArrayList tasks = stack.getAllTasks(); if (stack.getWindowingMode() == WINDOWING_MODE_PINNED) { /** * Workaround: Force-stop all the activities in the pinned stack before we reparent them @@ -1791,14 +1791,14 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks { */ boolean removeTaskByIdLocked(int taskId, boolean killProcess, boolean removeFromRecents, String reason) { - final TaskRecord tr = + final Task task = mRootActivityContainer.anyTaskForId(taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS); - if (tr != null) { - tr.removeTaskActivitiesLocked(reason); - cleanUpRemovedTaskLocked(tr, killProcess, removeFromRecents); - mService.getLockTaskController().clearLockedTask(tr); + if (task != null) { + task.removeTaskActivitiesLocked(reason); + cleanUpRemovedTaskLocked(task, killProcess, removeFromRecents); + mService.getLockTaskController().clearLockedTask(task); mService.getTaskChangeNotificationController().notifyTaskStackChanged(); - if (tr.isPersistable) { + if (task.isPersistable) { mService.notifyTaskPersisterLocked(null, true); } return true; @@ -1807,19 +1807,19 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks { return false; } - void cleanUpRemovedTaskLocked(TaskRecord tr, boolean killProcess, boolean removeFromRecents) { + void cleanUpRemovedTaskLocked(Task task, boolean killProcess, boolean removeFromRecents) { if (removeFromRecents) { - mRecentTasks.remove(tr); + mRecentTasks.remove(task); } - ComponentName component = tr.getBaseIntent().getComponent(); + ComponentName component = task.getBaseIntent().getComponent(); if (component == null) { - Slog.w(TAG, "No component for base intent of task: " + tr); + Slog.w(TAG, "No component for base intent of task: " + task); return; } // Find any running services associated with this app and stop if needed. final Message msg = PooledLambda.obtainMessage(ActivityManagerInternal::cleanUpServices, - mService.mAmInternal, tr.mUserId, component, new Intent(tr.getBaseIntent())); + mService.mAmInternal, task.mUserId, component, new Intent(task.getBaseIntent())); mService.mH.sendMessage(msg); if (!killProcess) { @@ -1836,7 +1836,7 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks { SparseArray uids = pmap.valueAt(i); for (int j = 0; j < uids.size(); j++) { WindowProcessController proc = uids.valueAt(j); - if (proc.mUserId != tr.mUserId) { + if (proc.mUserId != task.mUserId) { // Don't kill process for a different user. continue; } @@ -1849,7 +1849,7 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks { continue; } - if (!proc.shouldKillProcessForRemovedTask(tr)) { + if (!proc.shouldKillProcessForRemovedTask(task)) { // Don't kill process(es) that has an activity in a different task that is also // in recents, or has an activity not stopped. return; @@ -1881,7 +1881,7 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks { * @param onTop If the stack for the task should be the topmost on the display. * @return true if the task has been restored successfully. */ - boolean restoreRecentTaskLocked(TaskRecord task, ActivityOptions aOptions, boolean onTop) { + boolean restoreRecentTaskLocked(Task task, ActivityOptions aOptions, boolean onTop) { final ActivityStack stack = mRootActivityContainer.getLaunchStack(null, aOptions, task, onTop); final ActivityStack currentStack = task.getStack(); @@ -1904,12 +1904,12 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks { } @Override - public void onRecentTaskAdded(TaskRecord task) { + public void onRecentTaskAdded(Task task) { task.touchActiveTime(); } @Override - public void onRecentTaskRemoved(TaskRecord task, boolean wasTrimmed, boolean killProcess) { + public void onRecentTaskRemoved(Task task, boolean wasTrimmed, boolean killProcess) { if (wasTrimmed) { // Task was trimmed from the recent tasks list -- remove the active task record as well // since the user won't really be able to go back to it @@ -1924,7 +1924,7 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks { * the various checks on tasks that are going to be reparented from one stack to another. */ // TODO: Look into changing users to this method to ActivityDisplay.resolveWindowingMode() - ActivityStack getReparentTargetStack(TaskRecord task, ActivityStack stack, boolean toTop) { + ActivityStack getReparentTargetStack(Task task, ActivityStack stack, boolean toTop) { final ActivityStack prevStack = task.getStack(); final int stackId = stack.mStackId; final boolean inMultiWindowMode = stack.inMultiWindowMode(); @@ -2077,7 +2077,7 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks { // Called when WindowManager has finished animating the launchingBehind activity to the back. private void handleLaunchTaskBehindCompleteLocked(ActivityRecord r) { - final TaskRecord task = r.getTaskRecord(); + final Task task = r.getTask(); final ActivityStack stack = task.getStack(); mRecentTasks.add(task); @@ -2088,7 +2088,7 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks { // task has been shown briefly final ActivityRecord top = stack.getTopActivity(); if (top != null) { - top.getTaskRecord().touchActiveTime(); + top.getTask().touchActiveTime(); } } @@ -2207,7 +2207,7 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks { static boolean dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list, String prefix, String label, boolean complete, boolean brief, boolean client, - String dumpPackage, boolean needNL, String header, TaskRecord lastTask) { + String dumpPackage, boolean needNL, String header, Task lastTask) { String innerPrefix = null; String[] args = null; boolean printed = false; @@ -2230,8 +2230,8 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks { pw.println(header); header = null; } - if (lastTask != r.getTaskRecord()) { - lastTask = r.getTaskRecord(); + if (lastTask != r.getTask()) { + lastTask = r.getTask(); pw.print(prefix); pw.print(full ? "* " : " "); pw.println(lastTask); @@ -2391,13 +2391,13 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks { WindowManagerService.WINDOW_FREEZE_TIMEOUT_DURATION); } - void handleNonResizableTaskIfNeeded(TaskRecord task, int preferredWindowingMode, + void handleNonResizableTaskIfNeeded(Task task, int preferredWindowingMode, int preferredDisplayId, ActivityStack actualStack) { handleNonResizableTaskIfNeeded(task, preferredWindowingMode, preferredDisplayId, actualStack, false /* forceNonResizable */); } - void handleNonResizableTaskIfNeeded(TaskRecord task, int preferredWindowingMode, + void handleNonResizableTaskIfNeeded(Task task, int preferredWindowingMode, int preferredDisplayId, ActivityStack actualStack, boolean forceNonResizable) { final boolean isSecondaryDisplayPreferred = (preferredDisplayId != DEFAULT_DISPLAY && preferredDisplayId != INVALID_DISPLAY); @@ -2466,7 +2466,7 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks { } /** Notifies that the top activity of the task is forced to be resizeable. */ - private void handleForcedResizableTaskIfNeeded(TaskRecord task, int reason) { + private void handleForcedResizableTaskIfNeeded(Task task, int reason) { final ActivityRecord topActivity = task.getTopActivity(); if (topActivity == null || topActivity.noDisplay || !topActivity.isNonResizableOrForcedResizable(task.getWindowingMode())) { @@ -2490,7 +2490,7 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks { mActivityMetricsLogger.logWindowState(); } - void scheduleUpdateMultiWindowMode(TaskRecord task) { + void scheduleUpdateMultiWindowMode(Task task) { // If the stack is animating in a way where we will be forcing a multi-mode change at the // end, then ensure that we defer all in between multi-window mode changes if (task.getStack().deferScheduleMultiWindowModeChanged()) { @@ -2509,7 +2509,7 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks { } } - void scheduleUpdatePictureInPictureModeIfNeeded(TaskRecord task, ActivityStack prevStack) { + void scheduleUpdatePictureInPictureModeIfNeeded(Task task, ActivityStack prevStack) { final ActivityStack stack = task.getStack(); if (prevStack == null || prevStack == stack || (!prevStack.inPinnedWindowingMode() && !stack.inPinnedWindowingMode())) { @@ -2519,7 +2519,7 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks { scheduleUpdatePictureInPictureModeIfNeeded(task, stack.getRequestedOverrideBounds()); } - void scheduleUpdatePictureInPictureModeIfNeeded(TaskRecord task, Rect targetStackBounds) { + void scheduleUpdatePictureInPictureModeIfNeeded(Task task, Rect targetStackBounds) { for (int i = task.getChildCount() - 1; i >= 0; i--) { final ActivityRecord r = task.getChildAt(i); if (r.attachedToProcess()) { @@ -2537,7 +2537,7 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks { } } - void updatePictureInPictureMode(TaskRecord task, Rect targetStackBounds, boolean forceUpdate) { + void updatePictureInPictureMode(Task task, Rect targetStackBounds, boolean forceUpdate) { mHandler.removeMessages(REPORT_PIP_MODE_CHANGED_MSG); for (int i = task.getChildCount() - 1; i >= 0; i--) { final ActivityRecord r = task.getChildAt(i); @@ -2694,14 +2694,14 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks { * * @param task The task to put into resizing mode */ - void setResizingDuringAnimation(TaskRecord task) { + void setResizingDuringAnimation(Task task) { mResizingTasksDuringAnimation.add(task.mTaskId); task.setTaskDockedResizing(true); } int startActivityFromRecents(int callingPid, int callingUid, int taskId, SafeActivityOptions options) { - TaskRecord task = null; + Task task = null; final String callingPackage; final Intent intent; final int userId; diff --git a/services/core/java/com/android/server/wm/ActivityStartController.java b/services/core/java/com/android/server/wm/ActivityStartController.java index e2e2b743d0116..3c79c32fb008e 100644 --- a/services/core/java/com/android/server/wm/ActivityStartController.java +++ b/services/core/java/com/android/server/wm/ActivityStartController.java @@ -271,7 +271,7 @@ public class ActivityStartController { final int startActivityInPackage(int uid, int realCallingPid, int realCallingUid, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, SafeActivityOptions options, - int userId, TaskRecord inTask, String reason, boolean validateIncomingUser, + int userId, Task inTask, String reason, boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent, boolean allowBackgroundActivityStart) { userId = checkTargetUser(userId, validateIncomingUser, realCallingPid, realCallingUid, diff --git a/services/core/java/com/android/server/wm/ActivityStartInterceptor.java b/services/core/java/com/android/server/wm/ActivityStartInterceptor.java index effd154a6aa0a..8420695bbdd6e 100644 --- a/services/core/java/com/android/server/wm/ActivityStartInterceptor.java +++ b/services/core/java/com/android/server/wm/ActivityStartInterceptor.java @@ -97,7 +97,7 @@ class ActivityStartInterceptor { ResolveInfo mRInfo; ActivityInfo mAInfo; String mResolvedType; - TaskRecord mInTask; + Task mInTask; ActivityOptions mActivityOptions; ActivityStartInterceptor( @@ -144,7 +144,7 @@ class ActivityStartInterceptor { * @return true if an interception occurred */ boolean intercept(Intent intent, ResolveInfo rInfo, ActivityInfo aInfo, String resolvedType, - TaskRecord inTask, int callingPid, int callingUid, ActivityOptions activityOptions) { + Task inTask, int callingPid, int callingUid, ActivityOptions activityOptions) { mUserManager = UserManager.get(mServiceContext); mIntent = intent; diff --git a/services/core/java/com/android/server/wm/ActivityStarter.java b/services/core/java/com/android/server/wm/ActivityStarter.java index 5cb1df260b892..2218c7237e761 100644 --- a/services/core/java/com/android/server/wm/ActivityStarter.java +++ b/services/core/java/com/android/server/wm/ActivityStarter.java @@ -82,7 +82,7 @@ import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLAS import static com.android.server.wm.ActivityTaskManagerService.ANIMATE; import static com.android.server.wm.LaunchParamsController.LaunchParamsModifier.PHASE_BOUNDS; import static com.android.server.wm.LaunchParamsController.LaunchParamsModifier.PHASE_DISPLAY; -import static com.android.server.wm.TaskRecord.REPARENT_MOVE_STACK_TO_FRONT; +import static com.android.server.wm.Task.REPARENT_MOVE_STACK_TO_FRONT; import android.annotation.NonNull; import android.annotation.Nullable; @@ -175,9 +175,9 @@ class ActivityStarter { // The display to launch the activity onto, barring any strong reason to do otherwise. private int mPreferredDisplayId; - private TaskRecord mInTask; + private Task mInTask; private boolean mAddingToTask; - private TaskRecord mReuseTask; + private Task mReuseTask; private ActivityInfo mNewTaskInfo; private Intent mNewTaskIntent; @@ -330,7 +330,7 @@ class ActivityStarter { boolean componentSpecified; boolean avoidMoveToFront; ActivityRecord[] outActivity; - TaskRecord inTask; + Task inTask; String reason; ProfilerInfo profilerInfo; Configuration globalConfig; @@ -571,7 +571,7 @@ class ActivityStarter { */ void startResolvedActivity(final ActivityRecord r, ActivityRecord sourceRecord, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, - int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask) { + int startFlags, boolean doResume, ActivityOptions options, Task inTask) { try { mSupervisor.getActivityMetricsLogger().notifyActivityLaunching(r.intent); mLastStartReason = "startResolvedActivity"; @@ -808,7 +808,7 @@ class ActivityStarter { final int realCallingUid = request.realCallingUid; final int startFlags = request.startFlags; final SafeActivityOptions options = request.activityOptions; - TaskRecord inTask = request.inTask; + Task inTask = request.inTask; int err = ActivityManager.START_SUCCESS; // Pull the optional Ephemeral Installer-only bundle out of the options early. @@ -895,7 +895,7 @@ class ActivityStarter { } if (err == ActivityManager.START_SUCCESS && sourceRecord != null - && sourceRecord.getTaskRecord().voiceSession != null) { + && sourceRecord.getTask().voiceSession != null) { // If this activity is being launched as part of a voice session, we need to ensure // that it is safe to do so. If the upcoming activity will also be part of the voice // session, we can only launch it if it has explicitly said it supports the VOICE @@ -1392,7 +1392,7 @@ class ActivityStarter { */ private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, - int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask, + int startFlags, boolean doResume, ActivityOptions options, Task inTask, boolean restrictedBgActivity) { int result = START_CANCELED; final ActivityStack startedActivityStack; @@ -1464,7 +1464,7 @@ class ActivityStarter { */ private int startActivityInner(final ActivityRecord r, ActivityRecord sourceRecord, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, - int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask, + int startFlags, boolean doResume, ActivityOptions options, Task inTask, boolean restrictedBgActivity) { setInitialState(r, options, inTask, doResume, startFlags, sourceRecord, voiceSession, voiceInteractor, restrictedBgActivity); @@ -1477,7 +1477,7 @@ class ActivityStarter { mIntent.setFlags(mLaunchFlags); - final TaskRecord reusedTask = getReusableTask(); + final Task reusedTask = getReusableTask(); mSupervisor.getLaunchParamsController().calculate(reusedTask != null ? reusedTask : mInTask, r.info.windowLayout, r, sourceRecord, options, PHASE_BOUNDS, mLaunchParams); mPreferredDisplayId = @@ -1493,7 +1493,7 @@ class ActivityStarter { } // Compute if there is an existing task that should be used for. - final TaskRecord targetTask = reusedTask != null ? reusedTask : computeTargetTask(); + final Task targetTask = reusedTask != null ? reusedTask : computeTargetTask(); final boolean newTask = targetTask == null; // Check if starting activity on given task or on a new task is allowed. @@ -1525,11 +1525,11 @@ class ActivityStarter { mTargetStack = computeStackFocus(mStartActivity, true, mLaunchFlags, mOptions); } if (newTask) { - final TaskRecord taskToAffiliate = (mLaunchTaskBehind && mSourceRecord != null) - ? mSourceRecord.getTaskRecord() : null; + final Task taskToAffiliate = (mLaunchTaskBehind && mSourceRecord != null) + ? mSourceRecord.getTask() : null; setNewTask(taskToAffiliate); if (mService.getLockTaskController().isLockTaskModeViolation( - mStartActivity.getTaskRecord())) { + mStartActivity.getTask())) { Slog.e(TAG, "Attempted Lock Task Mode violation mStartActivity=" + mStartActivity); return START_RETURN_LOCK_TASK_MODE_VIOLATION; } @@ -1550,10 +1550,10 @@ class ActivityStarter { ); if (newTask) { EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, mStartActivity.mUserId, - mStartActivity.getTaskRecord().mTaskId); + mStartActivity.getTask().mTaskId); } mStartActivity.logStartActivity( - EventLogTags.AM_CREATE_ACTIVITY, mStartActivity.getTaskRecord()); + EventLogTags.AM_CREATE_ACTIVITY, mStartActivity.getTask()); mTargetStack.mLastPausedActivity = null; mRootActivityContainer.sendPowerHintForLaunchStartIfNeeded( @@ -1563,7 +1563,7 @@ class ActivityStarter { mKeepCurTransition, mOptions); if (mDoResume) { final ActivityRecord topTaskActivity = - mStartActivity.getTaskRecord().topRunningActivityLocked(); + mStartActivity.getTask().topRunningActivityLocked(); if (!mTargetStack.isFocusable() || (topTaskActivity != null && topTaskActivity.mTaskOverlay && mStartActivity != topTaskActivity)) { @@ -1591,36 +1591,36 @@ class ActivityStarter { mTargetStack, mStartActivity, mOptions); } } else if (mStartActivity != null) { - mSupervisor.mRecentTasks.add(mStartActivity.getTaskRecord()); + mSupervisor.mRecentTasks.add(mStartActivity.getTask()); } mRootActivityContainer.updateUserStack(mStartActivity.mUserId, mTargetStack); - mSupervisor.handleNonResizableTaskIfNeeded(mStartActivity.getTaskRecord(), + mSupervisor.handleNonResizableTaskIfNeeded(mStartActivity.getTask(), preferredWindowingMode, mPreferredDisplayId, mTargetStack); return START_SUCCESS; } - private TaskRecord computeTargetTask() { + private Task computeTargetTask() { if (mStartActivity.resultTo == null && mInTask == null && !mAddingToTask && (mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0) { // A new task should be created instead of using existing one. return null; } else if (mSourceRecord != null) { - return mSourceRecord.getTaskRecord(); + return mSourceRecord.getTask(); } else if (mInTask != null) { return mInTask; } else { final ActivityRecord top = computeStackFocus(mStartActivity, false /* newTask */, mLaunchFlags, mOptions).getTopActivity(); if (top != null) { - return top.getTaskRecord(); + return top.getTask(); } } return null; } - private int isAllowedToStart(ActivityRecord r, boolean newTask, TaskRecord targetTask) { + private int isAllowedToStart(ActivityRecord r, boolean newTask, Task targetTask) { if (mStartActivity.packageName == null) { if (mStartActivity.resultTo != null) { mStartActivity.resultTo.sendResult(INVALID_UID, mStartActivity.resultWho, @@ -1666,8 +1666,7 @@ class ActivityStarter { * - Comply to the specified activity launch flags * - Determine whether need to add a new activity on top or just brought the task to front. */ - private int recycleTask(TaskRecord targetTask, ActivityRecord targetTaskTop, - TaskRecord reusedTask) { + private int recycleTask(Task targetTask, ActivityRecord targetTaskTop, Task reusedTask) { // True if we are clearing top and resetting of a standard (default) launch mode // ({@code LAUNCH_MULTIPLE}) activity. The existing activity will be finished. final boolean clearTopAndResetStandardLaunchMode = @@ -1680,7 +1679,7 @@ class ActivityStarter { // If mStartActivity does not have a task associated with it, associate it with the // reused activity's task. Do not do so if we're clearing top and resetting for a // standard launchMode activity. - if (mStartActivity.getTaskRecord() == null && !clearTopAndResetStandardLaunchMode) { + if (mStartActivity.getTask() == null && !clearTopAndResetStandardLaunchMode) { mStartActivity.setTaskForReuse(reusedTask); clearTaskForReuse = true; } @@ -1796,7 +1795,7 @@ class ActivityStarter { // Don't use mStartActivity.task to show the toast. We're not starting a new activity but // reusing 'top'. Fields in mStartActivity may not be fully initialized. - mSupervisor.handleNonResizableTaskIfNeeded(top.getTaskRecord(), + mSupervisor.handleNonResizableTaskIfNeeded(top.getTask(), mLaunchParams.mWindowingMode, mPreferredDisplayId, topStack); return START_DELIVERED_TO_TOP; @@ -1806,7 +1805,7 @@ class ActivityStarter { * Applying the launching flags to the task, which might clear few or all the activities in the * task. */ - private void complyActivityFlags(TaskRecord targetTask, ActivityRecord reusedActivity) { + private void complyActivityFlags(Task targetTask, ActivityRecord reusedActivity) { ActivityRecord targetTaskTop = targetTask.getTopActivity(); final boolean resetTask = reusedActivity != null && (mLaunchFlags & FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0; @@ -1818,10 +1817,10 @@ class ActivityStarter { == (FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK)) { // The caller has requested to completely replace any existing task with its new // activity. Well that should not be too hard... - // Note: we must persist the {@link TaskRecord} first as intentActivity could be + // Note: we must persist the {@link Task} first as intentActivity could be // removed from calling performClearTaskLocked (For example, if it is being brought out // of history or if it is finished immediately), thus disassociating the task. Also note - // that mReuseTask is reset as a result of {@link TaskRecord#performClearTaskLocked} + // that mReuseTask is reset as a result of {@link Task#performClearTaskLocked} // launching another activity. // TODO(b/36119896): We shouldn't trigger activity launches in this path since we are // already launching one. @@ -1838,9 +1837,9 @@ class ActivityStarter { mLaunchFlags); // The above code can remove {@code reusedActivity} from the task, leading to the - // {@code ActivityRecord} removing its reference to the {@code TaskRecord}. The task + // {@code ActivityRecord} removing its reference to the {@code Task}. The task // reference is needed in the call below to {@link setTargetStackAndMoveToFrontIfNeeded} - if (targetTaskTop.getTaskRecord() == null) { + if (targetTaskTop.getTask() == null) { targetTask.addChild(targetTaskTop); } @@ -1848,7 +1847,7 @@ class ActivityStarter { if (top.isRootOfTask()) { // Activity aliases may mean we use different intents for the top activity, // so make sure the task now has the identity of the new intent. - top.getTaskRecord().setIntent(mStartActivity); + top.getTask().setIntent(mStartActivity); } deliverNewIntent(top); } else { @@ -1873,7 +1872,7 @@ class ActivityStarter { final ActivityRecord act = targetTask.findActivityInHistoryLocked( mStartActivity); if (act != null) { - final TaskRecord task = act.getTaskRecord(); + final Task task = act.getTask(); task.moveActivityToFrontLocked(act); act.updateOptionsLocked(mOptions); deliverNewIntent(act); @@ -1894,7 +1893,7 @@ class ActivityStarter { // activity in the task is the root activity, deliver this new intent to it if it // desires. if (targetTaskTop.isRootOfTask()) { - targetTaskTop.getTaskRecord().setIntent(mStartActivity); + targetTaskTop.getTask().setIntent(mStartActivity); } deliverNewIntent(targetTaskTop); } else if (!targetTask.isSameIntentFilter(mStartActivity)) { @@ -1968,7 +1967,7 @@ class ActivityStarter { } } - private void setInitialState(ActivityRecord r, ActivityOptions options, TaskRecord inTask, + private void setInitialState(ActivityRecord r, ActivityOptions options, Task inTask, boolean doResume, int startFlags, ActivityRecord sourceRecord, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, boolean restrictedBgActivity) { @@ -2036,7 +2035,7 @@ class ActivityStarter { if (mOptions.getLaunchTaskId() != -1 && mOptions.getTaskOverlay()) { r.mTaskOverlay = true; if (!mOptions.canTaskOverlayResume()) { - final TaskRecord task = mRootActivityContainer.anyTaskForId( + final Task task = mRootActivityContainer.anyTaskForId( mOptions.getLaunchTaskId()); final ActivityRecord top = task != null ? task.getTopActivity() : null; if (top != null && !top.isState(RESUMED)) { @@ -2210,7 +2209,7 @@ class ActivityStarter { // example, if this method is being called for processing a pending activity launch, it // is possible that the activity has been removed from the task after the launch was // enqueued. - final TaskRecord sourceTask = mSourceRecord.getTaskRecord(); + final Task sourceTask = mSourceRecord.getTask(); mNewTaskIntent = sourceTask != null ? sourceTask.intent : null; } mSourceRecord = null; @@ -2221,7 +2220,7 @@ class ActivityStarter { * Decide whether the new activity should be inserted into an existing task. Returns null * if not or an ActivityRecord with the task into which the new activity should be added. */ - private TaskRecord getReusableTask() { + private Task getReusableTask() { // We may want to try to place the new activity in to an existing task. We always // do this if the target activity is singleTask or singleInstance; we will also do // this if NEW_TASK has been requested, and there is not an additional qualifier telling @@ -2236,7 +2235,7 @@ class ActivityStarter { putIntoExistingTask &= mInTask == null && mStartActivity.resultTo == null; ActivityRecord intentActivity = null; if (mOptions != null && mOptions.getLaunchTaskId() != -1) { - TaskRecord launchTask = mRootActivityContainer.anyTaskForId(mOptions.getLaunchTaskId()); + Task launchTask = mRootActivityContainer.anyTaskForId(mOptions.getLaunchTaskId()); if (launchTask != null) { return launchTask; } @@ -2265,7 +2264,7 @@ class ActivityStarter { intentActivity = null; } - return intentActivity != null ? intentActivity.getTaskRecord() : null; + return intentActivity != null ? intentActivity.getTask() : null; } /** @@ -2286,8 +2285,8 @@ class ActivityStarter { final ActivityStack focusStack = mTargetStack.getDisplay().getFocusedStack(); final ActivityRecord curTop = (focusStack == null) ? null : focusStack.topRunningNonDelayedActivityLocked(mNotTop); - final TaskRecord topTask = curTop != null ? curTop.getTaskRecord() : null; - differentTopTask = topTask != intentActivity.getTaskRecord() + final Task topTask = curTop != null ? curTop.getTask() : null; + differentTopTask = topTask != intentActivity.getTask() || (focusStack != null && topTask != focusStack.topTask()); } else { // The existing task should always be different from those in other displays. @@ -2297,14 +2296,14 @@ class ActivityStarter { if (differentTopTask && !mAvoidMoveToFront) { mStartActivity.intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT); if (mSourceRecord == null || (mSourceStack.getTopActivity() != null && - mSourceStack.getTopActivity().getTaskRecord() - == mSourceRecord.getTaskRecord())) { + mSourceStack.getTopActivity().getTask() + == mSourceRecord.getTask())) { // We really do want to push this one into the user's face, right now. if (mLaunchTaskBehind && mSourceRecord != null) { - intentActivity.setTaskToAffiliateWith(mSourceRecord.getTaskRecord()); + intentActivity.setTaskToAffiliateWith(mSourceRecord.getTask()); } - final TaskRecord intentTask = intentActivity.getTaskRecord(); + final Task intentTask = intentActivity.getTask(); final ActivityStack launchStack = getLaunchStack(mStartActivity, mLaunchFlags, intentTask, mOptions); if (launchStack == null || launchStack == mTargetStack) { @@ -2336,7 +2335,7 @@ class ActivityStarter { // Target and computed stacks are on different displays and we've // found a matching task - move the existing instance to that display and // move it to front. - intentActivity.getTaskRecord().reparent(launchStack, ON_TOP, + intentActivity.getTask().reparent(launchStack, ON_TOP, REPARENT_MOVE_STACK_TO_FRONT, ANIMATE, DEFER_RESUME, "reparentToDisplay"); mMovedToFront = true; @@ -2346,7 +2345,7 @@ class ActivityStarter { // For example, the activity may have been initially started with an intent // which placed it in the fullscreen stack. To ensure the proper handling of // the activity based on home stack assumptions, we must move it over. - intentActivity.getTaskRecord().reparent(launchStack, ON_TOP, + intentActivity.getTask().reparent(launchStack, ON_TOP, REPARENT_MOVE_STACK_TO_FRONT, ANIMATE, DEFER_RESUME, "reparentingHome"); mMovedToFront = true; @@ -2365,7 +2364,7 @@ class ActivityStarter { // Need to update mTargetStack because if task was moved out of it, the original stack may // be destroyed. mTargetStack = intentActivity.getActivityStack(); - mSupervisor.handleNonResizableTaskIfNeeded(intentActivity.getTaskRecord(), + mSupervisor.handleNonResizableTaskIfNeeded(intentActivity.getTask(), WINDOWING_MODE_UNDEFINED, DEFAULT_DISPLAY, mTargetStack); } @@ -2378,19 +2377,19 @@ class ActivityStarter { mRootActivityContainer.updateUserStack(mStartActivity.mUserId, mTargetStack); } - private void setNewTask(TaskRecord taskToAffiliate) { + private void setNewTask(Task taskToAffiliate) { final boolean toTop = !mLaunchTaskBehind && !mAvoidMoveToFront; - final TaskRecord task = mTargetStack.createTaskRecord( + final Task task = mTargetStack.createTask( mSupervisor.getNextTaskIdForUserLocked(mStartActivity.mUserId), mNewTaskInfo != null ? mNewTaskInfo : mStartActivity.info, mNewTaskIntent != null ? mNewTaskIntent : mIntent, mVoiceSession, mVoiceInteractor, toTop, mStartActivity, mSourceRecord, mOptions); addOrReparentStartingActivity(task, "setTaskFromReuseOrCreateNewTask - mReuseTask"); - updateBounds(mStartActivity.getTaskRecord(), mLaunchParams.mBounds); + updateBounds(mStartActivity.getTask(), mLaunchParams.mBounds); if (DEBUG_TASKS) { Slog.v(TAG_TASKS, "Starting new activity " + mStartActivity - + " in new task " + mStartActivity.getTaskRecord()); + + " in new task " + mStartActivity.getTask()); } if (taskToAffiliate != null) { @@ -2403,14 +2402,14 @@ class ActivityStarter { return; } - activity.logStartActivity(AM_NEW_INTENT, activity.getTaskRecord()); + activity.logStartActivity(AM_NEW_INTENT, activity.getTask()); activity.deliverNewIntentLocked(mCallingUid, mStartActivity.intent, mStartActivity.launchedFromPackage); mIntentDelivered = true; } @VisibleForTesting - void updateBounds(TaskRecord task, Rect bounds) { + void updateBounds(Task task, Rect bounds) { if (bounds.isEmpty()) { return; } @@ -2423,8 +2422,8 @@ class ActivityStarter { } } - private void addOrReparentStartingActivity(TaskRecord parent, String reason) { - if (mStartActivity.getTaskRecord() == null || mStartActivity.getTaskRecord() == parent) { + private void addOrReparentStartingActivity(Task parent, String reason) { + if (mStartActivity.getTask() == null || mStartActivity.getTask() == parent) { parent.addChild(mStartActivity); } else { mStartActivity.reparent(parent, parent.getChildCount() /* top */, reason); @@ -2460,7 +2459,7 @@ class ActivityStarter { private ActivityStack computeStackFocus(ActivityRecord r, boolean newTask, int launchFlags, ActivityOptions aOptions) { - final TaskRecord task = r.getTaskRecord(); + final Task task = r.getTask(); ActivityStack stack = getLaunchStack(r, launchFlags, task, aOptions); if (stack != null) { return stack; @@ -2542,7 +2541,7 @@ class ActivityStarter { && (mPreferredDisplayId == focusedStack.mDisplayId); } - private ActivityStack getLaunchStack(ActivityRecord r, int launchFlags, TaskRecord task, + private ActivityStack getLaunchStack(ActivityRecord r, int launchFlags, Task task, ActivityOptions aOptions) { // We are reusing a task, keep the stack! if (mReuseTask != null) { @@ -2753,7 +2752,7 @@ class ActivityStarter { return this; } - ActivityStarter setInTask(TaskRecord inTask) { + ActivityStarter setInTask(Task inTask) { mRequest.inTask = inTask; return this; } diff --git a/services/core/java/com/android/server/wm/ActivityTaskManagerInternal.java b/services/core/java/com/android/server/wm/ActivityTaskManagerInternal.java index 0488a3b7065b9..cce005bc859cf 100644 --- a/services/core/java/com/android/server/wm/ActivityTaskManagerInternal.java +++ b/services/core/java/com/android/server/wm/ActivityTaskManagerInternal.java @@ -229,7 +229,7 @@ public abstract class ActivityTaskManagerInternal { public abstract int startActivityInPackage(int uid, int realCallingPid, int realCallingUid, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, SafeActivityOptions options, - int userId, TaskRecord inTask, String reason, boolean validateIncomingUser, + int userId, Task inTask, String reason, boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent, boolean allowBackgroundActivityStart); /** diff --git a/services/core/java/com/android/server/wm/ActivityTaskManagerService.java b/services/core/java/com/android/server/wm/ActivityTaskManagerService.java index 32f46520f821f..3ef848cb0106e 100644 --- a/services/core/java/com/android/server/wm/ActivityTaskManagerService.java +++ b/services/core/java/com/android/server/wm/ActivityTaskManagerService.java @@ -117,9 +117,9 @@ import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_P import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION; import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY; import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS; -import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK; -import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT; -import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE; +import static com.android.server.wm.Task.LOCK_TASK_AUTH_DONT_LOCK; +import static com.android.server.wm.Task.REPARENT_KEEP_STACK_AT_FRONT; +import static com.android.server.wm.Task.REPARENT_LEAVE_STACK_IN_PLACE; import android.Manifest; import android.annotation.IntDef; @@ -1572,7 +1572,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub { return true; } // Keep track of the root activity of the task before we finish it - final TaskRecord tr = r.getTaskRecord(); + final Task tr = r.getTask(); final ActivityRecord rootR = tr.getRootActivity(); if (rootR == null) { Slog.w(TAG, "Finishing task with all activities already finished"); @@ -1994,7 +1994,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub { if (r == null) { return false; } - final TaskRecord task = r.getTaskRecord(); + final Task task = r.getTask(); int index = task.mChildren.lastIndexOf(r); if (index > 0) { ActivityRecord under = task.getChildAt(index - 1); @@ -2086,7 +2086,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub { final long callingId = Binder.clearCallingIdentity(); try { synchronized (mGlobalLock) { - final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId, + final Task task = mRootActivityContainer.anyTaskForId(taskId, MATCH_TASK_IN_STACKS_ONLY); if (task == null) { return; @@ -2196,7 +2196,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub { final long origId = Binder.clearCallingIdentity(); try { int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot); - final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId); + final Task task = mRootActivityContainer.anyTaskForId(taskId); if (task != null) { return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId); } @@ -2214,7 +2214,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub { Rect rect = new Rect(); try { synchronized (mGlobalLock) { - final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId, + final Task task = mRootActivityContainer.anyTaskForId(taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS); if (task == null) { Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found"); @@ -2237,7 +2237,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub { synchronized (mGlobalLock) { enforceCallerIsRecentsOrHasPermission( MANAGE_ACTIVITY_STACKS, "getTaskDescription()"); - final TaskRecord tr = mRootActivityContainer.anyTaskForId(id, + final Task tr = mRootActivityContainer.anyTaskForId(id, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS); if (tr != null) { return tr.getTaskDescription(); @@ -2257,7 +2257,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub { synchronized (mGlobalLock) { final long ident = Binder.clearCallingIdentity(); try { - final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId, + final Task task = mRootActivityContainer.anyTaskForId(taskId, MATCH_TASK_IN_STACKS_ONLY); if (task == null) { Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId); @@ -2335,7 +2335,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub { // windows above full screen activities. Instead of directly finishing the // task, a task change listener is used to notify SystemUI so the action can be // handled specially. - final TaskRecord task = r.getTaskRecord(); + final Task task = r.getTask(); mTaskChangeNotificationController .notifyBackPressedOnTaskRoot(task.getTaskInfo()); } else { @@ -2393,7 +2393,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub { } } try { - final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId); + final Task task = mRootActivityContainer.anyTaskForId(taskId); if (task == null) { Slog.d(TAG, "Could not find task for id: "+ taskId); SafeActivityOptions.abort(options); @@ -2573,7 +2573,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub { synchronized (mGlobalLock) { final long ident = Binder.clearCallingIdentity(); try { - final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId); + final Task task = mRootActivityContainer.anyTaskForId(taskId); if (task == null) { Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId); return; @@ -2685,7 +2685,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub { synchronized (mGlobalLock) { final long ident = Binder.clearCallingIdentity(); try { - final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId, + final Task task = mRootActivityContainer.anyTaskForId(taskId, MATCH_TASK_IN_STACKS_ONLY); if (task == null) { Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId); @@ -2817,7 +2817,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub { if (r == null) { return; } - startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */); + startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */); } } @@ -2828,7 +2828,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub { long ident = Binder.clearCallingIdentity(); try { synchronized (mGlobalLock) { - final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId, + final Task task = mRootActivityContainer.anyTaskForId(taskId, MATCH_TASK_IN_STACKS_ONLY); if (task == null) { return; @@ -2850,7 +2850,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub { if (r == null) { return; } - stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */); + stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */); } } @@ -2864,7 +2864,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub { stopLockTaskModeInternal(null, true /* isSystemCaller */); } - private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) { + private void startLockTaskModeLocked(@Nullable Task task, boolean isSystemCaller) { if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task); if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) { return; @@ -2893,7 +2893,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub { } } - private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) { + private void stopLockTaskModeInternal(@Nullable Task task, boolean isSystemCaller) { final int callingUid = Binder.getCallingUid(); long ident = Binder.clearCallingIdentity(); try { @@ -2943,7 +2943,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub { ActivityRecord r = ActivityRecord.isInStackLocked(token); if (r != null) { r.setTaskDescription(td); - final TaskRecord task = r.getTaskRecord(); + final Task task = r.getTask(); task.updateTaskDescription(); } } @@ -2999,7 +2999,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub { public boolean isTopOfTask(IBinder token) { synchronized (mGlobalLock) { ActivityRecord r = ActivityRecord.isInStackLocked(token); - return r != null && r.getTaskRecord().getTopActivity() == r; + return r != null && r.getTask().getTopActivity() == r; } } @@ -3038,7 +3038,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub { } if (structure != null) { // Pre-fill the task/activity component for all assist data receivers - structure.setTaskId(pae.activity.getTaskRecord().mTaskId); + structure.setTaskId(pae.activity.getTask().mTaskId); structure.setActivityComponent(pae.activity.mActivityComponent); structure.setHomeActivity(pae.isHome); } @@ -3065,7 +3065,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub { // Caller wants result sent back to them. sendBundle = new Bundle(); sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID, - pae.activity.getTaskRecord().mTaskId); + pae.activity.getTask().mTaskId); sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID, pae.activity.assistToken); sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras); @@ -3153,7 +3153,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub { } final ActivityStack stack = r.getActivityStack(); - final TaskRecord task = stack.createTaskRecord( + final Task task = stack.createTask( mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent, null /* voiceSession */, null /* voiceInteractor */, !ON_TOP); if (!mRecentTasks.addToBottom(task)) { @@ -3182,7 +3182,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub { @Override public void setTaskResizeable(int taskId, int resizeableMode) { synchronized (mGlobalLock) { - final TaskRecord task = mRootActivityContainer.anyTaskForId( + final Task task = mRootActivityContainer.anyTaskForId( taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS); if (task == null) { Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found"); @@ -3198,7 +3198,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub { long ident = Binder.clearCallingIdentity(); try { synchronized (mGlobalLock) { - final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId, + final Task task = mRootActivityContainer.anyTaskForId(taskId, MATCH_TASK_IN_STACKS_ONLY); if (task == null) { Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found"); @@ -3243,7 +3243,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub { private void sanitizeAndApplyConfigChange(ConfigurationContainer container, WindowContainerTransaction.Change change) { - if (!(container instanceof TaskRecord)) { + if (!(container instanceof Task)) { throw new RuntimeException("Invalid token in task transaction"); } // The "client"-facing API should prevent bad changes; however, just in case, sanitize @@ -3884,7 +3884,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub { try { if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task=" + taskId + " in stackId=" + stackId + " at position=" + position); - final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId); + final Task task = mRootActivityContainer.anyTaskForId(taskId); if (task == null) { throw new IllegalArgumentException("positionTaskInStack: no task for id=" + taskId); @@ -4359,7 +4359,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub { if (ActivityRecord.forTokenLocked(callingActivity) != activity) { throw new SecurityException("Only focused activity can call startVoiceInteraction"); } - if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null + if (mRunningVoice != null || activity.getTask().voiceSession != null || activity.voiceSession != null) { Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction"); return; @@ -4469,7 +4469,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub { final long ident = Binder.clearCallingIdentity(); try { synchronized (mGlobalLock) { - final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId, + final Task task = mRootActivityContainer.anyTaskForId(taskId, MATCH_TASK_IN_STACKS_ONLY); if (task == null) { Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found"); @@ -4495,7 +4495,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub { private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution, boolean restoreFromDisk) { - final TaskRecord task; + final Task task; synchronized (mGlobalLock) { task = mRootActivityContainer.anyTaskForId(taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS); @@ -4820,7 +4820,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub { } /** Pokes the task persister. */ - void notifyTaskPersisterLocked(TaskRecord task, boolean flush) { + void notifyTaskPersisterLocked(Task task, boolean flush) { mRecentTasks.notifyTaskPersisterLocked(task, flush); } @@ -4977,7 +4977,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub { String[] newArgs = new String[args.length - opti]; System.arraycopy(args, opti, newArgs, 0, args.length - opti); - TaskRecord lastTask = null; + Task lastTask = null; boolean needSep = false; for (int i = activities.size() - 1; i >= 0; i--) { ActivityRecord r = activities.get(i); @@ -4986,7 +4986,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub { } needSep = true; synchronized (mGlobalLock) { - final TaskRecord task = r.getTaskRecord(); + final Task task = r.getTask(); if (lastTask != task) { lastTask = task; pw.print("TASK "); pw.print(lastTask.affinity); @@ -5403,7 +5403,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub { /** Update AMS states when an activity is resumed. */ void setResumedActivityUncheckLocked(ActivityRecord r, String reason) { - final TaskRecord task = r.getTaskRecord(); + final Task task = r.getTask(); if (task.isActivityTypeStandard()) { if (mCurAppTimeTracker != r.appTimeTracker) { // We are switching app tracking. Complete the current one. @@ -5435,7 +5435,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub { if (mLastResumedActivity != null) { final IVoiceInteractionSession session; - final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord(); + final Task lastResumedActivityTask = mLastResumedActivity.getTask(); if (lastResumedActivityTask != null && lastResumedActivityTask.voiceSession != null) { session = lastResumedActivityTask.voiceSession; @@ -5536,7 +5536,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub { void updateActivityUsageStats(ActivityRecord activity, int event) { ComponentName taskRoot = null; - final TaskRecord task = activity.getTaskRecord(); + final Task task = activity.getTask(); if (task != null) { final ActivityRecord rootActivity = task.getRootActivity(); if (rootActivity != null) { @@ -6141,7 +6141,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub { public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, SafeActivityOptions options, - int userId, TaskRecord inTask, String reason, boolean validateIncomingUser, + int userId, Task inTask, String reason, boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent, boolean allowBackgroundActivityStart) { synchronized (mGlobalLock) { @@ -6570,13 +6570,13 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub { @Override public ActivityTokens getTopActivityForTask(int taskId) { synchronized (mGlobalLock) { - final TaskRecord taskRecord = mRootActivityContainer.anyTaskForId(taskId); - if (taskRecord == null) { + final Task task = mRootActivityContainer.anyTaskForId(taskId); + if (task == null) { Slog.w(TAG, "getApplicationThreadForTopActivity failed:" + " Requested task not found"); return null; } - final ActivityRecord activity = taskRecord.getTopActivity(); + final ActivityRecord activity = task.getTopActivity(); if (activity == null) { Slog.w(TAG, "getApplicationThreadForTopActivity failed:" + " Requested activity not found"); diff --git a/services/core/java/com/android/server/wm/AppTaskImpl.java b/services/core/java/com/android/server/wm/AppTaskImpl.java index c5e190dc59cd7..93a22caa27572 100644 --- a/services/core/java/com/android/server/wm/AppTaskImpl.java +++ b/services/core/java/com/android/server/wm/AppTaskImpl.java @@ -79,12 +79,12 @@ class AppTaskImpl extends IAppTask.Stub { synchronized (mService.mGlobalLock) { long origId = Binder.clearCallingIdentity(); try { - TaskRecord tr = mService.mRootActivityContainer.anyTaskForId(mTaskId, + Task task = mService.mRootActivityContainer.anyTaskForId(mTaskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS); - if (tr == null) { + if (task == null) { throw new IllegalArgumentException("Unable to find task ID " + mTaskId); } - return mService.getRecentTasks().createRecentTaskInfo(tr); + return mService.getRecentTasks().createRecentTaskInfo(task); } finally { Binder.restoreCallingIdentity(origId); } @@ -136,12 +136,12 @@ class AppTaskImpl extends IAppTask.Stub { checkCaller(); int callingUser = UserHandle.getCallingUserId(); - TaskRecord tr; + Task task; IApplicationThread appThread; synchronized (mService.mGlobalLock) { - tr = mService.mRootActivityContainer.anyTaskForId(mTaskId, + task = mService.mRootActivityContainer.anyTaskForId(mTaskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS); - if (tr == null) { + if (task == null) { throw new IllegalArgumentException("Unable to find task ID " + mTaskId); } appThread = IApplicationThread.Stub.asInterface(whoThread); @@ -156,7 +156,7 @@ class AppTaskImpl extends IAppTask.Stub { .setResolvedType(resolvedType) .setActivityOptions(bOptions) .setUserId(callingUser) - .setInTask(tr) + .setInTask(task) .execute(); } @@ -167,12 +167,12 @@ class AppTaskImpl extends IAppTask.Stub { synchronized (mService.mGlobalLock) { long origId = Binder.clearCallingIdentity(); try { - TaskRecord tr = mService.mRootActivityContainer.anyTaskForId(mTaskId, + Task task = mService.mRootActivityContainer.anyTaskForId(mTaskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS); - if (tr == null) { + if (task == null) { throw new IllegalArgumentException("Unable to find task ID " + mTaskId); } - Intent intent = tr.getBaseIntent(); + Intent intent = task.getBaseIntent(); if (exclude) { intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); } else { diff --git a/services/core/java/com/android/server/wm/LaunchParamsController.java b/services/core/java/com/android/server/wm/LaunchParamsController.java index 6de48d1b2d078..03e13221c4a77 100644 --- a/services/core/java/com/android/server/wm/LaunchParamsController.java +++ b/services/core/java/com/android/server/wm/LaunchParamsController.java @@ -67,14 +67,14 @@ class LaunchParamsController { /** * Returns the {@link LaunchParams} calculated by the registered modifiers - * @param task The {@link TaskRecord} currently being positioned. + * @param task The {@link Task} currently being positioned. * @param layout The specified {@link WindowLayout}. * @param activity The {@link ActivityRecord} currently being positioned. * @param source The {@link ActivityRecord} from which activity was started from. * @param options The {@link ActivityOptions} specified for the activity. * @param result The resulting params. */ - void calculate(TaskRecord task, WindowLayout layout, ActivityRecord activity, + void calculate(Task task, WindowLayout layout, ActivityRecord activity, ActivityRecord source, ActivityOptions options, int phase, LaunchParams result) { result.reset(); @@ -120,11 +120,11 @@ class LaunchParamsController { * A convenience method for laying out a task. * @return {@code true} if bounds were set on the task. {@code false} otherwise. */ - boolean layoutTask(TaskRecord task, WindowLayout layout) { + boolean layoutTask(Task task, WindowLayout layout) { return layoutTask(task, layout, null /*activity*/, null /*source*/, null /*options*/); } - boolean layoutTask(TaskRecord task, WindowLayout layout, ActivityRecord activity, + boolean layoutTask(Task task, WindowLayout layout, ActivityRecord activity, ActivityRecord source, ActivityOptions options) { calculate(task, layout, activity, source, options, PHASE_BOUNDS, mTmpParams); @@ -184,7 +184,7 @@ class LaunchParamsController { /** The bounds within the parent container. */ final Rect mBounds = new Rect(); - /** The id of the display the {@link TaskRecord} would prefer to be on. */ + /** The id of the display the {@link Task} would prefer to be on. */ int mPreferredDisplayId; /** The windowing mode to be in. */ @@ -304,7 +304,7 @@ class LaunchParamsController { * @return see {@link LaunchParamsModifier.Result} */ @Result - int onCalculate(TaskRecord task, WindowLayout layout, ActivityRecord activity, + int onCalculate(Task task, WindowLayout layout, ActivityRecord activity, ActivityRecord source, ActivityOptions options, @Phase int phase, LaunchParams currentParams, LaunchParams outParams); } diff --git a/services/core/java/com/android/server/wm/LaunchParamsPersister.java b/services/core/java/com/android/server/wm/LaunchParamsPersister.java index 5d27390da588f..c3bcc740a065c 100644 --- a/services/core/java/com/android/server/wm/LaunchParamsPersister.java +++ b/services/core/java/com/android/server/wm/LaunchParamsPersister.java @@ -55,7 +55,7 @@ import java.util.function.IntFunction; /** * Persister that saves launch parameters in memory and in storage. It saves the last seen state of * tasks key-ed on task's user ID and the activity used to launch the task ({@link - * TaskRecord#realActivity}) and that's used to determine the launch params when the activity is + * Task#realActivity}) and that's used to determine the launch params when the activity is * being launched again in {@link LaunchParamsController}. * * Need to hold {@link ActivityTaskManagerService#getGlobalLock()} to access this class. @@ -196,7 +196,7 @@ class LaunchParamsPersister { } } - void saveTask(TaskRecord task) { + void saveTask(Task task) { final ComponentName name = task.realActivity; final int userId = task.mUserId; PersistableLaunchParams params; @@ -220,7 +220,7 @@ class LaunchParamsPersister { } } - private boolean saveTaskToLaunchParam(TaskRecord task, PersistableLaunchParams params) { + private boolean saveTaskToLaunchParam(Task task, PersistableLaunchParams params) { final ActivityStack stack = task.getStack(); final int displayId = stack.mDisplayId; final ActivityDisplay display = @@ -245,7 +245,7 @@ class LaunchParamsPersister { return changed; } - void getLaunchParams(TaskRecord task, ActivityRecord activity, LaunchParams outParams) { + void getLaunchParams(Task task, ActivityRecord activity, LaunchParams outParams) { final ComponentName name = task != null ? task.realActivity : activity.mActivityComponent; final int userId = task != null ? task.mUserId : activity.mUserId; @@ -412,7 +412,7 @@ class LaunchParamsPersister { /** The bounds within the parent container. */ final Rect mBounds = new Rect(); - /** The unique id of the display the {@link TaskRecord} would prefer to be on. */ + /** The unique id of the display the {@link Task} would prefer to be on. */ String mDisplayUniqueId; /** The windowing mode to be in. */ diff --git a/services/core/java/com/android/server/wm/LockTaskController.java b/services/core/java/com/android/server/wm/LockTaskController.java index dc45686a13599..6810f8c161649 100644 --- a/services/core/java/com/android/server/wm/LockTaskController.java +++ b/services/core/java/com/android/server/wm/LockTaskController.java @@ -32,11 +32,11 @@ import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTAS import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK; import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM; import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME; -import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK; -import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_LAUNCHABLE; -import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_LAUNCHABLE_PRIV; -import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_PINNABLE; -import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_WHITELISTED; +import static com.android.server.wm.Task.LOCK_TASK_AUTH_DONT_LOCK; +import static com.android.server.wm.Task.LOCK_TASK_AUTH_LAUNCHABLE; +import static com.android.server.wm.Task.LOCK_TASK_AUTH_LAUNCHABLE_PRIV; +import static com.android.server.wm.Task.LOCK_TASK_AUTH_PINNABLE; +import static com.android.server.wm.Task.LOCK_TASK_AUTH_WHITELISTED; import android.annotation.NonNull; import android.annotation.Nullable; @@ -157,7 +157,7 @@ public class LockTaskController { * * The list is empty if LockTask is inactive. */ - private final ArrayList mLockTaskModeTasks = new ArrayList<>(); + private final ArrayList mLockTaskModeTasks = new ArrayList<>(); /** * Packages that are allowed to be launched into the lock task mode for each user. @@ -221,14 +221,14 @@ public class LockTaskController { * back of the stack. */ @VisibleForTesting - boolean isTaskLocked(TaskRecord task) { + boolean isTaskLocked(Task task) { return mLockTaskModeTasks.contains(task); } /** * @return {@code true} whether this task first started the current LockTask session. */ - private boolean isRootTask(TaskRecord task) { + private boolean isRootTask(Task task) { return mLockTaskModeTasks.indexOf(task) == 0; } @@ -237,7 +237,7 @@ public class LockTaskController { * of the last locked task and finishing it would mean that lock task mode is ended illegally. */ boolean activityBlockedFromFinish(ActivityRecord activity) { - final TaskRecord task = activity.getTaskRecord(); + final Task task = activity.getTask(); if (activity == task.getRootActivity() && activity == task.getTopActivity() && task.mLockTaskAuth != LOCK_TASK_AUTH_LAUNCHABLE_PRIV @@ -254,7 +254,7 @@ public class LockTaskController { * {@link ActivityStack#moveTaskToBackLocked(int)} * @see #mLockTaskModeTasks */ - boolean canMoveTaskToBack(TaskRecord task) { + boolean canMoveTaskToBack(Task task) { if (isRootTask(task)) { showLockTaskToast(); return false; @@ -266,7 +266,7 @@ public class LockTaskController { * @return whether the requested task is allowed to be locked (either whitelisted, or declares * lockTaskMode="always" in the manifest). */ - boolean isTaskWhitelisted(TaskRecord task) { + boolean isTaskWhitelisted(Task task) { switch(task.mLockTaskAuth) { case LOCK_TASK_AUTH_WHITELISTED: case LOCK_TASK_AUTH_LAUNCHABLE: @@ -282,7 +282,7 @@ public class LockTaskController { /** * @return whether the requested task is disallowed to be launched. */ - boolean isLockTaskModeViolation(TaskRecord task) { + boolean isLockTaskModeViolation(Task task) { return isLockTaskModeViolation(task, false); } @@ -290,7 +290,7 @@ public class LockTaskController { * @param isNewClearTask whether the task would be cleared as part of the operation. * @return whether the requested task is disallowed to be launched. */ - boolean isLockTaskModeViolation(TaskRecord task, boolean isNewClearTask) { + boolean isLockTaskModeViolation(Task task, boolean isNewClearTask) { if (isLockTaskModeViolationInternal(task, isNewClearTask)) { showLockTaskToast(); return true; @@ -301,14 +301,14 @@ public class LockTaskController { /** * @return the root task of the lock task. */ - TaskRecord getRootTask() { + Task getRootTask() { if (mLockTaskModeTasks.isEmpty()) { return null; } return mLockTaskModeTasks.get(0); } - private boolean isLockTaskModeViolationInternal(TaskRecord task, boolean isNewClearTask) { + private boolean isLockTaskModeViolationInternal(Task task, boolean isNewClearTask) { // TODO: Double check what's going on here. If the task is already in lock task mode, it's // likely whitelisted, so will return false below. if (isTaskLocked(task) && !isNewClearTask) { @@ -339,7 +339,7 @@ public class LockTaskController { & DevicePolicyManager.LOCK_TASK_FEATURE_KEYGUARD) != 0; } - private boolean isEmergencyCallTask(TaskRecord task) { + private boolean isEmergencyCallTask(Task task) { final Intent intent = task.intent; if (intent == null) { return false; @@ -384,7 +384,7 @@ public class LockTaskController { * @throws SecurityException if the caller is not authorized to stop the lock task mode, i.e. if * they differ from the one that launched lock task mode. */ - void stopLockTaskMode(@Nullable TaskRecord task, boolean isSystemCaller, int callingUid) { + void stopLockTaskMode(@Nullable Task task, boolean isSystemCaller, int callingUid) { if (mLockTaskModeState == LOCK_TASK_MODE_NONE) { return; } @@ -407,8 +407,8 @@ public class LockTaskController { // It is possible lockTaskMode was started by the system process because // android:lockTaskMode is set to a locking value in the application manifest // instead of the app calling startLockTaskMode. In this case - // {@link TaskRecord.mLockTaskUid} will be 0, so we compare the callingUid to the - // {@link TaskRecord.effectiveUid} instead. Also caller with + // {@link Task.mLockTaskUid} will be 0, so we compare the callingUid to the + // {@link Task.effectiveUid} instead. Also caller with // {@link MANAGE_ACTIVITY_STACKS} can stop any lock task. if (callingUid != task.mLockTaskUid && (task.mLockTaskUid != 0 || callingUid != task.effectiveUid)) { @@ -425,7 +425,7 @@ public class LockTaskController { * Clear all locked tasks and request the end of LockTask mode. * * This method is called by UserController when starting a new foreground user, and, - * unlike {@link #stopLockTaskMode(TaskRecord, boolean, int)}, it doesn't perform the checks. + * unlike {@link #stopLockTaskMode(Task, boolean, int)}, it doesn't perform the checks. */ void clearLockedTasks(String reason) { if (DEBUG_LOCKTASK) Slog.i(TAG_LOCKTASK, "clearLockedTasks: " + reason); @@ -443,7 +443,7 @@ public class LockTaskController { * * @param task the task to be cleared from LockTask mode. */ - void clearLockedTask(final TaskRecord task) { + void clearLockedTask(final Task task) { if (task == null || mLockTaskModeTasks.isEmpty()) return; if (task == mLockTaskModeTasks.get(0)) { @@ -466,7 +466,7 @@ public class LockTaskController { * Remove the given task from the locked task list. If this was the last task in the list, * lock task mode is stopped. */ - private void removeLockedTask(final TaskRecord task) { + private void removeLockedTask(final Task task) { if (!mLockTaskModeTasks.remove(task)) { return; } @@ -527,7 +527,7 @@ public class LockTaskController { * at the calling task's mLockTaskAuth to decide which mode to start. * @param callingUid the caller that requested the launch of lock task mode. */ - void startLockTaskMode(@NonNull TaskRecord task, boolean isSystemCaller, int callingUid) { + void startLockTaskMode(@NonNull Task task, boolean isSystemCaller, int callingUid) { if (!isSystemCaller) { task.mLockTaskUid = callingUid; if (task.mLockTaskAuth == LOCK_TASK_AUTH_PINNABLE) { @@ -555,7 +555,7 @@ public class LockTaskController { * @param lockTaskModeState whether fully locked or pinned mode. * @param andResume whether the task should be brought to foreground as part of the operation. */ - private void setLockTaskMode(@NonNull TaskRecord task, int lockTaskModeState, + private void setLockTaskMode(@NonNull Task task, int lockTaskModeState, String reason, boolean andResume) { // Should have already been checked, but do it again. if (task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) { @@ -632,7 +632,7 @@ public class LockTaskController { boolean taskChanged = false; for (int taskNdx = mLockTaskModeTasks.size() - 1; taskNdx >= 0; --taskNdx) { - final TaskRecord lockedTask = mLockTaskModeTasks.get(taskNdx); + final Task lockedTask = mLockTaskModeTasks.get(taskNdx); final boolean wasWhitelisted = lockedTask.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE || lockedTask.mLockTaskAuth == LOCK_TASK_AUTH_WHITELISTED; lockedTask.setLockTaskAuth(); @@ -659,7 +659,7 @@ public class LockTaskController { } final ActivityRecord r = mSupervisor.mRootActivityContainer.topRunningActivity(); - final TaskRecord task = (r != null) ? r.getTaskRecord() : null; + final Task task = (r != null) ? r.getTask() : null; if (mLockTaskModeTasks.isEmpty() && task!= null && task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE) { // This task must have just been authorized. diff --git a/services/core/java/com/android/server/wm/RecentTasks.java b/services/core/java/com/android/server/wm/RecentTasks.java index 71696778f8912..2f46937bb1d90 100644 --- a/services/core/java/com/android/server/wm/RecentTasks.java +++ b/services/core/java/com/android/server/wm/RecentTasks.java @@ -119,7 +119,7 @@ class RecentTasks { private static final long FREEZE_TASK_LIST_TIMEOUT_MS = TimeUnit.SECONDS.toMillis(5); // Comparator to sort by taskId - private static final Comparator TASK_ID_COMPARATOR = + private static final Comparator TASK_ID_COMPARATOR = (lhs, rhs) -> rhs.mTaskId - lhs.mTaskId; // Placeholder variables to keep track of activities/apps that are no longer avialble while @@ -135,12 +135,12 @@ class RecentTasks { /** * Called when a task is added to the recent tasks list. */ - void onRecentTaskAdded(TaskRecord task); + void onRecentTaskAdded(Task task); /** * Called when a task is removed from the recent tasks list. */ - void onRecentTaskRemoved(TaskRecord task, boolean wasTrimmed, boolean killProcess); + void onRecentTaskRemoved(Task task, boolean wasTrimmed, boolean killProcess); } /** @@ -171,7 +171,7 @@ class RecentTasks { DEFAULT_INITIAL_CAPACITY); // List of all active recent tasks - private final ArrayList mTasks = new ArrayList<>(); + private final ArrayList mTasks = new ArrayList<>(); private final ArrayList mCallbacks = new ArrayList<>(); // These values are generally loaded from resources, but can be set dynamically in the tests @@ -188,7 +188,7 @@ class RecentTasks { private long mFreezeTaskListTimeoutMs = FREEZE_TASK_LIST_TIMEOUT_MS; // Mainly to avoid object recreation on multiple calls. - private final ArrayList mTmpRecents = new ArrayList<>(); + private final ArrayList mTmpRecents = new ArrayList<>(); private final HashMap mTmpAvailActCache = new HashMap<>(); private final HashMap mTmpAvailAppCache = new HashMap<>(); private final SparseBooleanArray mTmpQuietProfileUserIds = new SparseBooleanArray(); @@ -211,7 +211,7 @@ class RecentTasks { final DisplayContent dc = rac.getActivityDisplay(displayId).mDisplayContent; if (dc.pointWithinAppWindow(x, y)) { final ActivityStack stack = mService.getTopDisplayFocusedStack(); - final TaskRecord topTask = stack != null ? stack.topTask() : null; + final Task topTask = stack != null ? stack.topTask() : null; resetFreezeTaskListReordering(topTask); } } @@ -288,7 +288,7 @@ class RecentTasks { * Commits the frozen recent task list order, moving the provided {@param topTask} to the * front of the list. */ - void resetFreezeTaskListReordering(TaskRecord topTask) { + void resetFreezeTaskListReordering(Task topTask) { if (!mFreezeTaskListReordering) { return; } @@ -319,9 +319,7 @@ class RecentTasks { void resetFreezeTaskListReorderingOnTimeout() { synchronized (mService.mGlobalLock) { final ActivityStack focusedStack = mService.getTopDisplayFocusedStack(); - final TaskRecord topTask = focusedStack != null - ? focusedStack.topTask() - : null; + final Task topTask = focusedStack != null ? focusedStack.topTask() : null; resetFreezeTaskListReordering(topTask); } } @@ -432,14 +430,14 @@ class RecentTasks { mCallbacks.remove(callback); } - private void notifyTaskAdded(TaskRecord task) { + private void notifyTaskAdded(Task task) { for (int i = 0; i < mCallbacks.size(); i++) { mCallbacks.get(i).onRecentTaskAdded(task); } mTaskNotificationController.notifyTaskListUpdated(); } - private void notifyTaskRemoved(TaskRecord task, boolean wasTrimmed, boolean killProcess) { + private void notifyTaskRemoved(Task task, boolean wasTrimmed, boolean killProcess) { for (int i = 0; i < mCallbacks.size(); i++) { mCallbacks.get(i).onRecentTaskRemoved(task, wasTrimmed, killProcess); } @@ -463,14 +461,14 @@ class RecentTasks { // Check if any tasks are added before recents is loaded final SparseBooleanArray preaddedTasks = new SparseBooleanArray(); - for (final TaskRecord task : mTasks) { + for (final Task task : mTasks) { if (task.mUserId == userId && shouldPersistTaskLocked(task)) { preaddedTasks.put(task.mTaskId, true); } } Slog.i(TAG, "Loading recents for user " + userId + " into memory."); - List tasks = mTaskPersister.restoreTasksForUserLocked(userId, preaddedTasks); + List tasks = mTaskPersister.restoreTasksForUserLocked(userId, preaddedTasks); mTasks.addAll(tasks); cleanupLocked(userId); mUsersWithRecentsLoaded.put(userId, true); @@ -509,7 +507,7 @@ class RecentTasks { /** * Kicks off the task persister to write any pending tasks to disk. */ - void notifyTaskPersisterLocked(TaskRecord task, boolean flush) { + void notifyTaskPersisterLocked(Task task, boolean flush) { final ActivityStack stack = task != null ? task.getStack() : null; if (stack != null && stack.isHomeOrRecentsStack()) { // Never persist the home or recents stack. @@ -529,7 +527,7 @@ class RecentTasks { } } for (int i = mTasks.size() - 1; i >= 0; i--) { - final TaskRecord task = mTasks.get(i); + final Task task = mTasks.get(i); if (shouldPersistTaskLocked(task)) { // Set of persisted taskIds for task.userId should not be null here // TODO Investigate why it can happen. For now initialize with an empty set @@ -543,7 +541,7 @@ class RecentTasks { } } - private static boolean shouldPersistTaskLocked(TaskRecord task) { + private static boolean shouldPersistTaskLocked(Task task) { final ActivityStack stack = task.getStack(); return task.isPersistable && (stack == null || !stack.isHomeOrRecentsStack()); } @@ -613,11 +611,11 @@ class RecentTasks { } for (int i = mTasks.size() - 1; i >= 0; --i) { - TaskRecord tr = mTasks.get(i); - if (tr.mUserId == userId) { + Task task = mTasks.get(i); + if (task.mUserId == userId) { if(DEBUG_TASKS) Slog.i(TAG_TASKS, - "remove RecentTask " + tr + " when finishing user" + userId); - remove(tr); + "remove RecentTask " + task + " when finishing user" + userId); + remove(task); } } } @@ -625,17 +623,17 @@ class RecentTasks { void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) { final Set packageNames = Sets.newHashSet(packages); for (int i = mTasks.size() - 1; i >= 0; --i) { - final TaskRecord tr = mTasks.get(i); - if (tr.realActivity != null - && packageNames.contains(tr.realActivity.getPackageName()) - && tr.mUserId == userId - && tr.realActivitySuspended != suspended) { - tr.realActivitySuspended = suspended; + final Task task = mTasks.get(i); + if (task.realActivity != null + && packageNames.contains(task.realActivity.getPackageName()) + && task.mUserId == userId + && task.realActivitySuspended != suspended) { + task.realActivitySuspended = suspended; if (suspended) { - mSupervisor.removeTaskByIdLocked(tr.mTaskId, false, + mSupervisor.removeTaskByIdLocked(task.mTaskId, false, REMOVE_FROM_RECENTS, "suspended-package"); } - notifyTaskPersisterLocked(tr, false); + notifyTaskPersisterLocked(task, false); } } } @@ -645,22 +643,22 @@ class RecentTasks { return; } for (int i = mTasks.size() - 1; i >= 0; --i) { - final TaskRecord tr = mTasks.get(i); - if (tr.mUserId == userId && !mService.getLockTaskController().isTaskWhitelisted(tr)) { - remove(tr); + final Task task = mTasks.get(i); + if (task.mUserId == userId && !mService.getLockTaskController().isTaskWhitelisted(task)) { + remove(task); } } } void removeTasksByPackageName(String packageName, int userId) { for (int i = mTasks.size() - 1; i >= 0; --i) { - final TaskRecord tr = mTasks.get(i); + final Task task = mTasks.get(i); final String taskPackageName = - tr.getBaseIntent().getComponent().getPackageName(); - if (tr.mUserId != userId) continue; + task.getBaseIntent().getComponent().getPackageName(); + if (task.mUserId != userId) continue; if (!taskPackageName.equals(packageName)) continue; - mSupervisor.removeTaskByIdLocked(tr.mTaskId, true, REMOVE_FROM_RECENTS, + mSupervisor.removeTaskByIdLocked(task.mTaskId, true, REMOVE_FROM_RECENTS, "remove-package-task"); } } @@ -668,11 +666,11 @@ class RecentTasks { void removeAllVisibleTasks(int userId) { Set profileIds = getProfileIds(userId); for (int i = mTasks.size() - 1; i >= 0; --i) { - final TaskRecord tr = mTasks.get(i); - if (!profileIds.contains(tr.mUserId)) continue; - if (isVisibleRecentTask(tr)) { + final Task task = mTasks.get(i); + if (!profileIds.contains(task.mUserId)) continue; + if (isVisibleRecentTask(task)) { mTasks.remove(i); - notifyTaskRemoved(tr, true /* wasTrimmed */, true /* killProcess */); + notifyTaskRemoved(task, true /* wasTrimmed */, true /* killProcess */); } } } @@ -680,16 +678,16 @@ class RecentTasks { void cleanupDisabledPackageTasksLocked(String packageName, Set filterByClasses, int userId) { for (int i = mTasks.size() - 1; i >= 0; --i) { - final TaskRecord tr = mTasks.get(i); - if (userId != UserHandle.USER_ALL && tr.mUserId != userId) { + final Task task = mTasks.get(i); + if (userId != UserHandle.USER_ALL && task.mUserId != userId) { continue; } - ComponentName cn = tr.intent != null ? tr.intent.getComponent() : null; + ComponentName cn = task.intent != null ? task.intent.getComponent() : null; final boolean sameComponent = cn != null && cn.getPackageName().equals(packageName) && (filterByClasses == null || filterByClasses.contains(cn.getClassName())); if (sameComponent) { - mSupervisor.removeTaskByIdLocked(tr.mTaskId, false, + mSupervisor.removeTaskByIdLocked(task.mTaskId, false, REMOVE_FROM_RECENTS, "disabled-package"); } } @@ -714,7 +712,7 @@ class RecentTasks { final IPackageManager pm = AppGlobals.getPackageManager(); for (int i = recentsCount - 1; i >= 0; i--) { - final TaskRecord task = mTasks.get(i); + final Task task = mTasks.get(i); if (userId != UserHandle.USER_ALL && task.mUserId != userId) { // Only look at tasks for the user ID of interest. continue; @@ -810,7 +808,7 @@ class RecentTasks { * @return whether the given {@param task} can be added to the list without causing another * task to be trimmed as a result of that add. */ - private boolean canAddTaskWithoutTrim(TaskRecord task) { + private boolean canAddTaskWithoutTrim(Task task) { return findRemoveIndexForAddTask(task) == -1; } @@ -821,18 +819,18 @@ class RecentTasks { final ArrayList list = new ArrayList<>(); final int size = mTasks.size(); for (int i = 0; i < size; i++) { - final TaskRecord tr = mTasks.get(i); + final Task task = mTasks.get(i); // Skip tasks that do not match the caller. We don't need to verify // callingPackage, because we are also limiting to callingUid and know // that will limit to the correct security sandbox. - if (tr.effectiveUid != callingUid) { + if (task.effectiveUid != callingUid) { continue; } - Intent intent = tr.getBaseIntent(); + Intent intent = task.getBaseIntent(); if (intent == null || !callingPackage.equals(intent.getComponent().getPackageName())) { continue; } - AppTaskImpl taskImpl = new AppTaskImpl(mService, tr.mTaskId, callingUid); + AppTaskImpl taskImpl = new AppTaskImpl(mService, task.mTaskId, callingUid); list.add(taskImpl.asBinder()); } return list; @@ -893,11 +891,11 @@ class RecentTasks { final int size = mTasks.size(); int numVisibleTasks = 0; for (int i = 0; i < size; i++) { - final TaskRecord tr = mTasks.get(i); + final Task task = mTasks.get(i); - if (isVisibleRecentTask(tr)) { + if (isVisibleRecentTask(task)) { numVisibleTasks++; - if (isInVisibleRange(tr, i, numVisibleTasks, withExcluded)) { + if (isInVisibleRange(task, i, numVisibleTasks, withExcluded)) { // Fall through } else { // Not in visible range @@ -914,48 +912,48 @@ class RecentTasks { } // Only add calling user or related users recent tasks - if (!includedUsers.contains(Integer.valueOf(tr.mUserId))) { - if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "Skipping, not user: " + tr); + if (!includedUsers.contains(Integer.valueOf(task.mUserId))) { + if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "Skipping, not user: " + task); continue; } - if (tr.realActivitySuspended) { - if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "Skipping, activity suspended: " + tr); + if (task.realActivitySuspended) { + if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "Skipping, activity suspended: " + task); continue; } if (!getTasksAllowed) { // If the caller doesn't have the GET_TASKS permission, then only // allow them to see a small subset of tasks -- their own and home. - if (!tr.isActivityTypeHome() && tr.effectiveUid != callingUid) { - if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "Skipping, not allowed: " + tr); + if (!task.isActivityTypeHome() && task.effectiveUid != callingUid) { + if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "Skipping, not allowed: " + task); continue; } } - if (tr.autoRemoveRecents && tr.getTopActivity() == null) { + if (task.autoRemoveRecents && task.getTopActivity() == null) { // Don't include auto remove tasks that are finished or finishing. if (DEBUG_RECENTS) { - Slog.d(TAG_RECENTS, "Skipping, auto-remove without activity: " + tr); + Slog.d(TAG_RECENTS, "Skipping, auto-remove without activity: " + task); } continue; } - if ((flags & RECENT_IGNORE_UNAVAILABLE) != 0 && !tr.isAvailable) { + if ((flags & RECENT_IGNORE_UNAVAILABLE) != 0 && !task.isAvailable) { if (DEBUG_RECENTS) { - Slog.d(TAG_RECENTS, "Skipping, unavail real act: " + tr); + Slog.d(TAG_RECENTS, "Skipping, unavail real act: " + task); } continue; } - if (!tr.mUserSetupComplete) { + if (!task.mUserSetupComplete) { // Don't include task launched while user is not done setting-up. if (DEBUG_RECENTS) { - Slog.d(TAG_RECENTS, "Skipping, user setup not complete: " + tr); + Slog.d(TAG_RECENTS, "Skipping, user setup not complete: " + task); } continue; } - final ActivityManager.RecentTaskInfo rti = createRecentTaskInfo(tr); + final ActivityManager.RecentTaskInfo rti = createRecentTaskInfo(task); if (!getDetailedTasks) { rti.baseIntent.replaceExtras((Bundle) null); } @@ -971,7 +969,7 @@ class RecentTasks { void getPersistableTaskIds(ArraySet persistentTaskIds) { final int size = mTasks.size(); for (int i = 0; i < size; i++) { - final TaskRecord task = mTasks.get(i); + final Task task = mTasks.get(i); if (TaskPersister.DEBUG) Slog.d(TAG, "LazyTaskWriter: task=" + task + " persistable=" + task.isPersistable); final ActivityStack stack = task.getStack(); @@ -987,7 +985,7 @@ class RecentTasks { } @VisibleForTesting - ArrayList getRawTasks() { + ArrayList getRawTasks() { return mTasks; } @@ -999,11 +997,11 @@ class RecentTasks { final int size = mTasks.size(); int numVisibleTasks = 0; for (int i = 0; i < size; i++) { - final TaskRecord tr = mTasks.get(i); - if (isVisibleRecentTask(tr)) { + final Task task = mTasks.get(i); + if (isVisibleRecentTask(task)) { numVisibleTasks++; - if (isInVisibleRange(tr, i, numVisibleTasks, false /* skipExcludedCheck */)) { - res.put(tr.mTaskId, true); + if (isInVisibleRange(task, i, numVisibleTasks, false /* skipExcludedCheck */)) { + res.put(task.mTaskId, true); } } } @@ -1013,12 +1011,12 @@ class RecentTasks { /** * @return the task in the task list with the given {@param id} if one exists. */ - TaskRecord getTask(int id) { + Task getTask(int id) { final int recentsCount = mTasks.size(); for (int i = 0; i < recentsCount; i++) { - TaskRecord tr = mTasks.get(i); - if (tr.mTaskId == id) { - return tr; + Task task = mTasks.get(i); + if (task.mTaskId == id) { + return task; } } return null; @@ -1027,7 +1025,7 @@ class RecentTasks { /** * Add a new task to the recent tasks list. */ - void add(TaskRecord task) { + void add(Task task) { if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG, "add: task=" + task); final boolean isAffiliated = task.mAffiliatedTaskId != task.mTaskId @@ -1098,7 +1096,7 @@ class RecentTasks { } else if (isAffiliated) { // If this is a new affiliated task, then move all of the affiliated tasks // to the front and insert this new one. - TaskRecord other = task.mNextAffiliate; + Task other = task.mNextAffiliate; if (other == null) { other = task.mPrevAffiliate; } @@ -1154,7 +1152,7 @@ class RecentTasks { /** * Add the task to the bottom if possible. */ - boolean addToBottom(TaskRecord task) { + boolean addToBottom(Task task) { if (!canAddTaskWithoutTrim(task)) { // Adding this task would cause the task to be removed (since it's appended at // the bottom and would be trimmed) so just return now @@ -1168,7 +1166,7 @@ class RecentTasks { /** * Remove a task from the recent tasks list. */ - void remove(TaskRecord task) { + void remove(Task task) { mTasks.remove(task); notifyTaskRemoved(task, false /* wasTrimmed */, false /* killProcess */); } @@ -1186,10 +1184,10 @@ class RecentTasks { // Remove from the end of the list until we reach the max number of recents while (recentsCount > mGlobalMaxNumTasks) { - final TaskRecord tr = mTasks.remove(recentsCount - 1); - notifyTaskRemoved(tr, true /* wasTrimmed */, false /* killProcess */); + final Task task = mTasks.remove(recentsCount - 1); + notifyTaskRemoved(task, true /* wasTrimmed */, false /* killProcess */); recentsCount--; - if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG, "Trimming over max-recents task=" + tr + if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG, "Trimming over max-recents task=" + task + " max=" + mGlobalMaxNumTasks); } @@ -1208,7 +1206,7 @@ class RecentTasks { // Remove any inactive tasks, calculate the latest set of visible tasks. int numVisibleTasks = 0; for (int i = 0; i < mTasks.size();) { - final TaskRecord task = mTasks.get(i); + final Task task = mTasks.get(i); if (isActiveRecentTask(task, mTmpQuietProfileUserIds)) { if (!mHasVisibleRecentTasks) { @@ -1250,7 +1248,7 @@ class RecentTasks { /** * @return whether the given task should be considered active. */ - private boolean isActiveRecentTask(TaskRecord task, SparseBooleanArray quietProfileUserIds) { + private boolean isActiveRecentTask(Task task, SparseBooleanArray quietProfileUserIds) { if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG, "isActiveRecentTask: task=" + task + " globalMax=" + mGlobalMaxNumTasks); @@ -1262,7 +1260,7 @@ class RecentTasks { if (task.mAffiliatedTaskId != INVALID_TASK_ID && task.mAffiliatedTaskId != task.mTaskId) { // Keep the task active if its affiliated task is also active - final TaskRecord affiliatedTask = getTask(task.mAffiliatedTaskId); + final Task affiliatedTask = getTask(task.mAffiliatedTaskId); if (affiliatedTask != null) { if (!isActiveRecentTask(affiliatedTask, quietProfileUserIds)) { if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG, @@ -1280,7 +1278,7 @@ class RecentTasks { * @return whether the given active task should be presented to the user through SystemUI. */ @VisibleForTesting - boolean isVisibleRecentTask(TaskRecord task) { + boolean isVisibleRecentTask(Task task) { if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG, "isVisibleRecentTask: task=" + task + " minVis=" + mMinNumVisibleTasks + " maxVis=" + mMaxNumVisibleTasks + " sessionDuration=" + mActiveTasksSessionDurationMs @@ -1338,7 +1336,7 @@ class RecentTasks { /** * @return whether the given visible task is within the policy range. */ - private boolean isInVisibleRange(TaskRecord task, int taskIndex, int numVisibleTasks, + private boolean isInVisibleRange(Task task, int taskIndex, int numVisibleTasks, boolean skipExcludedCheck) { if (!skipExcludedCheck) { // Keep the most recent task even if it is excluded from recents @@ -1376,7 +1374,7 @@ class RecentTasks { /** * @return whether the given task can be trimmed even if it is outside the visible range. */ - protected boolean isTrimmable(TaskRecord task) { + protected boolean isTrimmable(Task task) { final ActivityStack stack = task.getStack(); // No stack for task, just trim it @@ -1399,7 +1397,7 @@ class RecentTasks { * If needed, remove oldest existing entries in recents that are for the same kind * of task as the given one. */ - private void removeForAddTask(TaskRecord task) { + private void removeForAddTask(Task task) { final int removeIndex = findRemoveIndexForAddTask(task); if (removeIndex == -1) { // Nothing to trim @@ -1409,7 +1407,7 @@ class RecentTasks { // There is a similar task that will be removed for the addition of {@param task}, but it // can be the same task, and if so, the task will be re-added in add(), so skip the // callbacks here. - final TaskRecord removedTask = mTasks.remove(removeIndex); + final Task removedTask = mTasks.remove(removeIndex); if (removedTask != task) { notifyTaskRemoved(removedTask, false /* wasTrimmed */, false /* killProcess */); if (DEBUG_RECENTS_TRIM_TASKS) Slog.d(TAG, "Trimming task=" + removedTask @@ -1422,7 +1420,7 @@ class RecentTasks { * Find the task that would be removed if the given {@param task} is added to the recent tasks * list (if any). */ - private int findRemoveIndexForAddTask(TaskRecord task) { + private int findRemoveIndexForAddTask(Task task) { if (mFreezeTaskListReordering) { // Defer removing tasks due to the addition of new tasks until the task list is unfrozen return -1; @@ -1433,15 +1431,15 @@ class RecentTasks { final boolean document = intent != null && intent.isDocument(); int maxRecents = task.maxRecents - 1; for (int i = 0; i < recentsCount; i++) { - final TaskRecord tr = mTasks.get(i); - if (task != tr) { - if (!hasCompatibleActivityTypeAndWindowingMode(task, tr) - || task.mUserId != tr.mUserId) { + final Task t = mTasks.get(i); + if (task != t) { + if (!hasCompatibleActivityTypeAndWindowingMode(task, t) + || task.mUserId != t.mUserId) { continue; } - final Intent trIntent = tr.intent; + final Intent trIntent = t.intent; final boolean sameAffinity = - task.affinity != null && task.affinity.equals(tr.affinity); + task.affinity != null && task.affinity.equals(t.affinity); final boolean sameIntent = intent != null && intent.filterEquals(trIntent); boolean multiTasksAllowed = false; final int flags = intent.getFlags(); @@ -1458,8 +1456,8 @@ class RecentTasks { if (bothDocuments) { // Do these documents belong to the same activity? final boolean sameActivity = task.realActivity != null - && tr.realActivity != null - && task.realActivity.equals(tr.realActivity); + && t.realActivity != null + && task.realActivity.equals(t.realActivity); if (!sameActivity) { // If the document is open in another app or is not the same document, we // don't need to trim it. @@ -1487,7 +1485,7 @@ class RecentTasks { // Extract the affiliates of the chain containing recent at index start. private int processNextAffiliateChainLocked(int start) { - final TaskRecord startTask = mTasks.get(start); + final Task startTask = mTasks.get(start); final int affiliateId = startTask.mAffiliatedTaskId; // Quick identification of isolated tasks. I.e. those not launched behind. @@ -1503,7 +1501,7 @@ class RecentTasks { // Remove all tasks that are affiliated to affiliateId and put them in mTmpRecents. mTmpRecents.clear(); for (int i = mTasks.size() - 1; i >= start; --i) { - final TaskRecord task = mTasks.get(i); + final Task task = mTasks.get(i); if (task.mAffiliatedTaskId == affiliateId) { mTasks.remove(i); mTmpRecents.add(task); @@ -1516,7 +1514,7 @@ class RecentTasks { // Go through and fix up the linked list. // The first one is the end of the chain and has no next. - final TaskRecord first = mTmpRecents.get(0); + final Task first = mTmpRecents.get(0); first.inRecents = true; if (first.mNextAffiliate != null) { Slog.w(TAG, "Link error 1 first.next=" + first.mNextAffiliate); @@ -1526,8 +1524,8 @@ class RecentTasks { // Everything in the middle is doubly linked from next to prev. final int tmpSize = mTmpRecents.size(); for (int i = 0; i < tmpSize - 1; ++i) { - final TaskRecord next = mTmpRecents.get(i); - final TaskRecord prev = mTmpRecents.get(i + 1); + final Task next = mTmpRecents.get(i); + final Task prev = mTmpRecents.get(i + 1); if (next.mPrevAffiliate != prev) { Slog.w(TAG, "Link error 2 next=" + next + " prev=" + next.mPrevAffiliate + " setting prev=" + prev); @@ -1543,7 +1541,7 @@ class RecentTasks { prev.inRecents = true; } // The last one is the beginning of the list and has no prev. - final TaskRecord last = mTmpRecents.get(tmpSize - 1); + final Task last = mTmpRecents.get(tmpSize - 1); if (last.mPrevAffiliate != null) { Slog.w(TAG, "Link error 4 last.prev=" + last.mPrevAffiliate); last.setPrevAffiliate(null); @@ -1558,9 +1556,9 @@ class RecentTasks { return start + tmpSize; } - private boolean moveAffiliatedTasksToFront(TaskRecord task, int taskIndex) { + private boolean moveAffiliatedTasksToFront(Task task, int taskIndex) { int recentsCount = mTasks.size(); - TaskRecord top = task; + Task top = task; int topIndex = taskIndex; while (top.mNextAffiliate != null && topIndex > 0) { top = top.mNextAffiliate; @@ -1571,9 +1569,9 @@ class RecentTasks { // Find the end of the chain, doing a sanity check along the way. boolean sane = top.mAffiliatedTaskId == task.mAffiliatedTaskId; int endIndex = topIndex; - TaskRecord prev = top; + Task prev = top; while (endIndex < recentsCount) { - TaskRecord cur = mTasks.get(endIndex); + Task cur = mTasks.get(endIndex); if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: looking at next chain @" + endIndex + " " + cur); if (cur == top) { @@ -1648,7 +1646,7 @@ class RecentTasks { for (int i=topIndex; i<=endIndex; i++) { if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: moving affiliated " + task + " from " + i + " to " + (i-topIndex)); - TaskRecord cur = mTasks.remove(i); + Task cur = mTasks.remove(i); mTasks.add(i - topIndex, cur); } if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: done moving tasks " + topIndex @@ -1676,9 +1674,9 @@ class RecentTasks { boolean printedHeader = false; final int size = mTasks.size(); for (int i = 0; i < size; i++) { - final TaskRecord tr = mTasks.get(i); - if (dumpPackage != null && (tr.realActivity == null || - !dumpPackage.equals(tr.realActivity.getPackageName()))) { + final Task task = mTasks.get(i); + if (dumpPackage != null && (task.realActivity == null || + !dumpPackage.equals(task.realActivity.getPackageName()))) { continue; } @@ -1688,9 +1686,9 @@ class RecentTasks { printedAnything = true; } pw.print(" * Recent #"); pw.print(i); pw.print(": "); - pw.println(tr); + pw.println(task); if (dumpAll) { - tr.dump(pw, " "); + task.dump(pw, " "); } } @@ -1724,9 +1722,9 @@ class RecentTasks { } /** - * Creates a new RecentTaskInfo from a TaskRecord. + * Creates a new RecentTaskInfo from a Task. */ - ActivityManager.RecentTaskInfo createRecentTaskInfo(TaskRecord tr) { + ActivityManager.RecentTaskInfo createRecentTaskInfo(Task tr) { ActivityManager.RecentTaskInfo rti = new ActivityManager.RecentTaskInfo(); tr.fillTaskInfo(rti); // Fill in some deprecated values @@ -1740,7 +1738,7 @@ class RecentTasks { * compatible. This is necessary because we currently don't persist the activity type * or the windowing mode with the task, so they can be undefined when restored. */ - private boolean hasCompatibleActivityTypeAndWindowingMode(TaskRecord t1, TaskRecord t2) { + private boolean hasCompatibleActivityTypeAndWindowingMode(Task t1, Task t2) { final int activityType = t1.getActivityType(); final int windowingMode = t1.getWindowingMode(); final boolean isUndefinedType = activityType == ACTIVITY_TYPE_UNDEFINED; diff --git a/services/core/java/com/android/server/wm/RecentsAnimation.java b/services/core/java/com/android/server/wm/RecentsAnimation.java index 83804a767d0b8..caf95de753579 100644 --- a/services/core/java/com/android/server/wm/RecentsAnimation.java +++ b/services/core/java/com/android/server/wm/RecentsAnimation.java @@ -211,7 +211,7 @@ class RecentsAnimation implements RecentsAnimationCallbacks, // If there are multiple tasks in the target stack (ie. the home stack, with 3p // and default launchers coexisting), then move the task to the top as a part of // moving the stack to the front - final TaskRecord task = targetActivity.getTaskRecord(); + final Task task = targetActivity.getTask(); if (targetStack.topTask() != task) { targetStack.positionChildAtTop(task); } @@ -328,7 +328,7 @@ class RecentsAnimation implements RecentsAnimationCallbacks, if (sendUserLeaveHint) { // Setting this allows the previous app to PiP. mStackSupervisor.mUserLeaving = true; - targetStack.moveTaskToFrontLocked(targetActivity.getTaskRecord(), + targetStack.moveTaskToFrontLocked(targetActivity.getTask(), true /* noAnimation */, null /* activityOptions */, targetActivity.appTimeTracker, "RecentsAnimation.onAnimationFinished()"); @@ -491,7 +491,7 @@ class RecentsAnimation implements RecentsAnimationCallbacks, } for (int i = targetStack.getChildCount() - 1; i >= 0; i--) { - final TaskRecord task = targetStack.getChildAt(i); + final Task task = targetStack.getChildAt(i); if (task.mUserId == mUserId && task.getBaseIntent().getComponent().equals(mTargetIntent.getComponent())) { return task.getTopActivity(); diff --git a/services/core/java/com/android/server/wm/RootActivityContainer.java b/services/core/java/com/android/server/wm/RootActivityContainer.java index e60cd933d4b8e..cb41372f6960b 100644 --- a/services/core/java/com/android/server/wm/RootActivityContainer.java +++ b/services/core/java/com/android/server/wm/RootActivityContainer.java @@ -62,8 +62,8 @@ import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_TASKS import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM; import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME; import static com.android.server.wm.ActivityTaskManagerService.ANIMATE; -import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE; -import static com.android.server.wm.TaskRecord.REPARENT_MOVE_STACK_TO_FRONT; +import static com.android.server.wm.Task.REPARENT_LEAVE_STACK_IN_PLACE; +import static com.android.server.wm.Task.REPARENT_MOVE_STACK_TO_FRONT; import static java.lang.Integer.MAX_VALUE; @@ -858,7 +858,7 @@ class RootActivityContainer extends ConfigurationContainer for (int stackNdx = display.getChildCount() - 1; stackNdx >= 0; --stackNdx) { final ActivityStack stack = display.getChildAt(stackNdx); stack.switchUser(userId); - TaskRecord task = stack.topTask(); + Task task = stack.topTask(); if (task != null) { stack.positionChildAtTop(task); } @@ -966,7 +966,7 @@ class RootActivityContainer extends ConfigurationContainer final ActivityDisplay display = r.getActivityStack().getDisplay(); try { - final TaskRecord task = r.getTaskRecord(); + final Task task = r.getTask(); final ActivityStack pinnedStack = display.getPinnedStack(); // This will change the pinned stack's windowing mode to its original mode, ensuring @@ -995,7 +995,7 @@ class RootActivityContainer extends ConfigurationContainer // activity into that task, and then reparent the whole task to the new stack. This // ensures that all the necessary work to migrate states in the old and new stacks // is also done. - final TaskRecord newTask = task.getStack().createTaskRecord( + final Task newTask = task.getStack().createTask( mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), r.info, r.intent, null, null, true); r.reparent(newTask, MAX_VALUE, "moveActivityToStack"); @@ -1090,7 +1090,7 @@ class RootActivityContainer extends ConfigurationContainer * @return The task id that was finished in this stack, or INVALID_TASK_ID if none was finished. */ int finishTopCrashedActivities(WindowProcessController app, String reason) { - TaskRecord finishedTask = null; + Task finishedTask = null; ActivityStack focusedStack = getTopDisplayFocusedStack(); for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) { final ActivityDisplay display = mActivityDisplays.get(displayNdx); @@ -1098,7 +1098,7 @@ class RootActivityContainer extends ConfigurationContainer // so we need to be careful with indexes in the loop and check child count every time. for (int stackNdx = 0; stackNdx < display.getChildCount(); ++stackNdx) { final ActivityStack stack = display.getChildAt(stackNdx); - final TaskRecord t = stack.finishTopCrashedActivityLocked(app, reason); + final Task t = stack.finishTopCrashedActivityLocked(app, reason); if (stack == focusedStack || finishedTask == null) { finishedTask = t; } @@ -1253,14 +1253,14 @@ class RootActivityContainer extends ConfigurationContainer info.position = display != null ? display.getIndexOf(stack) : 0; info.configuration.setTo(stack.getConfiguration()); - ArrayList tasks = stack.getAllTasks(); + ArrayList tasks = stack.getAllTasks(); final int numTasks = tasks.size(); int[] taskIds = new int[numTasks]; String[] taskNames = new String[numTasks]; Rect[] taskBounds = new Rect[numTasks]; int[] taskUserIds = new int[numTasks]; for (int i = 0; i < numTasks; ++i) { - final TaskRecord task = tasks.get(i); + final Task task = tasks.get(i); taskIds[i] = task.mTaskId; taskNames[i] = task.origActivity != null ? task.origActivity.flattenToString() : task.realActivity != null ? task.realActivity.flattenToString() @@ -1547,7 +1547,7 @@ class RootActivityContainer extends ConfigurationContainer void releaseSomeActivitiesLocked(WindowProcessController app, String reason) { // Tasks is non-null only if two or more tasks are found. - ArraySet tasks = app.getReleaseSomeActivitiesTasks(); + ArraySet tasks = app.getReleaseSomeActivitiesTasks(); if (tasks == null) { if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Didn't find two or more tasks to release"); return; @@ -1630,7 +1630,7 @@ class RootActivityContainer extends ConfigurationContainer } ActivityStack getLaunchStack(@Nullable ActivityRecord r, - @Nullable ActivityOptions options, @Nullable TaskRecord candidateTask, boolean onTop) { + @Nullable ActivityOptions options, @Nullable Task candidateTask, boolean onTop) { return getLaunchStack(r, options, candidateTask, onTop, null /* launchParams */, -1 /* no realCallingPid */, -1 /* no realCallingUid */); } @@ -1648,7 +1648,7 @@ class RootActivityContainer extends ConfigurationContainer * @return The stack to use for the launch or INVALID_STACK_ID. */ ActivityStack getLaunchStack(@Nullable ActivityRecord r, - @Nullable ActivityOptions options, @Nullable TaskRecord candidateTask, boolean onTop, + @Nullable ActivityOptions options, @Nullable Task candidateTask, boolean onTop, @Nullable LaunchParamsController.LaunchParams launchParams, int realCallingPid, int realCallingUid) { int taskId = INVALID_TASK_ID; @@ -1666,7 +1666,7 @@ class RootActivityContainer extends ConfigurationContainer if (taskId != INVALID_TASK_ID) { // Temporarily set the task id to invalid in case in re-entry. options.setLaunchTaskId(INVALID_TASK_ID); - final TaskRecord task = anyTaskForId(taskId, + final Task task = anyTaskForId(taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE, options, onTop); options.setLaunchTaskId(taskId); if (task != null) { @@ -1765,7 +1765,7 @@ class RootActivityContainer extends ConfigurationContainer * @return Existing stack if there is a valid one, new dynamic stack if it is valid or null. */ private ActivityStack getValidLaunchStackOnDisplay(int displayId, @NonNull ActivityRecord r, - @Nullable TaskRecord candidateTask, @Nullable ActivityOptions options, + @Nullable Task candidateTask, @Nullable ActivityOptions options, @Nullable LaunchParamsController.LaunchParams launchParams) { final ActivityDisplay activityDisplay = getActivityDisplayOrCreate(displayId); if (activityDisplay == null) { @@ -1780,8 +1780,7 @@ class RootActivityContainer extends ConfigurationContainer // If {@code r} is already in target display and its task is the same as the candidate task, // the intention should be getting a launch stack for the reusable activity, so we can use // the existing stack. - if (candidateTask != null - && (r.getTaskRecord() == null || r.getTaskRecord() == candidateTask)) { + if (candidateTask != null && (r.getTask() == null || r.getTask() == candidateTask)) { final int attachedDisplayId = r.getDisplayId(); if (attachedDisplayId == INVALID_DISPLAY || attachedDisplayId == displayId) { return candidateTask.getStack(); @@ -1846,7 +1845,7 @@ class RootActivityContainer extends ConfigurationContainer } int resolveActivityType(@Nullable ActivityRecord r, @Nullable ActivityOptions options, - @Nullable TaskRecord task) { + @Nullable Task task) { // Preference is given to the activity type for the activity then the task since the type // once set shouldn't change. int activityType = r != null ? r.getActivityType() : ACTIVITY_TYPE_UNDEFINED; @@ -2103,9 +2102,9 @@ class RootActivityContainer extends ConfigurationContainer final ActivityDisplay display = mActivityDisplays.get(displayNdx); for (int stackNdx = display.getChildCount() - 1; stackNdx >= 0; --stackNdx) { final ActivityStack stack = display.getChildAt(stackNdx); - final List tasks = stack.getAllTasks(); + final List tasks = stack.getAllTasks(); for (int taskNdx = tasks.size() - 1; taskNdx >= 0; taskNdx--) { - final TaskRecord task = tasks.get(taskNdx); + final Task task = tasks.get(taskNdx); // Check the task for a top activity belonging to userId, or returning a // result to an activity belonging to userId. Example case: a document @@ -2133,7 +2132,7 @@ class RootActivityContainer extends ConfigurationContainer * * @return {@code true} if the top activity looks like it belongs to {@param userId}. */ - private boolean taskTopActivityIsUser(TaskRecord task, @UserIdInt int userId) { + private boolean taskTopActivityIsUser(Task task, @UserIdInt int userId) { // To handle the case that work app is in the task but just is not the top one. final ActivityRecord activityRecord = task.getTopActivity(); final ActivityRecord resultTo = (activityRecord != null ? activityRecord.resultTo : null); @@ -2152,22 +2151,22 @@ class RootActivityContainer extends ConfigurationContainer } } - TaskRecord anyTaskForId(int id) { + Task anyTaskForId(int id) { return anyTaskForId(id, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE); } - TaskRecord anyTaskForId(int id, @AnyTaskForIdMatchTaskMode int matchMode) { + Task anyTaskForId(int id, @AnyTaskForIdMatchTaskMode int matchMode) { return anyTaskForId(id, matchMode, null, !ON_TOP); } /** - * Returns a {@link TaskRecord} for the input id if available. {@code null} otherwise. + * Returns a {@link Task} for the input id if available. {@code null} otherwise. * @param id Id of the task we would like returned. * @param matchMode The mode to match the given task id in. * @param aOptions The activity options to use for restoration. Can be null. * @param onTop If the stack for the task should be the topmost on the display. */ - TaskRecord anyTaskForId(int id, @AnyTaskForIdMatchTaskMode int matchMode, + Task anyTaskForId(int id, @AnyTaskForIdMatchTaskMode int matchMode, @Nullable ActivityOptions aOptions, boolean onTop) { // If options are set, ensure that we are attempting to actually restore a task if (matchMode != MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE && aOptions != null) { @@ -2180,7 +2179,7 @@ class RootActivityContainer extends ConfigurationContainer final ActivityDisplay display = mActivityDisplays.get(displayNdx); for (int stackNdx = display.getChildCount() - 1; stackNdx >= 0; --stackNdx) { final ActivityStack stack = display.getChildAt(stackNdx); - final TaskRecord task = stack.taskForIdLocked(id); + final Task task = stack.taskForIdLocked(id); if (task == null) { continue; } @@ -2208,7 +2207,7 @@ class RootActivityContainer extends ConfigurationContainer // Otherwise, check the recent tasks and return if we find it there and we are not restoring // the task from recents if (DEBUG_RECENTS) Slog.v(TAG_RECENTS, "Looking for task id=" + id + " in recents"); - final TaskRecord task = mStackSupervisor.mRecentTasks.getTask(id); + final Task task = mStackSupervisor.mRecentTasks.getTask(id); if (task == null) { if (DEBUG_RECENTS) { diff --git a/services/core/java/com/android/server/wm/RunningTasks.java b/services/core/java/com/android/server/wm/RunningTasks.java index 81a85476c53a4..f2678bbf0c9fc 100644 --- a/services/core/java/com/android/server/wm/RunningTasks.java +++ b/services/core/java/com/android/server/wm/RunningTasks.java @@ -33,11 +33,11 @@ import java.util.TreeSet; class RunningTasks { // Comparator to sort by last active time (descending) - private static final Comparator LAST_ACTIVE_TIME_COMPARATOR = + private static final Comparator LAST_ACTIVE_TIME_COMPARATOR = (o1, o2) -> Long.signum(o2.lastActiveTime - o1.lastActiveTime); - private final TreeSet mTmpSortedSet = new TreeSet<>(LAST_ACTIVE_TIME_COMPARATOR); - private final ArrayList mTmpStackTasks = new ArrayList<>(); + private final TreeSet mTmpSortedSet = new TreeSet<>(LAST_ACTIVE_TIME_COMPARATOR); + private final ArrayList mTmpStackTasks = new ArrayList<>(); void getTasks(int maxNum, List list, @ActivityType int ignoreActivityType, @WindowingMode int ignoreWindowingMode, ArrayList activityDisplays, @@ -62,13 +62,13 @@ class RunningTasks { } // Take the first {@param maxNum} tasks and create running task infos for them - final Iterator iter = mTmpSortedSet.iterator(); + final Iterator iter = mTmpSortedSet.iterator(); while (iter.hasNext()) { if (maxNum == 0) { break; } - final TaskRecord task = iter.next(); + final Task task = iter.next(); list.add(createRunningTaskInfo(task)); maxNum--; } @@ -77,7 +77,7 @@ class RunningTasks { /** * Constructs a {@link RunningTaskInfo} from a given {@param task}. */ - private RunningTaskInfo createRunningTaskInfo(TaskRecord task) { + private RunningTaskInfo createRunningTaskInfo(Task task) { final RunningTaskInfo rti = new RunningTaskInfo(); task.fillTaskInfo(rti); // Fill in some deprecated values diff --git a/services/core/java/com/android/server/wm/Task.java b/services/core/java/com/android/server/wm/Task.java index 7de845607a9ea..4038548e8b74a 100644 --- a/services/core/java/com/android/server/wm/Task.java +++ b/services/core/java/com/android/server/wm/Task.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 The Android Open Source Project + * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,17 +17,77 @@ package com.android.server.wm; import static android.app.ActivityTaskManager.INVALID_STACK_ID; +import static android.app.ActivityTaskManager.INVALID_TASK_ID; +import static android.app.ActivityTaskManager.RESIZE_MODE_FORCED; +import static android.app.ActivityTaskManager.RESIZE_MODE_SYSTEM; import static android.app.ActivityTaskManager.RESIZE_MODE_SYSTEM_SCREEN_ROTATION; +import static android.app.WindowConfiguration.ACTIVITY_TYPE_STANDARD; +import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED; +import static android.app.WindowConfiguration.ROTATION_UNDEFINED; +import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM; +import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN; +import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED; +import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY; +import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY; +import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED; +import static android.content.Intent.FLAG_ACTIVITY_NEW_DOCUMENT; +import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK; +import static android.content.Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS; +import static android.content.Intent.FLAG_ACTIVITY_TASK_ON_HOME; +import static android.content.pm.ActivityInfo.FLAG_RELINQUISH_TASK_IDENTITY; +import static android.content.pm.ActivityInfo.LOCK_TASK_LAUNCH_MODE_ALWAYS; +import static android.content.pm.ActivityInfo.LOCK_TASK_LAUNCH_MODE_DEFAULT; +import static android.content.pm.ActivityInfo.LOCK_TASK_LAUNCH_MODE_IF_WHITELISTED; +import static android.content.pm.ActivityInfo.LOCK_TASK_LAUNCH_MODE_NEVER; import static android.content.pm.ActivityInfo.RESIZE_MODE_FORCE_RESIZABLE_LANDSCAPE_ONLY; import static android.content.pm.ActivityInfo.RESIZE_MODE_FORCE_RESIZABLE_PORTRAIT_ONLY; import static android.content.pm.ActivityInfo.RESIZE_MODE_FORCE_RESIZABLE_PRESERVE_ORIENTATION; +import static android.content.pm.ActivityInfo.RESIZE_MODE_FORCE_RESIZEABLE; +import static android.content.pm.ActivityInfo.RESIZE_MODE_RESIZEABLE; +import static android.content.pm.ActivityInfo.RESIZE_MODE_RESIZEABLE_AND_PIPABLE_DEPRECATED; +import static android.content.pm.ActivityInfo.RESIZE_MODE_RESIZEABLE_VIA_SDK_VERSION; import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_UNSET; import static android.content.res.Configuration.EMPTY; +import static android.content.res.Configuration.ORIENTATION_LANDSCAPE; +import static android.content.res.Configuration.ORIENTATION_PORTRAIT; +import static android.content.res.Configuration.ORIENTATION_UNDEFINED; +import static android.os.Trace.TRACE_TAG_WINDOW_MANAGER; +import static android.provider.Settings.Secure.USER_SETUP_COMPLETE; +import static android.view.Display.DEFAULT_DISPLAY; import static android.view.SurfaceControl.METADATA_TASK_ID; import static com.android.server.EventLogTags.WM_TASK_CREATED; import static com.android.server.EventLogTags.WM_TASK_REMOVED; +import static com.android.server.am.TaskRecordProto.ACTIVITIES; +import static com.android.server.am.TaskRecordProto.ACTIVITY_TYPE; +import static com.android.server.am.TaskRecordProto.BOUNDS; +import static com.android.server.am.TaskRecordProto.FULLSCREEN; +import static com.android.server.am.TaskRecordProto.ID; +import static com.android.server.am.TaskRecordProto.LAST_NON_FULLSCREEN_BOUNDS; +import static com.android.server.am.TaskRecordProto.MIN_HEIGHT; +import static com.android.server.am.TaskRecordProto.MIN_WIDTH; +import static com.android.server.am.TaskRecordProto.ORIG_ACTIVITY; +import static com.android.server.am.TaskRecordProto.REAL_ACTIVITY; +import static com.android.server.am.TaskRecordProto.RESIZE_MODE; +import static com.android.server.am.TaskRecordProto.STACK_ID; +import static com.android.server.am.TaskRecordProto.TASK; +import static com.android.server.wm.ActivityRecord.FINISH_RESULT_REMOVED; +import static com.android.server.wm.ActivityRecord.STARTING_WINDOW_SHOWN; +import static com.android.server.wm.ActivityStackSupervisor.ON_TOP; +import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS; +import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS; +import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ADD_REMOVE; +import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK; +import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_RECENTS; +import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS; +import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_ADD_REMOVE; +import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK; +import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_RECENTS; +import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_TASKS; +import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM; +import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME; import static com.android.server.wm.DragResizeMode.DRAG_RESIZE_MODE_DOCKED_DIVIDER; +import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_ADD_REMOVE; import static com.android.server.wm.TaskProto.APP_WINDOW_TOKENS; import static com.android.server.wm.TaskProto.BOUNDS; import static com.android.server.wm.TaskProto.DISPLAYED_BOUNDS; @@ -39,32 +99,240 @@ import static com.android.server.wm.TaskProto.WINDOW_CONTAINER; import static com.android.server.wm.WindowContainer.AnimationFlags.CHILDREN; import static com.android.server.wm.WindowContainer.AnimationFlags.TRANSITION; import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_STACK; -import static com.android.server.wm.WindowManagerDebugConfig.TAG_WITH_CLASS_NAME; import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM; -import android.annotation.CallSuper; +import static java.lang.Integer.MAX_VALUE; + +import android.annotation.IntDef; +import android.annotation.NonNull; +import android.annotation.Nullable; +import android.app.Activity; import android.app.ActivityManager; import android.app.ActivityManager.TaskDescription; +import android.app.ActivityManager.TaskSnapshot; +import android.app.ActivityOptions; +import android.app.ActivityTaskManager; +import android.app.AppGlobals; +import android.app.TaskInfo; +import android.app.WindowConfiguration; +import android.content.ComponentName; +import android.content.Intent; import android.content.pm.ActivityInfo; +import android.content.pm.ApplicationInfo; +import android.content.pm.IPackageManager; +import android.content.pm.PackageManager; import android.content.res.Configuration; import android.graphics.Rect; +import android.os.Debug; import android.os.IBinder; +import android.os.RemoteException; +import android.os.SystemClock; +import android.os.Trace; +import android.os.UserHandle; +import android.provider.Settings; +import android.service.voice.IVoiceInteractionSession; +import android.util.DisplayMetrics; import android.util.EventLog; import android.util.Slog; import android.util.proto.ProtoOutputStream; import android.view.Display; +import android.view.DisplayInfo; import android.view.RemoteAnimationTarget; import android.view.Surface; import android.view.SurfaceControl; import com.android.internal.annotations.VisibleForTesting; +import com.android.internal.app.IVoiceInteractor; import com.android.internal.util.ToBooleanFunction; +import com.android.internal.util.XmlUtils; +import com.android.server.protolog.common.ProtoLog; +import com.android.server.wm.ActivityStack.ActivityState; +import org.xmlpull.v1.XmlPullParser; +import org.xmlpull.v1.XmlPullParserException; +import org.xmlpull.v1.XmlSerializer; + +import java.io.IOException; import java.io.PrintWriter; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.util.ArrayList; +import java.util.Objects; import java.util.function.Consumer; -class Task extends WindowContainer implements ConfigurationContainerListener{ - static final String TAG = TAG_WITH_CLASS_NAME ? "Task" : TAG_WM; +class Task extends WindowContainer implements ConfigurationContainerListener { + private static final String TAG = TAG_WITH_CLASS_NAME ? "Task" : TAG_ATM; + private static final String TAG_ADD_REMOVE = TAG + POSTFIX_ADD_REMOVE; + private static final String TAG_RECENTS = TAG + POSTFIX_RECENTS; + private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK; + private static final String TAG_TASKS = TAG + POSTFIX_TASKS; + + private static final String ATTR_TASKID = "task_id"; + private static final String TAG_INTENT = "intent"; + private static final String TAG_AFFINITYINTENT = "affinity_intent"; + private static final String ATTR_REALACTIVITY = "real_activity"; + private static final String ATTR_REALACTIVITY_SUSPENDED = "real_activity_suspended"; + private static final String ATTR_ORIGACTIVITY = "orig_activity"; + private static final String TAG_ACTIVITY = "activity"; + private static final String ATTR_AFFINITY = "affinity"; + private static final String ATTR_ROOT_AFFINITY = "root_affinity"; + private static final String ATTR_ROOTHASRESET = "root_has_reset"; + private static final String ATTR_AUTOREMOVERECENTS = "auto_remove_recents"; + private static final String ATTR_ASKEDCOMPATMODE = "asked_compat_mode"; + private static final String ATTR_USERID = "user_id"; + private static final String ATTR_USER_SETUP_COMPLETE = "user_setup_complete"; + private static final String ATTR_EFFECTIVE_UID = "effective_uid"; + @Deprecated + private static final String ATTR_TASKTYPE = "task_type"; + private static final String ATTR_LASTDESCRIPTION = "last_description"; + private static final String ATTR_LASTTIMEMOVED = "last_time_moved"; + private static final String ATTR_NEVERRELINQUISH = "never_relinquish_identity"; + private static final String ATTR_TASK_AFFILIATION = "task_affiliation"; + private static final String ATTR_PREV_AFFILIATION = "prev_affiliation"; + private static final String ATTR_NEXT_AFFILIATION = "next_affiliation"; + private static final String ATTR_TASK_AFFILIATION_COLOR = "task_affiliation_color"; + private static final String ATTR_CALLING_UID = "calling_uid"; + private static final String ATTR_CALLING_PACKAGE = "calling_package"; + private static final String ATTR_SUPPORTS_PICTURE_IN_PICTURE = "supports_picture_in_picture"; + private static final String ATTR_RESIZE_MODE = "resize_mode"; + private static final String ATTR_NON_FULLSCREEN_BOUNDS = "non_fullscreen_bounds"; + private static final String ATTR_MIN_WIDTH = "min_width"; + private static final String ATTR_MIN_HEIGHT = "min_height"; + private static final String ATTR_PERSIST_TASK_VERSION = "persist_task_version"; + + // Current version of the task record we persist. Used to check if we need to run any upgrade + // code. + private static final int PERSIST_TASK_VERSION = 1; + + private static final int INVALID_MIN_SIZE = -1; + + /** + * The modes to control how the stack is moved to the front when calling {@link Task#reparent}. + */ + @Retention(RetentionPolicy.SOURCE) + @IntDef({ + REPARENT_MOVE_STACK_TO_FRONT, + REPARENT_KEEP_STACK_AT_FRONT, + REPARENT_LEAVE_STACK_IN_PLACE + }) + @interface ReparentMoveStackMode {} + // Moves the stack to the front if it was not at the front + static final int REPARENT_MOVE_STACK_TO_FRONT = 0; + // Only moves the stack to the front if it was focused or front most already + static final int REPARENT_KEEP_STACK_AT_FRONT = 1; + // Do not move the stack as a part of reparenting + static final int REPARENT_LEAVE_STACK_IN_PLACE = 2; + + /** + * The factory used to create {@link Task}. This allows OEM subclass {@link Task}. + */ + private static TaskFactory sTaskFactory; + + String affinity; // The affinity name for this task, or null; may change identity. + String rootAffinity; // Initial base affinity, or null; does not change from initial root. + final IVoiceInteractionSession voiceSession; // Voice interaction session driving task + final IVoiceInteractor voiceInteractor; // Associated interactor to provide to app + Intent intent; // The original intent that started the task. Note that this value can + // be null. + Intent affinityIntent; // Intent of affinity-moved activity that started this task. + int effectiveUid; // The current effective uid of the identity of this task. + ComponentName origActivity; // The non-alias activity component of the intent. + ComponentName realActivity; // The actual activity component that started the task. + boolean realActivitySuspended; // True if the actual activity component that started the + // task is suspended. + boolean inRecents; // Actually in the recents list? + long lastActiveTime; // Last time this task was active in the current device session, + // including sleep. This time is initialized to the elapsed time when + // restored from disk. + boolean isAvailable; // Is the activity available to be launched? + boolean rootWasReset; // True if the intent at the root of the task had + // the FLAG_ACTIVITY_RESET_TASK_IF_NEEDED flag. + boolean autoRemoveRecents; // If true, we should automatically remove the task from + // recents when activity finishes + boolean askedCompatMode;// Have asked the user about compat mode for this task. + boolean hasBeenVisible; // Set if any activities in the task have been visible to the user. + + String stringName; // caching of toString() result. + boolean mUserSetupComplete; // The user set-up is complete as of the last time the task activity + // was changed. + + int numFullscreen; // Number of fullscreen activities. + + /** Can't be put in lockTask mode. */ + final static int LOCK_TASK_AUTH_DONT_LOCK = 0; + /** Can enter app pinning with user approval. Can never start over existing lockTask task. */ + final static int LOCK_TASK_AUTH_PINNABLE = 1; + /** Starts in LOCK_TASK_MODE_LOCKED automatically. Can start over existing lockTask task. */ + final static int LOCK_TASK_AUTH_LAUNCHABLE = 2; + /** Can enter lockTask without user approval. Can start over existing lockTask task. */ + final static int LOCK_TASK_AUTH_WHITELISTED = 3; + /** Priv-app that starts in LOCK_TASK_MODE_LOCKED automatically. Can start over existing + * lockTask task. */ + final static int LOCK_TASK_AUTH_LAUNCHABLE_PRIV = 4; + int mLockTaskAuth = LOCK_TASK_AUTH_PINNABLE; + + int mLockTaskUid = -1; // The uid of the application that called startLockTask(). + + /** Current stack. Setter must always be used to update the value. */ + private ActivityStack mStack; + + /** The process that had previously hosted the root activity of this task. + * Used to know that we should try harder to keep this process around, in case the + * user wants to return to it. */ + private WindowProcessController mRootProcess; + + /** Takes on same value as first root activity */ + boolean isPersistable = false; + int maxRecents; + + /** Only used for persistable tasks, otherwise 0. The last time this task was moved. Used for + * determining the order when restoring. Sign indicates whether last task movement was to front + * (positive) or back (negative). Absolute value indicates time. */ + long mLastTimeMoved; + + /** If original intent did not allow relinquishing task identity, save that information */ + private boolean mNeverRelinquishIdentity = true; + + // Used in the unique case where we are clearing the task in order to reuse it. In that case we + // do not want to delete the stack when the task goes empty. + private boolean mReuseTask = false; + + CharSequence lastDescription; // Last description captured for this item. + + int mAffiliatedTaskId; // taskId of parent affiliation or self if no parent. + int mAffiliatedTaskColor; // color of the parent task affiliation. + Task mPrevAffiliate; // previous task in affiliated chain. + int mPrevAffiliateTaskId = INVALID_TASK_ID; // previous id for persistence. + Task mNextAffiliate; // next task in affiliated chain. + int mNextAffiliateTaskId = INVALID_TASK_ID; // next id for persistence. + + // For relaunching the task from recents as though it was launched by the original launcher. + int mCallingUid; + String mCallingPackage; + + private final Rect mTmpStableBounds = new Rect(); + private final Rect mTmpNonDecorBounds = new Rect(); + private final Rect mTmpBounds = new Rect(); + private final Rect mTmpInsets = new Rect(); + + // Last non-fullscreen bounds the task was launched in or resized to. + // The information is persisted and used to determine the appropriate stack to launch the + // task into on restore. + Rect mLastNonFullscreenBounds = null; + // Minimal width and height of this task when it's resizeable. -1 means it should use the + // default minimal width/height. + int mMinWidth; + int mMinHeight; + + // Ranking (from top) of this task among all visible tasks. (-1 means it's not visible) + // This number will be assigned when we evaluate OOM scores for all visible tasks. + int mLayerRank = -1; + + /** Helper object used for updating override configuration. */ + private Configuration mTmpConfig = new Configuration(); + + /** Used by fillTaskInfo */ + final TaskActivitiesReport mReuseActivitiesReport = new TaskActivitiesReport(); final ActivityTaskManagerService mAtmService; @@ -122,22 +390,1851 @@ class Task extends WindowContainer implements ConfigurationConta /** @see #setCanAffectSystemUiFlags */ private boolean mCanAffectSystemUiFlags = true; - Task(int taskId, TaskStack stack, int userId, int resizeMode, boolean supportsPictureInPicture, - TaskDescription taskDescription, ActivityTaskManagerService atm) { - super(atm.mWindowManager); - mAtmService = atm; - mTaskId = taskId; - mUserId = userId; + /** + * Don't use constructor directly. Use {@link #create(ActivityTaskManagerService, int, + * ActivityInfo, Intent, TaskDescription)} instead. + */ + Task(ActivityTaskManagerService atmService, int _taskId, ActivityInfo info, Intent _intent, + IVoiceInteractionSession _voiceSession, IVoiceInteractor _voiceInteractor, + TaskDescription _taskDescription, ActivityStack stack) { + this(atmService, _taskId, _intent, null /*_affinityIntent*/, null /*_affinity*/, + null /*_rootAffinity*/, null /*_realActivity*/, null /*_origActivity*/, + false /*_rootWasReset*/, false /*_autoRemoveRecents*/, false /*_askedCompatMode*/, + UserHandle.getUserId(info.applicationInfo.uid), 0 /*_effectiveUid*/, + null /*_lastDescription*/, System.currentTimeMillis(), + true /*neverRelinquishIdentity*/, + _taskDescription != null ? _taskDescription : new TaskDescription(), + _taskId, INVALID_TASK_ID, INVALID_TASK_ID, 0 /*taskAffiliationColor*/, + info.applicationInfo.uid, info.packageName, info.resizeMode, + info.supportsPictureInPicture(), false /*_realActivitySuspended*/, + false /*userSetupComplete*/, INVALID_MIN_SIZE, INVALID_MIN_SIZE, info, + _voiceSession, _voiceInteractor, stack); + } + + /** Don't use constructor directly. This is only used by XML parser. */ + Task(ActivityTaskManagerService atmService, int _taskId, Intent _intent, + Intent _affinityIntent, String _affinity, String _rootAffinity, + ComponentName _realActivity, ComponentName _origActivity, boolean _rootWasReset, + boolean _autoRemoveRecents, boolean _askedCompatMode, int _userId, + int _effectiveUid, String _lastDescription, + long lastTimeMoved, boolean neverRelinquishIdentity, + TaskDescription _lastTaskDescription, int taskAffiliation, int prevTaskId, + int nextTaskId, int taskAffiliationColor, int callingUid, String callingPackage, + int resizeMode, boolean supportsPictureInPicture, boolean _realActivitySuspended, + boolean userSetupComplete, int minWidth, int minHeight, ActivityInfo info, + IVoiceInteractionSession _voiceSession, IVoiceInteractor _voiceInteractor, + ActivityStack stack) { + super(atmService.mWindowManager); + + EventLog.writeEvent(WM_TASK_CREATED, _taskId, + stack != null ? stack.mStackId : INVALID_STACK_ID); + mAtmService = atmService; + mTaskId = _taskId; + mUserId = _userId; mResizeMode = resizeMode; mSupportsPictureInPicture = supportsPictureInPicture; - mTaskDescription = taskDescription; - EventLog.writeEvent(WM_TASK_CREATED, mTaskId, - stack != null ? stack.mStackId : INVALID_STACK_ID); - + mTaskDescription = _lastTaskDescription; // Tasks have no set orientation value (including SCREEN_ORIENTATION_UNSPECIFIED). setOrientation(SCREEN_ORIENTATION_UNSET); - // TODO(task-merge): Is this really needed? - //setBounds(getResolvedOverrideBounds()); + mRemoteToken = new RemoteToken(this); + affinityIntent = _affinityIntent; + affinity = _affinity; + rootAffinity = _rootAffinity; + voiceSession = _voiceSession; + voiceInteractor = _voiceInteractor; + realActivity = _realActivity; + realActivitySuspended = _realActivitySuspended; + origActivity = _origActivity; + rootWasReset = _rootWasReset; + isAvailable = true; + autoRemoveRecents = _autoRemoveRecents; + askedCompatMode = _askedCompatMode; + mUserSetupComplete = userSetupComplete; + effectiveUid = _effectiveUid; + touchActiveTime(); + lastDescription = _lastDescription; + mLastTimeMoved = lastTimeMoved; + mNeverRelinquishIdentity = neverRelinquishIdentity; + mAffiliatedTaskId = taskAffiliation; + mAffiliatedTaskColor = taskAffiliationColor; + mPrevAffiliateTaskId = prevTaskId; + mNextAffiliateTaskId = nextTaskId; + mCallingUid = callingUid; + mCallingPackage = callingPackage; + mResizeMode = resizeMode; + if (info != null) { + setIntent(_intent, info); + setMinDimensions(info); + } else { + intent = _intent; + mMinWidth = minWidth; + mMinHeight = minHeight; + } + mAtmService.getTaskChangeNotificationController().notifyTaskCreated(_taskId, realActivity); + } + + void cleanUpResourcesForDestroy() { + if (hasChild()) { + return; + } + + // This task is going away, so save the last state if necessary. + saveLaunchingStateIfNeeded(); + + // TODO: VI what about activity? + final boolean isVoiceSession = voiceSession != null; + if (isVoiceSession) { + try { + voiceSession.taskFinished(intent, mTaskId); + } catch (RemoteException e) { + } + } + if (autoRemoveFromRecents() || isVoiceSession) { + // Task creator asked to remove this when done, or this task was a voice + // interaction, so it should not remain on the recent tasks list. + mAtmService.mStackSupervisor.mRecentTasks.remove(this); + } + + removeIfPossible(); + } + + @VisibleForTesting + @Override + void removeIfPossible() { + mAtmService.getLockTaskController().clearLockedTask(this); + if (shouldDeferRemoval()) { + if (DEBUG_STACK) Slog.i(TAG, "removeTask: deferring removing taskId=" + mTaskId); + return; + } + removeImmediately(); + mAtmService.getTaskChangeNotificationController().notifyTaskRemoved(mTaskId); + } + + void setResizeMode(int resizeMode) { + if (mResizeMode == resizeMode) { + return; + } + mResizeMode = resizeMode; + mAtmService.mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS); + mAtmService.mRootActivityContainer.resumeFocusedStacksTopActivities(); + updateTaskDescription(); + } + + boolean resize(Rect bounds, int resizeMode, boolean preserveWindow, boolean deferResume) { + mAtmService.deferWindowLayout(); + + try { + final boolean forced = (resizeMode & RESIZE_MODE_FORCED) != 0; + + if (getParent() == null) { + // Task doesn't exist in window manager yet (e.g. was restored from recents). + // All we can do for now is update the bounds so it can be used when the task is + // added to window manager. + setBounds(bounds); + if (!inFreeformWindowingMode()) { + // re-restore the task so it can have the proper stack association. + mAtmService.mStackSupervisor.restoreRecentTaskLocked(this, null, !ON_TOP); + } + return true; + } + + if (!canResizeToBounds(bounds)) { + throw new IllegalArgumentException("resizeTask: Can not resize task=" + this + + " to bounds=" + bounds + " resizeMode=" + mResizeMode); + } + + // Do not move the task to another stack here. + // This method assumes that the task is already placed in the right stack. + // we do not mess with that decision and we only do the resize! + + Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "resizeTask_" + mTaskId); + + boolean updatedConfig = false; + mTmpConfig.setTo(getResolvedOverrideConfiguration()); + if (setBounds(bounds) != BOUNDS_CHANGE_NONE) { + updatedConfig = !mTmpConfig.equals(getResolvedOverrideConfiguration()); + } + // This variable holds information whether the configuration didn't change in a + // significant way and the activity was kept the way it was. If it's false, it means + // the activity had to be relaunched due to configuration change. + boolean kept = true; + if (updatedConfig) { + final ActivityRecord r = topRunningActivityLocked(); + if (r != null && !deferResume) { + kept = r.ensureActivityConfiguration(0 /* globalChanges */, + preserveWindow); + // Preserve other windows for resizing because if resizing happens when there + // is a dialog activity in the front, the activity that still shows some + // content to the user will become black and cause flickers. Note in most cases + // this won't cause tons of irrelevant windows being preserved because only + // activities in this task may experience a bounds change. Configs for other + // activities stay the same. + mAtmService.mRootActivityContainer.ensureActivitiesVisible(r, 0, + preserveWindow); + if (!kept) { + mAtmService.mRootActivityContainer.resumeFocusedStacksTopActivities(); + } + } + } + resize(kept, forced); + + saveLaunchingStateIfNeeded(); + + Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER); + return kept; + } finally { + mAtmService.continueWindowLayout(); + } + } + + /** Convenience method to reparent a task to the top or bottom position of the stack. */ + boolean reparent(ActivityStack preferredStack, boolean toTop, + @ReparentMoveStackMode int moveStackMode, boolean animate, boolean deferResume, + String reason) { + return reparent(preferredStack, toTop ? MAX_VALUE : 0, moveStackMode, animate, deferResume, + true /* schedulePictureInPictureModeChange */, reason); + } + + /** + * Convenience method to reparent a task to the top or bottom position of the stack, with + * an option to skip scheduling the picture-in-picture mode change. + */ + boolean reparent(ActivityStack preferredStack, boolean toTop, + @ReparentMoveStackMode int moveStackMode, boolean animate, boolean deferResume, + boolean schedulePictureInPictureModeChange, String reason) { + return reparent(preferredStack, toTop ? MAX_VALUE : 0, moveStackMode, animate, + deferResume, schedulePictureInPictureModeChange, reason); + } + + /** Convenience method to reparent a task to a specific position of the stack. */ + boolean reparent(ActivityStack preferredStack, int position, + @ReparentMoveStackMode int moveStackMode, boolean animate, boolean deferResume, + String reason) { + return reparent(preferredStack, position, moveStackMode, animate, deferResume, + true /* schedulePictureInPictureModeChange */, reason); + } + + /** + * Reparents the task into a preferred stack, creating it if necessary. + * + * @param preferredStack the target stack to move this task + * @param position the position to place this task in the new stack + * @param animate whether or not we should wait for the new window created as a part of the + * reparenting to be drawn and animated in + * @param moveStackMode whether or not to move the stack to the front always, only if it was + * previously focused & in front, or never + * @param deferResume whether or not to update the visibility of other tasks and stacks that may + * have changed as a result of this reparenting + * @param schedulePictureInPictureModeChange specifies whether or not to schedule the PiP mode + * change. Callers may set this to false if they are explicitly scheduling PiP mode + * changes themselves, like during the PiP animation + * @param reason the caller of this reparenting + * @return whether the task was reparented + */ + // TODO: Inspect all call sites and change to just changing windowing mode of the stack vs. + // re-parenting the task. Can only be done when we are no longer using static stack Ids. + boolean reparent(ActivityStack preferredStack, int position, + @ReparentMoveStackMode int moveStackMode, boolean animate, boolean deferResume, + boolean schedulePictureInPictureModeChange, String reason) { + final ActivityStackSupervisor supervisor = mAtmService.mStackSupervisor; + final RootActivityContainer root = mAtmService.mRootActivityContainer; + final WindowManagerService windowManager = mAtmService.mWindowManager; + final ActivityStack sourceStack = getStack(); + final ActivityStack toStack = supervisor.getReparentTargetStack(this, preferredStack, + position == MAX_VALUE); + if (toStack == sourceStack) { + return false; + } + if (!canBeLaunchedOnDisplay(toStack.mDisplayId)) { + return false; + } + + final boolean toTopOfStack = position == MAX_VALUE; + if (toTopOfStack && toStack.getResumedActivity() != null + && toStack.topRunningActivityLocked() != null) { + // Pause the resumed activity on the target stack while re-parenting task on top of it. + toStack.startPausingLocked(false /* userLeaving */, false /* uiSleeping */, + null /* resuming */); + } + + final int toStackWindowingMode = toStack.getWindowingMode(); + final ActivityRecord topActivity = getTopActivity(); + + final boolean mightReplaceWindow = topActivity != null + && replaceWindowsOnTaskMove(getWindowingMode(), toStackWindowingMode); + if (mightReplaceWindow) { + // We are about to relaunch the activity because its configuration changed due to + // being maximized, i.e. size change. The activity will first remove the old window + // and then add a new one. This call will tell window manager about this, so it can + // preserve the old window until the new one is drawn. This prevents having a gap + // between the removal and addition, in which no window is visible. We also want the + // entrance of the new window to be properly animated. + // Note here we always set the replacing window first, as the flags might be needed + // during the relaunch. If we end up not doing any relaunch, we clear the flags later. + windowManager.setWillReplaceWindow(topActivity.appToken, animate); + } + + mAtmService.deferWindowLayout(); + boolean kept = true; + try { + final ActivityRecord r = topRunningActivityLocked(); + // give pinned stack a chance to save current bounds, this needs to be before the + // actual reparent. + if (inPinnedWindowingMode() + && !(toStackWindowingMode == WINDOWING_MODE_UNDEFINED) + && !r.isHidden()) { + r.savePinnedStackBounds(); + } + final boolean wasFocused = r != null && root.isTopDisplayFocusedStack(sourceStack) + && (topRunningActivityLocked() == r); + final boolean wasResumed = r != null && sourceStack.getResumedActivity() == r; + final boolean wasPaused = r != null && sourceStack.mPausingActivity == r; + + // In some cases the focused stack isn't the front stack. E.g. pinned stack. + // Whenever we are moving the top activity from the front stack we want to make sure to + // move the stack to the front. + final boolean wasFront = r != null && sourceStack.isTopStackOnDisplay() + && (sourceStack.topRunningActivityLocked() == r); + + final boolean moveStackToFront = moveStackMode == REPARENT_MOVE_STACK_TO_FRONT + || (moveStackMode == REPARENT_KEEP_STACK_AT_FRONT && (wasFocused || wasFront)); + + reparent(toStack, position, moveStackToFront, reason); + + if (schedulePictureInPictureModeChange) { + // Notify of picture-in-picture mode changes + supervisor.scheduleUpdatePictureInPictureModeIfNeeded(this, sourceStack); + } + + // If the task had focus before (or we're requested to move focus), move focus to the + // new stack by moving the stack to the front. + if (r != null) { + toStack.moveToFrontAndResumeStateIfNeeded(r, moveStackToFront, wasResumed, + wasPaused, reason); + } + if (!animate) { + mAtmService.mStackSupervisor.mNoAnimActivities.add(topActivity); + } + + // We might trigger a configuration change. Save the current task bounds for freezing. + // TODO: Should this call be moved inside the resize method in WM? + toStack.prepareFreezingTaskBounds(); + + // Make sure the task has the appropriate bounds/size for the stack it is in. + final boolean toStackSplitScreenPrimary = + toStackWindowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY; + final Rect configBounds = getRequestedOverrideBounds(); + if ((toStackWindowingMode == WINDOWING_MODE_FULLSCREEN + || toStackWindowingMode == WINDOWING_MODE_SPLIT_SCREEN_SECONDARY) + && !Objects.equals(configBounds, toStack.getRequestedOverrideBounds())) { + kept = resize(toStack.getRequestedOverrideBounds(), RESIZE_MODE_SYSTEM, + !mightReplaceWindow, deferResume); + } else if (toStackWindowingMode == WINDOWING_MODE_FREEFORM) { + Rect bounds = getLaunchBounds(); + if (bounds == null) { + mAtmService.mStackSupervisor.getLaunchParamsController().layoutTask(this, null); + bounds = configBounds; + } + kept = resize(bounds, RESIZE_MODE_FORCED, !mightReplaceWindow, deferResume); + } else if (toStackSplitScreenPrimary || toStackWindowingMode == WINDOWING_MODE_PINNED) { + if (toStackSplitScreenPrimary && moveStackMode == REPARENT_KEEP_STACK_AT_FRONT) { + // Move recents to front so it is not behind home stack when going into docked + // mode + mAtmService.mStackSupervisor.moveRecentsStackToFront(reason); + } + kept = resize(toStack.getRequestedOverrideBounds(), RESIZE_MODE_SYSTEM, + !mightReplaceWindow, deferResume); + } + } finally { + mAtmService.continueWindowLayout(); + } + + if (mightReplaceWindow) { + // If we didn't actual do a relaunch (indicated by kept==true meaning we kept the old + // window), we need to clear the replace window settings. Otherwise, we schedule a + // timeout to remove the old window if the replacing window is not coming in time. + windowManager.scheduleClearWillReplaceWindows(topActivity.appToken, !kept); + } + + if (!deferResume) { + // The task might have already been running and its visibility needs to be synchronized + // with the visibility of the stack / windows. + root.ensureActivitiesVisible(null, 0, !mightReplaceWindow); + root.resumeFocusedStacksTopActivities(); + } + + // TODO: Handle incorrect request to move before the actual move, not after. + supervisor.handleNonResizableTaskIfNeeded(this, preferredStack.getWindowingMode(), + DEFAULT_DISPLAY, toStack); + + return (preferredStack == toStack); + } + + /** + * @return {@code true} if the windows of tasks being moved to the target stack from the + * source stack should be replaced, meaning that window manager will keep the old window + * around until the new is ready. + */ + private static boolean replaceWindowsOnTaskMove( + int sourceWindowingMode, int targetWindowingMode) { + return sourceWindowingMode == WINDOWING_MODE_FREEFORM + || targetWindowingMode == WINDOWING_MODE_FREEFORM; + } + + /** + * DO NOT HOLD THE ACTIVITY MANAGER LOCK WHEN CALLING THIS METHOD! + */ + TaskSnapshot getSnapshot(boolean reducedResolution, boolean restoreFromDisk) { + + // TODO: Move this to {@link TaskWindowContainerController} once recent tasks are more + // synchronized between AM and WM. + return mAtmService.mWindowManager.getTaskSnapshot(mTaskId, mUserId, reducedResolution, + restoreFromDisk); + } + + void touchActiveTime() { + lastActiveTime = SystemClock.elapsedRealtime(); + } + + long getInactiveDuration() { + return SystemClock.elapsedRealtime() - lastActiveTime; + } + + /** Sets the original intent, and the calling uid and package. */ + void setIntent(ActivityRecord r) { + mCallingUid = r.launchedFromUid; + mCallingPackage = r.launchedFromPackage; + setIntent(r.intent, r.info); + setLockTaskAuth(r); + } + + /** Sets the original intent, _without_ updating the calling uid or package. */ + private void setIntent(Intent _intent, ActivityInfo info) { + if (intent == null) { + mNeverRelinquishIdentity = + (info.flags & FLAG_RELINQUISH_TASK_IDENTITY) == 0; + } else if (mNeverRelinquishIdentity) { + return; + } + + affinity = info.taskAffinity; + if (intent == null) { + // If this task already has an intent associated with it, don't set the root + // affinity -- we don't want it changing after initially set, but the initially + // set value may be null. + rootAffinity = affinity; + } + effectiveUid = info.applicationInfo.uid; + stringName = null; + + if (info.targetActivity == null) { + if (_intent != null) { + // If this Intent has a selector, we want to clear it for the + // recent task since it is not relevant if the user later wants + // to re-launch the app. + if (_intent.getSelector() != null || _intent.getSourceBounds() != null) { + _intent = new Intent(_intent); + _intent.setSelector(null); + _intent.setSourceBounds(null); + } + } + if (DEBUG_TASKS) Slog.v(TAG_TASKS, "Setting Intent of " + this + " to " + _intent); + intent = _intent; + realActivity = _intent != null ? _intent.getComponent() : null; + origActivity = null; + } else { + ComponentName targetComponent = new ComponentName( + info.packageName, info.targetActivity); + if (_intent != null) { + Intent targetIntent = new Intent(_intent); + targetIntent.setSelector(null); + targetIntent.setSourceBounds(null); + if (DEBUG_TASKS) Slog.v(TAG_TASKS, + "Setting Intent of " + this + " to target " + targetIntent); + intent = targetIntent; + realActivity = targetComponent; + origActivity = _intent.getComponent(); + } else { + intent = null; + realActivity = targetComponent; + origActivity = new ComponentName(info.packageName, info.name); + } + } + + final int intentFlags = intent == null ? 0 : intent.getFlags(); + if ((intentFlags & Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) { + // Once we are set to an Intent with this flag, we count this + // task as having a true root activity. + rootWasReset = true; + } + mUserId = UserHandle.getUserId(info.applicationInfo.uid); + mUserSetupComplete = Settings.Secure.getIntForUser( + mAtmService.mContext.getContentResolver(), USER_SETUP_COMPLETE, 0, mUserId) != 0; + if ((info.flags & ActivityInfo.FLAG_AUTO_REMOVE_FROM_RECENTS) != 0) { + // If the activity itself has requested auto-remove, then just always do it. + autoRemoveRecents = true; + } else if ((intentFlags & (FLAG_ACTIVITY_NEW_DOCUMENT | FLAG_ACTIVITY_RETAIN_IN_RECENTS)) + == FLAG_ACTIVITY_NEW_DOCUMENT) { + // If the caller has not asked for the document to be retained, then we may + // want to turn on auto-remove, depending on whether the target has set its + // own document launch mode. + if (info.documentLaunchMode != ActivityInfo.DOCUMENT_LAUNCH_NONE) { + autoRemoveRecents = false; + } else { + autoRemoveRecents = true; + } + } else { + autoRemoveRecents = false; + } + if (mResizeMode != info.resizeMode) { + mResizeMode = info.resizeMode; + updateTaskDescription(); + } + mSupportsPictureInPicture = info.supportsPictureInPicture(); + } + + /** Sets the original minimal width and height. */ + private void setMinDimensions(ActivityInfo info) { + if (info != null && info.windowLayout != null) { + mMinWidth = info.windowLayout.minWidth; + mMinHeight = info.windowLayout.minHeight; + } else { + mMinWidth = INVALID_MIN_SIZE; + mMinHeight = INVALID_MIN_SIZE; + } + } + + /** + * Return true if the input activity has the same intent filter as the intent this task + * record is based on (normally the root activity intent). + */ + boolean isSameIntentFilter(ActivityRecord r) { + final Intent intent = new Intent(r.intent); + // Make sure the component are the same if the input activity has the same real activity + // as the one in the task because either one of them could be the alias activity. + if (Objects.equals(realActivity, r.mActivityComponent) && this.intent != null) { + intent.setComponent(this.intent.getComponent()); + } + return intent.filterEquals(this.intent); + } + + boolean returnsToHomeStack() { + final int returnHomeFlags = FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_TASK_ON_HOME; + return intent != null && (intent.getFlags() & returnHomeFlags) == returnHomeFlags; + } + + void setPrevAffiliate(Task prevAffiliate) { + mPrevAffiliate = prevAffiliate; + mPrevAffiliateTaskId = prevAffiliate == null ? INVALID_TASK_ID : prevAffiliate.mTaskId; + } + + void setNextAffiliate(Task nextAffiliate) { + mNextAffiliate = nextAffiliate; + mNextAffiliateTaskId = nextAffiliate == null ? INVALID_TASK_ID : nextAffiliate.mTaskId; + } + + ActivityStack getStack() { + return mStack; + } + + @Override + void onParentChanged(ConfigurationContainer newParent, ConfigurationContainer oldParent) { + // TODO(stack-merge): Remove casts after object merge. + final ActivityStack oldStack = ((ActivityStack) oldParent); + final ActivityStack newStack = ((ActivityStack) newParent); + + mStack = newStack; + + super.onParentChanged(newParent, oldParent); + + if (oldStack != null) { + for (int i = getChildCount() - 1; i >= 0; --i) { + final ActivityRecord activity = getChildAt(i); + oldStack.onActivityRemovedFromStack(activity); + } + + if (oldStack.inPinnedWindowingMode() + && (newStack == null || !newStack.inPinnedWindowingMode())) { + // Notify if a task from the pinned stack is being removed + // (or moved depending on the mode). + mAtmService.getTaskChangeNotificationController().notifyActivityUnpinned(); + } + } + + if (newStack != null) { + for (int i = getChildCount() - 1; i >= 0; --i) { + final ActivityRecord activity = getChildAt(i); + newStack.onActivityAddedToStack(activity); + } + + // TODO: Ensure that this is actually necessary here + // Notify the voice session if required + if (voiceSession != null) { + try { + voiceSession.taskStarted(intent, mTaskId); + } catch (RemoteException e) { + } + } + } + + // First time we are adding the task to the system. + if (oldParent == null && newParent != null) { + + // TODO: Super random place to be doing this, but aligns with what used to be done + // before we unified Task level. Look into if this can be done in a better place. + updateOverrideConfigurationFromLaunchBounds(); + } + + // Task is being removed. + if (oldParent != null && newParent == null) { + cleanUpResourcesForDestroy(); + } + + + // Update task bounds if needed. + adjustBoundsForDisplayChangeIfNeeded(getDisplayContent()); + + if (getWindowConfiguration().windowsAreScaleable()) { + // We force windows out of SCALING_MODE_FREEZE so that we can continue to animate them + // while a resize is pending. + forceWindowsScaleable(true /* force */); + } else { + forceWindowsScaleable(false /* force */); + } + + mAtmService.mRootActivityContainer.updateUIDsPresentOnDisplay(); + } + + void updateTaskMovement(boolean toFront) { + if (isPersistable) { + mLastTimeMoved = System.currentTimeMillis(); + // Sign is used to keep tasks sorted when persisted. Tasks sent to the bottom most + // recently will be most negative, tasks sent to the bottom before that will be less + // negative. Similarly for recent tasks moved to the top which will be most positive. + if (!toFront) { + mLastTimeMoved *= -1; + } + } + mAtmService.mRootActivityContainer.invalidateTaskLayers(); + } + + /** + * @return Id of current stack, {@link ActivityTaskManager#INVALID_STACK_ID} if no stack is set. + */ + int getStackId() { + return mStack != null ? mStack.mStackId : INVALID_STACK_ID; + } + + // Close up recents linked list. + private void closeRecentsChain() { + if (mPrevAffiliate != null) { + mPrevAffiliate.setNextAffiliate(mNextAffiliate); + } + if (mNextAffiliate != null) { + mNextAffiliate.setPrevAffiliate(mPrevAffiliate); + } + setPrevAffiliate(null); + setNextAffiliate(null); + } + + void removedFromRecents() { + closeRecentsChain(); + if (inRecents) { + inRecents = false; + mAtmService.notifyTaskPersisterLocked(this, false); + } + + clearRootProcess(); + + mAtmService.mWindowManager.mTaskSnapshotController.notifyTaskRemovedFromRecents( + mTaskId, mUserId); + } + + void setTaskToAffiliateWith(Task taskToAffiliateWith) { + closeRecentsChain(); + mAffiliatedTaskId = taskToAffiliateWith.mAffiliatedTaskId; + mAffiliatedTaskColor = taskToAffiliateWith.mAffiliatedTaskColor; + // Find the end + while (taskToAffiliateWith.mNextAffiliate != null) { + final Task nextRecents = taskToAffiliateWith.mNextAffiliate; + if (nextRecents.mAffiliatedTaskId != mAffiliatedTaskId) { + Slog.e(TAG, "setTaskToAffiliateWith: nextRecents=" + nextRecents + " affilTaskId=" + + nextRecents.mAffiliatedTaskId + " should be " + mAffiliatedTaskId); + if (nextRecents.mPrevAffiliate == taskToAffiliateWith) { + nextRecents.setPrevAffiliate(null); + } + taskToAffiliateWith.setNextAffiliate(null); + break; + } + taskToAffiliateWith = nextRecents; + } + taskToAffiliateWith.setNextAffiliate(this); + setPrevAffiliate(taskToAffiliateWith); + setNextAffiliate(null); + } + + /** Returns the intent for the root activity for this task */ + Intent getBaseIntent() { + return intent != null ? intent : affinityIntent; + } + + /** Returns the first non-finishing activity from the bottom. */ + ActivityRecord getRootActivity() { + final int rootActivityIndex = findRootIndex(false /* effectiveRoot */); + if (rootActivityIndex == -1) { + // There are no non-finishing activities in the task. + return null; + } + return getChildAt(rootActivityIndex); + } + + ActivityRecord getTopActivity() { + return getTopActivity(true /* includeOverlays */); + } + + ActivityRecord getTopActivity(boolean includeOverlays) { + for (int i = getChildCount() - 1; i >= 0; --i) { + final ActivityRecord r = getChildAt(i); + if (r.finishing || (!includeOverlays && r.mTaskOverlay)) { + continue; + } + return r; + } + return null; + } + + ActivityRecord topRunningActivityLocked() { + if (mStack != null) { + for (int activityNdx = getChildCount() - 1; activityNdx >= 0; --activityNdx) { + ActivityRecord r = getChildAt(activityNdx); + if (!r.finishing && r.okToShowLocked()) { + return r; + } + } + } + return null; + } + + /** + * Return true if any activities in this task belongs to input uid. + */ + boolean containsAppUid(int uid) { + for (int i = getChildCount() - 1; i >= 0; --i) { + final ActivityRecord r = getChildAt(i); + if (r.getUid() == uid) { + return true; + } + } + return false; + } + + void getAllRunningVisibleActivitiesLocked(ArrayList outActivities) { + if (mStack != null) { + for (int activityNdx = getChildCount() - 1; activityNdx >= 0; --activityNdx) { + ActivityRecord r = getChildAt(activityNdx); + if (!r.finishing && r.okToShowLocked() && r.visibleIgnoringKeyguard) { + outActivities.add(r); + } + } + } + } + + ActivityRecord topRunningActivityWithStartingWindowLocked() { + if (mStack != null) { + for (int activityNdx = getChildCount() - 1; activityNdx >= 0; --activityNdx) { + ActivityRecord r = getChildAt(activityNdx); + if (r.mStartingWindowState != STARTING_WINDOW_SHOWN + || r.finishing || !r.okToShowLocked()) { + continue; + } + return r; + } + } + return null; + } + + /** + * Return the number of running activities, and the number of non-finishing/initializing + * activities in the provided {@param reportOut} respectively. + */ + void getNumRunningActivities(TaskActivitiesReport reportOut) { + reportOut.reset(); + for (int i = getChildCount() - 1; i >= 0; --i) { + final ActivityRecord r = getChildAt(i); + if (r.finishing) { + continue; + } + + reportOut.base = r; + + // Increment the total number of non-finishing activities + reportOut.numActivities++; + + if (reportOut.top == null || (reportOut.top.isState(ActivityState.INITIALIZING))) { + reportOut.top = r; + // Reset the number of running activities until we hit the first non-initializing + // activity + reportOut.numRunning = 0; + } + if (r.attachedToProcess()) { + // Increment the number of actually running activities + reportOut.numRunning++; + } + } + } + + boolean okToShowLocked() { + // NOTE: If {@link Task#topRunningActivity} return is not null then it is + // okay to show the activity when locked. + return mAtmService.mStackSupervisor.isCurrentProfileLocked(mUserId) + || topRunningActivityLocked() != null; + } + + /** + * Reorder the history stack so that the passed activity is brought to the front. + */ + final void moveActivityToFrontLocked(ActivityRecord newTop) { + if (DEBUG_ADD_REMOVE) Slog.i(TAG_ADD_REMOVE, "Removing and adding activity " + + newTop + " to stack at top callers=" + Debug.getCallers(4)); + + positionChildAtTop(newTop); + updateEffectiveIntent(); + } + + @Override + public int getActivityType() { + final int applicationType = super.getActivityType(); + if (applicationType != ACTIVITY_TYPE_UNDEFINED || !hasChild()) { + return applicationType; + } + return getChildAt(0).getActivityType(); + } + + @Override + void addChild(ActivityRecord r, int index) { + // If this task had any child before we added this one. + boolean hadChild = hasChild(); + + index = getAdjustedAddPosition(r, index); + super.addChild(r, index); + + ProtoLog.v(WM_DEBUG_ADD_REMOVE, "addChild: %s at top.", this); + r.inHistory = true; + + if (r.occludesParent()) { + numFullscreen++; + } + // Only set this based on the first activity + if (!hadChild) { + if (r.getActivityType() == ACTIVITY_TYPE_UNDEFINED) { + // Normally non-standard activity type for the activity record will be set when the + // object is created, however we delay setting the standard application type until + // this point so that the task can set the type for additional activities added in + // the else condition below. + r.setActivityType(ACTIVITY_TYPE_STANDARD); + } + setActivityType(r.getActivityType()); + isPersistable = r.isPersistable(); + mCallingUid = r.launchedFromUid; + mCallingPackage = r.launchedFromPackage; + // Clamp to [1, max]. + maxRecents = Math.min(Math.max(r.info.maxRecents, 1), + ActivityTaskManager.getMaxAppRecentsLimitStatic()); + } else { + // Otherwise make all added activities match this one. + r.setActivityType(getActivityType()); + } + + updateEffectiveIntent(); + if (r.isPersistable()) { + mAtmService.notifyTaskPersisterLocked(this, false); + } + + // Make sure the list of display UID whitelists is updated + // now that this record is in a new task. + mAtmService.mRootActivityContainer.updateUIDsPresentOnDisplay(); + } + + void addChild(ActivityRecord r) { + addChild(r, Integer.MAX_VALUE /* add on top */); + } + + @Override + void removeChild(ActivityRecord r) { + if (!mChildren.contains(r)) { + Slog.e(TAG, "removeChild: r=" + r + " not found in t=" + this); + return; + } + + super.removeChild(r); + if (r.occludesParent()) { + numFullscreen--; + } + if (r.isPersistable()) { + mAtmService.notifyTaskPersisterLocked(this, false); + } + + if (inPinnedWindowingMode()) { + // We normally notify listeners of task stack changes on pause, however pinned stack + // activities are normally in the paused state so no notification will be sent there + // before the activity is removed. We send it here so instead. + mAtmService.getTaskChangeNotificationController().notifyTaskStackChanged(); + } + + final String reason = "removeChild"; + if (hasChild()) { + updateEffectiveIntent(); + + // The following block can be executed multiple times if there is more than one overlay. + // {@link ActivityStackSupervisor#removeTaskByIdLocked} handles this by reverse lookup + // of the task by id and exiting early if not found. + if (onlyHasTaskOverlayActivities(false /* excludingFinishing */)) { + // When destroying a task, tell the supervisor to remove it so that any activity it + // has can be cleaned up correctly. This is currently the only place where we remove + // a task with the DESTROYING mode, so instead of passing the onlyHasTaskOverlays + // state into removeChild(), we just clear the task here before the other residual + // work. + // TODO: If the callers to removeChild() changes such that we have multiple places + // where we are destroying the task, move this back into removeChild() + mAtmService.mStackSupervisor.removeTaskByIdLocked(mTaskId, false /* killProcess */, + !REMOVE_FROM_RECENTS, reason); + } + } else if (!mReuseTask) { + // Remove entire task if it doesn't have any activity left and it isn't marked for reuse + mStack.removeChild(this, reason); + EventLog.writeEvent(WM_TASK_REMOVED, mTaskId, + "removeChild: last r=" + r + " in t=" + this); + removeIfPossible(); + } + } + + /** + * @return whether or not there are ONLY task overlay activities in the stack. + * If {@param excludeFinishing} is set, then ignore finishing activities in the check. + * If there are no task overlay activities, this call returns false. + */ + boolean onlyHasTaskOverlayActivities(boolean excludeFinishing) { + int count = 0; + for (int i = getChildCount() - 1; i >= 0; i--) { + final ActivityRecord r = getChildAt(i); + if (excludeFinishing && r.finishing) { + continue; + } + if (!r.mTaskOverlay) { + return false; + } + count++; + } + return count > 0; + } + + boolean autoRemoveFromRecents() { + // We will automatically remove the task either if it has explicitly asked for + // this, or it is empty and has never contained an activity that got shown to + // the user. + return autoRemoveRecents || (!hasChild() && !hasBeenVisible); + } + + /** + * Completely remove all activities associated with an existing + * task starting at a specified index. + */ + private void performClearTaskAtIndexLocked(int activityNdx, String reason) { + int numActivities = getChildCount(); + for ( ; activityNdx < numActivities; ++activityNdx) { + final ActivityRecord r = getChildAt(activityNdx); + if (r.finishing) { + continue; + } + if (mStack == null) { + // Task was restored from persistent storage. + r.takeFromHistory(); + removeChild(r); + --activityNdx; + --numActivities; + } else if (r.finishIfPossible(Activity.RESULT_CANCELED, null /* resultData */, reason, + false /* oomAdj */) + == FINISH_RESULT_REMOVED) { + --activityNdx; + --numActivities; + } + } + } + + /** + * Completely remove all activities associated with an existing task. + */ + void performClearTaskLocked() { + mReuseTask = true; + performClearTaskAtIndexLocked(0, "clear-task-all"); + mReuseTask = false; + } + + ActivityRecord performClearTaskForReuseLocked(ActivityRecord newR, int launchFlags) { + mReuseTask = true; + final ActivityRecord result = performClearTaskLocked(newR, launchFlags); + mReuseTask = false; + return result; + } + + /** + * Perform clear operation as requested by + * {@link Intent#FLAG_ACTIVITY_CLEAR_TOP}: search from the top of the + * stack to the given task, then look for + * an instance of that activity in the stack and, if found, finish all + * activities on top of it and return the instance. + * + * @param newR Description of the new activity being started. + * @return Returns the old activity that should be continued to be used, + * or {@code null} if none was found. + */ + final ActivityRecord performClearTaskLocked(ActivityRecord newR, int launchFlags) { + int numActivities = getChildCount(); + for (int activityNdx = numActivities - 1; activityNdx >= 0; --activityNdx) { + ActivityRecord r = getChildAt(activityNdx); + if (r.finishing) { + continue; + } + if (r.mActivityComponent.equals(newR.mActivityComponent)) { + // Here it is! Now finish everything in front... + final ActivityRecord ret = r; + + for (++activityNdx; activityNdx < numActivities; ++activityNdx) { + r = getChildAt(activityNdx); + if (r.finishing) { + continue; + } + ActivityOptions opts = r.takeOptionsLocked(false /* fromClient */); + if (opts != null) { + ret.updateOptionsLocked(opts); + } + if (r.finishIfPossible("clear-task-stack", false /* oomAdj */) + == FINISH_RESULT_REMOVED) { + --activityNdx; + --numActivities; + } + } + + // Finally, if this is a normal launch mode (that is, not + // expecting onNewIntent()), then we will finish the current + // instance of the activity so a new fresh one can be started. + if (ret.launchMode == ActivityInfo.LAUNCH_MULTIPLE + && (launchFlags & Intent.FLAG_ACTIVITY_SINGLE_TOP) == 0 + && !ActivityStarter.isDocumentLaunchesIntoExisting(launchFlags)) { + if (!ret.finishing) { + ret.finishIfPossible("clear-task-top", false /* oomAdj */); + return null; + } + } + + return ret; + } + } + + return null; + } + + void removeTaskActivitiesLocked(String reason) { + // Just remove the entire task. + performClearTaskAtIndexLocked(0, reason); + } + + String lockTaskAuthToString() { + switch (mLockTaskAuth) { + case LOCK_TASK_AUTH_DONT_LOCK: return "LOCK_TASK_AUTH_DONT_LOCK"; + case LOCK_TASK_AUTH_PINNABLE: return "LOCK_TASK_AUTH_PINNABLE"; + case LOCK_TASK_AUTH_LAUNCHABLE: return "LOCK_TASK_AUTH_LAUNCHABLE"; + case LOCK_TASK_AUTH_WHITELISTED: return "LOCK_TASK_AUTH_WHITELISTED"; + case LOCK_TASK_AUTH_LAUNCHABLE_PRIV: return "LOCK_TASK_AUTH_LAUNCHABLE_PRIV"; + default: return "unknown=" + mLockTaskAuth; + } + } + + void setLockTaskAuth() { + setLockTaskAuth(getRootActivity()); + } + + private void setLockTaskAuth(@Nullable ActivityRecord r) { + if (r == null) { + mLockTaskAuth = LOCK_TASK_AUTH_PINNABLE; + return; + } + + final String pkg = (realActivity != null) ? realActivity.getPackageName() : null; + final LockTaskController lockTaskController = mAtmService.getLockTaskController(); + switch (r.lockTaskLaunchMode) { + case LOCK_TASK_LAUNCH_MODE_DEFAULT: + mLockTaskAuth = lockTaskController.isPackageWhitelisted(mUserId, pkg) + ? LOCK_TASK_AUTH_WHITELISTED : LOCK_TASK_AUTH_PINNABLE; + break; + + case LOCK_TASK_LAUNCH_MODE_NEVER: + mLockTaskAuth = LOCK_TASK_AUTH_DONT_LOCK; + break; + + case LOCK_TASK_LAUNCH_MODE_ALWAYS: + mLockTaskAuth = LOCK_TASK_AUTH_LAUNCHABLE_PRIV; + break; + + case LOCK_TASK_LAUNCH_MODE_IF_WHITELISTED: + mLockTaskAuth = lockTaskController.isPackageWhitelisted(mUserId, pkg) + ? LOCK_TASK_AUTH_LAUNCHABLE : LOCK_TASK_AUTH_PINNABLE; + break; + } + if (DEBUG_LOCKTASK) Slog.d(TAG_LOCKTASK, "setLockTaskAuth: task=" + this + + " mLockTaskAuth=" + lockTaskAuthToString()); + } + + @Override + public boolean supportsSplitScreenWindowingMode() { + // A task can not be docked even if it is considered resizeable because it only supports + // picture-in-picture mode but has a non-resizeable resizeMode + return super.supportsSplitScreenWindowingMode() + // TODO(task-group): Probably makes sense to move this and associated code into + // WindowContainer so it affects every node. + && mAtmService.mSupportsSplitScreenMultiWindow + && (mAtmService.mForceResizableActivities + || (isResizeable(false /* checkSupportsPip */) + && !ActivityInfo.isPreserveOrientationMode(mResizeMode))); + } + + /** + * Check whether this task can be launched on the specified display. + * + * @param displayId Target display id. + * @return {@code true} if either it is the default display or this activity can be put on a + * secondary display. + */ + boolean canBeLaunchedOnDisplay(int displayId) { + return mAtmService.mStackSupervisor.canPlaceEntityOnDisplay(displayId, + -1 /* don't check PID */, -1 /* don't check UID */, null /* activityInfo */); + } + + /** + * Check that a given bounds matches the application requested orientation. + * + * @param bounds The bounds to be tested. + * @return True if the requested bounds are okay for a resizing request. + */ + private boolean canResizeToBounds(Rect bounds) { + if (bounds == null || !inFreeformWindowingMode()) { + // Note: If not on the freeform workspace, we ignore the bounds. + return true; + } + final boolean landscape = bounds.width() > bounds.height(); + final Rect configBounds = getRequestedOverrideBounds(); + if (mResizeMode == RESIZE_MODE_FORCE_RESIZABLE_PRESERVE_ORIENTATION) { + return configBounds.isEmpty() + || landscape == (configBounds.width() > configBounds.height()); + } + return (mResizeMode != RESIZE_MODE_FORCE_RESIZABLE_PORTRAIT_ONLY || !landscape) + && (mResizeMode != RESIZE_MODE_FORCE_RESIZABLE_LANDSCAPE_ONLY || landscape); + } + + /** + * @return {@code true} if the task is being cleared for the purposes of being reused. + */ + boolean isClearingToReuseTask() { + return mReuseTask; + } + + /** + * Find the activity in the history stack within the given task. Returns + * the index within the history at which it's found, or < 0 if not found. + */ + final ActivityRecord findActivityInHistoryLocked(ActivityRecord r) { + final ComponentName realActivity = r.mActivityComponent; + for (int activityNdx = getChildCount() - 1; activityNdx >= 0; --activityNdx) { + ActivityRecord candidate = getChildAt(activityNdx); + if (candidate.finishing) { + continue; + } + if (candidate.mActivityComponent.equals(realActivity)) { + return candidate; + } + } + return null; + } + + /** Updates the last task description values. */ + void updateTaskDescription() { + // TODO(AM refactor): Cleanup to use findRootIndex() + // Traverse upwards looking for any break between main task activities and + // utility activities. + int activityNdx; + final int numActivities = getChildCount(); + final boolean relinquish = numActivities != 0 + && (getChildAt(0).info.flags & FLAG_RELINQUISH_TASK_IDENTITY) != 0; + for (activityNdx = Math.min(numActivities, 1); activityNdx < numActivities; ++activityNdx) { + final ActivityRecord r = getChildAt(activityNdx); + if (relinquish && (r.info.flags & FLAG_RELINQUISH_TASK_IDENTITY) == 0) { + // This will be the top activity for determining taskDescription. Pre-inc to + // overcome initial decrement below. + ++activityNdx; + break; + } + if (r.intent != null + && (r.intent.getFlags() & Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) { + break; + } + } + if (activityNdx > 0) { + // Traverse downwards starting below break looking for set label, icon. + // Note that if there are activities in the task but none of them set the + // recent activity values, then we do not fall back to the last set + // values in the Task. + String label = null; + String iconFilename = null; + int iconResource = -1; + int colorPrimary = 0; + int colorBackground = 0; + int statusBarColor = 0; + int navigationBarColor = 0; + boolean statusBarContrastWhenTransparent = false; + boolean navigationBarContrastWhenTransparent = false; + boolean topActivity = true; + for (--activityNdx; activityNdx >= 0; --activityNdx) { + final ActivityRecord r = getChildAt(activityNdx); + if (r.mTaskOverlay) { + continue; + } + if (r.taskDescription != null) { + if (label == null) { + label = r.taskDescription.getLabel(); + } + if (iconResource == -1) { + iconResource = r.taskDescription.getIconResource(); + } + if (iconFilename == null) { + iconFilename = r.taskDescription.getIconFilename(); + } + if (colorPrimary == 0) { + colorPrimary = r.taskDescription.getPrimaryColor(); + } + if (topActivity) { + colorBackground = r.taskDescription.getBackgroundColor(); + statusBarColor = r.taskDescription.getStatusBarColor(); + navigationBarColor = r.taskDescription.getNavigationBarColor(); + statusBarContrastWhenTransparent = + r.taskDescription.getEnsureStatusBarContrastWhenTransparent(); + navigationBarContrastWhenTransparent = + r.taskDescription.getEnsureNavigationBarContrastWhenTransparent(); + } + } + topActivity = false; + } + final TaskDescription taskDescription = new TaskDescription(label, null, iconResource, + iconFilename, colorPrimary, colorBackground, statusBarColor, navigationBarColor, + statusBarContrastWhenTransparent, navigationBarContrastWhenTransparent, + mResizeMode, mMinWidth, mMinHeight); + setTaskDescription(taskDescription); + // Update the task affiliation color if we are the parent of the group + if (mTaskId == mAffiliatedTaskId) { + mAffiliatedTaskColor = taskDescription.getPrimaryColor(); + } + mAtmService.getTaskChangeNotificationController().notifyTaskDescriptionChanged( + getTaskInfo()); + } + } + + /** + * Find the index of the root activity in the task. It will be the first activity from the + * bottom that is not finishing. + * + * @param effectiveRoot Flag indicating whether 'effective root' should be returned - an + * activity that defines the task identity (its base intent). It's the + * first one that does not have + * {@link ActivityInfo#FLAG_RELINQUISH_TASK_IDENTITY}. + * @return index of the 'root' or 'effective' root in the list of activities, -1 if no eligible + * activity was found. + */ + int findRootIndex(boolean effectiveRoot) { + int effectiveNdx = -1; + final int topActivityNdx = getChildCount() - 1; + for (int activityNdx = 0; activityNdx <= topActivityNdx; ++activityNdx) { + final ActivityRecord r = getChildAt(activityNdx); + if (r.finishing) { + continue; + } + effectiveNdx = activityNdx; + if (!effectiveRoot || (r.info.flags & FLAG_RELINQUISH_TASK_IDENTITY) == 0) { + break; + } + } + return effectiveNdx; + } + + // TODO (AM refactor): Invoke automatically when there is a change in children + @VisibleForTesting + void updateEffectiveIntent() { + int effectiveRootIndex = findRootIndex(true /* effectiveRoot */); + if (effectiveRootIndex == -1) { + // All activities in the task are either finishing or relinquish task identity. + // But we still want to update the intent, so let's use the bottom activity. + effectiveRootIndex = 0; + } + final ActivityRecord r = getChildAt(effectiveRootIndex); + setIntent(r); + + // Update the task description when the activities change + updateTaskDescription(); + } + + void adjustForMinimalTaskDimensions(Rect bounds, Rect previousBounds) { + if (bounds == null) { + return; + } + int minWidth = mMinWidth; + int minHeight = mMinHeight; + // If the task has no requested minimal size, we'd like to enforce a minimal size + // so that the user can not render the task too small to manipulate. We don't need + // to do this for the pinned stack as the bounds are controlled by the system. + if (!inPinnedWindowingMode() && mStack != null) { + final int defaultMinSizeDp = + mAtmService.mRootActivityContainer.mDefaultMinSizeOfResizeableTaskDp; + final ActivityDisplay display = + mAtmService.mRootActivityContainer.getActivityDisplay(mStack.mDisplayId); + final float density = + (float) display.getConfiguration().densityDpi / DisplayMetrics.DENSITY_DEFAULT; + final int defaultMinSize = (int) (defaultMinSizeDp * density); + + if (minWidth == INVALID_MIN_SIZE) { + minWidth = defaultMinSize; + } + if (minHeight == INVALID_MIN_SIZE) { + minHeight = defaultMinSize; + } + } + final boolean adjustWidth = minWidth > bounds.width(); + final boolean adjustHeight = minHeight > bounds.height(); + if (!(adjustWidth || adjustHeight)) { + return; + } + + if (adjustWidth) { + if (!previousBounds.isEmpty() && bounds.right == previousBounds.right) { + bounds.left = bounds.right - minWidth; + } else { + // Either left bounds match, or neither match, or the previous bounds were + // fullscreen and we default to keeping left. + bounds.right = bounds.left + minWidth; + } + } + if (adjustHeight) { + if (!previousBounds.isEmpty() && bounds.bottom == previousBounds.bottom) { + bounds.top = bounds.bottom - minHeight; + } else { + // Either top bounds match, or neither match, or the previous bounds were + // fullscreen and we default to keeping top. + bounds.bottom = bounds.top + minHeight; + } + } + } + + void setLastNonFullscreenBounds(Rect bounds) { + if (mLastNonFullscreenBounds == null) { + mLastNonFullscreenBounds = new Rect(bounds); + } else { + mLastNonFullscreenBounds.set(bounds); + } + } + + /** + * This should be called when an child activity changes state. This should only + * be called from + * {@link ActivityRecord#setState(ActivityState, String)} . + * @param record The {@link ActivityRecord} whose state has changed. + * @param state The new state. + * @param reason The reason for the change. + */ + void onActivityStateChanged(ActivityRecord record, ActivityState state, String reason) { + final ActivityStack parent = getStack(); + + if (parent != null) { + parent.onActivityStateChanged(record, state, reason); + } + } + + @Override + public void onConfigurationChanged(Configuration newParentConfig) { + // Check if the new configuration supports persistent bounds (eg. is Freeform) and if so + // restore the last recorded non-fullscreen bounds. + final boolean prevPersistTaskBounds = getWindowConfiguration().persistTaskBounds(); + final boolean nextPersistTaskBounds = + getRequestedOverrideConfiguration().windowConfiguration.persistTaskBounds() + || newParentConfig.windowConfiguration.persistTaskBounds(); + if (!prevPersistTaskBounds && nextPersistTaskBounds + && mLastNonFullscreenBounds != null && !mLastNonFullscreenBounds.isEmpty()) { + // Bypass onRequestedOverrideConfigurationChanged here to avoid infinite loop. + getRequestedOverrideConfiguration().windowConfiguration + .setBounds(mLastNonFullscreenBounds); + } + + final boolean wasInMultiWindowMode = inMultiWindowMode(); + super.onConfigurationChanged(newParentConfig); + if (wasInMultiWindowMode != inMultiWindowMode()) { + mAtmService.mStackSupervisor.scheduleUpdateMultiWindowMode(this); + } + + // If the configuration supports persistent bounds (eg. Freeform), keep track of the + // current (non-fullscreen) bounds for persistence. + if (getWindowConfiguration().persistTaskBounds()) { + final Rect currentBounds = getRequestedOverrideBounds(); + if (!currentBounds.isEmpty()) { + setLastNonFullscreenBounds(currentBounds); + } + } + // TODO: Should also take care of Pip mode changes here. + + saveLaunchingStateIfNeeded(); + } + + /** + * Saves launching state if necessary so that we can launch the activity to its latest state. + * It only saves state if this task has been shown to user and it's in fullscreen or freeform + * mode on freeform displays. + */ + void saveLaunchingStateIfNeeded() { + if (!hasBeenVisible) { + // Not ever visible to user. + return; + } + + final int windowingMode = getWindowingMode(); + if (windowingMode != WINDOWING_MODE_FULLSCREEN + && windowingMode != WINDOWING_MODE_FREEFORM) { + return; + } + + // Don't persist state if display isn't in freeform mode. Then the task will be launched + // back to its last state in a freeform display when it's launched in a freeform display + // next time. + if (getWindowConfiguration().getDisplayWindowingMode() != WINDOWING_MODE_FREEFORM) { + return; + } + + // Saves the new state so that we can launch the activity at the same location. + mAtmService.mStackSupervisor.mLaunchParamsPersister.saveTask(this); + } + + /** + * Adjust bounds to stay within stack bounds. + * + * Since bounds might be outside of stack bounds, this method tries to move the bounds in a way + * that keep them unchanged, but be contained within the stack bounds. + * + * @param bounds Bounds to be adjusted. + * @param stackBounds Bounds within which the other bounds should remain. + * @param overlapPxX The amount of px required to be visible in the X dimension. + * @param overlapPxY The amount of px required to be visible in the Y dimension. + */ + private static void fitWithinBounds(Rect bounds, Rect stackBounds, int overlapPxX, + int overlapPxY) { + if (stackBounds == null || stackBounds.isEmpty() || stackBounds.contains(bounds)) { + return; + } + + // For each side of the parent (eg. left), check if the opposing side of the window (eg. + // right) is at least overlap pixels away. If less, offset the window by that difference. + int horizontalDiff = 0; + // If window is smaller than overlap, use it's smallest dimension instead + int overlapLR = Math.min(overlapPxX, bounds.width()); + if (bounds.right < (stackBounds.left + overlapLR)) { + horizontalDiff = overlapLR - (bounds.right - stackBounds.left); + } else if (bounds.left > (stackBounds.right - overlapLR)) { + horizontalDiff = -(overlapLR - (stackBounds.right - bounds.left)); + } + int verticalDiff = 0; + int overlapTB = Math.min(overlapPxY, bounds.width()); + if (bounds.bottom < (stackBounds.top + overlapTB)) { + verticalDiff = overlapTB - (bounds.bottom - stackBounds.top); + } else if (bounds.top > (stackBounds.bottom - overlapTB)) { + verticalDiff = -(overlapTB - (stackBounds.bottom - bounds.top)); + } + bounds.offset(horizontalDiff, verticalDiff); + } + + /** + * Intersects inOutBounds with intersectBounds-intersectInsets. If inOutBounds is larger than + * intersectBounds on a side, then the respective side will not be intersected. + * + * The assumption is that if inOutBounds is initially larger than intersectBounds, then the + * inset on that side is no-longer applicable. This scenario happens when a task's minimal + * bounds are larger than the provided parent/display bounds. + * + * @param inOutBounds the bounds to intersect. + * @param intersectBounds the bounds to intersect with. + * @param intersectInsets insets to apply to intersectBounds before intersecting. + */ + static void intersectWithInsetsIfFits( + Rect inOutBounds, Rect intersectBounds, Rect intersectInsets) { + if (inOutBounds.right <= intersectBounds.right) { + inOutBounds.right = + Math.min(intersectBounds.right - intersectInsets.right, inOutBounds.right); + } + if (inOutBounds.bottom <= intersectBounds.bottom) { + inOutBounds.bottom = + Math.min(intersectBounds.bottom - intersectInsets.bottom, inOutBounds.bottom); + } + if (inOutBounds.left >= intersectBounds.left) { + inOutBounds.left = + Math.max(intersectBounds.left + intersectInsets.left, inOutBounds.left); + } + if (inOutBounds.top >= intersectBounds.top) { + inOutBounds.top = + Math.max(intersectBounds.top + intersectInsets.top, inOutBounds.top); + } + } + + /** + * Gets bounds with non-decor and stable insets applied respectively. + * + * If bounds overhangs the display, those edges will not get insets. See + * {@link #intersectWithInsetsIfFits} + * + * @param outNonDecorBounds where to place bounds with non-decor insets applied. + * @param outStableBounds where to place bounds with stable insets applied. + * @param bounds the bounds to inset. + */ + private void calculateInsetFrames(Rect outNonDecorBounds, Rect outStableBounds, Rect bounds, + DisplayInfo displayInfo) { + outNonDecorBounds.set(bounds); + outStableBounds.set(bounds); + if (getStack() == null || getStack().getDisplay() == null) { + return; + } + DisplayPolicy policy = getStack().getDisplay().mDisplayContent.getDisplayPolicy(); + if (policy == null) { + return; + } + mTmpBounds.set(0, 0, displayInfo.logicalWidth, displayInfo.logicalHeight); + + policy.getNonDecorInsetsLw(displayInfo.rotation, displayInfo.logicalWidth, + displayInfo.logicalHeight, displayInfo.displayCutout, mTmpInsets); + intersectWithInsetsIfFits(outNonDecorBounds, mTmpBounds, mTmpInsets); + + policy.convertNonDecorInsetsToStableInsets(mTmpInsets, displayInfo.rotation); + intersectWithInsetsIfFits(outStableBounds, mTmpBounds, mTmpInsets); + } + + /** + * Asks docked-divider controller for the smallestwidthdp given bounds. + * @param bounds bounds to calculate smallestwidthdp for. + */ + private int getSmallestScreenWidthDpForDockedBounds(Rect bounds) { + DisplayContent dc = mStack.getDisplay().mDisplayContent; + if (dc != null) { + return dc.getDockedDividerController().getSmallestWidthDpForBounds(bounds); + } + return Configuration.SMALLEST_SCREEN_WIDTH_DP_UNDEFINED; + } + + void computeConfigResourceOverrides(@NonNull Configuration inOutConfig, + @NonNull Configuration parentConfig) { + computeConfigResourceOverrides(inOutConfig, parentConfig, null /* compatInsets */); + } + + /** + * Calculates configuration values used by the client to get resources. This should be run + * using app-facing bounds (bounds unmodified by animations or transient interactions). + * + * This assumes bounds are non-empty/null. For the null-bounds case, the caller is likely + * configuring an "inherit-bounds" window which means that all configuration settings would + * just be inherited from the parent configuration. + **/ + void computeConfigResourceOverrides(@NonNull Configuration inOutConfig, + @NonNull Configuration parentConfig, + @Nullable ActivityRecord.CompatDisplayInsets compatInsets) { + int windowingMode = inOutConfig.windowConfiguration.getWindowingMode(); + if (windowingMode == WINDOWING_MODE_UNDEFINED) { + windowingMode = parentConfig.windowConfiguration.getWindowingMode(); + } + + float density = inOutConfig.densityDpi; + if (density == Configuration.DENSITY_DPI_UNDEFINED) { + density = parentConfig.densityDpi; + } + density *= DisplayMetrics.DENSITY_DEFAULT_SCALE; + + final Rect bounds = inOutConfig.windowConfiguration.getBounds(); + Rect outAppBounds = inOutConfig.windowConfiguration.getAppBounds(); + if (outAppBounds == null || outAppBounds.isEmpty()) { + inOutConfig.windowConfiguration.setAppBounds(bounds); + outAppBounds = inOutConfig.windowConfiguration.getAppBounds(); + } + // Non-null compatibility insets means the activity prefers to keep its original size, so + // the out bounds doesn't need to be restricted by the parent. + final boolean insideParentBounds = compatInsets == null; + if (insideParentBounds && windowingMode != WINDOWING_MODE_FREEFORM) { + final Rect parentAppBounds = parentConfig.windowConfiguration.getAppBounds(); + if (parentAppBounds != null && !parentAppBounds.isEmpty()) { + outAppBounds.intersect(parentAppBounds); + } + } + + if (inOutConfig.screenWidthDp == Configuration.SCREEN_WIDTH_DP_UNDEFINED + || inOutConfig.screenHeightDp == Configuration.SCREEN_HEIGHT_DP_UNDEFINED) { + if (insideParentBounds && mStack != null) { + final DisplayInfo di = new DisplayInfo(); + mStack.getDisplay().mDisplay.getDisplayInfo(di); + + // For calculating screenWidthDp, screenWidthDp, we use the stable inset screen + // area, i.e. the screen area without the system bars. + // The non decor inset are areas that could never be removed in Honeycomb. See + // {@link WindowManagerPolicy#getNonDecorInsetsLw}. + calculateInsetFrames(mTmpNonDecorBounds, mTmpStableBounds, bounds, di); + } else { + // Apply the given non-decor and stable insets to calculate the corresponding bounds + // for screen size of configuration. + int rotation = inOutConfig.windowConfiguration.getRotation(); + if (rotation == ROTATION_UNDEFINED) { + rotation = parentConfig.windowConfiguration.getRotation(); + } + if (rotation != ROTATION_UNDEFINED && compatInsets != null) { + mTmpNonDecorBounds.set(bounds); + mTmpStableBounds.set(bounds); + compatInsets.getDisplayBoundsByRotation(mTmpBounds, rotation); + intersectWithInsetsIfFits(mTmpNonDecorBounds, mTmpBounds, + compatInsets.mNonDecorInsets[rotation]); + intersectWithInsetsIfFits(mTmpStableBounds, mTmpBounds, + compatInsets.mStableInsets[rotation]); + outAppBounds.set(mTmpNonDecorBounds); + } else { + // Set to app bounds because it excludes decor insets. + mTmpNonDecorBounds.set(outAppBounds); + mTmpStableBounds.set(outAppBounds); + } + } + + if (inOutConfig.screenWidthDp == Configuration.SCREEN_WIDTH_DP_UNDEFINED) { + final int overrideScreenWidthDp = (int) (mTmpStableBounds.width() / density); + inOutConfig.screenWidthDp = insideParentBounds + ? Math.min(overrideScreenWidthDp, parentConfig.screenWidthDp) + : overrideScreenWidthDp; + } + if (inOutConfig.screenHeightDp == Configuration.SCREEN_HEIGHT_DP_UNDEFINED) { + final int overrideScreenHeightDp = (int) (mTmpStableBounds.height() / density); + inOutConfig.screenHeightDp = insideParentBounds + ? Math.min(overrideScreenHeightDp, parentConfig.screenHeightDp) + : overrideScreenHeightDp; + } + + if (inOutConfig.smallestScreenWidthDp + == Configuration.SMALLEST_SCREEN_WIDTH_DP_UNDEFINED) { + if (WindowConfiguration.isFloating(windowingMode)) { + // For floating tasks, calculate the smallest width from the bounds of the task + inOutConfig.smallestScreenWidthDp = (int) ( + Math.min(bounds.width(), bounds.height()) / density); + } else if (WindowConfiguration.isSplitScreenWindowingMode(windowingMode)) { + // Iterating across all screen orientations, and return the minimum of the task + // width taking into account that the bounds might change because the snap + // algorithm snaps to a different value + inOutConfig.smallestScreenWidthDp = + getSmallestScreenWidthDpForDockedBounds(bounds); + } + // otherwise, it will just inherit + } + } + + if (inOutConfig.orientation == ORIENTATION_UNDEFINED) { + inOutConfig.orientation = (inOutConfig.screenWidthDp <= inOutConfig.screenHeightDp) + ? ORIENTATION_PORTRAIT : ORIENTATION_LANDSCAPE; + } + if (inOutConfig.screenLayout == Configuration.SCREENLAYOUT_UNDEFINED) { + // For calculating screen layout, we need to use the non-decor inset screen area for the + // calculation for compatibility reasons, i.e. screen area without system bars that + // could never go away in Honeycomb. + final int compatScreenWidthDp = (int) (mTmpNonDecorBounds.width() / density); + final int compatScreenHeightDp = (int) (mTmpNonDecorBounds.height() / density); + // We're only overriding LONG, SIZE and COMPAT parts of screenLayout, so we start + // override calculation with partial default. + // Reducing the screen layout starting from its parent config. + final int sl = parentConfig.screenLayout + & (Configuration.SCREENLAYOUT_LONG_MASK | Configuration.SCREENLAYOUT_SIZE_MASK); + final int longSize = Math.max(compatScreenHeightDp, compatScreenWidthDp); + final int shortSize = Math.min(compatScreenHeightDp, compatScreenWidthDp); + inOutConfig.screenLayout = Configuration.reduceScreenLayout(sl, longSize, shortSize); + } + } + + @Override + void resolveOverrideConfiguration(Configuration newParentConfig) { + mTmpBounds.set(getResolvedOverrideConfiguration().windowConfiguration.getBounds()); + super.resolveOverrideConfiguration(newParentConfig); + int windowingMode = + getRequestedOverrideConfiguration().windowConfiguration.getWindowingMode(); + if (windowingMode == WINDOWING_MODE_UNDEFINED) { + windowingMode = newParentConfig.windowConfiguration.getWindowingMode(); + } + Rect outOverrideBounds = + getResolvedOverrideConfiguration().windowConfiguration.getBounds(); + + if (windowingMode == WINDOWING_MODE_FULLSCREEN) { + computeFullscreenBounds(outOverrideBounds, null /* refActivity */, + newParentConfig.windowConfiguration.getBounds(), + newParentConfig.orientation); + } + + if (outOverrideBounds.isEmpty()) { + // If the task fills the parent, just inherit all the other configs from parent. + return; + } + + adjustForMinimalTaskDimensions(outOverrideBounds, mTmpBounds); + if (windowingMode == WINDOWING_MODE_FREEFORM) { + // by policy, make sure the window remains within parent somewhere + final float density = + ((float) newParentConfig.densityDpi) / DisplayMetrics.DENSITY_DEFAULT; + final Rect parentBounds = + new Rect(newParentConfig.windowConfiguration.getBounds()); + final ActivityDisplay display = mStack.getDisplay(); + if (display != null && display.mDisplayContent != null) { + // If a freeform window moves below system bar, there is no way to move it again + // by touch. Because its caption is covered by system bar. So we exclude them + // from stack bounds. and then caption will be shown inside stable area. + final Rect stableBounds = new Rect(); + display.mDisplayContent.getStableRect(stableBounds); + parentBounds.intersect(stableBounds); + } + + fitWithinBounds(outOverrideBounds, parentBounds, + (int) (density * WindowState.MINIMUM_VISIBLE_WIDTH_IN_DP), + (int) (density * WindowState.MINIMUM_VISIBLE_HEIGHT_IN_DP)); + + // Prevent to overlap caption with stable insets. + final int offsetTop = parentBounds.top - outOverrideBounds.top; + if (offsetTop > 0) { + outOverrideBounds.offset(0, offsetTop); + } + } + computeConfigResourceOverrides(getResolvedOverrideConfiguration(), newParentConfig); + } + + /** + * Compute bounds (letterbox or pillarbox) for + * {@link WindowConfiguration#WINDOWING_MODE_FULLSCREEN} when the parent doesn't handle the + * orientation change and the requested orientation is different from the parent. + */ + void computeFullscreenBounds(@NonNull Rect outBounds, @Nullable ActivityRecord refActivity, + @NonNull Rect parentBounds, int parentOrientation) { + // In FULLSCREEN mode, always start with empty bounds to indicate "fill parent". + outBounds.setEmpty(); + if (handlesOrientationChangeFromDescendant()) { + return; + } + if (refActivity == null) { + // Use the top activity as the reference of orientation. Don't include overlays because + // it is usually not the actual content or just temporarily shown. + // E.g. ForcedResizableInfoActivity. + refActivity = getTopActivity(false /* includeOverlays */); + } + + // If the task or the reference activity requires a different orientation (either by + // override or activityInfo), make it fit the available bounds by scaling down its bounds. + final int overrideOrientation = getRequestedOverrideConfiguration().orientation; + final int forcedOrientation = + (overrideOrientation != ORIENTATION_UNDEFINED || refActivity == null) + ? overrideOrientation : refActivity.getRequestedConfigurationOrientation(); + if (forcedOrientation == ORIENTATION_UNDEFINED || forcedOrientation == parentOrientation) { + return; + } + + final int parentWidth = parentBounds.width(); + final int parentHeight = parentBounds.height(); + final float aspect = ((float) parentHeight) / parentWidth; + if (forcedOrientation == ORIENTATION_LANDSCAPE) { + final int height = (int) (parentWidth / aspect); + final int top = parentBounds.centerY() - height / 2; + outBounds.set(parentBounds.left, top, parentBounds.right, top + height); + } else { + final int width = (int) (parentHeight * aspect); + final int left = parentBounds.centerX() - width / 2; + outBounds.set(left, parentBounds.top, left + width, parentBounds.bottom); + } + } + + Rect updateOverrideConfigurationFromLaunchBounds() { + final Rect bounds = getLaunchBounds(); + setBounds(bounds); + if (bounds != null && !bounds.isEmpty()) { + // TODO: Review if we actually want to do this - we are setting the launch bounds + // directly here. + bounds.set(getRequestedOverrideBounds()); + } + return bounds; + } + + /** Updates the task's bounds and override configuration to match what is expected for the + * input stack. */ + void updateOverrideConfigurationForStack(ActivityStack inStack) { + if (mStack != null && mStack == inStack) { + return; + } + + if (inStack.inFreeformWindowingMode()) { + if (!isResizeable()) { + throw new IllegalArgumentException("Can not position non-resizeable task=" + + this + " in stack=" + inStack); + } + if (!matchParentBounds()) { + return; + } + if (mLastNonFullscreenBounds != null) { + setBounds(mLastNonFullscreenBounds); + } else { + mAtmService.mStackSupervisor.getLaunchParamsController().layoutTask(this, null); + } + } else { + setBounds(inStack.getRequestedOverrideBounds()); + } + } + + /** Returns the bounds that should be used to launch this task. */ + Rect getLaunchBounds() { + if (mStack == null) { + return null; + } + + final int windowingMode = getWindowingMode(); + if (!isActivityTypeStandardOrUndefined() + || windowingMode == WINDOWING_MODE_FULLSCREEN + || (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY && !isResizeable())) { + return isResizeable() ? mStack.getRequestedOverrideBounds() : null; + } else if (!getWindowConfiguration().persistTaskBounds()) { + return mStack.getRequestedOverrideBounds(); + } + return mLastNonFullscreenBounds; + } + + void addStartingWindowsForVisibleActivities(boolean taskSwitch) { + for (int activityNdx = getChildCount() - 1; activityNdx >= 0; --activityNdx) { + final ActivityRecord r = getChildAt(activityNdx); + if (r.visible) { + r.showStartingWindow(null /* prev */, false /* newTask */, taskSwitch); + } + } + } + + void setRootProcess(WindowProcessController proc) { + clearRootProcess(); + if (intent != null + && (intent.getFlags() & Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0) { + mRootProcess = proc; + mRootProcess.addRecentTask(this); + } + } + + void clearRootProcess() { + if (mRootProcess != null) { + mRootProcess.removeRecentTask(this); + mRootProcess = null; + } + } + + void clearAllPendingOptions() { + for (int i = getChildCount() - 1; i >= 0; i--) { + getChildAt(i).clearOptionsLocked(false /* withAbort */); + } } @Override @@ -204,15 +2301,6 @@ class Task extends WindowContainer implements ConfigurationConta return hasWindowsAlive() && getTaskStack().isAnimating(TRANSITION | CHILDREN); } - @Override - void removeIfPossible() { - if (shouldDeferRemoval()) { - if (DEBUG_STACK) Slog.i(TAG, "removeTask: deferring removing taskId=" + mTaskId); - return; - } - removeImmediately(); - } - @Override void removeImmediately() { if (DEBUG_STACK) Slog.i(TAG, "removeTask: removing taskId=" + mTaskId); @@ -220,7 +2308,7 @@ class Task extends WindowContainer implements ConfigurationConta super.removeImmediately(); } - // TODO: Consolidate this with TaskRecord.reparent() + // TODO: Consolidate this with Task.reparent() void reparent(TaskStack stack, int position, boolean moveParents, String reason) { if (DEBUG_STACK) Slog.i(TAG, "reParentTask: removing taskId=" + mTaskId + " from stack=" + getTaskStack()); @@ -241,8 +2329,7 @@ class Task extends WindowContainer implements ConfigurationConta prevStack.moveHomeStackToFrontIfNeeded(wasTopFocusedStack, prevStackDisplay, reason); } - // TODO(task-merge): Remove cast. - stack.positionChildAt(position, (TaskRecord) this, moveParents); + stack.positionChildAt(position, this, moveParents); // If we are moving from the fullscreen stack to the pinned stack then we want to preserve // our insets so that there will not be a jump in the area covered by system decorations. @@ -744,7 +2831,7 @@ class Task extends WindowContainer implements ConfigurationConta } String getName() { - return toShortString(); + return "Task=" + mTaskId; } void clearPreserveNonFloatingState() { @@ -778,13 +2865,13 @@ class Task extends WindowContainer implements ConfigurationConta final long token = proto.start(fieldId); super.writeToProto(proto, WINDOW_CONTAINER, logLevel); - proto.write(ID, mTaskId); + proto.write(TaskProto.ID, mTaskId); for (int i = mChildren.size() - 1; i >= 0; i--) { final ActivityRecord activity = mChildren.get(i); activity.writeToProto(proto, APP_WINDOW_TOKENS, logLevel); } proto.write(FILLS_PARENT, matchParentBounds()); - getBounds().writeToProto(proto, BOUNDS); + getBounds().writeToProto(proto, TaskProto.BOUNDS); mOverrideDisplayedBounds.writeToProto(proto, DISPLAYED_BOUNDS); if (mSurfaceControl != null) { proto.write(SURFACE_WIDTH, mSurfaceControl.getWidth()); @@ -813,7 +2900,609 @@ class Task extends WindowContainer implements ConfigurationConta } } - String toShortString() { - return "Task=" + mTaskId; + /** + * Fills in a {@link TaskInfo} with information from this task. + * @param info the {@link TaskInfo} to fill in + */ + void fillTaskInfo(TaskInfo info) { + getNumRunningActivities(mReuseActivitiesReport); + info.userId = mUserId; + info.stackId = getStackId(); + info.taskId = mTaskId; + info.displayId = mStack == null ? Display.INVALID_DISPLAY : mStack.mDisplayId; + info.isRunning = getTopActivity() != null; + info.baseIntent = new Intent(getBaseIntent()); + info.baseActivity = mReuseActivitiesReport.base != null + ? mReuseActivitiesReport.base.intent.getComponent() + : null; + info.topActivity = mReuseActivitiesReport.top != null + ? mReuseActivitiesReport.top.mActivityComponent + : null; + info.origActivity = origActivity; + info.realActivity = realActivity; + info.numActivities = mReuseActivitiesReport.numActivities; + info.lastActiveTime = lastActiveTime; + info.taskDescription = new ActivityManager.TaskDescription(getTaskDescription()); + info.supportsSplitScreenMultiWindow = supportsSplitScreenWindowingMode(); + info.resizeMode = mResizeMode; + info.configuration.setTo(getConfiguration()); + } + + /** + * Returns a {@link TaskInfo} with information from this task. + */ + ActivityManager.RunningTaskInfo getTaskInfo() { + ActivityManager.RunningTaskInfo info = new ActivityManager.RunningTaskInfo(); + fillTaskInfo(info); + return info; + } + + void dump(PrintWriter pw, String prefix) { + pw.print(prefix); pw.print("userId="); pw.print(mUserId); + pw.print(" effectiveUid="); UserHandle.formatUid(pw, effectiveUid); + pw.print(" mCallingUid="); UserHandle.formatUid(pw, mCallingUid); + pw.print(" mUserSetupComplete="); pw.print(mUserSetupComplete); + pw.print(" mCallingPackage="); pw.println(mCallingPackage); + if (affinity != null || rootAffinity != null) { + pw.print(prefix); pw.print("affinity="); pw.print(affinity); + if (affinity == null || !affinity.equals(rootAffinity)) { + pw.print(" root="); pw.println(rootAffinity); + } else { + pw.println(); + } + } + if (voiceSession != null || voiceInteractor != null) { + pw.print(prefix); pw.print("VOICE: session=0x"); + pw.print(Integer.toHexString(System.identityHashCode(voiceSession))); + pw.print(" interactor=0x"); + pw.println(Integer.toHexString(System.identityHashCode(voiceInteractor))); + } + if (intent != null) { + StringBuilder sb = new StringBuilder(128); + sb.append(prefix); sb.append("intent={"); + intent.toShortString(sb, false, true, false, false); + sb.append('}'); + pw.println(sb.toString()); + } + if (affinityIntent != null) { + StringBuilder sb = new StringBuilder(128); + sb.append(prefix); sb.append("affinityIntent={"); + affinityIntent.toShortString(sb, false, true, false, false); + sb.append('}'); + pw.println(sb.toString()); + } + if (origActivity != null) { + pw.print(prefix); pw.print("origActivity="); + pw.println(origActivity.flattenToShortString()); + } + if (realActivity != null) { + pw.print(prefix); pw.print("mActivityComponent="); + pw.println(realActivity.flattenToShortString()); + } + if (autoRemoveRecents || isPersistable || !isActivityTypeStandard() || numFullscreen != 0) { + pw.print(prefix); pw.print("autoRemoveRecents="); pw.print(autoRemoveRecents); + pw.print(" isPersistable="); pw.print(isPersistable); + pw.print(" numFullscreen="); pw.print(numFullscreen); + pw.print(" activityType="); pw.println(getActivityType()); + } + if (rootWasReset || mNeverRelinquishIdentity || mReuseTask + || mLockTaskAuth != LOCK_TASK_AUTH_PINNABLE) { + pw.print(prefix); pw.print("rootWasReset="); pw.print(rootWasReset); + pw.print(" mNeverRelinquishIdentity="); pw.print(mNeverRelinquishIdentity); + pw.print(" mReuseTask="); pw.print(mReuseTask); + pw.print(" mLockTaskAuth="); pw.println(lockTaskAuthToString()); + } + if (mAffiliatedTaskId != mTaskId || mPrevAffiliateTaskId != INVALID_TASK_ID + || mPrevAffiliate != null || mNextAffiliateTaskId != INVALID_TASK_ID + || mNextAffiliate != null) { + pw.print(prefix); pw.print("affiliation="); pw.print(mAffiliatedTaskId); + pw.print(" prevAffiliation="); pw.print(mPrevAffiliateTaskId); + pw.print(" ("); + if (mPrevAffiliate == null) { + pw.print("null"); + } else { + pw.print(Integer.toHexString(System.identityHashCode(mPrevAffiliate))); + } + pw.print(") nextAffiliation="); pw.print(mNextAffiliateTaskId); + pw.print(" ("); + if (mNextAffiliate == null) { + pw.print("null"); + } else { + pw.print(Integer.toHexString(System.identityHashCode(mNextAffiliate))); + } + pw.println(")"); + } + pw.print(prefix); pw.print("Activities="); pw.println(mChildren); + if (!askedCompatMode || !inRecents || !isAvailable) { + pw.print(prefix); pw.print("askedCompatMode="); pw.print(askedCompatMode); + pw.print(" inRecents="); pw.print(inRecents); + pw.print(" isAvailable="); pw.println(isAvailable); + } + if (lastDescription != null) { + pw.print(prefix); pw.print("lastDescription="); pw.println(lastDescription); + } + if (mRootProcess != null) { + pw.print(prefix); pw.print("mRootProcess="); pw.println(mRootProcess); + } + pw.print(prefix); pw.print("stackId="); pw.println(getStackId()); + pw.print(prefix + "hasBeenVisible=" + hasBeenVisible); + pw.print(" mResizeMode=" + ActivityInfo.resizeModeToString(mResizeMode)); + pw.print(" mSupportsPictureInPicture=" + mSupportsPictureInPicture); + pw.print(" isResizeable=" + isResizeable()); + pw.print(" lastActiveTime=" + lastActiveTime); + pw.println(" (inactive for " + (getInactiveDuration() / 1000) + "s)"); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(128); + if (stringName != null) { + sb.append(stringName); + sb.append(" U="); + sb.append(mUserId); + sb.append(" StackId="); + sb.append(getStackId()); + sb.append(" sz="); + sb.append(getChildCount()); + sb.append('}'); + return sb.toString(); + } + sb.append("Task{"); + sb.append(Integer.toHexString(System.identityHashCode(this))); + sb.append(" #"); + sb.append(mTaskId); + if (affinity != null) { + sb.append(" A="); + sb.append(affinity); + } else if (intent != null) { + sb.append(" I="); + sb.append(intent.getComponent().flattenToShortString()); + } else if (affinityIntent != null && affinityIntent.getComponent() != null) { + sb.append(" aI="); + sb.append(affinityIntent.getComponent().flattenToShortString()); + } else { + sb.append(" ??"); + } + stringName = sb.toString(); + return toString(); + } + + @Override + public void writeToProto(ProtoOutputStream proto, long fieldId, + @WindowTraceLogLevel int logLevel) { + if (logLevel == WindowTraceLogLevel.CRITICAL && !isVisible()) { + return; + } + + final long token = proto.start(fieldId); + writeToProtoInnerTaskOnly(proto, TASK, logLevel); + proto.write(com.android.server.am.TaskRecordProto.ID, mTaskId); + for (int i = getChildCount() - 1; i >= 0; i--) { + final ActivityRecord activity = getChildAt(i); + activity.writeToProto(proto, ACTIVITIES); + } + proto.write(STACK_ID, getStackId()); + if (mLastNonFullscreenBounds != null) { + mLastNonFullscreenBounds.writeToProto(proto, LAST_NON_FULLSCREEN_BOUNDS); + } + if (realActivity != null) { + proto.write(REAL_ACTIVITY, realActivity.flattenToShortString()); + } + if (origActivity != null) { + proto.write(ORIG_ACTIVITY, origActivity.flattenToShortString()); + } + proto.write(ACTIVITY_TYPE, getActivityType()); + proto.write(RESIZE_MODE, mResizeMode); + // TODO: Remove, no longer needed with windowingMode. + proto.write(FULLSCREEN, matchParentBounds()); + + if (!matchParentBounds()) { + final Rect bounds = getRequestedOverrideBounds(); + bounds.writeToProto(proto, com.android.server.am.TaskRecordProto.BOUNDS); + } + proto.write(MIN_WIDTH, mMinWidth); + proto.write(MIN_HEIGHT, mMinHeight); + proto.end(token); + } + + /** @see #getNumRunningActivities(TaskActivitiesReport) */ + static class TaskActivitiesReport { + int numRunning; + int numActivities; + ActivityRecord top; + ActivityRecord base; + + void reset() { + numRunning = numActivities = 0; + top = base = null; + } + } + + /** + * Saves this {@link Task} to XML using given serializer. + */ + void saveToXml(XmlSerializer out) throws IOException, XmlPullParserException { + if (DEBUG_RECENTS) Slog.i(TAG_RECENTS, "Saving task=" + this); + + out.attribute(null, ATTR_TASKID, String.valueOf(mTaskId)); + if (realActivity != null) { + out.attribute(null, ATTR_REALACTIVITY, realActivity.flattenToShortString()); + } + out.attribute(null, ATTR_REALACTIVITY_SUSPENDED, String.valueOf(realActivitySuspended)); + if (origActivity != null) { + out.attribute(null, ATTR_ORIGACTIVITY, origActivity.flattenToShortString()); + } + // Write affinity, and root affinity if it is different from affinity. + // We use the special string "@" for a null root affinity, so we can identify + // later whether we were given a root affinity or should just make it the + // same as the affinity. + if (affinity != null) { + out.attribute(null, ATTR_AFFINITY, affinity); + if (!affinity.equals(rootAffinity)) { + out.attribute(null, ATTR_ROOT_AFFINITY, rootAffinity != null ? rootAffinity : "@"); + } + } else if (rootAffinity != null) { + out.attribute(null, ATTR_ROOT_AFFINITY, rootAffinity != null ? rootAffinity : "@"); + } + out.attribute(null, ATTR_ROOTHASRESET, String.valueOf(rootWasReset)); + out.attribute(null, ATTR_AUTOREMOVERECENTS, String.valueOf(autoRemoveRecents)); + out.attribute(null, ATTR_ASKEDCOMPATMODE, String.valueOf(askedCompatMode)); + out.attribute(null, ATTR_USERID, String.valueOf(mUserId)); + out.attribute(null, ATTR_USER_SETUP_COMPLETE, String.valueOf(mUserSetupComplete)); + out.attribute(null, ATTR_EFFECTIVE_UID, String.valueOf(effectiveUid)); + out.attribute(null, ATTR_LASTTIMEMOVED, String.valueOf(mLastTimeMoved)); + out.attribute(null, ATTR_NEVERRELINQUISH, String.valueOf(mNeverRelinquishIdentity)); + if (lastDescription != null) { + out.attribute(null, ATTR_LASTDESCRIPTION, lastDescription.toString()); + } + if (getTaskDescription() != null) { + getTaskDescription().saveToXml(out); + } + out.attribute(null, ATTR_TASK_AFFILIATION_COLOR, String.valueOf(mAffiliatedTaskColor)); + out.attribute(null, ATTR_TASK_AFFILIATION, String.valueOf(mAffiliatedTaskId)); + out.attribute(null, ATTR_PREV_AFFILIATION, String.valueOf(mPrevAffiliateTaskId)); + out.attribute(null, ATTR_NEXT_AFFILIATION, String.valueOf(mNextAffiliateTaskId)); + out.attribute(null, ATTR_CALLING_UID, String.valueOf(mCallingUid)); + out.attribute(null, ATTR_CALLING_PACKAGE, mCallingPackage == null ? "" : mCallingPackage); + out.attribute(null, ATTR_RESIZE_MODE, String.valueOf(mResizeMode)); + out.attribute(null, ATTR_SUPPORTS_PICTURE_IN_PICTURE, + String.valueOf(mSupportsPictureInPicture)); + if (mLastNonFullscreenBounds != null) { + out.attribute( + null, ATTR_NON_FULLSCREEN_BOUNDS, mLastNonFullscreenBounds.flattenToString()); + } + out.attribute(null, ATTR_MIN_WIDTH, String.valueOf(mMinWidth)); + out.attribute(null, ATTR_MIN_HEIGHT, String.valueOf(mMinHeight)); + out.attribute(null, ATTR_PERSIST_TASK_VERSION, String.valueOf(PERSIST_TASK_VERSION)); + + if (affinityIntent != null) { + out.startTag(null, TAG_AFFINITYINTENT); + affinityIntent.saveToXml(out); + out.endTag(null, TAG_AFFINITYINTENT); + } + + if (intent != null) { + out.startTag(null, TAG_INTENT); + intent.saveToXml(out); + out.endTag(null, TAG_INTENT); + } + + final int numActivities = getChildCount(); + for (int activityNdx = 0; activityNdx < numActivities; ++activityNdx) { + final ActivityRecord r = getChildAt(activityNdx); + if (r.info.persistableMode == ActivityInfo.PERSIST_ROOT_ONLY || !r.isPersistable() + || ((r.intent.getFlags() & FLAG_ACTIVITY_NEW_DOCUMENT + | FLAG_ACTIVITY_RETAIN_IN_RECENTS) == FLAG_ACTIVITY_NEW_DOCUMENT) + && activityNdx > 0) { + // Stop at first non-persistable or first break in task (CLEAR_WHEN_TASK_RESET). + break; + } + out.startTag(null, TAG_ACTIVITY); + r.saveToXml(out); + out.endTag(null, TAG_ACTIVITY); + } + } + + @VisibleForTesting + static TaskFactory getTaskFactory() { + if (sTaskFactory == null) { + setTaskFactory(new TaskFactory()); + } + return sTaskFactory; + } + + static void setTaskFactory(TaskFactory factory) { + sTaskFactory = factory; + } + + static Task create(ActivityTaskManagerService service, int taskId, ActivityInfo info, + Intent intent, IVoiceInteractionSession voiceSession, + IVoiceInteractor voiceInteractor, ActivityStack stack) { + return getTaskFactory().create( + service, taskId, info, intent, voiceSession, voiceInteractor, stack); + } + + static Task create(ActivityTaskManagerService service, int taskId, ActivityInfo info, + Intent intent, TaskDescription taskDescription, ActivityStack stack) { + return getTaskFactory().create(service, taskId, info, intent, taskDescription, stack); + } + + static Task restoreFromXml(XmlPullParser in, ActivityStackSupervisor stackSupervisor) + throws IOException, XmlPullParserException { + return getTaskFactory().restoreFromXml(in, stackSupervisor); + } + + /** + * A factory class used to create {@link Task} or its subclass if any. This can be + * specified when system boots by setting it with + * {@link #setTaskFactory(TaskFactory)}. + */ + static class TaskFactory { + + Task create(ActivityTaskManagerService service, int taskId, ActivityInfo info, + Intent intent, IVoiceInteractionSession voiceSession, + IVoiceInteractor voiceInteractor, ActivityStack stack) { + return new Task(service, taskId, info, intent, voiceSession, voiceInteractor, + null /*taskDescription*/, stack); + } + + Task create(ActivityTaskManagerService service, int taskId, ActivityInfo info, + Intent intent, TaskDescription taskDescription, ActivityStack stack) { + return new Task(service, taskId, info, intent, null /*voiceSession*/, + null /*voiceInteractor*/, taskDescription, stack); + } + + /** + * Should only be used when we're restoring {@link Task} from storage. + */ + Task create(ActivityTaskManagerService service, int taskId, Intent intent, + Intent affinityIntent, String affinity, String rootAffinity, + ComponentName realActivity, ComponentName origActivity, boolean rootWasReset, + boolean autoRemoveRecents, boolean askedCompatMode, int userId, + int effectiveUid, String lastDescription, + long lastTimeMoved, boolean neverRelinquishIdentity, + TaskDescription lastTaskDescription, int taskAffiliation, int prevTaskId, + int nextTaskId, int taskAffiliationColor, int callingUid, String callingPackage, + int resizeMode, boolean supportsPictureInPicture, boolean realActivitySuspended, + boolean userSetupComplete, int minWidth, int minHeight, ActivityStack stack) { + return new Task(service, taskId, intent, affinityIntent, affinity, + rootAffinity, realActivity, origActivity, rootWasReset, autoRemoveRecents, + askedCompatMode, userId, effectiveUid, lastDescription, + lastTimeMoved, neverRelinquishIdentity, lastTaskDescription, taskAffiliation, + prevTaskId, nextTaskId, taskAffiliationColor, callingUid, callingPackage, + resizeMode, supportsPictureInPicture, realActivitySuspended, userSetupComplete, + minWidth, minHeight, null /*ActivityInfo*/, null /*_voiceSession*/, + null /*_voiceInteractor*/, stack); + } + + Task restoreFromXml(XmlPullParser in, ActivityStackSupervisor stackSupervisor) + throws IOException, XmlPullParserException { + Intent intent = null; + Intent affinityIntent = null; + ArrayList activities = new ArrayList<>(); + ComponentName realActivity = null; + boolean realActivitySuspended = false; + ComponentName origActivity = null; + String affinity = null; + String rootAffinity = null; + boolean hasRootAffinity = false; + boolean rootHasReset = false; + boolean autoRemoveRecents = false; + boolean askedCompatMode = false; + int taskType = 0; + int userId = 0; + boolean userSetupComplete = true; + int effectiveUid = -1; + String lastDescription = null; + long lastTimeOnTop = 0; + boolean neverRelinquishIdentity = true; + int taskId = INVALID_TASK_ID; + final int outerDepth = in.getDepth(); + TaskDescription taskDescription = new TaskDescription(); + int taskAffiliation = INVALID_TASK_ID; + int taskAffiliationColor = 0; + int prevTaskId = INVALID_TASK_ID; + int nextTaskId = INVALID_TASK_ID; + int callingUid = -1; + String callingPackage = ""; + int resizeMode = RESIZE_MODE_FORCE_RESIZEABLE; + boolean supportsPictureInPicture = false; + Rect lastNonFullscreenBounds = null; + int minWidth = INVALID_MIN_SIZE; + int minHeight = INVALID_MIN_SIZE; + int persistTaskVersion = 0; + + for (int attrNdx = in.getAttributeCount() - 1; attrNdx >= 0; --attrNdx) { + final String attrName = in.getAttributeName(attrNdx); + final String attrValue = in.getAttributeValue(attrNdx); + if (TaskPersister.DEBUG) Slog.d(TaskPersister.TAG, "Task: attribute name=" + + attrName + " value=" + attrValue); + switch (attrName) { + case ATTR_TASKID: + if (taskId == INVALID_TASK_ID) taskId = Integer.parseInt(attrValue); + break; + case ATTR_REALACTIVITY: + realActivity = ComponentName.unflattenFromString(attrValue); + break; + case ATTR_REALACTIVITY_SUSPENDED: + realActivitySuspended = Boolean.valueOf(attrValue); + break; + case ATTR_ORIGACTIVITY: + origActivity = ComponentName.unflattenFromString(attrValue); + break; + case ATTR_AFFINITY: + affinity = attrValue; + break; + case ATTR_ROOT_AFFINITY: + rootAffinity = attrValue; + hasRootAffinity = true; + break; + case ATTR_ROOTHASRESET: + rootHasReset = Boolean.parseBoolean(attrValue); + break; + case ATTR_AUTOREMOVERECENTS: + autoRemoveRecents = Boolean.parseBoolean(attrValue); + break; + case ATTR_ASKEDCOMPATMODE: + askedCompatMode = Boolean.parseBoolean(attrValue); + break; + case ATTR_USERID: + userId = Integer.parseInt(attrValue); + break; + case ATTR_USER_SETUP_COMPLETE: + userSetupComplete = Boolean.parseBoolean(attrValue); + break; + case ATTR_EFFECTIVE_UID: + effectiveUid = Integer.parseInt(attrValue); + break; + case ATTR_TASKTYPE: + taskType = Integer.parseInt(attrValue); + break; + case ATTR_LASTDESCRIPTION: + lastDescription = attrValue; + break; + case ATTR_LASTTIMEMOVED: + lastTimeOnTop = Long.parseLong(attrValue); + break; + case ATTR_NEVERRELINQUISH: + neverRelinquishIdentity = Boolean.parseBoolean(attrValue); + break; + case ATTR_TASK_AFFILIATION: + taskAffiliation = Integer.parseInt(attrValue); + break; + case ATTR_PREV_AFFILIATION: + prevTaskId = Integer.parseInt(attrValue); + break; + case ATTR_NEXT_AFFILIATION: + nextTaskId = Integer.parseInt(attrValue); + break; + case ATTR_TASK_AFFILIATION_COLOR: + taskAffiliationColor = Integer.parseInt(attrValue); + break; + case ATTR_CALLING_UID: + callingUid = Integer.parseInt(attrValue); + break; + case ATTR_CALLING_PACKAGE: + callingPackage = attrValue; + break; + case ATTR_RESIZE_MODE: + resizeMode = Integer.parseInt(attrValue); + break; + case ATTR_SUPPORTS_PICTURE_IN_PICTURE: + supportsPictureInPicture = Boolean.parseBoolean(attrValue); + break; + case ATTR_NON_FULLSCREEN_BOUNDS: + lastNonFullscreenBounds = Rect.unflattenFromString(attrValue); + break; + case ATTR_MIN_WIDTH: + minWidth = Integer.parseInt(attrValue); + break; + case ATTR_MIN_HEIGHT: + minHeight = Integer.parseInt(attrValue); + break; + case ATTR_PERSIST_TASK_VERSION: + persistTaskVersion = Integer.parseInt(attrValue); + break; + default: + if (attrName.startsWith(TaskDescription.ATTR_TASKDESCRIPTION_PREFIX)) { + taskDescription.restoreFromXml(attrName, attrValue); + } else { + Slog.w(TAG, "Task: Unknown attribute=" + attrName); + } + } + } + + int event; + while (((event = in.next()) != XmlPullParser.END_DOCUMENT) + && (event != XmlPullParser.END_TAG || in.getDepth() >= outerDepth)) { + if (event == XmlPullParser.START_TAG) { + final String name = in.getName(); + if (TaskPersister.DEBUG) Slog.d(TaskPersister.TAG, + "Task: START_TAG name=" + name); + if (TAG_AFFINITYINTENT.equals(name)) { + affinityIntent = Intent.restoreFromXml(in); + } else if (TAG_INTENT.equals(name)) { + intent = Intent.restoreFromXml(in); + } else if (TAG_ACTIVITY.equals(name)) { + ActivityRecord activity = + ActivityRecord.restoreFromXml(in, stackSupervisor); + if (TaskPersister.DEBUG) Slog.d(TaskPersister.TAG, "Task: activity=" + + activity); + if (activity != null) { + activities.add(activity); + } + } else { + handleUnknownTag(name, in); + } + } + } + if (!hasRootAffinity) { + rootAffinity = affinity; + } else if ("@".equals(rootAffinity)) { + rootAffinity = null; + } + if (effectiveUid <= 0) { + Intent checkIntent = intent != null ? intent : affinityIntent; + effectiveUid = 0; + if (checkIntent != null) { + IPackageManager pm = AppGlobals.getPackageManager(); + try { + ApplicationInfo ai = pm.getApplicationInfo( + checkIntent.getComponent().getPackageName(), + PackageManager.MATCH_UNINSTALLED_PACKAGES + | PackageManager.MATCH_DISABLED_COMPONENTS, userId); + if (ai != null) { + effectiveUid = ai.uid; + } + } catch (RemoteException e) { + } + } + Slog.w(TAG, "Updating task #" + taskId + " for " + checkIntent + + ": effectiveUid=" + effectiveUid); + } + + if (persistTaskVersion < 1) { + // We need to convert the resize mode of home activities saved before version one if + // they are marked as RESIZE_MODE_RESIZEABLE to + // RESIZE_MODE_RESIZEABLE_VIA_SDK_VERSION since we didn't have that differentiation + // before version 1 and the system didn't resize home activities before then. + if (taskType == 1 /* old home type */ && resizeMode == RESIZE_MODE_RESIZEABLE) { + resizeMode = RESIZE_MODE_RESIZEABLE_VIA_SDK_VERSION; + } + } else { + // This activity has previously marked itself explicitly as both resizeable and + // supporting picture-in-picture. Since there is no longer a requirement for + // picture-in-picture activities to be resizeable, we can mark this simply as + // resizeable and supporting picture-in-picture separately. + if (resizeMode == RESIZE_MODE_RESIZEABLE_AND_PIPABLE_DEPRECATED) { + resizeMode = RESIZE_MODE_RESIZEABLE; + supportsPictureInPicture = true; + } + } + + final Task task = create(stackSupervisor.mService, + taskId, intent, affinityIntent, + affinity, rootAffinity, realActivity, origActivity, rootHasReset, + autoRemoveRecents, askedCompatMode, userId, effectiveUid, lastDescription, + lastTimeOnTop, neverRelinquishIdentity, taskDescription, + taskAffiliation, prevTaskId, nextTaskId, taskAffiliationColor, callingUid, + callingPackage, resizeMode, supportsPictureInPicture, realActivitySuspended, + userSetupComplete, minWidth, minHeight, null /*stack*/); + task.mLastNonFullscreenBounds = lastNonFullscreenBounds; + task.setBounds(lastNonFullscreenBounds); + + for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { + task.addChild(activities.get(activityNdx)); + } + + if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "Restored task=" + task); + return task; + } + + void handleUnknownTag(String name, XmlPullParser in) + throws IOException, XmlPullParserException { + Slog.e(TAG, "restoreTask: Unexpected name=" + name); + XmlUtils.skipCurrentTag(in); + } } } diff --git a/services/core/java/com/android/server/wm/TaskChangeNotificationController.java b/services/core/java/com/android/server/wm/TaskChangeNotificationController.java index a61c908e0f6fb..688fe1290b186 100644 --- a/services/core/java/com/android/server/wm/TaskChangeNotificationController.java +++ b/services/core/java/com/android/server/wm/TaskChangeNotificationController.java @@ -350,7 +350,7 @@ class TaskChangeNotificationController { void notifyActivityPinned(ActivityRecord r) { mHandler.removeMessages(NOTIFY_ACTIVITY_PINNED_LISTENERS_MSG); final Message msg = mHandler.obtainMessage(NOTIFY_ACTIVITY_PINNED_LISTENERS_MSG, - r.getTaskRecord().mTaskId, r.getStackId(), r.packageName); + r.getTask().mTaskId, r.getStackId(), r.packageName); msg.sendingUid = r.mUserId; forAllLocalListeners(mNotifyActivityPinned, msg); msg.sendToTarget(); diff --git a/services/core/java/com/android/server/wm/TaskLaunchParamsModifier.java b/services/core/java/com/android/server/wm/TaskLaunchParamsModifier.java index 31145deb449eb..d7bc072dc69ac 100644 --- a/services/core/java/com/android/server/wm/TaskLaunchParamsModifier.java +++ b/services/core/java/com/android/server/wm/TaskLaunchParamsModifier.java @@ -93,7 +93,7 @@ class TaskLaunchParamsModifier implements LaunchParamsModifier { } @VisibleForTesting - int onCalculate(TaskRecord task, ActivityInfo.WindowLayout layout, ActivityRecord activity, + int onCalculate(Task task, ActivityInfo.WindowLayout layout, ActivityRecord activity, ActivityRecord source, ActivityOptions options, LaunchParams currentParams, LaunchParams outParams) { return onCalculate(task, layout, activity, source, options, PHASE_BOUNDS, currentParams, @@ -101,7 +101,7 @@ class TaskLaunchParamsModifier implements LaunchParamsModifier { } @Override - public int onCalculate(TaskRecord task, ActivityInfo.WindowLayout layout, + public int onCalculate(Task task, ActivityInfo.WindowLayout layout, ActivityRecord activity, ActivityRecord source, ActivityOptions options, int phase, LaunchParams currentParams, LaunchParams outParams) { initLogBuilder(task, activity); @@ -111,7 +111,7 @@ class TaskLaunchParamsModifier implements LaunchParamsModifier { return result; } - private int calculate(TaskRecord task, ActivityInfo.WindowLayout layout, + private int calculate(Task task, ActivityInfo.WindowLayout layout, ActivityRecord activity, ActivityRecord source, ActivityOptions options, int phase, LaunchParams currentParams, LaunchParams outParams) { final ActivityRecord root; @@ -292,7 +292,7 @@ class TaskLaunchParamsModifier implements LaunchParamsModifier { return RESULT_CONTINUE; } - private int getPreferredLaunchDisplay(@Nullable TaskRecord task, + private int getPreferredLaunchDisplay(@Nullable Task task, @Nullable ActivityOptions options, ActivityRecord source, LaunchParams currentParams) { if (!mSupervisor.mService.mSupportsMultiDisplay) { return DEFAULT_DISPLAY; @@ -865,7 +865,7 @@ class TaskLaunchParamsModifier implements LaunchParamsModifier { inOutBounds.offset(horizontalOffset, verticalOffset); } - private void initLogBuilder(TaskRecord task, ActivityRecord activity) { + private void initLogBuilder(Task task, ActivityRecord activity) { if (DEBUG) { mLogBuilder = new StringBuilder("TaskLaunchParamsModifier:task=" + task + " activity=" + activity); diff --git a/services/core/java/com/android/server/wm/TaskPersister.java b/services/core/java/com/android/server/wm/TaskPersister.java index f9a75d3d4943c..1e2f0d094944d 100644 --- a/services/core/java/com/android/server/wm/TaskPersister.java +++ b/services/core/java/com/android/server/wm/TaskPersister.java @@ -118,7 +118,7 @@ public class TaskPersister implements PersisterQueue.Listener { mPersisterQueue.addListener(this); } - private void removeThumbnails(TaskRecord task) { + private void removeThumbnails(Task task) { mPersisterQueue.removeItems( item -> { File file = new File(item.mFilePath); @@ -185,7 +185,7 @@ public class TaskPersister implements PersisterQueue.Listener { mTaskIdsInFile.delete(userId); } - void wakeup(TaskRecord task, boolean flush) { + void wakeup(Task task, boolean flush) { synchronized (mPersisterQueue) { if (task != null) { final TaskWriteQueueItem item = mPersisterQueue.findLastItem( @@ -256,12 +256,12 @@ public class TaskPersister implements PersisterQueue.Listener { } } - private TaskRecord taskIdToTask(int taskId, ArrayList tasks) { + private Task taskIdToTask(int taskId, ArrayList tasks) { if (taskId < 0) { return null; } for (int taskNdx = tasks.size() - 1; taskNdx >= 0; --taskNdx) { - final TaskRecord task = tasks.get(taskNdx); + final Task task = tasks.get(taskNdx); if (task.mTaskId == taskId) { return task; } @@ -270,8 +270,8 @@ public class TaskPersister implements PersisterQueue.Listener { return null; } - List restoreTasksForUserLocked(final int userId, SparseBooleanArray preaddedTasks) { - final ArrayList tasks = new ArrayList(); + List restoreTasksForUserLocked(final int userId, SparseBooleanArray preaddedTasks) { + final ArrayList tasks = new ArrayList(); ArraySet recoveredTaskIds = new ArraySet(); File userTasksDir = getUserTasksDir(userId); @@ -320,7 +320,7 @@ public class TaskPersister implements PersisterQueue.Listener { if (event == XmlPullParser.START_TAG) { if (DEBUG) Slog.d(TAG, "restoreTasksForUserLocked: START_TAG name=" + name); if (TAG_TASK.equals(name)) { - final TaskRecord task = TaskRecord.restoreFromXml(in, mStackSupervisor); + final Task task = Task.restoreFromXml(in, mStackSupervisor); if (DEBUG) Slog.d(TAG, "restoreTasksForUserLocked: restored task=" + task); if (task != null) { @@ -375,14 +375,14 @@ public class TaskPersister implements PersisterQueue.Listener { // Fix up task affiliation from taskIds for (int taskNdx = tasks.size() - 1; taskNdx >= 0; --taskNdx) { - final TaskRecord task = tasks.get(taskNdx); + final Task task = tasks.get(taskNdx); task.setPrevAffiliate(taskIdToTask(task.mPrevAffiliateTaskId, tasks)); task.setNextAffiliate(taskIdToTask(task.mNextAffiliateTaskId, tasks)); } - Collections.sort(tasks, new Comparator() { + Collections.sort(tasks, new Comparator() { @Override - public int compare(TaskRecord lhs, TaskRecord rhs) { + public int compare(Task lhs, Task rhs) { final long diff = rhs.mLastTimeMoved - lhs.mLastTimeMoved; if (diff < 0) { return -1; @@ -507,14 +507,14 @@ public class TaskPersister implements PersisterQueue.Listener { private static class TaskWriteQueueItem implements PersisterQueue.WriteQueueItem { private final ActivityTaskManagerService mService; - private final TaskRecord mTask; + private final Task mTask; - TaskWriteQueueItem(TaskRecord task, ActivityTaskManagerService service) { + TaskWriteQueueItem(Task task, ActivityTaskManagerService service) { mTask = task; mService = service; } - private StringWriter saveToXml(TaskRecord task) throws IOException, XmlPullParserException { + private StringWriter saveToXml(Task task) throws IOException, XmlPullParserException { if (DEBUG) Slog.d(TAG, "saveToXml: task=" + task); final XmlSerializer xmlSerializer = new FastXmlSerializer(); StringWriter stringWriter = new StringWriter(); @@ -542,7 +542,7 @@ public class TaskPersister implements PersisterQueue.Listener { public void process() { // Write out one task. StringWriter stringWriter = null; - TaskRecord task = mTask; + Task task = mTask; if (DEBUG) Slog.d(TAG, "Writing task=" + task); synchronized (mService.mGlobalLock) { if (task.inRecents) { diff --git a/services/core/java/com/android/server/wm/TaskRecord.java b/services/core/java/com/android/server/wm/TaskRecord.java deleted file mode 100644 index d645d72d60756..0000000000000 --- a/services/core/java/com/android/server/wm/TaskRecord.java +++ /dev/null @@ -1,2762 +0,0 @@ -/* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.server.wm; - -import static android.app.ActivityTaskManager.INVALID_STACK_ID; -import static android.app.ActivityTaskManager.INVALID_TASK_ID; -import static android.app.ActivityTaskManager.RESIZE_MODE_FORCED; -import static android.app.ActivityTaskManager.RESIZE_MODE_SYSTEM; -import static android.app.WindowConfiguration.ACTIVITY_TYPE_STANDARD; -import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED; -import static android.app.WindowConfiguration.ROTATION_UNDEFINED; -import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM; -import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN; -import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED; -import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY; -import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY; -import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED; -import static android.content.Intent.FLAG_ACTIVITY_NEW_DOCUMENT; -import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK; -import static android.content.Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS; -import static android.content.Intent.FLAG_ACTIVITY_TASK_ON_HOME; -import static android.content.pm.ActivityInfo.FLAG_RELINQUISH_TASK_IDENTITY; -import static android.content.pm.ActivityInfo.LOCK_TASK_LAUNCH_MODE_ALWAYS; -import static android.content.pm.ActivityInfo.LOCK_TASK_LAUNCH_MODE_DEFAULT; -import static android.content.pm.ActivityInfo.LOCK_TASK_LAUNCH_MODE_IF_WHITELISTED; -import static android.content.pm.ActivityInfo.LOCK_TASK_LAUNCH_MODE_NEVER; -import static android.content.pm.ActivityInfo.RESIZE_MODE_FORCE_RESIZABLE_LANDSCAPE_ONLY; -import static android.content.pm.ActivityInfo.RESIZE_MODE_FORCE_RESIZABLE_PORTRAIT_ONLY; -import static android.content.pm.ActivityInfo.RESIZE_MODE_FORCE_RESIZABLE_PRESERVE_ORIENTATION; -import static android.content.pm.ActivityInfo.RESIZE_MODE_FORCE_RESIZEABLE; -import static android.content.pm.ActivityInfo.RESIZE_MODE_RESIZEABLE; -import static android.content.pm.ActivityInfo.RESIZE_MODE_RESIZEABLE_AND_PIPABLE_DEPRECATED; -import static android.content.pm.ActivityInfo.RESIZE_MODE_RESIZEABLE_VIA_SDK_VERSION; -import static android.content.res.Configuration.ORIENTATION_LANDSCAPE; -import static android.content.res.Configuration.ORIENTATION_PORTRAIT; -import static android.content.res.Configuration.ORIENTATION_UNDEFINED; -import static android.os.Trace.TRACE_TAG_WINDOW_MANAGER; -import static android.provider.Settings.Secure.USER_SETUP_COMPLETE; -import static android.view.Display.DEFAULT_DISPLAY; - -import static com.android.server.EventLogTags.WM_TASK_REMOVED; -import static com.android.server.am.TaskRecordProto.ACTIVITIES; -import static com.android.server.am.TaskRecordProto.ACTIVITY_TYPE; -import static com.android.server.am.TaskRecordProto.BOUNDS; -import static com.android.server.am.TaskRecordProto.FULLSCREEN; -import static com.android.server.am.TaskRecordProto.ID; -import static com.android.server.am.TaskRecordProto.LAST_NON_FULLSCREEN_BOUNDS; -import static com.android.server.am.TaskRecordProto.MIN_HEIGHT; -import static com.android.server.am.TaskRecordProto.MIN_WIDTH; -import static com.android.server.am.TaskRecordProto.ORIG_ACTIVITY; -import static com.android.server.am.TaskRecordProto.REAL_ACTIVITY; -import static com.android.server.am.TaskRecordProto.RESIZE_MODE; -import static com.android.server.am.TaskRecordProto.STACK_ID; -import static com.android.server.am.TaskRecordProto.TASK; -import static com.android.server.wm.ActivityRecord.FINISH_RESULT_REMOVED; -import static com.android.server.wm.ActivityRecord.STARTING_WINDOW_SHOWN; -import static com.android.server.wm.ActivityStackSupervisor.ON_TOP; -import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS; -import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS; -import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ADD_REMOVE; -import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK; -import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_RECENTS; -import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS; -import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_ADD_REMOVE; -import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK; -import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_RECENTS; -import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_TASKS; -import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM; -import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME; -import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_ADD_REMOVE; - -import static java.lang.Integer.MAX_VALUE; - -import android.annotation.IntDef; -import android.annotation.NonNull; -import android.annotation.Nullable; -import android.app.Activity; -import android.app.ActivityManager; -import android.app.ActivityManager.TaskDescription; -import android.app.ActivityManager.TaskSnapshot; -import android.app.ActivityOptions; -import android.app.ActivityTaskManager; -import android.app.AppGlobals; -import android.app.TaskInfo; -import android.app.WindowConfiguration; -import android.content.ComponentName; -import android.content.Intent; -import android.content.pm.ActivityInfo; -import android.content.pm.ApplicationInfo; -import android.content.pm.IPackageManager; -import android.content.pm.PackageManager; -import android.content.res.Configuration; -import android.graphics.Rect; -import android.os.Debug; -import android.os.RemoteException; -import android.os.SystemClock; -import android.os.Trace; -import android.os.UserHandle; -import android.provider.Settings; -import android.service.voice.IVoiceInteractionSession; -import android.util.DisplayMetrics; -import android.util.EventLog; -import android.util.Slog; -import android.util.proto.ProtoOutputStream; -import android.view.Display; -import android.view.DisplayInfo; - -import com.android.internal.annotations.VisibleForTesting; -import com.android.internal.app.IVoiceInteractor; -import com.android.internal.util.XmlUtils; -import com.android.server.protolog.common.ProtoLog; -import com.android.server.wm.ActivityStack.ActivityState; - -import org.xmlpull.v1.XmlPullParser; -import org.xmlpull.v1.XmlPullParserException; -import org.xmlpull.v1.XmlSerializer; - -import java.io.IOException; -import java.io.PrintWriter; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.util.ArrayList; -import java.util.Objects; - -class TaskRecord extends Task { - private static final String TAG = TAG_WITH_CLASS_NAME ? "TaskRecord" : TAG_ATM; - private static final String TAG_ADD_REMOVE = TAG + POSTFIX_ADD_REMOVE; - private static final String TAG_RECENTS = TAG + POSTFIX_RECENTS; - private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK; - private static final String TAG_TASKS = TAG + POSTFIX_TASKS; - - private static final String ATTR_TASKID = "task_id"; - private static final String TAG_INTENT = "intent"; - private static final String TAG_AFFINITYINTENT = "affinity_intent"; - private static final String ATTR_REALACTIVITY = "real_activity"; - private static final String ATTR_REALACTIVITY_SUSPENDED = "real_activity_suspended"; - private static final String ATTR_ORIGACTIVITY = "orig_activity"; - private static final String TAG_ACTIVITY = "activity"; - private static final String ATTR_AFFINITY = "affinity"; - private static final String ATTR_ROOT_AFFINITY = "root_affinity"; - private static final String ATTR_ROOTHASRESET = "root_has_reset"; - private static final String ATTR_AUTOREMOVERECENTS = "auto_remove_recents"; - private static final String ATTR_ASKEDCOMPATMODE = "asked_compat_mode"; - private static final String ATTR_USERID = "user_id"; - private static final String ATTR_USER_SETUP_COMPLETE = "user_setup_complete"; - private static final String ATTR_EFFECTIVE_UID = "effective_uid"; - @Deprecated - private static final String ATTR_TASKTYPE = "task_type"; - private static final String ATTR_LASTDESCRIPTION = "last_description"; - private static final String ATTR_LASTTIMEMOVED = "last_time_moved"; - private static final String ATTR_NEVERRELINQUISH = "never_relinquish_identity"; - private static final String ATTR_TASK_AFFILIATION = "task_affiliation"; - private static final String ATTR_PREV_AFFILIATION = "prev_affiliation"; - private static final String ATTR_NEXT_AFFILIATION = "next_affiliation"; - private static final String ATTR_TASK_AFFILIATION_COLOR = "task_affiliation_color"; - private static final String ATTR_CALLING_UID = "calling_uid"; - private static final String ATTR_CALLING_PACKAGE = "calling_package"; - private static final String ATTR_SUPPORTS_PICTURE_IN_PICTURE = "supports_picture_in_picture"; - private static final String ATTR_RESIZE_MODE = "resize_mode"; - private static final String ATTR_NON_FULLSCREEN_BOUNDS = "non_fullscreen_bounds"; - private static final String ATTR_MIN_WIDTH = "min_width"; - private static final String ATTR_MIN_HEIGHT = "min_height"; - private static final String ATTR_PERSIST_TASK_VERSION = "persist_task_version"; - - // Current version of the task record we persist. Used to check if we need to run any upgrade - // code. - private static final int PERSIST_TASK_VERSION = 1; - - private static final int INVALID_MIN_SIZE = -1; - - /** - * The modes to control how the stack is moved to the front when calling - * {@link TaskRecord#reparent}. - */ - @Retention(RetentionPolicy.SOURCE) - @IntDef({ - REPARENT_MOVE_STACK_TO_FRONT, - REPARENT_KEEP_STACK_AT_FRONT, - REPARENT_LEAVE_STACK_IN_PLACE - }) - @interface ReparentMoveStackMode {} - // Moves the stack to the front if it was not at the front - static final int REPARENT_MOVE_STACK_TO_FRONT = 0; - // Only moves the stack to the front if it was focused or front most already - static final int REPARENT_KEEP_STACK_AT_FRONT = 1; - // Do not move the stack as a part of reparenting - static final int REPARENT_LEAVE_STACK_IN_PLACE = 2; - - /** - * The factory used to create {@link TaskRecord}. This allows OEM subclass {@link TaskRecord}. - */ - private static TaskRecordFactory sTaskRecordFactory; - - String affinity; // The affinity name for this task, or null; may change identity. - String rootAffinity; // Initial base affinity, or null; does not change from initial root. - final IVoiceInteractionSession voiceSession; // Voice interaction session driving task - final IVoiceInteractor voiceInteractor; // Associated interactor to provide to app - Intent intent; // The original intent that started the task. Note that this value can - // be null. - Intent affinityIntent; // Intent of affinity-moved activity that started this task. - int effectiveUid; // The current effective uid of the identity of this task. - ComponentName origActivity; // The non-alias activity component of the intent. - ComponentName realActivity; // The actual activity component that started the task. - boolean realActivitySuspended; // True if the actual activity component that started the - // task is suspended. - boolean inRecents; // Actually in the recents list? - long lastActiveTime; // Last time this task was active in the current device session, - // including sleep. This time is initialized to the elapsed time when - // restored from disk. - boolean isAvailable; // Is the activity available to be launched? - boolean rootWasReset; // True if the intent at the root of the task had - // the FLAG_ACTIVITY_RESET_TASK_IF_NEEDED flag. - boolean autoRemoveRecents; // If true, we should automatically remove the task from - // recents when activity finishes - boolean askedCompatMode;// Have asked the user about compat mode for this task. - boolean hasBeenVisible; // Set if any activities in the task have been visible to the user. - - String stringName; // caching of toString() result. - boolean mUserSetupComplete; // The user set-up is complete as of the last time the task activity - // was changed. - - int numFullscreen; // Number of fullscreen activities. - - /** Can't be put in lockTask mode. */ - final static int LOCK_TASK_AUTH_DONT_LOCK = 0; - /** Can enter app pinning with user approval. Can never start over existing lockTask task. */ - final static int LOCK_TASK_AUTH_PINNABLE = 1; - /** Starts in LOCK_TASK_MODE_LOCKED automatically. Can start over existing lockTask task. */ - final static int LOCK_TASK_AUTH_LAUNCHABLE = 2; - /** Can enter lockTask without user approval. Can start over existing lockTask task. */ - final static int LOCK_TASK_AUTH_WHITELISTED = 3; - /** Priv-app that starts in LOCK_TASK_MODE_LOCKED automatically. Can start over existing - * lockTask task. */ - final static int LOCK_TASK_AUTH_LAUNCHABLE_PRIV = 4; - int mLockTaskAuth = LOCK_TASK_AUTH_PINNABLE; - - int mLockTaskUid = -1; // The uid of the application that called startLockTask(). - - /** Current stack. Setter must always be used to update the value. */ - private ActivityStack mStack; - - /** The process that had previously hosted the root activity of this task. - * Used to know that we should try harder to keep this process around, in case the - * user wants to return to it. */ - private WindowProcessController mRootProcess; - - /** Takes on same value as first root activity */ - boolean isPersistable = false; - int maxRecents; - - /** Only used for persistable tasks, otherwise 0. The last time this task was moved. Used for - * determining the order when restoring. Sign indicates whether last task movement was to front - * (positive) or back (negative). Absolute value indicates time. */ - long mLastTimeMoved; - - /** If original intent did not allow relinquishing task identity, save that information */ - private boolean mNeverRelinquishIdentity = true; - - // Used in the unique case where we are clearing the task in order to reuse it. In that case we - // do not want to delete the stack when the task goes empty. - private boolean mReuseTask = false; - - CharSequence lastDescription; // Last description captured for this item. - - int mAffiliatedTaskId; // taskId of parent affiliation or self if no parent. - int mAffiliatedTaskColor; // color of the parent task affiliation. - TaskRecord mPrevAffiliate; // previous task in affiliated chain. - int mPrevAffiliateTaskId = INVALID_TASK_ID; // previous id for persistence. - TaskRecord mNextAffiliate; // next task in affiliated chain. - int mNextAffiliateTaskId = INVALID_TASK_ID; // next id for persistence. - - // For relaunching the task from recents as though it was launched by the original launcher. - int mCallingUid; - String mCallingPackage; - - private final Rect mTmpStableBounds = new Rect(); - private final Rect mTmpNonDecorBounds = new Rect(); - private final Rect mTmpBounds = new Rect(); - private final Rect mTmpInsets = new Rect(); - - // Last non-fullscreen bounds the task was launched in or resized to. - // The information is persisted and used to determine the appropriate stack to launch the - // task into on restore. - Rect mLastNonFullscreenBounds = null; - // Minimal width and height of this task when it's resizeable. -1 means it should use the - // default minimal width/height. - int mMinWidth; - int mMinHeight; - - // Ranking (from top) of this task among all visible tasks. (-1 means it's not visible) - // This number will be assigned when we evaluate OOM scores for all visible tasks. - int mLayerRank = -1; - - /** Helper object used for updating override configuration. */ - private Configuration mTmpConfig = new Configuration(); - - /** Used by fillTaskInfo */ - final TaskActivitiesReport mReuseActivitiesReport = new TaskActivitiesReport(); - - /** - * Don't use constructor directly. Use {@link #create(ActivityTaskManagerService, int, - * ActivityInfo, Intent, TaskDescription)} instead. - */ - TaskRecord(ActivityTaskManagerService atmService, int _taskId, ActivityInfo info, Intent _intent, - IVoiceInteractionSession _voiceSession, IVoiceInteractor _voiceInteractor, - TaskDescription _taskDescription, ActivityStack stack) { - this(atmService, _taskId, _intent, null /*_affinityIntent*/, null /*_affinity*/, - null /*_rootAffinity*/, null /*_realActivity*/, null /*_origActivity*/, - false /*_rootWasReset*/, false /*_autoRemoveRecents*/, false /*_askedCompatMode*/, - UserHandle.getUserId(info.applicationInfo.uid), 0 /*_effectiveUid*/, - null /*_lastDescription*/, System.currentTimeMillis(), - true /*neverRelinquishIdentity*/, - _taskDescription != null ? _taskDescription : new TaskDescription(), - _taskId, INVALID_TASK_ID, INVALID_TASK_ID, 0 /*taskAffiliationColor*/, - info.applicationInfo.uid, info.packageName, info.resizeMode, - info.supportsPictureInPicture(), false /*_realActivitySuspended*/, - false /*userSetupComplete*/, INVALID_MIN_SIZE, INVALID_MIN_SIZE, info, - _voiceSession, _voiceInteractor, stack); - } - - /** Don't use constructor directly. This is only used by XML parser. */ - TaskRecord(ActivityTaskManagerService atmService, int _taskId, Intent _intent, - Intent _affinityIntent, String _affinity, String _rootAffinity, - ComponentName _realActivity, ComponentName _origActivity, boolean _rootWasReset, - boolean _autoRemoveRecents, boolean _askedCompatMode, int _userId, - int _effectiveUid, String _lastDescription, - long lastTimeMoved, boolean neverRelinquishIdentity, - TaskDescription _lastTaskDescription, int taskAffiliation, int prevTaskId, - int nextTaskId, int taskAffiliationColor, int callingUid, String callingPackage, - int resizeMode, boolean supportsPictureInPicture, boolean _realActivitySuspended, - boolean userSetupComplete, int minWidth, int minHeight, ActivityInfo info, - IVoiceInteractionSession _voiceSession, IVoiceInteractor _voiceInteractor, - ActivityStack stack) { - super(_taskId, stack, _userId, resizeMode, - supportsPictureInPicture, _lastTaskDescription, atmService); - mRemoteToken = new RemoteToken(this); - affinityIntent = _affinityIntent; - affinity = _affinity; - rootAffinity = _rootAffinity; - voiceSession = _voiceSession; - voiceInteractor = _voiceInteractor; - realActivity = _realActivity; - realActivitySuspended = _realActivitySuspended; - origActivity = _origActivity; - rootWasReset = _rootWasReset; - isAvailable = true; - autoRemoveRecents = _autoRemoveRecents; - askedCompatMode = _askedCompatMode; - mUserSetupComplete = userSetupComplete; - effectiveUid = _effectiveUid; - touchActiveTime(); - lastDescription = _lastDescription; - mLastTimeMoved = lastTimeMoved; - mNeverRelinquishIdentity = neverRelinquishIdentity; - mAffiliatedTaskId = taskAffiliation; - mAffiliatedTaskColor = taskAffiliationColor; - mPrevAffiliateTaskId = prevTaskId; - mNextAffiliateTaskId = nextTaskId; - mCallingUid = callingUid; - mCallingPackage = callingPackage; - mResizeMode = resizeMode; - if (info != null) { - setIntent(_intent, info); - setMinDimensions(info); - } else { - intent = _intent; - mMinWidth = minWidth; - mMinHeight = minHeight; - } - mAtmService.getTaskChangeNotificationController().notifyTaskCreated(_taskId, realActivity); - } - - void cleanUpResourcesForDestroy() { - if (hasChild()) { - return; - } - - // This task is going away, so save the last state if necessary. - saveLaunchingStateIfNeeded(); - - // TODO: VI what about activity? - final boolean isVoiceSession = voiceSession != null; - if (isVoiceSession) { - try { - voiceSession.taskFinished(intent, mTaskId); - } catch (RemoteException e) { - } - } - if (autoRemoveFromRecents() || isVoiceSession) { - // Task creator asked to remove this when done, or this task was a voice - // interaction, so it should not remain on the recent tasks list. - mAtmService.mStackSupervisor.mRecentTasks.remove(this); - } - - removeIfPossible(); - } - - @VisibleForTesting - @Override - void removeIfPossible() { - mAtmService.getLockTaskController().clearLockedTask(this); - super.removeIfPossible(); - mAtmService.getTaskChangeNotificationController().notifyTaskRemoved(mTaskId); - } - - void setResizeMode(int resizeMode) { - if (mResizeMode == resizeMode) { - return; - } - mResizeMode = resizeMode; - mAtmService.mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS); - mAtmService.mRootActivityContainer.resumeFocusedStacksTopActivities(); - updateTaskDescription(); - } - - boolean resize(Rect bounds, int resizeMode, boolean preserveWindow, boolean deferResume) { - mAtmService.deferWindowLayout(); - - try { - final boolean forced = (resizeMode & RESIZE_MODE_FORCED) != 0; - - if (getParent() == null) { - // Task doesn't exist in window manager yet (e.g. was restored from recents). - // All we can do for now is update the bounds so it can be used when the task is - // added to window manager. - setBounds(bounds); - if (!inFreeformWindowingMode()) { - // re-restore the task so it can have the proper stack association. - mAtmService.mStackSupervisor.restoreRecentTaskLocked(this, null, !ON_TOP); - } - return true; - } - - if (!canResizeToBounds(bounds)) { - throw new IllegalArgumentException("resizeTask: Can not resize task=" + this - + " to bounds=" + bounds + " resizeMode=" + mResizeMode); - } - - // Do not move the task to another stack here. - // This method assumes that the task is already placed in the right stack. - // we do not mess with that decision and we only do the resize! - - Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "resizeTask_" + mTaskId); - - boolean updatedConfig = false; - mTmpConfig.setTo(getResolvedOverrideConfiguration()); - if (setBounds(bounds) != BOUNDS_CHANGE_NONE) { - updatedConfig = !mTmpConfig.equals(getResolvedOverrideConfiguration()); - } - // This variable holds information whether the configuration didn't change in a significant - - // way and the activity was kept the way it was. If it's false, it means the activity - // had - // to be relaunched due to configuration change. - boolean kept = true; - if (updatedConfig) { - final ActivityRecord r = topRunningActivityLocked(); - if (r != null && !deferResume) { - kept = r.ensureActivityConfiguration(0 /* globalChanges */, - preserveWindow); - // Preserve other windows for resizing because if resizing happens when there - // is a dialog activity in the front, the activity that still shows some - // content to the user will become black and cause flickers. Note in most cases - // this won't cause tons of irrelevant windows being preserved because only - // activities in this task may experience a bounds change. Configs for other - // activities stay the same. - mAtmService.mRootActivityContainer.ensureActivitiesVisible(r, 0, preserveWindow); - if (!kept) { - mAtmService.mRootActivityContainer.resumeFocusedStacksTopActivities(); - } - } - } - resize(kept, forced); - - saveLaunchingStateIfNeeded(); - - Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER); - return kept; - } finally { - mAtmService.continueWindowLayout(); - } - } - - /** - * Convenience method to reparent a task to the top or bottom position of the stack. - */ - boolean reparent(ActivityStack preferredStack, boolean toTop, - @ReparentMoveStackMode int moveStackMode, boolean animate, boolean deferResume, - String reason) { - return reparent(preferredStack, toTop ? MAX_VALUE : 0, moveStackMode, animate, deferResume, - true /* schedulePictureInPictureModeChange */, reason); - } - - /** - * Convenience method to reparent a task to the top or bottom position of the stack, with - * an option to skip scheduling the picture-in-picture mode change. - */ - boolean reparent(ActivityStack preferredStack, boolean toTop, - @ReparentMoveStackMode int moveStackMode, boolean animate, boolean deferResume, - boolean schedulePictureInPictureModeChange, String reason) { - return reparent(preferredStack, toTop ? MAX_VALUE : 0, moveStackMode, animate, - deferResume, schedulePictureInPictureModeChange, reason); - } - - /** Convenience method to reparent a task to a specific position of the stack. */ - boolean reparent(ActivityStack preferredStack, int position, - @ReparentMoveStackMode int moveStackMode, boolean animate, boolean deferResume, - String reason) { - return reparent(preferredStack, position, moveStackMode, animate, deferResume, - true /* schedulePictureInPictureModeChange */, reason); - } - - /** - * Reparents the task into a preferred stack, creating it if necessary. - * - * @param preferredStack the target stack to move this task - * @param position the position to place this task in the new stack - * @param animate whether or not we should wait for the new window created as a part of the - * reparenting to be drawn and animated in - * @param moveStackMode whether or not to move the stack to the front always, only if it was - * previously focused & in front, or never - * @param deferResume whether or not to update the visibility of other tasks and stacks that may - * have changed as a result of this reparenting - * @param schedulePictureInPictureModeChange specifies whether or not to schedule the PiP mode - * change. Callers may set this to false if they are explicitly scheduling PiP mode - * changes themselves, like during the PiP animation - * @param reason the caller of this reparenting - * @return whether the task was reparented - */ - // TODO: Inspect all call sites and change to just changing windowing mode of the stack vs. - // re-parenting the task. Can only be done when we are no longer using static stack Ids. - boolean reparent(ActivityStack preferredStack, int position, - @ReparentMoveStackMode int moveStackMode, boolean animate, boolean deferResume, - boolean schedulePictureInPictureModeChange, String reason) { - final ActivityStackSupervisor supervisor = mAtmService.mStackSupervisor; - final RootActivityContainer root = mAtmService.mRootActivityContainer; - final WindowManagerService windowManager = mAtmService.mWindowManager; - final ActivityStack sourceStack = getStack(); - final ActivityStack toStack = supervisor.getReparentTargetStack(this, preferredStack, - position == MAX_VALUE); - if (toStack == sourceStack) { - return false; - } - if (!canBeLaunchedOnDisplay(toStack.mDisplayId)) { - return false; - } - - final boolean toTopOfStack = position == MAX_VALUE; - if (toTopOfStack && toStack.getResumedActivity() != null - && toStack.topRunningActivityLocked() != null) { - // Pause the resumed activity on the target stack while re-parenting task on top of it. - toStack.startPausingLocked(false /* userLeaving */, false /* uiSleeping */, - null /* resuming */); - } - - final int toStackWindowingMode = toStack.getWindowingMode(); - final ActivityRecord topActivity = getTopActivity(); - - final boolean mightReplaceWindow = topActivity != null - && replaceWindowsOnTaskMove(getWindowingMode(), toStackWindowingMode); - if (mightReplaceWindow) { - // We are about to relaunch the activity because its configuration changed due to - // being maximized, i.e. size change. The activity will first remove the old window - // and then add a new one. This call will tell window manager about this, so it can - // preserve the old window until the new one is drawn. This prevents having a gap - // between the removal and addition, in which no window is visible. We also want the - // entrance of the new window to be properly animated. - // Note here we always set the replacing window first, as the flags might be needed - // during the relaunch. If we end up not doing any relaunch, we clear the flags later. - windowManager.setWillReplaceWindow(topActivity.appToken, animate); - } - - mAtmService.deferWindowLayout(); - boolean kept = true; - try { - final ActivityRecord r = topRunningActivityLocked(); - // give pinned stack a chance to save current bounds, this needs to be before the - // actual reparent. - if (inPinnedWindowingMode() - && !(toStackWindowingMode == WINDOWING_MODE_UNDEFINED) - && !r.isHidden()) { - r.savePinnedStackBounds(); - } - final boolean wasFocused = r != null && root.isTopDisplayFocusedStack(sourceStack) - && (topRunningActivityLocked() == r); - final boolean wasResumed = r != null && sourceStack.getResumedActivity() == r; - final boolean wasPaused = r != null && sourceStack.mPausingActivity == r; - - // In some cases the focused stack isn't the front stack. E.g. pinned stack. - // Whenever we are moving the top activity from the front stack we want to make sure to - // move the stack to the front. - final boolean wasFront = r != null && sourceStack.isTopStackOnDisplay() - && (sourceStack.topRunningActivityLocked() == r); - - final boolean moveStackToFront = moveStackMode == REPARENT_MOVE_STACK_TO_FRONT - || (moveStackMode == REPARENT_KEEP_STACK_AT_FRONT && (wasFocused || wasFront)); - - reparent(toStack, position, moveStackToFront, reason); - - if (schedulePictureInPictureModeChange) { - // Notify of picture-in-picture mode changes - supervisor.scheduleUpdatePictureInPictureModeIfNeeded(this, sourceStack); - } - - // If the task had focus before (or we're requested to move focus), move focus to the - // new stack by moving the stack to the front. - if (r != null) { - toStack.moveToFrontAndResumeStateIfNeeded(r, moveStackToFront, wasResumed, - wasPaused, reason); - } - if (!animate) { - mAtmService.mStackSupervisor.mNoAnimActivities.add(topActivity); - } - - // We might trigger a configuration change. Save the current task bounds for freezing. - // TODO: Should this call be moved inside the resize method in WM? - toStack.prepareFreezingTaskBounds(); - - // Make sure the task has the appropriate bounds/size for the stack it is in. - final boolean toStackSplitScreenPrimary = - toStackWindowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY; - final Rect configBounds = getRequestedOverrideBounds(); - if ((toStackWindowingMode == WINDOWING_MODE_FULLSCREEN - || toStackWindowingMode == WINDOWING_MODE_SPLIT_SCREEN_SECONDARY) - && !Objects.equals(configBounds, toStack.getRequestedOverrideBounds())) { - kept = resize(toStack.getRequestedOverrideBounds(), RESIZE_MODE_SYSTEM, - !mightReplaceWindow, deferResume); - } else if (toStackWindowingMode == WINDOWING_MODE_FREEFORM) { - Rect bounds = getLaunchBounds(); - if (bounds == null) { - mAtmService.mStackSupervisor.getLaunchParamsController().layoutTask(this, null); - bounds = configBounds; - } - kept = resize(bounds, RESIZE_MODE_FORCED, !mightReplaceWindow, deferResume); - } else if (toStackSplitScreenPrimary || toStackWindowingMode == WINDOWING_MODE_PINNED) { - if (toStackSplitScreenPrimary && moveStackMode == REPARENT_KEEP_STACK_AT_FRONT) { - // Move recents to front so it is not behind home stack when going into docked - // mode - mAtmService.mStackSupervisor.moveRecentsStackToFront(reason); - } - kept = resize(toStack.getRequestedOverrideBounds(), RESIZE_MODE_SYSTEM, - !mightReplaceWindow, deferResume); - } - } finally { - mAtmService.continueWindowLayout(); - } - - if (mightReplaceWindow) { - // If we didn't actual do a relaunch (indicated by kept==true meaning we kept the old - // window), we need to clear the replace window settings. Otherwise, we schedule a - // timeout to remove the old window if the replacing window is not coming in time. - windowManager.scheduleClearWillReplaceWindows(topActivity.appToken, !kept); - } - - if (!deferResume) { - // The task might have already been running and its visibility needs to be synchronized - // with the visibility of the stack / windows. - root.ensureActivitiesVisible(null, 0, !mightReplaceWindow); - root.resumeFocusedStacksTopActivities(); - } - - // TODO: Handle incorrect request to move before the actual move, not after. - supervisor.handleNonResizableTaskIfNeeded(this, preferredStack.getWindowingMode(), - DEFAULT_DISPLAY, toStack); - - return (preferredStack == toStack); - } - - /** - * @return True if the windows of tasks being moved to the target stack from the source stack - * should be replaced, meaning that window manager will keep the old window around until the new - * is ready. - */ - private static boolean replaceWindowsOnTaskMove( - int sourceWindowingMode, int targetWindowingMode) { - return sourceWindowingMode == WINDOWING_MODE_FREEFORM - || targetWindowingMode == WINDOWING_MODE_FREEFORM; - } - - /** - * DO NOT HOLD THE ACTIVITY MANAGER LOCK WHEN CALLING THIS METHOD! - */ - TaskSnapshot getSnapshot(boolean reducedResolution, boolean restoreFromDisk) { - - // TODO: Move this to {@link TaskWindowContainerController} once recent tasks are more - // synchronized between AM and WM. - return mAtmService.mWindowManager.getTaskSnapshot(mTaskId, mUserId, reducedResolution, - restoreFromDisk); - } - - void touchActiveTime() { - lastActiveTime = SystemClock.elapsedRealtime(); - } - - long getInactiveDuration() { - return SystemClock.elapsedRealtime() - lastActiveTime; - } - - /** Sets the original intent, and the calling uid and package. */ - void setIntent(ActivityRecord r) { - mCallingUid = r.launchedFromUid; - mCallingPackage = r.launchedFromPackage; - setIntent(r.intent, r.info); - setLockTaskAuth(r); - } - - /** Sets the original intent, _without_ updating the calling uid or package. */ - private void setIntent(Intent _intent, ActivityInfo info) { - if (intent == null) { - mNeverRelinquishIdentity = - (info.flags & FLAG_RELINQUISH_TASK_IDENTITY) == 0; - } else if (mNeverRelinquishIdentity) { - return; - } - - affinity = info.taskAffinity; - if (intent == null) { - // If this task already has an intent associated with it, don't set the root - // affinity -- we don't want it changing after initially set, but the initially - // set value may be null. - rootAffinity = affinity; - } - effectiveUid = info.applicationInfo.uid; - stringName = null; - - if (info.targetActivity == null) { - if (_intent != null) { - // If this Intent has a selector, we want to clear it for the - // recent task since it is not relevant if the user later wants - // to re-launch the app. - if (_intent.getSelector() != null || _intent.getSourceBounds() != null) { - _intent = new Intent(_intent); - _intent.setSelector(null); - _intent.setSourceBounds(null); - } - } - if (DEBUG_TASKS) Slog.v(TAG_TASKS, "Setting Intent of " + this + " to " + _intent); - intent = _intent; - realActivity = _intent != null ? _intent.getComponent() : null; - origActivity = null; - } else { - ComponentName targetComponent = new ComponentName( - info.packageName, info.targetActivity); - if (_intent != null) { - Intent targetIntent = new Intent(_intent); - targetIntent.setSelector(null); - targetIntent.setSourceBounds(null); - if (DEBUG_TASKS) Slog.v(TAG_TASKS, - "Setting Intent of " + this + " to target " + targetIntent); - intent = targetIntent; - realActivity = targetComponent; - origActivity = _intent.getComponent(); - } else { - intent = null; - realActivity = targetComponent; - origActivity = new ComponentName(info.packageName, info.name); - } - } - - final int intentFlags = intent == null ? 0 : intent.getFlags(); - if ((intentFlags & Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) { - // Once we are set to an Intent with this flag, we count this - // task as having a true root activity. - rootWasReset = true; - } - mUserId = UserHandle.getUserId(info.applicationInfo.uid); - mUserSetupComplete = Settings.Secure.getIntForUser( - mAtmService.mContext.getContentResolver(), USER_SETUP_COMPLETE, 0, mUserId) != 0; - if ((info.flags & ActivityInfo.FLAG_AUTO_REMOVE_FROM_RECENTS) != 0) { - // If the activity itself has requested auto-remove, then just always do it. - autoRemoveRecents = true; - } else if ((intentFlags & (FLAG_ACTIVITY_NEW_DOCUMENT | FLAG_ACTIVITY_RETAIN_IN_RECENTS)) - == FLAG_ACTIVITY_NEW_DOCUMENT) { - // If the caller has not asked for the document to be retained, then we may - // want to turn on auto-remove, depending on whether the target has set its - // own document launch mode. - if (info.documentLaunchMode != ActivityInfo.DOCUMENT_LAUNCH_NONE) { - autoRemoveRecents = false; - } else { - autoRemoveRecents = true; - } - } else { - autoRemoveRecents = false; - } - if (mResizeMode != info.resizeMode) { - mResizeMode = info.resizeMode; - updateTaskDescription(); - } - mSupportsPictureInPicture = info.supportsPictureInPicture(); - } - - /** Sets the original minimal width and height. */ - private void setMinDimensions(ActivityInfo info) { - if (info != null && info.windowLayout != null) { - mMinWidth = info.windowLayout.minWidth; - mMinHeight = info.windowLayout.minHeight; - } else { - mMinWidth = INVALID_MIN_SIZE; - mMinHeight = INVALID_MIN_SIZE; - } - } - - /** - * Return true if the input activity has the same intent filter as the intent this task - * record is based on (normally the root activity intent). - */ - boolean isSameIntentFilter(ActivityRecord r) { - final Intent intent = new Intent(r.intent); - // Make sure the component are the same if the input activity has the same real activity - // as the one in the task because either one of them could be the alias activity. - if (Objects.equals(realActivity, r.mActivityComponent) && this.intent != null) { - intent.setComponent(this.intent.getComponent()); - } - return intent.filterEquals(this.intent); - } - - boolean returnsToHomeStack() { - final int returnHomeFlags = FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_TASK_ON_HOME; - return intent != null && (intent.getFlags() & returnHomeFlags) == returnHomeFlags; - } - - void setPrevAffiliate(TaskRecord prevAffiliate) { - mPrevAffiliate = prevAffiliate; - mPrevAffiliateTaskId = prevAffiliate == null ? INVALID_TASK_ID : prevAffiliate.mTaskId; - } - - void setNextAffiliate(TaskRecord nextAffiliate) { - mNextAffiliate = nextAffiliate; - mNextAffiliateTaskId = nextAffiliate == null ? INVALID_TASK_ID : nextAffiliate.mTaskId; - } - - ActivityStack getStack() { - return mStack; - } - - @Override - void onParentChanged(ConfigurationContainer newParent, ConfigurationContainer oldParent) { - // TODO(stack-merge): Remove cats ater object merge. - final ActivityStack oldStack = ((ActivityStack) oldParent); - final ActivityStack newStack = ((ActivityStack) newParent); - - mStack = newStack; - - super.onParentChanged(newParent, oldParent); - - if (oldStack != null) { - for (int i = getChildCount() - 1; i >= 0; --i) { - final ActivityRecord activity = getChildAt(i); - oldStack.onActivityRemovedFromStack(activity); - } - - updateTaskMovement(true /*toFront*/); - - if (oldStack.inPinnedWindowingMode() - && (newStack == null || !newStack.inPinnedWindowingMode())) { - // Notify if a task from the pinned stack is being removed - // (or moved depending on the mode). - mAtmService.getTaskChangeNotificationController().notifyActivityUnpinned(); - } - } - - if (newStack != null) { - for (int i = getChildCount() - 1; i >= 0; --i) { - final ActivityRecord activity = getChildAt(i); - newStack.onActivityAddedToStack(activity); - } - - // TODO: Ensure that this is actually necessary here - // Notify the voice session if required - if (voiceSession != null) { - try { - voiceSession.taskStarted(intent, mTaskId); - } catch (RemoteException e) { - } - } - } - - // First time we are adding the task to the system. - if (oldParent == null && newParent != null) { - - // TODO: Super random place to be doing this, but aligns with what used to be done - // before we unified Task level. Look into if this can be done in a better place. - updateOverrideConfigurationFromLaunchBounds(); - } - - // Task is being removed. - if (oldParent != null && newParent == null) { - cleanUpResourcesForDestroy(); - } - - - // Update task bounds if needed. - adjustBoundsForDisplayChangeIfNeeded(getDisplayContent()); - - if (getWindowConfiguration().windowsAreScaleable()) { - // We force windows out of SCALING_MODE_FREEZE so that we can continue to animate them - // while a resize is pending. - forceWindowsScaleable(true /* force */); - } else { - forceWindowsScaleable(false /* force */); - } - - mAtmService.mRootActivityContainer.updateUIDsPresentOnDisplay(); - } - - /** TODO(task-merge): Consolidate into {@link TaskStack#onChildPositionChanged}. */ - void updateTaskMovement(boolean toFront) { - if (isPersistable) { - mLastTimeMoved = System.currentTimeMillis(); - // Sign is used to keep tasks sorted when persisted. Tasks sent to the bottom most - // recently will be most negative, tasks sent to the bottom before that will be less - // negative. Similarly for recent tasks moved to the top which will be most positive. - if (!toFront) { - mLastTimeMoved *= -1; - } - } - mAtmService.mRootActivityContainer.invalidateTaskLayers(); - } - - /** - * @return Id of current stack, {@link ActivityTaskManager#INVALID_STACK_ID} if no stack is set. - */ - int getStackId() { - return mStack != null ? mStack.mStackId : INVALID_STACK_ID; - } - - // Close up recents linked list. - private void closeRecentsChain() { - if (mPrevAffiliate != null) { - mPrevAffiliate.setNextAffiliate(mNextAffiliate); - } - if (mNextAffiliate != null) { - mNextAffiliate.setPrevAffiliate(mPrevAffiliate); - } - setPrevAffiliate(null); - setNextAffiliate(null); - } - - void removedFromRecents() { - closeRecentsChain(); - if (inRecents) { - inRecents = false; - mAtmService.notifyTaskPersisterLocked(this, false); - } - - clearRootProcess(); - - mAtmService.mWindowManager.mTaskSnapshotController.notifyTaskRemovedFromRecents( - mTaskId, mUserId); - } - - void setTaskToAffiliateWith(TaskRecord taskToAffiliateWith) { - closeRecentsChain(); - mAffiliatedTaskId = taskToAffiliateWith.mAffiliatedTaskId; - mAffiliatedTaskColor = taskToAffiliateWith.mAffiliatedTaskColor; - // Find the end - while (taskToAffiliateWith.mNextAffiliate != null) { - final TaskRecord nextRecents = taskToAffiliateWith.mNextAffiliate; - if (nextRecents.mAffiliatedTaskId != mAffiliatedTaskId) { - Slog.e(TAG, "setTaskToAffiliateWith: nextRecents=" + nextRecents + " affilTaskId=" - + nextRecents.mAffiliatedTaskId + " should be " + mAffiliatedTaskId); - if (nextRecents.mPrevAffiliate == taskToAffiliateWith) { - nextRecents.setPrevAffiliate(null); - } - taskToAffiliateWith.setNextAffiliate(null); - break; - } - taskToAffiliateWith = nextRecents; - } - taskToAffiliateWith.setNextAffiliate(this); - setPrevAffiliate(taskToAffiliateWith); - setNextAffiliate(null); - } - - /** Returns the intent for the root activity for this task */ - Intent getBaseIntent() { - return intent != null ? intent : affinityIntent; - } - - /** Returns the first non-finishing activity from the bottom. */ - ActivityRecord getRootActivity() { - final int rootActivityIndex = findRootIndex(false /* effectiveRoot */); - if (rootActivityIndex == -1) { - // There are no non-finishing activities in the task. - return null; - } - return getChildAt(rootActivityIndex); - } - - ActivityRecord getTopActivity() { - return getTopActivity(true /* includeOverlays */); - } - - ActivityRecord getTopActivity(boolean includeOverlays) { - for (int i = getChildCount() - 1; i >= 0; --i) { - final ActivityRecord r = getChildAt(i); - if (r.finishing || (!includeOverlays && r.mTaskOverlay)) { - continue; - } - return r; - } - return null; - } - - ActivityRecord topRunningActivityLocked() { - if (mStack != null) { - for (int activityNdx = getChildCount() - 1; activityNdx >= 0; --activityNdx) { - ActivityRecord r = getChildAt(activityNdx); - if (!r.finishing && r.okToShowLocked()) { - return r; - } - } - } - return null; - } - - /** - * Return true if any activities in this task belongs to input uid. - */ - boolean containsAppUid(int uid) { - for (int i = getChildCount() - 1; i >= 0; --i) { - final ActivityRecord r = getChildAt(i); - if (r.getUid() == uid) { - return true; - } - } - return false; - } - - void getAllRunningVisibleActivitiesLocked(ArrayList outActivities) { - if (mStack != null) { - for (int activityNdx = getChildCount() - 1; activityNdx >= 0; --activityNdx) { - ActivityRecord r = getChildAt(activityNdx); - if (!r.finishing && r.okToShowLocked() && r.visibleIgnoringKeyguard) { - outActivities.add(r); - } - } - } - } - - ActivityRecord topRunningActivityWithStartingWindowLocked() { - if (mStack != null) { - for (int activityNdx = getChildCount() - 1; activityNdx >= 0; --activityNdx) { - ActivityRecord r = getChildAt(activityNdx); - if (r.mStartingWindowState != STARTING_WINDOW_SHOWN - || r.finishing || !r.okToShowLocked()) { - continue; - } - return r; - } - } - return null; - } - - /** - * Return the number of running activities, and the number of non-finishing/initializing - * activities in the provided {@param reportOut} respectively. - */ - void getNumRunningActivities(TaskActivitiesReport reportOut) { - reportOut.reset(); - for (int i = getChildCount() - 1; i >= 0; --i) { - final ActivityRecord r = getChildAt(i); - if (r.finishing) { - continue; - } - - reportOut.base = r; - - // Increment the total number of non-finishing activities - reportOut.numActivities++; - - if (reportOut.top == null || (reportOut.top.isState(ActivityState.INITIALIZING))) { - reportOut.top = r; - // Reset the number of running activities until we hit the first non-initializing - // activity - reportOut.numRunning = 0; - } - if (r.attachedToProcess()) { - // Increment the number of actually running activities - reportOut.numRunning++; - } - } - } - - boolean okToShowLocked() { - // NOTE: If {@link TaskRecord#topRunningActivity} return is not null then it is - // okay to show the activity when locked. - return mAtmService.mStackSupervisor.isCurrentProfileLocked(mUserId) - || topRunningActivityLocked() != null; - } - - /** - * Reorder the history stack so that the passed activity is brought to the front. - */ - final void moveActivityToFrontLocked(ActivityRecord newTop) { - if (DEBUG_ADD_REMOVE) Slog.i(TAG_ADD_REMOVE, "Removing and adding activity " - + newTop + " to stack at top callers=" + Debug.getCallers(4)); - - positionChildAtTop(newTop); - updateEffectiveIntent(); - } - - @Override - /*@WindowConfiguration.ActivityType*/ - public int getActivityType() { - final int applicationType = super.getActivityType(); - if (applicationType != ACTIVITY_TYPE_UNDEFINED || !hasChild()) { - return applicationType; - } - return getChildAt(0).getActivityType(); - } - - @Override - void addChild(ActivityRecord r, int index) { - // If this task had any child before we added this one. - boolean hadChild = hasChild(); - - index = getAdjustedAddPosition(r, index); - super.addChild(r, index); - - ProtoLog.v(WM_DEBUG_ADD_REMOVE, "addChild: %s at top.", this); - r.inHistory = true; - - if (r.occludesParent()) { - numFullscreen++; - } - // Only set this based on the first activity - if (!hadChild) { - if (r.getActivityType() == ACTIVITY_TYPE_UNDEFINED) { - // Normally non-standard activity type for the activity record will be set when the - // object is created, however we delay setting the standard application type until - // this point so that the task can set the type for additional activities added in - // the else condition below. - r.setActivityType(ACTIVITY_TYPE_STANDARD); - } - setActivityType(r.getActivityType()); - isPersistable = r.isPersistable(); - mCallingUid = r.launchedFromUid; - mCallingPackage = r.launchedFromPackage; - // Clamp to [1, max]. - maxRecents = Math.min(Math.max(r.info.maxRecents, 1), - ActivityTaskManager.getMaxAppRecentsLimitStatic()); - } else { - // Otherwise make all added activities match this one. - r.setActivityType(getActivityType()); - } - - updateEffectiveIntent(); - if (r.isPersistable()) { - mAtmService.notifyTaskPersisterLocked(this, false); - } - - // Make sure the list of display UID whitelists is updated - // now that this record is in a new task. - mAtmService.mRootActivityContainer.updateUIDsPresentOnDisplay(); - } - - void addChild(ActivityRecord r) { - addChild(r, Integer.MAX_VALUE /* add on top */); - } - - @Override - void removeChild(ActivityRecord r) { - if (!mChildren.contains(r)) { - Slog.e(TAG, "removeChild: r=" + r + " not found in t=" + this); - return; - } - - super.removeChild(r); - if (r.occludesParent()) { - numFullscreen--; - } - if (r.isPersistable()) { - mAtmService.notifyTaskPersisterLocked(this, false); - } - - if (inPinnedWindowingMode()) { - // We normally notify listeners of task stack changes on pause, however pinned stack - // activities are normally in the paused state so no notification will be sent there - // before the activity is removed. We send it here so instead. - mAtmService.getTaskChangeNotificationController().notifyTaskStackChanged(); - } - - final String reason = "removeChild"; - if (hasChild()) { - updateEffectiveIntent(); - - // The following block can be executed multiple times if there is more than one overlay. - // {@link ActivityStackSupervisor#removeTaskByIdLocked} handles this by reverse lookup - // of the task by id and exiting early if not found. - if (onlyHasTaskOverlayActivities(false /* excludingFinishing */)) { - // When destroying a task, tell the supervisor to remove it so that any activity it - // has can be cleaned up correctly. This is currently the only place where we remove - // a task with the DESTROYING mode, so instead of passing the onlyHasTaskOverlays - // state into removeChild(), we just clear the task here before the other residual - // work. - // TODO: If the callers to removeChild() changes such that we have multiple places - // where we are destroying the task, move this back into removeChild() - mAtmService.mStackSupervisor.removeTaskByIdLocked(mTaskId, false /* killProcess */, - !REMOVE_FROM_RECENTS, reason); - } - } else if (!mReuseTask) { - // Remove entire task if it doesn't have any activity left and it isn't marked for reuse - mStack.removeChild(this, reason); - EventLog.writeEvent(WM_TASK_REMOVED, mTaskId, - "removeChild: last r=" + r + " in t=" + this); - removeIfPossible(); - } - } - - /** - * @return whether or not there are ONLY task overlay activities in the stack. - * If {@param excludeFinishing} is set, then ignore finishing activities in the check. - * If there are no task overlay activities, this call returns false. - */ - boolean onlyHasTaskOverlayActivities(boolean excludeFinishing) { - int count = 0; - for (int i = getChildCount() - 1; i >= 0; i--) { - final ActivityRecord r = getChildAt(i); - if (excludeFinishing && r.finishing) { - continue; - } - if (!r.mTaskOverlay) { - return false; - } - count++; - } - return count > 0; - } - - boolean autoRemoveFromRecents() { - // We will automatically remove the task either if it has explicitly asked for - // this, or it is empty and has never contained an activity that got shown to - // the user. - return autoRemoveRecents || (!hasChild() && !hasBeenVisible); - } - - /** - * Completely remove all activities associated with an existing - * task starting at a specified index. - */ - private void performClearTaskAtIndexLocked(int activityNdx, String reason) { - int numActivities = getChildCount(); - for ( ; activityNdx < numActivities; ++activityNdx) { - final ActivityRecord r = getChildAt(activityNdx); - if (r.finishing) { - continue; - } - if (mStack == null) { - // Task was restored from persistent storage. - r.takeFromHistory(); - removeChild(r); - --activityNdx; - --numActivities; - } else if (r.finishIfPossible(Activity.RESULT_CANCELED, null /* resultData */, reason, - false /* oomAdj */) - == FINISH_RESULT_REMOVED) { - --activityNdx; - --numActivities; - } - } - } - - /** - * Completely remove all activities associated with an existing task. - */ - void performClearTaskLocked() { - mReuseTask = true; - performClearTaskAtIndexLocked(0, "clear-task-all"); - mReuseTask = false; - } - - ActivityRecord performClearTaskForReuseLocked(ActivityRecord newR, int launchFlags) { - mReuseTask = true; - final ActivityRecord result = performClearTaskLocked(newR, launchFlags); - mReuseTask = false; - return result; - } - - /** - * Perform clear operation as requested by - * {@link Intent#FLAG_ACTIVITY_CLEAR_TOP}: search from the top of the - * stack to the given task, then look for - * an instance of that activity in the stack and, if found, finish all - * activities on top of it and return the instance. - * - * @param newR Description of the new activity being started. - * @return Returns the old activity that should be continued to be used, - * or null if none was found. - */ - final ActivityRecord performClearTaskLocked(ActivityRecord newR, int launchFlags) { - int numActivities = getChildCount(); - for (int activityNdx = numActivities - 1; activityNdx >= 0; --activityNdx) { - ActivityRecord r = getChildAt(activityNdx); - if (r.finishing) { - continue; - } - if (r.mActivityComponent.equals(newR.mActivityComponent)) { - // Here it is! Now finish everything in front... - final ActivityRecord ret = r; - - for (++activityNdx; activityNdx < numActivities; ++activityNdx) { - r = getChildAt(activityNdx); - if (r.finishing) { - continue; - } - ActivityOptions opts = r.takeOptionsLocked(false /* fromClient */); - if (opts != null) { - ret.updateOptionsLocked(opts); - } - if (r.finishIfPossible("clear-task-stack", false /* oomAdj */) - == FINISH_RESULT_REMOVED) { - --activityNdx; - --numActivities; - } - } - - // Finally, if this is a normal launch mode (that is, not - // expecting onNewIntent()), then we will finish the current - // instance of the activity so a new fresh one can be started. - if (ret.launchMode == ActivityInfo.LAUNCH_MULTIPLE - && (launchFlags & Intent.FLAG_ACTIVITY_SINGLE_TOP) == 0 - && !ActivityStarter.isDocumentLaunchesIntoExisting(launchFlags)) { - if (!ret.finishing) { - ret.finishIfPossible("clear-task-top", false /* oomAdj */); - return null; - } - } - - return ret; - } - } - - return null; - } - - void removeTaskActivitiesLocked(String reason) { - // Just remove the entire task. - performClearTaskAtIndexLocked(0, reason); - } - - String lockTaskAuthToString() { - switch (mLockTaskAuth) { - case LOCK_TASK_AUTH_DONT_LOCK: return "LOCK_TASK_AUTH_DONT_LOCK"; - case LOCK_TASK_AUTH_PINNABLE: return "LOCK_TASK_AUTH_PINNABLE"; - case LOCK_TASK_AUTH_LAUNCHABLE: return "LOCK_TASK_AUTH_LAUNCHABLE"; - case LOCK_TASK_AUTH_WHITELISTED: return "LOCK_TASK_AUTH_WHITELISTED"; - case LOCK_TASK_AUTH_LAUNCHABLE_PRIV: return "LOCK_TASK_AUTH_LAUNCHABLE_PRIV"; - default: return "unknown=" + mLockTaskAuth; - } - } - - void setLockTaskAuth() { - setLockTaskAuth(getRootActivity()); - } - - private void setLockTaskAuth(@Nullable ActivityRecord r) { - if (r == null) { - mLockTaskAuth = LOCK_TASK_AUTH_PINNABLE; - return; - } - - final String pkg = (realActivity != null) ? realActivity.getPackageName() : null; - final LockTaskController lockTaskController = mAtmService.getLockTaskController(); - switch (r.lockTaskLaunchMode) { - case LOCK_TASK_LAUNCH_MODE_DEFAULT: - mLockTaskAuth = lockTaskController.isPackageWhitelisted(mUserId, pkg) - ? LOCK_TASK_AUTH_WHITELISTED : LOCK_TASK_AUTH_PINNABLE; - break; - - case LOCK_TASK_LAUNCH_MODE_NEVER: - mLockTaskAuth = LOCK_TASK_AUTH_DONT_LOCK; - break; - - case LOCK_TASK_LAUNCH_MODE_ALWAYS: - mLockTaskAuth = LOCK_TASK_AUTH_LAUNCHABLE_PRIV; - break; - - case LOCK_TASK_LAUNCH_MODE_IF_WHITELISTED: - mLockTaskAuth = lockTaskController.isPackageWhitelisted(mUserId, pkg) - ? LOCK_TASK_AUTH_LAUNCHABLE : LOCK_TASK_AUTH_PINNABLE; - break; - } - if (DEBUG_LOCKTASK) Slog.d(TAG_LOCKTASK, "setLockTaskAuth: task=" + this + - " mLockTaskAuth=" + lockTaskAuthToString()); - } - - @Override - public boolean supportsSplitScreenWindowingMode() { - // A task can not be docked even if it is considered resizeable because it only supports - // picture-in-picture mode but has a non-resizeable resizeMode - return super.supportsSplitScreenWindowingMode() - // TODO(task-group): Probably makes sense to move this and associated code into - // WindowContainer so it affects every node. - && mAtmService.mSupportsSplitScreenMultiWindow - && (mAtmService.mForceResizableActivities - || (isResizeable(false /* checkSupportsPip */) - && !ActivityInfo.isPreserveOrientationMode(mResizeMode))); - } - - /** - * Check whether this task can be launched on the specified display. - * - * @param displayId Target display id. - * @return {@code true} if either it is the default display or this activity can be put on a - * secondary display. - */ - boolean canBeLaunchedOnDisplay(int displayId) { - return mAtmService.mStackSupervisor.canPlaceEntityOnDisplay(displayId, - -1 /* don't check PID */, -1 /* don't check UID */, null /* activityInfo */); - } - - /** - * Check that a given bounds matches the application requested orientation. - * - * @param bounds The bounds to be tested. - * @return True if the requested bounds are okay for a resizing request. - */ - private boolean canResizeToBounds(Rect bounds) { - if (bounds == null || !inFreeformWindowingMode()) { - // Note: If not on the freeform workspace, we ignore the bounds. - return true; - } - final boolean landscape = bounds.width() > bounds.height(); - final Rect configBounds = getRequestedOverrideBounds(); - if (mResizeMode == RESIZE_MODE_FORCE_RESIZABLE_PRESERVE_ORIENTATION) { - return configBounds.isEmpty() - || landscape == (configBounds.width() > configBounds.height()); - } - return (mResizeMode != RESIZE_MODE_FORCE_RESIZABLE_PORTRAIT_ONLY || !landscape) - && (mResizeMode != RESIZE_MODE_FORCE_RESIZABLE_LANDSCAPE_ONLY || landscape); - } - - /** - * @return {@code true} if the task is being cleared for the purposes of being reused. - */ - boolean isClearingToReuseTask() { - return mReuseTask; - } - - /** - * Find the activity in the history stack within the given task. Returns - * the index within the history at which it's found, or < 0 if not found. - */ - final ActivityRecord findActivityInHistoryLocked(ActivityRecord r) { - final ComponentName realActivity = r.mActivityComponent; - for (int activityNdx = getChildCount() - 1; activityNdx >= 0; --activityNdx) { - ActivityRecord candidate = getChildAt(activityNdx); - if (candidate.finishing) { - continue; - } - if (candidate.mActivityComponent.equals(realActivity)) { - return candidate; - } - } - return null; - } - - /** Updates the last task description values. */ - void updateTaskDescription() { - // TODO(AM refactor): Cleanup to use findRootIndex() - // Traverse upwards looking for any break between main task activities and - // utility activities. - int activityNdx; - final int numActivities = getChildCount(); - final boolean relinquish = numActivities != 0 && - (getChildAt(0).info.flags & FLAG_RELINQUISH_TASK_IDENTITY) != 0; - for (activityNdx = Math.min(numActivities, 1); activityNdx < numActivities; - ++activityNdx) { - final ActivityRecord r = getChildAt(activityNdx); - if (relinquish && (r.info.flags & FLAG_RELINQUISH_TASK_IDENTITY) == 0) { - // This will be the top activity for determining taskDescription. Pre-inc to - // overcome initial decrement below. - ++activityNdx; - break; - } - if (r.intent != null && - (r.intent.getFlags() & Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) { - break; - } - } - if (activityNdx > 0) { - // Traverse downwards starting below break looking for set label, icon. - // Note that if there are activities in the task but none of them set the - // recent activity values, then we do not fall back to the last set - // values in the TaskRecord. - String label = null; - String iconFilename = null; - int iconResource = -1; - int colorPrimary = 0; - int colorBackground = 0; - int statusBarColor = 0; - int navigationBarColor = 0; - boolean statusBarContrastWhenTransparent = false; - boolean navigationBarContrastWhenTransparent = false; - boolean topActivity = true; - for (--activityNdx; activityNdx >= 0; --activityNdx) { - final ActivityRecord r = getChildAt(activityNdx); - if (r.mTaskOverlay) { - continue; - } - if (r.taskDescription != null) { - if (label == null) { - label = r.taskDescription.getLabel(); - } - if (iconResource == -1) { - iconResource = r.taskDescription.getIconResource(); - } - if (iconFilename == null) { - iconFilename = r.taskDescription.getIconFilename(); - } - if (colorPrimary == 0) { - colorPrimary = r.taskDescription.getPrimaryColor(); - } - if (topActivity) { - colorBackground = r.taskDescription.getBackgroundColor(); - statusBarColor = r.taskDescription.getStatusBarColor(); - navigationBarColor = r.taskDescription.getNavigationBarColor(); - statusBarContrastWhenTransparent = - r.taskDescription.getEnsureStatusBarContrastWhenTransparent(); - navigationBarContrastWhenTransparent = - r.taskDescription.getEnsureNavigationBarContrastWhenTransparent(); - } - } - topActivity = false; - } - final TaskDescription taskDescription = new TaskDescription(label, null, iconResource, - iconFilename, colorPrimary, colorBackground, statusBarColor, navigationBarColor, - statusBarContrastWhenTransparent, navigationBarContrastWhenTransparent, - mResizeMode, mMinWidth, mMinHeight); - setTaskDescription(taskDescription); - // Update the task affiliation color if we are the parent of the group - if (mTaskId == mAffiliatedTaskId) { - mAffiliatedTaskColor = taskDescription.getPrimaryColor(); - } - mAtmService.getTaskChangeNotificationController().notifyTaskDescriptionChanged( - getTaskInfo()); - } - } - - /** - * Find the index of the root activity in the task. It will be the first activity from the - * bottom that is not finishing. - * - * @param effectiveRoot Flag indicating whether 'effective root' should be returned - an - * activity that defines the task identity (its base intent). It's the - * first one that does not have - * {@link ActivityInfo#FLAG_RELINQUISH_TASK_IDENTITY}. - * @return index of the 'root' or 'effective' root in the list of activities, -1 if no eligible - * activity was found. - */ - int findRootIndex(boolean effectiveRoot) { - int effectiveNdx = -1; - final int topActivityNdx = getChildCount() - 1; - for (int activityNdx = 0; activityNdx <= topActivityNdx; ++activityNdx) { - final ActivityRecord r = getChildAt(activityNdx); - if (r.finishing) { - continue; - } - effectiveNdx = activityNdx; - if (!effectiveRoot || (r.info.flags & FLAG_RELINQUISH_TASK_IDENTITY) == 0) { - break; - } - } - return effectiveNdx; - } - - // TODO (AM refactor): Invoke automatically when there is a change in children - @VisibleForTesting - void updateEffectiveIntent() { - int effectiveRootIndex = findRootIndex(true /* effectiveRoot */); - if (effectiveRootIndex == -1) { - // All activities in the task are either finishing or relinquish task identity. - // But we still want to update the intent, so let's use the bottom activity. - effectiveRootIndex = 0; - } - final ActivityRecord r = getChildAt(effectiveRootIndex); - setIntent(r); - - // Update the task description when the activities change - updateTaskDescription(); - } - - void adjustForMinimalTaskDimensions(Rect bounds, Rect previousBounds) { - if (bounds == null) { - return; - } - int minWidth = mMinWidth; - int minHeight = mMinHeight; - // If the task has no requested minimal size, we'd like to enforce a minimal size - // so that the user can not render the task too small to manipulate. We don't need - // to do this for the pinned stack as the bounds are controlled by the system. - if (!inPinnedWindowingMode() && mStack != null) { - final int defaultMinSizeDp = - mAtmService.mRootActivityContainer.mDefaultMinSizeOfResizeableTaskDp; - final ActivityDisplay display = - mAtmService.mRootActivityContainer.getActivityDisplay(mStack.mDisplayId); - final float density = - (float) display.getConfiguration().densityDpi / DisplayMetrics.DENSITY_DEFAULT; - final int defaultMinSize = (int) (defaultMinSizeDp * density); - - if (minWidth == INVALID_MIN_SIZE) { - minWidth = defaultMinSize; - } - if (minHeight == INVALID_MIN_SIZE) { - minHeight = defaultMinSize; - } - } - final boolean adjustWidth = minWidth > bounds.width(); - final boolean adjustHeight = minHeight > bounds.height(); - if (!(adjustWidth || adjustHeight)) { - return; - } - - if (adjustWidth) { - if (!previousBounds.isEmpty() && bounds.right == previousBounds.right) { - bounds.left = bounds.right - minWidth; - } else { - // Either left bounds match, or neither match, or the previous bounds were - // fullscreen and we default to keeping left. - bounds.right = bounds.left + minWidth; - } - } - if (adjustHeight) { - if (!previousBounds.isEmpty() && bounds.bottom == previousBounds.bottom) { - bounds.top = bounds.bottom - minHeight; - } else { - // Either top bounds match, or neither match, or the previous bounds were - // fullscreen and we default to keeping top. - bounds.bottom = bounds.top + minHeight; - } - } - } - - void setLastNonFullscreenBounds(Rect bounds) { - if (mLastNonFullscreenBounds == null) { - mLastNonFullscreenBounds = new Rect(bounds); - } else { - mLastNonFullscreenBounds.set(bounds); - } - } - - /** - * This should be called when an child activity changes state. This should only - * be called from - * {@link ActivityRecord#setState(ActivityState, String)} . - * @param record The {@link ActivityRecord} whose state has changed. - * @param state The new state. - * @param reason The reason for the change. - */ - void onActivityStateChanged(ActivityRecord record, ActivityState state, String reason) { - final ActivityStack parent = getStack(); - - if (parent != null) { - parent.onActivityStateChanged(record, state, reason); - } - } - - @Override - public void onConfigurationChanged(Configuration newParentConfig) { - // Check if the new configuration supports persistent bounds (eg. is Freeform) and if so - // restore the last recorded non-fullscreen bounds. - final boolean prevPersistTaskBounds = getWindowConfiguration().persistTaskBounds(); - final boolean nextPersistTaskBounds = - getRequestedOverrideConfiguration().windowConfiguration.persistTaskBounds() - || newParentConfig.windowConfiguration.persistTaskBounds(); - if (!prevPersistTaskBounds && nextPersistTaskBounds - && mLastNonFullscreenBounds != null && !mLastNonFullscreenBounds.isEmpty()) { - // Bypass onRequestedOverrideConfigurationChanged here to avoid infinite loop. - getRequestedOverrideConfiguration().windowConfiguration - .setBounds(mLastNonFullscreenBounds); - } - - final boolean wasInMultiWindowMode = inMultiWindowMode(); - super.onConfigurationChanged(newParentConfig); - if (wasInMultiWindowMode != inMultiWindowMode()) { - mAtmService.mStackSupervisor.scheduleUpdateMultiWindowMode(this); - } - - // If the configuration supports persistent bounds (eg. Freeform), keep track of the - // current (non-fullscreen) bounds for persistence. - if (getWindowConfiguration().persistTaskBounds()) { - final Rect currentBounds = getRequestedOverrideBounds(); - if (!currentBounds.isEmpty()) { - setLastNonFullscreenBounds(currentBounds); - } - } - // TODO: Should also take care of Pip mode changes here. - - saveLaunchingStateIfNeeded(); - } - - /** - * Saves launching state if necessary so that we can launch the activity to its latest state. - * It only saves state if this task has been shown to user and it's in fullscreen or freeform - * mode on freeform displays. - */ - void saveLaunchingStateIfNeeded() { - if (!hasBeenVisible) { - // Not ever visible to user. - return; - } - - final int windowingMode = getWindowingMode(); - if (windowingMode != WINDOWING_MODE_FULLSCREEN - && windowingMode != WINDOWING_MODE_FREEFORM) { - return; - } - - // Don't persist state if display isn't in freeform mode. Then the task will be launched - // back to its last state in a freeform display when it's launched in a freeform display - // next time. - if (getWindowConfiguration().getDisplayWindowingMode() != WINDOWING_MODE_FREEFORM) { - return; - } - - // Saves the new state so that we can launch the activity at the same location. - mAtmService.mStackSupervisor.mLaunchParamsPersister.saveTask(this); - } - - /** - * Adjust bounds to stay within stack bounds. - * - * Since bounds might be outside of stack bounds, this method tries to move the bounds in a way - * that keep them unchanged, but be contained within the stack bounds. - * - * @param bounds Bounds to be adjusted. - * @param stackBounds Bounds within which the other bounds should remain. - * @param overlapPxX The amount of px required to be visible in the X dimension. - * @param overlapPxY The amount of px required to be visible in the Y dimension. - */ - private static void fitWithinBounds(Rect bounds, Rect stackBounds, int overlapPxX, - int overlapPxY) { - if (stackBounds == null || stackBounds.isEmpty() || stackBounds.contains(bounds)) { - return; - } - - // For each side of the parent (eg. left), check if the opposing side of the window (eg. - // right) is at least overlap pixels away. If less, offset the window by that difference. - int horizontalDiff = 0; - // If window is smaller than overlap, use it's smallest dimension instead - int overlapLR = Math.min(overlapPxX, bounds.width()); - if (bounds.right < (stackBounds.left + overlapLR)) { - horizontalDiff = overlapLR - (bounds.right - stackBounds.left); - } else if (bounds.left > (stackBounds.right - overlapLR)) { - horizontalDiff = -(overlapLR - (stackBounds.right - bounds.left)); - } - int verticalDiff = 0; - int overlapTB = Math.min(overlapPxY, bounds.width()); - if (bounds.bottom < (stackBounds.top + overlapTB)) { - verticalDiff = overlapTB - (bounds.bottom - stackBounds.top); - } else if (bounds.top > (stackBounds.bottom - overlapTB)) { - verticalDiff = -(overlapTB - (stackBounds.bottom - bounds.top)); - } - bounds.offset(horizontalDiff, verticalDiff); - } - - /** - * Intersects inOutBounds with intersectBounds-intersectInsets. If inOutBounds is larger than - * intersectBounds on a side, then the respective side will not be intersected. - * - * The assumption is that if inOutBounds is initially larger than intersectBounds, then the - * inset on that side is no-longer applicable. This scenario happens when a task's minimal - * bounds are larger than the provided parent/display bounds. - * - * @param inOutBounds the bounds to intersect. - * @param intersectBounds the bounds to intersect with. - * @param intersectInsets insets to apply to intersectBounds before intersecting. - */ - static void intersectWithInsetsIfFits( - Rect inOutBounds, Rect intersectBounds, Rect intersectInsets) { - if (inOutBounds.right <= intersectBounds.right) { - inOutBounds.right = - Math.min(intersectBounds.right - intersectInsets.right, inOutBounds.right); - } - if (inOutBounds.bottom <= intersectBounds.bottom) { - inOutBounds.bottom = - Math.min(intersectBounds.bottom - intersectInsets.bottom, inOutBounds.bottom); - } - if (inOutBounds.left >= intersectBounds.left) { - inOutBounds.left = - Math.max(intersectBounds.left + intersectInsets.left, inOutBounds.left); - } - if (inOutBounds.top >= intersectBounds.top) { - inOutBounds.top = - Math.max(intersectBounds.top + intersectInsets.top, inOutBounds.top); - } - } - - /** - * Gets bounds with non-decor and stable insets applied respectively. - * - * If bounds overhangs the display, those edges will not get insets. See - * {@link #intersectWithInsetsIfFits} - * - * @param outNonDecorBounds where to place bounds with non-decor insets applied. - * @param outStableBounds where to place bounds with stable insets applied. - * @param bounds the bounds to inset. - */ - private void calculateInsetFrames(Rect outNonDecorBounds, Rect outStableBounds, Rect bounds, - DisplayInfo displayInfo) { - outNonDecorBounds.set(bounds); - outStableBounds.set(bounds); - if (getStack() == null || getStack().getDisplay() == null) { - return; - } - DisplayPolicy policy = getStack().getDisplay().mDisplayContent.getDisplayPolicy(); - if (policy == null) { - return; - } - mTmpBounds.set(0, 0, displayInfo.logicalWidth, displayInfo.logicalHeight); - - policy.getNonDecorInsetsLw(displayInfo.rotation, displayInfo.logicalWidth, - displayInfo.logicalHeight, displayInfo.displayCutout, mTmpInsets); - intersectWithInsetsIfFits(outNonDecorBounds, mTmpBounds, mTmpInsets); - - policy.convertNonDecorInsetsToStableInsets(mTmpInsets, displayInfo.rotation); - intersectWithInsetsIfFits(outStableBounds, mTmpBounds, mTmpInsets); - } - - /** - * Asks docked-divider controller for the smallestwidthdp given bounds. - * @param bounds bounds to calculate smallestwidthdp for. - */ - private int getSmallestScreenWidthDpForDockedBounds(Rect bounds) { - DisplayContent dc = mStack.getDisplay().mDisplayContent; - if (dc != null) { - return dc.getDockedDividerController().getSmallestWidthDpForBounds(bounds); - } - return Configuration.SMALLEST_SCREEN_WIDTH_DP_UNDEFINED; - } - - void computeConfigResourceOverrides(@NonNull Configuration inOutConfig, - @NonNull Configuration parentConfig) { - computeConfigResourceOverrides(inOutConfig, parentConfig, null /* compatInsets */); - } - - /** - * Calculates configuration values used by the client to get resources. This should be run - * using app-facing bounds (bounds unmodified by animations or transient interactions). - * - * This assumes bounds are non-empty/null. For the null-bounds case, the caller is likely - * configuring an "inherit-bounds" window which means that all configuration settings would - * just be inherited from the parent configuration. - **/ - void computeConfigResourceOverrides(@NonNull Configuration inOutConfig, - @NonNull Configuration parentConfig, - @Nullable ActivityRecord.CompatDisplayInsets compatInsets) { - int windowingMode = inOutConfig.windowConfiguration.getWindowingMode(); - if (windowingMode == WINDOWING_MODE_UNDEFINED) { - windowingMode = parentConfig.windowConfiguration.getWindowingMode(); - } - - float density = inOutConfig.densityDpi; - if (density == Configuration.DENSITY_DPI_UNDEFINED) { - density = parentConfig.densityDpi; - } - density *= DisplayMetrics.DENSITY_DEFAULT_SCALE; - - final Rect bounds = inOutConfig.windowConfiguration.getBounds(); - Rect outAppBounds = inOutConfig.windowConfiguration.getAppBounds(); - if (outAppBounds == null || outAppBounds.isEmpty()) { - inOutConfig.windowConfiguration.setAppBounds(bounds); - outAppBounds = inOutConfig.windowConfiguration.getAppBounds(); - } - // Non-null compatibility insets means the activity prefers to keep its original size, so - // the out bounds doesn't need to be restricted by the parent. - final boolean insideParentBounds = compatInsets == null; - if (insideParentBounds && windowingMode != WINDOWING_MODE_FREEFORM) { - final Rect parentAppBounds = parentConfig.windowConfiguration.getAppBounds(); - if (parentAppBounds != null && !parentAppBounds.isEmpty()) { - outAppBounds.intersect(parentAppBounds); - } - } - - if (inOutConfig.screenWidthDp == Configuration.SCREEN_WIDTH_DP_UNDEFINED - || inOutConfig.screenHeightDp == Configuration.SCREEN_HEIGHT_DP_UNDEFINED) { - if (insideParentBounds && mStack != null) { - final DisplayInfo di = new DisplayInfo(); - mStack.getDisplay().mDisplay.getDisplayInfo(di); - - // For calculating screenWidthDp, screenWidthDp, we use the stable inset screen - // area, i.e. the screen area without the system bars. - // The non decor inset are areas that could never be removed in Honeycomb. See - // {@link WindowManagerPolicy#getNonDecorInsetsLw}. - calculateInsetFrames(mTmpNonDecorBounds, mTmpStableBounds, bounds, di); - } else { - // Apply the given non-decor and stable insets to calculate the corresponding bounds - // for screen size of configuration. - int rotation = inOutConfig.windowConfiguration.getRotation(); - if (rotation == ROTATION_UNDEFINED) { - rotation = parentConfig.windowConfiguration.getRotation(); - } - if (rotation != ROTATION_UNDEFINED && compatInsets != null) { - mTmpNonDecorBounds.set(bounds); - mTmpStableBounds.set(bounds); - compatInsets.getDisplayBoundsByRotation(mTmpBounds, rotation); - intersectWithInsetsIfFits(mTmpNonDecorBounds, mTmpBounds, - compatInsets.mNonDecorInsets[rotation]); - intersectWithInsetsIfFits(mTmpStableBounds, mTmpBounds, - compatInsets.mStableInsets[rotation]); - outAppBounds.set(mTmpNonDecorBounds); - } else { - // Set to app bounds because it excludes decor insets. - mTmpNonDecorBounds.set(outAppBounds); - mTmpStableBounds.set(outAppBounds); - } - } - - if (inOutConfig.screenWidthDp == Configuration.SCREEN_WIDTH_DP_UNDEFINED) { - final int overrideScreenWidthDp = (int) (mTmpStableBounds.width() / density); - inOutConfig.screenWidthDp = insideParentBounds - ? Math.min(overrideScreenWidthDp, parentConfig.screenWidthDp) - : overrideScreenWidthDp; - } - if (inOutConfig.screenHeightDp == Configuration.SCREEN_HEIGHT_DP_UNDEFINED) { - final int overrideScreenHeightDp = (int) (mTmpStableBounds.height() / density); - inOutConfig.screenHeightDp = insideParentBounds - ? Math.min(overrideScreenHeightDp, parentConfig.screenHeightDp) - : overrideScreenHeightDp; - } - - if (inOutConfig.smallestScreenWidthDp - == Configuration.SMALLEST_SCREEN_WIDTH_DP_UNDEFINED) { - if (WindowConfiguration.isFloating(windowingMode)) { - // For floating tasks, calculate the smallest width from the bounds of the task - inOutConfig.smallestScreenWidthDp = (int) ( - Math.min(bounds.width(), bounds.height()) / density); - } else if (WindowConfiguration.isSplitScreenWindowingMode(windowingMode)) { - // Iterating across all screen orientations, and return the minimum of the task - // width taking into account that the bounds might change because the snap - // algorithm snaps to a different value - inOutConfig.smallestScreenWidthDp = - getSmallestScreenWidthDpForDockedBounds(bounds); - } - // otherwise, it will just inherit - } - } - - if (inOutConfig.orientation == ORIENTATION_UNDEFINED) { - inOutConfig.orientation = (inOutConfig.screenWidthDp <= inOutConfig.screenHeightDp) - ? ORIENTATION_PORTRAIT : ORIENTATION_LANDSCAPE; - } - if (inOutConfig.screenLayout == Configuration.SCREENLAYOUT_UNDEFINED) { - // For calculating screen layout, we need to use the non-decor inset screen area for the - // calculation for compatibility reasons, i.e. screen area without system bars that - // could never go away in Honeycomb. - final int compatScreenWidthDp = (int) (mTmpNonDecorBounds.width() / density); - final int compatScreenHeightDp = (int) (mTmpNonDecorBounds.height() / density); - // We're only overriding LONG, SIZE and COMPAT parts of screenLayout, so we start - // override calculation with partial default. - // Reducing the screen layout starting from its parent config. - final int sl = parentConfig.screenLayout - & (Configuration.SCREENLAYOUT_LONG_MASK | Configuration.SCREENLAYOUT_SIZE_MASK); - final int longSize = Math.max(compatScreenHeightDp, compatScreenWidthDp); - final int shortSize = Math.min(compatScreenHeightDp, compatScreenWidthDp); - inOutConfig.screenLayout = Configuration.reduceScreenLayout(sl, longSize, shortSize); - } - } - - @Override - void resolveOverrideConfiguration(Configuration newParentConfig) { - mTmpBounds.set(getResolvedOverrideConfiguration().windowConfiguration.getBounds()); - super.resolveOverrideConfiguration(newParentConfig); - int windowingMode = - getRequestedOverrideConfiguration().windowConfiguration.getWindowingMode(); - if (windowingMode == WINDOWING_MODE_UNDEFINED) { - windowingMode = newParentConfig.windowConfiguration.getWindowingMode(); - } - Rect outOverrideBounds = - getResolvedOverrideConfiguration().windowConfiguration.getBounds(); - - if (windowingMode == WINDOWING_MODE_FULLSCREEN) { - computeFullscreenBounds(outOverrideBounds, null /* refActivity */, - newParentConfig.windowConfiguration.getBounds(), - newParentConfig.orientation); - } - - if (outOverrideBounds.isEmpty()) { - // If the task fills the parent, just inherit all the other configs from parent. - return; - } - - adjustForMinimalTaskDimensions(outOverrideBounds, mTmpBounds); - if (windowingMode == WINDOWING_MODE_FREEFORM) { - // by policy, make sure the window remains within parent somewhere - final float density = - ((float) newParentConfig.densityDpi) / DisplayMetrics.DENSITY_DEFAULT; - final Rect parentBounds = - new Rect(newParentConfig.windowConfiguration.getBounds()); - final ActivityDisplay display = mStack.getDisplay(); - if (display != null && display.mDisplayContent != null) { - // If a freeform window moves below system bar, there is no way to move it again - // by touch. Because its caption is covered by system bar. So we exclude them - // from stack bounds. and then caption will be shown inside stable area. - final Rect stableBounds = new Rect(); - display.mDisplayContent.getStableRect(stableBounds); - parentBounds.intersect(stableBounds); - } - - fitWithinBounds(outOverrideBounds, parentBounds, - (int) (density * WindowState.MINIMUM_VISIBLE_WIDTH_IN_DP), - (int) (density * WindowState.MINIMUM_VISIBLE_HEIGHT_IN_DP)); - - // Prevent to overlap caption with stable insets. - final int offsetTop = parentBounds.top - outOverrideBounds.top; - if (offsetTop > 0) { - outOverrideBounds.offset(0, offsetTop); - } - } - computeConfigResourceOverrides(getResolvedOverrideConfiguration(), newParentConfig); - } - - /** - * Compute bounds (letterbox or pillarbox) for - * {@link WindowConfiguration#WINDOWING_MODE_FULLSCREEN} when the parent doesn't handle the - * orientation change and the requested orientation is different from the parent. - */ - void computeFullscreenBounds(@NonNull Rect outBounds, @Nullable ActivityRecord refActivity, - @NonNull Rect parentBounds, int parentOrientation) { - // In FULLSCREEN mode, always start with empty bounds to indicate "fill parent". - outBounds.setEmpty(); - if (handlesOrientationChangeFromDescendant()) { - return; - } - if (refActivity == null) { - // Use the top activity as the reference of orientation. Don't include overlays because - // it is usually not the actual content or just temporarily shown. - // E.g. ForcedResizableInfoActivity. - refActivity = getTopActivity(false /* includeOverlays */); - } - - // If the task or the reference activity requires a different orientation (either by - // override or activityInfo), make it fit the available bounds by scaling down its bounds. - final int overrideOrientation = getRequestedOverrideConfiguration().orientation; - final int forcedOrientation = - (overrideOrientation != ORIENTATION_UNDEFINED || refActivity == null) - ? overrideOrientation : refActivity.getRequestedConfigurationOrientation(); - if (forcedOrientation == ORIENTATION_UNDEFINED || forcedOrientation == parentOrientation) { - return; - } - - final int parentWidth = parentBounds.width(); - final int parentHeight = parentBounds.height(); - final float aspect = ((float) parentHeight) / parentWidth; - if (forcedOrientation == ORIENTATION_LANDSCAPE) { - final int height = (int) (parentWidth / aspect); - final int top = parentBounds.centerY() - height / 2; - outBounds.set(parentBounds.left, top, parentBounds.right, top + height); - } else { - final int width = (int) (parentHeight * aspect); - final int left = parentBounds.centerX() - width / 2; - outBounds.set(left, parentBounds.top, left + width, parentBounds.bottom); - } - } - - Rect updateOverrideConfigurationFromLaunchBounds() { - final Rect bounds = getLaunchBounds(); - setBounds(bounds); - if (bounds != null && !bounds.isEmpty()) { - // TODO: Review if we actually want to do this - we are setting the launch bounds - // directly here. - bounds.set(getRequestedOverrideBounds()); - } - return bounds; - } - - /** Updates the task's bounds and override configuration to match what is expected for the - * input stack. */ - void updateOverrideConfigurationForStack(ActivityStack inStack) { - if (mStack != null && mStack == inStack) { - return; - } - - if (inStack.inFreeformWindowingMode()) { - if (!isResizeable()) { - throw new IllegalArgumentException("Can not position non-resizeable task=" - + this + " in stack=" + inStack); - } - if (!matchParentBounds()) { - return; - } - if (mLastNonFullscreenBounds != null) { - setBounds(mLastNonFullscreenBounds); - } else { - mAtmService.mStackSupervisor.getLaunchParamsController().layoutTask(this, null); - } - } else { - setBounds(inStack.getRequestedOverrideBounds()); - } - } - - /** Returns the bounds that should be used to launch this task. */ - Rect getLaunchBounds() { - if (mStack == null) { - return null; - } - - final int windowingMode = getWindowingMode(); - if (!isActivityTypeStandardOrUndefined() - || windowingMode == WINDOWING_MODE_FULLSCREEN - || (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY && !isResizeable())) { - return isResizeable() ? mStack.getRequestedOverrideBounds() : null; - } else if (!getWindowConfiguration().persistTaskBounds()) { - return mStack.getRequestedOverrideBounds(); - } - return mLastNonFullscreenBounds; - } - - void addStartingWindowsForVisibleActivities(boolean taskSwitch) { - for (int activityNdx = getChildCount() - 1; activityNdx >= 0; --activityNdx) { - final ActivityRecord r = getChildAt(activityNdx); - if (r.visible) { - r.showStartingWindow(null /* prev */, false /* newTask */, taskSwitch); - } - } - } - - void setRootProcess(WindowProcessController proc) { - clearRootProcess(); - if (intent != null && - (intent.getFlags() & Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0) { - mRootProcess = proc; - mRootProcess.addRecentTask(this); - } - } - - void clearRootProcess() { - if (mRootProcess != null) { - mRootProcess.removeRecentTask(this); - mRootProcess = null; - } - } - - void clearAllPendingOptions() { - for (int i = getChildCount() - 1; i >= 0; i--) { - getChildAt(i).clearOptionsLocked(false /* withAbort */); - } - } - - /** - * Fills in a {@link TaskInfo} with information from this task. - * @param info the {@link TaskInfo} to fill in - */ - void fillTaskInfo(TaskInfo info) { - getNumRunningActivities(mReuseActivitiesReport); - info.userId = mUserId; - info.stackId = getStackId(); - info.taskId = mTaskId; - info.displayId = mStack == null ? Display.INVALID_DISPLAY : mStack.mDisplayId; - info.isRunning = getTopActivity() != null; - info.baseIntent = new Intent(getBaseIntent()); - info.baseActivity = mReuseActivitiesReport.base != null - ? mReuseActivitiesReport.base.intent.getComponent() - : null; - info.topActivity = mReuseActivitiesReport.top != null - ? mReuseActivitiesReport.top.mActivityComponent - : null; - info.origActivity = origActivity; - info.realActivity = realActivity; - info.numActivities = mReuseActivitiesReport.numActivities; - info.lastActiveTime = lastActiveTime; - info.taskDescription = new ActivityManager.TaskDescription(getTaskDescription()); - info.supportsSplitScreenMultiWindow = supportsSplitScreenWindowingMode(); - info.resizeMode = mResizeMode; - info.configuration.setTo(getConfiguration()); - } - - /** - * Returns a {@link TaskInfo} with information from this task. - */ - ActivityManager.RunningTaskInfo getTaskInfo() { - ActivityManager.RunningTaskInfo info = new ActivityManager.RunningTaskInfo(); - fillTaskInfo(info); - return info; - } - - void dump(PrintWriter pw, String prefix) { - pw.print(prefix); pw.print("userId="); pw.print(mUserId); - pw.print(" effectiveUid="); UserHandle.formatUid(pw, effectiveUid); - pw.print(" mCallingUid="); UserHandle.formatUid(pw, mCallingUid); - pw.print(" mUserSetupComplete="); pw.print(mUserSetupComplete); - pw.print(" mCallingPackage="); pw.println(mCallingPackage); - if (affinity != null || rootAffinity != null) { - pw.print(prefix); pw.print("affinity="); pw.print(affinity); - if (affinity == null || !affinity.equals(rootAffinity)) { - pw.print(" root="); pw.println(rootAffinity); - } else { - pw.println(); - } - } - if (voiceSession != null || voiceInteractor != null) { - pw.print(prefix); pw.print("VOICE: session=0x"); - pw.print(Integer.toHexString(System.identityHashCode(voiceSession))); - pw.print(" interactor=0x"); - pw.println(Integer.toHexString(System.identityHashCode(voiceInteractor))); - } - if (intent != null) { - StringBuilder sb = new StringBuilder(128); - sb.append(prefix); sb.append("intent={"); - intent.toShortString(sb, false, true, false, false); - sb.append('}'); - pw.println(sb.toString()); - } - if (affinityIntent != null) { - StringBuilder sb = new StringBuilder(128); - sb.append(prefix); sb.append("affinityIntent={"); - affinityIntent.toShortString(sb, false, true, false, false); - sb.append('}'); - pw.println(sb.toString()); - } - if (origActivity != null) { - pw.print(prefix); pw.print("origActivity="); - pw.println(origActivity.flattenToShortString()); - } - if (realActivity != null) { - pw.print(prefix); pw.print("mActivityComponent="); - pw.println(realActivity.flattenToShortString()); - } - if (autoRemoveRecents || isPersistable || !isActivityTypeStandard() || numFullscreen != 0) { - pw.print(prefix); pw.print("autoRemoveRecents="); pw.print(autoRemoveRecents); - pw.print(" isPersistable="); pw.print(isPersistable); - pw.print(" numFullscreen="); pw.print(numFullscreen); - pw.print(" activityType="); pw.println(getActivityType()); - } - if (rootWasReset || mNeverRelinquishIdentity || mReuseTask - || mLockTaskAuth != LOCK_TASK_AUTH_PINNABLE) { - pw.print(prefix); pw.print("rootWasReset="); pw.print(rootWasReset); - pw.print(" mNeverRelinquishIdentity="); pw.print(mNeverRelinquishIdentity); - pw.print(" mReuseTask="); pw.print(mReuseTask); - pw.print(" mLockTaskAuth="); pw.println(lockTaskAuthToString()); - } - if (mAffiliatedTaskId != mTaskId || mPrevAffiliateTaskId != INVALID_TASK_ID - || mPrevAffiliate != null || mNextAffiliateTaskId != INVALID_TASK_ID - || mNextAffiliate != null) { - pw.print(prefix); pw.print("affiliation="); pw.print(mAffiliatedTaskId); - pw.print(" prevAffiliation="); pw.print(mPrevAffiliateTaskId); - pw.print(" ("); - if (mPrevAffiliate == null) { - pw.print("null"); - } else { - pw.print(Integer.toHexString(System.identityHashCode(mPrevAffiliate))); - } - pw.print(") nextAffiliation="); pw.print(mNextAffiliateTaskId); - pw.print(" ("); - if (mNextAffiliate == null) { - pw.print("null"); - } else { - pw.print(Integer.toHexString(System.identityHashCode(mNextAffiliate))); - } - pw.println(")"); - } - pw.print(prefix); pw.print("Activities="); pw.println(mChildren); - if (!askedCompatMode || !inRecents || !isAvailable) { - pw.print(prefix); pw.print("askedCompatMode="); pw.print(askedCompatMode); - pw.print(" inRecents="); pw.print(inRecents); - pw.print(" isAvailable="); pw.println(isAvailable); - } - if (lastDescription != null) { - pw.print(prefix); pw.print("lastDescription="); pw.println(lastDescription); - } - if (mRootProcess != null) { - pw.print(prefix); pw.print("mRootProcess="); pw.println(mRootProcess); - } - pw.print(prefix); pw.print("stackId="); pw.println(getStackId()); - pw.print(prefix + "hasBeenVisible=" + hasBeenVisible); - pw.print(" mResizeMode=" + ActivityInfo.resizeModeToString(mResizeMode)); - pw.print(" mSupportsPictureInPicture=" + mSupportsPictureInPicture); - pw.print(" isResizeable=" + isResizeable()); - pw.print(" lastActiveTime=" + lastActiveTime); - pw.println(" (inactive for " + (getInactiveDuration() / 1000) + "s)"); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(128); - if (stringName != null) { - sb.append(stringName); - sb.append(" U="); - sb.append(mUserId); - sb.append(" StackId="); - sb.append(getStackId()); - sb.append(" sz="); - sb.append(getChildCount()); - sb.append('}'); - return sb.toString(); - } - sb.append("TaskRecord{"); - sb.append(Integer.toHexString(System.identityHashCode(this))); - sb.append(" #"); - sb.append(mTaskId); - if (affinity != null) { - sb.append(" A="); - sb.append(affinity); - } else if (intent != null) { - sb.append(" I="); - sb.append(intent.getComponent().flattenToShortString()); - } else if (affinityIntent != null && affinityIntent.getComponent() != null) { - sb.append(" aI="); - sb.append(affinityIntent.getComponent().flattenToShortString()); - } else { - sb.append(" ??"); - } - stringName = sb.toString(); - return toString(); - } - - @Override - public void writeToProto(ProtoOutputStream proto, long fieldId, - @WindowTraceLogLevel int logLevel) { - if (logLevel == WindowTraceLogLevel.CRITICAL && !isVisible()) { - return; - } - - final long token = proto.start(fieldId); - writeToProtoInnerTaskOnly(proto, TASK, logLevel); - proto.write(ID, mTaskId); - for (int i = getChildCount() - 1; i >= 0; i--) { - final ActivityRecord activity = getChildAt(i); - activity.writeToProto(proto, ACTIVITIES); - } - proto.write(STACK_ID, getStackId()); - if (mLastNonFullscreenBounds != null) { - mLastNonFullscreenBounds.writeToProto(proto, LAST_NON_FULLSCREEN_BOUNDS); - } - if (realActivity != null) { - proto.write(REAL_ACTIVITY, realActivity.flattenToShortString()); - } - if (origActivity != null) { - proto.write(ORIG_ACTIVITY, origActivity.flattenToShortString()); - } - proto.write(ACTIVITY_TYPE, getActivityType()); - proto.write(RESIZE_MODE, mResizeMode); - // TODO: Remove, no longer needed with windowingMode. - proto.write(FULLSCREEN, matchParentBounds()); - - if (!matchParentBounds()) { - final Rect bounds = getRequestedOverrideBounds(); - bounds.writeToProto(proto, BOUNDS); - } - proto.write(MIN_WIDTH, mMinWidth); - proto.write(MIN_HEIGHT, mMinHeight); - proto.end(token); - } - - /** - * See {@link #getNumRunningActivities(TaskActivitiesReport)}. - */ - static class TaskActivitiesReport { - int numRunning; - int numActivities; - ActivityRecord top; - ActivityRecord base; - - void reset() { - numRunning = numActivities = 0; - top = base = null; - } - } - - /** - * Saves this {@link TaskRecord} to XML using given serializer. - */ - void saveToXml(XmlSerializer out) throws IOException, XmlPullParserException { - if (DEBUG_RECENTS) Slog.i(TAG_RECENTS, "Saving task=" + this); - - out.attribute(null, ATTR_TASKID, String.valueOf(mTaskId)); - if (realActivity != null) { - out.attribute(null, ATTR_REALACTIVITY, realActivity.flattenToShortString()); - } - out.attribute(null, ATTR_REALACTIVITY_SUSPENDED, String.valueOf(realActivitySuspended)); - if (origActivity != null) { - out.attribute(null, ATTR_ORIGACTIVITY, origActivity.flattenToShortString()); - } - // Write affinity, and root affinity if it is different from affinity. - // We use the special string "@" for a null root affinity, so we can identify - // later whether we were given a root affinity or should just make it the - // same as the affinity. - if (affinity != null) { - out.attribute(null, ATTR_AFFINITY, affinity); - if (!affinity.equals(rootAffinity)) { - out.attribute(null, ATTR_ROOT_AFFINITY, rootAffinity != null ? rootAffinity : "@"); - } - } else if (rootAffinity != null) { - out.attribute(null, ATTR_ROOT_AFFINITY, rootAffinity != null ? rootAffinity : "@"); - } - out.attribute(null, ATTR_ROOTHASRESET, String.valueOf(rootWasReset)); - out.attribute(null, ATTR_AUTOREMOVERECENTS, String.valueOf(autoRemoveRecents)); - out.attribute(null, ATTR_ASKEDCOMPATMODE, String.valueOf(askedCompatMode)); - out.attribute(null, ATTR_USERID, String.valueOf(mUserId)); - out.attribute(null, ATTR_USER_SETUP_COMPLETE, String.valueOf(mUserSetupComplete)); - out.attribute(null, ATTR_EFFECTIVE_UID, String.valueOf(effectiveUid)); - out.attribute(null, ATTR_LASTTIMEMOVED, String.valueOf(mLastTimeMoved)); - out.attribute(null, ATTR_NEVERRELINQUISH, String.valueOf(mNeverRelinquishIdentity)); - if (lastDescription != null) { - out.attribute(null, ATTR_LASTDESCRIPTION, lastDescription.toString()); - } - if (getTaskDescription() != null) { - getTaskDescription().saveToXml(out); - } - out.attribute(null, ATTR_TASK_AFFILIATION_COLOR, String.valueOf(mAffiliatedTaskColor)); - out.attribute(null, ATTR_TASK_AFFILIATION, String.valueOf(mAffiliatedTaskId)); - out.attribute(null, ATTR_PREV_AFFILIATION, String.valueOf(mPrevAffiliateTaskId)); - out.attribute(null, ATTR_NEXT_AFFILIATION, String.valueOf(mNextAffiliateTaskId)); - out.attribute(null, ATTR_CALLING_UID, String.valueOf(mCallingUid)); - out.attribute(null, ATTR_CALLING_PACKAGE, mCallingPackage == null ? "" : mCallingPackage); - out.attribute(null, ATTR_RESIZE_MODE, String.valueOf(mResizeMode)); - out.attribute(null, ATTR_SUPPORTS_PICTURE_IN_PICTURE, - String.valueOf(mSupportsPictureInPicture)); - if (mLastNonFullscreenBounds != null) { - out.attribute( - null, ATTR_NON_FULLSCREEN_BOUNDS, mLastNonFullscreenBounds.flattenToString()); - } - out.attribute(null, ATTR_MIN_WIDTH, String.valueOf(mMinWidth)); - out.attribute(null, ATTR_MIN_HEIGHT, String.valueOf(mMinHeight)); - out.attribute(null, ATTR_PERSIST_TASK_VERSION, String.valueOf(PERSIST_TASK_VERSION)); - - if (affinityIntent != null) { - out.startTag(null, TAG_AFFINITYINTENT); - affinityIntent.saveToXml(out); - out.endTag(null, TAG_AFFINITYINTENT); - } - - if (intent != null) { - out.startTag(null, TAG_INTENT); - intent.saveToXml(out); - out.endTag(null, TAG_INTENT); - } - - final int numActivities = getChildCount(); - for (int activityNdx = 0; activityNdx < numActivities; ++activityNdx) { - final ActivityRecord r = getChildAt(activityNdx); - if (r.info.persistableMode == ActivityInfo.PERSIST_ROOT_ONLY || !r.isPersistable() || - ((r.intent.getFlags() & FLAG_ACTIVITY_NEW_DOCUMENT - | FLAG_ACTIVITY_RETAIN_IN_RECENTS) == FLAG_ACTIVITY_NEW_DOCUMENT) && - activityNdx > 0) { - // Stop at first non-persistable or first break in task (CLEAR_WHEN_TASK_RESET). - break; - } - out.startTag(null, TAG_ACTIVITY); - r.saveToXml(out); - out.endTag(null, TAG_ACTIVITY); - } - } - - @VisibleForTesting - static TaskRecordFactory getTaskRecordFactory() { - if (sTaskRecordFactory == null) { - setTaskRecordFactory(new TaskRecordFactory()); - } - return sTaskRecordFactory; - } - - static void setTaskRecordFactory(TaskRecordFactory factory) { - sTaskRecordFactory = factory; - } - - static TaskRecord create(ActivityTaskManagerService service, int taskId, ActivityInfo info, - Intent intent, IVoiceInteractionSession voiceSession, - IVoiceInteractor voiceInteractor, ActivityStack stack) { - return getTaskRecordFactory().create( - service, taskId, info, intent, voiceSession, voiceInteractor, stack); - } - - static TaskRecord create(ActivityTaskManagerService service, int taskId, ActivityInfo info, - Intent intent, TaskDescription taskDescription, ActivityStack stack) { - return getTaskRecordFactory().create(service, taskId, info, intent, taskDescription, stack); - } - - static TaskRecord restoreFromXml(XmlPullParser in, ActivityStackSupervisor stackSupervisor) - throws IOException, XmlPullParserException { - return getTaskRecordFactory().restoreFromXml(in, stackSupervisor); - } - - /** - * A factory class used to create {@link TaskRecord} or its subclass if any. This can be - * specified when system boots by setting it with - * {@link #setTaskRecordFactory(TaskRecordFactory)}. - */ - static class TaskRecordFactory { - - TaskRecord create(ActivityTaskManagerService service, int taskId, ActivityInfo info, - Intent intent, IVoiceInteractionSession voiceSession, - IVoiceInteractor voiceInteractor, ActivityStack stack) { - return new TaskRecord(service, taskId, info, intent, voiceSession, voiceInteractor, - null /*taskDescription*/, stack); - } - - TaskRecord create(ActivityTaskManagerService service, int taskId, ActivityInfo info, - Intent intent, TaskDescription taskDescription, ActivityStack stack) { - return new TaskRecord(service, taskId, info, intent, null /*voiceSession*/, - null /*voiceInteractor*/, taskDescription, stack); - } - - /** - * Should only be used when we're restoring {@link TaskRecord} from storage. - */ - TaskRecord create(ActivityTaskManagerService service, int taskId, Intent intent, - Intent affinityIntent, String affinity, String rootAffinity, - ComponentName realActivity, ComponentName origActivity, boolean rootWasReset, - boolean autoRemoveRecents, boolean askedCompatMode, int userId, - int effectiveUid, String lastDescription, - long lastTimeMoved, boolean neverRelinquishIdentity, - TaskDescription lastTaskDescription, int taskAffiliation, int prevTaskId, - int nextTaskId, int taskAffiliationColor, int callingUid, String callingPackage, - int resizeMode, boolean supportsPictureInPicture, boolean realActivitySuspended, - boolean userSetupComplete, int minWidth, int minHeight, ActivityStack stack) { - return new TaskRecord(service, taskId, intent, affinityIntent, affinity, - rootAffinity, realActivity, origActivity, rootWasReset, autoRemoveRecents, - askedCompatMode, userId, effectiveUid, lastDescription, - lastTimeMoved, neverRelinquishIdentity, lastTaskDescription, taskAffiliation, - prevTaskId, nextTaskId, taskAffiliationColor, callingUid, callingPackage, - resizeMode, supportsPictureInPicture, realActivitySuspended, userSetupComplete, - minWidth, minHeight, null /*ActivityInfo*/, null /*_voiceSession*/, - null /*_voiceInteractor*/, stack); - } - - TaskRecord restoreFromXml(XmlPullParser in, ActivityStackSupervisor stackSupervisor) - throws IOException, XmlPullParserException { - Intent intent = null; - Intent affinityIntent = null; - ArrayList activities = new ArrayList<>(); - ComponentName realActivity = null; - boolean realActivitySuspended = false; - ComponentName origActivity = null; - String affinity = null; - String rootAffinity = null; - boolean hasRootAffinity = false; - boolean rootHasReset = false; - boolean autoRemoveRecents = false; - boolean askedCompatMode = false; - int taskType = 0; - int userId = 0; - boolean userSetupComplete = true; - int effectiveUid = -1; - String lastDescription = null; - long lastTimeOnTop = 0; - boolean neverRelinquishIdentity = true; - int taskId = INVALID_TASK_ID; - final int outerDepth = in.getDepth(); - TaskDescription taskDescription = new TaskDescription(); - int taskAffiliation = INVALID_TASK_ID; - int taskAffiliationColor = 0; - int prevTaskId = INVALID_TASK_ID; - int nextTaskId = INVALID_TASK_ID; - int callingUid = -1; - String callingPackage = ""; - int resizeMode = RESIZE_MODE_FORCE_RESIZEABLE; - boolean supportsPictureInPicture = false; - Rect lastNonFullscreenBounds = null; - int minWidth = INVALID_MIN_SIZE; - int minHeight = INVALID_MIN_SIZE; - int persistTaskVersion = 0; - - for (int attrNdx = in.getAttributeCount() - 1; attrNdx >= 0; --attrNdx) { - final String attrName = in.getAttributeName(attrNdx); - final String attrValue = in.getAttributeValue(attrNdx); - if (TaskPersister.DEBUG) Slog.d(TaskPersister.TAG, "TaskRecord: attribute name=" + - attrName + " value=" + attrValue); - switch (attrName) { - case ATTR_TASKID: - if (taskId == INVALID_TASK_ID) taskId = Integer.parseInt(attrValue); - break; - case ATTR_REALACTIVITY: - realActivity = ComponentName.unflattenFromString(attrValue); - break; - case ATTR_REALACTIVITY_SUSPENDED: - realActivitySuspended = Boolean.valueOf(attrValue); - break; - case ATTR_ORIGACTIVITY: - origActivity = ComponentName.unflattenFromString(attrValue); - break; - case ATTR_AFFINITY: - affinity = attrValue; - break; - case ATTR_ROOT_AFFINITY: - rootAffinity = attrValue; - hasRootAffinity = true; - break; - case ATTR_ROOTHASRESET: - rootHasReset = Boolean.parseBoolean(attrValue); - break; - case ATTR_AUTOREMOVERECENTS: - autoRemoveRecents = Boolean.parseBoolean(attrValue); - break; - case ATTR_ASKEDCOMPATMODE: - askedCompatMode = Boolean.parseBoolean(attrValue); - break; - case ATTR_USERID: - userId = Integer.parseInt(attrValue); - break; - case ATTR_USER_SETUP_COMPLETE: - userSetupComplete = Boolean.parseBoolean(attrValue); - break; - case ATTR_EFFECTIVE_UID: - effectiveUid = Integer.parseInt(attrValue); - break; - case ATTR_TASKTYPE: - taskType = Integer.parseInt(attrValue); - break; - case ATTR_LASTDESCRIPTION: - lastDescription = attrValue; - break; - case ATTR_LASTTIMEMOVED: - lastTimeOnTop = Long.parseLong(attrValue); - break; - case ATTR_NEVERRELINQUISH: - neverRelinquishIdentity = Boolean.parseBoolean(attrValue); - break; - case ATTR_TASK_AFFILIATION: - taskAffiliation = Integer.parseInt(attrValue); - break; - case ATTR_PREV_AFFILIATION: - prevTaskId = Integer.parseInt(attrValue); - break; - case ATTR_NEXT_AFFILIATION: - nextTaskId = Integer.parseInt(attrValue); - break; - case ATTR_TASK_AFFILIATION_COLOR: - taskAffiliationColor = Integer.parseInt(attrValue); - break; - case ATTR_CALLING_UID: - callingUid = Integer.parseInt(attrValue); - break; - case ATTR_CALLING_PACKAGE: - callingPackage = attrValue; - break; - case ATTR_RESIZE_MODE: - resizeMode = Integer.parseInt(attrValue); - break; - case ATTR_SUPPORTS_PICTURE_IN_PICTURE: - supportsPictureInPicture = Boolean.parseBoolean(attrValue); - break; - case ATTR_NON_FULLSCREEN_BOUNDS: - lastNonFullscreenBounds = Rect.unflattenFromString(attrValue); - break; - case ATTR_MIN_WIDTH: - minWidth = Integer.parseInt(attrValue); - break; - case ATTR_MIN_HEIGHT: - minHeight = Integer.parseInt(attrValue); - break; - case ATTR_PERSIST_TASK_VERSION: - persistTaskVersion = Integer.parseInt(attrValue); - break; - default: - if (attrName.startsWith(TaskDescription.ATTR_TASKDESCRIPTION_PREFIX)) { - taskDescription.restoreFromXml(attrName, attrValue); - } else { - Slog.w(TAG, "TaskRecord: Unknown attribute=" + attrName); - } - } - } - - int event; - while (((event = in.next()) != XmlPullParser.END_DOCUMENT) && - (event != XmlPullParser.END_TAG || in.getDepth() >= outerDepth)) { - if (event == XmlPullParser.START_TAG) { - final String name = in.getName(); - if (TaskPersister.DEBUG) Slog.d(TaskPersister.TAG, - "TaskRecord: START_TAG name=" + name); - if (TAG_AFFINITYINTENT.equals(name)) { - affinityIntent = Intent.restoreFromXml(in); - } else if (TAG_INTENT.equals(name)) { - intent = Intent.restoreFromXml(in); - } else if (TAG_ACTIVITY.equals(name)) { - ActivityRecord activity = - ActivityRecord.restoreFromXml(in, stackSupervisor); - if (TaskPersister.DEBUG) Slog.d(TaskPersister.TAG, "TaskRecord: activity=" + - activity); - if (activity != null) { - activities.add(activity); - } - } else { - handleUnknownTag(name, in); - } - } - } - if (!hasRootAffinity) { - rootAffinity = affinity; - } else if ("@".equals(rootAffinity)) { - rootAffinity = null; - } - if (effectiveUid <= 0) { - Intent checkIntent = intent != null ? intent : affinityIntent; - effectiveUid = 0; - if (checkIntent != null) { - IPackageManager pm = AppGlobals.getPackageManager(); - try { - ApplicationInfo ai = pm.getApplicationInfo( - checkIntent.getComponent().getPackageName(), - PackageManager.MATCH_UNINSTALLED_PACKAGES - | PackageManager.MATCH_DISABLED_COMPONENTS, userId); - if (ai != null) { - effectiveUid = ai.uid; - } - } catch (RemoteException e) { - } - } - Slog.w(TAG, "Updating task #" + taskId + " for " + checkIntent - + ": effectiveUid=" + effectiveUid); - } - - if (persistTaskVersion < 1) { - // We need to convert the resize mode of home activities saved before version one if - // they are marked as RESIZE_MODE_RESIZEABLE to - // RESIZE_MODE_RESIZEABLE_VIA_SDK_VERSION since we didn't have that differentiation - // before version 1 and the system didn't resize home activities before then. - if (taskType == 1 /* old home type */ && resizeMode == RESIZE_MODE_RESIZEABLE) { - resizeMode = RESIZE_MODE_RESIZEABLE_VIA_SDK_VERSION; - } - } else { - // This activity has previously marked itself explicitly as both resizeable and - // supporting picture-in-picture. Since there is no longer a requirement for - // picture-in-picture activities to be resizeable, we can mark this simply as - // resizeable and supporting picture-in-picture separately. - if (resizeMode == RESIZE_MODE_RESIZEABLE_AND_PIPABLE_DEPRECATED) { - resizeMode = RESIZE_MODE_RESIZEABLE; - supportsPictureInPicture = true; - } - } - - final TaskRecord task = create(stackSupervisor.mService, - taskId, intent, affinityIntent, - affinity, rootAffinity, realActivity, origActivity, rootHasReset, - autoRemoveRecents, askedCompatMode, userId, effectiveUid, lastDescription, - lastTimeOnTop, neverRelinquishIdentity, taskDescription, - taskAffiliation, prevTaskId, nextTaskId, taskAffiliationColor, callingUid, - callingPackage, resizeMode, supportsPictureInPicture, realActivitySuspended, - userSetupComplete, minWidth, minHeight, null /*stack*/); - task.mLastNonFullscreenBounds = lastNonFullscreenBounds; - task.setBounds(lastNonFullscreenBounds); - - for (int activityNdx = activities.size() - 1; activityNdx >=0; --activityNdx) { - task.addChild(activities.get(activityNdx)); - } - - if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "Restored task=" + task); - return task; - } - - void handleUnknownTag(String name, XmlPullParser in) - throws IOException, XmlPullParserException { - Slog.e(TAG, "restoreTask: Unexpected name=" + name); - XmlUtils.skipCurrentTag(in); - } - } -} diff --git a/services/core/java/com/android/server/wm/TaskStack.java b/services/core/java/com/android/server/wm/TaskStack.java index 870ecccf66dc1..ec627c8817096 100644 --- a/services/core/java/com/android/server/wm/TaskStack.java +++ b/services/core/java/com/android/server/wm/TaskStack.java @@ -58,7 +58,6 @@ import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_STACK; import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_TASK_MOVEMENT; import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM; -import android.annotation.CallSuper; import android.app.RemoteAction; import android.content.res.Configuration; import android.graphics.Point; @@ -84,7 +83,7 @@ import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; -public class TaskStack extends WindowContainer implements +public class TaskStack extends WindowContainer implements BoundsAnimationTarget, ConfigurationContainerListener { /** Minimum size of an adjusted stack bounds relative to original stack bounds. Used to * restrict IME adjustment so that a min portion of top stack remains visible.*/ @@ -483,7 +482,7 @@ public class TaskStack extends WindowContainer implements * @param position Target position to add the task to. * @param showForAllUsers Whether to show the task regardless of the current user. */ - void addChild(TaskRecord task, int position, boolean showForAllUsers, boolean moveParents) { + void addChild(Task task, int position, boolean showForAllUsers, boolean moveParents) { // Add child task. addChild(task, null); @@ -496,11 +495,11 @@ public class TaskStack extends WindowContainer implements } @Override - void addChild(TaskRecord task, int position) { + void addChild(Task task, int position) { addChild(task, position, task.showForAllUsers(), false /* includingParents */); } - void positionChildAt(TaskRecord child, int position) { + void positionChildAt(Task child, int position) { if (DEBUG_STACK) { Slog.i(TAG_WM, "positionChildAt: positioning task=" + child + " at " + position); } @@ -515,7 +514,7 @@ public class TaskStack extends WindowContainer implements getDisplayContent().layoutAndAssignWindowLayersIfNeeded(); } - void positionChildAtTop(TaskRecord child, boolean includingParents) { + void positionChildAtTop(Task child, boolean includingParents) { if (child == null) { // TODO: Fix the call-points that cause this to happen. return; @@ -531,7 +530,7 @@ public class TaskStack extends WindowContainer implements displayContent.layoutAndAssignWindowLayersIfNeeded(); } - void positionChildAtBottom(TaskRecord child, boolean includingParents) { + void positionChildAtBottom(Task child, boolean includingParents) { if (child == null) { // TODO: Fix the call-points that cause this to happen. return; @@ -546,7 +545,7 @@ public class TaskStack extends WindowContainer implements } @Override - void positionChildAt(int position, TaskRecord child, boolean includingParents) { + void positionChildAt(int position, Task child, boolean includingParents) { positionChildAt(position, child, includingParents, child.showForAllUsers()); } @@ -555,7 +554,7 @@ public class TaskStack extends WindowContainer implements * {@link TaskStack#addChild(Task, int, boolean showForAllUsers, boolean)}, as it can receive * showForAllUsers param from {@link ActivityRecord} instead of {@link Task#showForAllUsers()}. */ - private int positionChildAt(int position, TaskRecord child, boolean includingParents, + private int positionChildAt(int position, Task child, boolean includingParents, boolean showForAllUsers) { final int targetPosition = findPositionForTask(child, position, showForAllUsers); super.positionChildAt(targetPosition, child, includingParents); @@ -572,8 +571,9 @@ public class TaskStack extends WindowContainer implements @Override void onChildPositionChanged(WindowContainer child) { - // TODO(task-merge): Read comment on updateTaskMovement method. - //((TaskRecord) child).updateTaskMovement(true); + if (mChildren.contains(child)) { + ((Task) child).updateTaskMovement(getTopChild() == child); + } } void reparent(DisplayContent newParent, boolean onTop) { diff --git a/services/core/java/com/android/server/wm/WindowProcessController.java b/services/core/java/com/android/server/wm/WindowProcessController.java index 7cf0beefa1608..d63fbc217e540 100644 --- a/services/core/java/com/android/server/wm/WindowProcessController.java +++ b/services/core/java/com/android/server/wm/WindowProcessController.java @@ -165,7 +165,7 @@ public class WindowProcessController extends ConfigurationContainer mActivities = new ArrayList<>(); // any tasks this process had run root activities in - private final ArrayList mRecentTasks = new ArrayList<>(); + private final ArrayList mRecentTasks = new ArrayList<>(); // The most recent top-most activity that was resumed in the process for pre-Q app. private ActivityRecord mPreQTopResumedActivity = null; // The last time an activity was launched in the process @@ -550,7 +550,7 @@ public class WindowProcessController extends ConfigurationContainer= 0; --i) { - TaskRecord task = mActivities.get(i).getTaskRecord(); + Task task = mActivities.get(i).getTask(); if (task == null) { continue; } @@ -702,18 +702,18 @@ public class WindowProcessController extends ConfigurationContainer getReleaseSomeActivitiesTasks() { + ArraySet getReleaseSomeActivitiesTasks() { // Examine all activities currently running in the process. - TaskRecord firstTask = null; + Task firstTask = null; // Tasks is non-null only if two or more tasks are found. - ArraySet tasks = null; + ArraySet tasks = null; if (DEBUG_RELEASE) Slog.d(TAG_RELEASE, "Trying to release some activities in " + this); for (int i = 0; i < mActivities.size(); i++) { final ActivityRecord r = mActivities.get(i); @@ -745,7 +745,7 @@ public class WindowProcessController extends ConfigurationContainer 0) { final int layer = task.mLayerRank; if (layer >= 0 && minTaskLayer > layer) { @@ -1023,11 +1023,11 @@ public class WindowProcessController extends ConfigurationContainer { diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityMetricsLaunchObserverTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityMetricsLaunchObserverTests.java index 44cacd8213553..3c619f73aa6f3 100644 --- a/services/tests/wmtests/src/com/android/server/wm/ActivityMetricsLaunchObserverTests.java +++ b/services/tests/wmtests/src/com/android/server/wm/ActivityMetricsLaunchObserverTests.java @@ -78,7 +78,7 @@ public class ActivityMetricsLaunchObserverTests extends ActivityTestsBase { // This seems to be the easiest way to create an ActivityRecord. mTrampolineActivity = new ActivityBuilder(mService).setCreateTask(true).build(); mTopActivity = new ActivityBuilder(mService) - .setTask(mTrampolineActivity.getTaskRecord()) + .setTask(mTrampolineActivity.getTask()) .build(); } @@ -177,7 +177,7 @@ public class ActivityMetricsLaunchObserverTests extends ActivityTestsBase { mSupervisor.beginDeferResume(); // Create an activity with different process that meets process switch. final ActivityRecord noDrawnActivity = new ActivityBuilder(mService) - .setTask(mTopActivity.getTaskRecord()) + .setTask(mTopActivity.getTask()) .setProcessName("other") .build(); mSupervisor.readyToResume(); diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java index ac10482778498..c51a46a76f4cf 100644 --- a/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java +++ b/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java @@ -113,7 +113,7 @@ import org.mockito.invocation.InvocationOnMock; @RunWith(WindowTestRunner.class) public class ActivityRecordTests extends ActivityTestsBase { private ActivityStack mStack; - private TaskRecord mTask; + private Task mTask; private ActivityRecord mActivity; @Before @@ -147,7 +147,7 @@ public class ActivityRecordTests extends ActivityTestsBase { @Test public void testNoCleanupMovingActivityInSameStack() { - final TaskRecord newTask = new TaskBuilder(mService.mStackSupervisor).setStack(mStack) + final Task newTask = new TaskBuilder(mService.mStackSupervisor).setStack(mStack) .build(); mActivity.reparent(newTask, 0, null /*reason*/); verify(mStack, times(0)).onActivityRemovedFromStack(any()); @@ -255,7 +255,7 @@ public class ActivityRecordTests extends ActivityTestsBase { // Set options for two ActivityRecords in separate Tasks. Apply one ActivityRecord options. // Pending options should be cleared for only ActivityRecord that was applied - TaskRecord task2 = new TaskBuilder(mService.mStackSupervisor).setStack(mStack).build(); + Task task2 = new TaskBuilder(mService.mStackSupervisor).setStack(mStack).build(); activity2 = new ActivityBuilder(mService).setTask(task2).build(); activity2.updateOptionsLocked(activityOptions); mActivity.updateOptionsLocked(activityOptions); @@ -1171,7 +1171,7 @@ public class ActivityRecordTests extends ActivityTestsBase { public void testDestroyIfPossible_lastActivityAboveEmptyHomeStack() { // Empty the home stack. final ActivityStack homeStack = mActivity.getDisplay().getHomeStack(); - for (TaskRecord t : homeStack.getAllTasks()) { + for (Task t : homeStack.getAllTasks()) { homeStack.removeChild(t, "test"); } mActivity.finishing = true; @@ -1197,7 +1197,7 @@ public class ActivityRecordTests extends ActivityTestsBase { public void testCompleteFinishing_lastActivityAboveEmptyHomeStack() { // Empty the home stack. final ActivityStack homeStack = mActivity.getDisplay().getHomeStack(); - for (TaskRecord t : homeStack.getAllTasks()) { + for (Task t : homeStack.getAllTasks()) { homeStack.removeChild(t, "test"); } mActivity.finishing = true; @@ -1244,12 +1244,12 @@ public class ActivityRecordTests extends ActivityTestsBase { public void testDestroyImmediately_noApp_finishing() { mActivity.app = null; mActivity.finishing = true; - final TaskRecord task = mActivity.getTaskRecord(); + final Task task = mActivity.getTask(); mActivity.destroyImmediately(false /* removeFromApp */, "test"); assertEquals(DESTROYED, mActivity.getState()); - assertNull(mActivity.getTaskRecord()); + assertNull(mActivity.getTask()); assertEquals(0, task.getChildCount()); } @@ -1261,12 +1261,12 @@ public class ActivityRecordTests extends ActivityTestsBase { public void testDestroyImmediately_noApp_notFinishing() { mActivity.app = null; mActivity.finishing = false; - final TaskRecord task = mActivity.getTaskRecord(); + final Task task = mActivity.getTask(); mActivity.destroyImmediately(false /* removeFromApp */, "test"); assertEquals(DESTROYED, mActivity.getState()); - assertEquals(task, mActivity.getTaskRecord()); + assertEquals(task, mActivity.getTask()); assertEquals(1, task.getChildCount()); } @@ -1297,13 +1297,13 @@ public class ActivityRecordTests extends ActivityTestsBase { @Test public void testRemoveFromHistory() { final ActivityStack stack = mActivity.getActivityStack(); - final TaskRecord task = mActivity.getTaskRecord(); + final Task task = mActivity.getTask(); mActivity.removeFromHistory("test"); assertEquals(DESTROYED, mActivity.getState()); assertNull(mActivity.app); - assertNull(mActivity.getTaskRecord()); + assertNull(mActivity.getTask()); assertEquals(0, task.getChildCount()); assertNull(task.getStack()); assertEquals(0, stack.getChildCount()); diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityStackSupervisorTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityStackSupervisorTests.java index 1eeca91e29d07..128ed2a9d0e7b 100644 --- a/services/tests/wmtests/src/com/android/server/wm/ActivityStackSupervisorTests.java +++ b/services/tests/wmtests/src/com/android/server/wm/ActivityStackSupervisorTests.java @@ -116,7 +116,7 @@ public class ActivityStackSupervisorTests extends ActivityTestsBase { final ActivityStack stack = new StackBuilder(mRootActivityContainer) .setDisplay(newDisplay).build(); final ActivityRecord unresizableActivity = stack.getTopActivity(); - final TaskRecord task = unresizableActivity.getTaskRecord(); + final Task task = unresizableActivity.getTask(); unresizableActivity.info.resizeMode = ActivityInfo.RESIZE_MODE_UNRESIZEABLE; task.setResizeMode(unresizableActivity.info.resizeMode); diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityStackTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityStackTests.java index 57e5eb2812b43..d0e07b619ad61 100644 --- a/services/tests/wmtests/src/com/android/server/wm/ActivityStackTests.java +++ b/services/tests/wmtests/src/com/android/server/wm/ActivityStackTests.java @@ -43,7 +43,7 @@ import static com.android.server.wm.ActivityStack.STACK_VISIBILITY_VISIBLE; import static com.android.server.wm.ActivityStack.STACK_VISIBILITY_VISIBLE_BEHIND_TRANSLUCENT; import static com.android.server.wm.ActivityTaskManagerService.RELAUNCH_REASON_FREE_RESIZE; import static com.android.server.wm.ActivityTaskManagerService.RELAUNCH_REASON_WINDOWING_MODE_RESIZE; -import static com.android.server.wm.TaskRecord.REPARENT_MOVE_STACK_TO_FRONT; +import static com.android.server.wm.Task.REPARENT_MOVE_STACK_TO_FRONT; import static com.google.common.truth.Truth.assertThat; @@ -80,7 +80,7 @@ import org.junit.runner.RunWith; public class ActivityStackTests extends ActivityTestsBase { private ActivityDisplay mDefaultDisplay; private ActivityStack mStack; - private TaskRecord mTask; + private Task mTask; @Before public void setUp() throws Exception { @@ -111,7 +111,7 @@ public class ActivityStackTests extends ActivityTestsBase { final ActivityStack destStack = mRootActivityContainer.getDefaultDisplay().createStack( WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, true /* onTop */); - mTask.reparent(destStack, true /* toTop */, TaskRecord.REPARENT_KEEP_STACK_AT_FRONT, + mTask.reparent(destStack, true /* toTop */, Task.REPARENT_KEEP_STACK_AT_FRONT, false /* animate */, true /* deferResume*/, "testResumedActivityFromTaskReparenting"); @@ -233,7 +233,7 @@ public class ActivityStackTests extends ActivityTestsBase { .setStack(mStack) .setUid(0) .build(); - final TaskRecord task = r.getTaskRecord(); + final Task task = r.getTask(); // Overlay must be for a different user to prevent recognizing a matching top activity final ActivityRecord taskOverlay = new ActivityBuilder(mService).setTask(task) .setUid(UserHandle.PER_USER_RANGE * 2).build(); @@ -256,7 +256,7 @@ public class ActivityStackTests extends ActivityTestsBase { targetActivity); final ComponentName alias = new ComponentName(DEFAULT_COMPONENT_PACKAGE_NAME, aliasActivity); - final TaskRecord task = new TaskBuilder(mService.mStackSupervisor).setStack(mStack).build(); + final Task task = new TaskBuilder(mService.mStackSupervisor).setStack(mStack).build(); task.origActivity = alias; task.realActivity = target; new ActivityBuilder(mService).setComponent(target).setTask(task).setTargetActivity( @@ -1091,7 +1091,7 @@ public class ActivityStackTests extends ActivityTestsBase { public void testResetTaskWithFinishingActivities() { final ActivityRecord taskTop = new ActivityBuilder(mService).setStack(mStack).setCreateTask(true).build(); - // Make all activities in the task are finishing to simulate TaskRecord#getTopActivity + // Make all activities in the task are finishing to simulate Task#getTopActivity // returns null. taskTop.finishing = true; diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityStarterTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityStarterTests.java index a28bbb60d70cd..9af90e39da95c 100644 --- a/services/tests/wmtests/src/com/android/server/wm/ActivityStarterTests.java +++ b/services/tests/wmtests/src/com/android/server/wm/ActivityStarterTests.java @@ -132,7 +132,7 @@ public class ActivityStarterTests extends ActivityTestsBase { @Test public void testUpdateLaunchBounds() { // When in a non-resizeable stack, the task bounds should be updated. - final TaskRecord task = new TaskBuilder(mService.mStackSupervisor) + final Task task = new TaskBuilder(mService.mStackSupervisor) .setStack(mService.mRootActivityContainer.getDefaultDisplay().createStack( WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, true /* onTop */)) .build(); @@ -143,7 +143,7 @@ public class ActivityStarterTests extends ActivityTestsBase { assertEquals(new Rect(), task.getStack().getRequestedOverrideBounds()); // When in a resizeable stack, the stack bounds should be updated as well. - final TaskRecord task2 = new TaskBuilder(mService.mStackSupervisor) + final Task task2 = new TaskBuilder(mService.mStackSupervisor) .setStack(mService.mRootActivityContainer.getDefaultDisplay().createStack( WINDOWING_MODE_PINNED, ACTIVITY_TYPE_STANDARD, true /* onTop */)) .build(); @@ -712,10 +712,10 @@ public class ActivityStarterTests extends ActivityTestsBase { verify(options, times(shouldHaveAborted ? 1 : 0)).abort(); final ActivityRecord startedActivity = outActivity[0]; - if (startedActivity != null && startedActivity.getTaskRecord() != null) { + if (startedActivity != null && startedActivity.getTask() != null) { // Remove the activity so it doesn't interfere with with subsequent activity launch // tests from this method. - startedActivity.getTaskRecord().removeChild(startedActivity); + startedActivity.getTask().removeChild(startedActivity); } } @@ -807,7 +807,7 @@ public class ActivityStarterTests extends ActivityTestsBase { // Create another activity on top of the secondary display. final ActivityStack topStack = secondaryDisplay.createStack(WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, true /* onTop */); - final TaskRecord topTask = new TaskBuilder(mSupervisor).setStack(topStack).build(); + final Task topTask = new TaskBuilder(mSupervisor).setStack(topStack).build(); new ActivityBuilder(mService).setTask(topTask).build(); // Start activity with the same intent as {@code singleTaskActivity} on secondary display. @@ -829,14 +829,14 @@ public class ActivityStarterTests extends ActivityTestsBase { final ComponentName componentName = ComponentName.createRelative( DEFAULT_COMPONENT_PACKAGE_NAME, DEFAULT_COMPONENT_PACKAGE_NAME + ".SingleTaskActivity"); - final TaskRecord taskRecord = new TaskBuilder(mSupervisor) + final Task task = new TaskBuilder(mSupervisor) .setComponent(componentName) .setStack(stack) .build(); return new ActivityBuilder(mService) .setComponent(componentName) .setLaunchMode(LAUNCH_SINGLE_TASK) - .setTask(taskRecord) + .setTask(task) .build(); } diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityTaskManagerServiceTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityTaskManagerServiceTests.java index 399f28302f321..39aa51a05764b 100644 --- a/services/tests/wmtests/src/com/android/server/wm/ActivityTaskManagerServiceTests.java +++ b/services/tests/wmtests/src/com/android/server/wm/ActivityTaskManagerServiceTests.java @@ -69,7 +69,7 @@ public class ActivityTaskManagerServiceTests extends ActivityTestsBase { removeGlobalMinSizeRestriction(); final ActivityStack stack = new StackBuilder(mRootActivityContainer) .setWindowingMode(WINDOWING_MODE_FREEFORM).build(); - final TaskRecord task = stack.topTask(); + final Task task = stack.topTask(); WindowContainerTransaction t = new WindowContainerTransaction(); Rect newBounds = new Rect(10, 10, 100, 100); t.setBounds(task.mRemoteToken, new Rect(10, 10, 100, 100)); diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityTestsBase.java b/services/tests/wmtests/src/com/android/server/wm/ActivityTestsBase.java index ce13c0bcb8295..47b39b042fb5e 100644 --- a/services/tests/wmtests/src/com/android/server/wm/ActivityTestsBase.java +++ b/services/tests/wmtests/src/com/android/server/wm/ActivityTestsBase.java @@ -117,7 +117,7 @@ class ActivityTestsBase extends SystemServiceTestsBase { private ComponentName mComponent; private String mTargetActivity; - private TaskRecord mTaskRecord; + private Task mTask; private String mProcessName = "name"; private int mUid = 12345; private boolean mCreateTask; @@ -151,8 +151,8 @@ class ActivityTestsBase extends SystemServiceTestsBase { DEFAULT_COMPONENT_PACKAGE_NAME); } - ActivityBuilder setTask(TaskRecord task) { - mTaskRecord = task; + ActivityBuilder setTask(Task task) { + mTask = task; return this; } @@ -229,7 +229,7 @@ class ActivityTestsBase extends SystemServiceTestsBase { } if (mCreateTask) { - mTaskRecord = new TaskBuilder(mService.mStackSupervisor) + mTask = new TaskBuilder(mService.mStackSupervisor) .setComponent(mComponent) .setStack(mStack).build(); } @@ -265,11 +265,11 @@ class ActivityTestsBase extends SystemServiceTestsBase { false /* rootVoiceInteraction */, mService.mStackSupervisor, options, null /* sourceRecord */); spyOn(activity); - if (mTaskRecord != null) { + if (mTask != null) { // fullscreen value is normally read from resources in ctor, so for testing we need // to set it somewhere else since we can't mock resources. doReturn(true).when(activity).occludesParent(); - mTaskRecord.addChild(activity); + mTask.addChild(activity); // Make visible by default... activity.setHidden(false); } @@ -354,7 +354,7 @@ class ActivityTestsBase extends SystemServiceTestsBase { return this; } - TaskRecord build() { + Task build() { if (mStack == null && mCreateStack) { mStack = mSupervisor.mRootActivityContainer.getDefaultDisplay().createStack( WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, true /* onTop */); @@ -374,7 +374,7 @@ class ActivityTestsBase extends SystemServiceTestsBase { intent.setComponent(mComponent); intent.setFlags(mFlags); - final TaskRecord task = new TaskRecord(mSupervisor.mService, mTaskId, aInfo, + final Task task = new Task(mSupervisor.mService, mTaskId, aInfo, intent /*intent*/, mVoiceSession, null /*_voiceInteractor*/, null /*taskDescription*/, mStack); spyOn(task); diff --git a/services/tests/wmtests/src/com/android/server/wm/AppWindowTokenTests.java b/services/tests/wmtests/src/com/android/server/wm/AppWindowTokenTests.java index 85110745e9cbd..bd336ad2494f4 100644 --- a/services/tests/wmtests/src/com/android/server/wm/AppWindowTokenTests.java +++ b/services/tests/wmtests/src/com/android/server/wm/AppWindowTokenTests.java @@ -208,11 +208,9 @@ public class AppWindowTokenTests extends WindowTestsBase { @Test public void testSizeCompatBounds() { - // TODO(task-merge): Move once Task is merged into TaskRecord - final TaskRecord tr = (TaskRecord) mTask; // Disable the real configuration resolving because we only simulate partial flow. // TODO: Have test use full flow. - doNothing().when(tr).computeConfigResourceOverrides(any(), any()); + doNothing().when(mTask).computeConfigResourceOverrides(any(), any()); final Rect fixedBounds = mActivity.getRequestedOverrideConfiguration().windowConfiguration .getBounds(); fixedBounds.set(0, 0, 1200, 1600); diff --git a/services/tests/wmtests/src/com/android/server/wm/LaunchParamsControllerTests.java b/services/tests/wmtests/src/com/android/server/wm/LaunchParamsControllerTests.java index 46435ebd8e159..31b658ad50436 100644 --- a/services/tests/wmtests/src/com/android/server/wm/LaunchParamsControllerTests.java +++ b/services/tests/wmtests/src/com/android/server/wm/LaunchParamsControllerTests.java @@ -89,9 +89,9 @@ public class LaunchParamsControllerTests extends ActivityTestsBase { final WindowLayout layout = new WindowLayout(0, 0, 0, 0, 0, 0, 0); final ActivityOptions options = mock(ActivityOptions.class); - mController.calculate(record.getTaskRecord(), layout, record, source, options, PHASE_BOUNDS, + mController.calculate(record.getTask(), layout, record, source, options, PHASE_BOUNDS, new LaunchParams()); - verify(positioner, times(1)).onCalculate(eq(record.getTaskRecord()), eq(layout), eq(record), + verify(positioner, times(1)).onCalculate(eq(record.getTask()), eq(layout), eq(record), eq(source), eq(options), anyInt(), any(), any()); } @@ -114,7 +114,7 @@ public class LaunchParamsControllerTests extends ActivityTestsBase { mPersister.putLaunchParams(userId, name, expected); - mController.calculate(activity.getTaskRecord(), null /*layout*/, activity, null /*source*/, + mController.calculate(activity.getTask(), null /*layout*/, activity, null /*source*/, null /*options*/, PHASE_BOUNDS, new LaunchParams()); verify(positioner, times(1)).onCalculate(any(), any(), any(), any(), any(), anyInt(), eq(expected), any()); @@ -263,9 +263,9 @@ public class LaunchParamsControllerTests extends ActivityTestsBase { final WindowLayout layout = new WindowLayout(0, 0, 0, 0, 0, 0, 0); final ActivityOptions options = mock(ActivityOptions.class); - mController.calculate(record.getTaskRecord(), layout, record, source, options, PHASE_BOUNDS, + mController.calculate(record.getTask(), layout, record, source, options, PHASE_BOUNDS, new LaunchParams()); - verify(positioner, times(1)).onCalculate(eq(record.getTaskRecord()), eq(layout), eq(record), + verify(positioner, times(1)).onCalculate(eq(record.getTask()), eq(layout), eq(record), eq(source), eq(options), eq(PHASE_BOUNDS), any(), any()); } @@ -278,7 +278,7 @@ public class LaunchParamsControllerTests extends ActivityTestsBase { final LaunchParams params = new LaunchParams(); params.mPreferredDisplayId = 2; final InstrumentedPositioner positioner = new InstrumentedPositioner(RESULT_DONE, params); - final TaskRecord task = new TaskBuilder(mService.mStackSupervisor).build(); + final Task task = new TaskBuilder(mService.mStackSupervisor).build(); mController.registerModifier(positioner); @@ -298,7 +298,7 @@ public class LaunchParamsControllerTests extends ActivityTestsBase { final int windowingMode = WINDOWING_MODE_FREEFORM; params.mWindowingMode = windowingMode; final InstrumentedPositioner positioner = new InstrumentedPositioner(RESULT_DONE, params); - final TaskRecord task = new TaskBuilder(mService.mStackSupervisor).build(); + final Task task = new TaskBuilder(mService.mStackSupervisor).build(); mController.registerModifier(positioner); @@ -323,7 +323,7 @@ public class LaunchParamsControllerTests extends ActivityTestsBase { params.mWindowingMode = WINDOWING_MODE_FREEFORM; params.mBounds.set(expected); final InstrumentedPositioner positioner = new InstrumentedPositioner(RESULT_DONE, params); - final TaskRecord task = new TaskBuilder(mService.mStackSupervisor).build(); + final Task task = new TaskBuilder(mService.mStackSupervisor).build(); mController.registerModifier(positioner); @@ -331,7 +331,7 @@ public class LaunchParamsControllerTests extends ActivityTestsBase { mController.layoutTask(task, null /* windowLayout */); - // TaskRecord will make adjustments to requested bounds. We only need to guarantee that the + // Task will make adjustments to requested bounds. We only need to guarantee that the // reuqested bounds are expected. assertEquals(expected, task.getRequestedOverrideBounds()); } @@ -348,7 +348,7 @@ public class LaunchParamsControllerTests extends ActivityTestsBase { params.mWindowingMode = WINDOWING_MODE_FULLSCREEN; params.mBounds.set(expected); final InstrumentedPositioner positioner = new InstrumentedPositioner(RESULT_DONE, params); - final TaskRecord task = new TaskBuilder(mService.mStackSupervisor).build(); + final Task task = new TaskBuilder(mService.mStackSupervisor).build(); mController.registerModifier(positioner); @@ -371,7 +371,7 @@ public class LaunchParamsControllerTests extends ActivityTestsBase { } @Override - public int onCalculate(TaskRecord task, WindowLayout layout, ActivityRecord activity, + public int onCalculate(Task task, WindowLayout layout, ActivityRecord activity, ActivityRecord source, ActivityOptions options, int phase, LaunchParams currentParams, LaunchParams outParams) { outParams.set(mParams); @@ -421,7 +421,7 @@ public class LaunchParamsControllerTests extends ActivityTestsBase { } @Override - void saveTask(TaskRecord task) { + void saveTask(Task task) { final int userId = task.mUserId; final ComponentName realActivity = task.realActivity; mTmpParams.mPreferredDisplayId = task.getStack().mDisplayId; @@ -435,7 +435,7 @@ public class LaunchParamsControllerTests extends ActivityTestsBase { } @Override - void getLaunchParams(TaskRecord task, ActivityRecord activity, LaunchParams params) { + void getLaunchParams(Task task, ActivityRecord activity, LaunchParams params) { final int userId = task != null ? task.mUserId : activity.mUserId; final ComponentName name = task != null ? task.realActivity : activity.mActivityComponent; diff --git a/services/tests/wmtests/src/com/android/server/wm/LaunchParamsPersisterTests.java b/services/tests/wmtests/src/com/android/server/wm/LaunchParamsPersisterTests.java index b9fef4b008c35..0908f7193352b 100644 --- a/services/tests/wmtests/src/com/android/server/wm/LaunchParamsPersisterTests.java +++ b/services/tests/wmtests/src/com/android/server/wm/LaunchParamsPersisterTests.java @@ -81,9 +81,9 @@ public class LaunchParamsPersisterTests extends ActivityTestsBase { private File mFolder; private ActivityDisplay mTestDisplay; private String mDisplayUniqueId; - private TaskRecord mTestTask; - private TaskRecord mTaskWithDifferentUser; - private TaskRecord mTaskWithDifferentComponent; + private Task mTestTask; + private Task mTaskWithDifferentUser; + private Task mTaskWithDifferentComponent; private PackageManagerInternal mMockPmi; private PackageManagerInternal.PackageListObserver mObserver; @@ -234,7 +234,7 @@ public class LaunchParamsPersisterTests extends ActivityTestsBase { ActivityStack stack = mTestDisplay.createStack(TEST_WINDOWING_MODE, ACTIVITY_TYPE_STANDARD, /* onTop */ true); - final TaskRecord anotherTaskOfTheSameUser = new TaskBuilder(mSupervisor) + final Task anotherTaskOfTheSameUser = new TaskBuilder(mSupervisor) .setComponent(ALTERNATIVE_COMPONENT) .setUserId(TEST_USER_ID) .setStack(stack) @@ -246,7 +246,7 @@ public class LaunchParamsPersisterTests extends ActivityTestsBase { stack = mTestDisplay.createStack(TEST_WINDOWING_MODE, ACTIVITY_TYPE_STANDARD, /* onTop */ true); - final TaskRecord anotherTaskOfDifferentUser = new TaskBuilder(mSupervisor) + final Task anotherTaskOfDifferentUser = new TaskBuilder(mSupervisor) .setComponent(TEST_COMPONENT) .setUserId(ALTERNATIVE_USER_ID) .setStack(stack) diff --git a/services/tests/wmtests/src/com/android/server/wm/LockTaskControllerTest.java b/services/tests/wmtests/src/com/android/server/wm/LockTaskControllerTest.java index 05e173c957d31..6ced8160b426b 100644 --- a/services/tests/wmtests/src/com/android/server/wm/LockTaskControllerTest.java +++ b/services/tests/wmtests/src/com/android/server/wm/LockTaskControllerTest.java @@ -165,7 +165,7 @@ public class LockTaskControllerTest { @Test public void testStartLockTaskMode_once() throws Exception { // GIVEN a task record with whitelisted auth - TaskRecord tr = getTaskRecord(TaskRecord.LOCK_TASK_AUTH_WHITELISTED); + Task tr = getTask(Task.LOCK_TASK_AUTH_WHITELISTED); // WHEN calling setLockTaskMode for LOCKED mode without resuming mLockTaskController.startLockTaskMode(tr, false, TEST_UID); @@ -182,8 +182,8 @@ public class LockTaskControllerTest { @Test public void testStartLockTaskMode_twice() throws Exception { // GIVEN two task records with whitelisted auth - TaskRecord tr1 = getTaskRecord(TaskRecord.LOCK_TASK_AUTH_WHITELISTED); - TaskRecord tr2 = getTaskRecord(TaskRecord.LOCK_TASK_AUTH_WHITELISTED); + Task tr1 = getTask(Task.LOCK_TASK_AUTH_WHITELISTED); + Task tr2 = getTask(Task.LOCK_TASK_AUTH_WHITELISTED); // WHEN calling setLockTaskMode for LOCKED mode on both tasks mLockTaskController.startLockTaskMode(tr1, false, TEST_UID); @@ -202,7 +202,7 @@ public class LockTaskControllerTest { @Test public void testStartLockTaskMode_pinningRequest() { // GIVEN a task record that is not whitelisted, i.e. with pinned auth - TaskRecord tr = getTaskRecord(TaskRecord.LOCK_TASK_AUTH_PINNABLE); + Task tr = getTask(Task.LOCK_TASK_AUTH_PINNABLE); // WHEN calling startLockTaskMode mLockTaskController.startLockTaskMode(tr, false, TEST_UID); @@ -214,7 +214,7 @@ public class LockTaskControllerTest { @Test public void testStartLockTaskMode_pinnedBySystem() throws Exception { // GIVEN a task record with pinned auth - TaskRecord tr = getTaskRecord(TaskRecord.LOCK_TASK_AUTH_PINNABLE); + Task tr = getTask(Task.LOCK_TASK_AUTH_PINNABLE); // WHEN the system calls startLockTaskMode mLockTaskController.startLockTaskMode(tr, true, SYSTEM_UID); @@ -233,41 +233,41 @@ public class LockTaskControllerTest { @Test public void testLockTaskViolation() { // GIVEN one task record with whitelisted auth that is in lock task mode - TaskRecord tr = getTaskRecord(TaskRecord.LOCK_TASK_AUTH_WHITELISTED); + Task tr = getTask(Task.LOCK_TASK_AUTH_WHITELISTED); mLockTaskController.startLockTaskMode(tr, false, TEST_UID); // THEN it's not a lock task violation to try and launch this task without clearing assertFalse(mLockTaskController.isLockTaskModeViolation(tr, false)); // THEN it's a lock task violation to launch another task that is not whitelisted - assertTrue(mLockTaskController.isLockTaskModeViolation(getTaskRecord( - TaskRecord.LOCK_TASK_AUTH_PINNABLE))); + assertTrue(mLockTaskController.isLockTaskModeViolation(getTask( + Task.LOCK_TASK_AUTH_PINNABLE))); // THEN it's a lock task violation to launch another task that is disallowed from lock task - assertTrue(mLockTaskController.isLockTaskModeViolation(getTaskRecord( - TaskRecord.LOCK_TASK_AUTH_DONT_LOCK))); + assertTrue(mLockTaskController.isLockTaskModeViolation(getTask( + Task.LOCK_TASK_AUTH_DONT_LOCK))); // THEN it's no a lock task violation to launch another task that is whitelisted - assertFalse(mLockTaskController.isLockTaskModeViolation(getTaskRecord( - TaskRecord.LOCK_TASK_AUTH_WHITELISTED))); - assertFalse(mLockTaskController.isLockTaskModeViolation(getTaskRecord( - TaskRecord.LOCK_TASK_AUTH_LAUNCHABLE))); + assertFalse(mLockTaskController.isLockTaskModeViolation(getTask( + Task.LOCK_TASK_AUTH_WHITELISTED))); + assertFalse(mLockTaskController.isLockTaskModeViolation(getTask( + Task.LOCK_TASK_AUTH_LAUNCHABLE))); // THEN it's not a lock task violation to launch another task that is priv launchable - assertFalse(mLockTaskController.isLockTaskModeViolation(getTaskRecord( - TaskRecord.LOCK_TASK_AUTH_LAUNCHABLE_PRIV))); + assertFalse(mLockTaskController.isLockTaskModeViolation(getTask( + Task.LOCK_TASK_AUTH_LAUNCHABLE_PRIV))); } @Test public void testLockTaskViolation_emergencyCall() { // GIVEN one task record with whitelisted auth that is in lock task mode - TaskRecord tr = getTaskRecord(TaskRecord.LOCK_TASK_AUTH_WHITELISTED); + Task tr = getTask(Task.LOCK_TASK_AUTH_WHITELISTED); mLockTaskController.startLockTaskMode(tr, false, TEST_UID); // GIVEN tasks necessary for emergency calling - TaskRecord keypad = getTaskRecord(new Intent().setComponent(EMERGENCY_DIALER_COMPONENT), - TaskRecord.LOCK_TASK_AUTH_PINNABLE); - TaskRecord callAction = getTaskRecord(new Intent(Intent.ACTION_CALL_EMERGENCY), - TaskRecord.LOCK_TASK_AUTH_PINNABLE); - TaskRecord dialer = getTaskRecord("com.example.dialer", TaskRecord.LOCK_TASK_AUTH_PINNABLE); + Task keypad = getTask(new Intent().setComponent(EMERGENCY_DIALER_COMPONENT), + Task.LOCK_TASK_AUTH_PINNABLE); + Task callAction = getTask(new Intent(Intent.ACTION_CALL_EMERGENCY), + Task.LOCK_TASK_AUTH_PINNABLE); + Task dialer = getTask("com.example.dialer", Task.LOCK_TASK_AUTH_PINNABLE); when(mTelecomManager.getSystemDialerPackage()) .thenReturn(dialer.intent.getComponent().getPackageName()); @@ -291,7 +291,7 @@ public class LockTaskControllerTest { @Test public void testStopLockTaskMode() throws Exception { // GIVEN one task record with whitelisted auth that is in lock task mode - TaskRecord tr = getTaskRecord(TaskRecord.LOCK_TASK_AUTH_WHITELISTED); + Task tr = getTask(Task.LOCK_TASK_AUTH_WHITELISTED); mLockTaskController.startLockTaskMode(tr, false, TEST_UID); // WHEN the same caller calls stopLockTaskMode @@ -308,7 +308,7 @@ public class LockTaskControllerTest { @Test(expected = SecurityException.class) public void testStopLockTaskMode_differentCaller() { // GIVEN one task record with whitelisted auth that is in lock task mode - TaskRecord tr = getTaskRecord(TaskRecord.LOCK_TASK_AUTH_WHITELISTED); + Task tr = getTask(Task.LOCK_TASK_AUTH_WHITELISTED); mLockTaskController.startLockTaskMode(tr, false, TEST_UID); // WHEN a different caller calls stopLockTaskMode @@ -320,7 +320,7 @@ public class LockTaskControllerTest { @Test public void testStopLockTaskMode_systemCaller() { // GIVEN one task record with whitelisted auth that is in lock task mode - TaskRecord tr = getTaskRecord(TaskRecord.LOCK_TASK_AUTH_WHITELISTED); + Task tr = getTask(Task.LOCK_TASK_AUTH_WHITELISTED); mLockTaskController.startLockTaskMode(tr, false, TEST_UID); // WHEN system calls stopLockTaskMode @@ -333,8 +333,8 @@ public class LockTaskControllerTest { @Test public void testStopLockTaskMode_twoTasks() throws Exception { // GIVEN two task records with whitelisted auth that is in lock task mode - TaskRecord tr1 = getTaskRecord(TaskRecord.LOCK_TASK_AUTH_WHITELISTED); - TaskRecord tr2 = getTaskRecord(TaskRecord.LOCK_TASK_AUTH_WHITELISTED); + Task tr1 = getTask(Task.LOCK_TASK_AUTH_WHITELISTED); + Task tr2 = getTask(Task.LOCK_TASK_AUTH_WHITELISTED); mLockTaskController.startLockTaskMode(tr1, false, TEST_UID); mLockTaskController.startLockTaskMode(tr2, false, TEST_UID); @@ -354,8 +354,8 @@ public class LockTaskControllerTest { @Test public void testStopLockTaskMode_rootTask() throws Exception { // GIVEN two task records with whitelisted auth that is in lock task mode - TaskRecord tr1 = getTaskRecord(TaskRecord.LOCK_TASK_AUTH_WHITELISTED); - TaskRecord tr2 = getTaskRecord(TaskRecord.LOCK_TASK_AUTH_WHITELISTED); + Task tr1 = getTask(Task.LOCK_TASK_AUTH_WHITELISTED); + Task tr2 = getTask(Task.LOCK_TASK_AUTH_WHITELISTED); mLockTaskController.startLockTaskMode(tr1, false, TEST_UID); mLockTaskController.startLockTaskMode(tr2, false, TEST_UID); @@ -375,7 +375,7 @@ public class LockTaskControllerTest { @Test public void testStopLockTaskMode_pinned() throws Exception { // GIVEN one task records that is in pinned mode - TaskRecord tr = getTaskRecord(TaskRecord.LOCK_TASK_AUTH_PINNABLE); + Task tr = getTask(Task.LOCK_TASK_AUTH_PINNABLE); mLockTaskController.startLockTaskMode(tr, true, SYSTEM_UID); // GIVEN that the keyguard is required to show after unlocking Settings.Secure.putInt(mContext.getContentResolver(), @@ -402,8 +402,8 @@ public class LockTaskControllerTest { @Test public void testClearLockedTasks() throws Exception { // GIVEN two task records with whitelisted auth that is in lock task mode - TaskRecord tr1 = getTaskRecord(TaskRecord.LOCK_TASK_AUTH_WHITELISTED); - TaskRecord tr2 = getTaskRecord(TaskRecord.LOCK_TASK_AUTH_WHITELISTED); + Task tr1 = getTask(Task.LOCK_TASK_AUTH_WHITELISTED); + Task tr2 = getTask(Task.LOCK_TASK_AUTH_WHITELISTED); mLockTaskController.startLockTaskMode(tr1, false, TEST_UID); mLockTaskController.startLockTaskMode(tr2, false, TEST_UID); @@ -430,7 +430,7 @@ public class LockTaskControllerTest { .thenReturn(DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED); // AND there is a task record - TaskRecord tr1 = getTaskRecord(TaskRecord.LOCK_TASK_AUTH_WHITELISTED); + Task tr1 = getTask(Task.LOCK_TASK_AUTH_WHITELISTED); mLockTaskController.startLockTaskMode(tr1, true, TEST_UID); // WHEN calling clearLockedTasks on the root task @@ -450,7 +450,7 @@ public class LockTaskControllerTest { .thenReturn(true); // AND there is a task record - TaskRecord tr1 = getTaskRecord(TaskRecord.LOCK_TASK_AUTH_WHITELISTED); + Task tr1 = getTask(Task.LOCK_TASK_AUTH_WHITELISTED); mLockTaskController.startLockTaskMode(tr1, true, TEST_UID); // WHEN calling clearLockedTasks on the root task @@ -467,7 +467,7 @@ public class LockTaskControllerTest { Settings.Secure.LOCK_TO_APP_EXIT_LOCKED, 1, mContext.getUserId()); // AND there is a task record - TaskRecord tr1 = getTaskRecord(TaskRecord.LOCK_TASK_AUTH_WHITELISTED); + Task tr1 = getTask(Task.LOCK_TASK_AUTH_WHITELISTED); mLockTaskController.startLockTaskMode(tr1, true, TEST_UID); // WHEN calling clearLockedTasks on the root task @@ -484,7 +484,7 @@ public class LockTaskControllerTest { Settings.Secure.LOCK_TO_APP_EXIT_LOCKED, 0, mContext.getUserId()); // AND there is a task record - TaskRecord tr1 = getTaskRecord(TaskRecord.LOCK_TASK_AUTH_WHITELISTED); + Task tr1 = getTask(Task.LOCK_TASK_AUTH_WHITELISTED); mLockTaskController.startLockTaskMode(tr1, true, TEST_UID); // WHEN calling clearLockedTasks on the root task @@ -531,8 +531,8 @@ public class LockTaskControllerTest { @Test public void testUpdateLockTaskPackages_taskRemoved() throws Exception { // GIVEN two tasks which are whitelisted initially - TaskRecord tr1 = getTaskRecordForUpdate(TEST_PACKAGE_NAME, true); - TaskRecord tr2 = getTaskRecordForUpdate(TEST_PACKAGE_NAME_2, false); + Task tr1 = getTaskForUpdate(TEST_PACKAGE_NAME, true); + Task tr2 = getTaskForUpdate(TEST_PACKAGE_NAME_2, false); String[] whitelist = {TEST_PACKAGE_NAME, TEST_PACKAGE_NAME_2}; mLockTaskController.updateLockTaskPackages(TEST_USER_ID, whitelist); @@ -570,7 +570,7 @@ public class LockTaskControllerTest { @Test public void testUpdateLockTaskFeatures() throws Exception { // GIVEN a locked task - TaskRecord tr = getTaskRecord(TaskRecord.LOCK_TASK_AUTH_WHITELISTED); + Task tr = getTask(Task.LOCK_TASK_AUTH_WHITELISTED); mLockTaskController.startLockTaskMode(tr, false, TEST_UID); // THEN lock task mode should be started with default status bar masks @@ -612,7 +612,7 @@ public class LockTaskControllerTest { @Test public void testUpdateLockTaskFeatures_differentUser() throws Exception { // GIVEN a locked task - TaskRecord tr = getTaskRecord(TaskRecord.LOCK_TASK_AUTH_WHITELISTED); + Task tr = getTask(Task.LOCK_TASK_AUTH_WHITELISTED); mLockTaskController.startLockTaskMode(tr, false, TEST_UID); // THEN lock task mode should be started with default status bar masks @@ -634,7 +634,7 @@ public class LockTaskControllerTest { @Test public void testUpdateLockTaskFeatures_keyguard() { // GIVEN a locked task - TaskRecord tr = getTaskRecord(TaskRecord.LOCK_TASK_AUTH_WHITELISTED); + Task tr = getTask(Task.LOCK_TASK_AUTH_WHITELISTED); mLockTaskController.startLockTaskMode(tr, false, TEST_UID); // THEN keyguard should be disabled @@ -693,18 +693,18 @@ public class LockTaskControllerTest { assertTrue((StatusBarManager.DISABLE2_QUICK_SETTINGS & flags.second) != 0); } - private TaskRecord getTaskRecord(int lockTaskAuth) { - return getTaskRecord(TEST_PACKAGE_NAME, lockTaskAuth); + private Task getTask(int lockTaskAuth) { + return getTask(TEST_PACKAGE_NAME, lockTaskAuth); } - private TaskRecord getTaskRecord(String pkg, int lockTaskAuth) { + private Task getTask(String pkg, int lockTaskAuth) { final Intent intent = new Intent() .setComponent(ComponentName.createRelative(pkg, TEST_CLASS_NAME)); - return getTaskRecord(intent, lockTaskAuth); + return getTask(intent, lockTaskAuth); } - private TaskRecord getTaskRecord(Intent intent, int lockTaskAuth) { - TaskRecord tr = mock(TaskRecord.class); + private Task getTask(Intent intent, int lockTaskAuth) { + Task tr = mock(Task.class); tr.mLockTaskAuth = lockTaskAuth; tr.intent = intent; tr.mUserId = TEST_USER_ID; @@ -714,17 +714,15 @@ public class LockTaskControllerTest { /** * @param isAppAware {@code true} if the app has marked if_whitelisted in its manifest */ - private TaskRecord getTaskRecordForUpdate(String pkg, boolean isAppAware) { + private Task getTaskForUpdate(String pkg, boolean isAppAware) { final int authIfWhitelisted = isAppAware - ? TaskRecord.LOCK_TASK_AUTH_LAUNCHABLE - : TaskRecord.LOCK_TASK_AUTH_WHITELISTED; - TaskRecord tr = getTaskRecord(pkg, authIfWhitelisted); + ? Task.LOCK_TASK_AUTH_LAUNCHABLE + : Task.LOCK_TASK_AUTH_WHITELISTED; + Task tr = getTask(pkg, authIfWhitelisted); doAnswer((invocation) -> { boolean isWhitelisted = mLockTaskController.isPackageWhitelisted(TEST_USER_ID, pkg); - tr.mLockTaskAuth = isWhitelisted - ? authIfWhitelisted - : TaskRecord.LOCK_TASK_AUTH_PINNABLE; + tr.mLockTaskAuth = isWhitelisted ? authIfWhitelisted : Task.LOCK_TASK_AUTH_PINNABLE; return null; }).when(tr).setLockTaskAuth(); return tr; diff --git a/services/tests/wmtests/src/com/android/server/wm/RecentTasksTest.java b/services/tests/wmtests/src/com/android/server/wm/RecentTasksTest.java index cc99fe0fd1c3d..e0ffb0d03f890 100644 --- a/services/tests/wmtests/src/com/android/server/wm/RecentTasksTest.java +++ b/services/tests/wmtests/src/com/android/server/wm/RecentTasksTest.java @@ -101,8 +101,8 @@ public class RecentTasksTest extends ActivityTestsBase { private TestRecentTasks mRecentTasks; private TestRunningTasks mRunningTasks; - private ArrayList mTasks; - private ArrayList mSameDocumentTasks; + private ArrayList mTasks; + private ArrayList mSameDocumentTasks; private CallbacksRecorder mCallbacksRecorder; @@ -172,8 +172,8 @@ public class RecentTasksTest extends ActivityTestsBase { public void testAddTasksNoMultiple_expectNoTrim() { // Add same non-multiple-task document tasks will remove the task (to re-add it) but not // trim it - TaskRecord documentTask1 = createDocumentTask(".DocumentTask1"); - TaskRecord documentTask2 = createDocumentTask(".DocumentTask1"); + Task documentTask1 = createDocumentTask(".DocumentTask1"); + Task documentTask2 = createDocumentTask(".DocumentTask1"); mRecentTasks.add(documentTask1); mRecentTasks.add(documentTask2); assertThat(mCallbacksRecorder.mAdded).contains(documentTask1); @@ -186,8 +186,8 @@ public class RecentTasksTest extends ActivityTestsBase { public void testAddTasksMaxTaskRecents_expectNoTrim() { // Add a task hitting max-recents for that app will remove the task (to add the next one) // but not trim it - TaskRecord documentTask1 = createDocumentTask(".DocumentTask1"); - TaskRecord documentTask2 = createDocumentTask(".DocumentTask1"); + Task documentTask1 = createDocumentTask(".DocumentTask1"); + Task documentTask2 = createDocumentTask(".DocumentTask1"); documentTask1.maxRecents = 1; documentTask2.maxRecents = 1; mRecentTasks.add(documentTask1); @@ -202,7 +202,7 @@ public class RecentTasksTest extends ActivityTestsBase { public void testAddTasksSameTask_expectNoTrim() { // Add a task that is already in the task list does not trigger any callbacks, it just // moves in the list - TaskRecord documentTask1 = createDocumentTask(".DocumentTask1"); + Task documentTask1 = createDocumentTask(".DocumentTask1"); mRecentTasks.add(documentTask1); mRecentTasks.add(documentTask1); assertThat(mCallbacksRecorder.mAdded).hasSize(1); @@ -214,9 +214,9 @@ public class RecentTasksTest extends ActivityTestsBase { @Test public void testAddTasksMultipleDocumentTasks_expectNoTrim() { // Add same multiple-task document tasks does not trim the first tasks - TaskRecord documentTask1 = createDocumentTask(".DocumentTask1", + Task documentTask1 = createDocumentTask(".DocumentTask1", FLAG_ACTIVITY_MULTIPLE_TASK); - TaskRecord documentTask2 = createDocumentTask(".DocumentTask1", + Task documentTask2 = createDocumentTask(".DocumentTask1", FLAG_ACTIVITY_MULTIPLE_TASK); mRecentTasks.add(documentTask1); mRecentTasks.add(documentTask2); @@ -231,10 +231,10 @@ public class RecentTasksTest extends ActivityTestsBase { public void testAddTasksMultipleTasks_expectRemovedNoTrim() { // Add multiple same-affinity non-document tasks, ensure that it removes the other task, // but that it does not trim it - TaskRecord task1 = createTaskBuilder(".Task1") + Task task1 = createTaskBuilder(".Task1") .setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_MULTIPLE_TASK) .build(); - TaskRecord task2 = createTaskBuilder(".Task1") + Task task2 = createTaskBuilder(".Task1") .setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_MULTIPLE_TASK) .build(); mRecentTasks.add(task1); @@ -255,10 +255,10 @@ public class RecentTasksTest extends ActivityTestsBase { public void testAddTasksDifferentStacks_expectNoRemove() { // Adding the same task with different activity types should not trigger removal of the // other task - TaskRecord task1 = createTaskBuilder(".Task1") + Task task1 = createTaskBuilder(".Task1") .setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_MULTIPLE_TASK) .setStack(mDisplay.getHomeStack()).build(); - TaskRecord task2 = createTaskBuilder(".Task1") + Task task2 = createTaskBuilder(".Task1") .setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_MULTIPLE_TASK) .setStack(mStack).build(); mRecentTasks.add(task1); @@ -274,7 +274,7 @@ public class RecentTasksTest extends ActivityTestsBase { public void testAddTaskCompatibleActivityType_expectRemove() { // Test with undefined activity type since the type is not persisted by the task persister // and we want to ensure that a new task will match a restored task - TaskRecord task1 = createTaskBuilder(".Task1") + Task task1 = createTaskBuilder(".Task1") .setFlags(FLAG_ACTIVITY_NEW_TASK) .setStack(mStack) .build(); @@ -283,7 +283,7 @@ public class RecentTasksTest extends ActivityTestsBase { mRecentTasks.add(task1); mCallbacksRecorder.clear(); - TaskRecord task2 = createTaskBuilder(".Task1") + Task task2 = createTaskBuilder(".Task1") .setFlags(FLAG_ACTIVITY_NEW_TASK) .setStack(mStack) .build(); @@ -298,7 +298,7 @@ public class RecentTasksTest extends ActivityTestsBase { @Test public void testAddTaskCompatibleActivityTypeDifferentUser_expectNoRemove() { - TaskRecord task1 = createTaskBuilder(".Task1") + Task task1 = createTaskBuilder(".Task1") .setFlags(FLAG_ACTIVITY_NEW_TASK) .setStack(mStack) .setUserId(TEST_USER_0_ID) @@ -308,7 +308,7 @@ public class RecentTasksTest extends ActivityTestsBase { mRecentTasks.add(task1); mCallbacksRecorder.clear(); - TaskRecord task2 = createTaskBuilder(".Task1") + Task task2 = createTaskBuilder(".Task1") .setFlags(FLAG_ACTIVITY_NEW_TASK) .setStack(mStack) .setUserId(TEST_USER_1_ID) @@ -323,7 +323,7 @@ public class RecentTasksTest extends ActivityTestsBase { @Test public void testAddTaskCompatibleWindowingMode_expectRemove() { - TaskRecord task1 = createTaskBuilder(".Task1") + Task task1 = createTaskBuilder(".Task1") .setFlags(FLAG_ACTIVITY_NEW_TASK) .setStack(mStack) .build(); @@ -332,7 +332,7 @@ public class RecentTasksTest extends ActivityTestsBase { mRecentTasks.add(task1); mCallbacksRecorder.clear(); - TaskRecord task2 = createTaskBuilder(".Task1") + Task task2 = createTaskBuilder(".Task1") .setFlags(FLAG_ACTIVITY_NEW_TASK) .setStack(mStack) .build(); @@ -349,7 +349,7 @@ public class RecentTasksTest extends ActivityTestsBase { @Test public void testAddTaskIncompatibleWindowingMode_expectNoRemove() { - TaskRecord task1 = createTaskBuilder(".Task1") + Task task1 = createTaskBuilder(".Task1") .setFlags(FLAG_ACTIVITY_NEW_TASK) .setStack(mStack) .build(); @@ -357,7 +357,7 @@ public class RecentTasksTest extends ActivityTestsBase { assertEquals(WINDOWING_MODE_FULLSCREEN, task1.getWindowingMode()); mRecentTasks.add(task1); - TaskRecord task2 = createTaskBuilder(".Task1") + Task task2 = createTaskBuilder(".Task1") .setFlags(FLAG_ACTIVITY_NEW_TASK) .setStack(mStack) .build(); @@ -421,13 +421,13 @@ public class RecentTasksTest extends ActivityTestsBase { @Test public void testOrderedIteration() { mRecentTasks.setOnlyTestVisibleRange(); - TaskRecord task1 = createTaskBuilder(".Task1").build(); + Task task1 = createTaskBuilder(".Task1").build(); task1.lastActiveTime = new Random().nextInt(); - TaskRecord task2 = createTaskBuilder(".Task1").build(); + Task task2 = createTaskBuilder(".Task1").build(); task2.lastActiveTime = new Random().nextInt(); - TaskRecord task3 = createTaskBuilder(".Task1").build(); + Task task3 = createTaskBuilder(".Task1").build(); task3.lastActiveTime = new Random().nextInt(); - TaskRecord task4 = createTaskBuilder(".Task1").build(); + Task task4 = createTaskBuilder(".Task1").build(); task4.lastActiveTime = new Random().nextInt(); mRecentTasks.add(task1); mRecentTasks.add(task2); @@ -435,9 +435,9 @@ public class RecentTasksTest extends ActivityTestsBase { mRecentTasks.add(task4); long prevLastActiveTime = 0; - final ArrayList tasks = mRecentTasks.getRawTasks(); + final ArrayList tasks = mRecentTasks.getRawTasks(); for (int i = 0; i < tasks.size(); i++) { - final TaskRecord task = tasks.get(i); + final Task task = tasks.get(i); assertThat(prevLastActiveTime).isLessThan(task.lastActiveTime); prevLastActiveTime = task.lastActiveTime; } @@ -462,8 +462,8 @@ public class RecentTasksTest extends ActivityTestsBase { @Test public void testTrimQuietProfileTasks() { mRecentTasks.setOnlyTestVisibleRange(); - TaskRecord qt1 = createTaskBuilder(".QuietTask1").setUserId(TEST_QUIET_USER_ID).build(); - TaskRecord qt2 = createTaskBuilder(".QuietTask2").setUserId(TEST_QUIET_USER_ID).build(); + Task qt1 = createTaskBuilder(".QuietTask1").setUserId(TEST_QUIET_USER_ID).build(); + Task qt2 = createTaskBuilder(".QuietTask2").setUserId(TEST_QUIET_USER_ID).build(); mRecentTasks.add(qt1); mRecentTasks.add(qt2); @@ -479,14 +479,14 @@ public class RecentTasksTest extends ActivityTestsBase { mRecentTasks.setOnlyTestVisibleRange(); mRecentTasks.setParameters(-1 /* min */, -1 /* max */, 50 /* ms */); - TaskRecord t1 = createTaskBuilder(".Task1").build(); + Task t1 = createTaskBuilder(".Task1").build(); t1.touchActiveTime(); mRecentTasks.add(t1); // Force a small sleep just beyond the session duration SystemClock.sleep(75); - TaskRecord t2 = createTaskBuilder(".Task2").build(); + Task t2 = createTaskBuilder(".Task2").build(); t2.touchActiveTime(); mRecentTasks.add(t2); @@ -499,10 +499,10 @@ public class RecentTasksTest extends ActivityTestsBase { mRecentTasks.setOnlyTestVisibleRange(); mRecentTasks.setParameters(-1 /* min */, 4 /* max */, -1 /* ms */); - TaskRecord excludedTask1 = createTaskBuilder(".ExcludedTask1") + Task excludedTask1 = createTaskBuilder(".ExcludedTask1") .setFlags(FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) .build(); - TaskRecord excludedTask2 = createTaskBuilder(".ExcludedTask2") + Task excludedTask2 = createTaskBuilder(".ExcludedTask2") .setFlags(FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) .build(); @@ -519,12 +519,12 @@ public class RecentTasksTest extends ActivityTestsBase { @Test public void testVisibleTasks_excludedFromRecents_firstTaskNotVisible() { // Create some set of tasks, some of which are visible and some are not - TaskRecord homeTask = setTaskActivityType( + Task homeTask = setTaskActivityType( createTaskBuilder("com.android.pkg1", ".HomeTask").build(), ACTIVITY_TYPE_HOME); homeTask.mUserSetupComplete = true; mRecentTasks.add(homeTask); - TaskRecord excludedTask1 = createTaskBuilder(".ExcludedTask1") + Task excludedTask1 = createTaskBuilder(".ExcludedTask1") .setFlags(FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) .build(); excludedTask1.mUserSetupComplete = true; @@ -537,25 +537,25 @@ public class RecentTasksTest extends ActivityTestsBase { @Test public void testVisibleTasks_excludedFromRecents_withExcluded() { // Create some set of tasks, some of which are visible and some are not - TaskRecord t1 = createTaskBuilder("com.android.pkg1", ".Task1").build(); + Task t1 = createTaskBuilder("com.android.pkg1", ".Task1").build(); t1.mUserSetupComplete = true; mRecentTasks.add(t1); - TaskRecord homeTask = setTaskActivityType( + Task homeTask = setTaskActivityType( createTaskBuilder("com.android.pkg1", ".HomeTask").build(), ACTIVITY_TYPE_HOME); homeTask.mUserSetupComplete = true; mRecentTasks.add(homeTask); - TaskRecord excludedTask1 = createTaskBuilder(".ExcludedTask1") + Task excludedTask1 = createTaskBuilder(".ExcludedTask1") .setFlags(FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) .build(); excludedTask1.mUserSetupComplete = true; mRecentTasks.add(excludedTask1); - TaskRecord excludedTask2 = createTaskBuilder(".ExcludedTask2") + Task excludedTask2 = createTaskBuilder(".ExcludedTask2") .setFlags(FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) .build(); excludedTask2.mUserSetupComplete = true; mRecentTasks.add(excludedTask2); - TaskRecord t2 = createTaskBuilder("com.android.pkg2", ".Task1").build(); + Task t2 = createTaskBuilder("com.android.pkg2", ".Task1").build(); t2.mUserSetupComplete = true; mRecentTasks.add(t2); @@ -568,7 +568,7 @@ public class RecentTasksTest extends ActivityTestsBase { mRecentTasks.setParameters(5 /* min */, -1 /* max */, 25 /* ms */); for (int i = 0; i < 4; i++) { - final TaskRecord task = mTasks.get(i); + final Task task = mTasks.get(i); task.touchActiveTime(); mRecentTasks.add(task); } @@ -589,7 +589,7 @@ public class RecentTasksTest extends ActivityTestsBase { mRecentTasks.setParameters(-1 /* min */, 3 /* max */, -1 /* ms */); for (int i = 0; i < 5; i++) { - final TaskRecord task = mTasks.get(i); + final Task task = mTasks.get(i); task.touchActiveTime(); mRecentTasks.add(task); } @@ -612,7 +612,7 @@ public class RecentTasksTest extends ActivityTestsBase { ActivityStack singleTaskStack = singleTaskDisplay.createStack( WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, true /* onTop */); - TaskRecord excludedTask1 = createTaskBuilder(".ExcludedTask1") + Task excludedTask1 = createTaskBuilder(".ExcludedTask1") .setStack(singleTaskStack) .build(); @@ -771,7 +771,7 @@ public class RecentTasksTest extends ActivityTestsBase { // Add a number of tasks (beyond the max) but ensure that only the task in the stack behind // the home stack is trimmed once a new task is added - final TaskRecord behindHomeTask = createTaskBuilder(".Task1") + final Task behindHomeTask = createTaskBuilder(".Task1") .setStack(behindHomeStack) .build(); mRecentTasks.add(behindHomeTask); @@ -809,7 +809,7 @@ public class RecentTasksTest extends ActivityTestsBase { mRecentTasks.add(createTaskBuilder("com.android.pkg1", ".Task4").build()); mRecentTasks.removeTasksByPackageName("com.android.pkg1", TEST_USER_0_ID); - final ArrayList tasks = mRecentTasks.getRawTasks(); + final ArrayList tasks = mRecentTasks.getRawTasks(); for (int i = 0; i < tasks.size(); i++) { if (tasks.get(i).intent.getComponent().getPackageName().equals("com.android.pkg1")) { fail("Expected com.android.pkg1 tasks to be removed"); @@ -822,30 +822,30 @@ public class RecentTasksTest extends ActivityTestsBase { mRecentTasks.setParameters(-1 /* min */, 3 /* max */, 100 /* ms */); // Create some set of tasks, some of which are visible and some are not - TaskRecord t1 = createTaskBuilder("com.android.pkg1", ".Task1").build(); + Task t1 = createTaskBuilder("com.android.pkg1", ".Task1").build(); mRecentTasks.add(t1); mRecentTasks.add(setTaskActivityType( createTaskBuilder("com.android.pkg1", ".HomeTask").build(), ACTIVITY_TYPE_HOME)); - TaskRecord t2 = createTaskBuilder("com.android.pkg2", ".Task2").build(); + Task t2 = createTaskBuilder("com.android.pkg2", ".Task2").build(); mRecentTasks.add(t2); mRecentTasks.add(setTaskWindowingMode( createTaskBuilder("com.android.pkg1", ".PipTask").build(), WINDOWING_MODE_PINNED)); - TaskRecord t3 = createTaskBuilder("com.android.pkg3", ".Task3").build(); + Task t3 = createTaskBuilder("com.android.pkg3", ".Task3").build(); mRecentTasks.add(t3); // Create some more tasks that are out of visible range, but are still visible - TaskRecord t4 = createTaskBuilder("com.android.pkg3", ".Task4").build(); + Task t4 = createTaskBuilder("com.android.pkg3", ".Task4").build(); mRecentTasks.add(t4); - TaskRecord t5 = createTaskBuilder("com.android.pkg3", ".Task5").build(); + Task t5 = createTaskBuilder("com.android.pkg3", ".Task5").build(); mRecentTasks.add(t5); // Create some more tasks that are out of the active session range, but are still visible - TaskRecord t6 = createTaskBuilder("com.android.pkg3", ".Task6").build(); + Task t6 = createTaskBuilder("com.android.pkg3", ".Task6").build(); t6.lastActiveTime = SystemClock.elapsedRealtime() - 200; mRecentTasks.add(t6); - TaskRecord t7 = createTaskBuilder("com.android.pkg3", ".Task7").build(); + Task t7 = createTaskBuilder("com.android.pkg3", ".Task7").build(); t7.lastActiveTime = SystemClock.elapsedRealtime() - 200; mRecentTasks.add(t7); @@ -859,17 +859,17 @@ public class RecentTasksTest extends ActivityTestsBase { mRecentTasks.setParameters(-1 /* min */, 3 /* max */, 100 /* ms */); // Create a visible task per user - TaskRecord t1 = createTaskBuilder(".Task1") + Task t1 = createTaskBuilder(".Task1") .setUserId(TEST_USER_0_ID) .build(); mRecentTasks.add(t1); - TaskRecord t2 = createTaskBuilder(".Task2") + Task t2 = createTaskBuilder(".Task2") .setUserId(TEST_QUIET_USER_ID) .build(); mRecentTasks.add(t2); - TaskRecord t3 = createTaskBuilder(".Task3") + Task t3 = createTaskBuilder(".Task3") .setUserId(TEST_USER_1_ID) .build(); mRecentTasks.add(t3); @@ -881,7 +881,7 @@ public class RecentTasksTest extends ActivityTestsBase { @Test public void testNotRestoreRecentTaskApis() { - final TaskRecord task = createTaskBuilder(".Task").build(); + final Task task = createTaskBuilder(".Task").build(); final int taskId = task.mTaskId; mRecentTasks.add(task); // Only keep the task in RecentTasks. @@ -906,7 +906,7 @@ public class RecentTasksTest extends ActivityTestsBase { @Test public void addTask_callsTaskNotificationController() { - final TaskRecord task = createTaskBuilder(".Task").build(); + final Task task = createTaskBuilder(".Task").build(); mRecentTasks.add(task); mRecentTasks.remove(task); @@ -918,7 +918,7 @@ public class RecentTasksTest extends ActivityTestsBase { @Test public void removeTask_callsTaskNotificationController() { - final TaskRecord task = createTaskBuilder(".Task").build(); + final Task task = createTaskBuilder(".Task").build(); mRecentTasks.add(task); mRecentTasks.remove(task); @@ -931,8 +931,8 @@ public class RecentTasksTest extends ActivityTestsBase { @Test public void removeALlVisibleTask_callsTaskNotificationController_twice() { - final TaskRecord task1 = createTaskBuilder(".Task").build(); - final TaskRecord task2 = createTaskBuilder(".Task2").build(); + final Task task1 = createTaskBuilder(".Task").build(); + final Task task2 = createTaskBuilder(".Task2").build(); mRecentTasks.add(task1); mRecentTasks.add(task2); @@ -948,8 +948,8 @@ public class RecentTasksTest extends ActivityTestsBase { * Ensures that the raw recent tasks list is in the provided order. Note that the expected tasks * should be ordered from least to most recent. */ - private void assertRecentTasksOrder(TaskRecord... expectedTasks) { - ArrayList tasks = mRecentTasks.getRawTasks(); + private void assertRecentTasksOrder(Task... expectedTasks) { + ArrayList tasks = mRecentTasks.getRawTasks(); assertTrue(expectedTasks.length == tasks.size()); for (int i = 0; i < tasks.size(); i++) { assertTrue(expectedTasks[i] == tasks.get(i)); @@ -960,7 +960,7 @@ public class RecentTasksTest extends ActivityTestsBase { * Ensures that the recent tasks list is in the provided order. Note that the expected tasks * should be ordered from least to most recent. */ - private void assertGetRecentTasksOrder(int getRecentTaskFlags, TaskRecord... expectedTasks) { + private void assertGetRecentTasksOrder(int getRecentTaskFlags, Task... expectedTasks) { doNothing().when(mRecentTasks).loadUserRecentsLocked(anyInt()); doReturn(true).when(mRecentTasks).isUserRunning(anyInt(), anyInt()); List infos = mRecentTasks.getRecentTasks(MAX_VALUE, getRecentTaskFlags, @@ -1079,12 +1079,12 @@ public class RecentTasksTest extends ActivityTestsBase { .setUserId(TEST_USER_0_ID); } - private TaskRecord createDocumentTask(String className) { + private Task createDocumentTask(String className) { return createDocumentTask(className, 0); } - private TaskRecord createDocumentTask(String className, int flags) { - TaskRecord task = createTaskBuilder(className) + private Task createDocumentTask(String className, int flags) { + Task task = createTaskBuilder(className) .setFlags(FLAG_ACTIVITY_NEW_DOCUMENT | flags) .build(); task.affinity = null; @@ -1092,7 +1092,7 @@ public class RecentTasksTest extends ActivityTestsBase { return task; } - private TaskRecord setTaskActivityType(TaskRecord task, + private Task setTaskActivityType(Task task, @WindowConfiguration.ActivityType int activityType) { Configuration config1 = new Configuration(); config1.windowConfiguration.setActivityType(activityType); @@ -1100,7 +1100,7 @@ public class RecentTasksTest extends ActivityTestsBase { return task; } - private TaskRecord setTaskWindowingMode(TaskRecord task, + private Task setTaskWindowingMode(Task task, @WindowConfiguration.WindowingMode int windowingMode) { Configuration config1 = new Configuration(); config1.windowConfiguration.setWindowingMode(windowingMode); @@ -1112,14 +1112,14 @@ public class RecentTasksTest extends ActivityTestsBase { assertTrimmed(); } - private void assertTrimmed(TaskRecord... tasks) { - final ArrayList trimmed = mCallbacksRecorder.mTrimmed; - final ArrayList removed = mCallbacksRecorder.mRemoved; + private void assertTrimmed(Task... tasks) { + final ArrayList trimmed = mCallbacksRecorder.mTrimmed; + final ArrayList removed = mCallbacksRecorder.mRemoved; assertWithMessage("Expected " + tasks.length + " trimmed tasks, got " + trimmed.size()) .that(trimmed).hasSize(tasks.length); assertWithMessage("Expected " + tasks.length + " removed tasks, got " + removed.size()) .that(removed).hasSize(tasks.length); - for (TaskRecord task : tasks) { + for (Task task : tasks) { assertWithMessage("Expected trimmed task: " + task).that(trimmed).contains(task); assertWithMessage("Expected removed task: " + task).that(removed).contains(task); } @@ -1141,9 +1141,9 @@ public class RecentTasksTest extends ActivityTestsBase { } private static class CallbacksRecorder implements Callbacks { - public final ArrayList mAdded = new ArrayList<>(); - public final ArrayList mTrimmed = new ArrayList<>(); - public final ArrayList mRemoved = new ArrayList<>(); + public final ArrayList mAdded = new ArrayList<>(); + public final ArrayList mTrimmed = new ArrayList<>(); + public final ArrayList mRemoved = new ArrayList<>(); void clear() { mAdded.clear(); @@ -1152,12 +1152,12 @@ public class RecentTasksTest extends ActivityTestsBase { } @Override - public void onRecentTaskAdded(TaskRecord task) { + public void onRecentTaskAdded(Task task) { mAdded.add(task); } @Override - public void onRecentTaskRemoved(TaskRecord task, boolean wasTrimmed, boolean killProcess) { + public void onRecentTaskRemoved(Task task, boolean wasTrimmed, boolean killProcess) { if (wasTrimmed) { mTrimmed.add(task); } @@ -1167,7 +1167,7 @@ public class RecentTasksTest extends ActivityTestsBase { private static class TestTaskPersister extends TaskPersister { public SparseBooleanArray mUserTaskIdsOverride; - public ArrayList mUserTasksOverride; + public ArrayList mUserTasksOverride; TestTaskPersister(File workingDir) { super(workingDir); @@ -1182,7 +1182,7 @@ public class RecentTasksTest extends ActivityTestsBase { } @Override - List restoreTasksForUserLocked(int userId, SparseBooleanArray preaddedTasks) { + List restoreTasksForUserLocked(int userId, SparseBooleanArray preaddedTasks) { if (mUserTasksOverride != null) { return mUserTasksOverride; } @@ -1270,7 +1270,7 @@ public class RecentTasksTest extends ActivityTestsBase { } @Override - protected boolean isTrimmable(TaskRecord task) { + protected boolean isTrimmable(Task task) { return mIsTrimmableOverride || super.isTrimmable(task); } } diff --git a/services/tests/wmtests/src/com/android/server/wm/RecentsAnimationTest.java b/services/tests/wmtests/src/com/android/server/wm/RecentsAnimationTest.java index 75f50ec54886f..41cbd8137f5e8 100644 --- a/services/tests/wmtests/src/com/android/server/wm/RecentsAnimationTest.java +++ b/services/tests/wmtests/src/com/android/server/wm/RecentsAnimationTest.java @@ -234,7 +234,7 @@ public class RecentsAnimationTest extends ActivityTestsBase { // Start the recents animation. RecentsAnimationCallbacks recentsAnimation = startRecentsActivity( - targetActivity.getTaskRecord().getBaseIntent().getComponent(), + targetActivity.getTask().getBaseIntent().getComponent(), true /* getRecentsAnimation */); // Ensure launch-behind is set for being visible. assertTrue(targetActivity.mLaunchTaskBehind); @@ -342,7 +342,7 @@ public class RecentsAnimationTest extends ActivityTestsBase { .setCreateTask(true) .setComponent(new ComponentName(mContext.getPackageName(), "Home2")) .build(); - otherUserHomeActivity.getTaskRecord().mUserId = TEST_USER_ID; + otherUserHomeActivity.getTask().mUserId = TEST_USER_ID; ActivityStack fullscreenStack = display.createStack(WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, true /* onTop */); @@ -357,7 +357,7 @@ public class RecentsAnimationTest extends ActivityTestsBase { any() /* starting */, anyInt() /* configChanges */, anyBoolean() /* preserveWindows */); - startRecentsActivity(otherUserHomeActivity.getTaskRecord().getBaseIntent().getComponent(), + startRecentsActivity(otherUserHomeActivity.getTask().getBaseIntent().getComponent(), true); // Ensure we find the task for the right user and it is made visible diff --git a/services/tests/wmtests/src/com/android/server/wm/RootActivityContainerTests.java b/services/tests/wmtests/src/com/android/server/wm/RootActivityContainerTests.java index 33ddbbbcf0391..3cc781c2c2b26 100644 --- a/services/tests/wmtests/src/com/android/server/wm/RootActivityContainerTests.java +++ b/services/tests/wmtests/src/com/android/server/wm/RootActivityContainerTests.java @@ -101,7 +101,7 @@ public class RootActivityContainerTests extends ActivityTestsBase { @Test public void testRestoringInvalidTask() { mRootActivityContainer.getDefaultDisplay().removeAllTasks(); - TaskRecord task = mRootActivityContainer.anyTaskForId(0 /*taskId*/, + Task task = mRootActivityContainer.anyTaskForId(0 /*taskId*/, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE, null, false /* onTop */); assertNull(task); } @@ -114,7 +114,7 @@ public class RootActivityContainerTests extends ActivityTestsBase { public void testReplacingTaskInPinnedStack() { final ActivityRecord firstActivity = new ActivityBuilder(mService).setCreateTask(true) .setStack(mFullscreenStack).build(); - final TaskRecord task = firstActivity.getTaskRecord(); + final Task task = firstActivity.getTask(); final ActivityRecord secondActivity = new ActivityBuilder(mService).setTask(task) .setStack(mFullscreenStack).build(); @@ -148,7 +148,7 @@ public class RootActivityContainerTests extends ActivityTestsBase { } private static void ensureStackPlacement(ActivityStack stack, ActivityRecord... activities) { - final TaskRecord task = stack.getAllTasks().get(0); + final Task task = stack.getAllTasks().get(0); final ArrayList stackActivities = new ArrayList<>(); for (int i = 0; i < task.getChildCount(); i++) { @@ -279,7 +279,7 @@ public class RootActivityContainerTests extends ActivityTestsBase { assertTrue(pinnedActivity.isFocusable()); // Without the overridding activity, stack should not be focusable. - pinnedStack.removeChild(pinnedActivity.getTaskRecord(), "testFocusability"); + pinnedStack.removeChild(pinnedActivity.getTask(), "testFocusability"); assertFalse(pinnedStack.isFocusable()); } @@ -294,7 +294,7 @@ public class RootActivityContainerTests extends ActivityTestsBase { final ActivityStack primaryStack = mRootActivityContainer.getDefaultDisplay() .createStack(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, ACTIVITY_TYPE_STANDARD, true /* onTop */); - final TaskRecord task = new TaskBuilder(mSupervisor).setStack(primaryStack).build(); + final Task task = new TaskBuilder(mSupervisor).setStack(primaryStack).build(); final ActivityRecord r = new ActivityBuilder(mService).setTask(task).build(); // Find a launch stack for the top activity in split-screen primary, while requesting @@ -323,7 +323,7 @@ public class RootActivityContainerTests extends ActivityTestsBase { .setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) .setOnTop(true) .build(); - final TaskRecord task = primaryStack.topTask(); + final Task task = primaryStack.topTask(); // Resize dock stack. mService.resizeDockedStack(stackSize, taskSize, null, null, null); @@ -343,7 +343,7 @@ public class RootActivityContainerTests extends ActivityTestsBase { final ActivityStack targetStack = new StackBuilder(mRootActivityContainer) .setOnTop(false) .build(); - final TaskRecord targetTask = targetStack.getChildAt(0); + final Task targetTask = targetStack.getChildAt(0); // Create Recents on top of the display. final ActivityStack stack = new StackBuilder(mRootActivityContainer).setActivityType( @@ -366,14 +366,14 @@ public class RootActivityContainerTests extends ActivityTestsBase { final ActivityDisplay display = mRootActivityContainer.getDefaultDisplay(); final ActivityStack targetStack = display.createStack(WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, false /* onTop */); - final TaskRecord targetTask = new TaskBuilder(mSupervisor).setStack(targetStack).build(); + final Task targetTask = new TaskBuilder(mSupervisor).setStack(targetStack).build(); // Create Recents on secondary display. final TestActivityDisplay secondDisplay = addNewActivityDisplayAt( ActivityDisplay.POSITION_TOP); final ActivityStack stack = secondDisplay.createStack(WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_RECENTS, true /* onTop */); - final TaskRecord task = new TaskBuilder(mSupervisor).setStack(stack).build(); + final Task task = new TaskBuilder(mSupervisor).setStack(stack).build(); new ActivityBuilder(mService).setTask(task).build(); final String reason = "findTaskToMoveToFront"; @@ -393,7 +393,7 @@ public class RootActivityContainerTests extends ActivityTestsBase { final ActivityDisplay display = mRootActivityContainer.getDefaultDisplay(); final ActivityStack targetStack = spy(display.createStack(WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, false /* onTop */)); - final TaskRecord task = new TaskBuilder(mSupervisor).setStack(targetStack).build(); + final Task task = new TaskBuilder(mSupervisor).setStack(targetStack).build(); final ActivityRecord activity = new ActivityBuilder(mService).setTask(task).build(); display.positionChildAtBottom(targetStack); @@ -449,7 +449,7 @@ public class RootActivityContainerTests extends ActivityTestsBase { ActivityDisplay.POSITION_TOP); final ActivityStack stack = secondDisplay.createStack(WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, true /* onTop */); - final TaskRecord task = new TaskBuilder(mSupervisor).setStack(stack).build(); + final Task task = new TaskBuilder(mSupervisor).setStack(stack).build(); new ActivityBuilder(mService).setTask(task).build(); doReturn(true).when(mRootActivityContainer).resumeHomeActivity(any(), any(), anyInt()); @@ -473,7 +473,7 @@ public class RootActivityContainerTests extends ActivityTestsBase { final ActivityDisplay display = mRootActivityContainer.getDefaultDisplay(); final ActivityStack targetStack = spy(display.createStack(WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, false /* onTop */)); - final TaskRecord task = new TaskBuilder(mSupervisor).setStack(targetStack).build(); + final Task task = new TaskBuilder(mSupervisor).setStack(targetStack).build(); final ActivityRecord activity = new ActivityBuilder(mService).setTask(task).build(); activity.setState(ActivityState.RESUMED, "test"); @@ -493,7 +493,7 @@ public class RootActivityContainerTests extends ActivityTestsBase { final ActivityDisplay display = mRootActivityContainer.getDefaultDisplay(); final ActivityStack targetStack = spy(display.createStack(WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, false /* onTop */)); - final TaskRecord task = new TaskBuilder(mSupervisor).setStack(targetStack).build(); + final Task task = new TaskBuilder(mSupervisor).setStack(targetStack).build(); final ActivityRecord activity = new ActivityBuilder(mService).setTask(task).build(); activity.setState(ActivityState.RESUMED, "test"); display.positionChildAtBottom(targetStack); diff --git a/services/tests/wmtests/src/com/android/server/wm/RunningTasksTest.java b/services/tests/wmtests/src/com/android/server/wm/RunningTasksTest.java index af6649d8d61d4..15dcbf5468c39 100644 --- a/services/tests/wmtests/src/com/android/server/wm/RunningTasksTest.java +++ b/services/tests/wmtests/src/com/android/server/wm/RunningTasksTest.java @@ -20,8 +20,6 @@ import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED; import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED; import static android.view.Display.DEFAULT_DISPLAY; -import static com.android.server.wm.ActivityDisplay.POSITION_BOTTOM; - import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertEquals; @@ -105,9 +103,9 @@ public class RunningTasksTest extends ActivityTestsBase { /** * Create a task with a single activity in it, with the given last active time. */ - private TaskRecord createTask(ActivityStack stack, String className, int taskId, + private Task createTask(ActivityStack stack, String className, int taskId, int lastActiveTime) { - final TaskRecord task = new TaskBuilder(mService.mStackSupervisor) + final Task task = new TaskBuilder(mService.mStackSupervisor) .setComponent(new ComponentName(mContext.getPackageName(), className)) .setTaskId(taskId) .setStack(stack) diff --git a/services/tests/wmtests/src/com/android/server/wm/TaskLaunchParamsModifierTests.java b/services/tests/wmtests/src/com/android/server/wm/TaskLaunchParamsModifierTests.java index 5a141ae983f2a..27ebd5ad94aab 100644 --- a/services/tests/wmtests/src/com/android/server/wm/TaskLaunchParamsModifierTests.java +++ b/services/tests/wmtests/src/com/android/server/wm/TaskLaunchParamsModifierTests.java @@ -95,7 +95,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase { @Test public void testReturnsSkipWithEmptyActivity() { - final TaskRecord task = new TaskBuilder(mSupervisor).build(); + final Task task = new TaskBuilder(mSupervisor).build(); assertEquals(RESULT_SKIP, mTarget.onCalculate(task, /* layout */ null, /* activity */ null, /* source */ null, /* options */ null, mCurrent, mResult)); } @@ -183,7 +183,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase { ActivityRecord reusableActivity = createSourceActivity(fullscreenDisplay); ActivityRecord source = createSourceActivity(freeformDisplay); - assertEquals(RESULT_CONTINUE, mTarget.onCalculate(reusableActivity.getTaskRecord(), + assertEquals(RESULT_CONTINUE, mTarget.onCalculate(reusableActivity.getTask(), /* layout */ null, mActivity, source, /* options */ null, mCurrent, mResult)); assertEquals(fullscreenDisplay.mDisplayId, mResult.mPreferredDisplayId); @@ -195,7 +195,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase { WINDOWING_MODE_FREEFORM); ActivityRecord source = createSourceActivity(freeformDisplay); - assertEquals(RESULT_CONTINUE, mTarget.onCalculate(source.getTaskRecord(), null /* layout */, + assertEquals(RESULT_CONTINUE, mTarget.onCalculate(source.getTask(), null /* layout */, null /* activity */, null /* source */, null /* options */, mCurrent, mResult)); assertEquals(freeformDisplay.mDisplayId, mResult.mPreferredDisplayId); @@ -214,7 +214,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase { source.mHandoverLaunchDisplayId = freeformDisplay.mDisplayId; source.noDisplay = true; - assertEquals(RESULT_CONTINUE, mTarget.onCalculate(reusableActivity.getTaskRecord(), + assertEquals(RESULT_CONTINUE, mTarget.onCalculate(reusableActivity.getTask(), null /* layout */, mActivity, source, null /* options */, mCurrent, mResult)); assertEquals(freeformDisplay.mDisplayId, mResult.mPreferredDisplayId); @@ -1319,7 +1319,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase { final ActivityStack stack = display.createStack(display.getWindowingMode(), ACTIVITY_TYPE_STANDARD, true); stack.setWindowingMode(WINDOWING_MODE_FREEFORM); - final TaskRecord task = new TaskBuilder(mSupervisor).setStack(stack).build(); + final Task task = new TaskBuilder(mSupervisor).setStack(stack).build(); // Just work around the unnecessary adjustments for bounds. task.getWindowConfiguration().setBounds(bounds); } diff --git a/services/tests/wmtests/src/com/android/server/wm/TaskPositioningControllerTests.java b/services/tests/wmtests/src/com/android/server/wm/TaskPositioningControllerTests.java index d2342f081fa13..8e32dad4c7589 100644 --- a/services/tests/wmtests/src/com/android/server/wm/TaskPositioningControllerTests.java +++ b/services/tests/wmtests/src/com/android/server/wm/TaskPositioningControllerTests.java @@ -66,8 +66,7 @@ public class TaskPositioningControllerTests extends WindowTestsBase { any(InputChannel.class))).thenReturn(true); mWindow = createWindow(null, TYPE_BASE_APPLICATION, "window"); - // TODO(task-merge): Remove cast. - ((TaskRecord) mWindow.getTask()).setResizeMode(RESIZE_MODE_RESIZEABLE); + mWindow.getTask().setResizeMode(RESIZE_MODE_RESIZEABLE); mWindow.mInputChannel = new InputChannel(); mWm.mWindowMap.put(mWindow.mClient.asBinder(), mWindow); doReturn(mock(InputMonitor.class)).when(mDisplayContent).getInputMonitor(); @@ -143,8 +142,7 @@ public class TaskPositioningControllerTests extends WindowTestsBase { doReturn(mWindow.getTask()).when(content).findTaskForResizePoint(anyInt(), anyInt()); assertNotNull(mWindow.getTask().getTopVisibleAppMainWindow()); - // TODO(task-merge): Remove cast. - ((TaskRecord) mWindow.getTask()).setResizeMode(RESIZE_MODE_UNRESIZEABLE); + mWindow.getTask().setResizeMode(RESIZE_MODE_UNRESIZEABLE); mTarget.handleTapOutsideTask(content, 0, 0); // Wait until the looper processes finishTaskPositioning. diff --git a/services/tests/wmtests/src/com/android/server/wm/TaskRecordTests.java b/services/tests/wmtests/src/com/android/server/wm/TaskRecordTests.java index 2cafc965e6486..faa9f11f97bf3 100644 --- a/services/tests/wmtests/src/com/android/server/wm/TaskRecordTests.java +++ b/services/tests/wmtests/src/com/android/server/wm/TaskRecordTests.java @@ -72,13 +72,12 @@ import androidx.test.filters.FlakyTest; import androidx.test.filters.MediumTest; import com.android.internal.app.IVoiceInteractor; -import com.android.server.wm.TaskRecord.TaskRecordFactory; +import com.android.server.wm.Task.TaskFactory; import com.android.server.wm.utils.WmDisplayCutout; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.Mockito; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlSerializer; @@ -88,10 +87,9 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; -import java.util.ArrayList; /** - * Tests for exercising {@link TaskRecord}. + * Tests for exercising {@link Task}. * * Build/Install/Run: * atest WmTests:TaskRecordTests @@ -107,31 +105,31 @@ public class TaskRecordTests extends ActivityTestsBase { @Before public void setUp() throws Exception { - TaskRecord.setTaskRecordFactory(null); + Task.setTaskFactory(null); mParentBounds = new Rect(10 /*left*/, 30 /*top*/, 80 /*right*/, 60 /*bottom*/); removeGlobalMinSizeRestriction(); } @Test public void testRestoreWindowedTask() throws Exception { - final TaskRecord expected = createTaskRecord(64); + final Task expected = createTask(64); expected.mLastNonFullscreenBounds = new Rect(50, 50, 100, 100); final byte[] serializedBytes = serializeToBytes(expected); - final TaskRecord actual = restoreFromBytes(serializedBytes); + final Task actual = restoreFromBytes(serializedBytes); assertEquals(expected.mTaskId, actual.mTaskId); assertEquals(expected.mLastNonFullscreenBounds, actual.mLastNonFullscreenBounds); } @Test public void testDefaultTaskFactoryNotNull() throws Exception { - assertNotNull(TaskRecord.getTaskRecordFactory()); + assertNotNull(Task.getTaskFactory()); } /** Ensure we have no chance to modify the original intent. */ @Test public void testCopyBaseIntentForTaskInfo() { - final TaskRecord task = createTaskRecord(1); + final Task task = createTask(1); task.setTaskDescription(new ActivityManager.TaskDescription()); final TaskInfo info = task.getTaskInfo(); @@ -141,19 +139,19 @@ public class TaskRecordTests extends ActivityTestsBase { @Test public void testCreateTestRecordUsingCustomizedFactory() throws Exception { - TestTaskRecordFactory factory = new TestTaskRecordFactory(); - TaskRecord.setTaskRecordFactory(factory); + TestTaskFactory factory = new TestTaskFactory(); + Task.setTaskFactory(factory); assertFalse(factory.mCreated); - TaskRecord.create(null, 0, null, null, null, null); + Task.create(null, 0, null, null, null, null); assertTrue(factory.mCreated); } @Test public void testReturnsToHomeStack() throws Exception { - final TaskRecord task = createTaskRecord(1); + final Task task = createTask(1); assertFalse(task.returnsToHomeStack()); task.intent = null; assertFalse(task.returnsToHomeStack()); @@ -198,7 +196,7 @@ public class TaskRecordTests extends ActivityTestsBase { ActivityDisplay display = mService.mRootActivityContainer.getDefaultDisplay(); ActivityStack stack = display.createStack(WINDOWING_MODE_FREEFORM, ACTIVITY_TYPE_STANDARD, true /* onTop */); - TaskRecord task = new TaskBuilder(mSupervisor).setStack(stack).build(); + Task task = new TaskBuilder(mSupervisor).setStack(stack).build(); final Configuration parentConfig = stack.getConfiguration(); parentConfig.windowConfiguration.setBounds(parentBounds); parentConfig.densityDpi = DisplayMetrics.DENSITY_DEFAULT; @@ -237,7 +235,7 @@ public class TaskRecordTests extends ActivityTestsBase { ActivityDisplay display = mService.mRootActivityContainer.getDefaultDisplay(); ActivityStack stack = new StackBuilder(mRootActivityContainer).setDisplay(display) .setWindowingMode(WINDOWING_MODE_FREEFORM).build(); - TaskRecord task = stack.getChildAt(0); + Task task = stack.getChildAt(0); task.getRootActivity().setOrientation(SCREEN_ORIENTATION_UNSPECIFIED); DisplayInfo info = new DisplayInfo(); display.mDisplay.getDisplayInfo(info); @@ -281,7 +279,7 @@ public class TaskRecordTests extends ActivityTestsBase { ActivityStack stack = new StackBuilder(mRootActivityContainer) .setWindowingMode(WINDOWING_MODE_FULLSCREEN).setDisplay(display).build(); - TaskRecord task = stack.getChildAt(0); + Task task = stack.getChildAt(0); ActivityRecord root = task.getTopActivity(); assertEquals(fullScreenBounds, task.getBounds()); @@ -345,7 +343,7 @@ public class TaskRecordTests extends ActivityTestsBase { display.getRequestedOverrideConfiguration()); ActivityStack stack = new StackBuilder(mRootActivityContainer) .setWindowingMode(WINDOWING_MODE_FULLSCREEN).setDisplay(display).build(); - TaskRecord task = stack.getChildAt(0); + Task task = stack.getChildAt(0); ActivityRecord root = task.getTopActivity(); final WindowContainer parentWindowContainer = @@ -355,7 +353,7 @@ public class TaskRecordTests extends ActivityTestsBase { doReturn(parentWindowContainer).when(task).getParent(); doReturn(true).when(parentWindowContainer).handlesOrientationChangeFromDescendant(); - // Setting app to fixed portrait fits within parent, but TaskRecord shouldn't adjust the + // Setting app to fixed portrait fits within parent, but Task shouldn't adjust the // bounds because its parent says it will handle it at a later time. root.setRequestedOrientation(SCREEN_ORIENTATION_PORTRAIT); assertEquals(root, task.getRootActivity()); @@ -365,7 +363,7 @@ public class TaskRecordTests extends ActivityTestsBase { @Test public void testComputeConfigResourceOverrides() { - final TaskRecord task = new TaskBuilder(mSupervisor).build(); + final Task task = new TaskBuilder(mSupervisor).build(); final Configuration inOutConfig = new Configuration(); final Configuration parentConfig = new Configuration(); final int longSide = 1200; @@ -434,7 +432,7 @@ public class TaskRecordTests extends ActivityTestsBase { info.packageName = DEFAULT_COMPONENT_PACKAGE_NAME; info.targetActivity = targetClassName; - final TaskRecord task = TaskRecord.create(mService, 1 /* taskId */, info, intent, + final Task task = Task.create(mService, 1 /* taskId */, info, intent, null /* taskDescription */, null /*stack*/); assertEquals("The alias activity component should be saved in task intent.", aliasClassName, task.intent.getComponent().getClassName()); @@ -457,7 +455,7 @@ public class TaskRecordTests extends ActivityTestsBase { /** Test that root activity index is reported correctly for several activities in the task. */ @Test public void testFindRootIndex() { - final TaskRecord task = getTestTask(); + final Task task = getTestTask(); // Add an extra activity on top of the root one new ActivityBuilder(mService).setTask(task).build(); @@ -471,7 +469,7 @@ public class TaskRecordTests extends ActivityTestsBase { */ @Test public void testFindRootIndex_finishing() { - final TaskRecord task = getTestTask(); + final Task task = getTestTask(); // Add extra two activities and mark the two on the bottom as finishing. final ActivityRecord activity0 = task.getChildAt(0); activity0.finishing = true; @@ -489,7 +487,7 @@ public class TaskRecordTests extends ActivityTestsBase { */ @Test public void testFindRootIndex_effectiveRoot() { - final TaskRecord task = getTestTask(); + final Task task = getTestTask(); // Add an extra activity on top of the root one new ActivityBuilder(mService).setTask(task).build(); @@ -503,7 +501,7 @@ public class TaskRecordTests extends ActivityTestsBase { */ @Test public void testFindRootIndex_effectiveRoot_finishingAndRelinquishing() { - final TaskRecord task = getTestTask(); + final Task task = getTestTask(); // Add extra two activities. Mark the one on the bottom with "relinquishTaskIdentity" and // one above as finishing. final ActivityRecord activity0 = task.getChildAt(0); @@ -522,7 +520,7 @@ public class TaskRecordTests extends ActivityTestsBase { */ @Test public void testFindRootIndex_effectiveRoot_relinquishingAndSingleActivity() { - final TaskRecord task = getTestTask(); + final Task task = getTestTask(); // Set relinquishTaskIdentity for the only activity in the task task.getChildAt(0).info.flags |= FLAG_RELINQUISH_TASK_IDENTITY; @@ -536,7 +534,7 @@ public class TaskRecordTests extends ActivityTestsBase { */ @Test public void testFindRootIndex_effectiveRoot_relinquishingMultipleActivities() { - final TaskRecord task = getTestTask(); + final Task task = getTestTask(); // Set relinquishTaskIdentity for all activities in the task final ActivityRecord activity0 = task.getChildAt(0); activity0.info.flags |= FLAG_RELINQUISH_TASK_IDENTITY; @@ -547,10 +545,10 @@ public class TaskRecordTests extends ActivityTestsBase { task.getChildCount() - 1, task.findRootIndex(true /* effectiveRoot*/)); } - /** Test that bottom-most activity is reported in {@link TaskRecord#getRootActivity()}. */ + /** Test that bottom-most activity is reported in {@link Task#getRootActivity()}. */ @Test public void testGetRootActivity() { - final TaskRecord task = getTestTask(); + final Task task = getTestTask(); // Add an extra activity on top of the root one new ActivityBuilder(mService).setTask(task).build(); @@ -559,11 +557,11 @@ public class TaskRecordTests extends ActivityTestsBase { } /** - * Test that first non-finishing activity is reported in {@link TaskRecord#getRootActivity()}. + * Test that first non-finishing activity is reported in {@link Task#getRootActivity()}. */ @Test public void testGetRootActivity_finishing() { - final TaskRecord task = getTestTask(); + final Task task = getTestTask(); // Add an extra activity on top of the root one new ActivityBuilder(mService).setTask(task).build(); // Mark the root as finishing @@ -574,11 +572,11 @@ public class TaskRecordTests extends ActivityTestsBase { } /** - * Test that relinquishTaskIdentity flag is ignored in {@link TaskRecord#getRootActivity()}. + * Test that relinquishTaskIdentity flag is ignored in {@link Task#getRootActivity()}. */ @Test public void testGetRootActivity_relinquishTaskIdentity() { - final TaskRecord task = getTestTask(); + final Task task = getTestTask(); // Mark the bottom-most activity with FLAG_RELINQUISH_TASK_IDENTITY. final ActivityRecord activity0 = task.getChildAt(0); activity0.info.flags |= FLAG_RELINQUISH_TASK_IDENTITY; @@ -590,12 +588,12 @@ public class TaskRecordTests extends ActivityTestsBase { } /** - * Test that no activity is reported in {@link TaskRecord#getRootActivity()} when all activities + * Test that no activity is reported in {@link Task#getRootActivity()} when all activities * in the task are finishing. */ @Test public void testGetRootActivity_allFinishing() { - final TaskRecord task = getTestTask(); + final Task task = getTestTask(); // Mark the bottom-most activity as finishing. final ActivityRecord activity0 = task.getChildAt(0); activity0.finishing = true; @@ -611,7 +609,7 @@ public class TaskRecordTests extends ActivityTestsBase { */ @Test public void testIsRootActivity() { - final TaskRecord task = getTestTask(); + final Task task = getTestTask(); // Mark the bottom-most activity as finishing. final ActivityRecord activity0 = task.getChildAt(0); activity0.finishing = true; @@ -628,7 +626,7 @@ public class TaskRecordTests extends ActivityTestsBase { */ @Test public void testIsRootActivity_allFinishing() { - final TaskRecord task = getTestTask(); + final Task task = getTestTask(); // Mark the bottom-most activity as finishing. final ActivityRecord activity0 = task.getChildAt(0); activity0.finishing = true; @@ -646,10 +644,10 @@ public class TaskRecordTests extends ActivityTestsBase { */ @Test public void testGetTaskForActivity() { - final TaskRecord task0 = getTestTask(); + final Task task0 = getTestTask(); final ActivityRecord activity0 = task0.getChildAt(0); - final TaskRecord task1 = getTestTask(); + final Task task1 = getTestTask(); final ActivityRecord activity1 = task1.getChildAt(0); assertEquals(task0.mTaskId, @@ -664,7 +662,7 @@ public class TaskRecordTests extends ActivityTestsBase { */ @Test public void testGetTaskForActivity_onlyRoot_finishing() { - final TaskRecord task = getTestTask(); + final Task task = getTestTask(); // Make the current root activity finishing final ActivityRecord activity0 = task.getChildAt(0); activity0.finishing = true; @@ -687,7 +685,7 @@ public class TaskRecordTests extends ActivityTestsBase { */ @Test public void testGetTaskForActivity_onlyRoot_relinquishTaskIdentity() { - final TaskRecord task = getTestTask(); + final Task task = getTestTask(); // Make the current root activity relinquish task identity final ActivityRecord activity0 = task.getChildAt(0); activity0.info.flags |= FLAG_RELINQUISH_TASK_IDENTITY; @@ -710,7 +708,7 @@ public class TaskRecordTests extends ActivityTestsBase { */ @Test public void testGetTaskForActivity_notOnlyRoot() { - final TaskRecord task = getTestTask(); + final Task task = getTestTask(); // Mark the bottom-most activity as finishing. final ActivityRecord activity0 = task.getChildAt(0); activity0.finishing = true; @@ -731,12 +729,12 @@ public class TaskRecordTests extends ActivityTestsBase { } /** - * Test {@link TaskRecord#updateEffectiveIntent()}. + * Test {@link Task#updateEffectiveIntent()}. */ @Test public void testUpdateEffectiveIntent() { // Test simple case with a single activity. - final TaskRecord task = getTestTask(); + final Task task = getTestTask(); final ActivityRecord activity0 = task.getChildAt(0); spyOn(task); @@ -745,13 +743,13 @@ public class TaskRecordTests extends ActivityTestsBase { } /** - * Test {@link TaskRecord#updateEffectiveIntent()} with root activity marked as finishing. This + * Test {@link Task#updateEffectiveIntent()} with root activity marked as finishing. This * should make the task use the second activity when updating the intent. */ @Test public void testUpdateEffectiveIntent_rootFinishing() { // Test simple case with a single activity. - final TaskRecord task = getTestTask(); + final Task task = getTestTask(); final ActivityRecord activity0 = task.getChildAt(0); // Mark the bottom-most activity as finishing. activity0.finishing = true; @@ -764,14 +762,14 @@ public class TaskRecordTests extends ActivityTestsBase { } /** - * Test {@link TaskRecord#updateEffectiveIntent()} when all activities are finishing or + * Test {@link Task#updateEffectiveIntent()} when all activities are finishing or * relinquishing task identity. In this case the root activity should still be used when * updating the intent (legacy behavior). */ @Test public void testUpdateEffectiveIntent_allFinishing() { // Test simple case with a single activity. - final TaskRecord task = getTestTask(); + final Task task = getTestTask(); final ActivityRecord activity0 = task.getChildAt(0); // Mark the bottom-most activity as finishing. activity0.finishing = true; @@ -785,7 +783,7 @@ public class TaskRecordTests extends ActivityTestsBase { verify(task).setIntent(eq(activity0)); } - private TaskRecord getTestTask() { + private Task getTestTask() { final ActivityStack stack = new StackBuilder(mRootActivityContainer).build(); return stack.getChildAt(0); } @@ -796,7 +794,7 @@ public class TaskRecordTests extends ActivityTestsBase { ActivityDisplay display = mService.mRootActivityContainer.getDefaultDisplay(); ActivityStack stack = display.createStack(windowingMode, ACTIVITY_TYPE_STANDARD, true /* onTop */); - TaskRecord task = new TaskBuilder(mSupervisor).setStack(stack).build(); + Task task = new TaskBuilder(mSupervisor).setStack(stack).build(); final Configuration parentConfig = stack.getConfiguration(); parentConfig.windowConfiguration.setAppBounds(parentBounds); @@ -808,7 +806,7 @@ public class TaskRecordTests extends ActivityTestsBase { task.getResolvedOverrideConfiguration().windowConfiguration.getAppBounds()); } - private byte[] serializeToBytes(TaskRecord r) throws IOException, XmlPullParserException { + private byte[] serializeToBytes(Task r) throws IOException, XmlPullParserException { try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { final XmlSerializer serializer = Xml.newSerializer(); serializer.setOutput(os, "UTF-8"); @@ -823,29 +821,29 @@ public class TaskRecordTests extends ActivityTestsBase { } } - private TaskRecord restoreFromBytes(byte[] in) throws IOException, XmlPullParserException { + private Task restoreFromBytes(byte[] in) throws IOException, XmlPullParserException { try (Reader reader = new InputStreamReader(new ByteArrayInputStream(in))) { final XmlPullParser parser = Xml.newPullParser(); parser.setInput(reader); assertEquals(XmlPullParser.START_TAG, parser.next()); assertEquals(TASK_TAG, parser.getName()); - return TaskRecord.restoreFromXml(parser, mService.mStackSupervisor); + return Task.restoreFromXml(parser, mService.mStackSupervisor); } } - private TaskRecord createTaskRecord(int taskId) { - return new TaskRecord(mService, taskId, new Intent(), null, null, null, + private Task createTask(int taskId) { + return new Task(mService, taskId, new Intent(), null, null, null, ActivityBuilder.getDefaultComponent(), null, false, false, false, 0, 10050, null, 0, false, null, 0, 0, 0, 0, 0, null, 0, false, false, false, 0, 0, null /*ActivityInfo*/, null /*_voiceSession*/, null /*_voiceInteractor*/, null /*stack*/); } - private static class TestTaskRecordFactory extends TaskRecordFactory { + private static class TestTaskFactory extends TaskFactory { private boolean mCreated = false; @Override - TaskRecord create(ActivityTaskManagerService service, int taskId, ActivityInfo info, + Task create(ActivityTaskManagerService service, int taskId, ActivityInfo info, Intent intent, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, ActivityStack stack) { mCreated = true; @@ -853,7 +851,7 @@ public class TaskRecordTests extends ActivityTestsBase { } @Override - TaskRecord create(ActivityTaskManagerService service, int taskId, ActivityInfo info, + Task create(ActivityTaskManagerService service, int taskId, ActivityInfo info, Intent intent, ActivityManager.TaskDescription taskDescription, ActivityStack stack) { mCreated = true; @@ -861,7 +859,7 @@ public class TaskRecordTests extends ActivityTestsBase { } @Override - TaskRecord create(ActivityTaskManagerService service, int taskId, Intent intent, + Task create(ActivityTaskManagerService service, int taskId, Intent intent, Intent affinityIntent, String affinity, String rootAffinity, ComponentName realActivity, ComponentName origActivity, boolean rootWasReset, boolean autoRemoveRecents, @@ -879,7 +877,7 @@ public class TaskRecordTests extends ActivityTestsBase { } @Override - TaskRecord restoreFromXml(XmlPullParser in, ActivityStackSupervisor stackSupervisor) + Task restoreFromXml(XmlPullParser in, ActivityStackSupervisor stackSupervisor) throws IOException, XmlPullParserException { mCreated = true; return null; diff --git a/services/tests/wmtests/src/com/android/server/wm/TaskStackContainersTests.java b/services/tests/wmtests/src/com/android/server/wm/TaskStackContainersTests.java index f56839b28addf..8617fb258ba14 100644 --- a/services/tests/wmtests/src/com/android/server/wm/TaskStackContainersTests.java +++ b/services/tests/wmtests/src/com/android/server/wm/TaskStackContainersTests.java @@ -121,7 +121,7 @@ public class TaskStackContainersTests extends WindowTestsBase { false /* includingParents */); // Move the task of {@code mDisplayContent} to top. - stack.positionChildAt(WindowContainer.POSITION_TOP, (TaskRecord) task, true /* includingParents */); + stack.positionChildAt(WindowContainer.POSITION_TOP, task, true /* includingParents */); final int indexOfDisplayWithPinnedStack = mWm.mRoot.mChildren.indexOf(mDisplayContent); assertEquals("The testing DisplayContent should be moved to top with task", diff --git a/services/tests/wmtests/src/com/android/server/wm/TaskStackTests.java b/services/tests/wmtests/src/com/android/server/wm/TaskStackTests.java index 98d4e6667b313..40ce363245788 100644 --- a/services/tests/wmtests/src/com/android/server/wm/TaskStackTests.java +++ b/services/tests/wmtests/src/com/android/server/wm/TaskStackTests.java @@ -58,12 +58,12 @@ public class TaskStackTests extends WindowTestsBase { final Task task2 = createTaskInStack(stack, 1 /* userId */); // Current user task should be moved to top. - stack.positionChildAt(WindowContainer.POSITION_TOP, (TaskRecord) task1, false /* includingParents */); + stack.positionChildAt(WindowContainer.POSITION_TOP, task1, false /* includingParents */); assertEquals(stack.mChildren.get(0), task2); assertEquals(stack.mChildren.get(1), task1); // Non-current user won't be moved to top. - stack.positionChildAt(WindowContainer.POSITION_TOP, (TaskRecord) task2, false /* includingParents */); + stack.positionChildAt(WindowContainer.POSITION_TOP, task2, false /* includingParents */); assertEquals(stack.mChildren.get(0), task2); assertEquals(stack.mChildren.get(1), task1); } diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowTestUtils.java b/services/tests/wmtests/src/com/android/server/wm/WindowTestUtils.java index 11dc1babd21de..797a6bc7e087d 100644 --- a/services/tests/wmtests/src/com/android/server/wm/WindowTestUtils.java +++ b/services/tests/wmtests/src/com/android/server/wm/WindowTestUtils.java @@ -35,7 +35,7 @@ class WindowTestUtils { /** Creates a {@link Task} and adds it to the specified {@link ActivityStack}. */ static Task createTaskInStack(WindowManagerService service, ActivityStack stack, int userId) { synchronized (service.mGlobalLock) { - final TaskRecord task = new ActivityTestsBase.TaskBuilder( + final Task task = new ActivityTestsBase.TaskBuilder( stack.mStackSupervisor) .setUserId(userId) .setStack(stack)