blob: f814bb7c543cad87841f4e45c03970db7bca71e3 [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;
21import android.graphics.Rect;
Sunny Goyal4cad7532015-03-18 15:56:30 -070022import android.graphics.RectF;
Michael Jurka05713af2013-01-23 12:39:24 +010023import android.graphics.drawable.BitmapDrawable;
24import android.graphics.drawable.Drawable;
25import android.os.AsyncTask;
Winson Chung05304db2015-05-18 16:53:20 -070026import android.os.Handler;
Sunny Goyal7c74e4a2016-12-15 15:53:17 -080027import android.os.UserHandle;
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 Goyal782f0c92017-01-19 10:27:54 -080032import com.android.launcher3.compat.ShortcutConfigActivityInfo;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070033import 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;
Michael Jurka05713af2013-01-23 12:39:24 +010073
Adrian Roos65d60e22014-04-15 21:07:49 +020074 private final MainThreadExecutor mMainThreadExecutor = new MainThreadExecutor();
Sunny Goyal316490e2015-06-02 09:38:28 -070075 @Thunk final Handler mWorkerHandler;
Adrian Roos65d60e22014-04-15 21:07:49 +020076
Sunny Goyal383c5072015-06-12 21:18:53 -070077 public WidgetPreviewLoader(Context context, IconCache iconCache) {
Chris Wrenfd13c712013-09-27 15:45:19 -040078 mContext = context;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070079 mIconCache = iconCache;
Hyunyoung Song3e840f42016-03-01 11:57:44 -080080 mWidgetManager = AppWidgetManagerCompat.getInstance(context);
Sunny Goyal5b0e6692015-03-19 14:31:19 -070081 mUserManager = UserManagerCompat.getInstance(context);
82 mDb = new CacheDb(context);
Winson Chung05304db2015-05-18 16:53:20 -070083 mWorkerHandler = new Handler(LauncherModel.getWorkerLooper());
Michael Jurka3f4e0702013-02-05 11:21:28 +010084 }
Sunny Goyalffe83f12014-08-14 17:39:34 -070085
Sunny Goyal5b0e6692015-03-19 14:31:19 -070086 /**
87 * Generates the widget preview on {@link AsyncTask#THREAD_POOL_EXECUTOR}. Must be
88 * called on UI thread
89 *
Sunny Goyal5b0e6692015-03-19 14:31:19 -070090 * @return a request id which can be used to cancel the request.
91 */
Sunny Goyal4ddc4012016-03-10 12:02:29 -080092 public PreviewLoadRequest getPreview(WidgetItem item, int previewWidth,
Adam Cohen2e6da152015-05-06 11:42:25 -070093 int previewHeight, WidgetCell caller) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -070094 String size = previewWidth + "x" + previewHeight;
Sunny Goyal4ddc4012016-03-10 12:02:29 -080095 WidgetCacheKey key = new WidgetCacheKey(item.componentName, item.user, size);
Michael Jurka3f4e0702013-02-05 11:21:28 +010096
Sunny Goyal4ddc4012016-03-10 12:02:29 -080097 PreviewLoadTask task = new PreviewLoadTask(key, item, previewWidth, previewHeight, caller);
Sunny Goyal8ac727b2015-09-23 15:38:09 -070098 task.executeOnExecutor(Utilities.THREAD_POOL_EXECUTOR);
Hyunyoung Song559d90d2015-04-28 15:06:45 -070099 return new PreviewLoadRequest(task);
Michael Jurka05713af2013-01-23 12:39:24 +0100100 }
101
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700102 /**
103 * The DB holds the generated previews for various components. Previews can also have different
104 * sizes (landscape vs portrait).
105 */
Sunny Goyal6f709362015-12-17 17:09:36 -0800106 private static class CacheDb extends SQLiteCacheHelper {
Sunny Goyala2441e82017-01-14 13:40:15 -0800107 private static final int DB_VERSION = 5;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700108
109 private static final String TABLE_NAME = "shortcut_and_widget_previews";
110 private static final String COLUMN_COMPONENT = "componentName";
111 private static final String COLUMN_USER = "profileId";
112 private static final String COLUMN_SIZE = "size";
113 private static final String COLUMN_PACKAGE = "packageName";
114 private static final String COLUMN_LAST_UPDATED = "lastUpdated";
115 private static final String COLUMN_VERSION = "version";
116 private static final String COLUMN_PREVIEW_BITMAP = "preview_bitmap";
Michael Jurka05713af2013-01-23 12:39:24 +0100117
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100118 public CacheDb(Context context) {
Sunny Goyal6f709362015-12-17 17:09:36 -0800119 super(context, LauncherFiles.WIDGET_PREVIEWS_DB, DB_VERSION, TABLE_NAME);
Michael Jurka05713af2013-01-23 12:39:24 +0100120 }
121
122 @Override
Sunny Goyal6f709362015-12-17 17:09:36 -0800123 public void onCreateTable(SQLiteDatabase database) {
Michael Jurka32b7a092013-02-07 20:06:49 +0100124 database.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" +
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700125 COLUMN_COMPONENT + " TEXT NOT NULL, " +
126 COLUMN_USER + " INTEGER NOT NULL, " +
Michael Jurka05713af2013-01-23 12:39:24 +0100127 COLUMN_SIZE + " TEXT NOT NULL, " +
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700128 COLUMN_PACKAGE + " TEXT NOT NULL, " +
129 COLUMN_LAST_UPDATED + " INTEGER NOT NULL DEFAULT 0, " +
130 COLUMN_VERSION + " INTEGER NOT NULL DEFAULT 0, " +
131 COLUMN_PREVIEW_BITMAP + " BLOB, " +
132 "PRIMARY KEY (" + COLUMN_COMPONENT + ", " + COLUMN_USER + ", " + COLUMN_SIZE + ") " +
Michael Jurka32b7a092013-02-07 20:06:49 +0100133 ");");
Michael Jurka05713af2013-01-23 12:39:24 +0100134 }
Michael Jurka05713af2013-01-23 12:39:24 +0100135 }
136
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700137 @Thunk void writeToDb(WidgetCacheKey key, long[] versions, Bitmap preview) {
Michael Jurka05713af2013-01-23 12:39:24 +0100138 ContentValues values = new ContentValues();
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700139 values.put(CacheDb.COLUMN_COMPONENT, key.componentName.flattenToShortString());
140 values.put(CacheDb.COLUMN_USER, mUserManager.getSerialNumberForUser(key.user));
141 values.put(CacheDb.COLUMN_SIZE, key.size);
142 values.put(CacheDb.COLUMN_PACKAGE, key.componentName.getPackageName());
143 values.put(CacheDb.COLUMN_VERSION, versions[0]);
144 values.put(CacheDb.COLUMN_LAST_UPDATED, versions[1]);
145 values.put(CacheDb.COLUMN_PREVIEW_BITMAP, Utilities.flattenBitmap(preview));
Sunny Goyal6f709362015-12-17 17:09:36 -0800146 mDb.insertOrReplace(values);
Michael Jurka05713af2013-01-23 12:39:24 +0100147 }
148
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800149 public void removePackage(String packageName, UserHandle user) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700150 removePackage(packageName, user, mUserManager.getSerialNumberForUser(user));
151 }
152
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800153 private void removePackage(String packageName, UserHandle user, long userSerial) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700154 synchronized(mPackageVersions) {
155 mPackageVersions.remove(packageName);
156 }
157
Sunny Goyal6f709362015-12-17 17:09:36 -0800158 mDb.delete(
159 CacheDb.COLUMN_PACKAGE + " = ? AND " + CacheDb.COLUMN_USER + " = ?",
160 new String[]{packageName, Long.toString(userSerial)});
Michael Jurka8ff02ca2013-11-01 14:19:27 +0100161 }
162
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700163 /**
164 * Updates the persistent DB:
165 * 1. Any preview generated for an old package version is removed
166 * 2. Any preview for an absent package is removed
167 * This ensures that we remove entries for packages which changed while the launcher was dead.
168 */
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800169 public void removeObsoletePreviews(ArrayList<? extends ComponentKey> list) {
Sunny Goyal6388b2c2016-04-15 18:03:27 -0700170 Preconditions.assertWorkerThread();
Hyunyoung Song8821ca92015-05-04 16:28:20 -0700171
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700172 LongSparseArray<HashSet<String>> validPackages = new LongSparseArray<>();
173
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800174 for (ComponentKey key : list) {
175 final long userId = mUserManager.getSerialNumberForUser(key.user);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700176 HashSet<String> packages = validPackages.get(userId);
177 if (packages == null) {
178 packages = new HashSet<>();
179 validPackages.put(userId, packages);
180 }
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800181 packages.add(key.componentName.getPackageName());
Michael Jurka05713af2013-01-23 12:39:24 +0100182 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700183
184 LongSparseArray<HashSet<String>> packagesToDelete = new LongSparseArray<>();
185 Cursor c = null;
186 try {
Sunny Goyal6f709362015-12-17 17:09:36 -0800187 c = mDb.query(
188 new String[]{CacheDb.COLUMN_USER, CacheDb.COLUMN_PACKAGE,
189 CacheDb.COLUMN_LAST_UPDATED, CacheDb.COLUMN_VERSION},
190 null, null);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700191 while (c.moveToNext()) {
192 long userId = c.getLong(0);
193 String pkg = c.getString(1);
194 long lastUpdated = c.getLong(2);
195 long version = c.getLong(3);
196
197 HashSet<String> packages = validPackages.get(userId);
198 if (packages != null && packages.contains(pkg)) {
199 long[] versions = getPackageVersion(pkg);
200 if (versions[0] == version && versions[1] == lastUpdated) {
201 // Every thing checks out
202 continue;
203 }
204 }
205
206 // We need to delete this package.
207 packages = packagesToDelete.get(userId);
208 if (packages == null) {
209 packages = new HashSet<>();
210 packagesToDelete.put(userId, packages);
211 }
212 packages.add(pkg);
213 }
214
215 for (int i = 0; i < packagesToDelete.size(); i++) {
216 long userId = packagesToDelete.keyAt(i);
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800217 UserHandle user = mUserManager.getUserForSerialNumber(userId);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700218 for (String pkg : packagesToDelete.valueAt(i)) {
219 removePackage(pkg, user, userId);
220 }
221 }
222 } catch (SQLException e) {
Sunny Goyal6f709362015-12-17 17:09:36 -0800223 Log.e(TAG, "Error updating widget previews", e);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700224 } finally {
225 if (c != null) {
226 c.close();
227 }
228 }
229 }
230
Winson Chung05304db2015-05-18 16:53:20 -0700231 /**
232 * Reads the preview bitmap from the DB or null if the preview is not in the DB.
233 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700234 @Thunk Bitmap readFromDb(WidgetCacheKey key, Bitmap recycle, PreviewLoadTask loadTask) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700235 Cursor cursor = null;
236 try {
Sunny Goyal6f709362015-12-17 17:09:36 -0800237 cursor = mDb.query(
238 new String[]{CacheDb.COLUMN_PREVIEW_BITMAP},
239 CacheDb.COLUMN_COMPONENT + " = ? AND " + CacheDb.COLUMN_USER + " = ? AND "
240 + CacheDb.COLUMN_SIZE + " = ?",
241 new String[]{
Sunny Goyal3ef86912016-10-27 11:40:06 -0700242 key.componentName.flattenToShortString(),
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700243 Long.toString(mUserManager.getSerialNumberForUser(key.user)),
244 key.size
Sunny Goyal6f709362015-12-17 17:09:36 -0800245 });
Winson Chung05304db2015-05-18 16:53:20 -0700246 // If cancelled, skip getting the blob and decoding it into a bitmap
247 if (loadTask.isCancelled()) {
248 return null;
249 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700250 if (cursor.moveToNext()) {
251 byte[] blob = cursor.getBlob(0);
252 BitmapFactory.Options opts = new BitmapFactory.Options();
253 opts.inBitmap = recycle;
Michael Jurka6e27f642013-12-10 13:40:30 +0100254 try {
Winson Chung05304db2015-05-18 16:53:20 -0700255 if (!loadTask.isCancelled()) {
256 return BitmapFactory.decodeByteArray(blob, 0, blob.length, opts);
257 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700258 } catch (Exception e) {
259 return null;
Michael Jurka6e27f642013-12-10 13:40:30 +0100260 }
Michael Jurka05713af2013-01-23 12:39:24 +0100261 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700262 } catch (SQLException e) {
263 Log.w(TAG, "Error loading preview from DB", e);
264 } finally {
265 if (cursor != null) {
266 cursor.close();
267 }
268 }
269 return null;
Michael Jurka05713af2013-01-23 12:39:24 +0100270 }
271
Sunny Goyal27835952017-01-13 12:15:53 -0800272 private Bitmap generatePreview(BaseActivity launcher, WidgetItem item, Bitmap recycle,
Adam Cohen2e6da152015-05-06 11:42:25 -0700273 int previewWidth, int previewHeight) {
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800274 if (item.widgetInfo != null) {
275 return generateWidgetPreview(launcher, item.widgetInfo,
Adam Cohen2e6da152015-05-06 11:42:25 -0700276 previewWidth, recycle, null);
Michael Jurka05713af2013-01-23 12:39:24 +0100277 } else {
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800278 return generateShortcutPreview(launcher, item.activityInfo,
279 previewWidth, previewHeight, recycle);
Michael Jurka05713af2013-01-23 12:39:24 +0100280 }
281 }
282
Hyunyoung Song3e840f42016-03-01 11:57:44 -0800283 /**
284 * Generates the widget preview from either the {@link AppWidgetManagerCompat} or cache
285 * and add badge at the bottom right corner.
286 *
287 * @param launcher
288 * @param info information about the widget
289 * @param maxPreviewWidth width of the preview on either workspace or tray
290 * @param preview bitmap that can be recycled
291 * @param preScaledWidthOut return the width of the returned bitmap
292 * @return
293 */
Sunny Goyal27835952017-01-13 12:15:53 -0800294 public Bitmap generateWidgetPreview(BaseActivity launcher, LauncherAppWidgetProviderInfo info,
Sunny Goyal4cad7532015-03-18 15:56:30 -0700295 int maxPreviewWidth, Bitmap preview, int[] preScaledWidthOut) {
Michael Jurka05713af2013-01-23 12:39:24 +0100296 // Load the preview image if possible
Michael Jurka05713af2013-01-23 12:39:24 +0100297 if (maxPreviewWidth < 0) maxPreviewWidth = Integer.MAX_VALUE;
Michael Jurka05713af2013-01-23 12:39:24 +0100298
299 Drawable drawable = null;
Sunny Goyalffe83f12014-08-14 17:39:34 -0700300 if (info.previewImage != 0) {
Sunny Goyal2570d102016-10-27 11:38:45 -0700301 try {
Sunny Goyala52ecb02016-12-16 15:04:51 -0800302 drawable = info.loadPreviewImage(launcher.getApplicationContext(), 0);
Sunny Goyal2570d102016-10-27 11:38:45 -0700303 } catch (OutOfMemoryError e) {
304 Log.w(TAG, "Error loading widget preview for: " + info.provider, e);
305 // During OutOfMemoryError, the previous heap stack is not affected. Catching
306 // an OOM error here should be safe & not affect other parts of launcher.
307 drawable = null;
308 }
Adrian Roosfa9ffc22014-05-12 15:59:59 +0200309 if (drawable != null) {
310 drawable = mutateOnMainThread(drawable);
311 } else {
Michael Jurka05713af2013-01-23 12:39:24 +0100312 Log.w(TAG, "Can't load widget preview drawable 0x" +
Sunny Goyalffe83f12014-08-14 17:39:34 -0700313 Integer.toHexString(info.previewImage) + " for provider: " + info.provider);
Michael Jurka05713af2013-01-23 12:39:24 +0100314 }
315 }
316
Sunny Goyal4cad7532015-03-18 15:56:30 -0700317 final boolean widgetPreviewExists = (drawable != null);
Sunny Goyal233ee962015-08-03 13:05:01 -0700318 final int spanX = info.spanX;
319 final int spanY = info.spanY;
Sunny Goyal4cad7532015-03-18 15:56:30 -0700320
Michael Jurka05713af2013-01-23 12:39:24 +0100321 int previewWidth;
322 int previewHeight;
Hyunyoung Song3e840f42016-03-01 11:57:44 -0800323
Sunny Goyal4cad7532015-03-18 15:56:30 -0700324 Bitmap tileBitmap = null;
325
Michael Jurka05713af2013-01-23 12:39:24 +0100326 if (widgetPreviewExists) {
327 previewWidth = drawable.getIntrinsicWidth();
328 previewHeight = drawable.getIntrinsicHeight();
329 } else {
330 // Generate a preview image if we couldn't load one
Sunny Goyal4cad7532015-03-18 15:56:30 -0700331 tileBitmap = ((BitmapDrawable) mContext.getResources().getDrawable(
332 R.drawable.widget_tile)).getBitmap();
333 previewWidth = tileBitmap.getWidth() * spanX;
334 previewHeight = tileBitmap.getHeight() * spanY;
Michael Jurka05713af2013-01-23 12:39:24 +0100335 }
336
337 // Scale to fit width only - let the widget preview be clipped in the
338 // vertical dimension
339 float scale = 1f;
340 if (preScaledWidthOut != null) {
341 preScaledWidthOut[0] = previewWidth;
342 }
343 if (previewWidth > maxPreviewWidth) {
Sunny Goyala2441e82017-01-14 13:40:15 -0800344 scale = maxPreviewWidth / (float) (previewWidth);
Michael Jurka05713af2013-01-23 12:39:24 +0100345 }
346 if (scale != 1f) {
347 previewWidth = (int) (scale * previewWidth);
348 previewHeight = (int) (scale * previewHeight);
349 }
350
351 // 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 -0700352 final Canvas c = new Canvas();
Michael Jurka05713af2013-01-23 12:39:24 +0100353 if (preview == null) {
354 preview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700355 c.setBitmap(preview);
356 } else {
Sunny Goyala2441e82017-01-14 13:40:15 -0800357 // We use the preview bitmap height to determine where the badge will be drawn in the
358 // UI. If its larger than what we need, resize the preview bitmap so that there are
359 // no transparent pixels between the preview and the badge.
360 if (preview.getHeight() > previewHeight) {
361 preview.reconfigure(preview.getWidth(), previewHeight, preview.getConfig());
362 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700363 // Reusing bitmap. Clear it.
364 c.setBitmap(preview);
365 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100366 }
367
368 // Draw the scaled preview into the final bitmap
Hyunyoung Songb9f932e2015-07-30 15:04:59 -0700369 int x = (preview.getWidth() - previewWidth) / 2;
Michael Jurka05713af2013-01-23 12:39:24 +0100370 if (widgetPreviewExists) {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700371 drawable.setBounds(x, 0, x + previewWidth, previewHeight);
372 drawable.draw(c);
Michael Jurka05713af2013-01-23 12:39:24 +0100373 } else {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700374 final Paint p = new Paint();
375 p.setFilterBitmap(true);
Adam Cohen2e6da152015-05-06 11:42:25 -0700376 int appIconSize = launcher.getDeviceProfile().iconSizePx;
Michael Jurka05713af2013-01-23 12:39:24 +0100377
Sunny Goyal4cad7532015-03-18 15:56:30 -0700378 // draw the spanX x spanY tiles
379 final Rect src = new Rect(0, 0, tileBitmap.getWidth(), tileBitmap.getHeight());
380
381 float tileW = scale * tileBitmap.getWidth();
382 float tileH = scale * tileBitmap.getHeight();
383 final RectF dst = new RectF(0, 0, tileW, tileH);
384
385 float tx = x;
386 for (int i = 0; i < spanX; i++, tx += tileW) {
387 float ty = 0;
388 for (int j = 0; j < spanY; j++, ty += tileH) {
389 dst.offsetTo(tx, ty);
390 c.drawBitmap(tileBitmap, src, dst, p);
391 }
Michael Jurka05713af2013-01-23 12:39:24 +0100392 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700393
394 // Draw the icon in the top left corner
395 // TODO: use top right for RTL
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700396 int minOffset = (int) (appIconSize * WIDGET_PREVIEW_ICON_PADDING_PERCENTAGE);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700397 int smallestSide = Math.min(previewWidth, previewHeight);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700398 float iconScale = Math.min((float) smallestSide / (appIconSize + 2 * minOffset), scale);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700399
400 try {
Sunny Goyala52ecb02016-12-16 15:04:51 -0800401 Drawable icon = info.getIcon(launcher, mIconCache);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700402 if (icon != null) {
Sunny Goyal1ba7e362015-10-26 10:42:12 -0700403 icon = mutateOnMainThread(icon);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700404 int hoffset = (int) ((tileW - appIconSize * iconScale) / 2) + x;
405 int yoffset = (int) ((tileH - appIconSize * iconScale) / 2);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700406 icon.setBounds(hoffset, yoffset,
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700407 hoffset + (int) (appIconSize * iconScale),
408 yoffset + (int) (appIconSize * iconScale));
Sunny Goyal4cad7532015-03-18 15:56:30 -0700409 icon.draw(c);
410 }
Hyunyoung Song3e840f42016-03-01 11:57:44 -0800411 } catch (Resources.NotFoundException e) {
412 }
Michael Jurka05713af2013-01-23 12:39:24 +0100413 c.setBitmap(null);
414 }
Sunny Goyala2441e82017-01-14 13:40:15 -0800415 return preview;
Michael Jurka05713af2013-01-23 12:39:24 +0100416 }
417
Sunny Goyal782f0c92017-01-19 10:27:54 -0800418 private Bitmap generateShortcutPreview(BaseActivity launcher, ShortcutConfigActivityInfo info,
419 int maxWidth, int maxHeight, Bitmap preview) {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700420 final Canvas c = new Canvas();
421 if (preview == null) {
Michael Jurka05713af2013-01-23 12:39:24 +0100422 preview = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700423 c.setBitmap(preview);
424 } else if (preview.getWidth() != maxWidth || preview.getHeight() != maxHeight) {
425 throw new RuntimeException("Improperly sized bitmap passed as argument");
426 } else {
427 // Reusing bitmap. Clear it.
428 c.setBitmap(preview);
429 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100430 }
431
Sunny Goyal782f0c92017-01-19 10:27:54 -0800432 Drawable icon = mutateOnMainThread(info.getFullResIcon(mIconCache));
Sunny Goyal4cad7532015-03-18 15:56:30 -0700433 icon.setFilterBitmap(true);
434
Michael Jurka05713af2013-01-23 12:39:24 +0100435 // Draw a desaturated/scaled version of the icon in the background as a watermark
Sunny Goyal4cad7532015-03-18 15:56:30 -0700436 ColorMatrix colorMatrix = new ColorMatrix();
437 colorMatrix.setSaturation(0);
438 icon.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
439 icon.setAlpha((int) (255 * 0.06f));
440
441 Resources res = mContext.getResources();
442 int paddingTop = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_top);
443 int paddingLeft = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_left);
444 int paddingRight = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_right);
445 int scaledIconWidth = (maxWidth - paddingLeft - paddingRight);
446 icon.setBounds(paddingLeft, paddingTop,
447 paddingLeft + scaledIconWidth, paddingTop + scaledIconWidth);
448 icon.draw(c);
449
450 // Draw the final icon at top left corner.
451 // TODO: use top right for RTL
Adam Cohen2e6da152015-05-06 11:42:25 -0700452 int appIconSize = launcher.getDeviceProfile().iconSizePx;
453
Sunny Goyal4cad7532015-03-18 15:56:30 -0700454 icon.setAlpha(255);
455 icon.setColorFilter(null);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700456 icon.setBounds(0, 0, appIconSize, appIconSize);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700457 icon.draw(c);
458
Michael Jurka05713af2013-01-23 12:39:24 +0100459 c.setBitmap(null);
Michael Jurka05713af2013-01-23 12:39:24 +0100460 return preview;
461 }
462
Adrian Roos65d60e22014-04-15 21:07:49 +0200463 private Drawable mutateOnMainThread(final Drawable drawable) {
464 try {
465 return mMainThreadExecutor.submit(new Callable<Drawable>() {
466 @Override
467 public Drawable call() throws Exception {
468 return drawable.mutate();
469 }
470 }).get();
471 } catch (InterruptedException e) {
472 Thread.currentThread().interrupt();
473 throw new RuntimeException(e);
474 } catch (ExecutionException e) {
475 throw new RuntimeException(e);
476 }
477 }
Adrian Roos1f375ab2014-04-28 18:26:38 +0200478
Adrian Roos1f375ab2014-04-28 18:26:38 +0200479 /**
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700480 * @return an array of containing versionCode and lastUpdatedTime for the package.
Adrian Roos1f375ab2014-04-28 18:26:38 +0200481 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700482 @Thunk long[] getPackageVersion(String packageName) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700483 synchronized (mPackageVersions) {
484 long[] versions = mPackageVersions.get(packageName);
485 if (versions == null) {
486 versions = new long[2];
Adrian Roos1f375ab2014-04-28 18:26:38 +0200487 try {
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800488 PackageInfo info = mContext.getPackageManager().getPackageInfo(packageName,
489 PackageManager.GET_UNINSTALLED_PACKAGES);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700490 versions[0] = info.versionCode;
491 versions[1] = info.lastUpdateTime;
492 } catch (NameNotFoundException e) {
493 Log.e(TAG, "PackageInfo not found", e);
494 }
495 mPackageVersions.put(packageName, versions);
496 }
497 return versions;
498 }
499 }
500
501 /**
502 * A request Id which can be used by the client to cancel any request.
503 */
504 public class PreviewLoadRequest {
505
Sunny Goyalb4cbea42015-06-16 15:10:36 -0700506 @Thunk final PreviewLoadTask mTask;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700507
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700508 public PreviewLoadRequest(PreviewLoadTask task) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700509 mTask = task;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700510 }
511
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700512 public void cleanup() {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700513 if (mTask != null) {
514 mTask.cancel(true);
515 }
516
Winson Chung05304db2015-05-18 16:53:20 -0700517 // This only handles the case where the PreviewLoadTask is cancelled after the task has
518 // successfully completed (including having written to disk when necessary). In the
519 // other cases where it is cancelled while the task is running, it will be cleaned up
520 // in the tasks's onCancelled() call, and if cancelled while the task is writing to
521 // disk, it will be cancelled in the task's onPostExecute() call.
522 if (mTask.mBitmapToRecycle != null) {
Hyunyoung Songe98f4a42015-06-16 10:45:24 -0700523 mWorkerHandler.post(new Runnable() {
524 @Override
525 public void run() {
526 synchronized (mUnusedBitmaps) {
527 mUnusedBitmaps.add(mTask.mBitmapToRecycle);
528 }
529 mTask.mBitmapToRecycle = null;
530 }
531 });
Adrian Roos1f375ab2014-04-28 18:26:38 +0200532 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700533 }
534 }
535
536 public class PreviewLoadTask extends AsyncTask<Void, Void, Bitmap> {
Sunny Goyal316490e2015-06-02 09:38:28 -0700537 @Thunk final WidgetCacheKey mKey;
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800538 private final WidgetItem mInfo;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700539 private final int mPreviewHeight;
540 private final int mPreviewWidth;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700541 private final WidgetCell mCaller;
Sunny Goyala2441e82017-01-14 13:40:15 -0800542 private final BaseActivity mActivity;
Sunny Goyal316490e2015-06-02 09:38:28 -0700543 @Thunk long[] mVersions;
544 @Thunk Bitmap mBitmapToRecycle;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700545
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800546 PreviewLoadTask(WidgetCacheKey key, WidgetItem info, int previewWidth,
Hyunyoung Song3f471442015-04-08 19:01:34 -0700547 int previewHeight, WidgetCell caller) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700548 mKey = key;
549 mInfo = info;
550 mPreviewHeight = previewHeight;
551 mPreviewWidth = previewWidth;
552 mCaller = caller;
Sunny Goyala2441e82017-01-14 13:40:15 -0800553 mActivity = BaseActivity.fromContext(mCaller.getContext());
Hyunyoung Song3f471442015-04-08 19:01:34 -0700554 if (DEBUG) {
555 Log.d(TAG, String.format("%s, %s, %d, %d",
556 mKey, mInfo, mPreviewHeight, mPreviewWidth));
557 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700558 }
559
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700560 @Override
561 protected Bitmap doInBackground(Void... params) {
562 Bitmap unusedBitmap = null;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700563
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700564 // If already cancelled before this gets to run in the background, then return early
565 if (isCancelled()) {
566 return null;
567 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700568 synchronized (mUnusedBitmaps) {
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700569 // Check if we can re-use a bitmap
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700570 for (Bitmap candidate : mUnusedBitmaps) {
571 if (candidate != null && candidate.isMutable() &&
572 candidate.getWidth() == mPreviewWidth &&
573 candidate.getHeight() == mPreviewHeight) {
574 unusedBitmap = candidate;
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700575 mUnusedBitmaps.remove(unusedBitmap);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700576 break;
577 }
578 }
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700579 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700580
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700581 // creating a bitmap is expensive. Do not do this inside synchronized block.
582 if (unusedBitmap == null) {
583 unusedBitmap = Bitmap.createBitmap(mPreviewWidth, mPreviewHeight, Config.ARGB_8888);
Adrian Roos1f375ab2014-04-28 18:26:38 +0200584 }
Winson Chung05304db2015-05-18 16:53:20 -0700585 // If cancelled now, don't bother reading the preview from the DB
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700586 if (isCancelled()) {
Winson Chung05304db2015-05-18 16:53:20 -0700587 return unusedBitmap;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700588 }
Winson Chung05304db2015-05-18 16:53:20 -0700589 Bitmap preview = readFromDb(mKey, unusedBitmap, this);
590 // Only consider generating the preview if we have not cancelled the task already
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700591 if (!isCancelled() && preview == null) {
592 // Fetch the version info before we generate the preview, so that, in-case the
593 // app was updated while we are generating the preview, we use the old version info,
594 // which would gets re-written next time.
Winson Chung05304db2015-05-18 16:53:20 -0700595 mVersions = getPackageVersion(mKey.componentName.getPackageName());
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700596
597 // it's not in the db... we need to generate it
Sunny Goyala2441e82017-01-14 13:40:15 -0800598 preview = generatePreview(mActivity, mInfo, unusedBitmap, mPreviewWidth, mPreviewHeight);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700599 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700600 return preview;
601 }
602
603 @Override
Winson Chung05304db2015-05-18 16:53:20 -0700604 protected void onPostExecute(final Bitmap preview) {
605 mCaller.applyPreview(preview);
606
607 // Write the generated preview to the DB in the worker thread
608 if (mVersions != null) {
609 mWorkerHandler.post(new Runnable() {
610 @Override
611 public void run() {
612 if (!isCancelled()) {
613 // If we are still using this preview, then write it to the DB and then
614 // let the normal clear mechanism recycle the bitmap
615 writeToDb(mKey, mVersions, preview);
616 mBitmapToRecycle = preview;
617 } else {
618 // If we've already cancelled, then skip writing the bitmap to the DB
619 // and manually add the bitmap back to the recycled set
620 synchronized (mUnusedBitmaps) {
621 mUnusedBitmaps.add(preview);
622 }
623 }
624 }
625 });
626 } else {
627 // If we don't need to write to disk, then ensure the preview gets recycled by
628 // the normal clear mechanism
629 mBitmapToRecycle = preview;
630 }
631 }
632
633 @Override
Hyunyoung Songe98f4a42015-06-16 10:45:24 -0700634 protected void onCancelled(final Bitmap preview) {
Winson Chung05304db2015-05-18 16:53:20 -0700635 // If we've cancelled while the task is running, then can return the bitmap to the
636 // recycled set immediately. Otherwise, it will be recycled after the preview is written
637 // to disk.
638 if (preview != null) {
Hyunyoung Songe98f4a42015-06-16 10:45:24 -0700639 mWorkerHandler.post(new Runnable() {
640 @Override
641 public void run() {
642 synchronized (mUnusedBitmaps) {
643 mUnusedBitmaps.add(preview);
644 }
645 }
646 });
Winson Chung05304db2015-05-18 16:53:20 -0700647 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700648 }
649 }
650
651 private static final class WidgetCacheKey extends ComponentKey {
652
653 // TODO: remove dependency on size
Sunny Goyal316490e2015-06-02 09:38:28 -0700654 @Thunk final String size;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700655
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800656 public WidgetCacheKey(ComponentName componentName, UserHandle user, String size) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700657 super(componentName, user);
658 this.size = size;
659 }
660
661 @Override
662 public int hashCode() {
663 return super.hashCode() ^ size.hashCode();
664 }
665
666 @Override
667 public boolean equals(Object o) {
668 return super.equals(o) && ((WidgetCacheKey) o).size.equals(size);
Adrian Roos1f375ab2014-04-28 18:26:38 +0200669 }
670 }
Michael Jurka05713af2013-01-23 12:39:24 +0100671}