summaryrefslogtreecommitdiffstats
path: root/src/com/android/launcher3/WidgetPreviewLoader.java
blob: 5e859c72ae7f61903f595f01c9d5feab5556b116 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
package com.android.launcher3;

import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.CancellationSignal;
import android.os.Handler;
import android.os.UserHandle;
import android.support.v4.graphics.ColorUtils;
import android.util.Log;
import android.util.LongSparseArray;

import com.android.launcher3.compat.AppWidgetManagerCompat;
import com.android.launcher3.compat.ShortcutConfigActivityInfo;
import com.android.launcher3.compat.UserManagerCompat;
import com.android.launcher3.graphics.LauncherIcons;
import com.android.launcher3.graphics.ShadowGenerator;
import com.android.launcher3.model.WidgetItem;
import com.android.launcher3.util.ComponentKey;
import com.android.launcher3.util.Preconditions;
import com.android.launcher3.util.SQLiteCacheHelper;
import com.android.launcher3.util.Thunk;
import com.android.launcher3.widget.WidgetCell;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;

public class WidgetPreviewLoader {

    private static final String TAG = "WidgetPreviewLoader";
    private static final boolean DEBUG = false;

    private final HashMap<String, long[]> mPackageVersions = new HashMap<>();

    /**
     * Weak reference objects, do not prevent their referents from being made finalizable,
     * finalized, and then reclaimed.
     * Note: synchronized block used for this variable is expensive and the block should always
     * be posted to a background thread.
     */
    @Thunk final Set<Bitmap> mUnusedBitmaps =
            Collections.newSetFromMap(new WeakHashMap<Bitmap, Boolean>());

    private final Context mContext;
    private final IconCache mIconCache;
    private final UserManagerCompat mUserManager;
    private final AppWidgetManagerCompat mWidgetManager;
    private final CacheDb mDb;

    private final MainThreadExecutor mMainThreadExecutor = new MainThreadExecutor();
    @Thunk final Handler mWorkerHandler;

    public WidgetPreviewLoader(Context context, IconCache iconCache) {
        mContext = context;
        mIconCache = iconCache;
        mWidgetManager = AppWidgetManagerCompat.getInstance(context);
        mUserManager = UserManagerCompat.getInstance(context);
        mDb = new CacheDb(context);
        mWorkerHandler = new Handler(LauncherModel.getWorkerLooper());
    }

    /**
     * Generates the widget preview on {@link AsyncTask#THREAD_POOL_EXECUTOR}. Must be
     * called on UI thread
     *
     * @return a request id which can be used to cancel the request.
     */
    public CancellationSignal getPreview(WidgetItem item, int previewWidth,
            int previewHeight, WidgetCell caller) {
        String size = previewWidth + "x" + previewHeight;
        WidgetCacheKey key = new WidgetCacheKey(item.componentName, item.user, size);

        PreviewLoadTask task = new PreviewLoadTask(key, item, previewWidth, previewHeight, caller);
        task.executeOnExecutor(Utilities.THREAD_POOL_EXECUTOR);

        CancellationSignal signal = new CancellationSignal();
        signal.setOnCancelListener(task);
        return signal;
    }

    /**
     * The DB holds the generated previews for various components. Previews can also have different
     * sizes (landscape vs portrait).
     */
    private static class CacheDb extends SQLiteCacheHelper {
        private static final int DB_VERSION = 6;

        private static final String TABLE_NAME = "shortcut_and_widget_previews";
        private static final String COLUMN_COMPONENT = "componentName";
        private static final String COLUMN_USER = "profileId";
        private static final String COLUMN_SIZE = "size";
        private static final String COLUMN_PACKAGE = "packageName";
        private static final String COLUMN_LAST_UPDATED = "lastUpdated";
        private static final String COLUMN_VERSION = "version";
        private static final String COLUMN_PREVIEW_BITMAP = "preview_bitmap";

        public CacheDb(Context context) {
            super(context, LauncherFiles.WIDGET_PREVIEWS_DB, DB_VERSION, TABLE_NAME);
        }

