1 package com.android.launcher3;
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;
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;
38 import java.util.ArrayList;
39 import java.util.Collections;
40 import java.util.HashMap;
41 import java.util.HashSet;
43 import java.util.WeakHashMap;
44 import java.util.concurrent.Callable;
45 import java.util.concurrent.ExecutionException;
47 public class WidgetPreviewLoader {
49 private static final String TAG = "WidgetPreviewLoader";
50 private static final boolean DEBUG = false;
52 private static final float WIDGET_PREVIEW_ICON_PADDING_PERCENTAGE = 0.25f;
54 private final HashMap<String, long[]> mPackageVersions = new HashMap<>();
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.
62 @Thunk final Set<Bitmap> mUnusedBitmaps =
63 Collections.newSetFromMap(new WeakHashMap<Bitmap, Boolean>());
65 private final Context mContext;
66 private final IconCache mIconCache;
67 private final UserManagerCompat mUserManager;
68 private final AppWidgetManagerCompat mManager;
70 private final int mProfileBadgeMargin;
72 private final MainThreadExecutor mMainThreadExecutor = new MainThreadExecutor();
73 @Thunk final Handler mWorkerHandler;
75 public WidgetPreviewLoader(Context context, IconCache iconCache) {
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);
86 public void recreateWidgetPreviewDb() {
90 mDb = new CacheDb(mContext);
94 * Generates the widget preview on {@link AsyncTask#THREAD_POOL_EXECUTOR}. Must be
97 * @param o either {@link LauncherAppWidgetProviderInfo} or {@link ResolveInfo}
98 * @return a request id which can be used to cancel the request.
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);
105 PreviewLoadTask task = new PreviewLoadTask(key, o, previewWidth, previewHeight, caller);
106 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
107 return new PreviewLoadRequest(task);
111 * The DB holds the generated previews for various components. Previews can also have different
112 * sizes (landscape vs portrait).
114 private static class CacheDb extends SQLiteOpenHelper {
115 private static final int DB_VERSION = 4;
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";
126 public CacheDb(Context context) {
127 super(context, LauncherFiles.WIDGET_PREVIEWS_DB, null, DB_VERSION);
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 + ") " +
145 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
146 if (oldVersion != newVersion) {
152 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
153 if (oldVersion != newVersion) {
158 private void clearDB(SQLiteDatabase db) {
159 db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
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);
170 ResolveInfo info = (ResolveInfo) o;
171 return new WidgetCacheKey(
172 new ComponentName(info.activityInfo.packageName, info.activityInfo.name),
173 UserHandleCompat.myUserHandle(), size);
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));
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);
194 public void removePackage(String packageName, UserHandleCompat user) {
195 removePackage(packageName, user, mUserManager.getSerialNumberForUser(user));
198 private void removePackage(String packageName, UserHandleCompat user, long userSerial) {
199 synchronized(mPackageVersions) {
200 mPackageVersions.remove(packageName);
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);
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.
218 public void removeObsoletePreviews(ArrayList<Object> list) {
219 Utilities.assertWorkerThread();
221 LongSparseArray<HashSet<String>> validPackages = new LongSparseArray<>();
223 for (Object obj : list) {
224 final UserHandleCompat user;
226 if (obj instanceof ResolveInfo) {
227 user = UserHandleCompat.myUserHandle();
228 pkg = ((ResolveInfo) obj).activityInfo.packageName;
230 LauncherAppWidgetProviderInfo info = (LauncherAppWidgetProviderInfo) obj;
231 user = mManager.getUser(info);
232 pkg = info.provider.getPackageName();
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);
244 LongSparseArray<HashSet<String>> packagesToDelete = new LongSparseArray<>();
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);
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
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);
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);
282 } catch (SQLException e) {
283 Log.e(TAG, "Error updatating widget previews", e);
292 * Reads the preview bitmap from the DB or null if the preview is not in the DB.
294 @Thunk Bitmap readFromDb(WidgetCacheKey key, Bitmap recycle, PreviewLoadTask loadTask) {
295 Cursor cursor = null;
297 cursor = mDb.getReadableDatabase().query(
299 new String[] { CacheDb.COLUMN_PREVIEW_BITMAP },
300 CacheDb.COLUMN_COMPONENT + " = ? AND " + CacheDb.COLUMN_USER + " = ? AND " + CacheDb.COLUMN_SIZE + " = ?",
302 key.componentName.flattenToString(),
303 Long.toString(mUserManager.getSerialNumberForUser(key.user)),
307 // If cancelled, skip getting the blob and decoding it into a bitmap
308 if (loadTask.isCancelled()) {
311 if (cursor.moveToNext()) {
312 byte[] blob = cursor.getBlob(0);
313 BitmapFactory.Options opts = new BitmapFactory.Options();
314 opts.inBitmap = recycle;
316 if (!loadTask.isCancelled()) {
317 return BitmapFactory.decodeByteArray(blob, 0, blob.length, opts);
319 } catch (Exception e) {
323 } catch (SQLException e) {
324 Log.w(TAG, "Error loading preview from DB", e);
326 if (cursor != null) {
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);
339 return generateShortcutPreview(launcher,
340 (ResolveInfo) info, previewWidth, previewHeight, recycle, task);
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;
349 // Load the preview image if possible
350 if (maxPreviewWidth < 0) maxPreviewWidth = Integer.MAX_VALUE;
352 Drawable drawable = null;
353 if (info.previewImage != 0) {
354 drawable = mManager.loadPreview(info);
355 if (drawable != null) {
356 drawable = mutateOnMainThread(drawable);
358 Log.w(TAG, "Can't load widget preview drawable 0x" +
359 Integer.toHexString(info.previewImage) + " for provider: " + info.provider);
363 // Periodically check to bail out early.
364 if (task != null && task.isCancelled()) return null;
366 final boolean widgetPreviewExists = (drawable != null);
367 final int spanX = info.spanX;
368 final int spanY = info.spanY;
372 Bitmap tileBitmap = null;
374 if (widgetPreviewExists) {
375 previewWidth = drawable.getIntrinsicWidth();
376 previewHeight = drawable.getIntrinsicHeight();
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;
385 // Scale to fit width only - let the widget preview be clipped in the
386 // vertical dimension
388 if (preScaledWidthOut != null) {
389 preScaledWidthOut[0] = previewWidth;
391 if (previewWidth > maxPreviewWidth) {
392 scale = (maxPreviewWidth - 2 * mProfileBadgeMargin) / (float) (previewWidth);
395 previewWidth = (int) (scale * previewWidth);
396 previewHeight = (int) (scale * previewHeight);
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);
405 // Reusing bitmap. Clear it.
406 c.setBitmap(preview);
407 c.drawColor(0, PorterDuff.Mode.CLEAR);
410 // Periodically check to bail out early.
411 if (task != null && task.isCancelled()) return null;
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);
419 final Paint p = new Paint();
420 p.setFilterBitmap(true);
421 int appIconSize = launcher.getDeviceProfile().iconSizePx;
423 // draw the spanX x spanY tiles
424 final Rect src = new Rect(0, 0, tileBitmap.getWidth(), tileBitmap.getHeight());
426 float tileW = scale * tileBitmap.getWidth();
427 float tileH = scale * tileBitmap.getHeight();
428 final RectF dst = new RectF(0, 0, tileW, tileH);
431 for (int i = 0; i < spanX; i++, tx += tileW) {
433 for (int j = 0; j < spanY; j++, ty += tileH) {
434 dst.offsetTo(tx, ty);
435 c.drawBitmap(tileBitmap, src, dst, p);
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);
445 // Periodically check to bail out early.
446 if (task != null && task.isCancelled()) return null;
449 Drawable icon = mutateOnMainThread(mManager.loadIcon(info, mIconCache));
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));
458 } catch (Resources.NotFoundException e) { }
461 int imageHeight = Math.min(preview.getHeight(), previewHeight + mProfileBadgeMargin);
462 return mManager.getBadgeBitmap(info, preview, imageHeight);
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;
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");
477 // Reusing bitmap. Clear it.
478 c.setBitmap(preview);
479 c.drawColor(0, PorterDuff.Mode.CLEAR);
482 // Periodically check to bail out early.
483 if (task != null && task.isCancelled()) return null;
485 Drawable icon = mutateOnMainThread(mIconCache.getFullResIcon(info.activityInfo));
486 icon.setFilterBitmap(true);
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));
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);
503 // Periodically check to bail out early.
504 if (task != null && task.isCancelled()) return null;
506 // Draw the final icon at top left corner.
507 // TODO: use top right for RTL
508 int appIconSize = launcher.getDeviceProfile().iconSizePx;
511 icon.setColorFilter(null);
512 icon.setBounds(0, 0, appIconSize, appIconSize);
519 private Drawable mutateOnMainThread(final Drawable drawable) {
521 return mMainThreadExecutor.submit(new Callable<Drawable>() {
523 public Drawable call() throws Exception {
524 return drawable.mutate();
527 } catch (InterruptedException e) {
528 Thread.currentThread().interrupt();
529 throw new RuntimeException(e);
530 } catch (ExecutionException e) {
531 throw new RuntimeException(e);
536 * @return an array of containing versionCode and lastUpdatedTime for the package.
538 @Thunk long[] getPackageVersion(String packageName) {
539 synchronized (mPackageVersions) {
540 long[] versions = mPackageVersions.get(packageName);
541 if (versions == null) {
542 versions = new long[2];
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);
550 mPackageVersions.put(packageName, versions);
557 * A request Id which can be used by the client to cancel any request.
559 public class PreviewLoadRequest {
560 @Thunk PreviewLoadTask mLoadTask;
561 @Thunk PreviewGenerateTask mGenerateTask;
563 public PreviewLoadRequest(PreviewLoadTask task) {
567 public void cleanup() {
568 mLoadTask.cancel(true);
570 if (mGenerateTask != null) {
571 mGenerateTask.cancel(true);
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);
586 * Parent task to consolidate common data.
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;
596 PreviewTask(WidgetCacheKey key, Object info, int previewWidth,
597 int previewHeight, WidgetCell caller) {
600 mPreviewHeight = previewHeight;
601 mPreviewWidth = previewWidth;
604 Log.d(TAG, String.format("%s, %s, %d, %d",
605 mKey, mInfo, mPreviewHeight, mPreviewWidth));
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.
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);
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;
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);
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);
644 // If cancelled now, don't bother reading the preview from the DB
645 if (isCancelled()) return null;
647 return readFromDb(mKey, mUnusedBitmap, this);
651 protected void onPostExecute(final Bitmap preview) {
652 if (isCancelled()) return;
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;
660 request.mGenerateTask = new PreviewGenerateTask(mKey, mInfo, mPreviewWidth,
661 mPreviewHeight, mCaller, mUnusedBitmap);
663 // Must be run on default synchronous executor, otherwise images may fail to load.
664 request.mGenerateTask.execute();
666 applyPreviewIfActive(this, mCaller, preview);
671 protected void onCancelled(final Bitmap preview) {
672 recycleBitmap(preview);
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.
681 public class PreviewGenerateTask extends PreviewTask {
682 @Thunk long[] mVersions;
683 @Thunk Bitmap mBitmapToRecycle;
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;
692 protected Bitmap doInBackground(Void... params) {
693 if (isCancelled()) return null;
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());
700 Launcher launcher = (Launcher) mCaller.getContext();
702 // Periodically check to bail out early.
703 if (isCancelled()) return null;
705 // it's not in the db... we need to generate it
706 return generatePreview(launcher, mInfo, mUnusedBitmap, mPreviewWidth, mPreviewHeight, this);
710 protected void onPostExecute(final Bitmap preview) {
711 if (preview == null || isCancelled()) return;
713 applyPreviewIfActive(this, mCaller, preview);
715 // Write the generated preview to the DB in the worker thread
716 if (mVersions != null) {
717 mWorkerHandler.post(new Runnable() {
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;
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);
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;
742 protected void onCancelled(final Bitmap preview) {
743 recycleBitmap(preview);
747 private void recycleBitmap(final Bitmap bitmap) {
748 if (bitmap != null) {
749 mWorkerHandler.post(new Runnable() {
752 synchronized (mUnusedBitmaps) {
753 mUnusedBitmaps.add(bitmap);
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);
768 private static final class WidgetCacheKey extends ComponentKey {
770 // TODO: remove dependency on size
771 @Thunk final String size;
773 public WidgetCacheKey(ComponentName componentName, UserHandleCompat user, String size) {
774 super(componentName, user);
779 public int hashCode() {
780 return super.hashCode() ^ size.hashCode();
784 public boolean equals(Object o) {
785 return super.equals(o) && ((WidgetCacheKey) o).size.equals(size);