blob: 75952d1a61519d9284ca219927f6aa03c6c14fc4 [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;
7import android.content.pm.PackageManager.NameNotFoundException;
Michael Jurka05713af2013-01-23 12:39:24 +01008import android.content.pm.ResolveInfo;
9import 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;
13import android.database.sqlite.SQLiteOpenHelper;
14import 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 Goyalffe83f12014-08-14 17:39:34 -070030import com.android.launcher3.compat.AppWidgetManagerCompat;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070031import com.android.launcher3.compat.UserHandleCompat;
32import com.android.launcher3.compat.UserManagerCompat;
33import com.android.launcher3.util.ComponentKey;
Adam Cohen091440a2015-03-18 14:16:05 -070034import com.android.launcher3.util.Thunk;
Hyunyoung Song3f471442015-04-08 19:01:34 -070035import com.android.launcher3.widget.WidgetCell;
Hyunyoung Song8821ca92015-05-04 16:28:20 -070036
37import java.util.ArrayList;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070038import java.util.Collections;
Michael Jurka05713af2013-01-23 12:39:24 +010039import java.util.HashMap;
40import java.util.HashSet;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070041import java.util.Set;
42import java.util.WeakHashMap;
Adrian Roos65d60e22014-04-15 21:07:49 +020043import java.util.concurrent.Callable;
44import java.util.concurrent.ExecutionException;
Michael Jurka05713af2013-01-23 12:39:24 +010045
Sunny Goyalffe83f12014-08-14 17:39:34 -070046public class WidgetPreviewLoader {
Michael Jurka05713af2013-01-23 12:39:24 +010047
Sunny Goyalffe83f12014-08-14 17:39:34 -070048 private static final String TAG = "WidgetPreviewLoader";
Hyunyoung Song3f471442015-04-08 19:01:34 -070049 private static final boolean DEBUG = false;
Sunny Goyalffe83f12014-08-14 17:39:34 -070050
51 private static final float WIDGET_PREVIEW_ICON_PADDING_PERCENTAGE = 0.25f;
Sunny Goyalffe83f12014-08-14 17:39:34 -070052
Sunny Goyal5b0e6692015-03-19 14:31:19 -070053 private final HashMap<String, long[]> mPackageVersions = new HashMap<>();
Hyunyoung Song559d90d2015-04-28 15:06:45 -070054
55 /**
56 * Weak reference objects, do not prevent their referents from being made finalizable,
57 * finalized, and then reclaimed.
58 */
Sunny Goyal316490e2015-06-02 09:38:28 -070059 @Thunk Set<Bitmap> mUnusedBitmaps =
Hyunyoung Song559d90d2015-04-28 15:06:45 -070060 Collections.newSetFromMap(new WeakHashMap<Bitmap, Boolean>());
Sunny Goyal4cad7532015-03-18 15:56:30 -070061
62 private final Context mContext;
Sunny Goyalffe83f12014-08-14 17:39:34 -070063 private final IconCache mIconCache;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070064 private final UserManagerCompat mUserManager;
Sunny Goyalffe83f12014-08-14 17:39:34 -070065 private final AppWidgetManagerCompat mManager;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070066 private final CacheDb mDb;
Hyunyoung Song41e33692015-06-15 12:26:54 -070067 private final int mProfileBadgeMargin;
Michael Jurka05713af2013-01-23 12:39:24 +010068
Adrian Roos65d60e22014-04-15 21:07:49 +020069 private final MainThreadExecutor mMainThreadExecutor = new MainThreadExecutor();
Sunny Goyal316490e2015-06-02 09:38:28 -070070 @Thunk final Handler mWorkerHandler;
Adrian Roos65d60e22014-04-15 21:07:49 +020071
Adam Cohen2e6da152015-05-06 11:42:25 -070072 public WidgetPreviewLoader(Context context, InvariantDeviceProfile inv, IconCache iconCache) {
Chris Wrenfd13c712013-09-27 15:45:19 -040073 mContext = context;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070074 mIconCache = iconCache;
Sunny Goyalffe83f12014-08-14 17:39:34 -070075 mManager = AppWidgetManagerCompat.getInstance(context);
Sunny Goyal5b0e6692015-03-19 14:31:19 -070076 mUserManager = UserManagerCompat.getInstance(context);
77 mDb = new CacheDb(context);
Winson Chung05304db2015-05-18 16:53:20 -070078 mWorkerHandler = new Handler(LauncherModel.getWorkerLooper());
Hyunyoung Song41e33692015-06-15 12:26:54 -070079 mProfileBadgeMargin = context.getResources()
80 .getDimensionPixelSize(R.dimen.profile_badge_margin);
Michael Jurka3f4e0702013-02-05 11:21:28 +010081 }
Sunny Goyalffe83f12014-08-14 17:39:34 -070082
Sunny Goyal5b0e6692015-03-19 14:31:19 -070083 /**
84 * Generates the widget preview on {@link AsyncTask#THREAD_POOL_EXECUTOR}. Must be
85 * called on UI thread
86 *
87 * @param o either {@link LauncherAppWidgetProviderInfo} or {@link ResolveInfo}
Sunny Goyal5b0e6692015-03-19 14:31:19 -070088 * @return a request id which can be used to cancel the request.
89 */
Adam Cohen2e6da152015-05-06 11:42:25 -070090 public PreviewLoadRequest getPreview(final Object o, int previewWidth,
91 int previewHeight, WidgetCell caller) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -070092 String size = previewWidth + "x" + previewHeight;
93 WidgetCacheKey key = getObjectKey(o, size);
Michael Jurka3f4e0702013-02-05 11:21:28 +010094
Sunny Goyal5b0e6692015-03-19 14:31:19 -070095 PreviewLoadTask task = new PreviewLoadTask(key, o, previewWidth, previewHeight, caller);
96 task.executeOnExecutor(AsyncTask.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 */
104 private static class CacheDb extends SQLiteOpenHelper {
105 private static final int DB_VERSION = 3;
106
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 Goyal5b0e6692015-03-19 14:31:19 -0700117 super(context, LauncherFiles.WIDGET_PREVIEWS_DB, null, DB_VERSION);
Michael Jurka05713af2013-01-23 12:39:24 +0100118 }
119
120 @Override
121 public void onCreate(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 }
133
134 @Override
135 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Michael Jurkae5919c52013-03-06 17:30:10 +0100136 if (oldVersion != newVersion) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700137 clearDB(db);
Michael Jurkae5919c52013-03-06 17:30:10 +0100138 }
Michael Jurka05713af2013-01-23 12:39:24 +0100139 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700140
141 @Override
142 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
143 if (oldVersion != newVersion) {
144 clearDB(db);
145 }
146 }
147
148 private void clearDB(SQLiteDatabase db) {
149 db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
150 onCreate(db);
151 }
Michael Jurka05713af2013-01-23 12:39:24 +0100152 }
153
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700154 private WidgetCacheKey getObjectKey(Object o, String size) {
Michael Jurka05713af2013-01-23 12:39:24 +0100155 // should cache the string builder
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700156 if (o instanceof LauncherAppWidgetProviderInfo) {
157 LauncherAppWidgetProviderInfo info = (LauncherAppWidgetProviderInfo) o;
158 return new WidgetCacheKey(info.provider, mManager.getUser(info), size);
Michael Jurka05713af2013-01-23 12:39:24 +0100159 } else {
160 ResolveInfo info = (ResolveInfo) o;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700161 return new WidgetCacheKey(
162 new ComponentName(info.activityInfo.packageName, info.activityInfo.name),
163 UserHandleCompat.myUserHandle(), size);
Michael Jurka05713af2013-01-23 12:39:24 +0100164 }
165 }
166
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700167 @Thunk void writeToDb(WidgetCacheKey key, long[] versions, Bitmap preview) {
Michael Jurka05713af2013-01-23 12:39:24 +0100168 ContentValues values = new ContentValues();
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700169 values.put(CacheDb.COLUMN_COMPONENT, key.componentName.flattenToShortString());
170 values.put(CacheDb.COLUMN_USER, mUserManager.getSerialNumberForUser(key.user));
171 values.put(CacheDb.COLUMN_SIZE, key.size);
172 values.put(CacheDb.COLUMN_PACKAGE, key.componentName.getPackageName());
173 values.put(CacheDb.COLUMN_VERSION, versions[0]);
174 values.put(CacheDb.COLUMN_LAST_UPDATED, versions[1]);
175 values.put(CacheDb.COLUMN_PREVIEW_BITMAP, Utilities.flattenBitmap(preview));
Michael Jurka05713af2013-01-23 12:39:24 +0100176
Michael Jurka6e27f642013-12-10 13:40:30 +0100177 try {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700178 mDb.getWritableDatabase().insertWithOnConflict(CacheDb.TABLE_NAME, null, values,
179 SQLiteDatabase.CONFLICT_REPLACE);
180 } catch (SQLException e) {
181 Log.e(TAG, "Error saving image to DB", e);
Michael Jurka6e27f642013-12-10 13:40:30 +0100182 }
Michael Jurka05713af2013-01-23 12:39:24 +0100183 }
184
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700185 public void removePackage(String packageName, UserHandleCompat user) {
186 removePackage(packageName, user, mUserManager.getSerialNumberForUser(user));
187 }
188
189 private void removePackage(String packageName, UserHandleCompat user, long userSerial) {
190 synchronized(mPackageVersions) {
191 mPackageVersions.remove(packageName);
192 }
193
Michael Jurka6e27f642013-12-10 13:40:30 +0100194 try {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700195 mDb.getWritableDatabase().delete(CacheDb.TABLE_NAME,
196 CacheDb.COLUMN_PACKAGE + " = ? AND " + CacheDb.COLUMN_USER + " = ?",
197 new String[] {packageName, Long.toString(userSerial)});
198 } catch (SQLException e) {
199 Log.e(TAG, "Unable to delete items from DB", e);
Michael Jurka6e27f642013-12-10 13:40:30 +0100200 }
Michael Jurka8ff02ca2013-11-01 14:19:27 +0100201 }
202
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700203 /**
204 * Updates the persistent DB:
205 * 1. Any preview generated for an old package version is removed
206 * 2. Any preview for an absent package is removed
207 * This ensures that we remove entries for packages which changed while the launcher was dead.
208 */
Hyunyoung Song8821ca92015-05-04 16:28:20 -0700209 public void removeObsoletePreviews(ArrayList<Object> list) {
Hyunyoung Song2bd3d7d2015-05-21 13:04:53 -0700210 Utilities.assertWorkerThread();
Hyunyoung Song8821ca92015-05-04 16:28:20 -0700211
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700212 LongSparseArray<UserHandleCompat> userIdCache = new LongSparseArray<>();
213 LongSparseArray<HashSet<String>> validPackages = new LongSparseArray<>();
214
Hyunyoung Song8821ca92015-05-04 16:28:20 -0700215 for (Object obj : list) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700216 final UserHandleCompat user;
217 final String pkg;
218 if (obj instanceof ResolveInfo) {
219 user = UserHandleCompat.myUserHandle();
220 pkg = ((ResolveInfo) obj).activityInfo.packageName;
221 } else {
222 LauncherAppWidgetProviderInfo info = (LauncherAppWidgetProviderInfo) obj;
223 user = mManager.getUser(info);
224 pkg = info.provider.getPackageName();
225 }
226
227 int userIdIndex = userIdCache.indexOfValue(user);
228 final long userId;
229 if (userIdIndex < 0) {
230 userId = mUserManager.getSerialNumberForUser(user);
231 userIdCache.put(userId, user);
232 } else {
233 userId = userIdCache.keyAt(userIdIndex);
234 }
235
236 HashSet<String> packages = validPackages.get(userId);
237 if (packages == null) {
238 packages = new HashSet<>();
239 validPackages.put(userId, packages);
240 }
241 packages.add(pkg);
Michael Jurka05713af2013-01-23 12:39:24 +0100242 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700243
244 LongSparseArray<HashSet<String>> packagesToDelete = new LongSparseArray<>();
245 Cursor c = null;
246 try {
247 c = mDb.getReadableDatabase().query(CacheDb.TABLE_NAME,
248 new String[] {CacheDb.COLUMN_USER, CacheDb.COLUMN_PACKAGE,
249 CacheDb.COLUMN_LAST_UPDATED, CacheDb.COLUMN_VERSION},
250 null, null, null, null, null);
251 while (c.moveToNext()) {
252 long userId = c.getLong(0);
253 String pkg = c.getString(1);
254 long lastUpdated = c.getLong(2);
255 long version = c.getLong(3);
256
257 HashSet<String> packages = validPackages.get(userId);
258 if (packages != null && packages.contains(pkg)) {
259 long[] versions = getPackageVersion(pkg);
260 if (versions[0] == version && versions[1] == lastUpdated) {
261 // Every thing checks out
262 continue;
263 }
264 }
265
266 // We need to delete this package.
267 packages = packagesToDelete.get(userId);
268 if (packages == null) {
269 packages = new HashSet<>();
270 packagesToDelete.put(userId, packages);
271 }
272 packages.add(pkg);
273 }
274
275 for (int i = 0; i < packagesToDelete.size(); i++) {
276 long userId = packagesToDelete.keyAt(i);
277 UserHandleCompat user = mUserManager.getUserForSerialNumber(userId);
278 for (String pkg : packagesToDelete.valueAt(i)) {
279 removePackage(pkg, user, userId);
280 }
281 }
282 } catch (SQLException e) {
283 Log.e(TAG, "Error updatating widget previews", e);
284 } finally {
285 if (c != null) {
286 c.close();
287 }
288 }
289 }
290
Winson Chung05304db2015-05-18 16:53:20 -0700291 /**
292 * Reads the preview bitmap from the DB or null if the preview is not in the DB.
293 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700294 @Thunk Bitmap readFromDb(WidgetCacheKey key, Bitmap recycle, PreviewLoadTask loadTask) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700295 Cursor cursor = null;
296 try {
297 cursor = mDb.getReadableDatabase().query(
298 CacheDb.TABLE_NAME,
299 new String[] { CacheDb.COLUMN_PREVIEW_BITMAP },
300 CacheDb.COLUMN_COMPONENT + " = ? AND " + CacheDb.COLUMN_USER + " = ? AND " + CacheDb.COLUMN_SIZE + " = ?",
301 new String[] {
302 key.componentName.flattenToString(),
303 Long.toString(mUserManager.getSerialNumberForUser(key.user)),
304 key.size
305 },
306 null, null, null);
Winson Chung05304db2015-05-18 16:53:20 -0700307 // If cancelled, skip getting the blob and decoding it into a bitmap
308 if (loadTask.isCancelled()) {
309 return null;
310 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700311 if (cursor.moveToNext()) {
312 byte[] blob = cursor.getBlob(0);
313 BitmapFactory.Options opts = new BitmapFactory.Options();
314 opts.inBitmap = recycle;
Michael Jurka6e27f642013-12-10 13:40:30 +0100315 try {
Winson Chung05304db2015-05-18 16:53:20 -0700316 if (!loadTask.isCancelled()) {
317 return BitmapFactory.decodeByteArray(blob, 0, blob.length, opts);
318 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700319 } catch (Exception e) {
320 return null;
Michael Jurka6e27f642013-12-10 13:40:30 +0100321 }
Michael Jurka05713af2013-01-23 12:39:24 +0100322 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700323 } catch (SQLException e) {
324 Log.w(TAG, "Error loading preview from DB", e);
325 } finally {
326 if (cursor != null) {
327 cursor.close();
328 }
329 }
330 return null;
Michael Jurka05713af2013-01-23 12:39:24 +0100331 }
332
Sunny Goyal316490e2015-06-02 09:38:28 -0700333 @Thunk Bitmap generatePreview(Launcher launcher, Object info, Bitmap recycle,
Adam Cohen2e6da152015-05-06 11:42:25 -0700334 int previewWidth, int previewHeight) {
Adam Cohen59400422014-03-05 18:07:04 -0800335 if (info instanceof LauncherAppWidgetProviderInfo) {
Adam Cohen2e6da152015-05-06 11:42:25 -0700336 return generateWidgetPreview(launcher, (LauncherAppWidgetProviderInfo) info,
337 previewWidth, recycle, null);
Michael Jurka05713af2013-01-23 12:39:24 +0100338 } else {
Adam Cohen2e6da152015-05-06 11:42:25 -0700339 return generateShortcutPreview(launcher,
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700340 (ResolveInfo) info, previewWidth, previewHeight, recycle);
Michael Jurka05713af2013-01-23 12:39:24 +0100341 }
342 }
343
Adam Cohen2e6da152015-05-06 11:42:25 -0700344 public Bitmap generateWidgetPreview(Launcher launcher, LauncherAppWidgetProviderInfo info,
Sunny Goyal4cad7532015-03-18 15:56:30 -0700345 int maxPreviewWidth, Bitmap preview, int[] preScaledWidthOut) {
Michael Jurka05713af2013-01-23 12:39:24 +0100346 // Load the preview image if possible
Michael Jurka05713af2013-01-23 12:39:24 +0100347 if (maxPreviewWidth < 0) maxPreviewWidth = Integer.MAX_VALUE;
Michael Jurka05713af2013-01-23 12:39:24 +0100348
349 Drawable drawable = null;
Sunny Goyalffe83f12014-08-14 17:39:34 -0700350 if (info.previewImage != 0) {
351 drawable = mManager.loadPreview(info);
Adrian Roosfa9ffc22014-05-12 15:59:59 +0200352 if (drawable != null) {
353 drawable = mutateOnMainThread(drawable);
354 } else {
Michael Jurka05713af2013-01-23 12:39:24 +0100355 Log.w(TAG, "Can't load widget preview drawable 0x" +
Sunny Goyalffe83f12014-08-14 17:39:34 -0700356 Integer.toHexString(info.previewImage) + " for provider: " + info.provider);
Michael Jurka05713af2013-01-23 12:39:24 +0100357 }
358 }
359
Sunny Goyal4cad7532015-03-18 15:56:30 -0700360 final boolean widgetPreviewExists = (drawable != null);
Adam Cohen2e6da152015-05-06 11:42:25 -0700361 final int spanX = info.getSpanX(launcher) < 1 ? 1 : info.getSpanX(launcher);
362 final int spanY = info.getSpanY(launcher) < 1 ? 1 : info.getSpanY(launcher);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700363
Michael Jurka05713af2013-01-23 12:39:24 +0100364 int previewWidth;
365 int previewHeight;
Sunny Goyal4cad7532015-03-18 15:56:30 -0700366 Bitmap tileBitmap = null;
367
Michael Jurka05713af2013-01-23 12:39:24 +0100368 if (widgetPreviewExists) {
369 previewWidth = drawable.getIntrinsicWidth();
370 previewHeight = drawable.getIntrinsicHeight();
371 } else {
372 // Generate a preview image if we couldn't load one
Sunny Goyal4cad7532015-03-18 15:56:30 -0700373 tileBitmap = ((BitmapDrawable) mContext.getResources().getDrawable(
374 R.drawable.widget_tile)).getBitmap();
375 previewWidth = tileBitmap.getWidth() * spanX;
376 previewHeight = tileBitmap.getHeight() * spanY;
Michael Jurka05713af2013-01-23 12:39:24 +0100377 }
378
379 // Scale to fit width only - let the widget preview be clipped in the
380 // vertical dimension
381 float scale = 1f;
382 if (preScaledWidthOut != null) {
383 preScaledWidthOut[0] = previewWidth;
384 }
385 if (previewWidth > maxPreviewWidth) {
386 scale = maxPreviewWidth / (float) previewWidth;
387 }
388 if (scale != 1f) {
389 previewWidth = (int) (scale * previewWidth);
390 previewHeight = (int) (scale * previewHeight);
391 }
392
393 // 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 -0700394 final Canvas c = new Canvas();
Michael Jurka05713af2013-01-23 12:39:24 +0100395 if (preview == null) {
396 preview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700397 c.setBitmap(preview);
398 } else {
399 // Reusing bitmap. Clear it.
400 c.setBitmap(preview);
401 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100402 }
403
404 // Draw the scaled preview into the final bitmap
Hyunyoung Song41e33692015-06-15 12:26:54 -0700405 int x = (preview.getWidth() - previewWidth - mProfileBadgeMargin) / 2;
Michael Jurka05713af2013-01-23 12:39:24 +0100406 if (widgetPreviewExists) {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700407 drawable.setBounds(x, 0, x + previewWidth, previewHeight);
408 drawable.draw(c);
Michael Jurka05713af2013-01-23 12:39:24 +0100409 } else {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700410 final Paint p = new Paint();
411 p.setFilterBitmap(true);
Adam Cohen2e6da152015-05-06 11:42:25 -0700412 int appIconSize = launcher.getDeviceProfile().iconSizePx;
Michael Jurka05713af2013-01-23 12:39:24 +0100413
Sunny Goyal4cad7532015-03-18 15:56:30 -0700414 // draw the spanX x spanY tiles
415 final Rect src = new Rect(0, 0, tileBitmap.getWidth(), tileBitmap.getHeight());
416
417 float tileW = scale * tileBitmap.getWidth();
418 float tileH = scale * tileBitmap.getHeight();
419 final RectF dst = new RectF(0, 0, tileW, tileH);
420
421 float tx = x;
422 for (int i = 0; i < spanX; i++, tx += tileW) {
423 float ty = 0;
424 for (int j = 0; j < spanY; j++, ty += tileH) {
425 dst.offsetTo(tx, ty);
426 c.drawBitmap(tileBitmap, src, dst, p);
427 }
Michael Jurka05713af2013-01-23 12:39:24 +0100428 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700429
430 // Draw the icon in the top left corner
431 // TODO: use top right for RTL
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700432 int minOffset = (int) (appIconSize * WIDGET_PREVIEW_ICON_PADDING_PERCENTAGE);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700433 int smallestSide = Math.min(previewWidth, previewHeight);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700434 float iconScale = Math.min((float) smallestSide / (appIconSize + 2 * minOffset), scale);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700435
436 try {
437 Drawable icon = mutateOnMainThread(mManager.loadIcon(info, mIconCache));
438 if (icon != null) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700439 int hoffset = (int) ((tileW - appIconSize * iconScale) / 2) + x;
440 int yoffset = (int) ((tileH - appIconSize * iconScale) / 2);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700441 icon.setBounds(hoffset, yoffset,
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700442 hoffset + (int) (appIconSize * iconScale),
443 yoffset + (int) (appIconSize * iconScale));
Sunny Goyal4cad7532015-03-18 15:56:30 -0700444 icon.draw(c);
445 }
446 } catch (Resources.NotFoundException e) { }
Michael Jurka05713af2013-01-23 12:39:24 +0100447 c.setBitmap(null);
448 }
Hyunyoung Song41e33692015-06-15 12:26:54 -0700449 int imageHeight = Math.min(preview.getHeight(), previewHeight + mProfileBadgeMargin);
450 return mManager.getBadgeBitmap(info, preview, imageHeight);
Michael Jurka05713af2013-01-23 12:39:24 +0100451 }
452
453 private Bitmap generateShortcutPreview(
Adam Cohen2e6da152015-05-06 11:42:25 -0700454 Launcher launcher, ResolveInfo info, int maxWidth, int maxHeight, Bitmap preview) {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700455 final Canvas c = new Canvas();
456 if (preview == null) {
Michael Jurka05713af2013-01-23 12:39:24 +0100457 preview = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700458 c.setBitmap(preview);
459 } else if (preview.getWidth() != maxWidth || preview.getHeight() != maxHeight) {
460 throw new RuntimeException("Improperly sized bitmap passed as argument");
461 } else {
462 // Reusing bitmap. Clear it.
463 c.setBitmap(preview);
464 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100465 }
466
Sunny Goyal4cad7532015-03-18 15:56:30 -0700467 Drawable icon = mutateOnMainThread(mIconCache.getFullResIcon(info.activityInfo));
468 icon.setFilterBitmap(true);
469
Michael Jurka05713af2013-01-23 12:39:24 +0100470 // Draw a desaturated/scaled version of the icon in the background as a watermark
Sunny Goyal4cad7532015-03-18 15:56:30 -0700471 ColorMatrix colorMatrix = new ColorMatrix();
472 colorMatrix.setSaturation(0);
473 icon.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
474 icon.setAlpha((int) (255 * 0.06f));
475
476 Resources res = mContext.getResources();
477 int paddingTop = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_top);
478 int paddingLeft = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_left);
479 int paddingRight = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_right);
480 int scaledIconWidth = (maxWidth - paddingLeft - paddingRight);
481 icon.setBounds(paddingLeft, paddingTop,
482 paddingLeft + scaledIconWidth, paddingTop + scaledIconWidth);
483 icon.draw(c);
484
485 // Draw the final icon at top left corner.
486 // TODO: use top right for RTL
Adam Cohen2e6da152015-05-06 11:42:25 -0700487 int appIconSize = launcher.getDeviceProfile().iconSizePx;
488
Sunny Goyal4cad7532015-03-18 15:56:30 -0700489 icon.setAlpha(255);
490 icon.setColorFilter(null);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700491 icon.setBounds(0, 0, appIconSize, appIconSize);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700492 icon.draw(c);
493
Michael Jurka05713af2013-01-23 12:39:24 +0100494 c.setBitmap(null);
Michael Jurka05713af2013-01-23 12:39:24 +0100495 return preview;
496 }
497
Adrian Roos65d60e22014-04-15 21:07:49 +0200498 private Drawable mutateOnMainThread(final Drawable drawable) {
499 try {
500 return mMainThreadExecutor.submit(new Callable<Drawable>() {
501 @Override
502 public Drawable call() throws Exception {
503 return drawable.mutate();
504 }
505 }).get();
506 } catch (InterruptedException e) {
507 Thread.currentThread().interrupt();
508 throw new RuntimeException(e);
509 } catch (ExecutionException e) {
510 throw new RuntimeException(e);
511 }
512 }
Adrian Roos1f375ab2014-04-28 18:26:38 +0200513
Adrian Roos1f375ab2014-04-28 18:26:38 +0200514 /**
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700515 * @return an array of containing versionCode and lastUpdatedTime for the package.
Adrian Roos1f375ab2014-04-28 18:26:38 +0200516 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700517 @Thunk long[] getPackageVersion(String packageName) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700518 synchronized (mPackageVersions) {
519 long[] versions = mPackageVersions.get(packageName);
520 if (versions == null) {
521 versions = new long[2];
Adrian Roos1f375ab2014-04-28 18:26:38 +0200522 try {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700523 PackageInfo info = mContext.getPackageManager().getPackageInfo(packageName, 0);
524 versions[0] = info.versionCode;
525 versions[1] = info.lastUpdateTime;
526 } catch (NameNotFoundException e) {
527 Log.e(TAG, "PackageInfo not found", e);
528 }
529 mPackageVersions.put(packageName, versions);
530 }
531 return versions;
532 }
533 }
534
535 /**
536 * A request Id which can be used by the client to cancel any request.
537 */
538 public class PreviewLoadRequest {
539
540 private final PreviewLoadTask mTask;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700541
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700542 public PreviewLoadRequest(PreviewLoadTask task) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700543 mTask = task;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700544 }
545
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700546 public void cleanup() {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700547 if (mTask != null) {
548 mTask.cancel(true);
549 }
550
Winson Chung05304db2015-05-18 16:53:20 -0700551 // This only handles the case where the PreviewLoadTask is cancelled after the task has
552 // successfully completed (including having written to disk when necessary). In the
553 // other cases where it is cancelled while the task is running, it will be cleaned up
554 // in the tasks's onCancelled() call, and if cancelled while the task is writing to
555 // disk, it will be cancelled in the task's onPostExecute() call.
556 if (mTask.mBitmapToRecycle != null) {
557 synchronized (mUnusedBitmaps) {
558 mUnusedBitmaps.add(mTask.mBitmapToRecycle);
559 }
560 mTask.mBitmapToRecycle = null;
Adrian Roos1f375ab2014-04-28 18:26:38 +0200561 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700562 }
563 }
564
565 public class PreviewLoadTask extends AsyncTask<Void, Void, Bitmap> {
Sunny Goyal316490e2015-06-02 09:38:28 -0700566 @Thunk final WidgetCacheKey mKey;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700567 private final Object mInfo;
568 private final int mPreviewHeight;
569 private final int mPreviewWidth;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700570 private final WidgetCell mCaller;
Sunny Goyal316490e2015-06-02 09:38:28 -0700571 @Thunk long[] mVersions;
572 @Thunk Bitmap mBitmapToRecycle;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700573
574 PreviewLoadTask(WidgetCacheKey key, Object info, int previewWidth,
Hyunyoung Song3f471442015-04-08 19:01:34 -0700575 int previewHeight, WidgetCell caller) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700576 mKey = key;
577 mInfo = info;
578 mPreviewHeight = previewHeight;
579 mPreviewWidth = previewWidth;
580 mCaller = caller;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700581 if (DEBUG) {
582 Log.d(TAG, String.format("%s, %s, %d, %d",
583 mKey, mInfo, mPreviewHeight, mPreviewWidth));
584 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700585 }
586
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700587 @Override
588 protected Bitmap doInBackground(Void... params) {
589 Bitmap unusedBitmap = null;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700590
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700591 // If already cancelled before this gets to run in the background, then return early
592 if (isCancelled()) {
593 return null;
594 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700595 synchronized (mUnusedBitmaps) {
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700596 // Check if we can re-use a bitmap
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700597 for (Bitmap candidate : mUnusedBitmaps) {
598 if (candidate != null && candidate.isMutable() &&
599 candidate.getWidth() == mPreviewWidth &&
600 candidate.getHeight() == mPreviewHeight) {
601 unusedBitmap = candidate;
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700602 mUnusedBitmaps.remove(unusedBitmap);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700603 break;
604 }
605 }
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700606 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700607
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700608 // creating a bitmap is expensive. Do not do this inside synchronized block.
609 if (unusedBitmap == null) {
610 unusedBitmap = Bitmap.createBitmap(mPreviewWidth, mPreviewHeight, Config.ARGB_8888);
Adrian Roos1f375ab2014-04-28 18:26:38 +0200611 }
Winson Chung05304db2015-05-18 16:53:20 -0700612 // If cancelled now, don't bother reading the preview from the DB
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700613 if (isCancelled()) {
Winson Chung05304db2015-05-18 16:53:20 -0700614 return unusedBitmap;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700615 }
Winson Chung05304db2015-05-18 16:53:20 -0700616 Bitmap preview = readFromDb(mKey, unusedBitmap, this);
617 // Only consider generating the preview if we have not cancelled the task already
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700618 if (!isCancelled() && preview == null) {
619 // Fetch the version info before we generate the preview, so that, in-case the
620 // app was updated while we are generating the preview, we use the old version info,
621 // which would gets re-written next time.
Winson Chung05304db2015-05-18 16:53:20 -0700622 mVersions = getPackageVersion(mKey.componentName.getPackageName());
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700623
Adam Cohen2e6da152015-05-06 11:42:25 -0700624 Launcher launcher = (Launcher) mCaller.getContext();
625
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700626 // it's not in the db... we need to generate it
Adam Cohen2e6da152015-05-06 11:42:25 -0700627 preview = generatePreview(launcher, mInfo, unusedBitmap, mPreviewWidth, mPreviewHeight);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700628 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700629 return preview;
630 }
631
632 @Override
Winson Chung05304db2015-05-18 16:53:20 -0700633 protected void onPostExecute(final Bitmap preview) {
634 mCaller.applyPreview(preview);
635
636 // Write the generated preview to the DB in the worker thread
637 if (mVersions != null) {
638 mWorkerHandler.post(new Runnable() {
639 @Override
640 public void run() {
641 if (!isCancelled()) {
642 // If we are still using this preview, then write it to the DB and then
643 // let the normal clear mechanism recycle the bitmap
644 writeToDb(mKey, mVersions, preview);
645 mBitmapToRecycle = preview;
646 } else {
647 // If we've already cancelled, then skip writing the bitmap to the DB
648 // and manually add the bitmap back to the recycled set
649 synchronized (mUnusedBitmaps) {
650 mUnusedBitmaps.add(preview);
651 }
652 }
653 }
654 });
655 } else {
656 // If we don't need to write to disk, then ensure the preview gets recycled by
657 // the normal clear mechanism
658 mBitmapToRecycle = preview;
659 }
660 }
661
662 @Override
663 protected void onCancelled(Bitmap preview) {
664 // If we've cancelled while the task is running, then can return the bitmap to the
665 // recycled set immediately. Otherwise, it will be recycled after the preview is written
666 // to disk.
667 if (preview != null) {
668 synchronized (mUnusedBitmaps) {
669 mUnusedBitmaps.add(preview);
670 }
671 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700672 }
673 }
674
675 private static final class WidgetCacheKey extends ComponentKey {
676
677 // TODO: remove dependency on size
Sunny Goyal316490e2015-06-02 09:38:28 -0700678 @Thunk final String size;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700679
680 public WidgetCacheKey(ComponentName componentName, UserHandleCompat user, String size) {
681 super(componentName, user);
682 this.size = size;
683 }
684
685 @Override
686 public int hashCode() {
687 return super.hashCode() ^ size.hashCode();
688 }
689
690 @Override
691 public boolean equals(Object o) {
692 return super.equals(o) && ((WidgetCacheKey) o).size.equals(size);
Adrian Roos1f375ab2014-04-28 18:26:38 +0200693 }
694 }
Michael Jurka05713af2013-01-23 12:39:24 +0100695}