blob: 629387ed0b99c5e22798fa68053c3d577eff29ad [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 Goyal383c5072015-06-12 21:18:53 -070030
Sunny Goyalffe83f12014-08-14 17:39:34 -070031import com.android.launcher3.compat.AppWidgetManagerCompat;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070032import com.android.launcher3.compat.UserHandleCompat;
33import com.android.launcher3.compat.UserManagerCompat;
34import com.android.launcher3.util.ComponentKey;
Adam Cohen091440a2015-03-18 14:16:05 -070035import com.android.launcher3.util.Thunk;
Hyunyoung Song3f471442015-04-08 19:01:34 -070036import com.android.launcher3.widget.WidgetCell;
Hyunyoung Song8821ca92015-05-04 16:28:20 -070037
38import java.util.ArrayList;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070039import java.util.Collections;
Michael Jurka05713af2013-01-23 12:39:24 +010040import java.util.HashMap;
41import java.util.HashSet;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070042import java.util.Set;
43import java.util.WeakHashMap;
Adrian Roos65d60e22014-04-15 21:07:49 +020044import java.util.concurrent.Callable;
45import java.util.concurrent.ExecutionException;
Michael Jurka05713af2013-01-23 12:39:24 +010046
Sunny Goyalffe83f12014-08-14 17:39:34 -070047public class WidgetPreviewLoader {
Michael Jurka05713af2013-01-23 12:39:24 +010048
Sunny Goyalffe83f12014-08-14 17:39:34 -070049 private static final String TAG = "WidgetPreviewLoader";
Hyunyoung Song3f471442015-04-08 19:01:34 -070050 private static final boolean DEBUG = false;
Sunny Goyalffe83f12014-08-14 17:39:34 -070051
52 private static final float WIDGET_PREVIEW_ICON_PADDING_PERCENTAGE = 0.25f;
Sunny Goyalffe83f12014-08-14 17:39:34 -070053
Sunny Goyal5b0e6692015-03-19 14:31:19 -070054 private final HashMap<String, long[]> mPackageVersions = new HashMap<>();
Hyunyoung Song559d90d2015-04-28 15:06:45 -070055
56 /**
57 * Weak reference objects, do not prevent their referents from being made finalizable,
58 * finalized, and then reclaimed.
Hyunyoung Songe98f4a42015-06-16 10:45:24 -070059 * Note: synchronized block used for this variable is expensive and the block should always
60 * be posted to a background thread.
Hyunyoung Song559d90d2015-04-28 15:06:45 -070061 */
Sunny Goyalb4cbea42015-06-16 15:10:36 -070062 @Thunk final Set<Bitmap> mUnusedBitmaps =
Hyunyoung Song559d90d2015-04-28 15:06:45 -070063 Collections.newSetFromMap(new WeakHashMap<Bitmap, Boolean>());
Sunny Goyal4cad7532015-03-18 15:56:30 -070064
65 private final Context mContext;
Sunny Goyalffe83f12014-08-14 17:39:34 -070066 private final IconCache mIconCache;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070067 private final UserManagerCompat mUserManager;
Sunny Goyalffe83f12014-08-14 17:39:34 -070068 private final AppWidgetManagerCompat mManager;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070069 private final CacheDb mDb;
Hyunyoung Song41e33692015-06-15 12:26:54 -070070 private final int mProfileBadgeMargin;
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;
Sunny Goyalffe83f12014-08-14 17:39:34 -070078 mManager = 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());
Hyunyoung Song41e33692015-06-15 12:26:54 -070082 mProfileBadgeMargin = context.getResources()
83 .getDimensionPixelSize(R.dimen.profile_badge_margin);
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 *
90 * @param o either {@link LauncherAppWidgetProviderInfo} or {@link ResolveInfo}
Sunny Goyal5b0e6692015-03-19 14:31:19 -070091 * @return a request id which can be used to cancel the request.
92 */
Adam Cohen2e6da152015-05-06 11:42:25 -070093 public PreviewLoadRequest getPreview(final Object o, int previewWidth,
94 int previewHeight, WidgetCell caller) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -070095 String size = previewWidth + "x" + previewHeight;
96 WidgetCacheKey key = getObjectKey(o, size);
Michael Jurka3f4e0702013-02-05 11:21:28 +010097
Sunny Goyal5b0e6692015-03-19 14:31:19 -070098 PreviewLoadTask task = new PreviewLoadTask(key, o, previewWidth, previewHeight, caller);
99 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700100 return new PreviewLoadRequest(task);
Michael Jurka05713af2013-01-23 12:39:24 +0100101 }
102
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700103 /**
104 * The DB holds the generated previews for various components. Previews can also have different
105 * sizes (landscape vs portrait).
106 */
107 private static class CacheDb extends SQLiteOpenHelper {
108 private static final int DB_VERSION = 3;
109
110 private static final String TABLE_NAME = "shortcut_and_widget_previews";
111 private static final String COLUMN_COMPONENT = "componentName";
112 private static final String COLUMN_USER = "profileId";
113 private static final String COLUMN_SIZE = "size";
114 private static final String COLUMN_PACKAGE = "packageName";
115 private static final String COLUMN_LAST_UPDATED = "lastUpdated";
116 private static final String COLUMN_VERSION = "version";
117 private static final String COLUMN_PREVIEW_BITMAP = "preview_bitmap";
Michael Jurka05713af2013-01-23 12:39:24 +0100118
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100119 public CacheDb(Context context) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700120 super(context, LauncherFiles.WIDGET_PREVIEWS_DB, null, DB_VERSION);
Michael Jurka05713af2013-01-23 12:39:24 +0100121 }
122
123 @Override
124 public void onCreate(SQLiteDatabase database) {
Michael Jurka32b7a092013-02-07 20:06:49 +0100125 database.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" +
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700126 COLUMN_COMPONENT + " TEXT NOT NULL, " +
127 COLUMN_USER + " INTEGER NOT NULL, " +
Michael Jurka05713af2013-01-23 12:39:24 +0100128 COLUMN_SIZE + " TEXT NOT NULL, " +
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700129 COLUMN_PACKAGE + " TEXT NOT NULL, " +
130 COLUMN_LAST_UPDATED + " INTEGER NOT NULL DEFAULT 0, " +
131 COLUMN_VERSION + " INTEGER NOT NULL DEFAULT 0, " +
132 COLUMN_PREVIEW_BITMAP + " BLOB, " +
133 "PRIMARY KEY (" + COLUMN_COMPONENT + ", " + COLUMN_USER + ", " + COLUMN_SIZE + ") " +
Michael Jurka32b7a092013-02-07 20:06:49 +0100134 ");");
Michael Jurka05713af2013-01-23 12:39:24 +0100135 }
136
137 @Override
138 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Michael Jurkae5919c52013-03-06 17:30:10 +0100139 if (oldVersion != newVersion) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700140 clearDB(db);
Michael Jurkae5919c52013-03-06 17:30:10 +0100141 }
Michael Jurka05713af2013-01-23 12:39:24 +0100142 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700143
144 @Override
145 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
146 if (oldVersion != newVersion) {
147 clearDB(db);
148 }
149 }
150
151 private void clearDB(SQLiteDatabase db) {
152 db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
153 onCreate(db);
154 }
Michael Jurka05713af2013-01-23 12:39:24 +0100155 }
156
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700157 private WidgetCacheKey getObjectKey(Object o, String size) {
Michael Jurka05713af2013-01-23 12:39:24 +0100158 // should cache the string builder
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700159 if (o instanceof LauncherAppWidgetProviderInfo) {
160 LauncherAppWidgetProviderInfo info = (LauncherAppWidgetProviderInfo) o;
161 return new WidgetCacheKey(info.provider, mManager.getUser(info), size);
Michael Jurka05713af2013-01-23 12:39:24 +0100162 } else {
163 ResolveInfo info = (ResolveInfo) o;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700164 return new WidgetCacheKey(
165 new ComponentName(info.activityInfo.packageName, info.activityInfo.name),
166 UserHandleCompat.myUserHandle(), size);
Michael Jurka05713af2013-01-23 12:39:24 +0100167 }
168 }
169
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700170 @Thunk void writeToDb(WidgetCacheKey key, long[] versions, Bitmap preview) {
Michael Jurka05713af2013-01-23 12:39:24 +0100171 ContentValues values = new ContentValues();
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700172 values.put(CacheDb.COLUMN_COMPONENT, key.componentName.flattenToShortString());
173 values.put(CacheDb.COLUMN_USER, mUserManager.getSerialNumberForUser(key.user));
174 values.put(CacheDb.COLUMN_SIZE, key.size);
175 values.put(CacheDb.COLUMN_PACKAGE, key.componentName.getPackageName());
176 values.put(CacheDb.COLUMN_VERSION, versions[0]);
177 values.put(CacheDb.COLUMN_LAST_UPDATED, versions[1]);
178 values.put(CacheDb.COLUMN_PREVIEW_BITMAP, Utilities.flattenBitmap(preview));
Michael Jurka05713af2013-01-23 12:39:24 +0100179
Michael Jurka6e27f642013-12-10 13:40:30 +0100180 try {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700181 mDb.getWritableDatabase().insertWithOnConflict(CacheDb.TABLE_NAME, null, values,
182 SQLiteDatabase.CONFLICT_REPLACE);
183 } catch (SQLException e) {
184 Log.e(TAG, "Error saving image to DB", e);
Michael Jurka6e27f642013-12-10 13:40:30 +0100185 }
Michael Jurka05713af2013-01-23 12:39:24 +0100186 }
187
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700188 public void removePackage(String packageName, UserHandleCompat user) {
189 removePackage(packageName, user, mUserManager.getSerialNumberForUser(user));
190 }
191
192 private void removePackage(String packageName, UserHandleCompat user, long userSerial) {
193 synchronized(mPackageVersions) {
194 mPackageVersions.remove(packageName);
195 }
196
Michael Jurka6e27f642013-12-10 13:40:30 +0100197 try {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700198 mDb.getWritableDatabase().delete(CacheDb.TABLE_NAME,
199 CacheDb.COLUMN_PACKAGE + " = ? AND " + CacheDb.COLUMN_USER + " = ?",
200 new String[] {packageName, Long.toString(userSerial)});
201 } catch (SQLException e) {
202 Log.e(TAG, "Unable to delete items from DB", e);
Michael Jurka6e27f642013-12-10 13:40:30 +0100203 }
Michael Jurka8ff02ca2013-11-01 14:19:27 +0100204 }
205
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700206 /**
207 * Updates the persistent DB:
208 * 1. Any preview generated for an old package version is removed
209 * 2. Any preview for an absent package is removed
210 * This ensures that we remove entries for packages which changed while the launcher was dead.
211 */
Hyunyoung Song8821ca92015-05-04 16:28:20 -0700212 public void removeObsoletePreviews(ArrayList<Object> list) {
Hyunyoung Song2bd3d7d2015-05-21 13:04:53 -0700213 Utilities.assertWorkerThread();
Hyunyoung Song8821ca92015-05-04 16:28:20 -0700214
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700215 LongSparseArray<UserHandleCompat> userIdCache = new LongSparseArray<>();
216 LongSparseArray<HashSet<String>> validPackages = new LongSparseArray<>();
217
Hyunyoung Song8821ca92015-05-04 16:28:20 -0700218 for (Object obj : list) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700219 final UserHandleCompat user;
220 final String pkg;
221 if (obj instanceof ResolveInfo) {
222 user = UserHandleCompat.myUserHandle();
223 pkg = ((ResolveInfo) obj).activityInfo.packageName;
224 } else {
225 LauncherAppWidgetProviderInfo info = (LauncherAppWidgetProviderInfo) obj;
226 user = mManager.getUser(info);
227 pkg = info.provider.getPackageName();
228 }
229
230 int userIdIndex = userIdCache.indexOfValue(user);
231 final long userId;
232 if (userIdIndex < 0) {
233 userId = mUserManager.getSerialNumberForUser(user);
234 userIdCache.put(userId, user);
235 } else {
236 userId = userIdCache.keyAt(userIdIndex);
237 }
238
239 HashSet<String> packages = validPackages.get(userId);
240 if (packages == null) {
241 packages = new HashSet<>();
242 validPackages.put(userId, packages);
243 }
244 packages.add(pkg);
Michael Jurka05713af2013-01-23 12:39:24 +0100245 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700246
247 LongSparseArray<HashSet<String>> packagesToDelete = new LongSparseArray<>();
248 Cursor c = null;
249 try {
250 c = mDb.getReadableDatabase().query(CacheDb.TABLE_NAME,
251 new String[] {CacheDb.COLUMN_USER, CacheDb.COLUMN_PACKAGE,
252 CacheDb.COLUMN_LAST_UPDATED, CacheDb.COLUMN_VERSION},
253 null, null, null, null, null);
254 while (c.moveToNext()) {
255 long userId = c.getLong(0);
256 String pkg = c.getString(1);
257 long lastUpdated = c.getLong(2);
258 long version = c.getLong(3);
259
260 HashSet<String> packages = validPackages.get(userId);
261 if (packages != null && packages.contains(pkg)) {
262 long[] versions = getPackageVersion(pkg);
263 if (versions[0] == version && versions[1] == lastUpdated) {
264 // Every thing checks out
265 continue;
266 }
267 }
268
269 // We need to delete this package.
270 packages = packagesToDelete.get(userId);
271 if (packages == null) {
272 packages = new HashSet<>();
273 packagesToDelete.put(userId, packages);
274 }
275 packages.add(pkg);
276 }
277
278 for (int i = 0; i < packagesToDelete.size(); i++) {
279 long userId = packagesToDelete.keyAt(i);
280 UserHandleCompat user = mUserManager.getUserForSerialNumber(userId);
281 for (String pkg : packagesToDelete.valueAt(i)) {
282 removePackage(pkg, user, userId);
283 }
284 }
285 } catch (SQLException e) {
286 Log.e(TAG, "Error updatating widget previews", e);
287 } finally {
288 if (c != null) {
289 c.close();
290 }
291 }
292 }
293
Winson Chung05304db2015-05-18 16:53:20 -0700294 /**
295 * Reads the preview bitmap from the DB or null if the preview is not in the DB.
296 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700297 @Thunk Bitmap readFromDb(WidgetCacheKey key, Bitmap recycle, PreviewLoadTask loadTask) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700298 Cursor cursor = null;
299 try {
300 cursor = mDb.getReadableDatabase().query(
301 CacheDb.TABLE_NAME,
302 new String[] { CacheDb.COLUMN_PREVIEW_BITMAP },
303 CacheDb.COLUMN_COMPONENT + " = ? AND " + CacheDb.COLUMN_USER + " = ? AND " + CacheDb.COLUMN_SIZE + " = ?",
304 new String[] {
305 key.componentName.flattenToString(),
306 Long.toString(mUserManager.getSerialNumberForUser(key.user)),
307 key.size
308 },
309 null, null, null);
Winson Chung05304db2015-05-18 16:53:20 -0700310 // If cancelled, skip getting the blob and decoding it into a bitmap
311 if (loadTask.isCancelled()) {
312 return null;
313 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700314 if (cursor.moveToNext()) {
315 byte[] blob = cursor.getBlob(0);
316 BitmapFactory.Options opts = new BitmapFactory.Options();
317 opts.inBitmap = recycle;
Michael Jurka6e27f642013-12-10 13:40:30 +0100318 try {
Winson Chung05304db2015-05-18 16:53:20 -0700319 if (!loadTask.isCancelled()) {
320 return BitmapFactory.decodeByteArray(blob, 0, blob.length, opts);
321 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700322 } catch (Exception e) {
323 return null;
Michael Jurka6e27f642013-12-10 13:40:30 +0100324 }
Michael Jurka05713af2013-01-23 12:39:24 +0100325 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700326 } catch (SQLException e) {
327 Log.w(TAG, "Error loading preview from DB", e);
328 } finally {
329 if (cursor != null) {
330 cursor.close();
331 }
332 }
333 return null;
Michael Jurka05713af2013-01-23 12:39:24 +0100334 }
335
Sunny Goyal316490e2015-06-02 09:38:28 -0700336 @Thunk Bitmap generatePreview(Launcher launcher, Object info, Bitmap recycle,
Adam Cohen2e6da152015-05-06 11:42:25 -0700337 int previewWidth, int previewHeight) {
Adam Cohen59400422014-03-05 18:07:04 -0800338 if (info instanceof LauncherAppWidgetProviderInfo) {
Adam Cohen2e6da152015-05-06 11:42:25 -0700339 return generateWidgetPreview(launcher, (LauncherAppWidgetProviderInfo) info,
340 previewWidth, recycle, null);
Michael Jurka05713af2013-01-23 12:39:24 +0100341 } else {
Adam Cohen2e6da152015-05-06 11:42:25 -0700342 return generateShortcutPreview(launcher,
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700343 (ResolveInfo) info, previewWidth, previewHeight, recycle);
Michael Jurka05713af2013-01-23 12:39:24 +0100344 }
345 }
346
Adam Cohen2e6da152015-05-06 11:42:25 -0700347 public Bitmap generateWidgetPreview(Launcher launcher, LauncherAppWidgetProviderInfo info,
Sunny Goyal4cad7532015-03-18 15:56:30 -0700348 int maxPreviewWidth, Bitmap preview, int[] preScaledWidthOut) {
Michael Jurka05713af2013-01-23 12:39:24 +0100349 // Load the preview image if possible
Michael Jurka05713af2013-01-23 12:39:24 +0100350 if (maxPreviewWidth < 0) maxPreviewWidth = Integer.MAX_VALUE;
Michael Jurka05713af2013-01-23 12:39:24 +0100351
352 Drawable drawable = null;
Sunny Goyalffe83f12014-08-14 17:39:34 -0700353 if (info.previewImage != 0) {
354 drawable = mManager.loadPreview(info);
Adrian Roosfa9ffc22014-05-12 15:59:59 +0200355 if (drawable != null) {
356 drawable = mutateOnMainThread(drawable);
357 } else {
Michael Jurka05713af2013-01-23 12:39:24 +0100358 Log.w(TAG, "Can't load widget preview drawable 0x" +
Sunny Goyalffe83f12014-08-14 17:39:34 -0700359 Integer.toHexString(info.previewImage) + " for provider: " + info.provider);
Michael Jurka05713af2013-01-23 12:39:24 +0100360 }
361 }
362
Sunny Goyal4cad7532015-03-18 15:56:30 -0700363 final boolean widgetPreviewExists = (drawable != null);
Adam Cohen2e6da152015-05-06 11:42:25 -0700364 final int spanX = info.getSpanX(launcher) < 1 ? 1 : info.getSpanX(launcher);
365 final int spanY = info.getSpanY(launcher) < 1 ? 1 : info.getSpanY(launcher);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700366
Michael Jurka05713af2013-01-23 12:39:24 +0100367 int previewWidth;
368 int previewHeight;
Sunny Goyal4cad7532015-03-18 15:56:30 -0700369 Bitmap tileBitmap = null;
370
Michael Jurka05713af2013-01-23 12:39:24 +0100371 if (widgetPreviewExists) {
372 previewWidth = drawable.getIntrinsicWidth();
373 previewHeight = drawable.getIntrinsicHeight();
374 } else {
375 // Generate a preview image if we couldn't load one
Sunny Goyal4cad7532015-03-18 15:56:30 -0700376 tileBitmap = ((BitmapDrawable) mContext.getResources().getDrawable(
377 R.drawable.widget_tile)).getBitmap();
378 previewWidth = tileBitmap.getWidth() * spanX;
379 previewHeight = tileBitmap.getHeight() * spanY;
Michael Jurka05713af2013-01-23 12:39:24 +0100380 }
381
382 // Scale to fit width only - let the widget preview be clipped in the
383 // vertical dimension
384 float scale = 1f;
385 if (preScaledWidthOut != null) {
386 preScaledWidthOut[0] = previewWidth;
387 }
388 if (previewWidth > maxPreviewWidth) {
389 scale = maxPreviewWidth / (float) previewWidth;
390 }
391 if (scale != 1f) {
392 previewWidth = (int) (scale * previewWidth);
393 previewHeight = (int) (scale * previewHeight);
394 }
395
396 // 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 -0700397 final Canvas c = new Canvas();
Michael Jurka05713af2013-01-23 12:39:24 +0100398 if (preview == null) {
399 preview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700400 c.setBitmap(preview);
401 } else {
402 // Reusing bitmap. Clear it.
403 c.setBitmap(preview);
404 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100405 }
406
407 // Draw the scaled preview into the final bitmap
Hyunyoung Song41e33692015-06-15 12:26:54 -0700408 int x = (preview.getWidth() - previewWidth - mProfileBadgeMargin) / 2;
Michael Jurka05713af2013-01-23 12:39:24 +0100409 if (widgetPreviewExists) {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700410 drawable.setBounds(x, 0, x + previewWidth, previewHeight);
411 drawable.draw(c);
Michael Jurka05713af2013-01-23 12:39:24 +0100412 } else {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700413 final Paint p = new Paint();
414 p.setFilterBitmap(true);
Adam Cohen2e6da152015-05-06 11:42:25 -0700415 int appIconSize = launcher.getDeviceProfile().iconSizePx;
Michael Jurka05713af2013-01-23 12:39:24 +0100416
Sunny Goyal4cad7532015-03-18 15:56:30 -0700417 // draw the spanX x spanY tiles
418 final Rect src = new Rect(0, 0, tileBitmap.getWidth(), tileBitmap.getHeight());
419
420 float tileW = scale * tileBitmap.getWidth();
421 float tileH = scale * tileBitmap.getHeight();
422 final RectF dst = new RectF(0, 0, tileW, tileH);
423
424 float tx = x;
425 for (int i = 0; i < spanX; i++, tx += tileW) {
426 float ty = 0;
427 for (int j = 0; j < spanY; j++, ty += tileH) {
428 dst.offsetTo(tx, ty);
429 c.drawBitmap(tileBitmap, src, dst, p);
430 }
Michael Jurka05713af2013-01-23 12:39:24 +0100431 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700432
433 // Draw the icon in the top left corner
434 // TODO: use top right for RTL
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700435 int minOffset = (int) (appIconSize * WIDGET_PREVIEW_ICON_PADDING_PERCENTAGE);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700436 int smallestSide = Math.min(previewWidth, previewHeight);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700437 float iconScale = Math.min((float) smallestSide / (appIconSize + 2 * minOffset), scale);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700438
439 try {
440 Drawable icon = mutateOnMainThread(mManager.loadIcon(info, mIconCache));
441 if (icon != null) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700442 int hoffset = (int) ((tileW - appIconSize * iconScale) / 2) + x;
443 int yoffset = (int) ((tileH - appIconSize * iconScale) / 2);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700444 icon.setBounds(hoffset, yoffset,
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700445 hoffset + (int) (appIconSize * iconScale),
446 yoffset + (int) (appIconSize * iconScale));
Sunny Goyal4cad7532015-03-18 15:56:30 -0700447 icon.draw(c);
448 }
449 } catch (Resources.NotFoundException e) { }
Michael Jurka05713af2013-01-23 12:39:24 +0100450 c.setBitmap(null);
451 }
Hyunyoung Song41e33692015-06-15 12:26:54 -0700452 int imageHeight = Math.min(preview.getHeight(), previewHeight + mProfileBadgeMargin);
453 return mManager.getBadgeBitmap(info, preview, imageHeight);
Michael Jurka05713af2013-01-23 12:39:24 +0100454 }
455
456 private Bitmap generateShortcutPreview(
Adam Cohen2e6da152015-05-06 11:42:25 -0700457 Launcher launcher, ResolveInfo info, int maxWidth, int maxHeight, Bitmap preview) {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700458 final Canvas c = new Canvas();
459 if (preview == null) {
Michael Jurka05713af2013-01-23 12:39:24 +0100460 preview = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700461 c.setBitmap(preview);
462 } else if (preview.getWidth() != maxWidth || preview.getHeight() != maxHeight) {
463 throw new RuntimeException("Improperly sized bitmap passed as argument");
464 } else {
465 // Reusing bitmap. Clear it.
466 c.setBitmap(preview);
467 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100468 }
469
Sunny Goyal4cad7532015-03-18 15:56:30 -0700470 Drawable icon = mutateOnMainThread(mIconCache.getFullResIcon(info.activityInfo));
471 icon.setFilterBitmap(true);
472
Michael Jurka05713af2013-01-23 12:39:24 +0100473 // Draw a desaturated/scaled version of the icon in the background as a watermark
Sunny Goyal4cad7532015-03-18 15:56:30 -0700474 ColorMatrix colorMatrix = new ColorMatrix();
475 colorMatrix.setSaturation(0);
476 icon.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
477 icon.setAlpha((int) (255 * 0.06f));
478
479 Resources res = mContext.getResources();
480 int paddingTop = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_top);
481 int paddingLeft = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_left);
482 int paddingRight = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_right);
483 int scaledIconWidth = (maxWidth - paddingLeft - paddingRight);
484 icon.setBounds(paddingLeft, paddingTop,
485 paddingLeft + scaledIconWidth, paddingTop + scaledIconWidth);
486 icon.draw(c);
487
488 // Draw the final icon at top left corner.
489 // TODO: use top right for RTL
Adam Cohen2e6da152015-05-06 11:42:25 -0700490 int appIconSize = launcher.getDeviceProfile().iconSizePx;
491
Sunny Goyal4cad7532015-03-18 15:56:30 -0700492 icon.setAlpha(255);
493 icon.setColorFilter(null);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700494 icon.setBounds(0, 0, appIconSize, appIconSize);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700495 icon.draw(c);
496
Michael Jurka05713af2013-01-23 12:39:24 +0100497 c.setBitmap(null);
Michael Jurka05713af2013-01-23 12:39:24 +0100498 return preview;
499 }
500
Adrian Roos65d60e22014-04-15 21:07:49 +0200501 private Drawable mutateOnMainThread(final Drawable drawable) {
502 try {
503 return mMainThreadExecutor.submit(new Callable<Drawable>() {
504 @Override
505 public Drawable call() throws Exception {
506 return drawable.mutate();
507 }
508 }).get();
509 } catch (InterruptedException e) {
510 Thread.currentThread().interrupt();
511 throw new RuntimeException(e);
512 } catch (ExecutionException e) {
513 throw new RuntimeException(e);
514 }
515 }
Adrian Roos1f375ab2014-04-28 18:26:38 +0200516
Adrian Roos1f375ab2014-04-28 18:26:38 +0200517 /**
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700518 * @return an array of containing versionCode and lastUpdatedTime for the package.
Adrian Roos1f375ab2014-04-28 18:26:38 +0200519 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700520 @Thunk long[] getPackageVersion(String packageName) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700521 synchronized (mPackageVersions) {
522 long[] versions = mPackageVersions.get(packageName);
523 if (versions == null) {
524 versions = new long[2];
Adrian Roos1f375ab2014-04-28 18:26:38 +0200525 try {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700526 PackageInfo info = mContext.getPackageManager().getPackageInfo(packageName, 0);
527 versions[0] = info.versionCode;
528 versions[1] = info.lastUpdateTime;
529 } catch (NameNotFoundException e) {
530 Log.e(TAG, "PackageInfo not found", e);
531 }
532 mPackageVersions.put(packageName, versions);
533 }
534 return versions;
535 }
536 }
537
538 /**
539 * A request Id which can be used by the client to cancel any request.
540 */
541 public class PreviewLoadRequest {
542
Sunny Goyalb4cbea42015-06-16 15:10:36 -0700543 @Thunk final PreviewLoadTask mTask;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700544
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700545 public PreviewLoadRequest(PreviewLoadTask task) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700546 mTask = task;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700547 }
548
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700549 public void cleanup() {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700550 if (mTask != null) {
551 mTask.cancel(true);
552 }
553
Winson Chung05304db2015-05-18 16:53:20 -0700554 // This only handles the case where the PreviewLoadTask is cancelled after the task has
555 // successfully completed (including having written to disk when necessary). In the
556 // other cases where it is cancelled while the task is running, it will be cleaned up
557 // in the tasks's onCancelled() call, and if cancelled while the task is writing to
558 // disk, it will be cancelled in the task's onPostExecute() call.
559 if (mTask.mBitmapToRecycle != null) {
Hyunyoung Songe98f4a42015-06-16 10:45:24 -0700560 mWorkerHandler.post(new Runnable() {
561 @Override
562 public void run() {
563 synchronized (mUnusedBitmaps) {
564 mUnusedBitmaps.add(mTask.mBitmapToRecycle);
565 }
566 mTask.mBitmapToRecycle = null;
567 }
568 });
Adrian Roos1f375ab2014-04-28 18:26:38 +0200569 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700570 }
571 }
572
573 public class PreviewLoadTask extends AsyncTask<Void, Void, Bitmap> {
Sunny Goyal316490e2015-06-02 09:38:28 -0700574 @Thunk final WidgetCacheKey mKey;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700575 private final Object mInfo;
576 private final int mPreviewHeight;
577 private final int mPreviewWidth;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700578 private final WidgetCell mCaller;
Sunny Goyal316490e2015-06-02 09:38:28 -0700579 @Thunk long[] mVersions;
580 @Thunk Bitmap mBitmapToRecycle;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700581
582 PreviewLoadTask(WidgetCacheKey key, Object info, int previewWidth,
Hyunyoung Song3f471442015-04-08 19:01:34 -0700583 int previewHeight, WidgetCell caller) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700584 mKey = key;
585 mInfo = info;
586 mPreviewHeight = previewHeight;
587 mPreviewWidth = previewWidth;
588 mCaller = caller;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700589 if (DEBUG) {
590 Log.d(TAG, String.format("%s, %s, %d, %d",
591 mKey, mInfo, mPreviewHeight, mPreviewWidth));
592 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700593 }
594
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700595 @Override
596 protected Bitmap doInBackground(Void... params) {
597 Bitmap unusedBitmap = null;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700598
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700599 // If already cancelled before this gets to run in the background, then return early
600 if (isCancelled()) {
601 return null;
602 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700603 synchronized (mUnusedBitmaps) {
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700604 // Check if we can re-use a bitmap
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700605 for (Bitmap candidate : mUnusedBitmaps) {
606 if (candidate != null && candidate.isMutable() &&
607 candidate.getWidth() == mPreviewWidth &&
608 candidate.getHeight() == mPreviewHeight) {
609 unusedBitmap = candidate;
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700610 mUnusedBitmaps.remove(unusedBitmap);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700611 break;
612 }
613 }
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700614 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700615
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700616 // creating a bitmap is expensive. Do not do this inside synchronized block.
617 if (unusedBitmap == null) {
618 unusedBitmap = Bitmap.createBitmap(mPreviewWidth, mPreviewHeight, Config.ARGB_8888);
Adrian Roos1f375ab2014-04-28 18:26:38 +0200619 }
Winson Chung05304db2015-05-18 16:53:20 -0700620 // If cancelled now, don't bother reading the preview from the DB
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700621 if (isCancelled()) {
Winson Chung05304db2015-05-18 16:53:20 -0700622 return unusedBitmap;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700623 }
Winson Chung05304db2015-05-18 16:53:20 -0700624 Bitmap preview = readFromDb(mKey, unusedBitmap, this);
625 // Only consider generating the preview if we have not cancelled the task already
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700626 if (!isCancelled() && preview == null) {
627 // Fetch the version info before we generate the preview, so that, in-case the
628 // app was updated while we are generating the preview, we use the old version info,
629 // which would gets re-written next time.
Winson Chung05304db2015-05-18 16:53:20 -0700630 mVersions = getPackageVersion(mKey.componentName.getPackageName());
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700631
Adam Cohen2e6da152015-05-06 11:42:25 -0700632 Launcher launcher = (Launcher) mCaller.getContext();
633
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700634 // it's not in the db... we need to generate it
Adam Cohen2e6da152015-05-06 11:42:25 -0700635 preview = generatePreview(launcher, mInfo, unusedBitmap, mPreviewWidth, mPreviewHeight);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700636 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700637 return preview;
638 }
639
640 @Override
Winson Chung05304db2015-05-18 16:53:20 -0700641 protected void onPostExecute(final Bitmap preview) {
642 mCaller.applyPreview(preview);
643
644 // Write the generated preview to the DB in the worker thread
645 if (mVersions != null) {
646 mWorkerHandler.post(new Runnable() {
647 @Override
648 public void run() {
649 if (!isCancelled()) {
650 // If we are still using this preview, then write it to the DB and then
651 // let the normal clear mechanism recycle the bitmap
652 writeToDb(mKey, mVersions, preview);
653 mBitmapToRecycle = preview;
654 } else {
655 // If we've already cancelled, then skip writing the bitmap to the DB
656 // and manually add the bitmap back to the recycled set
657 synchronized (mUnusedBitmaps) {
658 mUnusedBitmaps.add(preview);
659 }
660 }
661 }
662 });
663 } else {
664 // If we don't need to write to disk, then ensure the preview gets recycled by
665 // the normal clear mechanism
666 mBitmapToRecycle = preview;
667 }
668 }
669
670 @Override
Hyunyoung Songe98f4a42015-06-16 10:45:24 -0700671 protected void onCancelled(final Bitmap preview) {
Winson Chung05304db2015-05-18 16:53:20 -0700672 // If we've cancelled while the task is running, then can return the bitmap to the
673 // recycled set immediately. Otherwise, it will be recycled after the preview is written
674 // to disk.
675 if (preview != null) {
Hyunyoung Songe98f4a42015-06-16 10:45:24 -0700676 mWorkerHandler.post(new Runnable() {
677 @Override
678 public void run() {
679 synchronized (mUnusedBitmaps) {
680 mUnusedBitmaps.add(preview);
681 }
682 }
683 });
Winson Chung05304db2015-05-18 16:53:20 -0700684 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700685 }
686 }
687
688 private static final class WidgetCacheKey extends ComponentKey {
689
690 // TODO: remove dependency on size
Sunny Goyal316490e2015-06-02 09:38:28 -0700691 @Thunk final String size;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700692
693 public WidgetCacheKey(ComponentName componentName, UserHandleCompat user, String size) {
694 super(componentName, user);
695 this.size = size;
696 }
697
698 @Override
699 public int hashCode() {
700 return super.hashCode() ^ size.hashCode();
701 }
702
703 @Override
704 public boolean equals(Object o) {
705 return super.equals(o) && ((WidgetCacheKey) o).size.equals(size);
Adrian Roos1f375ab2014-04-28 18:26:38 +0200706 }
707 }
Michael Jurka05713af2013-01-23 12:39:24 +0100708}