OSDN Git Service

am 68207e25: (-s ours) Merge "Import translations. DO NOT MERGE" into ub-now-porkchop...
[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 final 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     /**
87      * Generates the widget preview on {@link AsyncTask#THREAD_POOL_EXECUTOR}. Must be
88      * called on UI thread
89      *
90      * @param o either {@link LauncherAppWidgetProviderInfo} or {@link ResolveInfo}
91      * @return a request id which can be used to cancel the request.
92      */
93     public PreviewLoadRequest getPreview(final Object o, int previewWidth,
94             int previewHeight, WidgetCell caller) {
95         String size = previewWidth + "x" + previewHeight;
96         WidgetCacheKey key = getObjectKey(o, size);
97
98         PreviewLoadTask task = new PreviewLoadTask(key, o, previewWidth, previewHeight, caller);
99         task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
100         return new PreviewLoadRequest(task);
101     }
102
103     /**
104      * The DB holds the generated previews for various components. Previews can also have different
105      * sizes (landscape vs portrait).
106      */
107     private static class CacheDb extends SQLiteOpenHelper {
108         private static final int DB_VERSION = 4;
109
110         private static final String TABLE_NAME = "shortcut_and_widget_previews";
111         private static final String COLUMN_COMPONENT = "componentName";
112         private static final String COLUMN_USER = "profileId";
113         private static final String COLUMN_SIZE = "size";
114         private static final String COLUMN_PACKAGE = "packageName";
115         private static final String COLUMN_LAST_UPDATED = "lastUpdated";
116         private static final String COLUMN_VERSION = "version";
117         private static final String COLUMN_PREVIEW_BITMAP = "preview_bitmap";
118
119         public CacheDb(Context context) {
120             super(context, LauncherFiles.WIDGET_PREVIEWS_DB, null, DB_VERSION);
121         }
122
123         @Override
124         public void onCreate(SQLiteDatabase database) {
125             database.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" +
126                     COLUMN_COMPONENT + " TEXT NOT NULL, " +
127                     COLUMN_USER + " INTEGER NOT NULL, " +
128                     COLUMN_SIZE + " TEXT NOT NULL, " +
129                     COLUMN_PACKAGE + " TEXT NOT NULL, " +
130                     COLUMN_LAST_UPDATED + " INTEGER NOT NULL DEFAULT 0, " +
131                     COLUMN_VERSION + " INTEGER NOT NULL DEFAULT 0, " +
132                     COLUMN_PREVIEW_BITMAP + " BLOB, " +
133                     "PRIMARY KEY (" + COLUMN_COMPONENT + ", " + COLUMN_USER + ", " + COLUMN_SIZE + ") " +
134                     ");");
135         }
136
137         @Override
138         public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
139             if (oldVersion != newVersion) {
140                 clearDB(db);
141             }
142         }
143
144         @Override
145         public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
146             if (oldVersion != newVersion) {
147                 clearDB(db);
148             }
149         }
150
151         private void clearDB(SQLiteDatabase db) {
152             db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
153             onCreate(db);
154         }
155     }
156
157     private WidgetCacheKey getObjectKey(Object o, String size) {
158         // should cache the string builder
159         if (o instanceof LauncherAppWidgetProviderInfo) {
160             LauncherAppWidgetProviderInfo info = (LauncherAppWidgetProviderInfo) o;
161             return new WidgetCacheKey(info.provider, mManager.getUser(info), size);
162         } else {
163             ResolveInfo info = (ResolveInfo) o;
164             return new WidgetCacheKey(
165                     new ComponentName(info.activityInfo.packageName, info.activityInfo.name),
166                     UserHandleCompat.myUserHandle(), size);
167         }
168     }
169
170     @Thunk void writeToDb(WidgetCacheKey key, long[] versions, Bitmap preview) {
171         ContentValues values = new ContentValues();
172         values.put(CacheDb.COLUMN_COMPONENT, key.componentName.flattenToShortString());
173         values.put(CacheDb.COLUMN_USER, mUserManager.getSerialNumberForUser(key.user));
174         values.put(CacheDb.COLUMN_SIZE, key.size);
175         values.put(CacheDb.COLUMN_PACKAGE, key.componentName.getPackageName());
176         values.put(CacheDb.COLUMN_VERSION, versions[0]);
177         values.put(CacheDb.COLUMN_LAST_UPDATED, versions[1]);
178         values.put(CacheDb.COLUMN_PREVIEW_BITMAP, Utilities.flattenBitmap(preview));
179
180         try {
181             mDb.getWritableDatabase().insertWithOnConflict(CacheDb.TABLE_NAME, null, values,
182                     SQLiteDatabase.CONFLICT_REPLACE);
183         } catch (SQLException e) {
184             Log.e(TAG, "Error saving image to DB", e);
185         }
186     }
187
188     public void removePackage(String packageName, UserHandleCompat user) {
189         removePackage(packageName, user, mUserManager.getSerialNumberForUser(user));
190     }
191
192     private void removePackage(String packageName, UserHandleCompat user, long userSerial) {
193         synchronized(mPackageVersions) {
194             mPackageVersions.remove(packageName);
195         }
196
197         try {
198             mDb.getWritableDatabase().delete(CacheDb.TABLE_NAME,
199                     CacheDb.COLUMN_PACKAGE + " = ? AND " + CacheDb.COLUMN_USER + " = ?",
200                     new String[] {packageName, Long.toString(userSerial)});
201         } catch (SQLException e) {
202             Log.e(TAG, "Unable to delete items from DB", e);
203         }
204     }
205
206     /**
207      * Updates the persistent DB:
208      *   1. Any preview generated for an old package version is removed
209      *   2. Any preview for an absent package is removed
210      * This ensures that we remove entries for packages which changed while the launcher was dead.
211      */
212     public void removeObsoletePreviews(ArrayList<Object> list) {
213         Utilities.assertWorkerThread();
214
215         LongSparseArray<HashSet<String>> validPackages = new LongSparseArray<>();
216
217         for (Object obj : list) {
218             final UserHandleCompat user;
219             final String pkg;
220             if (obj instanceof ResolveInfo) {
221                 user = UserHandleCompat.myUserHandle();
222                 pkg = ((ResolveInfo) obj).activityInfo.packageName;
223             } else {
224                 LauncherAppWidgetProviderInfo info = (LauncherAppWidgetProviderInfo) obj;
225                 user = mManager.getUser(info);
226                 pkg = info.provider.getPackageName();
227             }
228
229             final long userId = mUserManager.getSerialNumberForUser(user);
230             HashSet<String> packages = validPackages.get(userId);
231             if (packages == null) {
232                 packages = new HashSet<>();
233                 validPackages.put(userId, packages);
234             }
235             packages.add(pkg);
236         }
237
238         LongSparseArray<HashSet<String>> packagesToDelete = new LongSparseArray<>();
239         Cursor c = null;
240         try {
241             c = mDb.getReadableDatabase().query(CacheDb.TABLE_NAME,
242                     new String[] {CacheDb.COLUMN_USER, CacheDb.COLUMN_PACKAGE,
243                         CacheDb.COLUMN_LAST_UPDATED, CacheDb.COLUMN_VERSION},
244                     null, null, null, null, null);
245             while (c.moveToNext()) {
246                 long userId = c.getLong(0);
247                 String pkg = c.getString(1);
248                 long lastUpdated = c.getLong(2);
249                 long version = c.getLong(3);
250
251                 HashSet<String> packages = validPackages.get(userId);
252                 if (packages != null && packages.contains(pkg)) {
253                     long[] versions = getPackageVersion(pkg);
254                     if (versions[0] == version && versions[1] == lastUpdated) {
255                         // Every thing checks out
256                         continue;
257                     }
258                 }
259
260                 // We need to delete this package.
261                 packages = packagesToDelete.get(userId);
262                 if (packages == null) {
263                     packages = new HashSet<>();
264                     packagesToDelete.put(userId, packages);
265                 }
266                 packages.add(pkg);
267             }
268
269             for (int i = 0; i < packagesToDelete.size(); i++) {
270                 long userId = packagesToDelete.keyAt(i);
271                 UserHandleCompat user = mUserManager.getUserForSerialNumber(userId);
272                 for (String pkg : packagesToDelete.valueAt(i)) {
273                     removePackage(pkg, user, userId);
274                 }
275             }
276         } catch (SQLException e) {
277             Log.e(TAG, "Error updatating widget previews", e);
278         } finally {
279             if (c != null) {
280                 c.close();
281             }
282         }
283     }
284
285     /**
286      * Reads the preview bitmap from the DB or null if the preview is not in the DB.
287      */
288     @Thunk Bitmap readFromDb(WidgetCacheKey key, Bitmap recycle, PreviewLoadTask loadTask) {
289         Cursor cursor = null;
290         try {
291             cursor = mDb.getReadableDatabase().query(
292                     CacheDb.TABLE_NAME,
293                     new String[] { CacheDb.COLUMN_PREVIEW_BITMAP },
294                     CacheDb.COLUMN_COMPONENT + " = ? AND " + CacheDb.COLUMN_USER + " = ? AND " + CacheDb.COLUMN_SIZE + " = ?",
295                     new String[] {
296                             key.componentName.flattenToString(),
297                             Long.toString(mUserManager.getSerialNumberForUser(key.user)),
298                             key.size
299                     },
300                     null, null, null);
301             // If cancelled, skip getting the blob and decoding it into a bitmap
302             if (loadTask.isCancelled()) {
303                 return null;
304             }
305             if (cursor.moveToNext()) {
306                 byte[] blob = cursor.getBlob(0);
307                 BitmapFactory.Options opts = new BitmapFactory.Options();
308                 opts.inBitmap = recycle;
309                 try {
310                     if (!loadTask.isCancelled()) {
311                         return BitmapFactory.decodeByteArray(blob, 0, blob.length, opts);
312                     }
313                 } catch (Exception e) {
314                     return null;
315                 }
316             }
317         } catch (SQLException e) {
318             Log.w(TAG, "Error loading preview from DB", e);
319         } finally {
320             if (cursor != null) {
321                 cursor.close();
322             }
323         }
324         return null;
325     }
326
327     @Thunk Bitmap generatePreview(Launcher launcher, Object info, Bitmap recycle,
328             int previewWidth, int previewHeight) {
329         if (info instanceof LauncherAppWidgetProviderInfo) {
330             return generateWidgetPreview(launcher, (LauncherAppWidgetProviderInfo) info,
331                     previewWidth, recycle, null);
332         } else {
333             return generateShortcutPreview(launcher,
334                     (ResolveInfo) info, previewWidth, previewHeight, recycle);
335         }
336     }
337
338     public Bitmap generateWidgetPreview(Launcher launcher, LauncherAppWidgetProviderInfo info,
339             int maxPreviewWidth, Bitmap preview, int[] preScaledWidthOut) {
340         // Load the preview image if possible
341         if (maxPreviewWidth < 0) maxPreviewWidth = Integer.MAX_VALUE;
342
343         Drawable drawable = null;
344         if (info.previewImage != 0) {
345             drawable = mManager.loadPreview(info);
346             if (drawable != null) {
347                 drawable = mutateOnMainThread(drawable);
348             } else {
349                 Log.w(TAG, "Can't load widget preview drawable 0x" +
350                         Integer.toHexString(info.previewImage) + " for provider: " + info.provider);
351             }
352         }
353
354         final boolean widgetPreviewExists = (drawable != null);
355         final int spanX = info.spanX;
356         final int spanY = info.spanY;
357
358         int previewWidth;
359         int previewHeight;
360         Bitmap tileBitmap = null;
361
362         if (widgetPreviewExists) {
363             previewWidth = drawable.getIntrinsicWidth();
364             previewHeight = drawable.getIntrinsicHeight();
365         } else {
366             // Generate a preview image if we couldn't load one
367             tileBitmap = ((BitmapDrawable) mContext.getResources().getDrawable(
368                     R.drawable.widget_tile)).getBitmap();
369             previewWidth = tileBitmap.getWidth() * spanX;
370             previewHeight = tileBitmap.getHeight() * spanY;
371         }
372
373         // Scale to fit width only - let the widget preview be clipped in the
374         // vertical dimension
375         float scale = 1f;
376         if (preScaledWidthOut != null) {
377             preScaledWidthOut[0] = previewWidth;
378         }
379         if (previewWidth > maxPreviewWidth) {
380             scale = (maxPreviewWidth - 2 * mProfileBadgeMargin) / (float) (previewWidth);
381         }
382         if (scale != 1f) {
383             previewWidth = (int) (scale * previewWidth);
384             previewHeight = (int) (scale * previewHeight);
385         }
386
387         // If a bitmap is passed in, we use it; otherwise, we create a bitmap of the right size
388         final Canvas c = new Canvas();
389         if (preview == null) {
390             preview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
391             c.setBitmap(preview);
392         } else {
393             // Reusing bitmap. Clear it.
394             c.setBitmap(preview);
395             c.drawColor(0, PorterDuff.Mode.CLEAR);
396         }
397
398         // Draw the scaled preview into the final bitmap
399         int x = (preview.getWidth() - previewWidth) / 2;
400         if (widgetPreviewExists) {
401             drawable.setBounds(x, 0, x + previewWidth, previewHeight);
402             drawable.draw(c);
403         } else {
404             final Paint p = new Paint();
405             p.setFilterBitmap(true);
406             int appIconSize = launcher.getDeviceProfile().iconSizePx;
407
408             // draw the spanX x spanY tiles
409             final Rect src = new Rect(0, 0, tileBitmap.getWidth(), tileBitmap.getHeight());
410
411             float tileW = scale * tileBitmap.getWidth();
412             float tileH = scale * tileBitmap.getHeight();
413             final RectF dst = new RectF(0, 0, tileW, tileH);
414
415             float tx = x;
416             for (int i = 0; i < spanX; i++, tx += tileW) {
417                 float ty = 0;
418                 for (int j = 0; j < spanY; j++, ty += tileH) {
419                     dst.offsetTo(tx, ty);
420                     c.drawBitmap(tileBitmap, src, dst, p);
421                 }
422             }
423
424             // Draw the icon in the top left corner
425             // TODO: use top right for RTL
426             int minOffset = (int) (appIconSize * WIDGET_PREVIEW_ICON_PADDING_PERCENTAGE);
427             int smallestSide = Math.min(previewWidth, previewHeight);
428             float iconScale = Math.min((float) smallestSide / (appIconSize + 2 * minOffset), scale);
429
430             try {
431                 Drawable icon = mutateOnMainThread(mManager.loadIcon(info, mIconCache));
432                 if (icon != null) {
433                     int hoffset = (int) ((tileW - appIconSize * iconScale) / 2) + x;
434                     int yoffset = (int) ((tileH - appIconSize * iconScale) / 2);
435                     icon.setBounds(hoffset, yoffset,
436                             hoffset + (int) (appIconSize * iconScale),
437                             yoffset + (int) (appIconSize * iconScale));
438                     icon.draw(c);
439                 }
440             } catch (Resources.NotFoundException e) { }
441             c.setBitmap(null);
442         }
443         int imageHeight = Math.min(preview.getHeight(), previewHeight + mProfileBadgeMargin);
444         return mManager.getBadgeBitmap(info, preview, imageHeight);
445     }
446
447     private Bitmap generateShortcutPreview(
448             Launcher launcher, ResolveInfo info, int maxWidth, int maxHeight, Bitmap preview) {
449         final Canvas c = new Canvas();
450         if (preview == null) {
451             preview = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
452             c.setBitmap(preview);
453         } else if (preview.getWidth() != maxWidth || preview.getHeight() != maxHeight) {
454             throw new RuntimeException("Improperly sized bitmap passed as argument");
455         } else {
456             // Reusing bitmap. Clear it.
457             c.setBitmap(preview);
458             c.drawColor(0, PorterDuff.Mode.CLEAR);
459         }
460
461         Drawable icon = mutateOnMainThread(mIconCache.getFullResIcon(info.activityInfo));
462         icon.setFilterBitmap(true);
463
464         // Draw a desaturated/scaled version of the icon in the background as a watermark
465         ColorMatrix colorMatrix = new ColorMatrix();
466         colorMatrix.setSaturation(0);
467         icon.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
468         icon.setAlpha((int) (255 * 0.06f));
469
470         Resources res = mContext.getResources();
471         int paddingTop = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_top);
472         int paddingLeft = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_left);
473         int paddingRight = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_right);
474         int scaledIconWidth = (maxWidth - paddingLeft - paddingRight);
475         icon.setBounds(paddingLeft, paddingTop,
476                 paddingLeft + scaledIconWidth, paddingTop + scaledIconWidth);
477         icon.draw(c);
478
479         // Draw the final icon at top left corner.
480         // TODO: use top right for RTL
481         int appIconSize = launcher.getDeviceProfile().iconSizePx;
482
483         icon.setAlpha(255);
484         icon.setColorFilter(null);
485         icon.setBounds(0, 0, appIconSize, appIconSize);
486         icon.draw(c);
487
488         c.setBitmap(null);
489         return preview;
490     }
491
492     private Drawable mutateOnMainThread(final Drawable drawable) {
493         try {
494             return mMainThreadExecutor.submit(new Callable<Drawable>() {
495                 @Override
496                 public Drawable call() throws Exception {
497                     return drawable.mutate();
498                 }
499             }).get();
500         } catch (InterruptedException e) {
501             Thread.currentThread().interrupt();
502             throw new RuntimeException(e);
503         } catch (ExecutionException e) {
504             throw new RuntimeException(e);
505         }
506     }
507
508     /**
509      * @return an array of containing versionCode and lastUpdatedTime for the package.
510      */
511     @Thunk long[] getPackageVersion(String packageName) {
512         synchronized (mPackageVersions) {
513             long[] versions = mPackageVersions.get(packageName);
514             if (versions == null) {
515                 versions = new long[2];
516                 try {
517                     PackageInfo info = mContext.getPackageManager().getPackageInfo(packageName, 0);
518                     versions[0] = info.versionCode;
519                     versions[1] = info.lastUpdateTime;
520                 } catch (NameNotFoundException e) {
521                     Log.e(TAG, "PackageInfo not found", e);
522                 }
523                 mPackageVersions.put(packageName, versions);
524             }
525             return versions;
526         }
527     }
528
529     /**
530      * A request Id which can be used by the client to cancel any request.
531      */
532     public class PreviewLoadRequest {
533
534         @Thunk final PreviewLoadTask mTask;
535
536         public PreviewLoadRequest(PreviewLoadTask task) {
537             mTask = task;
538         }
539
540         public void cleanup() {
541             if (mTask != null) {
542                 mTask.cancel(true);
543             }
544
545             // This only handles the case where the PreviewLoadTask is cancelled after the task has
546             // successfully completed (including having written to disk when necessary).  In the
547             // other cases where it is cancelled while the task is running, it will be cleaned up
548             // in the tasks's onCancelled() call, and if cancelled while the task is writing to
549             // disk, it will be cancelled in the task's onPostExecute() call.
550             if (mTask.mBitmapToRecycle != null) {
551                 mWorkerHandler.post(new Runnable() {
552                     @Override
553                     public void run() {
554                         synchronized (mUnusedBitmaps) {
555                             mUnusedBitmaps.add(mTask.mBitmapToRecycle);
556                         }
557                         mTask.mBitmapToRecycle = null;
558                     }
559                 });
560             }
561         }
562     }
563
564     public class PreviewLoadTask extends AsyncTask<Void, Void, Bitmap> {
565         @Thunk final WidgetCacheKey mKey;
566         private final Object mInfo;
567         private final int mPreviewHeight;
568         private final int mPreviewWidth;
569         private final WidgetCell mCaller;
570         @Thunk long[] mVersions;
571         @Thunk Bitmap mBitmapToRecycle;
572
573         PreviewLoadTask(WidgetCacheKey key, Object info, int previewWidth,
574                 int previewHeight, WidgetCell caller) {
575             mKey = key;
576             mInfo = info;
577             mPreviewHeight = previewHeight;
578             mPreviewWidth = previewWidth;
579             mCaller = caller;
580             if (DEBUG) {
581                 Log.d(TAG, String.format("%s, %s, %d, %d",
582                         mKey, mInfo, mPreviewHeight, mPreviewWidth));
583             }
584         }
585
586         @Override
587         protected Bitmap doInBackground(Void... params) {
588             Bitmap unusedBitmap = null;
589
590             // If already cancelled before this gets to run in the background, then return early
591             if (isCancelled()) {
592                 return null;
593             }
594             synchronized (mUnusedBitmaps) {
595                 // Check if we can re-use a bitmap
596                 for (Bitmap candidate : mUnusedBitmaps) {
597                     if (candidate != null && candidate.isMutable() &&
598                             candidate.getWidth() == mPreviewWidth &&
599                             candidate.getHeight() == mPreviewHeight) {
600                         unusedBitmap = candidate;
601                         mUnusedBitmaps.remove(unusedBitmap);
602                         break;
603                     }
604                 }
605             }
606
607             // creating a bitmap is expensive. Do not do this inside synchronized block.
608             if (unusedBitmap == null) {
609                 unusedBitmap = Bitmap.createBitmap(mPreviewWidth, mPreviewHeight, Config.ARGB_8888);
610             }
611             // If cancelled now, don't bother reading the preview from the DB
612             if (isCancelled()) {
613                 return unusedBitmap;
614             }
615             Bitmap preview = readFromDb(mKey, unusedBitmap, this);
616             // Only consider generating the preview if we have not cancelled the task already
617             if (!isCancelled() && preview == null) {
618                 // Fetch the version info before we generate the preview, so that, in-case the
619                 // app was updated while we are generating the preview, we use the old version info,
620                 // which would gets re-written next time.
621                 mVersions = getPackageVersion(mKey.componentName.getPackageName());
622
623                 Launcher launcher = (Launcher) mCaller.getContext();
624
625                 // it's not in the db... we need to generate it
626                 preview = generatePreview(launcher, mInfo, unusedBitmap, mPreviewWidth, mPreviewHeight);
627             }
628             return preview;
629         }
630
631         @Override
632         protected void onPostExecute(final Bitmap preview) {
633             mCaller.applyPreview(preview);
634
635             // Write the generated preview to the DB in the worker thread
636             if (mVersions != null) {
637                 mWorkerHandler.post(new Runnable() {
638                     @Override
639                     public void run() {
640                         if (!isCancelled()) {
641                             // If we are still using this preview, then write it to the DB and then
642                             // let the normal clear mechanism recycle the bitmap
643                             writeToDb(mKey, mVersions, preview);
644                             mBitmapToRecycle = preview;
645                         } else {
646                             // If we've already cancelled, then skip writing the bitmap to the DB
647                             // and manually add the bitmap back to the recycled set
648                             synchronized (mUnusedBitmaps) {
649                                 mUnusedBitmaps.add(preview);
650                             }
651                         }
652                     }
653                 });
654             } else {
655                 // If we don't need to write to disk, then ensure the preview gets recycled by
656                 // the normal clear mechanism
657                 mBitmapToRecycle = preview;
658             }
659         }
660
661         @Override
662         protected void onCancelled(final Bitmap preview) {
663             // If we've cancelled while the task is running, then can return the bitmap to the
664             // recycled set immediately. Otherwise, it will be recycled after the preview is written
665             // to disk.
666             if (preview != null) {
667                 mWorkerHandler.post(new Runnable() {
668                     @Override
669                     public void run() {
670                         synchronized (mUnusedBitmaps) {
671                             mUnusedBitmaps.add(preview);
672                         }
673                     }
674                 });
675             }
676         }
677     }
678
679     private static final class WidgetCacheKey extends ComponentKey {
680
681         // TODO: remove dependency on size
682         @Thunk final String size;
683
684         public WidgetCacheKey(ComponentName componentName, UserHandleCompat user, String size) {
685             super(componentName, user);
686             this.size = size;
687         }
688
689         @Override
690         public int hashCode() {
691             return super.hashCode() ^ size.hashCode();
692         }
693
694         @Override
695         public boolean equals(Object o) {
696             return super.equals(o) && ((WidgetCacheKey) o).size.equals(size);
697         }
698     }
699 }