OSDN Git Service

Prevent widget previews from showing empty images.
[android-x86/packages-apps-Trebuchet.git] / src / com / android / launcher3 / WidgetPreviewLoader.java
1 package com.android.launcher3;
2
3 import android.content.ComponentName;
4 import android.content.ContentValues;
5 import android.content.Context;
6 import android.content.pm.PackageInfo;
7 import android.content.pm.PackageManager.NameNotFoundException;
8 import android.content.pm.ResolveInfo;
9 import android.content.res.Resources;
10 import android.database.Cursor;
11 import android.database.SQLException;
12 import android.database.sqlite.SQLiteDatabase;
13 import android.database.sqlite.SQLiteOpenHelper;
14 import android.graphics.Bitmap;
15 import android.graphics.Bitmap.Config;
16 import android.graphics.BitmapFactory;
17 import android.graphics.Canvas;
18 import android.graphics.ColorMatrix;
19 import android.graphics.ColorMatrixColorFilter;
20 import android.graphics.Paint;
21 import android.graphics.PorterDuff;
22 import android.graphics.Rect;
23 import android.graphics.RectF;
24 import android.graphics.drawable.BitmapDrawable;
25 import android.graphics.drawable.Drawable;
26 import android.os.AsyncTask;
27 import android.os.Handler;
28 import android.util.Log;
29 import android.util.LongSparseArray;
30
31 import com.android.launcher3.compat.AppWidgetManagerCompat;
32 import com.android.launcher3.compat.UserHandleCompat;
33 import com.android.launcher3.compat.UserManagerCompat;
34 import com.android.launcher3.util.ComponentKey;
35 import com.android.launcher3.util.Thunk;
36 import com.android.launcher3.widget.WidgetCell;
37
38 import java.util.ArrayList;
39 import java.util.Collections;
40 import java.util.HashMap;
41 import java.util.HashSet;
42 import java.util.Set;
43 import java.util.WeakHashMap;
44 import java.util.concurrent.Callable;
45 import java.util.concurrent.ExecutionException;
46
47 public class WidgetPreviewLoader {
48
49     private static final String TAG = "WidgetPreviewLoader";
50     private static final boolean DEBUG = false;
51
52     private static final float WIDGET_PREVIEW_ICON_PADDING_PERCENTAGE = 0.25f;
53
54     private final HashMap<String, long[]> mPackageVersions = new HashMap<>();
55
56     /**
57      * Weak reference objects, do not prevent their referents from being made finalizable,
58      * finalized, and then reclaimed.
59      * Note: synchronized block used for this variable is expensive and the block should always
60      * be posted to a background thread.
61      */
62     @Thunk final Set<Bitmap> mUnusedBitmaps =
63             Collections.newSetFromMap(new WeakHashMap<Bitmap, Boolean>());
64
65     private final Context mContext;
66     private final IconCache mIconCache;
67     private final UserManagerCompat mUserManager;
68     private final AppWidgetManagerCompat mManager;
69     private CacheDb mDb;
70     private final int mProfileBadgeMargin;
71
72     private final MainThreadExecutor mMainThreadExecutor = new MainThreadExecutor();
73     @Thunk final Handler mWorkerHandler;
74
75     public WidgetPreviewLoader(Context context, IconCache iconCache) {
76         mContext = context;
77         mIconCache = iconCache;
78         mManager = AppWidgetManagerCompat.getInstance(context);
79         mUserManager = UserManagerCompat.getInstance(context);
80         mDb = new CacheDb(context);
81         mWorkerHandler = new Handler(LauncherModel.getWorkerLooper());
82         mProfileBadgeMargin = context.getResources()
83                 .getDimensionPixelSize(R.dimen.profile_badge_margin);
84     }
85
86     public void recreateWidgetPreviewDb() {
87         if (mDb != null) {
88             mDb.close();
89         }
90         mDb = new CacheDb(mContext);
91     }
92
93     /**
94      * Generates the widget preview on {@link AsyncTask#THREAD_POOL_EXECUTOR}. Must be
95      * called on UI thread
96      *
97      * @param o either {@link LauncherAppWidgetProviderInfo} or {@link ResolveInfo}
98      * @return a request id which can be used to cancel the request.
99      */
100     public PreviewLoadRequest getPreview(final Object o, int previewWidth,
101             int previewHeight, WidgetCell caller) {
102         String size = previewWidth + "x" + previewHeight;
103         WidgetCacheKey key = getObjectKey(o, size);
104
105         PreviewLoadTask task = new PreviewLoadTask(key, o, previewWidth, previewHeight, caller);
106         task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
107         return new PreviewLoadRequest(task);
108     }
109
110     /**
111      * The DB holds the generated previews for various components. Previews can also have different
112      * sizes (landscape vs portrait).
113      */
114     private static class CacheDb extends SQLiteOpenHelper {
115         private static final int DB_VERSION = 4;
116
117         private static final String TABLE_NAME = "shortcut_and_widget_previews";
118         private static final String COLUMN_COMPONENT = "componentName";
119         private static final String COLUMN_USER = "profileId";
120         private static final String COLUMN_SIZE = "size";
121         private static final String COLUMN_PACKAGE = "packageName";
122         private static final String COLUMN_LAST_UPDATED = "lastUpdated";
123         private static final String COLUMN_VERSION = "version";
124         private static final String COLUMN_PREVIEW_BITMAP = "preview_bitmap";
125
126         public CacheDb(Context context) {
127             super(context, LauncherFiles.WIDGET_PREVIEWS_DB, null, DB_VERSION);
128         }
129
130         @Override
131         public void onCreate(SQLiteDatabase database) {
132             database.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" +
133                     COLUMN_COMPONENT + " TEXT NOT NULL, " +
134                     COLUMN_USER + " INTEGER NOT NULL, " +
135                     COLUMN_SIZE + " TEXT NOT NULL, " +
136                     COLUMN_PACKAGE + " TEXT NOT NULL, " +
137                     COLUMN_LAST_UPDATED + " INTEGER NOT NULL DEFAULT 0, " +
138                     COLUMN_VERSION + " INTEGER NOT NULL DEFAULT 0, " +
139                     COLUMN_PREVIEW_BITMAP + " BLOB, " +
140                     "PRIMARY KEY (" + COLUMN_COMPONENT + ", " + COLUMN_USER + ", " + COLUMN_SIZE + ") " +
141                     ");");
142         }
143
144         @Override
145         public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
146             if (oldVersion != newVersion) {
147                 clearDB(db);
148             }
149         }
150
151         @Override
152         public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
153             if (oldVersion != newVersion) {
154                 clearDB(db);
155             }
156         }
157
158         private void clearDB(SQLiteDatabase db) {
159             db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
160             onCreate(db);
161         }
162     }
163
164     private WidgetCacheKey getObjectKey(Object o, String size) {
165         // should cache the string builder
166         if (o instanceof LauncherAppWidgetProviderInfo) {
167             LauncherAppWidgetProviderInfo info = (LauncherAppWidgetProviderInfo) o;
168             return new WidgetCacheKey(info.provider, mManager.getUser(info), size);
169         } else {
170             ResolveInfo info = (ResolveInfo) o;
171             return new WidgetCacheKey(
172                     new ComponentName(info.activityInfo.packageName, info.activityInfo.name),
173                     UserHandleCompat.myUserHandle(), size);
174         }
175     }
176
177     @Thunk void writeToDb(WidgetCacheKey key, long[] versions, Bitmap preview) {
178         ContentValues values = new ContentValues();
179         values.put(CacheDb.COLUMN_COMPONENT, key.componentName.flattenToString());
180         values.put(CacheDb.COLUMN_USER, mUserManager.getSerialNumberForUser(key.user));
181         values.put(CacheDb.COLUMN_SIZE, key.size);
182         values.put(CacheDb.COLUMN_PACKAGE, key.componentName.getPackageName());
183         values.put(CacheDb.COLUMN_VERSION, versions[0]);
184         values.put(CacheDb.COLUMN_LAST_UPDATED, versions[1]);
185         values.put(CacheDb.COLUMN_PREVIEW_BITMAP, Utilities.flattenBitmap(preview));
186         try {
187             mDb.getWritableDatabase().insertWithOnConflict(CacheDb.TABLE_NAME, null, values,
188                     SQLiteDatabase.CONFLICT_REPLACE);
189         } catch (SQLException e) {
190             Log.e(TAG, "Error saving image to DB", e);
191         }
192     }
193
194     public void removePackage(String packageName, UserHandleCompat user) {
195         removePackage(packageName, user, mUserManager.getSerialNumberForUser(user));
196     }
197
198     private void removePackage(String packageName, UserHandleCompat user, long userSerial) {
199         synchronized(mPackageVersions) {
200             mPackageVersions.remove(packageName);
201         }
202
203         try {
204             mDb.getWritableDatabase().delete(CacheDb.TABLE_NAME,
205                     CacheDb.COLUMN_PACKAGE + " = ? AND " + CacheDb.COLUMN_USER + " = ?",
206                     new String[] {packageName, Long.toString(userSerial)});
207         } catch (SQLException e) {
208             Log.e(TAG, "Unable to delete items from DB", e);
209         }
210     }
211
212     /**
213      * Updates the persistent DB:
214      *   1. Any preview generated for an old package version is removed
215      *   2. Any preview for an absent package is removed
216      * This ensures that we remove entries for packages which changed while the launcher was dead.
217      */
218     public void removeObsoletePreviews(ArrayList<Object> list) {
219         Utilities.assertWorkerThread();
220
221         LongSparseArray<HashSet<String>> validPackages = new LongSparseArray<>();
222
223         for (Object obj : list) {
224             final UserHandleCompat user;
225             final String pkg;
226             if (obj instanceof ResolveInfo) {
227                 user = UserHandleCompat.myUserHandle();
228                 pkg = ((ResolveInfo) obj).activityInfo.packageName;
229             } else {
230                 LauncherAppWidgetProviderInfo info = (LauncherAppWidgetProviderInfo) obj;
231                 user = mManager.getUser(info);
232                 pkg = info.provider.getPackageName();
233             }
234
235             final long userId = mUserManager.getSerialNumberForUser(user);
236             HashSet<String> packages = validPackages.get(userId);
237             if (packages == null) {
238                 packages = new HashSet<>();
239                 validPackages.put(userId, packages);
240             }
241             packages.add(pkg);
242         }
243
244         LongSparseArray<HashSet<String>> packagesToDelete = new LongSparseArray<>();
245         Cursor c = null;
246         try {
247             c = mDb.getReadableDatabase().query(CacheDb.TABLE_NAME,
248                     new String[] {CacheDb.COLUMN_USER, CacheDb.COLUMN_PACKAGE,
249                         CacheDb.COLUMN_LAST_UPDATED, CacheDb.COLUMN_VERSION},
250                     null, null, null, null, null);
251             while (c.moveToNext()) {
252                 long userId = c.getLong(0);
253                 String pkg = c.getString(1);
254                 long lastUpdated = c.getLong(2);
255                 long version = c.getLong(3);
256
257                 HashSet<String> packages = validPackages.get(userId);
258                 if (packages != null && packages.contains(pkg)) {
259                     long[] versions = getPackageVersion(pkg);
260                     if (versions[0] == version && versions[1] == lastUpdated) {
261                         // Every thing checks out
262                         continue;
263                     }
264                 }
265
266                 // We need to delete this package.
267                 packages = packagesToDelete.get(userId);
268                 if (packages == null) {
269                     packages = new HashSet<>();
270                     packagesToDelete.put(userId, packages);
271                 }
272                 packages.add(pkg);
273             }
274
275             for (int i = 0; i < packagesToDelete.size(); i++) {
276                 long userId = packagesToDelete.keyAt(i);
277                 UserHandleCompat user = mUserManager.getUserForSerialNumber(userId);
278                 for (String pkg : packagesToDelete.valueAt(i)) {
279                     removePackage(pkg, user, userId);
280                 }
281             }
282         } catch (SQLException e) {
283             Log.e(TAG, "Error updatating widget previews", e);
284         } finally {
285             if (c != null) {
286                 c.close();
287             }
288         }
289     }
290
291     /**
292      * Reads the preview bitmap from the DB or null if the preview is not in the DB.
293      */
294     @Thunk Bitmap readFromDb(WidgetCacheKey key, Bitmap recycle, PreviewLoadTask loadTask) {
295         Cursor cursor = null;
296         try {
297             cursor = mDb.getReadableDatabase().query(
298                     CacheDb.TABLE_NAME,
299                     new String[] { CacheDb.COLUMN_PREVIEW_BITMAP },
300                     CacheDb.COLUMN_COMPONENT + " = ? AND " + CacheDb.COLUMN_USER + " = ? AND " + CacheDb.COLUMN_SIZE + " = ?",
301                     new String[] {
302                             key.componentName.flattenToString(),
303                             Long.toString(mUserManager.getSerialNumberForUser(key.user)),
304                             key.size
305                     },
306                     null, null, null);
307             // If cancelled, skip getting the blob and decoding it into a bitmap
308             if (loadTask.isCancelled()) {
309                 return null;
310             }
311             if (cursor.moveToNext()) {
312                 byte[] blob = cursor.getBlob(0);
313                 BitmapFactory.Options opts = new BitmapFactory.Options();
314                 opts.inBitmap = recycle;
315                 try {
316                     if (!loadTask.isCancelled()) {
317                         return BitmapFactory.decodeByteArray(blob, 0, blob.length, opts);
318                     }
319                 } catch (Exception e) {
320                     return null;
321                 }
322             }
323         } catch (SQLException e) {
324             Log.w(TAG, "Error loading preview from DB", e);
325         } finally {
326             if (cursor != null) {
327                 cursor.close();
328             }
329         }
330         return null;
331     }
332
333     @Thunk Bitmap generatePreview(Launcher launcher, Object info, Bitmap recycle,
334             int previewWidth, int previewHeight, PreviewGenerateTask task) {
335         if (info instanceof LauncherAppWidgetProviderInfo) {
336             return generateWidgetPreview(launcher, (LauncherAppWidgetProviderInfo) info,
337                     previewWidth, recycle, null, task);
338         } else {
339             return generateShortcutPreview(launcher,
340                     (ResolveInfo) info, previewWidth, previewHeight, recycle, task);
341         }
342     }
343
344     public Bitmap generateWidgetPreview(Launcher launcher, LauncherAppWidgetProviderInfo info,
345             int maxPreviewWidth, Bitmap preview, int[] preScaledWidthOut, PreviewGenerateTask task) {
346         // Periodically check to bail out early.
347         if (task != null && task.isCancelled()) return null;
348
349         // Load the preview image if possible
350         if (maxPreviewWidth < 0) maxPreviewWidth = Integer.MAX_VALUE;
351
352         Drawable drawable = null;
353         if (info.previewImage != 0) {
354             drawable = mManager.loadPreview(info);
355             if (drawable != null) {
356                 drawable = mutateOnMainThread(drawable);
357             } else {
358                 Log.w(TAG, "Can't load widget preview drawable 0x" +
359                         Integer.toHexString(info.previewImage) + " for provider: " + info.provider);
360             }
361         }
362
363         // Periodically check to bail out early.
364         if (task != null && task.isCancelled()) return null;
365
366         final boolean widgetPreviewExists = (drawable != null);
367         final int spanX = info.spanX;
368         final int spanY = info.spanY;
369
370         int previewWidth;
371         int previewHeight;
372         Bitmap tileBitmap = null;
373
374         if (widgetPreviewExists) {
375             previewWidth = drawable.getIntrinsicWidth();
376             previewHeight = drawable.getIntrinsicHeight();
377         } else {
378             // Generate a preview image if we couldn't load one
379             tileBitmap = ((BitmapDrawable) mContext.getResources().getDrawable(
380                     R.drawable.widget_tile)).getBitmap();
381             previewWidth = tileBitmap.getWidth() * spanX;
382             previewHeight = tileBitmap.getHeight() * spanY;
383         }
384
385         // Scale to fit width only - let the widget preview be clipped in the
386         // vertical dimension
387         float scale = 1f;
388         if (preScaledWidthOut != null) {
389             preScaledWidthOut[0] = previewWidth;
390         }
391         if (previewWidth > maxPreviewWidth) {
392             scale = (maxPreviewWidth - 2 * mProfileBadgeMargin) / (float) (previewWidth);
393         }
394         if (scale != 1f) {
395             previewWidth = (int) (scale * previewWidth);
396             previewHeight = (int) (scale * previewHeight);
397         }
398
399         // If a bitmap is passed in, we use it; otherwise, we create a bitmap of the right size
400         final Canvas c = new Canvas();
401         if (preview == null) {
402             preview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
403             c.setBitmap(preview);
404         } else {
405             // Reusing bitmap. Clear it.
406             c.setBitmap(preview);
407             c.drawColor(0, PorterDuff.Mode.CLEAR);
408         }
409
410         // Periodically check to bail out early.
411         if (task != null && task.isCancelled()) return null;
412
413         // Draw the scaled preview into the final bitmap
414         int x = (preview.getWidth() - previewWidth) / 2;
415         if (widgetPreviewExists) {
416             drawable.setBounds(x, 0, x + previewWidth, previewHeight);
417             drawable.draw(c);
418         } else {
419             final Paint p = new Paint();
420             p.setFilterBitmap(true);
421             int appIconSize = launcher.getDeviceProfile().iconSizePx;
422
423             // draw the spanX x spanY tiles
424             final Rect src = new Rect(0, 0, tileBitmap.getWidth(), tileBitmap.getHeight());
425
426             float tileW = scale * tileBitmap.getWidth();
427             float tileH = scale * tileBitmap.getHeight();
428             final RectF dst = new RectF(0, 0, tileW, tileH);
429
430             float tx = x;
431             for (int i = 0; i < spanX; i++, tx += tileW) {
432                 float ty = 0;
433                 for (int j = 0; j < spanY; j++, ty += tileH) {
434                     dst.offsetTo(tx, ty);
435                     c.drawBitmap(tileBitmap, src, dst, p);
436                 }
437             }
438
439             // Draw the icon in the top left corner
440             // TODO: use top right for RTL
441             int minOffset = (int) (appIconSize * WIDGET_PREVIEW_ICON_PADDING_PERCENTAGE);
442             int smallestSide = Math.min(previewWidth, previewHeight);
443             float iconScale = Math.min((float) smallestSide / (appIconSize + 2 * minOffset), scale);
444
445             // Periodically check to bail out early.
446             if (task != null && task.isCancelled()) return null;
447
448             try {
449                 Drawable icon = mutateOnMainThread(mManager.loadIcon(info, mIconCache));
450                 if (icon != null) {
451                     int hoffset = (int) ((tileW - appIconSize * iconScale) / 2) + x;
452                     int yoffset = (int) ((tileH - appIconSize * iconScale) / 2);
453                     icon.setBounds(hoffset, yoffset,
454                             hoffset + (int) (appIconSize * iconScale),
455                             yoffset + (int) (appIconSize * iconScale));
456                     icon.draw(c);
457                 }
458             } catch (Resources.NotFoundException e) { }
459             c.setBitmap(null);
460         }
461         int imageHeight = Math.min(preview.getHeight(), previewHeight + mProfileBadgeMargin);
462         return mManager.getBadgeBitmap(info, preview, imageHeight);
463     }
464
465     private Bitmap generateShortcutPreview(Launcher launcher, ResolveInfo info, int maxWidth,
466                                            int maxHeight, Bitmap preview, PreviewGenerateTask task) {
467         // Periodically check to bail out early.
468         if (task != null && task.isCancelled()) return null;
469
470         final Canvas c = new Canvas();
471         if (preview == null) {
472             preview = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
473             c.setBitmap(preview);
474         } else if (preview.getWidth() != maxWidth || preview.getHeight() != maxHeight) {
475             throw new RuntimeException("Improperly sized bitmap passed as argument");
476         } else {
477             // Reusing bitmap. Clear it.
478             c.setBitmap(preview);
479             c.drawColor(0, PorterDuff.Mode.CLEAR);
480         }
481
482         // Periodically check to bail out early.
483         if (task != null && task.isCancelled()) return null;
484
485         Drawable icon = mutateOnMainThread(mIconCache.getFullResIcon(info.activityInfo));
486         icon.setFilterBitmap(true);
487
488         // Draw a desaturated/scaled version of the icon in the background as a watermark
489         ColorMatrix colorMatrix = new ColorMatrix();
490         colorMatrix.setSaturation(0);
491         icon.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
492         icon.setAlpha((int) (255 * 0.06f));
493
494         Resources res = mContext.getResources();
495         int paddingTop = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_top);
496         int paddingLeft = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_left);
497         int paddingRight = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_right);
498         int scaledIconWidth = (maxWidth - paddingLeft - paddingRight);
499         icon.setBounds(paddingLeft, paddingTop,
500                 paddingLeft + scaledIconWidth, paddingTop + scaledIconWidth);
501         icon.draw(c);
502
503         // Periodically check to bail out early.
504         if (task != null && task.isCancelled()) return null;
505
506         // Draw the final icon at top left corner.
507         // TODO: use top right for RTL
508         int appIconSize = launcher.getDeviceProfile().iconSizePx;
509
510         icon.setAlpha(255);
511         icon.setColorFilter(null);
512         icon.setBounds(0, 0, appIconSize, appIconSize);
513         icon.draw(c);
514
515         c.setBitmap(null);
516         return preview;
517     }
518
519     private Drawable mutateOnMainThread(final Drawable drawable) {
520         try {
521             return mMainThreadExecutor.submit(new Callable<Drawable>() {
522                 @Override
523                 public Drawable call() throws Exception {
524                     return drawable.mutate();
525                 }
526             }).get();
527         } catch (InterruptedException e) {
528             Thread.currentThread().interrupt();
529             throw new RuntimeException(e);
530         } catch (ExecutionException e) {
531             throw new RuntimeException(e);
532         }
533     }
534
535     /**
536      * @return an array of containing versionCode and lastUpdatedTime for the package.
537      */
538     @Thunk long[] getPackageVersion(String packageName) {
539         synchronized (mPackageVersions) {
540             long[] versions = mPackageVersions.get(packageName);
541             if (versions == null) {
542                 versions = new long[2];
543                 try {
544                     PackageInfo info = mContext.getPackageManager().getPackageInfo(packageName, 0);
545                     versions[0] = info.versionCode;
546                     versions[1] = info.lastUpdateTime;
547                 } catch (NameNotFoundException e) {
548                     Log.e(TAG, "PackageInfo not found", e);
549                 }
550                 mPackageVersions.put(packageName, versions);
551             }
552             return versions;
553         }
554     }
555
556     /**
557      * A request Id which can be used by the client to cancel any request.
558      */
559     public class PreviewLoadRequest {
560         @Thunk PreviewLoadTask mLoadTask;
561         @Thunk PreviewGenerateTask mGenerateTask;
562
563         public PreviewLoadRequest(PreviewLoadTask task) {
564             mLoadTask = task;
565         }
566
567         public void cleanup() {
568             mLoadTask.cancel(true);
569
570             if (mGenerateTask != null) {
571                 mGenerateTask.cancel(true);
572
573                 // This only handles the case where the PreviewGenerateTask is cancelled after the
574                 // task has successfully completed. In the other cases where it is cancelled while
575                 // the task is running, it will be cleaned up in the tasks's onCancelled() call,
576                 // and if cancelled while the task is writing to disk, it will be cancelled in the
577                 // task's onPostExecute() call.
578                 if (mGenerateTask.mBitmapToRecycle != null) {
579                     recycleBitmap(mGenerateTask.mBitmapToRecycle);
580                 }
581             }
582         }
583     }
584
585     /**
586      * Parent task to consolidate common data.
587      */
588     public abstract class PreviewTask extends AsyncTask<Void, Void, Bitmap> {
589         @Thunk final WidgetCacheKey mKey;
590         protected final Object mInfo;
591         protected final int mPreviewHeight;
592         protected final int mPreviewWidth;
593         protected final WidgetCell mCaller;
594         protected Bitmap mUnusedBitmap;
595
596         PreviewTask(WidgetCacheKey key, Object info, int previewWidth,
597                         int previewHeight, WidgetCell caller) {
598             mKey = key;
599             mInfo = info;
600             mPreviewHeight = previewHeight;
601             mPreviewWidth = previewWidth;
602             mCaller = caller;
603             if (DEBUG) {
604                 Log.d(TAG, String.format("%s, %s, %d, %d",
605                         mKey, mInfo, mPreviewHeight, mPreviewWidth));
606             }
607         }
608     }
609
610     /**
611      * This task's job is to load the preview if it is ready in the database. It will not generate
612      * a preview on it's own, because this tasks runs on a multi-threaded executor,
613      * and non-synchronous loading from {@link AppWidgetManagerCompat} can return null images.
614      */
615     public class PreviewLoadTask extends PreviewTask {
616         PreviewLoadTask(WidgetCacheKey key, Object info, int previewWidth,
617                 int previewHeight, WidgetCell caller) {
618             super(key, info, previewWidth, previewHeight, caller);
619         }
620
621         @Override
622         protected Bitmap doInBackground(Void... params) {
623             // If already cancelled before this gets to run in the background, then return early
624             if (isCancelled()) return null;
625
626             synchronized (mUnusedBitmaps) {
627                 // Check if we can re-use a bitmap
628                 for (Bitmap candidate : mUnusedBitmaps) {
629                     if (candidate != null && candidate.isMutable() &&
630                             candidate.getWidth() == mPreviewWidth &&
631                             candidate.getHeight() == mPreviewHeight) {
632                         mUnusedBitmap = candidate;
633                         mUnusedBitmaps.remove(mUnusedBitmap);
634                         break;
635                     }
636                 }
637             }
638
639             // creating a bitmap is expensive. Do not do this inside synchronized block.
640             if (mUnusedBitmap == null) {
641                 mUnusedBitmap = Bitmap.createBitmap(mPreviewWidth, mPreviewHeight, Config.ARGB_8888);
642             }
643
644             // If cancelled now, don't bother reading the preview from the DB
645             if (isCancelled()) return null;
646
647             return readFromDb(mKey, mUnusedBitmap, this);
648         }
649
650         @Override
651         protected void onPostExecute(final Bitmap preview) {
652             if (isCancelled()) return;
653
654             // We need to generate a new image
655             if (preview == null) {
656                 // Make sure we are still a valid request.
657                 PreviewLoadRequest request = mCaller.getActiveRequest();
658                 if (request == null || request.mLoadTask != this) return;
659
660                 request.mGenerateTask = new PreviewGenerateTask(mKey, mInfo, mPreviewWidth,
661                         mPreviewHeight, mCaller, mUnusedBitmap);
662
663                 // Must be run on default synchronous executor, otherwise images may fail to load.
664                 request.mGenerateTask.execute();
665             } else {
666                 applyPreviewIfActive(this, mCaller, preview);
667             }
668         }
669
670         @Override
671         protected void onCancelled(final Bitmap preview) {
672             recycleBitmap(preview);
673         }
674     }
675
676     /**
677      * This task's job is to generate preview images if they are not currently available in
678      * the database. It must be run on a single threaded worker, otherwise
679      * {@link AppWidgetManagerCompat} may return null images.
680      */
681     public class PreviewGenerateTask extends PreviewTask {
682         @Thunk long[] mVersions;
683         @Thunk Bitmap mBitmapToRecycle;
684
685         PreviewGenerateTask(WidgetCacheKey key, Object info, int previewWidth,
686                         int previewHeight, WidgetCell caller, Bitmap unusedBitmap) {
687             super(key, info, previewWidth, previewHeight, caller);
688             mUnusedBitmap = unusedBitmap;
689         }
690
691         @Override
692         protected Bitmap doInBackground(Void... params) {
693             if (isCancelled()) return null;
694
695             // Fetch the version info before we generate the preview, so that, in-case the
696             // app was updated while we are generating the preview, we use the old version info,
697             // which would gets re-written next time.
698             mVersions = getPackageVersion(mKey.componentName.getPackageName());
699
700             Launcher launcher = (Launcher) mCaller.getContext();
701
702             // Periodically check to bail out early.
703             if (isCancelled()) return null;
704
705             // it's not in the db... we need to generate it
706             return generatePreview(launcher, mInfo, mUnusedBitmap, mPreviewWidth, mPreviewHeight, this);
707         }
708
709         @Override
710         protected void onPostExecute(final Bitmap preview) {
711             if (preview == null || isCancelled()) return;
712
713             applyPreviewIfActive(this, mCaller, preview);
714
715             // Write the generated preview to the DB in the worker thread
716             if (mVersions != null) {
717                 mWorkerHandler.post(new Runnable() {
718                     @Override
719                     public void run() {
720                         if (!isCancelled()) {
721                             // If we are still using this preview, then write it to the DB and then
722                             // let the normal clear mechanism recycle the bitmap
723                             writeToDb(mKey, mVersions, preview);
724                             mBitmapToRecycle = preview;
725                         } else {
726                             // If we've already cancelled, then skip writing the bitmap to the DB
727                             // and manually add the bitmap back to the recycled set
728                             synchronized (mUnusedBitmaps) {
729                                 mUnusedBitmaps.add(preview);
730                             }
731                         }
732                     }
733                 });
734             } else {
735                 // If we don't need to write to disk, then ensure the preview gets recycled by
736                 // the normal clear mechanism
737                 mBitmapToRecycle = preview;
738             }
739         }
740
741         @Override
742         protected void onCancelled(final Bitmap preview) {
743             recycleBitmap(preview);
744         }
745     }
746
747     private void recycleBitmap(final Bitmap bitmap) {
748         if (bitmap != null) {
749             mWorkerHandler.post(new Runnable() {
750                 @Override
751                 public void run() {
752                     synchronized (mUnusedBitmaps) {
753                         mUnusedBitmaps.add(bitmap);
754                     }
755                 }
756             });
757         }
758     }
759
760     private static void applyPreviewIfActive(PreviewTask task, WidgetCell caller, Bitmap preview) {
761         // Verify that we are still the active preview task.
762         PreviewLoadRequest request = caller.getActiveRequest();
763         if (request != null && (request.mLoadTask == task || request.mGenerateTask == task)) {
764             caller.applyPreview(preview);
765         }
766     }
767
768     private static final class WidgetCacheKey extends ComponentKey {
769
770         // TODO: remove dependency on size
771         @Thunk final String size;
772
773         public WidgetCacheKey(ComponentName componentName, UserHandleCompat user, String size) {
774             super(componentName, user);
775             this.size = size;
776         }
777
778         @Override
779         public int hashCode() {
780             return super.hashCode() ^ size.hashCode();
781         }
782
783         @Override
784         public boolean equals(Object o) {
785             return super.equals(o) && ((WidgetCacheKey) o).size.equals(size);
786         }
787     }
788 }