1 /*
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 
17 package com.android.server.wm;
18 
19 import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
20 
21 import android.annotation.NonNull;
22 import android.graphics.Bitmap;
23 import android.graphics.BitmapFactory;
24 import android.os.Debug;
25 import android.os.Environment;
26 import android.os.FileUtils;
27 import android.os.SystemClock;
28 import android.util.ArraySet;
29 import android.util.AtomicFile;
30 import android.util.Slog;
31 import android.util.SparseArray;
32 import android.util.SparseBooleanArray;
33 import android.util.Xml;
34 
35 import com.android.internal.annotations.VisibleForTesting;
36 import com.android.internal.util.FastXmlSerializer;
37 import com.android.internal.util.XmlUtils;
38 
39 import libcore.io.IoUtils;
40 
41 import org.xmlpull.v1.XmlPullParser;
42 import org.xmlpull.v1.XmlPullParserException;
43 import org.xmlpull.v1.XmlSerializer;
44 
45 import java.io.BufferedReader;
46 import java.io.BufferedWriter;
47 import java.io.File;
48 import java.io.FileNotFoundException;
49 import java.io.FileOutputStream;
50 import java.io.FileReader;
51 import java.io.FileWriter;
52 import java.io.IOException;
53 import java.io.StringWriter;
54 import java.util.ArrayList;
55 import java.util.Collections;
56 import java.util.Comparator;
57 import java.util.List;
58 
59 /**
60  * Persister that saves recent tasks into disk.
61  */
62 public class TaskPersister implements PersisterQueue.Listener {
63     static final String TAG = "TaskPersister";
64     static final boolean DEBUG = false;
65     static final String IMAGE_EXTENSION = ".png";
66 
67     private static final String TASKS_DIRNAME = "recent_tasks";
68     private static final String TASK_FILENAME_SUFFIX = "_task.xml";
69     private static final String IMAGES_DIRNAME = "recent_images";
70     private static final String PERSISTED_TASK_IDS_FILENAME = "persisted_taskIds.txt";
71 
72     private static final String TAG_TASK = "task";
73 
74     private final ActivityTaskManagerService mService;
75     private final ActivityStackSupervisor mStackSupervisor;
76     private final RecentTasks mRecentTasks;
77     private final SparseArray<SparseBooleanArray> mTaskIdsInFile = new SparseArray<>();
78     private final File mTaskIdsDir;
79     // To lock file operations in TaskPersister
80     private final Object mIoLock = new Object();
81     private final PersisterQueue mPersisterQueue;
82 
83     private final ArraySet<Integer> mTmpTaskIds = new ArraySet<>();
84 
TaskPersister(File systemDir, ActivityStackSupervisor stackSupervisor, ActivityTaskManagerService service, RecentTasks recentTasks, PersisterQueue persisterQueue)85     TaskPersister(File systemDir, ActivityStackSupervisor stackSupervisor,
86             ActivityTaskManagerService service, RecentTasks recentTasks,
87             PersisterQueue persisterQueue) {
88 
89         final File legacyImagesDir = new File(systemDir, IMAGES_DIRNAME);
90         if (legacyImagesDir.exists()) {
91             if (!FileUtils.deleteContents(legacyImagesDir) || !legacyImagesDir.delete()) {
92                 Slog.i(TAG, "Failure deleting legacy images directory: " + legacyImagesDir);
93             }
94         }
95 
96         final File legacyTasksDir = new File(systemDir, TASKS_DIRNAME);
97         if (legacyTasksDir.exists()) {
98             if (!FileUtils.deleteContents(legacyTasksDir) || !legacyTasksDir.delete()) {
99                 Slog.i(TAG, "Failure deleting legacy tasks directory: " + legacyTasksDir);
100             }
101         }
102 
103         mTaskIdsDir = new File(Environment.getDataDirectory(), "system_de");
104         mStackSupervisor = stackSupervisor;
105         mService = service;
106         mRecentTasks = recentTasks;
107         mPersisterQueue = persisterQueue;
108         mPersisterQueue.addListener(this);
109     }
110 
111     @VisibleForTesting
TaskPersister(File workingDir)112     TaskPersister(File workingDir) {
113         mTaskIdsDir = workingDir;
114         mStackSupervisor = null;
115         mService = null;
116         mRecentTasks = null;
117         mPersisterQueue = new PersisterQueue();
118         mPersisterQueue.addListener(this);
119     }
120 
removeThumbnails(TaskRecord task)121     private void removeThumbnails(TaskRecord task) {
122         mPersisterQueue.removeItems(
123                 item -> {
124                     File file = new File(item.mFilePath);
125                     return file.getName().startsWith(Integer.toString(task.taskId));
126                 },
127                 ImageWriteQueueItem.class);
128     }
129 
130     @NonNull
loadPersistedTaskIdsForUser(int userId)131     SparseBooleanArray loadPersistedTaskIdsForUser(int userId) {
132         if (mTaskIdsInFile.get(userId) != null) {
133             return mTaskIdsInFile.get(userId).clone();
134         }
135         final SparseBooleanArray persistedTaskIds = new SparseBooleanArray();
136         synchronized (mIoLock) {
137             BufferedReader reader = null;
138             String line;
139             try {
140                 reader = new BufferedReader(new FileReader(getUserPersistedTaskIdsFile(userId)));
141                 while ((line = reader.readLine()) != null) {
142                     for (String taskIdString : line.split("\\s+")) {
143                         int id = Integer.parseInt(taskIdString);
144                         persistedTaskIds.put(id, true);
145                     }
146                 }
147             } catch (FileNotFoundException e) {
148                 // File doesn't exist. Ignore.
149             } catch (Exception e) {
150                 Slog.e(TAG, "Error while reading taskIds file for user " + userId, e);
151             } finally {
152                 IoUtils.closeQuietly(reader);
153             }
154         }
155         mTaskIdsInFile.put(userId, persistedTaskIds);
156         return persistedTaskIds.clone();
157     }
158 
159 
160     @VisibleForTesting
writePersistedTaskIdsForUser(@onNull SparseBooleanArray taskIds, int userId)161     void writePersistedTaskIdsForUser(@NonNull SparseBooleanArray taskIds, int userId) {
162         if (userId < 0) {
163             return;
164         }
165         final File persistedTaskIdsFile = getUserPersistedTaskIdsFile(userId);
166         synchronized (mIoLock) {
167             BufferedWriter writer = null;
168             try {
169                 writer = new BufferedWriter(new FileWriter(persistedTaskIdsFile));
170                 for (int i = 0; i < taskIds.size(); i++) {
171                     if (taskIds.valueAt(i)) {
172                         writer.write(String.valueOf(taskIds.keyAt(i)));
173                         writer.newLine();
174                     }
175                 }
176             } catch (Exception e) {
177                 Slog.e(TAG, "Error while writing taskIds file for user " + userId, e);
178             } finally {
179                 IoUtils.closeQuietly(writer);
180             }
181         }
182     }
183 
unloadUserDataFromMemory(int userId)184     void unloadUserDataFromMemory(int userId) {
185         mTaskIdsInFile.delete(userId);
186     }
187 
wakeup(TaskRecord task, boolean flush)188     void wakeup(TaskRecord task, boolean flush) {
189         synchronized (mPersisterQueue) {
190             if (task != null) {
191                 final TaskWriteQueueItem item = mPersisterQueue.findLastItem(
192                         queueItem -> task == queueItem.mTask, TaskWriteQueueItem.class);
193                 if (item != null && !task.inRecents) {
194                     removeThumbnails(task);
195                 }
196 
197                 if (item == null && task.isPersistable) {
198                     mPersisterQueue.addItem(new TaskWriteQueueItem(task, mService), flush);
199                 }
200             } else {
201                 // Dummy. Ensures removeObsoleteFiles is called when LazyTaskThreadWriter is
202                 // notified.
203                 mPersisterQueue.addItem(PersisterQueue.EMPTY_ITEM, flush);
204             }
205             if (DEBUG) {
206                 Slog.d(TAG, "wakeup: task=" + task + " flush=" + flush + " Callers="
207                         + Debug.getCallers(4));
208             }
209         }
210 
211         mPersisterQueue.yieldIfQueueTooDeep();
212     }
213 
flush()214     void flush() {
215         mPersisterQueue.flush();
216     }
217 
saveImage(Bitmap image, String filePath)218     void saveImage(Bitmap image, String filePath) {
219         mPersisterQueue.updateLastOrAddItem(new ImageWriteQueueItem(filePath, image),
220                 /* flush */ false);
221         if (DEBUG) {
222             Slog.d(TAG, "saveImage: filePath=" + filePath + " now="
223                     + SystemClock.uptimeMillis() + " Callers=" + Debug.getCallers(4));
224         }
225     }
226 
getTaskDescriptionIcon(String filePath)227     Bitmap getTaskDescriptionIcon(String filePath) {
228         // See if it is in the write queue
229         final Bitmap icon = getImageFromWriteQueue(filePath);
230         if (icon != null) {
231             return icon;
232         }
233         return restoreImage(filePath);
234     }
235 
getImageFromWriteQueue(String filePath)236     private Bitmap getImageFromWriteQueue(String filePath) {
237         final ImageWriteQueueItem item = mPersisterQueue.findLastItem(
238                 queueItem -> queueItem.mFilePath.equals(filePath), ImageWriteQueueItem.class);
239         return item != null ? item.mImage : null;
240     }
241 
fileToString(File file)242     private String fileToString(File file) {
243         final String newline = System.lineSeparator();
244         try {
245             BufferedReader reader = new BufferedReader(new FileReader(file));
246             StringBuffer sb = new StringBuffer((int) file.length() * 2);
247             String line;
248             while ((line = reader.readLine()) != null) {
249                 sb.append(line + newline);
250             }
251             reader.close();
252             return sb.toString();
253         } catch (IOException ioe) {
254             Slog.e(TAG, "Couldn't read file " + file.getName());
255             return null;
256         }
257     }
258 
taskIdToTask(int taskId, ArrayList<TaskRecord> tasks)259     private TaskRecord taskIdToTask(int taskId, ArrayList<TaskRecord> tasks) {
260         if (taskId < 0) {
261             return null;
262         }
263         for (int taskNdx = tasks.size() - 1; taskNdx >= 0; --taskNdx) {
264             final TaskRecord task = tasks.get(taskNdx);
265             if (task.taskId == taskId) {
266                 return task;
267             }
268         }
269         Slog.e(TAG, "Restore affiliation error looking for taskId=" + taskId);
270         return null;
271     }
272 
restoreTasksForUserLocked(final int userId, SparseBooleanArray preaddedTasks)273     List<TaskRecord> restoreTasksForUserLocked(final int userId, SparseBooleanArray preaddedTasks) {
274         final ArrayList<TaskRecord> tasks = new ArrayList<TaskRecord>();
275         ArraySet<Integer> recoveredTaskIds = new ArraySet<Integer>();
276 
277         File userTasksDir = getUserTasksDir(userId);
278 
279         File[] recentFiles = userTasksDir.listFiles();
280         if (recentFiles == null) {
281             Slog.e(TAG, "restoreTasksForUserLocked: Unable to list files from " + userTasksDir);
282             return tasks;
283         }
284 
285         for (int taskNdx = 0; taskNdx < recentFiles.length; ++taskNdx) {
286             File taskFile = recentFiles[taskNdx];
287             if (DEBUG) {
288                 Slog.d(TAG, "restoreTasksForUserLocked: userId=" + userId
289                         + ", taskFile=" + taskFile.getName());
290             }
291 
292             if (!taskFile.getName().endsWith(TASK_FILENAME_SUFFIX)) {
293                 continue;
294             }
295             try {
296                 final int taskId = Integer.parseInt(taskFile.getName().substring(
297                         0 /* beginIndex */,
298                         taskFile.getName().length() - TASK_FILENAME_SUFFIX.length()));
299                 if (preaddedTasks.get(taskId, false)) {
300                     Slog.w(TAG, "Task #" + taskId +
301                             " has already been created so we don't restore again");
302                     continue;
303                 }
304             } catch (NumberFormatException e) {
305                 Slog.w(TAG, "Unexpected task file name", e);
306                 continue;
307             }
308 
309             BufferedReader reader = null;
310             boolean deleteFile = false;
311             try {
312                 reader = new BufferedReader(new FileReader(taskFile));
313                 final XmlPullParser in = Xml.newPullParser();
314                 in.setInput(reader);
315 
316                 int event;
317                 while (((event = in.next()) != XmlPullParser.END_DOCUMENT) &&
318                         event != XmlPullParser.END_TAG) {
319                     final String name = in.getName();
320                     if (event == XmlPullParser.START_TAG) {
321                         if (DEBUG) Slog.d(TAG, "restoreTasksForUserLocked: START_TAG name=" + name);
322                         if (TAG_TASK.equals(name)) {
323                             final TaskRecord task = TaskRecord.restoreFromXml(in, mStackSupervisor);
324                             if (DEBUG) Slog.d(TAG, "restoreTasksForUserLocked: restored task="
325                                     + task);
326                             if (task != null) {
327                                 // XXX Don't add to write queue... there is no reason to write
328                                 // out the stuff we just read, if we don't write it we will
329                                 // read the same thing again.
330                                 // mWriteQueue.add(new TaskWriteQueueItem(task));
331 
332                                 final int taskId = task.taskId;
333                                 if (mService.mRootActivityContainer.anyTaskForId(taskId,
334                                         MATCH_TASK_IN_STACKS_OR_RECENT_TASKS) != null) {
335                                     // Should not happen.
336                                     Slog.wtf(TAG, "Existing task with taskId " + taskId + "found");
337                                 } else if (userId != task.userId) {
338                                     // Should not happen.
339                                     Slog.wtf(TAG, "Task with userId " + task.userId + " found in "
340                                             + userTasksDir.getAbsolutePath());
341                                 } else {
342                                     // Looks fine.
343                                     mStackSupervisor.setNextTaskIdForUserLocked(taskId, userId);
344                                     task.isPersistable = true;
345                                     tasks.add(task);
346                                     recoveredTaskIds.add(taskId);
347                                 }
348                             } else {
349                                 Slog.e(TAG, "restoreTasksForUserLocked: Unable to restore taskFile="
350                                         + taskFile + ": " + fileToString(taskFile));
351                             }
352                         } else {
353                             Slog.wtf(TAG, "restoreTasksForUserLocked: Unknown xml event=" + event
354                                     + " name=" + name);
355                         }
356                     }
357                     XmlUtils.skipCurrentTag(in);
358                 }
359             } catch (Exception e) {
360                 Slog.wtf(TAG, "Unable to parse " + taskFile + ". Error ", e);
361                 Slog.e(TAG, "Failing file: " + fileToString(taskFile));
362                 deleteFile = true;
363             } finally {
364                 IoUtils.closeQuietly(reader);
365                 if (deleteFile) {
366                     if (DEBUG) Slog.d(TAG, "Deleting file=" + taskFile.getName());
367                     taskFile.delete();
368                 }
369             }
370         }
371 
372         if (!DEBUG) {
373             removeObsoleteFiles(recoveredTaskIds, userTasksDir.listFiles());
374         }
375 
376         // Fix up task affiliation from taskIds
377         for (int taskNdx = tasks.size() - 1; taskNdx >= 0; --taskNdx) {
378             final TaskRecord task = tasks.get(taskNdx);
379             task.setPrevAffiliate(taskIdToTask(task.mPrevAffiliateTaskId, tasks));
380             task.setNextAffiliate(taskIdToTask(task.mNextAffiliateTaskId, tasks));
381         }
382 
383         Collections.sort(tasks, new Comparator<TaskRecord>() {
384             @Override
385             public int compare(TaskRecord lhs, TaskRecord rhs) {
386                 final long diff = rhs.mLastTimeMoved - lhs.mLastTimeMoved;
387                 if (diff < 0) {
388                     return -1;
389                 } else if (diff > 0) {
390                     return +1;
391                 } else {
392                     return 0;
393                 }
394             }
395         });
396         return tasks;
397     }
398 
399     @Override
onPreProcessItem(boolean queueEmpty)400     public void onPreProcessItem(boolean queueEmpty) {
401         // We can't lock mService while locking the queue, but we don't want to
402         // call removeObsoleteFiles before every item, only the last time
403         // before going to sleep. The risk is that we call removeObsoleteFiles()
404         // successively.
405         if (queueEmpty) {
406             if (DEBUG) Slog.d(TAG, "Looking for obsolete files.");
407             mTmpTaskIds.clear();
408             synchronized (mService.mGlobalLock) {
409                 if (DEBUG) Slog.d(TAG, "mRecents=" + mRecentTasks);
410                 mRecentTasks.getPersistableTaskIds(mTmpTaskIds);
411                 mService.mWindowManager.removeObsoleteTaskFiles(mTmpTaskIds,
412                         mRecentTasks.usersWithRecentsLoadedLocked());
413             }
414             removeObsoleteFiles(mTmpTaskIds);
415         }
416         writeTaskIdsFiles();
417     }
418 
removeObsoleteFiles(ArraySet<Integer> persistentTaskIds, File[] files)419     private static void removeObsoleteFiles(ArraySet<Integer> persistentTaskIds, File[] files) {
420         if (DEBUG) Slog.d(TAG, "removeObsoleteFiles: persistentTaskIds=" + persistentTaskIds +
421                 " files=" + files);
422         if (files == null) {
423             Slog.e(TAG, "File error accessing recents directory (directory doesn't exist?).");
424             return;
425         }
426         for (int fileNdx = 0; fileNdx < files.length; ++fileNdx) {
427             File file = files[fileNdx];
428             String filename = file.getName();
429             final int taskIdEnd = filename.indexOf('_');
430             if (taskIdEnd > 0) {
431                 final int taskId;
432                 try {
433                     taskId = Integer.parseInt(filename.substring(0, taskIdEnd));
434                     if (DEBUG) Slog.d(TAG, "removeObsoleteFiles: Found taskId=" + taskId);
435                 } catch (Exception e) {
436                     Slog.wtf(TAG, "removeObsoleteFiles: Can't parse file=" + file.getName());
437                     file.delete();
438                     continue;
439                 }
440                 if (!persistentTaskIds.contains(taskId)) {
441                     if (DEBUG) Slog.d(TAG, "removeObsoleteFiles: deleting file=" + file.getName());
442                     file.delete();
443                 }
444             }
445         }
446     }
447 
writeTaskIdsFiles()448     private void writeTaskIdsFiles() {
449         SparseArray<SparseBooleanArray> changedTaskIdsPerUser = new SparseArray<>();
450         synchronized (mService.mGlobalLock) {
451             for (int userId : mRecentTasks.usersWithRecentsLoadedLocked()) {
452                 SparseBooleanArray taskIdsToSave = mRecentTasks.getTaskIdsForUser(userId);
453                 SparseBooleanArray persistedIdsInFile = mTaskIdsInFile.get(userId);
454                 if (persistedIdsInFile != null && persistedIdsInFile.equals(taskIdsToSave)) {
455                     continue;
456                 } else {
457                     SparseBooleanArray taskIdsToSaveCopy = taskIdsToSave.clone();
458                     mTaskIdsInFile.put(userId, taskIdsToSaveCopy);
459                     changedTaskIdsPerUser.put(userId, taskIdsToSaveCopy);
460                 }
461             }
462         }
463         for (int i = 0; i < changedTaskIdsPerUser.size(); i++) {
464             writePersistedTaskIdsForUser(changedTaskIdsPerUser.valueAt(i),
465                     changedTaskIdsPerUser.keyAt(i));
466         }
467     }
468 
removeObsoleteFiles(ArraySet<Integer> persistentTaskIds)469     private void removeObsoleteFiles(ArraySet<Integer> persistentTaskIds) {
470         int[] candidateUserIds;
471         synchronized (mService.mGlobalLock) {
472             // Remove only from directories of the users who have recents in memory synchronized
473             // with persistent storage.
474             candidateUserIds = mRecentTasks.usersWithRecentsLoadedLocked();
475         }
476         for (int userId : candidateUserIds) {
477             removeObsoleteFiles(persistentTaskIds, getUserImagesDir(userId).listFiles());
478             removeObsoleteFiles(persistentTaskIds, getUserTasksDir(userId).listFiles());
479         }
480     }
481 
restoreImage(String filename)482     static Bitmap restoreImage(String filename) {
483         if (DEBUG) Slog.d(TAG, "restoreImage: restoring " + filename);
484         return BitmapFactory.decodeFile(filename);
485     }
486 
getUserPersistedTaskIdsFile(int userId)487     private File getUserPersistedTaskIdsFile(int userId) {
488         File userTaskIdsDir = new File(mTaskIdsDir, String.valueOf(userId));
489         if (!userTaskIdsDir.exists() && !userTaskIdsDir.mkdirs()) {
490             Slog.e(TAG, "Error while creating user directory: " + userTaskIdsDir);
491         }
492         return new File(userTaskIdsDir, PERSISTED_TASK_IDS_FILENAME);
493     }
494 
getUserTasksDir(int userId)495     private static File getUserTasksDir(int userId) {
496         return new File(Environment.getDataSystemCeDirectory(userId), TASKS_DIRNAME);
497     }
498 
getUserImagesDir(int userId)499     static File getUserImagesDir(int userId) {
500         return new File(Environment.getDataSystemCeDirectory(userId), IMAGES_DIRNAME);
501     }
502 
createParentDirectory(String filePath)503     private static boolean createParentDirectory(String filePath) {
504         File parentDir = new File(filePath).getParentFile();
505         return parentDir.exists() || parentDir.mkdirs();
506     }
507 
508     private static class TaskWriteQueueItem implements PersisterQueue.WriteQueueItem {
509         private final ActivityTaskManagerService mService;
510         private final TaskRecord mTask;
511 
TaskWriteQueueItem(TaskRecord task, ActivityTaskManagerService service)512         TaskWriteQueueItem(TaskRecord task, ActivityTaskManagerService service) {
513             mTask = task;
514             mService = service;
515         }
516 
saveToXml(TaskRecord task)517         private StringWriter saveToXml(TaskRecord task) throws IOException, XmlPullParserException {
518             if (DEBUG) Slog.d(TAG, "saveToXml: task=" + task);
519             final XmlSerializer xmlSerializer = new FastXmlSerializer();
520             StringWriter stringWriter = new StringWriter();
521             xmlSerializer.setOutput(stringWriter);
522 
523             if (DEBUG) {
524                 xmlSerializer.setFeature(
525                         "http://xmlpull.org/v1/doc/features.html#indent-output", true);
526             }
527 
528             // save task
529             xmlSerializer.startDocument(null, true);
530 
531             xmlSerializer.startTag(null, TAG_TASK);
532             task.saveToXml(xmlSerializer);
533             xmlSerializer.endTag(null, TAG_TASK);
534 
535             xmlSerializer.endDocument();
536             xmlSerializer.flush();
537 
538             return stringWriter;
539         }
540 
541         @Override
process()542         public void process() {
543             // Write out one task.
544             StringWriter stringWriter = null;
545             TaskRecord task = mTask;
546             if (DEBUG) Slog.d(TAG, "Writing task=" + task);
547             synchronized (mService.mGlobalLock) {
548                 if (task.inRecents) {
549                     // Still there.
550                     try {
551                         if (DEBUG) Slog.d(TAG, "Saving task=" + task);
552                         stringWriter = saveToXml(task);
553                     } catch (IOException e) {
554                     } catch (XmlPullParserException e) {
555                     }
556                 }
557             }
558             if (stringWriter != null) {
559                 // Write out xml file while not holding mService lock.
560                 FileOutputStream file = null;
561                 AtomicFile atomicFile = null;
562                 try {
563                     File userTasksDir = getUserTasksDir(task.userId);
564                     if (!userTasksDir.isDirectory() && !userTasksDir.mkdirs()) {
565                         Slog.e(TAG, "Failure creating tasks directory for user " + task.userId
566                                 + ": " + userTasksDir + " Dropping persistence for task " + task);
567                         return;
568                     }
569                     atomicFile = new AtomicFile(new File(userTasksDir,
570                             String.valueOf(task.taskId) + TASK_FILENAME_SUFFIX));
571                     file = atomicFile.startWrite();
572                     file.write(stringWriter.toString().getBytes());
573                     file.write('\n');
574                     atomicFile.finishWrite(file);
575                 } catch (IOException e) {
576                     if (file != null) {
577                         atomicFile.failWrite(file);
578                     }
579                     Slog.e(TAG,
580                             "Unable to open " + atomicFile + " for persisting. " + e);
581                 }
582             }
583         }
584 
585         @Override
toString()586         public String toString() {
587             return "TaskWriteQueueItem{task=" + mTask + "}";
588         }
589     }
590 
591     private static class ImageWriteQueueItem implements
592             PersisterQueue.WriteQueueItem<ImageWriteQueueItem> {
593         final String mFilePath;
594         Bitmap mImage;
595 
ImageWriteQueueItem(String filePath, Bitmap image)596         ImageWriteQueueItem(String filePath, Bitmap image) {
597             mFilePath = filePath;
598             mImage = image;
599         }
600 
601         @Override
process()602         public void process() {
603             final String filePath = mFilePath;
604             if (!createParentDirectory(filePath)) {
605                 Slog.e(TAG, "Error while creating images directory for file: " + filePath);
606                 return;
607             }
608             final Bitmap bitmap = mImage;
609             if (DEBUG) Slog.d(TAG, "writing bitmap: filename=" + filePath);
610             FileOutputStream imageFile = null;
611             try {
612                 imageFile = new FileOutputStream(new File(filePath));
613                 bitmap.compress(Bitmap.CompressFormat.PNG, 100, imageFile);
614             } catch (Exception e) {
615                 Slog.e(TAG, "saveImage: unable to save " + filePath, e);
616             } finally {
617                 IoUtils.closeQuietly(imageFile);
618             }
619         }
620 
621         @Override
matches(ImageWriteQueueItem item)622         public boolean matches(ImageWriteQueueItem item) {
623             return mFilePath.equals(item.mFilePath);
624         }
625 
626         @Override
updateFrom(ImageWriteQueueItem item)627         public void updateFrom(ImageWriteQueueItem item) {
628             mImage = item.mImage;
629         }
630 
631         @Override
toString()632         public String toString() {
633             return "ImageWriteQueueItem{path=" + mFilePath
634                     + ", image=(" + mImage.getWidth() + "x" + mImage.getHeight() + ")}";
635         }
636     }
637 }
638