        @Override
        public void onCreateTable(SQLiteDatabase database) {
            database.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" +
                    COLUMN_COMPONENT + " TEXT NOT NULL, " +
                    COLUMN_USER + " INTEGER NOT NULL, " +
                    COLUMN_SIZE + " TEXT NOT NULL, " +
                    COLUMN_PACKAGE + " TEXT NOT NULL, " +
                    COLUMN_LAST_UPDATED + " INTEGER NOT NULL DEFAULT 0, " +
                    COLUMN_VERSION + " INTEGER NOT NULL DEFAULT 0, " +
                    COLUMN_PREVIEW_BITMAP + " BLOB, " +
                    "PRIMARY KEY (" + COLUMN_COMPONENT + ", " + COLUMN_USER + ", " + COLUMN_SIZE + ") " +
                    ");");
        }
    }

    @Thunk void writeToDb(WidgetCacheKey key, long[] versions, Bitmap preview) {
        ContentValues values = new ContentValues();
        values.put(CacheDb.COLUMN_COMPONENT, key.componentName.flattenToShortString());
        values.put(CacheDb.COLUMN_USER, mUserManager.getSerialNumberForUser(key.user));
        values.put(CacheDb.COLUMN_SIZE, key.size);
        values.put(CacheDb.COLUMN_PACKAGE, key.componentName.getPackageName());
        values.put(CacheDb.COLUMN_VERSION, versions[0]);
        values.put(CacheDb.COLUMN_LAST_UPDATED, versions[1]);
        values.put(CacheDb.COLUMN_PREVIEW_BITMAP, Utilities.flattenBitmap(preview));
        mDb.insertOrReplace(values);
    }

    public void removePackage(String packageName, UserHandle user) {
        removePackage(packageName, user, mUserManager.getSerialNumberForUser(user));
    }

    private void removePackage(String packageName, UserHandle user, long userSerial) {
        synchronized(mPackageVersions) {
            mPackageVersions.remove(packageName);
        }

        mDb.delete(
                CacheDb.COLUMN_PACKAGE + " = ? AND " + CacheDb.COLUMN_USER + " = ?",
                new String[]{packageName, Long.toString(userSerial)});
    }

    /**
     * Updates the persistent DB:
     *   1. Any preview generated for an old package version is removed
     *   2. Any preview for an absent package is removed
     * This ensures that we remove entries for packages which changed while the launcher was dead.
     */
    public void removeObsoletePreviews(ArrayList<? extends ComponentKey> list) {
        Preconditions.assertWorkerThread();

        LongSparseArray<HashSet<String>> validPackages = new LongSparseArray<>();

        for (ComponentKey key : list) {
            final long userId = mUserManager.getSerialNumberForUser(key.user);
            HashSet<String> packages = validPackages.get(userId);
            if (packages == null) {
                packages = new HashSet<>();
                validPackages.put(userId, packages);
            }
            packages.add(key.componentName.getPackageName());
        }

        LongSparseArray<HashSet<String>> packagesToDelete = new LongSparseArray<>();
        Cursor c = null;
        try {
            c = mDb.query(
                    new String[]{CacheDb.COLUMN_USER, CacheDb.COLUMN_PACKAGE,
                            CacheDb.COLUMN_LAST_UPDATED, CacheDb.COLUMN_VERSION},
                    null, null);
            while (c.moveToNext()) {
                long userId = c.getLong(0);
                String pkg = c.getString(1);
                long lastUpdated = c.getLong(2);
                long version = c.getLong(3);

                HashSet<String> packages = validPackages.get(userId);
                if (packages != null && packages.contains(pkg)) {
                    long[] versions = getPackageVersion(pkg);
                    if (versions[0] == version && versions[1] == lastUpdated) {
                        // Every thing checks out
                        continue;
                    }
                }

                // We need to delete this package.
                packages = packagesToDelete.get(userId);
                if (packages == null) {
                    packages = new HashSet<>();
                    packagesToDelete.put(userId, packages);
                }
                packages.add(pkg);
            }

            for (int i = 0; i < packagesToDelete.size(); i++) {
                long userId = packagesToDelete.keyAt(i);
                UserHandle user = mUserManager.getUserForSerialNumber(userId);
                for (String pkg : packagesToDelete.valueAt(i)) {
                    removePackage(pkg, user, userId);
                }
            }
        } catch (SQLException e) {
            Log.e(TAG, "Error updating widget previews", e);
        } finally {
            if (c != null) {
                c.close();
            }
        }
    }

    /**
     * Reads the preview bitmap from the DB or null if the preview is not in the DB.
     */
    @Thunk Bitmap readFromDb(WidgetCacheKey key, Bitmap recycle, PreviewLoadTask loadTask) {
        Cursor cursor = null;
        try {
            cursor = mDb.query(
                    new String[]{CacheDb.COLUMN_PREVIEW_BITMAP},
                    CacheDb.COLUMN_COMPONENT + " = ? AND " + CacheDb.COLUMN_USER + " = ? AND "
                            + CacheDb.COLUMN_SIZE + " = ?",
                    new String[]{
                            key.componentName.flattenToShortString(),
                            Long.toString(mUserManager.getSerialNumberForUser(key.user)),
                            key.size
                    });
            // If cancelled, skip getting the blob and decoding it into a bitmap
            if (loadTask.isCancelled()) {
                return null;
            }
            if (cursor.moveToNext()) {
                byte[] blob = cursor.getBlob(0);
                BitmapFactory.Options opts = new BitmapFactory.Options();
                opts.inBitmap = recycle;
                try {
                    if (!loadTask.isCancelled()) {
                        return BitmapFactory.decodeByteArray(blob, 0, blob.length, opts);
                    }
                } catch (Exception e) {
                    return null;
                }
            }
        } catch (SQLException e) {
            Log.w(TAG, "Error loading preview from DB", e);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return null;
    }

    private Bitmap generatePreview(BaseActivity launcher, WidgetItem item, Bitmap recycle,
            int previewWidth, int previewHeight) {
        if (item.widgetInfo != null) {
            return generateWidgetPreview(launcher, item.widgetInfo,
                    previewWidth, recycle, null);
        } else {
            return generateShortcutPreview(launcher, item.activityInfo,
                    previewWidth, previewHeight, recycle);
        }
    }

    /**
     * Generates the widget preview from either the {@link AppWidgetManagerCompat} or cache
     * and add badge at the bottom right corner.
     *
     * @param launcher
     * @param info                        information about the widget
     * @param maxPreviewWidth             width of the preview on either workspace or tray
     * @param preview                     bitmap that can be recycled
     * @param preScaledWidthOut           return the width of the returned bitmap
     * @return
     */
    public Bitmap generateWidgetPreview(BaseActivity launcher, LauncherAppWidgetProviderInfo info,
            int maxPreviewWidth, Bitmap preview, int[] preScaledWidthOut) {
        // Load the preview image if possible
        if (maxPreviewWidth < 0) maxPreviewWidth = Integer.MAX_VALUE;

        Drawable drawable = null;
        if (info.previewImage != 0) {
            try {
                drawable = info.loadPreviewImage(mContext, 0);
            } catch (OutOfMemoryError e) {
                Log.w(TAG, "Error loading widget preview for: " + info.provider, e);
                // During OutOfMemoryError, the previous heap stack is not affected. Catching
                // an OOM error here should be safe & not affect other parts of launcher.
                drawable = null;
            }
            if (drawable != null) {
                drawable = mutateOnMainThread(drawable);
            } else {
                Log.w(TAG, "Can't load widget preview drawable 0x" +
                        Integer.toHexString(info.previewImage) + " for provider: " + info.provider);
            }
        }

        final boolean widgetPreviewExists = (drawable != null);
        final int spanX = info.spanX;
        final int spanY = info.spanY;

        int previewWidth;
        int previewHeight;

        if (widgetPreviewExists) {
            previewWidth = drawable.getIntrinsicWidth();
            previewHeight = drawable.getIntrinsicHeight();
        } else {
            DeviceProfile dp = launcher.getDeviceProfile();
            int tileSize = Math.min(dp.cellWidthPx, dp.cellHeightPx);
            previewWidth = tileSize * spanX;
            previewHeight = tileSize * spanY;
        }

        // Scale to fit width only - let the widget preview be clipped in the
        // vertical dimension
        float scale = 1f;
        if (preScaledWidthOut != null) {
            preScaledWidthOut[0] = previewWidth;
        }
        if (previewWidth > maxPreviewWidth) {
            scale = maxPreviewWidth / (float) (previewWidth);
        }
        if (scale != 1f) {
            previewWidth = (int) (scale * previewWidth);
            previewHeight = (int) (scale * previewHeight);
        }

        // If a bitmap is passed in, we use it; otherwise, we create a bitmap of the right size
        final Canvas c = new Canvas();
        if (preview == null) {
            preview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
            c.setBitmap(preview);
        } else {
            // We use the preview bitmap height to determine where the badge will be drawn in the
            // UI. If its larger than what we need, resize the preview bitmap so that there are
            // no transparent pixels between the preview and the badge.
            if (preview.getHeight() > previewHeight) {
                preview.reconfigure(preview.getWidth(), previewHeight, preview.getConfig());
            }
            // Reusing bitmap. Clear it.
            c.setBitmap(preview);
            c.drawColor(0, PorterDuff.Mode.CLEAR);
        }

        // Draw the scaled preview into the final bitmap
        int x = (preview.getWidth() - previewWidth) / 2;
        if (widgetPreviewExists) {
            drawable.setBounds(x, 0, x + previewWidth, previewHeight);
            drawable.draw(c);
        } else {
            final Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
            RectF boxRect = drawBoxWithShadow(c, p, previewWidth, previewHeight);

            // Draw horizontal and vertical lines to represent individual columns.
            p.setStyle(Paint.Style.STROKE);
            p.setStrokeWidth(mContext.getResources()
                    .getDimension(R.dimen.widget_preview_cell_divider_width));
            p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));

            float t = boxRect.left;
            float tileSize = boxRect.width() / spanX;
            for (int i = 1; i < spanX; i++) {
                t += tileSize;
                c.drawLine(t, 0, t, previewHeight, p);
            }

            t = boxRect.top;
            tileSize = boxRect.height() / spanY;
            for (int i = 1; i < spanY; i++) {
                t += tileSize;
                c.drawLine(0, t, previewWidth, t, p);
            }

            // Draw icon in the center.
            try {
                Drawable icon = info.getIcon(launcher, mIconCache);
                if (icon != null) {
                    int appIconSize = launcher.getDeviceProfile().iconSizePx;
                    int iconSize = (int) Math.min(appIconSize * scale,
                            Math.min(boxRect.width(), boxRect.height()));

                    icon = mutateOnMainThread(icon);
                    int hoffset = (previewWidth - iconSize) / 2;
                    int yoffset = (previewHeight - iconSize) / 2;
                    icon.setBounds(hoffset, yoffset, hoffset + iconSize, yoffset + iconSize);
                    icon.draw(c);
                }
            } catch (Resources.NotFoundException e) { }
            c.setBitmap(null);
        }
        return preview;
    }

    private RectF drawBoxWithShadow(Canvas c, Paint p, int width, int height) {
        Resources res = mContext.getResources();
        float shadowBlur = res.getDimension(R.dimen.widget_preview_shadow_blur);
        float keyShadowDistance = res.getDimension(R.dimen.widget_preview_key_shadow_distance);
        float corner = res.getDimension(R.dimen.widget_preview_corner_radius);
        int shadowColor = ColorUtils.setAlphaComponent(
                res.getColor(R.color.default_shadow_color_no_alpha),
                ShadowGenerator.AMBIENT_SHADOW_ALPHA);

        RectF bounds = new RectF(shadowBlur, shadowBlur,
                width - shadowBlur, height - shadowBlur - keyShadowDistance);
        p.setColor(Color.WHITE);

        // Key shadow
        p.setShadowLayer(shadowBlur, 0, keyShadowDistance, shadowColor);
        c.drawRoundRect(bounds, corner, corner, p);

        // Ambient shadow
        p.setShadowLayer(shadowBlur, 0, 0, shadowColor);
        c.drawRoundRect(bounds, corner, corner, p);

        p.clearShadowLayer();
        return bounds;
    }

    private Bitmap generateShortcutPreview(BaseActivity launcher, ShortcutConfigActivityInfo info,
            int maxWidth, int maxHeight, Bitmap preview) {
        int iconSize = launcher.getDeviceProfile().iconSizePx;
        int padding = launcher.getResources()
                .getDimensionPixelSize(R.dimen.widget_preview_shortcut_padding);

        int size = iconSize + 2 * padding;
        if (maxHeight < size || maxWidth < size) {
            throw new RuntimeException("Max size is too small for preview");
        }
        final Canvas c = new Canvas();
        if (preview == null || preview.getWidth() < size || preview.getHeight() < size) {
            preview = Bitmap.createBitmap(size, size, Config.ARGB_8888);
            c.setBitmap(preview);
        } else {
            if (preview.getWidth() > size || preview.getHeight() > size) {
                preview.reconfigure(size, size, preview.getConfig());
            }

            // Reusing bitmap. Clear it.
            c.setBitmap(preview);
            c.drawColor(0, PorterDuff.Mode.CLEAR);
        }
        Paint p = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
        RectF boxRect = drawBoxWithShadow(c, p, size, size);

        Bitmap icon = LauncherIcons.createScaledBitmapWithoutShadow(
                mutateOnMainThread(info.getFullResIcon(mIconCache)), mContext);
        Rect src = new Rect(0, 0, icon.getWidth(), icon.getHeight());

        boxRect.set(0, 0, iconSize, iconSize);
        boxRect.offset(padding, padding);
        c.drawBitmap(icon, src, boxRect, p);
        c.setBitmap(null);
        return preview;
    }

    private Drawable mutateOnMainThread(final Drawable drawable) {
        try {
            return mMainThreadExecutor.submit(new Callable<Drawable>() {
                @Override
                public Drawable call() throws Exception {
                    return drawable.mutate();
                }
            }).get();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @return an array of containing versionCode and lastUpdatedTime for the package.
     */
    @Thunk long[] getPackageVersion(String packageName) {
        synchronized (mPackageVersions) {
            long[] versions = mPackageVersions.get(packageName);
            if (versions == null) {
                versions = new long[2];
                try {
                    PackageInfo info = mContext.getPackageManager().getPackageInfo(packageName,
                            PackageManager.GET_UNINSTALLED_PACKAGES);
                    versions[0] = info.versionCode;
                    versions[1] = info.lastUpdateTime;
                } catch (NameNotFoundException e) {
                    Log.e(TAG, "PackageInfo not found", e);
                }
                mPackageVersions.put(packageName, versions);
            }
            return versions;
        }
    }

    public class PreviewLoadTask extends AsyncTask<Void, Void, Bitmap>
            implements CancellationSignal.OnCancelListener {
        @Thunk final WidgetCacheKey mKey;
        private final WidgetItem mInfo;
        private final int mPreviewHeight;
        private final int mPreviewWidth;
        private final WidgetCell mCaller;
        private final BaseActivity mActivity;
        @Thunk long[] mVersions;
        @Thunk Bitmap mBitmapToRecycle;

        PreviewLoadTask(WidgetCacheKey key, WidgetItem info, int previewWidth,
                int previewHeight, WidgetCell caller) {
            mKey = key;
            mInfo = info;
            mPreviewHeight = previewHeight;
            mPreviewWidth = previewWidth;
            mCaller = caller;
            mActivity = BaseActivity.fromContext(mCaller.getContext());
            if (DEBUG) {
                Log.d(TAG, String.format("%s, %s, %d, %d",
                        mKey, mInfo, mPreviewHeight, mPreviewWidth));
            }
        }

        @Override
        protected Bitmap doInBackground(Void... params) {
            Bitmap unusedBitmap = null;

            // If already cancelled before this gets to run in the background, then return early
            if (isCancelled()) {
                return null;
            }
            synchronized (mUnusedBitmaps) {
                // Check if we can re-use a bitmap
                for (Bitmap candidate : mUnusedBitmaps) {
                    if (candidate != null && candidate.isMutable() &&
                            candidate.getWidth() == mPreviewWidth &&
                            candidate.getHeight() == mPreviewHeight) {
                        unusedBitmap = candidate;
                        mUnusedBitmaps.remove(unusedBitmap);
                        break;
                    }
                }
            }

            // creating a bitmap is expensive. Do not do this inside synchronized block.
            if (unusedBitmap == null) {
                unusedBitmap = Bitmap.createBitmap(mPreviewWidth, mPreviewHeight, Config.ARGB_8888);
            }
            // If cancelled now, don't bother reading the preview from the DB
            if (isCancelled()) {
                return unusedBitmap;
            }
            Bitmap preview = readFromDb(mKey, unusedBitmap, this);
            // Only consider generating the preview if we have not cancelled the task already
            if (!isCancelled() && preview == null) {
                // Fetch the version info before we generate the preview, so that, in-case the
                // app was updated while we are generating the preview, we use the old version info,
                // which would gets re-written next time.
                boolean persistable = mInfo.activityInfo == null
                        || mInfo.activityInfo.isPersistable();
                mVersions = persistable ? getPackageVersion(mKey.componentName.getPackageName())
                        : null;

                // it's not in the db... we need to generate it
                preview = generatePreview(mActivity, mInfo, unusedBitmap, mPreviewWidth, mPreviewHeight);
            }
            return preview;
        }

        @Override
        protected void onPostExecute(final Bitmap preview) {
            mCaller.applyPreview(preview);

            // Write the generated preview to the DB in the worker thread
            if (mVersions != null) {
                mWorkerHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (!isCancelled()) {
                            // If we are still using this preview, then write it to the DB and then
                            // let the normal clear mechanism recycle the bitmap
                            writeToDb(mKey, mVersions, preview);
                            mBitmapToRecycle = preview;
                        } else {
                            // If we've already cancelled, then skip writing the bitmap to the DB
                            // and manually add the bitmap back to the recycled set
                            synchronized (mUnusedBitmaps) {
                                mUnusedBitmaps.add(preview);
                            }
                        }
                    }
                });
            } else {
                // If we don't need to write to disk, then ensure the preview gets recycled by
                // the normal clear mechanism
                mBitmapToRecycle = preview;
            }
        }

        @Override
        protected void onCancelled(final Bitmap preview) {
            // If we've cancelled while the task is running, then can return the bitmap to the
            // recycled set immediately. Otherwise, it will be recycled after the preview is written
            // to disk.
            if (preview != null) {
                mWorkerHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        synchronized (mUnusedBitmaps) {
                            mUnusedBitmaps.add(preview);
                        }
                    }
                });
            }
        }

        @Override
        public void onCancel() {
            cancel(true);

            // This only handles the case where the PreviewLoadTask is cancelled after the task has
            // successfully completed (including having written to disk when necessary).  In the
            // other cases where it is cancelled while the task is running, it will be cleaned up
            // in the tasks's onCancelled() call, and if cancelled while the task is writing to
            // disk, it will be cancelled in the task's onPostExecute() call.
            if (mBitmapToRecycle != null) {
                mWorkerHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        synchronized (mUnusedBitmaps) {
                            mUnusedBitmaps.add(mBitmapToRecycle);
                        }
                        mBitmapToRecycle = null;
                    }
                });
            }
        }
    }

    private static final class WidgetCacheKey extends ComponentKey {

        @Thunk final String size;

        public WidgetCacheKey(ComponentName componentName, UserHandle user, String size) {
            super(componentName, user);
            this.size = size;
        }

        @Override
        public int hashCode() {
            return super.hashCode() ^ size.hashCode();
        }

        @Override
        public boolean equals(Object o) {
            return super.equals(o) && ((WidgetCacheKey) o).size.equals(size);
        }
    }
}