blob: 3512210c76994b97e2cd38775473218c463e4e39 [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 Goyal5b0e6692015-03-19 14:31:19 -07006import android.content.pm.PackageInfo;
Sunny Goyal4ddc4012016-03-10 12:02:29 -08007import android.content.pm.PackageManager;
Sunny Goyal5b0e6692015-03-19 14:31:19 -07008import android.content.pm.PackageManager.NameNotFoundException;
Michael Jurka05713af2013-01-23 12:39:24 +01009import android.content.res.Resources;
10import android.database.Cursor;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070011import android.database.SQLException;
Michael Jurka05713af2013-01-23 12:39:24 +010012import android.database.sqlite.SQLiteDatabase;
Michael Jurka05713af2013-01-23 12:39:24 +010013import android.graphics.Bitmap;
14import android.graphics.Bitmap.Config;
15import android.graphics.BitmapFactory;
16import android.graphics.Canvas;
17import android.graphics.ColorMatrix;
18import android.graphics.ColorMatrixColorFilter;
19import android.graphics.Paint;
20import android.graphics.PorterDuff;
Sunny Goyal92bbfa12017-02-07 15:06:32 -080021import android.graphics.PorterDuffXfermode;
Sunny Goyal4cad7532015-03-18 15:56:30 -070022import android.graphics.RectF;
Michael Jurka05713af2013-01-23 12:39:24 +010023import android.graphics.drawable.Drawable;
24import android.os.AsyncTask;
Winson Chung05304db2015-05-18 16:53:20 -070025import android.os.Handler;
Sunny Goyal7c74e4a2016-12-15 15:53:17 -080026import android.os.UserHandle;
Michael Jurka05713af2013-01-23 12:39:24 +010027import android.util.Log;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070028import android.util.LongSparseArray;
Sunny Goyal383c5072015-06-12 21:18:53 -070029
Sunny Goyalffe83f12014-08-14 17:39:34 -070030import com.android.launcher3.compat.AppWidgetManagerCompat;
Sunny Goyal782f0c92017-01-19 10:27:54 -080031import com.android.launcher3.compat.ShortcutConfigActivityInfo;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070032import com.android.launcher3.compat.UserManagerCompat;
Sunny Goyal92bbfa12017-02-07 15:06:32 -080033import com.android.launcher3.graphics.ShadowGenerator;
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
Sunny Goyal5b0e6692015-03-19 14:31:19 -070055 private final HashMap<String, long[]> mPackageVersions = new HashMap<>();
Hyunyoung Song559d90d2015-04-28 15:06:45 -070056
57 /**
58 * Weak reference objects, do not prevent their referents from being made finalizable,
59 * finalized, and then reclaimed.
Hyunyoung Songe98f4a42015-06-16 10:45:24 -070060 * Note: synchronized block used for this variable is expensive and the block should always
61 * be posted to a background thread.
Hyunyoung Song559d90d2015-04-28 15:06:45 -070062 */
Sunny Goyalb4cbea42015-06-16 15:10:36 -070063 @Thunk final Set<Bitmap> mUnusedBitmaps =
Hyunyoung Song559d90d2015-04-28 15:06:45 -070064 Collections.newSetFromMap(new WeakHashMap<Bitmap, Boolean>());
Sunny Goyal4cad7532015-03-18 15:56:30 -070065
66 private final Context mContext;
Sunny Goyalffe83f12014-08-14 17:39:34 -070067 private final IconCache mIconCache;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070068 private final UserManagerCompat mUserManager;
Hyunyoung Song3e840f42016-03-01 11:57:44 -080069 private final AppWidgetManagerCompat mWidgetManager;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070070 private final CacheDb mDb;
Michael Jurka05713af2013-01-23 12:39:24 +010071
Adrian Roos65d60e22014-04-15 21:07:49 +020072 private final MainThreadExecutor mMainThreadExecutor = new MainThreadExecutor();
Sunny Goyal316490e2015-06-02 09:38:28 -070073 @Thunk final Handler mWorkerHandler;
Adrian Roos65d60e22014-04-15 21:07:49 +020074
Sunny Goyal383c5072015-06-12 21:18:53 -070075 public WidgetPreviewLoader(Context context, IconCache iconCache) {
Chris Wrenfd13c712013-09-27 15:45:19 -040076 mContext = context;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070077 mIconCache = iconCache;
Hyunyoung Song3e840f42016-03-01 11:57:44 -080078 mWidgetManager = AppWidgetManagerCompat.getInstance(context);
Sunny Goyal5b0e6692015-03-19 14:31:19 -070079 mUserManager = UserManagerCompat.getInstance(context);
80 mDb = new CacheDb(context);
Winson Chung05304db2015-05-18 16:53:20 -070081 mWorkerHandler = new Handler(LauncherModel.getWorkerLooper());
Michael Jurka3f4e0702013-02-05 11:21:28 +010082 }
Sunny Goyalffe83f12014-08-14 17:39:34 -070083
Sunny Goyal5b0e6692015-03-19 14:31:19 -070084 /**
85 * Generates the widget preview on {@link AsyncTask#THREAD_POOL_EXECUTOR}. Must be
86 * called on UI thread
87 *
Sunny Goyal5b0e6692015-03-19 14:31:19 -070088 * @return a request id which can be used to cancel the request.
89 */
Sunny Goyal4ddc4012016-03-10 12:02:29 -080090 public PreviewLoadRequest getPreview(WidgetItem item, int previewWidth,
Adam Cohen2e6da152015-05-06 11:42:25 -070091 int previewHeight, WidgetCell caller) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -070092 String size = previewWidth + "x" + previewHeight;
Sunny Goyal4ddc4012016-03-10 12:02:29 -080093 WidgetCacheKey key = new WidgetCacheKey(item.componentName, item.user, size);
Michael Jurka3f4e0702013-02-05 11:21:28 +010094
Sunny Goyal4ddc4012016-03-10 12:02:29 -080095 PreviewLoadTask task = new PreviewLoadTask(key, item, previewWidth, previewHeight, caller);
Sunny Goyal8ac727b2015-09-23 15:38:09 -070096 task.executeOnExecutor(Utilities.THREAD_POOL_EXECUTOR);
Hyunyoung Song559d90d2015-04-28 15:06:45 -070097 return new PreviewLoadRequest(task);
Michael Jurka05713af2013-01-23 12:39:24 +010098 }
99
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700100 /**
101 * The DB holds the generated previews for various components. Previews can also have different
102 * sizes (landscape vs portrait).
103 */
Sunny Goyal6f709362015-12-17 17:09:36 -0800104 private static class CacheDb extends SQLiteCacheHelper {
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800105 private static final int DB_VERSION = 6;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700106
107 private static final String TABLE_NAME = "shortcut_and_widget_previews";
108 private static final String COLUMN_COMPONENT = "componentName";
109 private static final String COLUMN_USER = "profileId";
110 private static final String COLUMN_SIZE = "size";
111 private static final String COLUMN_PACKAGE = "packageName";
112 private static final String COLUMN_LAST_UPDATED = "lastUpdated";
113 private static final String COLUMN_VERSION = "version";
114 private static final String COLUMN_PREVIEW_BITMAP = "preview_bitmap";
Michael Jurka05713af2013-01-23 12:39:24 +0100115
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100116 public CacheDb(Context context) {
Sunny Goyal6f709362015-12-17 17:09:36 -0800117 super(context, LauncherFiles.WIDGET_PREVIEWS_DB, DB_VERSION, TABLE_NAME);
Michael Jurka05713af2013-01-23 12:39:24 +0100118 }
119
120 @Override
Sunny Goyal6f709362015-12-17 17:09:36 -0800121 public void onCreateTable(SQLiteDatabase database) {
Michael Jurka32b7a092013-02-07 20:06:49 +0100122 database.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" +
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700123 COLUMN_COMPONENT + " TEXT NOT NULL, " +
124 COLUMN_USER + " INTEGER NOT NULL, " +
Michael Jurka05713af2013-01-23 12:39:24 +0100125 COLUMN_SIZE + " TEXT NOT NULL, " +
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700126 COLUMN_PACKAGE + " TEXT NOT NULL, " +
127 COLUMN_LAST_UPDATED + " INTEGER NOT NULL DEFAULT 0, " +
128 COLUMN_VERSION + " INTEGER NOT NULL DEFAULT 0, " +
129 COLUMN_PREVIEW_BITMAP + " BLOB, " +
130 "PRIMARY KEY (" + COLUMN_COMPONENT + ", " + COLUMN_USER + ", " + COLUMN_SIZE + ") " +
Michael Jurka32b7a092013-02-07 20:06:49 +0100131 ");");
Michael Jurka05713af2013-01-23 12:39:24 +0100132 }
Michael Jurka05713af2013-01-23 12:39:24 +0100133 }
134
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700135 @Thunk void writeToDb(WidgetCacheKey key, long[] versions, Bitmap preview) {
Michael Jurka05713af2013-01-23 12:39:24 +0100136 ContentValues values = new ContentValues();
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700137 values.put(CacheDb.COLUMN_COMPONENT, key.componentName.flattenToShortString());
138 values.put(CacheDb.COLUMN_USER, mUserManager.getSerialNumberForUser(key.user));
139 values.put(CacheDb.COLUMN_SIZE, key.size);
140 values.put(CacheDb.COLUMN_PACKAGE, key.componentName.getPackageName());
141 values.put(CacheDb.COLUMN_VERSION, versions[0]);
142 values.put(CacheDb.COLUMN_LAST_UPDATED, versions[1]);
143 values.put(CacheDb.COLUMN_PREVIEW_BITMAP, Utilities.flattenBitmap(preview));
Sunny Goyal6f709362015-12-17 17:09:36 -0800144 mDb.insertOrReplace(values);
Michael Jurka05713af2013-01-23 12:39:24 +0100145 }
146
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800147 public void removePackage(String packageName, UserHandle user) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700148 removePackage(packageName, user, mUserManager.getSerialNumberForUser(user));
149 }
150
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800151 private void removePackage(String packageName, UserHandle user, long userSerial) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700152 synchronized(mPackageVersions) {
153 mPackageVersions.remove(packageName);
154 }
155
Sunny Goyal6f709362015-12-17 17:09:36 -0800156 mDb.delete(
157 CacheDb.COLUMN_PACKAGE + " = ? AND " + CacheDb.COLUMN_USER + " = ?",
158 new String[]{packageName, Long.toString(userSerial)});
Michael Jurka8ff02ca2013-11-01 14:19:27 +0100159 }
160
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700161 /**
162 * Updates the persistent DB:
163 * 1. Any preview generated for an old package version is removed
164 * 2. Any preview for an absent package is removed
165 * This ensures that we remove entries for packages which changed while the launcher was dead.
166 */
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800167 public void removeObsoletePreviews(ArrayList<? extends ComponentKey> list) {
Sunny Goyal6388b2c2016-04-15 18:03:27 -0700168 Preconditions.assertWorkerThread();
Hyunyoung Song8821ca92015-05-04 16:28:20 -0700169
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700170 LongSparseArray<HashSet<String>> validPackages = new LongSparseArray<>();
171
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800172 for (ComponentKey key : list) {
173 final long userId = mUserManager.getSerialNumberForUser(key.user);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700174 HashSet<String> packages = validPackages.get(userId);
175 if (packages == null) {
176 packages = new HashSet<>();
177 validPackages.put(userId, packages);
178 }
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800179 packages.add(key.componentName.getPackageName());
Michael Jurka05713af2013-01-23 12:39:24 +0100180 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700181
182 LongSparseArray<HashSet<String>> packagesToDelete = new LongSparseArray<>();
183 Cursor c = null;
184 try {
Sunny Goyal6f709362015-12-17 17:09:36 -0800185 c = mDb.query(
186 new String[]{CacheDb.COLUMN_USER, CacheDb.COLUMN_PACKAGE,
187 CacheDb.COLUMN_LAST_UPDATED, CacheDb.COLUMN_VERSION},
188 null, null);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700189 while (c.moveToNext()) {
190 long userId = c.getLong(0);
191 String pkg = c.getString(1);
192 long lastUpdated = c.getLong(2);
193 long version = c.getLong(3);
194
195 HashSet<String> packages = validPackages.get(userId);
196 if (packages != null && packages.contains(pkg)) {
197 long[] versions = getPackageVersion(pkg);
198 if (versions[0] == version && versions[1] == lastUpdated) {
199 // Every thing checks out
200 continue;
201 }
202 }
203
204 // We need to delete this package.
205 packages = packagesToDelete.get(userId);
206 if (packages == null) {
207 packages = new HashSet<>();
208 packagesToDelete.put(userId, packages);
209 }
210 packages.add(pkg);
211 }
212
213 for (int i = 0; i < packagesToDelete.size(); i++) {
214 long userId = packagesToDelete.keyAt(i);
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800215 UserHandle user = mUserManager.getUserForSerialNumber(userId);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700216 for (String pkg : packagesToDelete.valueAt(i)) {
217 removePackage(pkg, user, userId);
218 }
219 }
220 } catch (SQLException e) {
Sunny Goyal6f709362015-12-17 17:09:36 -0800221 Log.e(TAG, "Error updating widget previews", e);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700222 } finally {
223 if (c != null) {
224 c.close();
225 }
226 }
227 }
228
Winson Chung05304db2015-05-18 16:53:20 -0700229 /**
230 * Reads the preview bitmap from the DB or null if the preview is not in the DB.
231 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700232 @Thunk Bitmap readFromDb(WidgetCacheKey key, Bitmap recycle, PreviewLoadTask loadTask) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700233 Cursor cursor = null;
234 try {
Sunny Goyal6f709362015-12-17 17:09:36 -0800235 cursor = mDb.query(
236 new String[]{CacheDb.COLUMN_PREVIEW_BITMAP},
237 CacheDb.COLUMN_COMPONENT + " = ? AND " + CacheDb.COLUMN_USER + " = ? AND "
238 + CacheDb.COLUMN_SIZE + " = ?",
239 new String[]{
Sunny Goyal3ef86912016-10-27 11:40:06 -0700240 key.componentName.flattenToShortString(),
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700241 Long.toString(mUserManager.getSerialNumberForUser(key.user)),
242 key.size
Sunny Goyal6f709362015-12-17 17:09:36 -0800243 });
Winson Chung05304db2015-05-18 16:53:20 -0700244 // If cancelled, skip getting the blob and decoding it into a bitmap
245 if (loadTask.isCancelled()) {
246 return null;
247 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700248 if (cursor.moveToNext()) {
249 byte[] blob = cursor.getBlob(0);
250 BitmapFactory.Options opts = new BitmapFactory.Options();
251 opts.inBitmap = recycle;
Michael Jurka6e27f642013-12-10 13:40:30 +0100252 try {
Winson Chung05304db2015-05-18 16:53:20 -0700253 if (!loadTask.isCancelled()) {
254 return BitmapFactory.decodeByteArray(blob, 0, blob.length, opts);
255 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700256 } catch (Exception e) {
257 return null;
Michael Jurka6e27f642013-12-10 13:40:30 +0100258 }
Michael Jurka05713af2013-01-23 12:39:24 +0100259 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700260 } catch (SQLException e) {
261 Log.w(TAG, "Error loading preview from DB", e);
262 } finally {
263 if (cursor != null) {
264 cursor.close();
265 }
266 }
267 return null;
Michael Jurka05713af2013-01-23 12:39:24 +0100268 }
269
Sunny Goyal27835952017-01-13 12:15:53 -0800270 private Bitmap generatePreview(BaseActivity launcher, WidgetItem item, Bitmap recycle,
Adam Cohen2e6da152015-05-06 11:42:25 -0700271 int previewWidth, int previewHeight) {
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800272 if (item.widgetInfo != null) {
273 return generateWidgetPreview(launcher, item.widgetInfo,
Adam Cohen2e6da152015-05-06 11:42:25 -0700274 previewWidth, recycle, null);
Michael Jurka05713af2013-01-23 12:39:24 +0100275 } else {
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800276 return generateShortcutPreview(launcher, item.activityInfo,
277 previewWidth, previewHeight, recycle);
Michael Jurka05713af2013-01-23 12:39:24 +0100278 }
279 }
280
Hyunyoung Song3e840f42016-03-01 11:57:44 -0800281 /**
282 * Generates the widget preview from either the {@link AppWidgetManagerCompat} or cache
283 * and add badge at the bottom right corner.
284 *
285 * @param launcher
286 * @param info information about the widget
287 * @param maxPreviewWidth width of the preview on either workspace or tray
288 * @param preview bitmap that can be recycled
289 * @param preScaledWidthOut return the width of the returned bitmap
290 * @return
291 */
Sunny Goyal27835952017-01-13 12:15:53 -0800292 public Bitmap generateWidgetPreview(BaseActivity launcher, LauncherAppWidgetProviderInfo info,
Sunny Goyal4cad7532015-03-18 15:56:30 -0700293 int maxPreviewWidth, Bitmap preview, int[] preScaledWidthOut) {
Michael Jurka05713af2013-01-23 12:39:24 +0100294 // Load the preview image if possible
Michael Jurka05713af2013-01-23 12:39:24 +0100295 if (maxPreviewWidth < 0) maxPreviewWidth = Integer.MAX_VALUE;
Michael Jurka05713af2013-01-23 12:39:24 +0100296
297 Drawable drawable = null;
Sunny Goyalffe83f12014-08-14 17:39:34 -0700298 if (info.previewImage != 0) {
Sunny Goyal2570d102016-10-27 11:38:45 -0700299 try {
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800300 drawable = info.loadPreviewImage(mContext, 0);
Sunny Goyal2570d102016-10-27 11:38:45 -0700301 } catch (OutOfMemoryError e) {
302 Log.w(TAG, "Error loading widget preview for: " + info.provider, e);
303 // During OutOfMemoryError, the previous heap stack is not affected. Catching
304 // an OOM error here should be safe & not affect other parts of launcher.
305 drawable = null;
306 }
Adrian Roosfa9ffc22014-05-12 15:59:59 +0200307 if (drawable != null) {
308 drawable = mutateOnMainThread(drawable);
309 } else {
Michael Jurka05713af2013-01-23 12:39:24 +0100310 Log.w(TAG, "Can't load widget preview drawable 0x" +
Sunny Goyalffe83f12014-08-14 17:39:34 -0700311 Integer.toHexString(info.previewImage) + " for provider: " + info.provider);
Michael Jurka05713af2013-01-23 12:39:24 +0100312 }
313 }
314
Sunny Goyal4cad7532015-03-18 15:56:30 -0700315 final boolean widgetPreviewExists = (drawable != null);
Sunny Goyal233ee962015-08-03 13:05:01 -0700316 final int spanX = info.spanX;
317 final int spanY = info.spanY;
Sunny Goyal4cad7532015-03-18 15:56:30 -0700318
Michael Jurka05713af2013-01-23 12:39:24 +0100319 int previewWidth;
320 int previewHeight;
Hyunyoung Song3e840f42016-03-01 11:57:44 -0800321
Michael Jurka05713af2013-01-23 12:39:24 +0100322 if (widgetPreviewExists) {
323 previewWidth = drawable.getIntrinsicWidth();
324 previewHeight = drawable.getIntrinsicHeight();
325 } else {
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800326 DeviceProfile dp = launcher.getDeviceProfile();
327 int tileSize = Math.min(dp.cellWidthPx, dp.cellHeightPx);
328 previewWidth = tileSize * spanX;
329 previewHeight = tileSize * spanY;
Michael Jurka05713af2013-01-23 12:39:24 +0100330 }
331
332 // Scale to fit width only - let the widget preview be clipped in the
333 // vertical dimension
334 float scale = 1f;
335 if (preScaledWidthOut != null) {
336 preScaledWidthOut[0] = previewWidth;
337 }
338 if (previewWidth > maxPreviewWidth) {
Sunny Goyala2441e82017-01-14 13:40:15 -0800339 scale = maxPreviewWidth / (float) (previewWidth);
Michael Jurka05713af2013-01-23 12:39:24 +0100340 }
341 if (scale != 1f) {
342 previewWidth = (int) (scale * previewWidth);
343 previewHeight = (int) (scale * previewHeight);
344 }
345
346 // 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 -0700347 final Canvas c = new Canvas();
Michael Jurka05713af2013-01-23 12:39:24 +0100348 if (preview == null) {
349 preview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700350 c.setBitmap(preview);
351 } else {
Sunny Goyala2441e82017-01-14 13:40:15 -0800352 // We use the preview bitmap height to determine where the badge will be drawn in the
353 // UI. If its larger than what we need, resize the preview bitmap so that there are
354 // no transparent pixels between the preview and the badge.
355 if (preview.getHeight() > previewHeight) {
356 preview.reconfigure(preview.getWidth(), previewHeight, preview.getConfig());
357 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700358 // Reusing bitmap. Clear it.
359 c.setBitmap(preview);
360 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100361 }
362
363 // Draw the scaled preview into the final bitmap
Hyunyoung Songb9f932e2015-07-30 15:04:59 -0700364 int x = (preview.getWidth() - previewWidth) / 2;
Michael Jurka05713af2013-01-23 12:39:24 +0100365 if (widgetPreviewExists) {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700366 drawable.setBounds(x, 0, x + previewWidth, previewHeight);
367 drawable.draw(c);
Michael Jurka05713af2013-01-23 12:39:24 +0100368 } else {
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800369 Resources res = mContext.getResources();
370 float shadowBlur = res.getDimension(R.dimen.widget_preview_shadow_blur);
371 float keyShadowDistance = res.getDimension(R.dimen.widget_preview_key_shadow_distance);
372 float corner = res.getDimension(R.dimen.widget_preview_corner_radius);
Michael Jurka05713af2013-01-23 12:39:24 +0100373
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800374 RectF boxRect = new RectF(shadowBlur, shadowBlur,
375 previewWidth - shadowBlur, previewHeight - shadowBlur - keyShadowDistance);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700376
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800377 final Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
378 p.setColor(0xFFFFFFFF);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700379
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800380 // Key shadow
381 p.setShadowLayer(shadowBlur, 0, keyShadowDistance,
382 ShadowGenerator.KEY_SHADOW_ALPHA << 24);
383 c.drawRoundRect(boxRect, corner, corner, p);
384
385 // Ambient shadow
386 p.setShadowLayer(shadowBlur, 0, 0, ShadowGenerator.AMBIENT_SHADOW_ALPHA << 24);
387 c.drawRoundRect(boxRect, corner, corner, p);
388
389 // Draw horizontal and vertical lines to represent individual columns.
390 p.clearShadowLayer();
391 p.setStyle(Paint.Style.STROKE);
392 p.setStrokeWidth(res.getDimension(R.dimen.widget_preview_cell_divider_width));
393 p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
394
395 float t = boxRect.left;
396 float tileSize = boxRect.width() / spanX;
397 for (int i = 1; i < spanX; i++) {
398 t += tileSize;
399 c.drawLine(t, 0, t, previewHeight, p);
Michael Jurka05713af2013-01-23 12:39:24 +0100400 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700401
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800402 t = boxRect.top;
403 tileSize = boxRect.height() / spanY;
404 for (int i = 1; i < spanY; i++) {
405 t += tileSize;
406 c.drawLine(0, t, previewWidth, t, p);
407 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700408
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800409 // Draw icon in the center.
Sunny Goyal4cad7532015-03-18 15:56:30 -0700410 try {
Sunny Goyala52ecb02016-12-16 15:04:51 -0800411 Drawable icon = info.getIcon(launcher, mIconCache);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700412 if (icon != null) {
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800413 int appIconSize = launcher.getDeviceProfile().iconSizePx;
414 int iconSize = (int) Math.min(appIconSize * scale,
415 Math.min(boxRect.width(), boxRect.height()));
416
Sunny Goyal1ba7e362015-10-26 10:42:12 -0700417 icon = mutateOnMainThread(icon);
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800418 int hoffset = (previewWidth - iconSize) / 2;
419 int yoffset = (previewHeight - iconSize) / 2;
420 icon.setBounds(hoffset, yoffset, hoffset + iconSize, yoffset + iconSize);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700421 icon.draw(c);
422 }
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800423 } catch (Resources.NotFoundException e) { }
Michael Jurka05713af2013-01-23 12:39:24 +0100424 c.setBitmap(null);
425 }
Sunny Goyala2441e82017-01-14 13:40:15 -0800426 return preview;
Michael Jurka05713af2013-01-23 12:39:24 +0100427 }
428
Sunny Goyal782f0c92017-01-19 10:27:54 -0800429 private Bitmap generateShortcutPreview(BaseActivity launcher, ShortcutConfigActivityInfo info,
430 int maxWidth, int maxHeight, Bitmap preview) {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700431 final Canvas c = new Canvas();
432 if (preview == null) {
Michael Jurka05713af2013-01-23 12:39:24 +0100433 preview = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700434 c.setBitmap(preview);
435 } else if (preview.getWidth() != maxWidth || preview.getHeight() != maxHeight) {
436 throw new RuntimeException("Improperly sized bitmap passed as argument");
437 } else {
438 // Reusing bitmap. Clear it.
439 c.setBitmap(preview);
440 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100441 }
442
Sunny Goyal782f0c92017-01-19 10:27:54 -0800443 Drawable icon = mutateOnMainThread(info.getFullResIcon(mIconCache));
Sunny Goyal4cad7532015-03-18 15:56:30 -0700444 icon.setFilterBitmap(true);
445
Michael Jurka05713af2013-01-23 12:39:24 +0100446 // Draw a desaturated/scaled version of the icon in the background as a watermark
Sunny Goyal4cad7532015-03-18 15:56:30 -0700447 ColorMatrix colorMatrix = new ColorMatrix();
448 colorMatrix.setSaturation(0);
449 icon.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
450 icon.setAlpha((int) (255 * 0.06f));
451
452 Resources res = mContext.getResources();
453 int paddingTop = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_top);
454 int paddingLeft = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_left);
455 int paddingRight = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_right);
456 int scaledIconWidth = (maxWidth - paddingLeft - paddingRight);
457 icon.setBounds(paddingLeft, paddingTop,
458 paddingLeft + scaledIconWidth, paddingTop + scaledIconWidth);
459 icon.draw(c);
460
461 // Draw the final icon at top left corner.
462 // TODO: use top right for RTL
Adam Cohen2e6da152015-05-06 11:42:25 -0700463 int appIconSize = launcher.getDeviceProfile().iconSizePx;
464
Sunny Goyal4cad7532015-03-18 15:56:30 -0700465 icon.setAlpha(255);
466 icon.setColorFilter(null);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700467 icon.setBounds(0, 0, appIconSize, appIconSize);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700468 icon.draw(c);
469
Michael Jurka05713af2013-01-23 12:39:24 +0100470 c.setBitmap(null);
Michael Jurka05713af2013-01-23 12:39:24 +0100471 return preview;
472 }
473
Adrian Roos65d60e22014-04-15 21:07:49 +0200474 private Drawable mutateOnMainThread(final Drawable drawable) {
475 try {
476 return mMainThreadExecutor.submit(new Callable<Drawable>() {
477 @Override
478 public Drawable call() throws Exception {
479 return drawable.mutate();
480 }
481 }).get();
482 } catch (InterruptedException e) {
483 Thread.currentThread().interrupt();
484 throw new RuntimeException(e);
485 } catch (ExecutionException e) {
486 throw new RuntimeException(e);
487 }
488 }
Adrian Roos1f375ab2014-04-28 18:26:38 +0200489
Adrian Roos1f375ab2014-04-28 18:26:38 +0200490 /**
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700491 * @return an array of containing versionCode and lastUpdatedTime for the package.
Adrian Roos1f375ab2014-04-28 18:26:38 +0200492 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700493 @Thunk long[] getPackageVersion(String packageName) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700494 synchronized (mPackageVersions) {
495 long[] versions = mPackageVersions.get(packageName);
496 if (versions == null) {
497 versions = new long[2];
Adrian Roos1f375ab2014-04-28 18:26:38 +0200498 try {
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800499 PackageInfo info = mContext.getPackageManager().getPackageInfo(packageName,
500 PackageManager.GET_UNINSTALLED_PACKAGES);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700501 versions[0] = info.versionCode;
502 versions[1] = info.lastUpdateTime;
503 } catch (NameNotFoundException e) {
504 Log.e(TAG, "PackageInfo not found", e);
505 }
506 mPackageVersions.put(packageName, versions);
507 }
508 return versions;
509 }
510 }
511
512 /**
513 * A request Id which can be used by the client to cancel any request.
514 */
515 public class PreviewLoadRequest {
516
Sunny Goyalb4cbea42015-06-16 15:10:36 -0700517 @Thunk final PreviewLoadTask mTask;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700518
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700519 public PreviewLoadRequest(PreviewLoadTask task) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700520 mTask = task;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700521 }
522
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700523 public void cleanup() {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700524 if (mTask != null) {
525 mTask.cancel(true);
526 }
527
Winson Chung05304db2015-05-18 16:53:20 -0700528 // This only handles the case where the PreviewLoadTask is cancelled after the task has
529 // successfully completed (including having written to disk when necessary). In the
530 // other cases where it is cancelled while the task is running, it will be cleaned up
531 // in the tasks's onCancelled() call, and if cancelled while the task is writing to
532 // disk, it will be cancelled in the task's onPostExecute() call.
533 if (mTask.mBitmapToRecycle != null) {
Hyunyoung Songe98f4a42015-06-16 10:45:24 -0700534 mWorkerHandler.post(new Runnable() {
535 @Override
536 public void run() {
537 synchronized (mUnusedBitmaps) {
538 mUnusedBitmaps.add(mTask.mBitmapToRecycle);
539 }
540 mTask.mBitmapToRecycle = null;
541 }
542 });
Adrian Roos1f375ab2014-04-28 18:26:38 +0200543 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700544 }
545 }
546
547 public class PreviewLoadTask extends AsyncTask<Void, Void, Bitmap> {
Sunny Goyal316490e2015-06-02 09:38:28 -0700548 @Thunk final WidgetCacheKey mKey;
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800549 private final WidgetItem mInfo;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700550 private final int mPreviewHeight;
551 private final int mPreviewWidth;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700552 private final WidgetCell mCaller;
Sunny Goyala2441e82017-01-14 13:40:15 -0800553 private final BaseActivity mActivity;
Sunny Goyal316490e2015-06-02 09:38:28 -0700554 @Thunk long[] mVersions;
555 @Thunk Bitmap mBitmapToRecycle;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700556
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800557 PreviewLoadTask(WidgetCacheKey key, WidgetItem info, int previewWidth,
Hyunyoung Song3f471442015-04-08 19:01:34 -0700558 int previewHeight, WidgetCell caller) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700559 mKey = key;
560 mInfo = info;
561 mPreviewHeight = previewHeight;
562 mPreviewWidth = previewWidth;
563 mCaller = caller;
Sunny Goyala2441e82017-01-14 13:40:15 -0800564 mActivity = BaseActivity.fromContext(mCaller.getContext());
Hyunyoung Song3f471442015-04-08 19:01:34 -0700565 if (DEBUG) {
566 Log.d(TAG, String.format("%s, %s, %d, %d",
567 mKey, mInfo, mPreviewHeight, mPreviewWidth));
568 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700569 }
570
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700571 @Override
572 protected Bitmap doInBackground(Void... params) {
573 Bitmap unusedBitmap = null;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700574
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700575 // If already cancelled before this gets to run in the background, then return early
576 if (isCancelled()) {
577 return null;
578 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700579 synchronized (mUnusedBitmaps) {
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700580 // Check if we can re-use a bitmap
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700581 for (Bitmap candidate : mUnusedBitmaps) {
582 if (candidate != null && candidate.isMutable() &&
583 candidate.getWidth() == mPreviewWidth &&
584 candidate.getHeight() == mPreviewHeight) {
585 unusedBitmap = candidate;
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700586 mUnusedBitmaps.remove(unusedBitmap);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700587 break;
588 }
589 }
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700590 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700591
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700592 // creating a bitmap is expensive. Do not do this inside synchronized block.
593 if (unusedBitmap == null) {
594 unusedBitmap = Bitmap.createBitmap(mPreviewWidth, mPreviewHeight, Config.ARGB_8888);
Adrian Roos1f375ab2014-04-28 18:26:38 +0200595 }
Winson Chung05304db2015-05-18 16:53:20 -0700596 // If cancelled now, don't bother reading the preview from the DB
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700597 if (isCancelled()) {
Winson Chung05304db2015-05-18 16:53:20 -0700598 return unusedBitmap;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700599 }
Winson Chung05304db2015-05-18 16:53:20 -0700600 Bitmap preview = readFromDb(mKey, unusedBitmap, this);
601 // Only consider generating the preview if we have not cancelled the task already
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700602 if (!isCancelled() && preview == null) {
603 // Fetch the version info before we generate the preview, so that, in-case the
604 // app was updated while we are generating the preview, we use the old version info,
605 // which would gets re-written next time.
Sunny Goyal65513ba2017-01-20 11:54:25 -0800606 boolean persistable = mInfo.activityInfo == null
607 || mInfo.activityInfo.isPersistable();
608 mVersions = persistable ? getPackageVersion(mKey.componentName.getPackageName())
609 : null;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700610
611 // it's not in the db... we need to generate it
Sunny Goyala2441e82017-01-14 13:40:15 -0800612 preview = generatePreview(mActivity, mInfo, unusedBitmap, mPreviewWidth, mPreviewHeight);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700613 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700614 return preview;
615 }
616
617 @Override
Winson Chung05304db2015-05-18 16:53:20 -0700618 protected void onPostExecute(final Bitmap preview) {
619 mCaller.applyPreview(preview);
620
621 // Write the generated preview to the DB in the worker thread
622 if (mVersions != null) {
623 mWorkerHandler.post(new Runnable() {
624 @Override
625 public void run() {
626 if (!isCancelled()) {
627 // If we are still using this preview, then write it to the DB and then
628 // let the normal clear mechanism recycle the bitmap
629 writeToDb(mKey, mVersions, preview);
630 mBitmapToRecycle = preview;
631 } else {
632 // If we've already cancelled, then skip writing the bitmap to the DB
633 // and manually add the bitmap back to the recycled set
634 synchronized (mUnusedBitmaps) {
635 mUnusedBitmaps.add(preview);
636 }
637 }
638 }
639 });
640 } else {
641 // If we don't need to write to disk, then ensure the preview gets recycled by
642 // the normal clear mechanism
643 mBitmapToRecycle = preview;
644 }
645 }
646
647 @Override
Hyunyoung Songe98f4a42015-06-16 10:45:24 -0700648 protected void onCancelled(final Bitmap preview) {
Winson Chung05304db2015-05-18 16:53:20 -0700649 // If we've cancelled while the task is running, then can return the bitmap to the
650 // recycled set immediately. Otherwise, it will be recycled after the preview is written
651 // to disk.
652 if (preview != null) {
Hyunyoung Songe98f4a42015-06-16 10:45:24 -0700653 mWorkerHandler.post(new Runnable() {
654 @Override
655 public void run() {
656 synchronized (mUnusedBitmaps) {
657 mUnusedBitmaps.add(preview);
658 }
659 }
660 });
Winson Chung05304db2015-05-18 16:53:20 -0700661 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700662 }
663 }
664
665 private static final class WidgetCacheKey extends ComponentKey {
666
667 // TODO: remove dependency on size
Sunny Goyal316490e2015-06-02 09:38:28 -0700668 @Thunk final String size;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700669
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800670 public WidgetCacheKey(ComponentName componentName, UserHandle user, String size) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700671 super(componentName, user);
672 this.size = size;
673 }
674
675 @Override
676 public int hashCode() {
677 return super.hashCode() ^ size.hashCode();
678 }
679
680 @Override
681 public boolean equals(Object o) {
682 return super.equals(o) && ((WidgetCacheKey) o).size.equals(size);
Adrian Roos1f375ab2014-04-28 18:26:38 +0200683 }
684 }
Michael Jurka05713af2013-01-23 12:39:24 +0100685}