blob: 3f0674d999395dba89882e3367738909c48eb7a9 [file] [log] [blame]
Wale Ogunwalec82f2f52014-12-09 09:32:50 -08001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
17package com.android.server.am;
18
Suprabh Shukla09a88f52015-12-02 14:36:31 -080019import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_RECENTS;
20import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_TASKS;
21import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_RECENTS;
22import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_TASKS;
23import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
24import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
Wale Ogunwalee23149f2015-03-06 15:39:44 -080025import static com.android.server.am.TaskRecord.INVALID_TASK_ID;
26
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080027import android.app.ActivityManager;
28import android.app.AppGlobals;
29import android.content.ComponentName;
30import android.content.Intent;
31import android.content.pm.ActivityInfo;
32import android.content.pm.ApplicationInfo;
33import android.content.pm.IPackageManager;
34import android.content.pm.PackageManager;
Suprabh Shukla09a88f52015-12-02 14:36:31 -080035import android.graphics.Bitmap;
36import android.os.Environment;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080037import android.os.RemoteException;
38import android.os.UserHandle;
39import android.util.Slog;
Suprabh Shukla09a88f52015-12-02 14:36:31 -080040import android.util.SparseBooleanArray;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080041
Suprabh Shukla09a88f52015-12-02 14:36:31 -080042import java.io.File;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080043import java.util.ArrayList;
Suprabh Shukla09a88f52015-12-02 14:36:31 -080044import java.util.Arrays;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080045import java.util.Collections;
46import java.util.Comparator;
47import java.util.HashMap;
48
49/**
50 * Class for managing the recent tasks list.
51 */
52class RecentTasks extends ArrayList<TaskRecord> {
Wale Ogunwalee23149f2015-03-06 15:39:44 -080053 private static final String TAG = TAG_WITH_CLASS_NAME ? "RecentTasks" : TAG_AM;
Wale Ogunwaleee006da2015-03-30 14:49:25 -070054 private static final String TAG_RECENTS = TAG + POSTFIX_RECENTS;
55 private static final String TAG_TASKS = TAG + POSTFIX_TASKS;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080056
57 // Maximum number recent bitmaps to keep in memory.
58 private static final int MAX_RECENT_BITMAPS = 3;
59
Suprabh Shukla09a88f52015-12-02 14:36:31 -080060 /**
61 * Save recent tasks information across reboots.
62 */
63 private final TaskPersister mTaskPersister;
64 private final SparseBooleanArray mUsersWithRecentsLoaded = new SparseBooleanArray(5);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080065
66 // Mainly to avoid object recreation on multiple calls.
67 private final ArrayList<TaskRecord> mTmpRecents = new ArrayList<TaskRecord>();
Suprabh Shukla09a88f52015-12-02 14:36:31 -080068 private final HashMap<ComponentName, ActivityInfo> mTmpAvailActCache = new HashMap<>();
69 private final HashMap<String, ApplicationInfo> mTmpAvailAppCache = new HashMap<>();
70 private final ActivityInfo mTmpActivityInfo = new ActivityInfo();
71 private final ApplicationInfo mTmpAppInfo = new ApplicationInfo();
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080072
Suprabh Shukla09a88f52015-12-02 14:36:31 -080073 RecentTasks(ActivityManagerService service, ActivityStackSupervisor mStackSupervisor) {
74 File systemDir = Environment.getDataSystemDirectory();
75 mTaskPersister = new TaskPersister(systemDir, mStackSupervisor, service, this);
76 mStackSupervisor.setRecentTasks(this);
77 }
78
79 /**
Suprabh Shuklaf5bf0cb2016-01-19 17:42:03 -080080 * Loads the persistent recentTasks for {@code userId} into this list from persistent storage.
81 * Does nothing if they are already loaded.
Suprabh Shukla09a88f52015-12-02 14:36:31 -080082 *
83 * @param userId the user Id
84 */
85 void loadUserRecentsLocked(int userId) {
86 if (!mUsersWithRecentsLoaded.get(userId)) {
87 Slog.i(TAG, "Loading recents for user " + userId + " into memory.");
88 addAll(mTaskPersister.restoreTasksForUserLocked(userId));
89 cleanupLocked(userId);
90 mUsersWithRecentsLoaded.put(userId, true);
91 }
92 }
93
94 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
95 if (task != null && task.stack != null && task.stack.isHomeStack()) {
96 // Never persist the home stack.
97 return;
98 }
99 mTaskPersister.wakeup(task, flush);
100 }
101
102 void onSystemReady() {
103 clear();
104 loadUserRecentsLocked(UserHandle.USER_SYSTEM);
105 startPersisting();
106 }
107
108 void startPersisting() {
109 mTaskPersister.startPersisting();
110 }
111
112 Bitmap getTaskDescriptionIcon(String path) {
113 return mTaskPersister.getTaskDescriptionIcon(path);
114 }
115
116 Bitmap getImageFromWriteQueue(String path) {
117 return mTaskPersister.getImageFromWriteQueue(path);
118 }
119
120 void saveImage(Bitmap image, String path) {
121 mTaskPersister.saveImage(image, path);
122 }
123
124 void flush() {
125 mTaskPersister.flush();
126 }
127
128 /**
129 * Returns all userIds for which recents from storage are loaded
130 *
131 * @return an array of userIds.
132 */
133 int[] usersWithRecentsLoadedLocked() {
134 int[] usersWithRecentsLoaded = new int[mUsersWithRecentsLoaded.size()];
135 int len = 0;
136 for (int i = 0; i < usersWithRecentsLoaded.length; i++) {
137 int userId = mUsersWithRecentsLoaded.keyAt(i);
138 if (mUsersWithRecentsLoaded.valueAt(i)) {
139 usersWithRecentsLoaded[len++] = userId;
140 }
141 }
142 if (len < usersWithRecentsLoaded.length) {
143 // should never happen.
144 return Arrays.copyOf(usersWithRecentsLoaded, len);
145 }
146 return usersWithRecentsLoaded;
147 }
148
149 /**
150 * Removes recent tasks for this user if they are loaded, does not do anything otherwise.
151 *
152 * @param userId the user id.
153 */
154 void unloadUserRecentsLocked(int userId) {
155 if (mUsersWithRecentsLoaded.get(userId)) {
156 Slog.i(TAG, "Unloading recents for user " + userId + " from memory.");
157 mUsersWithRecentsLoaded.delete(userId);
158 removeTasksForUserLocked(userId);
159 }
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800160 }
161
162 TaskRecord taskForIdLocked(int id) {
163 final int recentsCount = size();
164 for (int i = 0; i < recentsCount; i++) {
165 TaskRecord tr = get(i);
166 if (tr.taskId == id) {
167 return tr;
168 }
169 }
170 return null;
171 }
172
173 /** Remove recent tasks for a user. */
174 void removeTasksForUserLocked(int userId) {
175 if(userId <= 0) {
176 Slog.i(TAG, "Can't remove recent task on user " + userId);
177 return;
178 }
179
180 for (int i = size() - 1; i >= 0; --i) {
181 TaskRecord tr = get(i);
182 if (tr.userId == userId) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700183 if(DEBUG_TASKS) Slog.i(TAG_TASKS,
184 "remove RecentTask " + tr + " when finishing user" + userId);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800185 remove(i);
186 tr.removedFromRecents();
187 }
188 }
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800189 }
190
191 /**
192 * Update the recent tasks lists: make sure tasks should still be here (their
193 * applications / activities still exist), update their availability, fix-up ordering
194 * of affiliations.
195 */
196 void cleanupLocked(int userId) {
197 int recentsCount = size();
198 if (recentsCount == 0) {
199 // Happens when called from the packagemanager broadcast before boot,
200 // or just any empty list.
201 return;
202 }
203
204 final IPackageManager pm = AppGlobals.getPackageManager();
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800205 for (int i = recentsCount - 1; i >= 0; i--) {
206 final TaskRecord task = get(i);
207 if (userId != UserHandle.USER_ALL && task.userId != userId) {
208 // Only look at tasks for the user ID of interest.
209 continue;
210 }
211 if (task.autoRemoveRecents && task.getTopActivity() == null) {
212 // This situation is broken, and we should just get rid of it now.
213 remove(i);
214 task.removedFromRecents();
215 Slog.w(TAG, "Removing auto-remove without activity: " + task);
216 continue;
217 }
218 // Check whether this activity is currently available.
219 if (task.realActivity != null) {
220 ActivityInfo ai = mTmpAvailActCache.get(task.realActivity);
221 if (ai == null) {
222 try {
223 // At this first cut, we're only interested in
224 // activities that are fully runnable based on
225 // current system state.
226 ai = pm.getActivityInfo(task.realActivity,
227 PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
228 } catch (RemoteException e) {
229 // Will never happen.
230 continue;
231 }
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800232 if (ai == null) {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800233 ai = mTmpActivityInfo;
234 }
235 mTmpAvailActCache.put(task.realActivity, ai);
236 }
237 if (ai == mTmpActivityInfo) {
238 // This could be either because the activity no longer exists, or the
239 // app is temporarily gone. For the former we want to remove the recents
240 // entry; for the latter we want to mark it as unavailable.
241 ApplicationInfo app = mTmpAvailAppCache
242 .get(task.realActivity.getPackageName());
243 if (app == null) {
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800244 try {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800245 app = pm.getApplicationInfo(task.realActivity.getPackageName(),
246 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800247 } catch (RemoteException e) {
248 // Will never happen.
249 continue;
250 }
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800251 if (app == null) {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800252 app = mTmpAppInfo;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800253 }
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800254 mTmpAvailAppCache.put(task.realActivity.getPackageName(), app);
255 }
256 if (app == mTmpAppInfo
257 || (app.flags & ApplicationInfo.FLAG_INSTALLED) == 0) {
258 // Doesn't exist any more! Good-bye.
259 remove(i);
260 task.removedFromRecents();
261 Slog.w(TAG, "Removing no longer valid recent: " + task);
262 continue;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800263 } else {
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800264 // Otherwise just not available for now.
265 if (DEBUG_RECENTS && task.isAvailable) Slog.d(TAG_RECENTS,
266 "Making recent unavailable: " + task);
267 task.isAvailable = false;
268 }
269 } else {
270 if (!ai.enabled || !ai.applicationInfo.enabled
271 || (ai.applicationInfo.flags
272 & ApplicationInfo.FLAG_INSTALLED) == 0) {
273 if (DEBUG_RECENTS && task.isAvailable) Slog.d(TAG_RECENTS,
274 "Making recent unavailable: " + task
275 + " (enabled=" + ai.enabled + "/"
276 + ai.applicationInfo.enabled
277 + " flags="
278 + Integer.toHexString(ai.applicationInfo.flags)
279 + ")");
280 task.isAvailable = false;
281 } else {
282 if (DEBUG_RECENTS && !task.isAvailable) Slog.d(TAG_RECENTS,
283 "Making recent available: " + task);
284 task.isAvailable = true;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800285 }
286 }
287 }
288 }
289
290 // Verify the affiliate chain for each task.
291 int i = 0;
292 recentsCount = size();
293 while (i < recentsCount) {
294 i = processNextAffiliateChainLocked(i);
295 }
296 // recent tasks are now in sorted, affiliated order.
297 }
298
299 private final boolean moveAffiliatedTasksToFront(TaskRecord task, int taskIndex) {
300 int recentsCount = size();
301 TaskRecord top = task;
302 int topIndex = taskIndex;
303 while (top.mNextAffiliate != null && topIndex > 0) {
304 top = top.mNextAffiliate;
305 topIndex--;
306 }
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700307 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: adding affilliates starting at "
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800308 + topIndex + " from intial " + taskIndex);
309 // Find the end of the chain, doing a sanity check along the way.
310 boolean sane = top.mAffiliatedTaskId == task.mAffiliatedTaskId;
311 int endIndex = topIndex;
312 TaskRecord prev = top;
313 while (endIndex < recentsCount) {
314 TaskRecord cur = get(endIndex);
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700315 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: looking at next chain @"
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800316 + endIndex + " " + cur);
317 if (cur == top) {
318 // Verify start of the chain.
319 if (cur.mNextAffiliate != null || cur.mNextAffiliateTaskId != INVALID_TASK_ID) {
320 Slog.wtf(TAG, "Bad chain @" + endIndex
321 + ": first task has next affiliate: " + prev);
322 sane = false;
323 break;
324 }
325 } else {
326 // Verify middle of the chain's next points back to the one before.
327 if (cur.mNextAffiliate != prev
328 || cur.mNextAffiliateTaskId != prev.taskId) {
329 Slog.wtf(TAG, "Bad chain @" + endIndex
330 + ": middle task " + cur + " @" + endIndex
331 + " has bad next affiliate "
332 + cur.mNextAffiliate + " id " + cur.mNextAffiliateTaskId
333 + ", expected " + prev);
334 sane = false;
335 break;
336 }
337 }
338 if (cur.mPrevAffiliateTaskId == INVALID_TASK_ID) {
339 // Chain ends here.
340 if (cur.mPrevAffiliate != null) {
341 Slog.wtf(TAG, "Bad chain @" + endIndex
342 + ": last task " + cur + " has previous affiliate "
343 + cur.mPrevAffiliate);
344 sane = false;
345 }
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700346 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: end of chain @" + endIndex);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800347 break;
348 } else {
349 // Verify middle of the chain's prev points to a valid item.
350 if (cur.mPrevAffiliate == null) {
351 Slog.wtf(TAG, "Bad chain @" + endIndex
352 + ": task " + cur + " has previous affiliate "
353 + cur.mPrevAffiliate + " but should be id "
354 + cur.mPrevAffiliate);
355 sane = false;
356 break;
357 }
358 }
359 if (cur.mAffiliatedTaskId != task.mAffiliatedTaskId) {
360 Slog.wtf(TAG, "Bad chain @" + endIndex
361 + ": task " + cur + " has affiliated id "
362 + cur.mAffiliatedTaskId + " but should be "
363 + task.mAffiliatedTaskId);
364 sane = false;
365 break;
366 }
367 prev = cur;
368 endIndex++;
369 if (endIndex >= recentsCount) {
370 Slog.wtf(TAG, "Bad chain ran off index " + endIndex
371 + ": last task " + prev);
372 sane = false;
373 break;
374 }
375 }
376 if (sane) {
377 if (endIndex < taskIndex) {
378 Slog.wtf(TAG, "Bad chain @" + endIndex
379 + ": did not extend to task " + task + " @" + taskIndex);
380 sane = false;
381 }
382 }
383 if (sane) {
384 // All looks good, we can just move all of the affiliated tasks
385 // to the top.
386 for (int i=topIndex; i<=endIndex; i++) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700387 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: moving affiliated " + task
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800388 + " from " + i + " to " + (i-topIndex));
389 TaskRecord cur = remove(i);
390 add(i - topIndex, cur);
391 }
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700392 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: done moving tasks " + topIndex
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800393 + " to " + endIndex);
394 return true;
395 }
396
397 // Whoops, couldn't do it.
398 return false;
399 }
400
401 final void addLocked(TaskRecord task) {
402 final boolean isAffiliated = task.mAffiliatedTaskId != task.taskId
403 || task.mNextAffiliateTaskId != INVALID_TASK_ID
404 || task.mPrevAffiliateTaskId != INVALID_TASK_ID;
405
406 int recentsCount = size();
407 // Quick case: never add voice sessions.
Amith Yamasani0af6fa72016-01-17 15:36:19 -0800408 // TODO: VI what about if it's just an activity?
409 // Probably nothing to do here
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800410 if (task.voiceSession != null) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700411 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS,
412 "addRecent: not adding voice interaction " + task);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800413 return;
414 }
415 // Another quick case: check if the top-most recent task is the same.
416 if (!isAffiliated && recentsCount > 0 && get(0) == task) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700417 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: already at top: " + task);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800418 return;
419 }
420 // Another quick case: check if this is part of a set of affiliated
421 // tasks that are at the top.
422 if (isAffiliated && recentsCount > 0 && task.inRecents
423 && task.mAffiliatedTaskId == get(0).mAffiliatedTaskId) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700424 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: affiliated " + get(0)
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800425 + " at top when adding " + task);
426 return;
427 }
428
429 boolean needAffiliationFix = false;
430
431 // Slightly less quick case: the task is already in recents, so all we need
432 // to do is move it.
433 if (task.inRecents) {
434 int taskIndex = indexOf(task);
435 if (taskIndex >= 0) {
436 if (!isAffiliated) {
437 // Simple case: this is not an affiliated task, so we just move it to the front.
438 remove(taskIndex);
439 add(0, task);
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800440 notifyTaskPersisterLocked(task, false);
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700441 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: moving to top " + task
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800442 + " from " + taskIndex);
443 return;
444 } else {
445 // More complicated: need to keep all affiliated tasks together.
446 if (moveAffiliatedTasksToFront(task, taskIndex)) {
447 // All went well.
448 return;
449 }
450
451 // Uh oh... something bad in the affiliation chain, try to rebuild
452 // everything and then go through our general path of adding a new task.
453 needAffiliationFix = true;
454 }
455 } else {
456 Slog.wtf(TAG, "Task with inRecent not in recents: " + task);
457 needAffiliationFix = true;
458 }
459 }
460
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700461 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: trimming tasks for " + task);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800462 trimForTaskLocked(task, true);
463
464 recentsCount = size();
465 final int maxRecents = ActivityManager.getMaxRecentTasksStatic();
466 while (recentsCount >= maxRecents) {
467 final TaskRecord tr = remove(recentsCount - 1);
468 tr.removedFromRecents();
469 recentsCount--;
470 }
471 task.inRecents = true;
472 if (!isAffiliated || needAffiliationFix) {
473 // If this is a simple non-affiliated task, or we had some failure trying to
474 // handle it as part of an affilated task, then just place it at the top.
475 add(0, task);
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700476 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: adding " + task);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800477 } else if (isAffiliated) {
478 // If this is a new affiliated task, then move all of the affiliated tasks
479 // to the front and insert this new one.
480 TaskRecord other = task.mNextAffiliate;
481 if (other == null) {
482 other = task.mPrevAffiliate;
483 }
484 if (other != null) {
485 int otherIndex = indexOf(other);
486 if (otherIndex >= 0) {
487 // Insert new task at appropriate location.
488 int taskIndex;
489 if (other == task.mNextAffiliate) {
490 // We found the index of our next affiliation, which is who is
491 // before us in the list, so add after that point.
492 taskIndex = otherIndex+1;
493 } else {
494 // We found the index of our previous affiliation, which is who is
495 // after us in the list, so add at their position.
496 taskIndex = otherIndex;
497 }
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700498 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS,
499 "addRecent: new affiliated task added at " + taskIndex + ": " + task);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800500 add(taskIndex, task);
501
502 // Now move everything to the front.
503 if (moveAffiliatedTasksToFront(task, taskIndex)) {
504 // All went well.
505 return;
506 }
507
508 // Uh oh... something bad in the affiliation chain, try to rebuild
509 // everything and then go through our general path of adding a new task.
510 needAffiliationFix = true;
511 } else {
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700512 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS,
513 "addRecent: couldn't find other affiliation " + other);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800514 needAffiliationFix = true;
515 }
516 } else {
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700517 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS,
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800518 "addRecent: adding affiliated task without next/prev:" + task);
519 needAffiliationFix = true;
520 }
521 }
522
523 if (needAffiliationFix) {
Wale Ogunwaleee006da2015-03-30 14:49:25 -0700524 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "addRecent: regrouping affiliations");
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800525 cleanupLocked(task.userId);
526 }
527 }
528
529 /**
530 * If needed, remove oldest existing entries in recents that are for the same kind
531 * of task as the given one.
532 */
533 int trimForTaskLocked(TaskRecord task, boolean doTrim) {
534 int recentsCount = size();
Wale Ogunwale2ab53cf2015-08-01 17:19:21 -0700535 final Intent intent = task.intent;
536 final boolean document = intent != null && intent.isDocument();
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800537 int maxRecents = task.maxRecents - 1;
538 for (int i = 0; i < recentsCount; i++) {
539 final TaskRecord tr = get(i);
540 if (task != tr) {
541 if (task.userId != tr.userId) {
542 continue;
543 }
544 if (i > MAX_RECENT_BITMAPS) {
545 tr.freeLastThumbnail();
546 }
Wale Ogunwale2ab53cf2015-08-01 17:19:21 -0700547 final Intent trIntent = tr.intent;
Wale Ogunwale7cbfcd82015-07-20 15:43:37 -0700548 final boolean sameAffinity =
549 task.affinity != null && task.affinity.equals(tr.affinity);
Wale Ogunwale2ab53cf2015-08-01 17:19:21 -0700550 final boolean sameIntent = (intent != null && intent.filterEquals(trIntent));
551 final boolean trIsDocument = trIntent != null && trIntent.isDocument();
Wale Ogunwale7cbfcd82015-07-20 15:43:37 -0700552 final boolean bothDocuments = document && trIsDocument;
Wale Ogunwale2ab53cf2015-08-01 17:19:21 -0700553 if (!sameAffinity && !sameIntent && !bothDocuments) {
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800554 continue;
555 }
Wale Ogunwale7cbfcd82015-07-20 15:43:37 -0700556
557 if (bothDocuments) {
558 // Do these documents belong to the same activity?
559 final boolean sameActivity = task.realActivity != null
560 && tr.realActivity != null
561 && task.realActivity.equals(tr.realActivity);
Robert Carr7cb57e12015-11-10 13:44:02 -0800562 // If the document is open in another app or is not the same
563 // document, we don't need to trim it.
564 if (!sameActivity || !sameIntent) {
Wale Ogunwale7cbfcd82015-07-20 15:43:37 -0700565 continue;
Robert Carr7cb57e12015-11-10 13:44:02 -0800566 // Otherwise only trim if we are over our max recents for this task
567 } else if (maxRecents > 0 && !doTrim) {
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800568 --maxRecents;
569 continue;
570 }
571 // Hit the maximum number of documents for this task. Fall through
572 // and remove this document from recents.
573 } else if (document || trIsDocument) {
574 // Only one of these is a document. Not the droid we're looking for.
575 continue;
576 }
577 }
578
579 if (!doTrim) {
580 // If the caller is not actually asking for a trim, just tell them we reached
581 // a point where the trim would happen.
582 return i;
583 }
584
585 // Either task and tr are the same or, their affinities match or their intents match
586 // and neither of them is a document, or they are documents using the same activity
587 // and their maxRecents has been reached.
588 tr.disposeThumbnail();
589 remove(i);
590 if (task != tr) {
591 tr.removedFromRecents();
592 }
593 i--;
594 recentsCount--;
595 if (task.intent == null) {
596 // If the new recent task we are adding is not fully
597 // specified, then replace it with the existing recent task.
598 task = tr;
599 }
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800600 notifyTaskPersisterLocked(tr, false);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800601 }
602
603 return -1;
604 }
605
606 // Sort by taskId
607 private static Comparator<TaskRecord> sTaskRecordComparator = new Comparator<TaskRecord>() {
608 @Override
609 public int compare(TaskRecord lhs, TaskRecord rhs) {
610 return rhs.taskId - lhs.taskId;
611 }
612 };
613
614 // Extract the affiliates of the chain containing recent at index start.
615 private int processNextAffiliateChainLocked(int start) {
616 final TaskRecord startTask = get(start);
617 final int affiliateId = startTask.mAffiliatedTaskId;
618
619 // Quick identification of isolated tasks. I.e. those not launched behind.
620 if (startTask.taskId == affiliateId && startTask.mPrevAffiliate == null &&
621 startTask.mNextAffiliate == null) {
622 // There is still a slim chance that there are other tasks that point to this task
623 // and that the chain is so messed up that this task no longer points to them but
624 // the gain of this optimization outweighs the risk.
625 startTask.inRecents = true;
626 return start + 1;
627 }
628
629 // Remove all tasks that are affiliated to affiliateId and put them in mTmpRecents.
630 mTmpRecents.clear();
631 for (int i = size() - 1; i >= start; --i) {
632 final TaskRecord task = get(i);
633 if (task.mAffiliatedTaskId == affiliateId) {
634 remove(i);
635 mTmpRecents.add(task);
636 }
637 }
638
639 // Sort them all by taskId. That is the order they were create in and that order will
640 // always be correct.
641 Collections.sort(mTmpRecents, sTaskRecordComparator);
642
643 // Go through and fix up the linked list.
644 // The first one is the end of the chain and has no next.
645 final TaskRecord first = mTmpRecents.get(0);
646 first.inRecents = true;
647 if (first.mNextAffiliate != null) {
648 Slog.w(TAG, "Link error 1 first.next=" + first.mNextAffiliate);
649 first.setNextAffiliate(null);
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800650 notifyTaskPersisterLocked(first, false);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800651 }
652 // Everything in the middle is doubly linked from next to prev.
653 final int tmpSize = mTmpRecents.size();
654 for (int i = 0; i < tmpSize - 1; ++i) {
655 final TaskRecord next = mTmpRecents.get(i);
656 final TaskRecord prev = mTmpRecents.get(i + 1);
657 if (next.mPrevAffiliate != prev) {
658 Slog.w(TAG, "Link error 2 next=" + next + " prev=" + next.mPrevAffiliate +
659 " setting prev=" + prev);
660 next.setPrevAffiliate(prev);
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800661 notifyTaskPersisterLocked(next, false);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800662 }
663 if (prev.mNextAffiliate != next) {
664 Slog.w(TAG, "Link error 3 prev=" + prev + " next=" + prev.mNextAffiliate +
665 " setting next=" + next);
666 prev.setNextAffiliate(next);
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800667 notifyTaskPersisterLocked(prev, false);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800668 }
669 prev.inRecents = true;
670 }
671 // The last one is the beginning of the list and has no prev.
672 final TaskRecord last = mTmpRecents.get(tmpSize - 1);
673 if (last.mPrevAffiliate != null) {
674 Slog.w(TAG, "Link error 4 last.prev=" + last.mPrevAffiliate);
675 last.setPrevAffiliate(null);
Suprabh Shukla09a88f52015-12-02 14:36:31 -0800676 notifyTaskPersisterLocked(last, false);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800677 }
678
679 // Insert the group back into mRecentTasks at start.
680 addAll(start, mTmpRecents);
681 mTmpRecents.clear();
682
683 // Let the caller know where we left off.
684 return start + tmpSize;
685 }
686
687}