Debian Codegraph @

libs/WindowManager/Shell/src/com/android/wm/shell/recents/RecentTasksController.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2021 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.android.wm.shell.recents;
18
19 import static android.app.ActivityTaskManager.INVALID_TASK_ID;
20 import static android.content.pm.PackageManager.FEATURE_PC;
21
22 import static com.android.wm.shell.common.ExecutorUtils.executeRemoteCallWithTaskPermission;
23 import static com.android.wm.shell.sysui.ShellSharedConstants.KEY_EXTRA_SHELL_RECENT_TASKS;
24
25 import android.app.ActivityManager;
26 import android.app.ActivityTaskManager;
27 import android.app.TaskInfo;
28 import android.content.ComponentName;
29 import android.content.Context;
30 import android.os.RemoteException;
31 import android.util.Slog;
32 import android.util.SparseArray;
33 import android.util.SparseIntArray;
34
35 import androidx.annotation.BinderThread;
36 import androidx.annotation.NonNull;
37 import androidx.annotation.Nullable;
38 import androidx.annotation.VisibleForTesting;
39
40 import com.android.internal.protolog.common.ProtoLog;
41 import com.android.wm.shell.common.ExternalInterfaceBinder;
42 import com.android.wm.shell.common.RemoteCallable;
43 import com.android.wm.shell.common.ShellExecutor;
44 import com.android.wm.shell.common.SingleInstanceRemoteListener;
45 import com.android.wm.shell.common.TaskStackListenerCallback;
46 import com.android.wm.shell.common.TaskStackListenerImpl;
47 import com.android.wm.shell.common.annotations.ExternalThread;
48 import com.android.wm.shell.common.annotations.ShellMainThread;
49 import com.android.wm.shell.desktopmode.DesktopModeStatus;
50 import com.android.wm.shell.desktopmode.DesktopModeTaskRepository;
51 import com.android.wm.shell.protolog.ShellProtoLogGroup;
52 import com.android.wm.shell.sysui.ShellCommandHandler;
53 import com.android.wm.shell.sysui.ShellController;
54 import com.android.wm.shell.sysui.ShellInit;
55 import com.android.wm.shell.util.GroupedRecentTaskInfo;
56 import com.android.wm.shell.util.SplitBounds;
57
58 import java.io.PrintWriter;
59 import java.util.ArrayList;
60 import java.util.HashMap;
61 import java.util.List;
62 import java.util.Map;
63 import java.util.Optional;
64 import java.util.concurrent.Executor;
65 import java.util.function.Consumer;
66
67 /**
68 * Manages the recent task list from the system, caching it as necessary.
69 */
70 public class RecentTasksController implements TaskStackListenerCallback,
71 RemoteCallable<RecentTasksController>, DesktopModeTaskRepository.ActiveTasksListener {
72 private static final String TAG = RecentTasksController.class.getSimpleName();
73
74 private final Context mContext;
75 private final ShellController mShellController;
76 private final ShellCommandHandler mShellCommandHandler;
77 private final Optional<DesktopModeTaskRepository> mDesktopModeTaskRepository;
78 private final ShellExecutor mMainExecutor;
79 private final TaskStackListenerImpl mTaskStackListener;
80 private final RecentTasksImpl mImpl = new RecentTasksImpl();
81 private final ActivityTaskManager mActivityTaskManager;
82 private IRecentTasksListener mListener;
83 private final boolean mIsDesktopMode;
84
85 // Mapping of split task ids, mappings are symmetrical (ie. if t1 is the taskid of a task in a
86 // pair, then mSplitTasks[t1] = t2, and mSplitTasks[t2] = t1)
87 private final SparseIntArray mSplitTasks = new SparseIntArray();
88 /**
89 * Maps taskId to {@link SplitBounds} for both taskIDs.
90 * Meaning there will be two taskId integers mapping to the same object.
91 * If there's any ordering to the pairing than we can probably just get away with only one
92 * taskID mapping to it, leaving both for consistency with {@link #mSplitTasks} for now.
93 */
94 private final Map<Integer, SplitBounds> mTaskSplitBoundsMap = new HashMap<>();
95
96 /**
97 * Creates {@link RecentTasksController}, returns {@code null} if the feature is not
98 * supported.
99 */
100 @Nullable
101 public static RecentTasksController create(
102 Context context,
103 ShellInit shellInit,
104 ShellController shellController,
105 ShellCommandHandler shellCommandHandler,
106 TaskStackListenerImpl taskStackListener,
107 ActivityTaskManager activityTaskManager,
108 Optional<DesktopModeTaskRepository> desktopModeTaskRepository,
109 @ShellMainThread ShellExecutor mainExecutor
110 ) {
111 if (!context.getResources().getBoolean(com.android.internal.R.bool.config_hasRecents)) {
112 return null;
113 }
114 return new RecentTasksController(context, shellInit, shellController, shellCommandHandler,
115 taskStackListener, activityTaskManager, desktopModeTaskRepository, mainExecutor);
116 }
117
118 RecentTasksController(Context context,
119 ShellInit shellInit,
120 ShellController shellController,
121 ShellCommandHandler shellCommandHandler,
122 TaskStackListenerImpl taskStackListener,
123 ActivityTaskManager activityTaskManager,
124 Optional<DesktopModeTaskRepository> desktopModeTaskRepository,
125 ShellExecutor mainExecutor) {
126 mContext = context;
127 mShellController = shellController;
128 mShellCommandHandler = shellCommandHandler;
129 mActivityTaskManager = activityTaskManager;
130 mIsDesktopMode = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
131 mTaskStackListener = taskStackListener;
132 mDesktopModeTaskRepository = desktopModeTaskRepository;
133 mMainExecutor = mainExecutor;
134 shellInit.addInitCallback(this::onInit, this);
135 }
136
137 public RecentTasks asRecentTasks() {
138 return mImpl;
139 }
140
141 private ExternalInterfaceBinder createExternalInterface() {
142 return new IRecentTasksImpl(this);
143 }
144
145 private void onInit() {
146 mShellController.addExternalInterface(KEY_EXTRA_SHELL_RECENT_TASKS,
147 this::createExternalInterface, this);
148 mShellCommandHandler.addDumpCallback(this::dump, this);
149 mTaskStackListener.addListener(this);
150 mDesktopModeTaskRepository.ifPresent(it -> it.addActiveTaskListener(this));
151 }
152
153 /**
154 * Adds a split pair. This call does not validate the taskIds, only that they are not the same.
155 */
156 public void addSplitPair(int taskId1, int taskId2, SplitBounds splitBounds) {
157 if (taskId1 == taskId2) {
158 return;
159 }
160 if (mSplitTasks.get(taskId1, INVALID_TASK_ID) == taskId2
161 && mTaskSplitBoundsMap.get(taskId1).equals(splitBounds)) {
162 // If the two tasks are already paired and the bounds are the same, then skip updating
163 return;
164 }
165 // Remove any previous pairs
166 removeSplitPair(taskId1);
167 removeSplitPair(taskId2);
168 mTaskSplitBoundsMap.remove(taskId1);
169 mTaskSplitBoundsMap.remove(taskId2);
170
171 mSplitTasks.put(taskId1, taskId2);
172 mSplitTasks.put(taskId2, taskId1);
173 mTaskSplitBoundsMap.put(taskId1, splitBounds);
174 mTaskSplitBoundsMap.put(taskId2, splitBounds);
175 notifyRecentTasksChanged();
176 ProtoLog.v(ShellProtoLogGroup.WM_SHELL_RECENT_TASKS, "Add split pair: %d, %d, %s",
177 taskId1, taskId2, splitBounds);
178 }
179
180 /**
181 * Removes a split pair.
182 */
183 public void removeSplitPair(int taskId) {
184 int pairedTaskId = mSplitTasks.get(taskId, INVALID_TASK_ID);
185 if (pairedTaskId != INVALID_TASK_ID) {
186 mSplitTasks.delete(taskId);
187 mSplitTasks.delete(pairedTaskId);
188 mTaskSplitBoundsMap.remove(taskId);
189 mTaskSplitBoundsMap.remove(pairedTaskId);
190 notifyRecentTasksChanged();
191 ProtoLog.v(ShellProtoLogGroup.WM_SHELL_RECENT_TASKS, "Remove split pair: %d, %d",
192 taskId, pairedTaskId);
193 }
194 }
195
196 @Override
197 public Context getContext() {
198 return mContext;
199 }
200
201 @Override
202 public ShellExecutor getRemoteCallExecutor() {
203 return mMainExecutor;
204 }
205
206 @Override
207 public void onTaskStackChanged() {
208 notifyRecentTasksChanged();
209 }
210
211 @Override
212 public void onRecentTaskListUpdated() {
213 // In some cases immediately after booting, the tasks in the system recent task list may be
214 // loaded, but not in the active task hierarchy in the system. These tasks are displayed in
215 // overview, but removing them don't result in a onTaskStackChanged() nor a onTaskRemoved()
216 // callback (those are for changes to the active tasks), but the task list is still updated,
217 // so we should also invalidate the change id to ensure we load a new list instead of
218 // reusing a stale list.
219 notifyRecentTasksChanged();
220 }
221
222 public void onTaskAdded(ActivityManager.RunningTaskInfo taskInfo) {
223 notifyRunningTaskAppeared(taskInfo);
224 }
225
226 public void onTaskRemoved(ActivityManager.RunningTaskInfo taskInfo) {
227 // Remove any split pairs associated with this task
228 removeSplitPair(taskInfo.taskId);
229 notifyRecentTasksChanged();
230 notifyRunningTaskVanished(taskInfo);
231 }
232
233 public void onTaskWindowingModeChanged(TaskInfo taskInfo) {
234 notifyRecentTasksChanged();
235 }
236
237 @Override
238 public void onActiveTasksChanged() {
239 notifyRecentTasksChanged();
240 }
241
242 @VisibleForTesting
243 void notifyRecentTasksChanged() {
244 ProtoLog.v(ShellProtoLogGroup.WM_SHELL_RECENT_TASKS, "Notify recent tasks changed");
245 if (mListener == null) {
246 return;
247 }
248 try {
249 mListener.onRecentTasksChanged();
250 } catch (RemoteException e) {
251 Slog.w(TAG, "Failed call notifyRecentTasksChanged", e);
252 }
253 }
254
255 /**
256 * Notify the running task listener that a task appeared on desktop environment.
257 */
258 private void notifyRunningTaskAppeared(ActivityManager.RunningTaskInfo taskInfo) {
259 if (mListener == null || !mIsDesktopMode || taskInfo.realActivity == null) {
260 return;
261 }
262 try {
263 mListener.onRunningTaskAppeared(taskInfo);
264 } catch (RemoteException e) {
265 Slog.w(TAG, "Failed call onRunningTaskAppeared", e);
266 }
267 }
268
269 /**
270 * Notify the running task listener that a task was removed on desktop environment.
271 */
272 private void notifyRunningTaskVanished(ActivityManager.RunningTaskInfo taskInfo) {
273 if (mListener == null || !mIsDesktopMode || taskInfo.realActivity == null) {
274 return;
275 }
276 try {
277 mListener.onRunningTaskVanished(taskInfo);
278 } catch (RemoteException e) {
279 Slog.w(TAG, "Failed call onRunningTaskVanished", e);
280 }
281 }
282
283 @VisibleForTesting
284 void registerRecentTasksListener(IRecentTasksListener listener) {
285 mListener = listener;
286 }
287
288 @VisibleForTesting
289 void unregisterRecentTasksListener() {
290 mListener = null;
291 }
292
293 @VisibleForTesting
294 boolean hasRecentTasksListener() {
295 return mListener != null;
296 }
297
298 @VisibleForTesting
299 ArrayList<GroupedRecentTaskInfo> getRecentTasks(int maxNum, int flags, int userId) {
300 // Note: the returned task list is from the most-recent to least-recent order
301 final List<ActivityManager.RecentTaskInfo> rawList = mActivityTaskManager.getRecentTasks(
302 maxNum, flags, userId);
303
304 // Make a mapping of task id -> task info
305 final SparseArray<ActivityManager.RecentTaskInfo> rawMapping = new SparseArray<>();
306 for (int i = 0; i < rawList.size(); i++) {
307 final ActivityManager.RecentTaskInfo taskInfo = rawList.get(i);
308 rawMapping.put(taskInfo.taskId, taskInfo);
309 }
310
311 boolean desktopModeActive = DesktopModeStatus.isActive(mContext);
312 ArrayList<ActivityManager.RecentTaskInfo> freeformTasks = new ArrayList<>();
313
314 // Pull out the pairs as we iterate back in the list
315 ArrayList<GroupedRecentTaskInfo> recentTasks = new ArrayList<>();
316 for (int i = 0; i < rawList.size(); i++) {
317 final ActivityManager.RecentTaskInfo taskInfo = rawList.get(i);
318 if (!rawMapping.contains(taskInfo.taskId)) {
319 // If it's not in the mapping, then it was already paired with another task
320 continue;
321 }
322
323 if (desktopModeActive && mDesktopModeTaskRepository.isPresent()
324 && mDesktopModeTaskRepository.get().isActiveTask(taskInfo.taskId)) {
325 // Freeform tasks will be added as a separate entry
326 freeformTasks.add(taskInfo);
327 continue;
328 }
329
330 final int pairedTaskId = mSplitTasks.get(taskInfo.taskId);
331 if (!desktopModeActive && pairedTaskId != INVALID_TASK_ID && rawMapping.contains(
332 pairedTaskId)) {
333 final ActivityManager.RecentTaskInfo pairedTaskInfo = rawMapping.get(pairedTaskId);
334 rawMapping.remove(pairedTaskId);
335 recentTasks.add(GroupedRecentTaskInfo.forSplitTasks(taskInfo, pairedTaskInfo,
336 mTaskSplitBoundsMap.get(pairedTaskId)));
337 } else {
338 recentTasks.add(GroupedRecentTaskInfo.forSingleTask(taskInfo));
339 }
340 }
341
342 // Add a special entry for freeform tasks
343 if (!freeformTasks.isEmpty()) {
344 recentTasks.add(0, GroupedRecentTaskInfo.forFreeformTasks(
345 freeformTasks.toArray(new ActivityManager.RecentTaskInfo[0])));
346 }
347
348 return recentTasks;
349 }
350
351 /**
352 * Returns the top running leaf task.
353 */
354 @Nullable
355 public ActivityManager.RunningTaskInfo getTopRunningTask() {
356 List<ActivityManager.RunningTaskInfo> tasks = mActivityTaskManager.getTasks(1,
357 false /* filterOnlyVisibleRecents */);
358 return tasks.isEmpty() ? null : tasks.get(0);
359 }
360
361 /**
362 * Find the background task that match the given component.
363 */
364 @Nullable
365 public ActivityManager.RecentTaskInfo findTaskInBackground(ComponentName componentName) {
366 if (componentName == null) {
367 return null;
368 }
369 List<ActivityManager.RecentTaskInfo> tasks = mActivityTaskManager.getRecentTasks(
370 Integer.MAX_VALUE, ActivityManager.RECENT_IGNORE_UNAVAILABLE,
371 ActivityManager.getCurrentUser());
372 for (int i = 0; i < tasks.size(); i++) {
373 final ActivityManager.RecentTaskInfo task = tasks.get(i);
374 if (task.isVisible) {
375 continue;
376 }
377 if (componentName.equals(task.baseIntent.getComponent())) {
378 return task;
379 }
380 }
381 return null;
382 }
383
384 public void dump(@NonNull PrintWriter pw, String prefix) {
385 final String innerPrefix = prefix + " ";
386 pw.println(prefix + TAG);
387 pw.println(prefix + " mListener=" + mListener);
388 pw.println(prefix + "Tasks:");
389 ArrayList<GroupedRecentTaskInfo> recentTasks = getRecentTasks(Integer.MAX_VALUE,
390 ActivityManager.RECENT_IGNORE_UNAVAILABLE, ActivityManager.getCurrentUser());
391 for (int i = 0; i < recentTasks.size(); i++) {
392 pw.println(innerPrefix + recentTasks.get(i));
393 }
394 }
395
396 /**
397 * The interface for calls from outside the Shell, within the host process.
398 */
399 @ExternalThread
400 private class RecentTasksImpl implements RecentTasks {
401 @Override
402 public void getRecentTasks(int maxNum, int flags, int userId, Executor executor,
403 Consumer<List<GroupedRecentTaskInfo>> callback) {
404 mMainExecutor.execute(() -> {
405 List<GroupedRecentTaskInfo> tasks =
406 RecentTasksController.this.getRecentTasks(maxNum, flags, userId);
407 executor.execute(() -> callback.accept(tasks));
408 });
409 }
410 }
411
412
413 /**
414 * The interface for calls from outside the host process.
415 */
416 @BinderThread
417 private static class IRecentTasksImpl extends IRecentTasks.Stub
418 implements ExternalInterfaceBinder {
419 private RecentTasksController mController;
420 private final SingleInstanceRemoteListener<RecentTasksController,
421 IRecentTasksListener> mListener;
422 private final IRecentTasksListener mRecentTasksListener = new IRecentTasksListener.Stub() {
423 @Override
424 public void onRecentTasksChanged() throws RemoteException {
425 mListener.call(l -> l.onRecentTasksChanged());
426 }
427
428 @Override
429 public void onRunningTaskAppeared(ActivityManager.RunningTaskInfo taskInfo) {
430 mListener.call(l -> l.onRunningTaskAppeared(taskInfo));
431 }
432
433 @Override
434 public void onRunningTaskVanished(ActivityManager.RunningTaskInfo taskInfo) {
435 mListener.call(l -> l.onRunningTaskVanished(taskInfo));
436 }
437 };
438
439 public IRecentTasksImpl(RecentTasksController controller) {
440 mController = controller;
441 mListener = new SingleInstanceRemoteListener<>(controller,
442 c -> c.registerRecentTasksListener(mRecentTasksListener),
443 c -> c.unregisterRecentTasksListener());
444 }
445
446 /**
447 * Invalidates this instance, preventing future calls from updating the controller.
448 */
449 @Override
450 public void invalidate() {
451 mController = null;
452 // Unregister the listener to ensure any registered binder death recipients are unlinked
453 mListener.unregister();
454 }
455
456 @Override
457 public void registerRecentTasksListener(IRecentTasksListener listener)
458 throws RemoteException {
459 executeRemoteCallWithTaskPermission(mController, "registerRecentTasksListener",
460 (controller) -> mListener.register(listener));
461 }
462
463 @Override
464 public void unregisterRecentTasksListener(IRecentTasksListener listener)
465 throws RemoteException {
466 executeRemoteCallWithTaskPermission(mController, "unregisterRecentTasksListener",
467 (controller) -> mListener.unregister());
468 }
469
470 @Override
471 public GroupedRecentTaskInfo[] getRecentTasks(int maxNum, int flags, int userId)
472 throws RemoteException {
473 if (mController == null) {
474 // The controller is already invalidated -- just return an empty task list for now
475 return new GroupedRecentTaskInfo[0];
476 }
477
478 final GroupedRecentTaskInfo[][] out = new GroupedRecentTaskInfo[][]{null};
479 executeRemoteCallWithTaskPermission(mController, "getRecentTasks",
480 (controller) -> out[0] = controller.getRecentTasks(maxNum, flags, userId)
481 .toArray(new GroupedRecentTaskInfo[0]),
482 true /* blocking */);
483 return out[0];
484 }
485
486 @Override
487 public ActivityManager.RunningTaskInfo[] getRunningTasks(int maxNum) {
488 final ActivityManager.RunningTaskInfo[][] tasks =
489 new ActivityManager.RunningTaskInfo[][] {null};
490 executeRemoteCallWithTaskPermission(mController, "getRunningTasks",
491 (controller) -> tasks[0] = ActivityTaskManager.getInstance().getTasks(maxNum)
492 .toArray(new ActivityManager.RunningTaskInfo[0]),
493 true /* blocking */);
494 return tasks[0];
495 }
496 }
497 }