1 package com.android.launcher3;
2 
3 import static com.android.launcher3.util.Executors.MAIN_EXECUTOR;
4 import static com.android.launcher3.util.Executors.MODEL_EXECUTOR;
5 
6 import android.content.ComponentName;
7 import android.content.ContentValues;
8 import android.content.Context;
9 import android.content.pm.PackageInfo;
10 import android.content.pm.PackageManager;
11 import android.content.pm.PackageManager.NameNotFoundException;
12 import android.content.res.Resources;
13 import android.database.Cursor;
14 import android.database.SQLException;
15 import android.database.sqlite.SQLiteDatabase;
16 import android.graphics.Bitmap;
17 import android.graphics.Bitmap.Config;
18 import android.graphics.BitmapFactory;
19 import android.graphics.Canvas;
20 import android.graphics.Color;
21 import android.graphics.Paint;
22 import android.graphics.PorterDuff;
23 import android.graphics.PorterDuffXfermode;
24 import android.graphics.Rect;
25 import android.graphics.RectF;
26 import android.graphics.drawable.Drawable;
27 import android.os.AsyncTask;
28 import android.os.CancellationSignal;
29 import android.os.Process;
30 import android.os.UserHandle;
31 import android.util.Log;
32 import android.util.LongSparseArray;
33 
34 import androidx.annotation.Nullable;
35 
36 import com.android.launcher3.compat.AppWidgetManagerCompat;
37 import com.android.launcher3.compat.ShortcutConfigActivityInfo;
38 import com.android.launcher3.compat.UserManagerCompat;
39 import com.android.launcher3.icons.GraphicsUtils;
40 import com.android.launcher3.icons.IconCache;
41 import com.android.launcher3.icons.LauncherIcons;
42 import com.android.launcher3.icons.ShadowGenerator;
43 import com.android.launcher3.model.WidgetItem;
44 import com.android.launcher3.util.ComponentKey;
45 import com.android.launcher3.util.Executors;
46 import com.android.launcher3.util.PackageUserKey;
47 import com.android.launcher3.util.Preconditions;
48 import com.android.launcher3.util.SQLiteCacheHelper;
49 import com.android.launcher3.util.Thunk;
50 import com.android.launcher3.widget.WidgetCell;
51 
52 import java.util.ArrayList;
53 import java.util.Collections;
54 import java.util.HashMap;
55 import java.util.HashSet;
56 import java.util.Set;
57 import java.util.WeakHashMap;
58 import java.util.concurrent.ExecutionException;
59 
60 public class WidgetPreviewLoader {
61 
62     private static final String TAG = "WidgetPreviewLoader";
63     private static final boolean DEBUG = false;
64 
65     private final HashMap<String, long[]> mPackageVersions = new HashMap<>();
66 
67     /**
68      * Weak reference objects, do not prevent their referents from being made finalizable,
69      * finalized, and then reclaimed.
70      * Note: synchronized block used for this variable is expensive and the block should always
71      * be posted to a background thread.
72      */
73     @Thunk final Set<Bitmap> mUnusedBitmaps = Collections.newSetFromMap(new WeakHashMap<>());
74 
75     private final Context mContext;
76     private final IconCache mIconCache;
77     private final UserManagerCompat mUserManager;
78     private final CacheDb mDb;
79 
WidgetPreviewLoader(Context context, IconCache iconCache)80     public WidgetPreviewLoader(Context context, IconCache iconCache) {
81         mContext = context;
82         mIconCache = iconCache;
83         mUserManager = UserManagerCompat.getInstance(context);
84         mDb = new CacheDb(context);
85     }
86 
87     /**
88      * Generates the widget preview on {@link AsyncTask#THREAD_POOL_EXECUTOR}. Must be
89      * called on UI thread
90      *
91      * @return a request id which can be used to cancel the request.
92      */
getPreview(WidgetItem item, int previewWidth, int previewHeight, WidgetCell caller)93     public CancellationSignal getPreview(WidgetItem item, int previewWidth,
94             int previewHeight, WidgetCell caller) {
95         String size = previewWidth + "x" + previewHeight;
96         WidgetCacheKey key = new WidgetCacheKey(item.componentName, item.user, size);
97 
98         PreviewLoadTask task = new PreviewLoadTask(key, item, previewWidth, previewHeight, caller);
99         task.executeOnExecutor(Executors.THREAD_POOL_EXECUTOR);
100 
101         CancellationSignal signal = new CancellationSignal();
102         signal.setOnCancelListener(task);
103         return signal;
104     }
105 
refresh()106     public void refresh() {
107         mDb.clear();
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 SQLiteCacheHelper {
115         private static final int DB_VERSION = 9;
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 
CacheDb(Context context)126         public CacheDb(Context context) {
127             super(context, LauncherFiles.WIDGET_PREVIEWS_DB, DB_VERSION, TABLE_NAME);
128         }
129 
130         @Override
onCreateTable(SQLiteDatabase database)131         public void onCreateTable(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 
writeToDb(WidgetCacheKey key, long[] versions, Bitmap preview)145     @Thunk void writeToDb(WidgetCacheKey key, long[] versions, Bitmap preview) {
146         ContentValues values = new ContentValues();
147         values.put(CacheDb.COLUMN_COMPONENT, key.componentName.flattenToShortString());
148         values.put(CacheDb.COLUMN_USER, mUserManager.getSerialNumberForUser(key.user));
149         values.put(CacheDb.COLUMN_SIZE, key.size);
150         values.put(CacheDb.COLUMN_PACKAGE, key.componentName.getPackageName());
151         values.put(CacheDb.COLUMN_VERSION, versions[0]);
152         values.put(CacheDb.COLUMN_LAST_UPDATED, versions[1]);
153         values.put(CacheDb.COLUMN_PREVIEW_BITMAP, GraphicsUtils.flattenBitmap(preview));
154         mDb.insertOrReplace(values);
155     }
156 
removePackage(String packageName, UserHandle user)157     public void removePackage(String packageName, UserHandle user) {
158         removePackage(packageName, user, mUserManager.getSerialNumberForUser(user));
159     }
160 
removePackage(String packageName, UserHandle user, long userSerial)161     private void removePackage(String packageName, UserHandle user, long userSerial) {
162         synchronized(mPackageVersions) {
163             mPackageVersions.remove(packageName);
164         }
165 
166         mDb.delete(
167                 CacheDb.COLUMN_PACKAGE + " = ? AND " + CacheDb.COLUMN_USER + " = ?",
168                 new String[]{packageName, Long.toString(userSerial)});
169     }
170 
171     /**
172      * Updates the persistent DB:
173      *   1. Any preview generated for an old package version is removed
174      *   2. Any preview for an absent package is removed
175      * This ensures that we remove entries for packages which changed while the launcher was dead.
176      *
177      * @param packageUser if provided, specifies that list only contains previews for the
178      *                    given package/user, otherwise the list contains all previews
179      */
removeObsoletePreviews(ArrayList<? extends ComponentKey> list, @Nullable PackageUserKey packageUser)180     public void removeObsoletePreviews(ArrayList<? extends ComponentKey> list,
181             @Nullable PackageUserKey packageUser) {
182         Preconditions.assertWorkerThread();
183 
184         LongSparseArray<HashSet<String>> validPackages = new LongSparseArray<>();
185 
186         for (ComponentKey key : list) {
187             final long userId = mUserManager.getSerialNumberForUser(key.user);
188             HashSet<String> packages = validPackages.get(userId);
189             if (packages == null) {
190                 packages = new HashSet<>();
191                 validPackages.put(userId, packages);
192             }
193             packages.add(key.componentName.getPackageName());
194         }
195 
196         LongSparseArray<HashSet<String>> packagesToDelete = new LongSparseArray<>();
197         long passedUserId = packageUser == null ? 0
198                 : mUserManager.getSerialNumberForUser(packageUser.mUser);
199         Cursor c = null;
200         try {
201             c = mDb.query(
202                     new String[]{CacheDb.COLUMN_USER, CacheDb.COLUMN_PACKAGE,
203                             CacheDb.COLUMN_LAST_UPDATED, CacheDb.COLUMN_VERSION},
204                     null, null);
205             while (c.moveToNext()) {
206                 long userId = c.getLong(0);
207                 String pkg = c.getString(1);
208                 long lastUpdated = c.getLong(2);
209                 long version = c.getLong(3);
210 
211                 if (packageUser != null && (!pkg.equals(packageUser.mPackageName)
212                         || userId != passedUserId)) {
213                     // This preview is associated with a different package/user, no need to remove.
214                     continue;
215                 }
216 
217                 HashSet<String> packages = validPackages.get(userId);
218                 if (packages != null && packages.contains(pkg)) {
219                     long[] versions = getPackageVersion(pkg);
220                     if (versions[0] == version && versions[1] == lastUpdated) {
221                         // Every thing checks out
222                         continue;
223                     }
224                 }
225 
226                 // We need to delete this package.
227                 packages = packagesToDelete.get(userId);
228                 if (packages == null) {
229                     packages = new HashSet<>();
230                     packagesToDelete.put(userId, packages);
231                 }
232                 packages.add(pkg);
233             }
234 
235             for (int i = 0; i < packagesToDelete.size(); i++) {
236                 long userId = packagesToDelete.keyAt(i);
237                 UserHandle user = mUserManager.getUserForSerialNumber(userId);
238                 for (String pkg : packagesToDelete.valueAt(i)) {
239                     removePackage(pkg, user, userId);
240                 }
241             }
242         } catch (SQLException e) {
243             Log.e(TAG, "Error updating widget previews", e);
244         } finally {
245             if (c != null) {
246                 c.close();
247             }
248         }
249     }
250 
251     /**
252      * Reads the preview bitmap from the DB or null if the preview is not in the DB.
253      */
readFromDb(WidgetCacheKey key, Bitmap recycle, PreviewLoadTask loadTask)254     @Thunk Bitmap readFromDb(WidgetCacheKey key, Bitmap recycle, PreviewLoadTask loadTask) {
255         Cursor cursor = null;
256         try {
257             cursor = mDb.query(
258                     new String[]{CacheDb.COLUMN_PREVIEW_BITMAP},
259                     CacheDb.COLUMN_COMPONENT + " = ? AND " + CacheDb.COLUMN_USER + " = ? AND "
260                             + CacheDb.COLUMN_SIZE + " = ?",
261                     new String[]{
262                             key.componentName.flattenToShortString(),
263                             Long.toString(mUserManager.getSerialNumberForUser(key.user)),
264                             key.size
265                     });
266             // If cancelled, skip getting the blob and decoding it into a bitmap
267             if (loadTask.isCancelled()) {
268                 return null;
269             }
270             if (cursor.moveToNext()) {
271                 byte[] blob = cursor.getBlob(0);
272                 BitmapFactory.Options opts = new BitmapFactory.Options();
273                 opts.inBitmap = recycle;
274                 try {
275                     if (!loadTask.isCancelled()) {
276                         return BitmapFactory.decodeByteArray(blob, 0, blob.length, opts);
277                     }
278                 } catch (Exception e) {
279                     return null;
280                 }
281             }
282         } catch (SQLException e) {
283             Log.w(TAG, "Error loading preview from DB", e);
284         } finally {
285             if (cursor != null) {
286                 cursor.close();
287             }
288         }
289         return null;
290     }
291 
generatePreview(BaseActivity launcher, WidgetItem item, Bitmap recycle, int previewWidth, int previewHeight)292     private Bitmap generatePreview(BaseActivity launcher, WidgetItem item, Bitmap recycle,
293             int previewWidth, int previewHeight) {
294         if (item.widgetInfo != null) {
295             return generateWidgetPreview(launcher, item.widgetInfo,
296                     previewWidth, recycle, null);
297         } else {
298             return generateShortcutPreview(launcher, item.activityInfo,
299                     previewWidth, previewHeight, recycle);
300         }
301     }
302 
303     /**
304      * Generates the widget preview from either the {@link AppWidgetManagerCompat} or cache
305      * and add badge at the bottom right corner.
306      *
307      * @param launcher
308      * @param info                        information about the widget
309      * @param maxPreviewWidth             width of the preview on either workspace or tray
310      * @param preview                     bitmap that can be recycled
311      * @param preScaledWidthOut           return the width of the returned bitmap
312      * @return
313      */
generateWidgetPreview(BaseActivity launcher, LauncherAppWidgetProviderInfo info, int maxPreviewWidth, Bitmap preview, int[] preScaledWidthOut)314     public Bitmap generateWidgetPreview(BaseActivity launcher, LauncherAppWidgetProviderInfo info,
315             int maxPreviewWidth, Bitmap preview, int[] preScaledWidthOut) {
316         // Load the preview image if possible
317         if (maxPreviewWidth < 0) maxPreviewWidth = Integer.MAX_VALUE;
318 
319         Drawable drawable = null;
320         if (info.previewImage != 0) {
321             try {
322                 drawable = info.loadPreviewImage(mContext, 0);
323             } catch (OutOfMemoryError e) {
324                 Log.w(TAG, "Error loading widget preview for: " + info.provider, e);
325                 // During OutOfMemoryError, the previous heap stack is not affected. Catching
326                 // an OOM error here should be safe & not affect other parts of launcher.
327                 drawable = null;
328             }
329             if (drawable != null) {
330                 drawable = mutateOnMainThread(drawable);
331             } else {
332                 Log.w(TAG, "Can't load widget preview drawable 0x" +
333                         Integer.toHexString(info.previewImage) + " for provider: " + info.provider);
334             }
335         }
336 
337         final boolean widgetPreviewExists = (drawable != null);
338         final int spanX = info.spanX;
339         final int spanY = info.spanY;
340 
341         int previewWidth;
342         int previewHeight;
343 
344         if (widgetPreviewExists && drawable.getIntrinsicWidth() > 0
345                 && drawable.getIntrinsicHeight() > 0) {
346             previewWidth = drawable.getIntrinsicWidth();
347             previewHeight = drawable.getIntrinsicHeight();
348         } else {
349             DeviceProfile dp = launcher.getDeviceProfile();
350             int tileSize = Math.min(dp.cellWidthPx, dp.cellHeightPx);
351             previewWidth = tileSize * spanX;
352             previewHeight = tileSize * spanY;
353         }
354 
355         // Scale to fit width only - let the widget preview be clipped in the
356         // vertical dimension
357         float scale = 1f;
358         if (preScaledWidthOut != null) {
359             preScaledWidthOut[0] = previewWidth;
360         }
361         if (previewWidth > maxPreviewWidth) {
362             scale = maxPreviewWidth / (float) (previewWidth);
363         }
364         if (scale != 1f) {
365             previewWidth = Math.max((int)(scale * previewWidth), 1);
366             previewHeight = Math.max((int)(scale * previewHeight), 1);
367         }
368 
369         // If a bitmap is passed in, we use it; otherwise, we create a bitmap of the right size
370         final Canvas c = new Canvas();
371         if (preview == null) {
372             preview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
373             c.setBitmap(preview);
374         } else {
375             // We use the preview bitmap height to determine where the badge will be drawn in the
376             // UI. If its larger than what we need, resize the preview bitmap so that there are
377             // no transparent pixels between the preview and the badge.
378             if (preview.getHeight() > previewHeight) {
379                 preview.reconfigure(preview.getWidth(), previewHeight, preview.getConfig());
380             }
381             // Reusing bitmap. Clear it.
382             c.setBitmap(preview);
383             c.drawColor(0, PorterDuff.Mode.CLEAR);
384         }
385 
386         // Draw the scaled preview into the final bitmap
387         int x = (preview.getWidth() - previewWidth) / 2;
388         if (widgetPreviewExists) {
389             drawable.setBounds(x, 0, x + previewWidth, previewHeight);
390             drawable.draw(c);
391         } else {
392             RectF boxRect = drawBoxWithShadow(c, previewWidth, previewHeight);
393 
394             // Draw horizontal and vertical lines to represent individual columns.
395             final Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
396             p.setStyle(Paint.Style.STROKE);
397             p.setStrokeWidth(mContext.getResources()
398                     .getDimension(R.dimen.widget_preview_cell_divider_width));
399             p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
400 
401             float t = boxRect.left;
402             float tileSize = boxRect.width() / spanX;
403             for (int i = 1; i < spanX; i++) {
404                 t += tileSize;
405                 c.drawLine(t, 0, t, previewHeight, p);
406             }
407 
408             t = boxRect.top;
409             tileSize = boxRect.height() / spanY;
410             for (int i = 1; i < spanY; i++) {
411                 t += tileSize;
412                 c.drawLine(0, t, previewWidth, t, p);
413             }
414 
415             // Draw icon in the center.
416             try {
417                 Drawable icon =
418                         mIconCache.getFullResIcon(info.provider.getPackageName(), info.icon);
419                 if (icon != null) {
420                     int appIconSize = launcher.getDeviceProfile().iconSizePx;
421                     int iconSize = (int) Math.min(appIconSize * scale,
422                             Math.min(boxRect.width(), boxRect.height()));
423 
424                     icon = mutateOnMainThread(icon);
425                     int hoffset = (previewWidth - iconSize) / 2;
426                     int yoffset = (previewHeight - iconSize) / 2;
427                     icon.setBounds(hoffset, yoffset, hoffset + iconSize, yoffset + iconSize);
428                     icon.draw(c);
429                 }
430             } catch (Resources.NotFoundException e) { }
431             c.setBitmap(null);
432         }
433         return preview;
434     }
435 
drawBoxWithShadow(Canvas c, int width, int height)436     private RectF drawBoxWithShadow(Canvas c, int width, int height) {
437         Resources res = mContext.getResources();
438 
439         ShadowGenerator.Builder builder = new ShadowGenerator.Builder(Color.WHITE);
440         builder.shadowBlur = res.getDimension(R.dimen.widget_preview_shadow_blur);
441         builder.radius = res.getDimension(R.dimen.widget_preview_corner_radius);
442         builder.keyShadowDistance = res.getDimension(R.dimen.widget_preview_key_shadow_distance);
443 
444         builder.bounds.set(builder.shadowBlur, builder.shadowBlur,
445                 width - builder.shadowBlur,
446                 height - builder.shadowBlur - builder.keyShadowDistance);
447         builder.drawShadow(c);
448         return builder.bounds;
449     }
450 
generateShortcutPreview(BaseActivity launcher, ShortcutConfigActivityInfo info, int maxWidth, int maxHeight, Bitmap preview)451     private Bitmap generateShortcutPreview(BaseActivity launcher, ShortcutConfigActivityInfo info,
452             int maxWidth, int maxHeight, Bitmap preview) {
453         int iconSize = launcher.getDeviceProfile().allAppsIconSizePx;
454         int padding = launcher.getResources()
455                 .getDimensionPixelSize(R.dimen.widget_preview_shortcut_padding);
456 
457         int size = iconSize + 2 * padding;
458         if (maxHeight < size || maxWidth < size) {
459             throw new RuntimeException("Max size is too small for preview");
460         }
461         final Canvas c = new Canvas();
462         if (preview == null || preview.getWidth() < size || preview.getHeight() < size) {
463             preview = Bitmap.createBitmap(size, size, Config.ARGB_8888);
464             c.setBitmap(preview);
465         } else {
466             if (preview.getWidth() > size || preview.getHeight() > size) {
467                 preview.reconfigure(size, size, preview.getConfig());
468             }
469 
470             // Reusing bitmap. Clear it.
471             c.setBitmap(preview);
472             c.drawColor(0, PorterDuff.Mode.CLEAR);
473         }
474         RectF boxRect = drawBoxWithShadow(c, size, size);
475 
476         LauncherIcons li = LauncherIcons.obtain(mContext);
477         Bitmap icon = li.createBadgedIconBitmap(
478                 mutateOnMainThread(info.getFullResIcon(mIconCache)),
479                 Process.myUserHandle(), 0).icon;
480         li.recycle();
481 
482         Rect src = new Rect(0, 0, icon.getWidth(), icon.getHeight());
483 
484         boxRect.set(0, 0, iconSize, iconSize);
485         boxRect.offset(padding, padding);
486         c.drawBitmap(icon, src, boxRect,
487                 new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG));
488         c.setBitmap(null);
489         return preview;
490     }
491 
mutateOnMainThread(final Drawable drawable)492     private Drawable mutateOnMainThread(final Drawable drawable) {
493         try {
494             return MAIN_EXECUTOR.submit(drawable::mutate).get();
495         } catch (InterruptedException e) {
496             Thread.currentThread().interrupt();
497             throw new RuntimeException(e);
498         } catch (ExecutionException e) {
499             throw new RuntimeException(e);
500         }
501     }
502 
503     /**
504      * @return an array of containing versionCode and lastUpdatedTime for the package.
505      */
getPackageVersion(String packageName)506     @Thunk long[] getPackageVersion(String packageName) {
507         synchronized (mPackageVersions) {
508             long[] versions = mPackageVersions.get(packageName);
509             if (versions == null) {
510                 versions = new long[2];
511                 try {
512                     PackageInfo info = mContext.getPackageManager().getPackageInfo(packageName,
513                             PackageManager.GET_UNINSTALLED_PACKAGES);
514                     versions[0] = info.versionCode;
515                     versions[1] = info.lastUpdateTime;
516                 } catch (NameNotFoundException e) {
517                     Log.e(TAG, "PackageInfo not found", e);
518                 }
519                 mPackageVersions.put(packageName, versions);
520             }
521             return versions;
522         }
523     }
524 
525     public class PreviewLoadTask extends AsyncTask<Void, Void, Bitmap>
526             implements CancellationSignal.OnCancelListener {
527         @Thunk final WidgetCacheKey mKey;
528         private final WidgetItem mInfo;
529         private final int mPreviewHeight;
530         private final int mPreviewWidth;
531         private final WidgetCell mCaller;
532         private final BaseActivity mActivity;
533         @Thunk long[] mVersions;
534         @Thunk Bitmap mBitmapToRecycle;
535 
PreviewLoadTask(WidgetCacheKey key, WidgetItem info, int previewWidth, int previewHeight, WidgetCell caller)536         PreviewLoadTask(WidgetCacheKey key, WidgetItem info, int previewWidth,
537                 int previewHeight, WidgetCell caller) {
538             mKey = key;
539             mInfo = info;
540             mPreviewHeight = previewHeight;
541             mPreviewWidth = previewWidth;
542             mCaller = caller;
543             mActivity = BaseActivity.fromContext(mCaller.getContext());
544             if (DEBUG) {
545                 Log.d(TAG, String.format("%s, %s, %d, %d",
546                         mKey, mInfo, mPreviewHeight, mPreviewWidth));
547             }
548         }
549 
550         @Override
doInBackground(Void... params)551         protected Bitmap doInBackground(Void... params) {
552             Bitmap unusedBitmap = null;
553 
554             // If already cancelled before this gets to run in the background, then return early
555             if (isCancelled()) {
556                 return null;
557             }
558             synchronized (mUnusedBitmaps) {
559                 // Check if we can re-use a bitmap
560                 for (Bitmap candidate : mUnusedBitmaps) {
561                     if (candidate != null && candidate.isMutable() &&
562                             candidate.getWidth() == mPreviewWidth &&
563                             candidate.getHeight() == mPreviewHeight) {
564                         unusedBitmap = candidate;
565                         mUnusedBitmaps.remove(unusedBitmap);
566                         break;
567                     }
568                 }
569             }
570 
571             // creating a bitmap is expensive. Do not do this inside synchronized block.
572             if (unusedBitmap == null) {
573                 unusedBitmap = Bitmap.createBitmap(mPreviewWidth, mPreviewHeight, Config.ARGB_8888);
574             }
575             // If cancelled now, don't bother reading the preview from the DB
576             if (isCancelled()) {
577                 return unusedBitmap;
578             }
579             Bitmap preview = readFromDb(mKey, unusedBitmap, this);
580             // Only consider generating the preview if we have not cancelled the task already
581             if (!isCancelled() && preview == null) {
582                 // Fetch the version info before we generate the preview, so that, in-case the
583                 // app was updated while we are generating the preview, we use the old version info,
584                 // which would gets re-written next time.
585                 boolean persistable = mInfo.activityInfo == null
586                         || mInfo.activityInfo.isPersistable();
587                 mVersions = persistable ? getPackageVersion(mKey.componentName.getPackageName())
588                         : null;
589 
590                 // it's not in the db... we need to generate it
591                 preview = generatePreview(mActivity, mInfo, unusedBitmap, mPreviewWidth, mPreviewHeight);
592             }
593             return preview;
594         }
595 
596         @Override
onPostExecute(final Bitmap preview)597         protected void onPostExecute(final Bitmap preview) {
598             mCaller.applyPreview(preview);
599 
600             // Write the generated preview to the DB in the worker thread
601             if (mVersions != null) {
602                 MODEL_EXECUTOR.post(new Runnable() {
603                     @Override
604                     public void run() {
605                         if (!isCancelled()) {
606                             // If we are still using this preview, then write it to the DB and then
607                             // let the normal clear mechanism recycle the bitmap
608                             writeToDb(mKey, mVersions, preview);
609                             mBitmapToRecycle = preview;
610                         } else {
611                             // If we've already cancelled, then skip writing the bitmap to the DB
612                             // and manually add the bitmap back to the recycled set
613                             synchronized (mUnusedBitmaps) {
614                                 mUnusedBitmaps.add(preview);
615                             }
616                         }
617                     }
618                 });
619             } else {
620                 // If we don't need to write to disk, then ensure the preview gets recycled by
621                 // the normal clear mechanism
622                 mBitmapToRecycle = preview;
623             }
624         }
625 
626         @Override
onCancelled(final Bitmap preview)627         protected void onCancelled(final Bitmap preview) {
628             // If we've cancelled while the task is running, then can return the bitmap to the
629             // recycled set immediately. Otherwise, it will be recycled after the preview is written
630             // to disk.
631             if (preview != null) {
632                 MODEL_EXECUTOR.post(new Runnable() {
633                     @Override
634                     public void run() {
635                         synchronized (mUnusedBitmaps) {
636                             mUnusedBitmaps.add(preview);
637                         }
638                     }
639                 });
640             }
641         }
642 
643         @Override
onCancel()644         public void onCancel() {
645             cancel(true);
646 
647             // This only handles the case where the PreviewLoadTask is cancelled after the task has
648             // successfully completed (including having written to disk when necessary).  In the
649             // other cases where it is cancelled while the task is running, it will be cleaned up
650             // in the tasks's onCancelled() call, and if cancelled while the task is writing to
651             // disk, it will be cancelled in the task's onPostExecute() call.
652             if (mBitmapToRecycle != null) {
653                 MODEL_EXECUTOR.post(new Runnable() {
654                     @Override
655                     public void run() {
656                         synchronized (mUnusedBitmaps) {
657                             mUnusedBitmaps.add(mBitmapToRecycle);
658                         }
659                         mBitmapToRecycle = null;
660                     }
661                 });
662             }
663         }
664     }
665 
666     private static final class WidgetCacheKey extends ComponentKey {
667 
668         @Thunk final String size;
669 
WidgetCacheKey(ComponentName componentName, UserHandle user, String size)670         public WidgetCacheKey(ComponentName componentName, UserHandle user, String size) {
671             super(componentName, user);
672             this.size = size;
673         }
674 
675         @Override
hashCode()676         public int hashCode() {
677             return super.hashCode() ^ size.hashCode();
678         }
679 
680         @Override
equals(Object o)681         public boolean equals(Object o) {
682             return super.equals(o) && ((WidgetCacheKey) o).size.equals(size);
683         }
684     }
685 }
686