blob: 9a0007555eb5f51ac9900c8a9c26e65cf3a7beec [file] [log] [blame]
Craig Mautner21d24a22014-04-23 11:45:37 -07001/*
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
19import android.graphics.Bitmap;
20import android.graphics.BitmapFactory;
21import android.os.Debug;
Suprabh Shukla23593142015-11-03 17:31:15 -080022import android.os.Environment;
23import android.os.FileUtils;
Craig Mautner21d24a22014-04-23 11:45:37 -070024import android.os.SystemClock;
25import android.util.ArraySet;
26import android.util.AtomicFile;
27import android.util.Slog;
28import android.util.Xml;
Riley Andrewsf16c2e82015-06-02 18:24:48 -070029import android.os.Process;
Wale Ogunwale18795a22014-12-03 11:38:33 -080030
Craig Mautner21d24a22014-04-23 11:45:37 -070031import com.android.internal.util.FastXmlSerializer;
32import com.android.internal.util.XmlUtils;
Wale Ogunwale18795a22014-12-03 11:38:33 -080033
Craig Mautner21d24a22014-04-23 11:45:37 -070034import org.xmlpull.v1.XmlPullParser;
35import org.xmlpull.v1.XmlPullParserException;
36import org.xmlpull.v1.XmlSerializer;
37
38import java.io.BufferedReader;
39import java.io.File;
40import java.io.FileOutputStream;
41import java.io.FileReader;
42import java.io.IOException;
43import java.io.StringWriter;
44import java.util.ArrayList;
45import java.util.Arrays;
46import java.util.Comparator;
Suprabh Shukla23593142015-11-03 17:31:15 -080047import java.util.List;
Wale Ogunwale18795a22014-12-03 11:38:33 -080048
49import libcore.io.IoUtils;
50
Craig Mautner21d24a22014-04-23 11:45:37 -070051public class TaskPersister {
52 static final String TAG = "TaskPersister";
Stefan Kuhnee88d1e52015-05-18 10:33:45 -070053 static final boolean DEBUG = false;
Craig Mautner21d24a22014-04-23 11:45:37 -070054
Craig Mautnerf4f8bb72014-07-29 10:41:40 -070055 /** When not flushing don't write out files faster than this */
56 private static final long INTER_WRITE_DELAY_MS = 500;
57
Suprabh Shukla23593142015-11-03 17:31:15 -080058 /**
59 * When not flushing delay this long before writing the first file out. This gives the next task
60 * being launched a chance to load its resources without this occupying IO bandwidth.
61 */
Craig Mautnerf4f8bb72014-07-29 10:41:40 -070062 private static final long PRE_TASK_DELAY_MS = 3000;
Craig Mautner21d24a22014-04-23 11:45:37 -070063
Craig Mautner63f10902014-09-16 23:57:21 -070064 /** The maximum number of entries to keep in the queue before draining it automatically. */
65 private static final int MAX_WRITE_QUEUE_LENGTH = 6;
66
67 /** Special value for mWriteTime to mean don't wait, just write */
68 private static final long FLUSH_QUEUE = -1;
69
Craig Mautner21d24a22014-04-23 11:45:37 -070070 private static final String RECENTS_FILENAME = "_task";
71 private static final String TASKS_DIRNAME = "recent_tasks";
72 private static final String TASK_EXTENSION = ".xml";
73 private static final String IMAGES_DIRNAME = "recent_images";
Craig Mautnerc0ffce52014-07-01 12:38:52 -070074 static final String IMAGE_EXTENSION = ".png";
Craig Mautner21d24a22014-04-23 11:45:37 -070075
76 private static final String TAG_TASK = "task";
77
Craig Mautner21d24a22014-04-23 11:45:37 -070078 private final ActivityManagerService mService;
79 private final ActivityStackSupervisor mStackSupervisor;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -080080 private final RecentTasks mRecentTasks;
Craig Mautner21d24a22014-04-23 11:45:37 -070081
Suprabh Shukla23593142015-11-03 17:31:15 -080082 /**
83 * Value determines write delay mode as follows: < 0 We are Flushing. No delays between writes
84 * until the image queue is drained and all tasks needing persisting are written to disk. There
85 * is no delay between writes. == 0 We are Idle. Next writes will be delayed by
86 * #PRE_TASK_DELAY_MS. > 0 We are Actively writing. Next write will be at this time. Subsequent
87 * writes will be delayed by #INTER_WRITE_DELAY_MS.
88 */
Craig Mautnerf4f8bb72014-07-29 10:41:40 -070089 private long mNextWriteTime = 0;
Craig Mautner21d24a22014-04-23 11:45:37 -070090
91 private final LazyTaskWriterThread mLazyTaskWriterThread;
92
Craig Mautnerf4f8bb72014-07-29 10:41:40 -070093 private static class WriteQueueItem {}
Suprabh Shukla23593142015-11-03 17:31:15 -080094
Craig Mautnerf4f8bb72014-07-29 10:41:40 -070095 private static class TaskWriteQueueItem extends WriteQueueItem {
96 final TaskRecord mTask;
Winsonc809cbb2015-11-02 12:06:15 -080097
Craig Mautnerf4f8bb72014-07-29 10:41:40 -070098 TaskWriteQueueItem(TaskRecord task) {
99 mTask = task;
100 }
101 }
Suprabh Shukla23593142015-11-03 17:31:15 -0800102
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700103 private static class ImageWriteQueueItem extends WriteQueueItem {
Suprabh Shukla23593142015-11-03 17:31:15 -0800104 final String mFilePath;
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700105 Bitmap mImage;
Winsonc809cbb2015-11-02 12:06:15 -0800106
Suprabh Shukla23593142015-11-03 17:31:15 -0800107 ImageWriteQueueItem(String filePath, Bitmap image) {
108 mFilePath = filePath;
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700109 mImage = image;
110 }
111 }
112
113 ArrayList<WriteQueueItem> mWriteQueue = new ArrayList<WriteQueueItem>();
114
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800115 TaskPersister(File systemDir, ActivityStackSupervisor stackSupervisor,
116 RecentTasks recentTasks) {
Suprabh Shukla23593142015-11-03 17:31:15 -0800117
118 final File legacyImagesDir = new File(systemDir, IMAGES_DIRNAME);
119 if (legacyImagesDir.exists()) {
120 if (!FileUtils.deleteContents(legacyImagesDir) || !legacyImagesDir.delete()) {
121 Slog.i(TAG, "Failure deleting legacy images directory: " + legacyImagesDir);
Craig Mautner21d24a22014-04-23 11:45:37 -0700122 }
123 }
124
Suprabh Shukla23593142015-11-03 17:31:15 -0800125 final File legacyTasksDir = new File(systemDir, TASKS_DIRNAME);
126 if (legacyTasksDir.exists()) {
127 if (!FileUtils.deleteContents(legacyTasksDir) || !legacyTasksDir.delete()) {
128 Slog.i(TAG, "Failure deleting legacy tasks directory: " + legacyTasksDir);
Craig Mautner21d24a22014-04-23 11:45:37 -0700129 }
130 }
131
132 mStackSupervisor = stackSupervisor;
133 mService = stackSupervisor.mService;
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800134 mRecentTasks = recentTasks;
Craig Mautner21d24a22014-04-23 11:45:37 -0700135 mLazyTaskWriterThread = new LazyTaskWriterThread("LazyTaskWriterThread");
136 }
137
138 void startPersisting() {
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800139 if (!mLazyTaskWriterThread.isAlive()) {
140 mLazyTaskWriterThread.start();
141 }
Craig Mautner21d24a22014-04-23 11:45:37 -0700142 }
143
Craig Mautner63f10902014-09-16 23:57:21 -0700144 private void removeThumbnails(TaskRecord task) {
145 final String taskString = Integer.toString(task.taskId);
146 for (int queueNdx = mWriteQueue.size() - 1; queueNdx >= 0; --queueNdx) {
147 final WriteQueueItem item = mWriteQueue.get(queueNdx);
148 if (item instanceof ImageWriteQueueItem &&
Suprabh Shukla23593142015-11-03 17:31:15 -0800149 ((ImageWriteQueueItem) item).mFilePath.startsWith(taskString)) {
150 if (DEBUG) Slog.d(TAG, "Removing " + ((ImageWriteQueueItem) item).mFilePath +
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700151 " from write queue");
Craig Mautner63f10902014-09-16 23:57:21 -0700152 mWriteQueue.remove(queueNdx);
153 }
154 }
155 }
156
157 private void yieldIfQueueTooDeep() {
158 boolean stall = false;
159 synchronized (this) {
160 if (mNextWriteTime == FLUSH_QUEUE) {
161 stall = true;
162 }
163 }
164 if (stall) {
165 Thread.yield();
166 }
167 }
168
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700169 void wakeup(TaskRecord task, boolean flush) {
Craig Mautner21d24a22014-04-23 11:45:37 -0700170 synchronized (this) {
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700171 if (task != null) {
172 int queueNdx;
173 for (queueNdx = mWriteQueue.size() - 1; queueNdx >= 0; --queueNdx) {
174 final WriteQueueItem item = mWriteQueue.get(queueNdx);
175 if (item instanceof TaskWriteQueueItem &&
176 ((TaskWriteQueueItem) item).mTask == task) {
Craig Mautner63f10902014-09-16 23:57:21 -0700177 if (!task.inRecents) {
178 // This task is being removed.
179 removeThumbnails(task);
180 }
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700181 break;
182 }
183 }
Wale Ogunwalebe23ff42014-10-21 16:29:51 -0700184 if (queueNdx < 0 && task.isPersistable) {
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700185 mWriteQueue.add(new TaskWriteQueueItem(task));
186 }
187 } else {
188 // Dummy.
189 mWriteQueue.add(new WriteQueueItem());
190 }
Craig Mautner63f10902014-09-16 23:57:21 -0700191 if (flush || mWriteQueue.size() > MAX_WRITE_QUEUE_LENGTH) {
192 mNextWriteTime = FLUSH_QUEUE;
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700193 } else if (mNextWriteTime == 0) {
194 mNextWriteTime = SystemClock.uptimeMillis() + PRE_TASK_DELAY_MS;
195 }
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700196 if (DEBUG) Slog.d(TAG, "wakeup: task=" + task + " flush=" + flush + " mNextWriteTime="
197 + mNextWriteTime + " mWriteQueue.size=" + mWriteQueue.size()
198 + " Callers=" + Debug.getCallers(4));
Craig Mautner21d24a22014-04-23 11:45:37 -0700199 notifyAll();
200 }
Craig Mautner63f10902014-09-16 23:57:21 -0700201
202 yieldIfQueueTooDeep();
Craig Mautner21d24a22014-04-23 11:45:37 -0700203 }
204
Dianne Hackbornce0fd762014-09-19 12:58:15 -0700205 void flush() {
206 synchronized (this) {
207 mNextWriteTime = FLUSH_QUEUE;
208 notifyAll();
209 do {
210 try {
211 wait();
212 } catch (InterruptedException e) {
213 }
214 } while (mNextWriteTime == FLUSH_QUEUE);
215 }
216 }
217
Suprabh Shukla23593142015-11-03 17:31:15 -0800218 void saveImage(Bitmap image, String filePath) {
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700219 synchronized (this) {
220 int queueNdx;
221 for (queueNdx = mWriteQueue.size() - 1; queueNdx >= 0; --queueNdx) {
222 final WriteQueueItem item = mWriteQueue.get(queueNdx);
223 if (item instanceof ImageWriteQueueItem) {
224 ImageWriteQueueItem imageWriteQueueItem = (ImageWriteQueueItem) item;
Suprabh Shukla23593142015-11-03 17:31:15 -0800225 if (imageWriteQueueItem.mFilePath.equals(filePath)) {
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700226 // replace the Bitmap with the new one.
227 imageWriteQueueItem.mImage = image;
228 break;
229 }
230 }
231 }
232 if (queueNdx < 0) {
Suprabh Shukla23593142015-11-03 17:31:15 -0800233 mWriteQueue.add(new ImageWriteQueueItem(filePath, image));
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700234 }
Craig Mautner63f10902014-09-16 23:57:21 -0700235 if (mWriteQueue.size() > MAX_WRITE_QUEUE_LENGTH) {
236 mNextWriteTime = FLUSH_QUEUE;
237 } else if (mNextWriteTime == 0) {
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700238 mNextWriteTime = SystemClock.uptimeMillis() + PRE_TASK_DELAY_MS;
239 }
Suprabh Shukla23593142015-11-03 17:31:15 -0800240 if (DEBUG) Slog.d(TAG, "saveImage: filePath=" + filePath + " now=" +
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700241 SystemClock.uptimeMillis() + " mNextWriteTime=" +
242 mNextWriteTime + " Callers=" + Debug.getCallers(4));
243 notifyAll();
244 }
Craig Mautner63f10902014-09-16 23:57:21 -0700245
246 yieldIfQueueTooDeep();
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700247 }
248
Suprabh Shukla23593142015-11-03 17:31:15 -0800249 Bitmap getTaskDescriptionIcon(String filePath) {
Craig Mautner648f69b2014-09-18 14:16:26 -0700250 // See if it is in the write queue
Suprabh Shukla23593142015-11-03 17:31:15 -0800251 final Bitmap icon = getImageFromWriteQueue(filePath);
Craig Mautner648f69b2014-09-18 14:16:26 -0700252 if (icon != null) {
253 return icon;
254 }
Suprabh Shukla23593142015-11-03 17:31:15 -0800255 return restoreImage(filePath);
Craig Mautner648f69b2014-09-18 14:16:26 -0700256 }
257
Suprabh Shukla23593142015-11-03 17:31:15 -0800258 Bitmap getImageFromWriteQueue(String filePath) {
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700259 synchronized (this) {
260 for (int queueNdx = mWriteQueue.size() - 1; queueNdx >= 0; --queueNdx) {
261 final WriteQueueItem item = mWriteQueue.get(queueNdx);
262 if (item instanceof ImageWriteQueueItem) {
263 ImageWriteQueueItem imageWriteQueueItem = (ImageWriteQueueItem) item;
Suprabh Shukla23593142015-11-03 17:31:15 -0800264 if (imageWriteQueueItem.mFilePath.equals(filePath)) {
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700265 return imageWriteQueueItem.mImage;
266 }
267 }
268 }
269 return null;
270 }
271 }
272
Craig Mautner21d24a22014-04-23 11:45:37 -0700273 private StringWriter saveToXml(TaskRecord task) throws IOException, XmlPullParserException {
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700274 if (DEBUG) Slog.d(TAG, "saveToXml: task=" + task);
Craig Mautner21d24a22014-04-23 11:45:37 -0700275 final XmlSerializer xmlSerializer = new FastXmlSerializer();
276 StringWriter stringWriter = new StringWriter();
277 xmlSerializer.setOutput(stringWriter);
278
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700279 if (DEBUG) xmlSerializer.setFeature(
Suprabh Shukla23593142015-11-03 17:31:15 -0800280 "http://xmlpull.org/v1/doc/features.html#indent-output", true);
Craig Mautner21d24a22014-04-23 11:45:37 -0700281
282 // save task
283 xmlSerializer.startDocument(null, true);
284
285 xmlSerializer.startTag(null, TAG_TASK);
286 task.saveToXml(xmlSerializer);
287 xmlSerializer.endTag(null, TAG_TASK);
288
289 xmlSerializer.endDocument();
290 xmlSerializer.flush();
291
292 return stringWriter;
293 }
294
Craig Mautner77b04262014-06-27 15:22:12 -0700295 private String fileToString(File file) {
296 final String newline = System.lineSeparator();
297 try {
298 BufferedReader reader = new BufferedReader(new FileReader(file));
299 StringBuffer sb = new StringBuffer((int) file.length() * 2);
300 String line;
301 while ((line = reader.readLine()) != null) {
302 sb.append(line + newline);
303 }
304 reader.close();
305 return sb.toString();
306 } catch (IOException ioe) {
307 Slog.e(TAG, "Couldn't read file " + file.getName());
308 return null;
309 }
310 }
311
Craig Mautnera228ae92014-07-09 05:44:55 -0700312 private TaskRecord taskIdToTask(int taskId, ArrayList<TaskRecord> tasks) {
313 if (taskId < 0) {
314 return null;
315 }
316 for (int taskNdx = tasks.size() - 1; taskNdx >= 0; --taskNdx) {
317 final TaskRecord task = tasks.get(taskNdx);
318 if (task.taskId == taskId) {
319 return task;
320 }
321 }
322 Slog.e(TAG, "Restore affiliation error looking for taskId=" + taskId);
323 return null;
324 }
325
Suprabh Shukla23593142015-11-03 17:31:15 -0800326 private List<TaskRecord> restoreTasksForUserLocked(final int userId) {
327 final List<TaskRecord> tasks = new ArrayList<TaskRecord>();
Craig Mautner21d24a22014-04-23 11:45:37 -0700328 ArraySet<Integer> recoveredTaskIds = new ArraySet<Integer>();
329
Suprabh Shukla23593142015-11-03 17:31:15 -0800330 File userTasksDir = getUserTasksDir(userId);
331
332 File[] recentFiles = userTasksDir.listFiles();
Craig Mautner21d24a22014-04-23 11:45:37 -0700333 if (recentFiles == null) {
Suprabh Shukla23593142015-11-03 17:31:15 -0800334 Slog.e(TAG, "restoreTasksForUser: Unable to list files from " + userTasksDir);
Craig Mautner21d24a22014-04-23 11:45:37 -0700335 return tasks;
336 }
337
338 for (int taskNdx = 0; taskNdx < recentFiles.length; ++taskNdx) {
339 File taskFile = recentFiles[taskNdx];
Suprabh Shukla23593142015-11-03 17:31:15 -0800340 if (DEBUG) Slog.d(TAG, "restoreTasksForUser: userId=" + userId
341 + ", taskFile=" + taskFile.getName());
Craig Mautner21d24a22014-04-23 11:45:37 -0700342 BufferedReader reader = null;
Craig Mautnere0129b32014-05-25 16:41:09 -0700343 boolean deleteFile = false;
Craig Mautner21d24a22014-04-23 11:45:37 -0700344 try {
345 reader = new BufferedReader(new FileReader(taskFile));
346 final XmlPullParser in = Xml.newPullParser();
347 in.setInput(reader);
348
349 int event;
350 while (((event = in.next()) != XmlPullParser.END_DOCUMENT) &&
351 event != XmlPullParser.END_TAG) {
352 final String name = in.getName();
353 if (event == XmlPullParser.START_TAG) {
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700354 if (DEBUG) Slog.d(TAG, "restoreTasksLocked: START_TAG name=" + name);
Craig Mautner21d24a22014-04-23 11:45:37 -0700355 if (TAG_TASK.equals(name)) {
Suprabh Shukla23593142015-11-03 17:31:15 -0800356 final TaskRecord task = TaskRecord.restoreFromXml(in, mStackSupervisor);
357 if (DEBUG) Slog.d(TAG, "restoreTasksLocked: restored task="
358 + task);
Craig Mautner21d24a22014-04-23 11:45:37 -0700359 if (task != null) {
Dianne Hackborn852975d2014-08-22 17:42:43 -0700360 // XXX Don't add to write queue... there is no reason to write
361 // out the stuff we just read, if we don't write it we will
362 // read the same thing again.
Suprabh Shukla23593142015-11-03 17:31:15 -0800363 // mWriteQueue.add(new TaskWriteQueueItem(task));
Craig Mautner21d24a22014-04-23 11:45:37 -0700364 final int taskId = task.taskId;
Craig Mautner21d24a22014-04-23 11:45:37 -0700365 mStackSupervisor.setNextTaskId(taskId);
Amith Yamasani515d4062015-09-28 11:30:06 -0700366 // Check if it's a valid user id. Don't add tasks for removed users.
Suprabh Shukla23593142015-11-03 17:31:15 -0800367 if (userId == task.userId) {
Amith Yamasani515d4062015-09-28 11:30:06 -0700368 task.isPersistable = true;
369 tasks.add(task);
370 recoveredTaskIds.add(taskId);
371 }
Craig Mautner77b04262014-06-27 15:22:12 -0700372 } else {
Suprabh Shukla23593142015-11-03 17:31:15 -0800373 Slog.e(TAG, "restoreTasksForUser: Unable to restore taskFile="
374 + taskFile + ": " + fileToString(taskFile));
Craig Mautner21d24a22014-04-23 11:45:37 -0700375 }
376 } else {
Suprabh Shukla23593142015-11-03 17:31:15 -0800377 Slog.wtf(TAG, "restoreTasksForUser: Unknown xml event=" + event
378 + " name=" + name);
Craig Mautner21d24a22014-04-23 11:45:37 -0700379 }
380 }
381 XmlUtils.skipCurrentTag(in);
382 }
Craig Mautnere0129b32014-05-25 16:41:09 -0700383 } catch (Exception e) {
Craig Mautnera228ae92014-07-09 05:44:55 -0700384 Slog.wtf(TAG, "Unable to parse " + taskFile + ". Error ", e);
Craig Mautner77b04262014-06-27 15:22:12 -0700385 Slog.e(TAG, "Failing file: " + fileToString(taskFile));
Craig Mautnere0129b32014-05-25 16:41:09 -0700386 deleteFile = true;
Craig Mautner21d24a22014-04-23 11:45:37 -0700387 } finally {
Wale Ogunwale18795a22014-12-03 11:38:33 -0800388 IoUtils.closeQuietly(reader);
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700389 if (deleteFile) {
390 if (DEBUG) Slog.d(TAG, "Deleting file=" + taskFile.getName());
Craig Mautnere0129b32014-05-25 16:41:09 -0700391 taskFile.delete();
392 }
Craig Mautner21d24a22014-04-23 11:45:37 -0700393 }
394 }
395
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700396 if (!DEBUG) {
Suprabh Shukla23593142015-11-03 17:31:15 -0800397 removeObsoleteFiles(recoveredTaskIds, userTasksDir.listFiles());
398 }
399 return tasks;
400 }
401
402 ArrayList<TaskRecord> restoreTasksLocked(final int[] validUserIds) {
403 final ArrayList<TaskRecord> tasks = new ArrayList<TaskRecord>();
404
405 for (int userId : validUserIds) {
406 tasks.addAll(restoreTasksForUserLocked(userId));
Craig Mautner21d24a22014-04-23 11:45:37 -0700407 }
408
Suprabh Shukla23593142015-11-03 17:31:15 -0800409 // Fix up task affiliation from taskIds
Craig Mautnera228ae92014-07-09 05:44:55 -0700410 for (int taskNdx = tasks.size() - 1; taskNdx >= 0; --taskNdx) {
411 final TaskRecord task = tasks.get(taskNdx);
412 task.setPrevAffiliate(taskIdToTask(task.mPrevAffiliateTaskId, tasks));
413 task.setNextAffiliate(taskIdToTask(task.mNextAffiliateTaskId, tasks));
414 }
415
Craig Mautner21d24a22014-04-23 11:45:37 -0700416 TaskRecord[] tasksArray = new TaskRecord[tasks.size()];
417 tasks.toArray(tasksArray);
418 Arrays.sort(tasksArray, new Comparator<TaskRecord>() {
419 @Override
420 public int compare(TaskRecord lhs, TaskRecord rhs) {
Craig Mautner43e52ed2014-06-16 17:18:52 -0700421 final long diff = rhs.mLastTimeMoved - lhs.mLastTimeMoved;
Craig Mautner21d24a22014-04-23 11:45:37 -0700422 if (diff < 0) {
423 return -1;
424 } else if (diff > 0) {
425 return +1;
426 } else {
427 return 0;
428 }
429 }
430 });
431
432 return new ArrayList<TaskRecord>(Arrays.asList(tasksArray));
433 }
434
Craig Mautnere0129b32014-05-25 16:41:09 -0700435 private static void removeObsoleteFiles(ArraySet<Integer> persistentTaskIds, File[] files) {
Suprabh Shukla23593142015-11-03 17:31:15 -0800436 if (DEBUG) Slog.d(TAG, "removeObsoleteFiles: persistentTaskIds=" + persistentTaskIds +
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700437 " files=" + files);
Craig Mautnera5badf02014-09-11 12:47:03 -0700438 if (files == null) {
439 Slog.e(TAG, "File error accessing recents directory (too many files open?).");
440 return;
441 }
Craig Mautner21d24a22014-04-23 11:45:37 -0700442 for (int fileNdx = 0; fileNdx < files.length; ++fileNdx) {
443 File file = files[fileNdx];
444 String filename = file.getName();
Craig Mautnerffcfcaa2014-06-05 09:54:38 -0700445 final int taskIdEnd = filename.indexOf('_');
Craig Mautner21d24a22014-04-23 11:45:37 -0700446 if (taskIdEnd > 0) {
447 final int taskId;
448 try {
449 taskId = Integer.valueOf(filename.substring(0, taskIdEnd));
Suprabh Shukla23593142015-11-03 17:31:15 -0800450 if (DEBUG) Slog.d(TAG, "removeObsoleteFiles: Found taskId=" + taskId);
Craig Mautner21d24a22014-04-23 11:45:37 -0700451 } catch (Exception e) {
Suprabh Shukla23593142015-11-03 17:31:15 -0800452 Slog.wtf(TAG, "removeObsoleteFiles: Can't parse file=" + file.getName());
Craig Mautner21d24a22014-04-23 11:45:37 -0700453 file.delete();
454 continue;
455 }
456 if (!persistentTaskIds.contains(taskId)) {
Suprabh Shukla23593142015-11-03 17:31:15 -0800457 if (DEBUG) Slog.d(TAG, "removeObsoleteFiles: deleting file=" + file.getName());
Craig Mautner21d24a22014-04-23 11:45:37 -0700458 file.delete();
459 }
460 }
461 }
462 }
463
464 private void removeObsoleteFiles(ArraySet<Integer> persistentTaskIds) {
Suprabh Shukla23593142015-11-03 17:31:15 -0800465 for (int userId : mService.getRunningUserIds()) {
466 removeObsoleteFiles(persistentTaskIds, getUserImagesDir(userId).listFiles());
467 removeObsoleteFiles(persistentTaskIds, getUserTasksDir(userId).listFiles());
468 }
Craig Mautner21d24a22014-04-23 11:45:37 -0700469 }
470
471 static Bitmap restoreImage(String filename) {
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700472 if (DEBUG) Slog.d(TAG, "restoreImage: restoring " + filename);
Suprabh Shukla23593142015-11-03 17:31:15 -0800473 return BitmapFactory.decodeFile(filename);
474 }
475
476 static File getUserTasksDir(int userId) {
477 File userTasksDir = new File(Environment.getUserSystemDirectory(userId), TASKS_DIRNAME);
478
479 if (!userTasksDir.exists()) {
480 if (!userTasksDir.mkdir()) {
481 Slog.e(TAG, "Failure creating tasks directory for user " + userId + ": "
482 + userTasksDir);
483 }
484 }
485 return userTasksDir;
486 }
487
488 static File getUserImagesDir(int userId) {
489 File userImagesDir = new File(Environment.getUserSystemDirectory(userId), IMAGES_DIRNAME);
490
491 if (!userImagesDir.exists()) {
492 if (!userImagesDir.mkdir()) {
493 Slog.e(TAG, "Failure creating images directory for user " + userId + ": "
494 + userImagesDir);
495 }
496 }
497 return userImagesDir;
Craig Mautner21d24a22014-04-23 11:45:37 -0700498 }
499
500 private class LazyTaskWriterThread extends Thread {
Craig Mautner21d24a22014-04-23 11:45:37 -0700501
502 LazyTaskWriterThread(String name) {
503 super(name);
504 }
505
506 @Override
507 public void run() {
Riley Andrewsf16c2e82015-06-02 18:24:48 -0700508 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Craig Mautner21d24a22014-04-23 11:45:37 -0700509 ArraySet<Integer> persistentTaskIds = new ArraySet<Integer>();
510 while (true) {
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700511 // We can't lock mService while holding TaskPersister.this, but we don't want to
512 // call removeObsoleteFiles every time through the loop, only the last time before
513 // going to sleep. The risk is that we call removeObsoleteFiles() successively.
514 final boolean probablyDone;
Craig Mautner21d24a22014-04-23 11:45:37 -0700515 synchronized (TaskPersister.this) {
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700516 probablyDone = mWriteQueue.isEmpty();
517 }
518 if (probablyDone) {
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700519 if (DEBUG) Slog.d(TAG, "Looking for obsolete files.");
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700520 persistentTaskIds.clear();
521 synchronized (mService) {
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700522 if (DEBUG) Slog.d(TAG, "mRecents=" + mRecentTasks);
Wale Ogunwalec82f2f52014-12-09 09:32:50 -0800523 for (int taskNdx = mRecentTasks.size() - 1; taskNdx >= 0; --taskNdx) {
524 final TaskRecord task = mRecentTasks.get(taskNdx);
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700525 if (DEBUG) Slog.d(TAG, "LazyTaskWriter: task=" + task +
Wale Ogunwalebe23ff42014-10-21 16:29:51 -0700526 " persistable=" + task.isPersistable);
527 if ((task.isPersistable || task.inRecents)
Wale Ogunwale18795a22014-12-03 11:38:33 -0800528 && (task.stack == null || !task.stack.isHomeStack())) {
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700529 if (DEBUG) Slog.d(TAG, "adding to persistentTaskIds task=" + task);
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700530 persistentTaskIds.add(task.taskId);
531 } else {
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700532 if (DEBUG) Slog.d(TAG,
Wale Ogunwalebe23ff42014-10-21 16:29:51 -0700533 "omitting from persistentTaskIds task=" + task);
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700534 }
535 }
536 }
537 removeObsoleteFiles(persistentTaskIds);
538 }
539
540 // If mNextWriteTime, then don't delay between each call to saveToXml().
541 final WriteQueueItem item;
542 synchronized (TaskPersister.this) {
Craig Mautner63f10902014-09-16 23:57:21 -0700543 if (mNextWriteTime != FLUSH_QUEUE) {
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700544 // The next write we don't have to wait so long.
545 mNextWriteTime = SystemClock.uptimeMillis() + INTER_WRITE_DELAY_MS;
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700546 if (DEBUG) Slog.d(TAG, "Next write time may be in " +
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700547 INTER_WRITE_DELAY_MS + " msec. (" + mNextWriteTime + ")");
548 }
549
550 while (mWriteQueue.isEmpty()) {
Dianne Hackbornce0fd762014-09-19 12:58:15 -0700551 if (mNextWriteTime != 0) {
552 mNextWriteTime = 0; // idle.
553 TaskPersister.this.notifyAll(); // wake up flush() if needed.
554 }
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700555 try {
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700556 if (DEBUG) Slog.d(TAG, "LazyTaskWriter: waiting indefinitely.");
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700557 TaskPersister.this.wait();
558 } catch (InterruptedException e) {
559 }
Craig Mautner63f10902014-09-16 23:57:21 -0700560 // Invariant: mNextWriteTime is either FLUSH_QUEUE or PRE_WRITE_DELAY_MS
561 // from now.
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700562 }
563 item = mWriteQueue.remove(0);
564
Craig Mautner21d24a22014-04-23 11:45:37 -0700565 long now = SystemClock.uptimeMillis();
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700566 if (DEBUG) Slog.d(TAG, "LazyTaskWriter: now=" + now + " mNextWriteTime=" +
567 mNextWriteTime + " mWriteQueue.size=" + mWriteQueue.size());
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700568 while (now < mNextWriteTime) {
Craig Mautner21d24a22014-04-23 11:45:37 -0700569 try {
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700570 if (DEBUG) Slog.d(TAG, "LazyTaskWriter: waiting " +
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700571 (mNextWriteTime - now));
572 TaskPersister.this.wait(mNextWriteTime - now);
Craig Mautner21d24a22014-04-23 11:45:37 -0700573 } catch (InterruptedException e) {
574 }
575 now = SystemClock.uptimeMillis();
576 }
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700577
578 // Got something to do.
Craig Mautner21d24a22014-04-23 11:45:37 -0700579 }
580
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700581 if (item instanceof ImageWriteQueueItem) {
582 ImageWriteQueueItem imageWriteQueueItem = (ImageWriteQueueItem) item;
Suprabh Shukla23593142015-11-03 17:31:15 -0800583 final String filePath = imageWriteQueueItem.mFilePath;
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700584 final Bitmap bitmap = imageWriteQueueItem.mImage;
Suprabh Shukla23593142015-11-03 17:31:15 -0800585 if (DEBUG) Slog.d(TAG, "writing bitmap: filename=" + filePath);
Craig Mautnerc0ffce52014-07-01 12:38:52 -0700586 FileOutputStream imageFile = null;
587 try {
Suprabh Shukla23593142015-11-03 17:31:15 -0800588 imageFile = new FileOutputStream(new File(filePath));
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700589 bitmap.compress(Bitmap.CompressFormat.PNG, 100, imageFile);
Craig Mautnerc0ffce52014-07-01 12:38:52 -0700590 } catch (Exception e) {
Suprabh Shukla23593142015-11-03 17:31:15 -0800591 Slog.e(TAG, "saveImage: unable to save " + filePath, e);
Craig Mautnerc0ffce52014-07-01 12:38:52 -0700592 } finally {
Wale Ogunwale18795a22014-12-03 11:38:33 -0800593 IoUtils.closeQuietly(imageFile);
Craig Mautnerc0ffce52014-07-01 12:38:52 -0700594 }
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700595 } else if (item instanceof TaskWriteQueueItem) {
596 // Write out one task.
597 StringWriter stringWriter = null;
598 TaskRecord task = ((TaskWriteQueueItem) item).mTask;
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700599 if (DEBUG) Slog.d(TAG, "Writing task=" + task);
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700600 synchronized (mService) {
Craig Mautner63f10902014-09-16 23:57:21 -0700601 if (task.inRecents) {
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700602 // Still there.
Craig Mautner21d24a22014-04-23 11:45:37 -0700603 try {
Stefan Kuhnee88d1e52015-05-18 10:33:45 -0700604 if (DEBUG) Slog.d(TAG, "Saving task=" + task);
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700605 stringWriter = saveToXml(task);
606 } catch (IOException e) {
607 } catch (XmlPullParserException e) {
Craig Mautner21d24a22014-04-23 11:45:37 -0700608 }
609 }
Dianne Hackborn852975d2014-08-22 17:42:43 -0700610 }
611 if (stringWriter != null) {
612 // Write out xml file while not holding mService lock.
613 FileOutputStream file = null;
614 AtomicFile atomicFile = null;
615 try {
Suprabh Shukla23593142015-11-03 17:31:15 -0800616 atomicFile = new AtomicFile(new File(
617 getUserTasksDir(task.userId),
618 String.valueOf(task.taskId) + RECENTS_FILENAME
619 + TASK_EXTENSION));
Dianne Hackborn852975d2014-08-22 17:42:43 -0700620 file = atomicFile.startWrite();
621 file.write(stringWriter.toString().getBytes());
622 file.write('\n');
623 atomicFile.finishWrite(file);
Suprabh Shukla23593142015-11-03 17:31:15 -0800624
Dianne Hackborn852975d2014-08-22 17:42:43 -0700625 } catch (IOException e) {
626 if (file != null) {
627 atomicFile.failWrite(file);
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700628 }
Suprabh Shukla23593142015-11-03 17:31:15 -0800629 Slog.e(TAG,
630 "Unable to open " + atomicFile + " for persisting. " + e);
Craig Mautnerf4f8bb72014-07-29 10:41:40 -0700631 }
Craig Mautner21d24a22014-04-23 11:45:37 -0700632 }
633 }
Craig Mautner21d24a22014-04-23 11:45:37 -0700634 }
635 }
636 }
Craig Mautner21d24a22014-04-23 11:45:37 -0700637}