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;
69 private final CacheDb mDb;
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);
87 * Generates the widget preview on {@link AsyncTask#THREAD_POOL_EXECUTOR}. Must be
90 * @param o either {@link LauncherAppWidgetProviderInfo} or {@link ResolveInfo}
91 * @return a request id which can be used to cancel the request.
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);
98 PreviewLoadTask task = new PreviewLoadTask(key, o, previewWidth, previewHeight, caller);
99 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
100 return new PreviewLoadRequest(task);
104 * The DB holds the generated previews for various components. Previews can also have different
105 * sizes (landscape vs portrait).
107 private static class CacheDb extends SQLiteOpenHelper {
108 private static final int DB_VERSION = 4;
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";
119 public CacheDb(Context context) {
120 super(context, LauncherFiles.WIDGET_PREVIEWS_DB, null, DB_VERSION);
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 + ") " +
138 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
139 if (oldVersion != newVersion) {
145 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
146 if (oldVersion != newVersion) {
151 private void clearDB(SQLiteDatabase db) {
152 db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
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);
163 ResolveInfo info = (ResolveInfo) o;
164 return new WidgetCacheKey(
165 new ComponentName(info.activityInfo.packageName, info.activityInfo.name),
166 UserHandleCompat.myUserHandle(), size);
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));
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);
188 public void removePackage(String packageName, UserHandleCompat user) {
189 removePackage(packageName, user, mUserManager.getSerialNumberForUser(user));
192 private void removePackage(String packageName, UserHandleCompat user, long userSerial) {
193 synchronized(mPackageVersions) {
194 mPackageVersions.remove(packageName);
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);
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.
212 public void removeObsoletePreviews(ArrayList<Object> list) {
213 Utilities.assertWorkerThread();
215 LongSparseArray<HashSet<String>> validPackages = new LongSparseArray<>();
217 for (Object obj : list) {
218 final UserHandleCompat user;
220 if (obj instanceof ResolveInfo) {
221 user = UserHandleCompat.myUserHandle();
222 pkg = ((ResolveInfo) obj).activityInfo.packageName;
224 LauncherAppWidgetProviderInfo info = (LauncherAppWidgetProviderInfo) obj;
225 user = mManager.getUser(info);
226 pkg = info.provider.getPackageName();
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);
238 LongSparseArray<HashSet<String>> packagesToDelete = new LongSparseArray<>();
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);
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
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);
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);
276 } catch (SQLException e) {
277 Log.e(TAG, "Error updatating widget previews", e);
286 * Reads the preview bitmap from the DB or null if the preview is not in the DB.
288 @Thunk Bitmap readFromDb(WidgetCacheKey key, Bitmap recycle, PreviewLoadTask loadTask) {
289 Cursor cursor = null;
291 cursor = mDb.getReadableDatabase().query(
293 new String[] { CacheDb.COLUMN_PREVIEW_BITMAP },
294 CacheDb.COLUMN_COMPONENT + " = ? AND " + CacheDb.COLUMN_USER + " = ? AND " + CacheDb.COLUMN_SIZE + " = ?",
296 key.componentName.flattenToString(),
297 Long.toString(mUserManager.getSerialNumberForUser(key.user)),
301 // If cancelled, skip getting the blob and decoding it into a bitmap
302 if (loadTask.isCancelled()) {
305 if (cursor.moveToNext()) {
306 byte[] blob = cursor.getBlob(0);
307 BitmapFactory.Options opts = new BitmapFactory.Options();
308 opts.inBitmap = recycle;
310 if (!loadTask.isCancelled()) {
311 return BitmapFactory.decodeByteArray(blob, 0, blob.length, opts);
313 } catch (Exception e) {
317 } catch (SQLException e) {
318 Log.w(TAG, "Error loading preview from DB", e);
320 if (cursor != null) {
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);
333 return generateShortcutPreview(launcher,
334 (ResolveInfo) info, previewWidth, previewHeight, recycle);
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;
343 Drawable drawable = null;
344 if (info.previewImage != 0) {
345 drawable = mManager.loadPreview(info);
346 if (drawable != null) {
347 drawable = mutateOnMainThread(drawable);
349 Log.w(TAG, "Can't load widget preview drawable 0x" +
350 Integer.toHexString(info.previewImage) + " for provider: " + info.provider);
354 final boolean widgetPreviewExists = (drawable != null);
355 final int spanX = info.spanX;
356 final int spanY = info.spanY;
360 Bitmap tileBitmap = null;
362 if (widgetPreviewExists) {
363 previewWidth = drawable.getIntrinsicWidth();
364 previewHeight = drawable.getIntrinsicHeight();
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;
373 // Scale to fit width only - let the widget preview be clipped in the
374 // vertical dimension
376 if (preScaledWidthOut != null) {
377 preScaledWidthOut[0] = previewWidth;
379 if (previewWidth > maxPreviewWidth) {
380 scale = (maxPreviewWidth - 2 * mProfileBadgeMargin) / (float) (previewWidth);
383 previewWidth = (int) (scale * previewWidth);
384 previewHeight = (int) (scale * previewHeight);
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);
393 // Reusing bitmap. Clear it.
394 c.setBitmap(preview);
395 c.drawColor(0, PorterDuff.Mode.CLEAR);
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);
404 final Paint p = new Paint();
405 p.setFilterBitmap(true);
406 int appIconSize = launcher.getDeviceProfile().iconSizePx;
408 // draw the spanX x spanY tiles
409 final Rect src = new Rect(0, 0, tileBitmap.getWidth(), tileBitmap.getHeight());
411 float tileW = scale * tileBitmap.getWidth();
412 float tileH = scale * tileBitmap.getHeight();
413 final RectF dst = new RectF(0, 0, tileW, tileH);
416 for (int i = 0; i < spanX; i++, tx += tileW) {
418 for (int j = 0; j < spanY; j++, ty += tileH) {
419 dst.offsetTo(tx, ty);
420 c.drawBitmap(tileBitmap, src, dst, p);
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);
431 Drawable icon = mutateOnMainThread(mManager.loadIcon(info, mIconCache));
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));
440 } catch (Resources.NotFoundException e) { }
443 int imageHeight = Math.min(preview.getHeight(), previewHeight + mProfileBadgeMargin);
444 return mManager.getBadgeBitmap(info, preview, imageHeight);
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");
456 // Reusing bitmap. Clear it.
457 c.setBitmap(preview);
458 c.drawColor(0, PorterDuff.Mode.CLEAR);
461 Drawable icon = mutateOnMainThread(mIconCache.getFullResIcon(info.activityInfo));
462 icon.setFilterBitmap(true);
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));
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);
479 // Draw the final icon at top left corner.
480 // TODO: use top right for RTL
481 int appIconSize = launcher.getDeviceProfile().iconSizePx;
484 icon.setColorFilter(null);
485 icon.setBounds(0, 0, appIconSize, appIconSize);
492 private Drawable mutateOnMainThread(final Drawable drawable) {
494 return mMainThreadExecutor.submit(new Callable<Drawable>() {
496 public Drawable call() throws Exception {
497 return drawable.mutate();
500 } catch (InterruptedException e) {
501 Thread.currentThread().interrupt();
502 throw new RuntimeException(e);
503 } catch (ExecutionException e) {
504 throw new RuntimeException(e);
509 * @return an array of containing versionCode and lastUpdatedTime for the package.
511 @Thunk long[] getPackageVersion(String packageName) {
512 synchronized (mPackageVersions) {
513 long[] versions = mPackageVersions.get(packageName);
514 if (versions == null) {
515 versions = new long[2];
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);
523 mPackageVersions.put(packageName, versions);
530 * A request Id which can be used by the client to cancel any request.
532 public class PreviewLoadRequest {
534 @Thunk final PreviewLoadTask mTask;
536 public PreviewLoadRequest(PreviewLoadTask task) {
540 public void cleanup() {
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() {
554 synchronized (mUnusedBitmaps) {
555 mUnusedBitmaps.add(mTask.mBitmapToRecycle);
557 mTask.mBitmapToRecycle = null;
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;
573 PreviewLoadTask(WidgetCacheKey key, Object info, int previewWidth,
574 int previewHeight, WidgetCell caller) {
577 mPreviewHeight = previewHeight;
578 mPreviewWidth = previewWidth;
581 Log.d(TAG, String.format("%s, %s, %d, %d",
582 mKey, mInfo, mPreviewHeight, mPreviewWidth));
587 protected Bitmap doInBackground(Void... params) {
588 Bitmap unusedBitmap = null;
590 // If already cancelled before this gets to run in the background, then return early
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);
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);
611 // If cancelled now, don't bother reading the preview from the DB
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());
623 Launcher launcher = (Launcher) mCaller.getContext();
625 // it's not in the db... we need to generate it
626 preview = generatePreview(launcher, mInfo, unusedBitmap, mPreviewWidth, mPreviewHeight);
632 protected void onPostExecute(final Bitmap preview) {
633 mCaller.applyPreview(preview);
635 // Write the generated preview to the DB in the worker thread
636 if (mVersions != null) {
637 mWorkerHandler.post(new Runnable() {
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;
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);
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;
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
666 if (preview != null) {
667 mWorkerHandler.post(new Runnable() {
670 synchronized (mUnusedBitmaps) {
671 mUnusedBitmaps.add(preview);
679 private static final class WidgetCacheKey extends ComponentKey {
681 // TODO: remove dependency on size
682 @Thunk final String size;
684 public WidgetCacheKey(ComponentName componentName, UserHandleCompat user, String size) {
685 super(componentName, user);
690 public int hashCode() {
691 return super.hashCode() ^ size.hashCode();
695 public boolean equals(Object o) {
696 return super.equals(o) && ((WidgetCacheKey) o).size.equals(size);