blob: 45e65b55b5f564929cd95f07d9e7b25ace636215 [file] [log] [blame]
Daniel Sandler325dc232013-06-05 22:57:57 -04001package com.android.launcher3;
Michael Jurka05713af2013-01-23 12:39:24 +01002
Michael Jurka05713af2013-01-23 12:39:24 +01003import android.content.ComponentName;
4import android.content.ContentValues;
5import android.content.Context;
Sunny Goyal4ddc4012016-03-10 12:02:29 -08006import android.content.pm.ActivityInfo;
Sunny Goyal5b0e6692015-03-19 14:31:19 -07007import android.content.pm.PackageInfo;
Sunny Goyal4ddc4012016-03-10 12:02:29 -08008import android.content.pm.PackageManager;
Sunny Goyal5b0e6692015-03-19 14:31:19 -07009import android.content.pm.PackageManager.NameNotFoundException;
Michael Jurka05713af2013-01-23 12:39:24 +010010import android.content.res.Resources;
11import android.database.Cursor;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070012import android.database.SQLException;
Michael Jurka05713af2013-01-23 12:39:24 +010013import android.database.sqlite.SQLiteDatabase;
Michael Jurka05713af2013-01-23 12:39:24 +010014import android.graphics.Bitmap;
15import android.graphics.Bitmap.Config;
16import android.graphics.BitmapFactory;
17import android.graphics.Canvas;
18import android.graphics.ColorMatrix;
19import android.graphics.ColorMatrixColorFilter;
20import android.graphics.Paint;
21import android.graphics.PorterDuff;
22import android.graphics.Rect;
Sunny Goyal4cad7532015-03-18 15:56:30 -070023import android.graphics.RectF;
Michael Jurka05713af2013-01-23 12:39:24 +010024import android.graphics.drawable.BitmapDrawable;
25import android.graphics.drawable.Drawable;
26import android.os.AsyncTask;
Winson Chung05304db2015-05-18 16:53:20 -070027import android.os.Handler;
Michael Jurka05713af2013-01-23 12:39:24 +010028import android.util.Log;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070029import android.util.LongSparseArray;
Sunny Goyal383c5072015-06-12 21:18:53 -070030
Sunny Goyalffe83f12014-08-14 17:39:34 -070031import com.android.launcher3.compat.AppWidgetManagerCompat;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070032import com.android.launcher3.compat.UserHandleCompat;
33import com.android.launcher3.compat.UserManagerCompat;
Sunny Goyal4ddc4012016-03-10 12:02:29 -080034import com.android.launcher3.model.WidgetItem;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070035import com.android.launcher3.util.ComponentKey;
Sunny Goyal6388b2c2016-04-15 18:03:27 -070036import com.android.launcher3.util.Preconditions;
Sunny Goyal6f709362015-12-17 17:09:36 -080037import com.android.launcher3.util.SQLiteCacheHelper;
Adam Cohen091440a2015-03-18 14:16:05 -070038import com.android.launcher3.util.Thunk;
Hyunyoung Song3f471442015-04-08 19:01:34 -070039import com.android.launcher3.widget.WidgetCell;
Hyunyoung Song8821ca92015-05-04 16:28:20 -070040
41import java.util.ArrayList;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070042import java.util.Collections;
Michael Jurka05713af2013-01-23 12:39:24 +010043import java.util.HashMap;
44import java.util.HashSet;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070045import java.util.Set;
46import java.util.WeakHashMap;
Adrian Roos65d60e22014-04-15 21:07:49 +020047import java.util.concurrent.Callable;
48import java.util.concurrent.ExecutionException;
Michael Jurka05713af2013-01-23 12:39:24 +010049
Sunny Goyalffe83f12014-08-14 17:39:34 -070050public class WidgetPreviewLoader {
Michael Jurka05713af2013-01-23 12:39:24 +010051
Sunny Goyalffe83f12014-08-14 17:39:34 -070052 private static final String TAG = "WidgetPreviewLoader";
Hyunyoung Song3f471442015-04-08 19:01:34 -070053 private static final boolean DEBUG = false;
Sunny Goyalffe83f12014-08-14 17:39:34 -070054
55 private static final float WIDGET_PREVIEW_ICON_PADDING_PERCENTAGE = 0.25f;
Sunny Goyalffe83f12014-08-14 17:39:34 -070056
Sunny Goyal5b0e6692015-03-19 14:31:19 -070057 private final HashMap<String, long[]> mPackageVersions = new HashMap<>();
Hyunyoung Song559d90d2015-04-28 15:06:45 -070058
59 /**
60 * Weak reference objects, do not prevent their referents from being made finalizable,
61 * finalized, and then reclaimed.
Hyunyoung Songe98f4a42015-06-16 10:45:24 -070062 * Note: synchronized block used for this variable is expensive and the block should always
63 * be posted to a background thread.
Hyunyoung Song559d90d2015-04-28 15:06:45 -070064 */
Sunny Goyalb4cbea42015-06-16 15:10:36 -070065 @Thunk final Set<Bitmap> mUnusedBitmaps =
Hyunyoung Song559d90d2015-04-28 15:06:45 -070066 Collections.newSetFromMap(new WeakHashMap<Bitmap, Boolean>());
Sunny Goyal4cad7532015-03-18 15:56:30 -070067
68 private final Context mContext;
Sunny Goyalffe83f12014-08-14 17:39:34 -070069 private final IconCache mIconCache;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070070 private final UserManagerCompat mUserManager;
Hyunyoung Song3e840f42016-03-01 11:57:44 -080071 private final AppWidgetManagerCompat mWidgetManager;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070072 private final CacheDb mDb;
Hyunyoung Song41e33692015-06-15 12:26:54 -070073 private final int mProfileBadgeMargin;
Michael Jurka05713af2013-01-23 12:39:24 +010074
Adrian Roos65d60e22014-04-15 21:07:49 +020075 private final MainThreadExecutor mMainThreadExecutor = new MainThreadExecutor();
Sunny Goyal316490e2015-06-02 09:38:28 -070076 @Thunk final Handler mWorkerHandler;
Adrian Roos65d60e22014-04-15 21:07:49 +020077
Sunny Goyal383c5072015-06-12 21:18:53 -070078 public WidgetPreviewLoader(Context context, IconCache iconCache) {
Chris Wrenfd13c712013-09-27 15:45:19 -040079 mContext = context;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070080 mIconCache = iconCache;
Hyunyoung Song3e840f42016-03-01 11:57:44 -080081 mWidgetManager = AppWidgetManagerCompat.getInstance(context);
Sunny Goyal5b0e6692015-03-19 14:31:19 -070082 mUserManager = UserManagerCompat.getInstance(context);
83 mDb = new CacheDb(context);
Winson Chung05304db2015-05-18 16:53:20 -070084 mWorkerHandler = new Handler(LauncherModel.getWorkerLooper());
Hyunyoung Song41e33692015-06-15 12:26:54 -070085 mProfileBadgeMargin = context.getResources()
86 .getDimensionPixelSize(R.dimen.profile_badge_margin);
Michael Jurka3f4e0702013-02-05 11:21:28 +010087 }
Sunny Goyalffe83f12014-08-14 17:39:34 -070088
Sunny Goyal5b0e6692015-03-19 14:31:19 -070089 /**
90 * Generates the widget preview on {@link AsyncTask#THREAD_POOL_EXECUTOR}. Must be
91 * called on UI thread
92 *
Sunny Goyal5b0e6692015-03-19 14:31:19 -070093 * @return a request id which can be used to cancel the request.
94 */
Sunny Goyal4ddc4012016-03-10 12:02:29 -080095 public PreviewLoadRequest getPreview(WidgetItem item, int previewWidth,
Adam Cohen2e6da152015-05-06 11:42:25 -070096 int previewHeight, WidgetCell caller) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -070097 String size = previewWidth + "x" + previewHeight;
Sunny Goyal4ddc4012016-03-10 12:02:29 -080098 WidgetCacheKey key = new WidgetCacheKey(item.componentName, item.user, size);
Michael Jurka3f4e0702013-02-05 11:21:28 +010099
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800100 PreviewLoadTask task = new PreviewLoadTask(key, item, previewWidth, previewHeight, caller);
Sunny Goyal8ac727b2015-09-23 15:38:09 -0700101 task.executeOnExecutor(Utilities.THREAD_POOL_EXECUTOR);
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700102 return new PreviewLoadRequest(task);
Michael Jurka05713af2013-01-23 12:39:24 +0100103 }
104
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700105 /**
106 * The DB holds the generated previews for various components. Previews can also have different
107 * sizes (landscape vs portrait).
108 */
Sunny Goyal6f709362015-12-17 17:09:36 -0800109 private static class CacheDb extends SQLiteCacheHelper {
Sunny Goyal2d648b02015-08-11 13:56:28 -0700110 private static final int DB_VERSION = 4;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700111
112 private static final String TABLE_NAME = "shortcut_and_widget_previews";
113 private static final String COLUMN_COMPONENT = "componentName";
114 private static final String COLUMN_USER = "profileId";
115 private static final String COLUMN_SIZE = "size";
116 private static final String COLUMN_PACKAGE = "packageName";
117 private static final String COLUMN_LAST_UPDATED = "lastUpdated";
118 private static final String COLUMN_VERSION = "version";
119 private static final String COLUMN_PREVIEW_BITMAP = "preview_bitmap";
Michael Jurka05713af2013-01-23 12:39:24 +0100120
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100121 public CacheDb(Context context) {
Sunny Goyal6f709362015-12-17 17:09:36 -0800122 super(context, LauncherFiles.WIDGET_PREVIEWS_DB, DB_VERSION, TABLE_NAME);
Michael Jurka05713af2013-01-23 12:39:24 +0100123 }
124
125 @Override
Sunny Goyal6f709362015-12-17 17:09:36 -0800126 public void onCreateTable(SQLiteDatabase database) {
Michael Jurka32b7a092013-02-07 20:06:49 +0100127 database.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" +
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700128 COLUMN_COMPONENT + " TEXT NOT NULL, " +
129 COLUMN_USER + " INTEGER NOT NULL, " +
Michael Jurka05713af2013-01-23 12:39:24 +0100130 COLUMN_SIZE + " TEXT NOT NULL, " +
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700131 COLUMN_PACKAGE + " TEXT NOT NULL, " +
132 COLUMN_LAST_UPDATED + " INTEGER NOT NULL DEFAULT 0, " +
133 COLUMN_VERSION + " INTEGER NOT NULL DEFAULT 0, " +
134 COLUMN_PREVIEW_BITMAP + " BLOB, " +
135 "PRIMARY KEY (" + COLUMN_COMPONENT + ", " + COLUMN_USER + ", " + COLUMN_SIZE + ") " +
Michael Jurka32b7a092013-02-07 20:06:49 +0100136 ");");
Michael Jurka05713af2013-01-23 12:39:24 +0100137 }
Michael Jurka05713af2013-01-23 12:39:24 +0100138 }
139
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700140 @Thunk void writeToDb(WidgetCacheKey key, long[] versions, Bitmap preview) {
Michael Jurka05713af2013-01-23 12:39:24 +0100141 ContentValues values = new ContentValues();
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700142 values.put(CacheDb.COLUMN_COMPONENT, key.componentName.flattenToShortString());
143 values.put(CacheDb.COLUMN_USER, mUserManager.getSerialNumberForUser(key.user));
144 values.put(CacheDb.COLUMN_SIZE, key.size);
145 values.put(CacheDb.COLUMN_PACKAGE, key.componentName.getPackageName());
146 values.put(CacheDb.COLUMN_VERSION, versions[0]);
147 values.put(CacheDb.COLUMN_LAST_UPDATED, versions[1]);
148 values.put(CacheDb.COLUMN_PREVIEW_BITMAP, Utilities.flattenBitmap(preview));
Sunny Goyal6f709362015-12-17 17:09:36 -0800149 mDb.insertOrReplace(values);
Michael Jurka05713af2013-01-23 12:39:24 +0100150 }
151
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700152 public void removePackage(String packageName, UserHandleCompat user) {
153 removePackage(packageName, user, mUserManager.getSerialNumberForUser(user));
154 }
155
156 private void removePackage(String packageName, UserHandleCompat user, long userSerial) {
157 synchronized(mPackageVersions) {
158 mPackageVersions.remove(packageName);
159 }
160
Sunny Goyal6f709362015-12-17 17:09:36 -0800161 mDb.delete(
162 CacheDb.COLUMN_PACKAGE + " = ? AND " + CacheDb.COLUMN_USER + " = ?",
163 new String[]{packageName, Long.toString(userSerial)});
Michael Jurka8ff02ca2013-11-01 14:19:27 +0100164 }
165
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700166 /**
167 * Updates the persistent DB:
168 * 1. Any preview generated for an old package version is removed
169 * 2. Any preview for an absent package is removed
170 * This ensures that we remove entries for packages which changed while the launcher was dead.
171 */
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800172 public void removeObsoletePreviews(ArrayList<? extends ComponentKey> list) {
Sunny Goyal6388b2c2016-04-15 18:03:27 -0700173 Preconditions.assertWorkerThread();
Hyunyoung Song8821ca92015-05-04 16:28:20 -0700174
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700175 LongSparseArray<HashSet<String>> validPackages = new LongSparseArray<>();
176
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800177 for (ComponentKey key : list) {
178 final long userId = mUserManager.getSerialNumberForUser(key.user);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700179 HashSet<String> packages = validPackages.get(userId);
180 if (packages == null) {
181 packages = new HashSet<>();
182 validPackages.put(userId, packages);
183 }
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800184 packages.add(key.componentName.getPackageName());
Michael Jurka05713af2013-01-23 12:39:24 +0100185 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700186
187 LongSparseArray<HashSet<String>> packagesToDelete = new LongSparseArray<>();
188 Cursor c = null;
189 try {
Sunny Goyal6f709362015-12-17 17:09:36 -0800190 c = mDb.query(
191 new String[]{CacheDb.COLUMN_USER, CacheDb.COLUMN_PACKAGE,
192 CacheDb.COLUMN_LAST_UPDATED, CacheDb.COLUMN_VERSION},
193 null, null);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700194 while (c.moveToNext()) {
195 long userId = c.getLong(0);
196 String pkg = c.getString(1);
197 long lastUpdated = c.getLong(2);
198 long version = c.getLong(3);
199
200 HashSet<String> packages = validPackages.get(userId);
201 if (packages != null && packages.contains(pkg)) {
202 long[] versions = getPackageVersion(pkg);
203 if (versions[0] == version && versions[1] == lastUpdated) {
204 // Every thing checks out
205 continue;
206 }
207 }
208
209 // We need to delete this package.
210 packages = packagesToDelete.get(userId);
211 if (packages == null) {
212 packages = new HashSet<>();
213 packagesToDelete.put(userId, packages);
214 }
215 packages.add(pkg);
216 }
217
218 for (int i = 0; i < packagesToDelete.size(); i++) {
219 long userId = packagesToDelete.keyAt(i);
220 UserHandleCompat user = mUserManager.getUserForSerialNumber(userId);
221 for (String pkg : packagesToDelete.valueAt(i)) {
222 removePackage(pkg, user, userId);
223 }
224 }
225 } catch (SQLException e) {
Sunny Goyal6f709362015-12-17 17:09:36 -0800226 Log.e(TAG, "Error updating widget previews", e);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700227 } finally {
228 if (c != null) {
229 c.close();
230 }
231 }
232 }
233
Winson Chung05304db2015-05-18 16:53:20 -0700234 /**
235 * Reads the preview bitmap from the DB or null if the preview is not in the DB.
236 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700237 @Thunk Bitmap readFromDb(WidgetCacheKey key, Bitmap recycle, PreviewLoadTask loadTask) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700238 Cursor cursor = null;
239 try {
Sunny Goyal6f709362015-12-17 17:09:36 -0800240 cursor = mDb.query(
241 new String[]{CacheDb.COLUMN_PREVIEW_BITMAP},
242 CacheDb.COLUMN_COMPONENT + " = ? AND " + CacheDb.COLUMN_USER + " = ? AND "
243 + CacheDb.COLUMN_SIZE + " = ?",
244 new String[]{
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700245 key.componentName.flattenToString(),
246 Long.toString(mUserManager.getSerialNumberForUser(key.user)),
247 key.size
Sunny Goyal6f709362015-12-17 17:09:36 -0800248 });
Winson Chung05304db2015-05-18 16:53:20 -0700249 // If cancelled, skip getting the blob and decoding it into a bitmap
250 if (loadTask.isCancelled()) {
251 return null;
252 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700253 if (cursor.moveToNext()) {
254 byte[] blob = cursor.getBlob(0);
255 BitmapFactory.Options opts = new BitmapFactory.Options();
256 opts.inBitmap = recycle;
Michael Jurka6e27f642013-12-10 13:40:30 +0100257 try {
Winson Chung05304db2015-05-18 16:53:20 -0700258 if (!loadTask.isCancelled()) {
259 return BitmapFactory.decodeByteArray(blob, 0, blob.length, opts);
260 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700261 } catch (Exception e) {
262 return null;
Michael Jurka6e27f642013-12-10 13:40:30 +0100263 }
Michael Jurka05713af2013-01-23 12:39:24 +0100264 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700265 } catch (SQLException e) {
266 Log.w(TAG, "Error loading preview from DB", e);
267 } finally {
268 if (cursor != null) {
269 cursor.close();
270 }
271 }
272 return null;
Michael Jurka05713af2013-01-23 12:39:24 +0100273 }
274
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800275 private Bitmap generatePreview(Launcher launcher, WidgetItem item, Bitmap recycle,
Adam Cohen2e6da152015-05-06 11:42:25 -0700276 int previewWidth, int previewHeight) {
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800277 if (item.widgetInfo != null) {
278 return generateWidgetPreview(launcher, item.widgetInfo,
Adam Cohen2e6da152015-05-06 11:42:25 -0700279 previewWidth, recycle, null);
Michael Jurka05713af2013-01-23 12:39:24 +0100280 } else {
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800281 return generateShortcutPreview(launcher, item.activityInfo,
282 previewWidth, previewHeight, recycle);
Michael Jurka05713af2013-01-23 12:39:24 +0100283 }
284 }
285
Hyunyoung Song3e840f42016-03-01 11:57:44 -0800286 /**
287 * Generates the widget preview from either the {@link AppWidgetManagerCompat} or cache
288 * and add badge at the bottom right corner.
289 *
290 * @param launcher
291 * @param info information about the widget
292 * @param maxPreviewWidth width of the preview on either workspace or tray
293 * @param preview bitmap that can be recycled
294 * @param preScaledWidthOut return the width of the returned bitmap
295 * @return
296 */
Adam Cohen2e6da152015-05-06 11:42:25 -0700297 public Bitmap generateWidgetPreview(Launcher launcher, LauncherAppWidgetProviderInfo info,
Sunny Goyal4cad7532015-03-18 15:56:30 -0700298 int maxPreviewWidth, Bitmap preview, int[] preScaledWidthOut) {
Michael Jurka05713af2013-01-23 12:39:24 +0100299 // Load the preview image if possible
Michael Jurka05713af2013-01-23 12:39:24 +0100300 if (maxPreviewWidth < 0) maxPreviewWidth = Integer.MAX_VALUE;
Michael Jurka05713af2013-01-23 12:39:24 +0100301
302 Drawable drawable = null;
Sunny Goyalffe83f12014-08-14 17:39:34 -0700303 if (info.previewImage != 0) {
Hyunyoung Song3e840f42016-03-01 11:57:44 -0800304 drawable = mWidgetManager.loadPreview(info);
Adrian Roosfa9ffc22014-05-12 15:59:59 +0200305 if (drawable != null) {
306 drawable = mutateOnMainThread(drawable);
307 } else {
Michael Jurka05713af2013-01-23 12:39:24 +0100308 Log.w(TAG, "Can't load widget preview drawable 0x" +
Sunny Goyalffe83f12014-08-14 17:39:34 -0700309 Integer.toHexString(info.previewImage) + " for provider: " + info.provider);
Michael Jurka05713af2013-01-23 12:39:24 +0100310 }
311 }
312
Sunny Goyal4cad7532015-03-18 15:56:30 -0700313 final boolean widgetPreviewExists = (drawable != null);
Sunny Goyal233ee962015-08-03 13:05:01 -0700314 final int spanX = info.spanX;
315 final int spanY = info.spanY;
Sunny Goyal4cad7532015-03-18 15:56:30 -0700316
Michael Jurka05713af2013-01-23 12:39:24 +0100317 int previewWidth;
318 int previewHeight;
Hyunyoung Song3e840f42016-03-01 11:57:44 -0800319
Sunny Goyal4cad7532015-03-18 15:56:30 -0700320 Bitmap tileBitmap = null;
321
Michael Jurka05713af2013-01-23 12:39:24 +0100322 if (widgetPreviewExists) {
323 previewWidth = drawable.getIntrinsicWidth();
324 previewHeight = drawable.getIntrinsicHeight();
325 } else {
326 // Generate a preview image if we couldn't load one
Sunny Goyal4cad7532015-03-18 15:56:30 -0700327 tileBitmap = ((BitmapDrawable) mContext.getResources().getDrawable(
328 R.drawable.widget_tile)).getBitmap();
329 previewWidth = tileBitmap.getWidth() * spanX;
330 previewHeight = tileBitmap.getHeight() * spanY;
Michael Jurka05713af2013-01-23 12:39:24 +0100331 }
332
333 // Scale to fit width only - let the widget preview be clipped in the
334 // vertical dimension
335 float scale = 1f;
336 if (preScaledWidthOut != null) {
337 preScaledWidthOut[0] = previewWidth;
338 }
339 if (previewWidth > maxPreviewWidth) {
Hyunyoung Songb9f932e2015-07-30 15:04:59 -0700340 scale = (maxPreviewWidth - 2 * mProfileBadgeMargin) / (float) (previewWidth);
Michael Jurka05713af2013-01-23 12:39:24 +0100341 }
342 if (scale != 1f) {
343 previewWidth = (int) (scale * previewWidth);
344 previewHeight = (int) (scale * previewHeight);
345 }
346
347 // If a bitmap is passed in, we use it; otherwise, we create a bitmap of the right size
Sunny Goyal4cad7532015-03-18 15:56:30 -0700348 final Canvas c = new Canvas();
Michael Jurka05713af2013-01-23 12:39:24 +0100349 if (preview == null) {
350 preview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700351 c.setBitmap(preview);
352 } else {
353 // Reusing bitmap. Clear it.
354 c.setBitmap(preview);
355 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100356 }
357
358 // Draw the scaled preview into the final bitmap
Hyunyoung Songb9f932e2015-07-30 15:04:59 -0700359 int x = (preview.getWidth() - previewWidth) / 2;
Michael Jurka05713af2013-01-23 12:39:24 +0100360 if (widgetPreviewExists) {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700361 drawable.setBounds(x, 0, x + previewWidth, previewHeight);
362 drawable.draw(c);
Michael Jurka05713af2013-01-23 12:39:24 +0100363 } else {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700364 final Paint p = new Paint();
365 p.setFilterBitmap(true);
Adam Cohen2e6da152015-05-06 11:42:25 -0700366 int appIconSize = launcher.getDeviceProfile().iconSizePx;
Michael Jurka05713af2013-01-23 12:39:24 +0100367
Sunny Goyal4cad7532015-03-18 15:56:30 -0700368 // draw the spanX x spanY tiles
369 final Rect src = new Rect(0, 0, tileBitmap.getWidth(), tileBitmap.getHeight());
370
371 float tileW = scale * tileBitmap.getWidth();
372 float tileH = scale * tileBitmap.getHeight();
373 final RectF dst = new RectF(0, 0, tileW, tileH);
374
375 float tx = x;
376 for (int i = 0; i < spanX; i++, tx += tileW) {
377 float ty = 0;
378 for (int j = 0; j < spanY; j++, ty += tileH) {
379 dst.offsetTo(tx, ty);
380 c.drawBitmap(tileBitmap, src, dst, p);
381 }
Michael Jurka05713af2013-01-23 12:39:24 +0100382 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700383
384 // Draw the icon in the top left corner
385 // TODO: use top right for RTL
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700386 int minOffset = (int) (appIconSize * WIDGET_PREVIEW_ICON_PADDING_PERCENTAGE);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700387 int smallestSide = Math.min(previewWidth, previewHeight);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700388 float iconScale = Math.min((float) smallestSide / (appIconSize + 2 * minOffset), scale);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700389
390 try {
Hyunyoung Song3e840f42016-03-01 11:57:44 -0800391 Drawable icon = mWidgetManager.loadIcon(info, mIconCache);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700392 if (icon != null) {
Sunny Goyal1ba7e362015-10-26 10:42:12 -0700393 icon = mutateOnMainThread(icon);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700394 int hoffset = (int) ((tileW - appIconSize * iconScale) / 2) + x;
395 int yoffset = (int) ((tileH - appIconSize * iconScale) / 2);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700396 icon.setBounds(hoffset, yoffset,
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700397 hoffset + (int) (appIconSize * iconScale),
398 yoffset + (int) (appIconSize * iconScale));
Sunny Goyal4cad7532015-03-18 15:56:30 -0700399 icon.draw(c);
400 }
Hyunyoung Song3e840f42016-03-01 11:57:44 -0800401 } catch (Resources.NotFoundException e) {
402 }
Michael Jurka05713af2013-01-23 12:39:24 +0100403 c.setBitmap(null);
404 }
Hyunyoung Song3e840f42016-03-01 11:57:44 -0800405 int imageWidth = Math.min(preview.getWidth(), previewWidth + mProfileBadgeMargin);
Hyunyoung Song41e33692015-06-15 12:26:54 -0700406 int imageHeight = Math.min(preview.getHeight(), previewHeight + mProfileBadgeMargin);
Hyunyoung Song3e840f42016-03-01 11:57:44 -0800407 return mWidgetManager.getBadgeBitmap(info, preview, imageWidth, imageHeight);
Michael Jurka05713af2013-01-23 12:39:24 +0100408 }
409
410 private Bitmap generateShortcutPreview(
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800411 Launcher launcher, ActivityInfo info, int maxWidth, int maxHeight, Bitmap preview) {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700412 final Canvas c = new Canvas();
413 if (preview == null) {
Michael Jurka05713af2013-01-23 12:39:24 +0100414 preview = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700415 c.setBitmap(preview);
416 } else if (preview.getWidth() != maxWidth || preview.getHeight() != maxHeight) {
417 throw new RuntimeException("Improperly sized bitmap passed as argument");
418 } else {
419 // Reusing bitmap. Clear it.
420 c.setBitmap(preview);
421 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100422 }
423
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800424 Drawable icon = mutateOnMainThread(mIconCache.getFullResIcon(info));
Sunny Goyal4cad7532015-03-18 15:56:30 -0700425 icon.setFilterBitmap(true);
426
Michael Jurka05713af2013-01-23 12:39:24 +0100427 // Draw a desaturated/scaled version of the icon in the background as a watermark
Sunny Goyal4cad7532015-03-18 15:56:30 -0700428 ColorMatrix colorMatrix = new ColorMatrix();
429 colorMatrix.setSaturation(0);
430 icon.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
431 icon.setAlpha((int) (255 * 0.06f));
432
433 Resources res = mContext.getResources();
434 int paddingTop = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_top);
435 int paddingLeft = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_left);
436 int paddingRight = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_right);
437 int scaledIconWidth = (maxWidth - paddingLeft - paddingRight);
438 icon.setBounds(paddingLeft, paddingTop,
439 paddingLeft + scaledIconWidth, paddingTop + scaledIconWidth);
440 icon.draw(c);
441
442 // Draw the final icon at top left corner.
443 // TODO: use top right for RTL
Adam Cohen2e6da152015-05-06 11:42:25 -0700444 int appIconSize = launcher.getDeviceProfile().iconSizePx;
445
Sunny Goyal4cad7532015-03-18 15:56:30 -0700446 icon.setAlpha(255);
447 icon.setColorFilter(null);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700448 icon.setBounds(0, 0, appIconSize, appIconSize);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700449 icon.draw(c);
450
Michael Jurka05713af2013-01-23 12:39:24 +0100451 c.setBitmap(null);
Michael Jurka05713af2013-01-23 12:39:24 +0100452 return preview;
453 }
454
Adrian Roos65d60e22014-04-15 21:07:49 +0200455 private Drawable mutateOnMainThread(final Drawable drawable) {
456 try {
457 return mMainThreadExecutor.submit(new Callable<Drawable>() {
458 @Override
459 public Drawable call() throws Exception {
460 return drawable.mutate();
461 }
462 }).get();
463 } catch (InterruptedException e) {
464 Thread.currentThread().interrupt();
465 throw new RuntimeException(e);
466 } catch (ExecutionException e) {
467 throw new RuntimeException(e);
468 }
469 }
Adrian Roos1f375ab2014-04-28 18:26:38 +0200470
Adrian Roos1f375ab2014-04-28 18:26:38 +0200471 /**
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700472 * @return an array of containing versionCode and lastUpdatedTime for the package.
Adrian Roos1f375ab2014-04-28 18:26:38 +0200473 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700474 @Thunk long[] getPackageVersion(String packageName) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700475 synchronized (mPackageVersions) {
476 long[] versions = mPackageVersions.get(packageName);
477 if (versions == null) {
478 versions = new long[2];
Adrian Roos1f375ab2014-04-28 18:26:38 +0200479 try {
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800480 PackageInfo info = mContext.getPackageManager().getPackageInfo(packageName,
481 PackageManager.GET_UNINSTALLED_PACKAGES);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700482 versions[0] = info.versionCode;
483 versions[1] = info.lastUpdateTime;
484 } catch (NameNotFoundException e) {
485 Log.e(TAG, "PackageInfo not found", e);
486 }
487 mPackageVersions.put(packageName, versions);
488 }
489 return versions;
490 }
491 }
492
493 /**
494 * A request Id which can be used by the client to cancel any request.
495 */
496 public class PreviewLoadRequest {
497
Sunny Goyalb4cbea42015-06-16 15:10:36 -0700498 @Thunk final PreviewLoadTask mTask;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700499
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700500 public PreviewLoadRequest(PreviewLoadTask task) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700501 mTask = task;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700502 }
503
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700504 public void cleanup() {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700505 if (mTask != null) {
506 mTask.cancel(true);
507 }
508
Winson Chung05304db2015-05-18 16:53:20 -0700509 // This only handles the case where the PreviewLoadTask is cancelled after the task has
510 // successfully completed (including having written to disk when necessary). In the
511 // other cases where it is cancelled while the task is running, it will be cleaned up
512 // in the tasks's onCancelled() call, and if cancelled while the task is writing to
513 // disk, it will be cancelled in the task's onPostExecute() call.
514 if (mTask.mBitmapToRecycle != null) {
Hyunyoung Songe98f4a42015-06-16 10:45:24 -0700515 mWorkerHandler.post(new Runnable() {
516 @Override
517 public void run() {
518 synchronized (mUnusedBitmaps) {
519 mUnusedBitmaps.add(mTask.mBitmapToRecycle);
520 }
521 mTask.mBitmapToRecycle = null;
522 }
523 });
Adrian Roos1f375ab2014-04-28 18:26:38 +0200524 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700525 }
526 }
527
528 public class PreviewLoadTask extends AsyncTask<Void, Void, Bitmap> {
Sunny Goyal316490e2015-06-02 09:38:28 -0700529 @Thunk final WidgetCacheKey mKey;
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800530 private final WidgetItem mInfo;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700531 private final int mPreviewHeight;
532 private final int mPreviewWidth;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700533 private final WidgetCell mCaller;
Sunny Goyal316490e2015-06-02 09:38:28 -0700534 @Thunk long[] mVersions;
535 @Thunk Bitmap mBitmapToRecycle;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700536
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800537 PreviewLoadTask(WidgetCacheKey key, WidgetItem info, int previewWidth,
Hyunyoung Song3f471442015-04-08 19:01:34 -0700538 int previewHeight, WidgetCell caller) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700539 mKey = key;
540 mInfo = info;
541 mPreviewHeight = previewHeight;
542 mPreviewWidth = previewWidth;
543 mCaller = caller;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700544 if (DEBUG) {
545 Log.d(TAG, String.format("%s, %s, %d, %d",
546 mKey, mInfo, mPreviewHeight, mPreviewWidth));
547 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700548 }
549
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700550 @Override
551 protected Bitmap doInBackground(Void... params) {
552 Bitmap unusedBitmap = null;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700553
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700554 // If already cancelled before this gets to run in the background, then return early
555 if (isCancelled()) {
556 return null;
557 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700558 synchronized (mUnusedBitmaps) {
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700559 // Check if we can re-use a bitmap
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700560 for (Bitmap candidate : mUnusedBitmaps) {
561 if (candidate != null && candidate.isMutable() &&
562 candidate.getWidth() == mPreviewWidth &&
563 candidate.getHeight() == mPreviewHeight) {
564 unusedBitmap = candidate;
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700565 mUnusedBitmaps.remove(unusedBitmap);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700566 break;
567 }
568 }
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700569 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700570
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700571 // 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);
Adrian Roos1f375ab2014-04-28 18:26:38 +0200574 }
Winson Chung05304db2015-05-18 16:53:20 -0700575 // If cancelled now, don't bother reading the preview from the DB
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700576 if (isCancelled()) {
Winson Chung05304db2015-05-18 16:53:20 -0700577 return unusedBitmap;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700578 }
Winson Chung05304db2015-05-18 16:53:20 -0700579 Bitmap preview = readFromDb(mKey, unusedBitmap, this);
580 // Only consider generating the preview if we have not cancelled the task already
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700581 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.
Winson Chung05304db2015-05-18 16:53:20 -0700585 mVersions = getPackageVersion(mKey.componentName.getPackageName());
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700586
Andrew Sappersteinabef55a2016-06-19 12:49:00 -0700587 Launcher launcher = Launcher.getLauncher(mCaller.getContext());
Adam Cohen2e6da152015-05-06 11:42:25 -0700588
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700589 // it's not in the db... we need to generate it
Adam Cohen2e6da152015-05-06 11:42:25 -0700590 preview = generatePreview(launcher, mInfo, unusedBitmap, mPreviewWidth, mPreviewHeight);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700591 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700592 return preview;
593 }
594
595 @Override
Winson Chung05304db2015-05-18 16:53:20 -0700596 protected void onPostExecute(final Bitmap preview) {
597 mCaller.applyPreview(preview);
598
599 // Write the generated preview to the DB in the worker thread
600 if (mVersions != null) {
601 mWorkerHandler.post(new Runnable() {
602 @Override
603 public void run() {
604 if (!isCancelled()) {
605 // If we are still using this preview, then write it to the DB and then
606 // let the normal clear mechanism recycle the bitmap
607 writeToDb(mKey, mVersions, preview);
608 mBitmapToRecycle = preview;
609 } else {
610 // If we've already cancelled, then skip writing the bitmap to the DB
611 // and manually add the bitmap back to the recycled set
612 synchronized (mUnusedBitmaps) {
613 mUnusedBitmaps.add(preview);
614 }
615 }
616 }
617 });
618 } else {
619 // If we don't need to write to disk, then ensure the preview gets recycled by
620 // the normal clear mechanism
621 mBitmapToRecycle = preview;
622 }
623 }
624
625 @Override
Hyunyoung Songe98f4a42015-06-16 10:45:24 -0700626 protected void onCancelled(final Bitmap preview) {
Winson Chung05304db2015-05-18 16:53:20 -0700627 // If we've cancelled while the task is running, then can return the bitmap to the
628 // recycled set immediately. Otherwise, it will be recycled after the preview is written
629 // to disk.
630 if (preview != null) {
Hyunyoung Songe98f4a42015-06-16 10:45:24 -0700631 mWorkerHandler.post(new Runnable() {
632 @Override
633 public void run() {
634 synchronized (mUnusedBitmaps) {
635 mUnusedBitmaps.add(preview);
636 }
637 }
638 });
Winson Chung05304db2015-05-18 16:53:20 -0700639 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700640 }
641 }
642
643 private static final class WidgetCacheKey extends ComponentKey {
644
645 // TODO: remove dependency on size
Sunny Goyal316490e2015-06-02 09:38:28 -0700646 @Thunk final String size;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700647
648 public WidgetCacheKey(ComponentName componentName, UserHandleCompat user, String size) {
649 super(componentName, user);
650 this.size = size;
651 }
652
653 @Override
654 public int hashCode() {
655 return super.hashCode() ^ size.hashCode();
656 }
657
658 @Override
659 public boolean equals(Object o) {
660 return super.equals(o) && ((WidgetCacheKey) o).size.equals(size);
Adrian Roos1f375ab2014-04-28 18:26:38 +0200661 }
662 }
Michael Jurka05713af2013-01-23 12:39:24 +0100663}