blob: e13d44c9b9ff037d8cb038255491f6f3f457c897 [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;
Sunny Goyal7ca99112015-09-23 10:16:38 -070046import java.util.concurrent.Executor;
47import java.util.concurrent.LinkedBlockingQueue;
48import java.util.concurrent.ThreadPoolExecutor;
49import java.util.concurrent.TimeUnit;
Michael Jurka05713af2013-01-23 12:39:24 +010050
Sunny Goyalffe83f12014-08-14 17:39:34 -070051public class WidgetPreviewLoader {
Michael Jurka05713af2013-01-23 12:39:24 +010052
Sunny Goyalffe83f12014-08-14 17:39:34 -070053 private static final String TAG = "WidgetPreviewLoader";
Hyunyoung Song3f471442015-04-08 19:01:34 -070054 private static final boolean DEBUG = false;
Sunny Goyalffe83f12014-08-14 17:39:34 -070055
Sunny Goyal7ca99112015-09-23 10:16:38 -070056 // These values are same as that in {@link AsyncTask}.
57 private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
58 private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
59 private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
60 private static final int KEEP_ALIVE = 1;
61 private static final Executor PREVIEW_LOAD_EXECUTOR = new ThreadPoolExecutor(
62 CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
63 TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
64
Sunny Goyalffe83f12014-08-14 17:39:34 -070065 private static final float WIDGET_PREVIEW_ICON_PADDING_PERCENTAGE = 0.25f;
Sunny Goyalffe83f12014-08-14 17:39:34 -070066
Sunny Goyal5b0e6692015-03-19 14:31:19 -070067 private final HashMap<String, long[]> mPackageVersions = new HashMap<>();
Hyunyoung Song559d90d2015-04-28 15:06:45 -070068
69 /**
70 * Weak reference objects, do not prevent their referents from being made finalizable,
71 * finalized, and then reclaimed.
Hyunyoung Songe98f4a42015-06-16 10:45:24 -070072 * Note: synchronized block used for this variable is expensive and the block should always
73 * be posted to a background thread.
Hyunyoung Song559d90d2015-04-28 15:06:45 -070074 */
Sunny Goyalb4cbea42015-06-16 15:10:36 -070075 @Thunk final Set<Bitmap> mUnusedBitmaps =
Hyunyoung Song559d90d2015-04-28 15:06:45 -070076 Collections.newSetFromMap(new WeakHashMap<Bitmap, Boolean>());
Sunny Goyal4cad7532015-03-18 15:56:30 -070077
78 private final Context mContext;
Sunny Goyalffe83f12014-08-14 17:39:34 -070079 private final IconCache mIconCache;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070080 private final UserManagerCompat mUserManager;
Sunny Goyalffe83f12014-08-14 17:39:34 -070081 private final AppWidgetManagerCompat mManager;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070082 private final CacheDb mDb;
Hyunyoung Song41e33692015-06-15 12:26:54 -070083 private final int mProfileBadgeMargin;
Michael Jurka05713af2013-01-23 12:39:24 +010084
Adrian Roos65d60e22014-04-15 21:07:49 +020085 private final MainThreadExecutor mMainThreadExecutor = new MainThreadExecutor();
Sunny Goyal316490e2015-06-02 09:38:28 -070086 @Thunk final Handler mWorkerHandler;
Adrian Roos65d60e22014-04-15 21:07:49 +020087
Sunny Goyal383c5072015-06-12 21:18:53 -070088 public WidgetPreviewLoader(Context context, IconCache iconCache) {
Chris Wrenfd13c712013-09-27 15:45:19 -040089 mContext = context;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070090 mIconCache = iconCache;
Sunny Goyalffe83f12014-08-14 17:39:34 -070091 mManager = AppWidgetManagerCompat.getInstance(context);
Sunny Goyal5b0e6692015-03-19 14:31:19 -070092 mUserManager = UserManagerCompat.getInstance(context);
93 mDb = new CacheDb(context);
Winson Chung05304db2015-05-18 16:53:20 -070094 mWorkerHandler = new Handler(LauncherModel.getWorkerLooper());
Hyunyoung Song41e33692015-06-15 12:26:54 -070095 mProfileBadgeMargin = context.getResources()
96 .getDimensionPixelSize(R.dimen.profile_badge_margin);
Michael Jurka3f4e0702013-02-05 11:21:28 +010097 }
Sunny Goyalffe83f12014-08-14 17:39:34 -070098
Sunny Goyal5b0e6692015-03-19 14:31:19 -070099 /**
100 * Generates the widget preview on {@link AsyncTask#THREAD_POOL_EXECUTOR}. Must be
101 * called on UI thread
102 *
103 * @param o either {@link LauncherAppWidgetProviderInfo} or {@link ResolveInfo}
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700104 * @return a request id which can be used to cancel the request.
105 */
Adam Cohen2e6da152015-05-06 11:42:25 -0700106 public PreviewLoadRequest getPreview(final Object o, int previewWidth,
107 int previewHeight, WidgetCell caller) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700108 String size = previewWidth + "x" + previewHeight;
109 WidgetCacheKey key = getObjectKey(o, size);
Michael Jurka3f4e0702013-02-05 11:21:28 +0100110
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700111 PreviewLoadTask task = new PreviewLoadTask(key, o, previewWidth, previewHeight, caller);
Sunny Goyal7ca99112015-09-23 10:16:38 -0700112 task.executeOnExecutor(PREVIEW_LOAD_EXECUTOR);
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700113 return new PreviewLoadRequest(task);
Michael Jurka05713af2013-01-23 12:39:24 +0100114 }
115
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700116 /**
117 * The DB holds the generated previews for various components. Previews can also have different
118 * sizes (landscape vs portrait).
119 */
120 private static class CacheDb extends SQLiteOpenHelper {
Sunny Goyal2d648b02015-08-11 13:56:28 -0700121 private static final int DB_VERSION = 4;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700122
123 private static final String TABLE_NAME = "shortcut_and_widget_previews";
124 private static final String COLUMN_COMPONENT = "componentName";
125 private static final String COLUMN_USER = "profileId";
126 private static final String COLUMN_SIZE = "size";
127 private static final String COLUMN_PACKAGE = "packageName";
128 private static final String COLUMN_LAST_UPDATED = "lastUpdated";
129 private static final String COLUMN_VERSION = "version";
130 private static final String COLUMN_PREVIEW_BITMAP = "preview_bitmap";
Michael Jurka05713af2013-01-23 12:39:24 +0100131
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100132 public CacheDb(Context context) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700133 super(context, LauncherFiles.WIDGET_PREVIEWS_DB, null, DB_VERSION);
Michael Jurka05713af2013-01-23 12:39:24 +0100134 }
135
136 @Override
137 public void onCreate(SQLiteDatabase database) {
Michael Jurka32b7a092013-02-07 20:06:49 +0100138 database.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" +
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700139 COLUMN_COMPONENT + " TEXT NOT NULL, " +
140 COLUMN_USER + " INTEGER NOT NULL, " +
Michael Jurka05713af2013-01-23 12:39:24 +0100141 COLUMN_SIZE + " TEXT NOT NULL, " +
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700142 COLUMN_PACKAGE + " TEXT NOT NULL, " +
143 COLUMN_LAST_UPDATED + " INTEGER NOT NULL DEFAULT 0, " +
144 COLUMN_VERSION + " INTEGER NOT NULL DEFAULT 0, " +
145 COLUMN_PREVIEW_BITMAP + " BLOB, " +
146 "PRIMARY KEY (" + COLUMN_COMPONENT + ", " + COLUMN_USER + ", " + COLUMN_SIZE + ") " +
Michael Jurka32b7a092013-02-07 20:06:49 +0100147 ");");
Michael Jurka05713af2013-01-23 12:39:24 +0100148 }
149
150 @Override
151 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Michael Jurkae5919c52013-03-06 17:30:10 +0100152 if (oldVersion != newVersion) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700153 clearDB(db);
Michael Jurkae5919c52013-03-06 17:30:10 +0100154 }
Michael Jurka05713af2013-01-23 12:39:24 +0100155 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700156
157 @Override
158 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
159 if (oldVersion != newVersion) {
160 clearDB(db);
161 }
162 }
163
164 private void clearDB(SQLiteDatabase db) {
165 db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
166 onCreate(db);
167 }
Michael Jurka05713af2013-01-23 12:39:24 +0100168 }
169
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700170 private WidgetCacheKey getObjectKey(Object o, String size) {
Michael Jurka05713af2013-01-23 12:39:24 +0100171 // should cache the string builder
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700172 if (o instanceof LauncherAppWidgetProviderInfo) {
173 LauncherAppWidgetProviderInfo info = (LauncherAppWidgetProviderInfo) o;
174 return new WidgetCacheKey(info.provider, mManager.getUser(info), size);
Michael Jurka05713af2013-01-23 12:39:24 +0100175 } else {
176 ResolveInfo info = (ResolveInfo) o;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700177 return new WidgetCacheKey(
178 new ComponentName(info.activityInfo.packageName, info.activityInfo.name),
179 UserHandleCompat.myUserHandle(), size);
Michael Jurka05713af2013-01-23 12:39:24 +0100180 }
181 }
182
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700183 @Thunk void writeToDb(WidgetCacheKey key, long[] versions, Bitmap preview) {
Michael Jurka05713af2013-01-23 12:39:24 +0100184 ContentValues values = new ContentValues();
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700185 values.put(CacheDb.COLUMN_COMPONENT, key.componentName.flattenToShortString());
186 values.put(CacheDb.COLUMN_USER, mUserManager.getSerialNumberForUser(key.user));
187 values.put(CacheDb.COLUMN_SIZE, key.size);
188 values.put(CacheDb.COLUMN_PACKAGE, key.componentName.getPackageName());
189 values.put(CacheDb.COLUMN_VERSION, versions[0]);
190 values.put(CacheDb.COLUMN_LAST_UPDATED, versions[1]);
191 values.put(CacheDb.COLUMN_PREVIEW_BITMAP, Utilities.flattenBitmap(preview));
Michael Jurka05713af2013-01-23 12:39:24 +0100192
Michael Jurka6e27f642013-12-10 13:40:30 +0100193 try {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700194 mDb.getWritableDatabase().insertWithOnConflict(CacheDb.TABLE_NAME, null, values,
195 SQLiteDatabase.CONFLICT_REPLACE);
196 } catch (SQLException e) {
197 Log.e(TAG, "Error saving image to DB", e);
Michael Jurka6e27f642013-12-10 13:40:30 +0100198 }
Michael Jurka05713af2013-01-23 12:39:24 +0100199 }
200
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700201 public void removePackage(String packageName, UserHandleCompat user) {
202 removePackage(packageName, user, mUserManager.getSerialNumberForUser(user));
203 }
204
205 private void removePackage(String packageName, UserHandleCompat user, long userSerial) {
206 synchronized(mPackageVersions) {
207 mPackageVersions.remove(packageName);
208 }
209
Michael Jurka6e27f642013-12-10 13:40:30 +0100210 try {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700211 mDb.getWritableDatabase().delete(CacheDb.TABLE_NAME,
212 CacheDb.COLUMN_PACKAGE + " = ? AND " + CacheDb.COLUMN_USER + " = ?",
213 new String[] {packageName, Long.toString(userSerial)});
214 } catch (SQLException e) {
215 Log.e(TAG, "Unable to delete items from DB", e);
Michael Jurka6e27f642013-12-10 13:40:30 +0100216 }
Michael Jurka8ff02ca2013-11-01 14:19:27 +0100217 }
218
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700219 /**
220 * Updates the persistent DB:
221 * 1. Any preview generated for an old package version is removed
222 * 2. Any preview for an absent package is removed
223 * This ensures that we remove entries for packages which changed while the launcher was dead.
224 */
Hyunyoung Song8821ca92015-05-04 16:28:20 -0700225 public void removeObsoletePreviews(ArrayList<Object> list) {
Hyunyoung Song2bd3d7d2015-05-21 13:04:53 -0700226 Utilities.assertWorkerThread();
Hyunyoung Song8821ca92015-05-04 16:28:20 -0700227
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700228 LongSparseArray<HashSet<String>> validPackages = new LongSparseArray<>();
229
Hyunyoung Song8821ca92015-05-04 16:28:20 -0700230 for (Object obj : list) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700231 final UserHandleCompat user;
232 final String pkg;
233 if (obj instanceof ResolveInfo) {
234 user = UserHandleCompat.myUserHandle();
235 pkg = ((ResolveInfo) obj).activityInfo.packageName;
236 } else {
237 LauncherAppWidgetProviderInfo info = (LauncherAppWidgetProviderInfo) obj;
238 user = mManager.getUser(info);
239 pkg = info.provider.getPackageName();
240 }
241
Sunny Goyala2a039b2015-08-05 13:22:21 -0700242 final long userId = mUserManager.getSerialNumberForUser(user);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700243 HashSet<String> packages = validPackages.get(userId);
244 if (packages == null) {
245 packages = new HashSet<>();
246 validPackages.put(userId, packages);
247 }
248 packages.add(pkg);
Michael Jurka05713af2013-01-23 12:39:24 +0100249 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700250
251 LongSparseArray<HashSet<String>> packagesToDelete = new LongSparseArray<>();
252 Cursor c = null;
253 try {
254 c = mDb.getReadableDatabase().query(CacheDb.TABLE_NAME,
255 new String[] {CacheDb.COLUMN_USER, CacheDb.COLUMN_PACKAGE,
256 CacheDb.COLUMN_LAST_UPDATED, CacheDb.COLUMN_VERSION},
257 null, null, null, null, null);
258 while (c.moveToNext()) {
259 long userId = c.getLong(0);
260 String pkg = c.getString(1);
261 long lastUpdated = c.getLong(2);
262 long version = c.getLong(3);
263
264 HashSet<String> packages = validPackages.get(userId);
265 if (packages != null && packages.contains(pkg)) {
266 long[] versions = getPackageVersion(pkg);
267 if (versions[0] == version && versions[1] == lastUpdated) {
268 // Every thing checks out
269 continue;
270 }
271 }
272
273 // We need to delete this package.
274 packages = packagesToDelete.get(userId);
275 if (packages == null) {
276 packages = new HashSet<>();
277 packagesToDelete.put(userId, packages);
278 }
279 packages.add(pkg);
280 }
281
282 for (int i = 0; i < packagesToDelete.size(); i++) {
283 long userId = packagesToDelete.keyAt(i);
284 UserHandleCompat user = mUserManager.getUserForSerialNumber(userId);
285 for (String pkg : packagesToDelete.valueAt(i)) {
286 removePackage(pkg, user, userId);
287 }
288 }
289 } catch (SQLException e) {
290 Log.e(TAG, "Error updatating widget previews", e);
291 } finally {
292 if (c != null) {
293 c.close();
294 }
295 }
296 }
297
Winson Chung05304db2015-05-18 16:53:20 -0700298 /**
299 * Reads the preview bitmap from the DB or null if the preview is not in the DB.
300 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700301 @Thunk Bitmap readFromDb(WidgetCacheKey key, Bitmap recycle, PreviewLoadTask loadTask) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700302 Cursor cursor = null;
303 try {
304 cursor = mDb.getReadableDatabase().query(
305 CacheDb.TABLE_NAME,
306 new String[] { CacheDb.COLUMN_PREVIEW_BITMAP },
307 CacheDb.COLUMN_COMPONENT + " = ? AND " + CacheDb.COLUMN_USER + " = ? AND " + CacheDb.COLUMN_SIZE + " = ?",
308 new String[] {
309 key.componentName.flattenToString(),
310 Long.toString(mUserManager.getSerialNumberForUser(key.user)),
311 key.size
312 },
313 null, null, null);
Winson Chung05304db2015-05-18 16:53:20 -0700314 // If cancelled, skip getting the blob and decoding it into a bitmap
315 if (loadTask.isCancelled()) {
316 return null;
317 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700318 if (cursor.moveToNext()) {
319 byte[] blob = cursor.getBlob(0);
320 BitmapFactory.Options opts = new BitmapFactory.Options();
321 opts.inBitmap = recycle;
Michael Jurka6e27f642013-12-10 13:40:30 +0100322 try {
Winson Chung05304db2015-05-18 16:53:20 -0700323 if (!loadTask.isCancelled()) {
324 return BitmapFactory.decodeByteArray(blob, 0, blob.length, opts);
325 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700326 } catch (Exception e) {
327 return null;
Michael Jurka6e27f642013-12-10 13:40:30 +0100328 }
Michael Jurka05713af2013-01-23 12:39:24 +0100329 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700330 } catch (SQLException e) {
331 Log.w(TAG, "Error loading preview from DB", e);
332 } finally {
333 if (cursor != null) {
334 cursor.close();
335 }
336 }
337 return null;
Michael Jurka05713af2013-01-23 12:39:24 +0100338 }
339
Sunny Goyal316490e2015-06-02 09:38:28 -0700340 @Thunk Bitmap generatePreview(Launcher launcher, Object info, Bitmap recycle,
Adam Cohen2e6da152015-05-06 11:42:25 -0700341 int previewWidth, int previewHeight) {
Adam Cohen59400422014-03-05 18:07:04 -0800342 if (info instanceof LauncherAppWidgetProviderInfo) {
Adam Cohen2e6da152015-05-06 11:42:25 -0700343 return generateWidgetPreview(launcher, (LauncherAppWidgetProviderInfo) info,
344 previewWidth, recycle, null);
Michael Jurka05713af2013-01-23 12:39:24 +0100345 } else {
Adam Cohen2e6da152015-05-06 11:42:25 -0700346 return generateShortcutPreview(launcher,
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700347 (ResolveInfo) info, previewWidth, previewHeight, recycle);
Michael Jurka05713af2013-01-23 12:39:24 +0100348 }
349 }
350
Adam Cohen2e6da152015-05-06 11:42:25 -0700351 public Bitmap generateWidgetPreview(Launcher launcher, LauncherAppWidgetProviderInfo info,
Sunny Goyal4cad7532015-03-18 15:56:30 -0700352 int maxPreviewWidth, Bitmap preview, int[] preScaledWidthOut) {
Michael Jurka05713af2013-01-23 12:39:24 +0100353 // Load the preview image if possible
Michael Jurka05713af2013-01-23 12:39:24 +0100354 if (maxPreviewWidth < 0) maxPreviewWidth = Integer.MAX_VALUE;
Michael Jurka05713af2013-01-23 12:39:24 +0100355
356 Drawable drawable = null;
Sunny Goyalffe83f12014-08-14 17:39:34 -0700357 if (info.previewImage != 0) {
358 drawable = mManager.loadPreview(info);
Adrian Roosfa9ffc22014-05-12 15:59:59 +0200359 if (drawable != null) {
360 drawable = mutateOnMainThread(drawable);
361 } else {
Michael Jurka05713af2013-01-23 12:39:24 +0100362 Log.w(TAG, "Can't load widget preview drawable 0x" +
Sunny Goyalffe83f12014-08-14 17:39:34 -0700363 Integer.toHexString(info.previewImage) + " for provider: " + info.provider);
Michael Jurka05713af2013-01-23 12:39:24 +0100364 }
365 }
366
Sunny Goyal4cad7532015-03-18 15:56:30 -0700367 final boolean widgetPreviewExists = (drawable != null);
Sunny Goyal233ee962015-08-03 13:05:01 -0700368 final int spanX = info.spanX;
369 final int spanY = info.spanY;
Sunny Goyal4cad7532015-03-18 15:56:30 -0700370
Michael Jurka05713af2013-01-23 12:39:24 +0100371 int previewWidth;
372 int previewHeight;
Sunny Goyal4cad7532015-03-18 15:56:30 -0700373 Bitmap tileBitmap = null;
374
Michael Jurka05713af2013-01-23 12:39:24 +0100375 if (widgetPreviewExists) {
376 previewWidth = drawable.getIntrinsicWidth();
377 previewHeight = drawable.getIntrinsicHeight();
378 } else {
379 // Generate a preview image if we couldn't load one
Sunny Goyal4cad7532015-03-18 15:56:30 -0700380 tileBitmap = ((BitmapDrawable) mContext.getResources().getDrawable(
381 R.drawable.widget_tile)).getBitmap();
382 previewWidth = tileBitmap.getWidth() * spanX;
383 previewHeight = tileBitmap.getHeight() * spanY;
Michael Jurka05713af2013-01-23 12:39:24 +0100384 }
385
386 // Scale to fit width only - let the widget preview be clipped in the
387 // vertical dimension
388 float scale = 1f;
389 if (preScaledWidthOut != null) {
390 preScaledWidthOut[0] = previewWidth;
391 }
392 if (previewWidth > maxPreviewWidth) {
Hyunyoung Songb9f932e2015-07-30 15:04:59 -0700393 scale = (maxPreviewWidth - 2 * mProfileBadgeMargin) / (float) (previewWidth);
Michael Jurka05713af2013-01-23 12:39:24 +0100394 }
395 if (scale != 1f) {
396 previewWidth = (int) (scale * previewWidth);
397 previewHeight = (int) (scale * previewHeight);
398 }
399
400 // 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 -0700401 final Canvas c = new Canvas();
Michael Jurka05713af2013-01-23 12:39:24 +0100402 if (preview == null) {
403 preview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700404 c.setBitmap(preview);
405 } else {
406 // Reusing bitmap. Clear it.
407 c.setBitmap(preview);
408 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100409 }
410
411 // Draw the scaled preview into the final bitmap
Hyunyoung Songb9f932e2015-07-30 15:04:59 -0700412 int x = (preview.getWidth() - previewWidth) / 2;
Michael Jurka05713af2013-01-23 12:39:24 +0100413 if (widgetPreviewExists) {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700414 drawable.setBounds(x, 0, x + previewWidth, previewHeight);
415 drawable.draw(c);
Michael Jurka05713af2013-01-23 12:39:24 +0100416 } else {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700417 final Paint p = new Paint();
418 p.setFilterBitmap(true);
Adam Cohen2e6da152015-05-06 11:42:25 -0700419 int appIconSize = launcher.getDeviceProfile().iconSizePx;
Michael Jurka05713af2013-01-23 12:39:24 +0100420
Sunny Goyal4cad7532015-03-18 15:56:30 -0700421 // draw the spanX x spanY tiles
422 final Rect src = new Rect(0, 0, tileBitmap.getWidth(), tileBitmap.getHeight());
423
424 float tileW = scale * tileBitmap.getWidth();
425 float tileH = scale * tileBitmap.getHeight();
426 final RectF dst = new RectF(0, 0, tileW, tileH);
427
428 float tx = x;
429 for (int i = 0; i < spanX; i++, tx += tileW) {
430 float ty = 0;
431 for (int j = 0; j < spanY; j++, ty += tileH) {
432 dst.offsetTo(tx, ty);
433 c.drawBitmap(tileBitmap, src, dst, p);
434 }
Michael Jurka05713af2013-01-23 12:39:24 +0100435 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700436
437 // Draw the icon in the top left corner
438 // TODO: use top right for RTL
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700439 int minOffset = (int) (appIconSize * WIDGET_PREVIEW_ICON_PADDING_PERCENTAGE);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700440 int smallestSide = Math.min(previewWidth, previewHeight);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700441 float iconScale = Math.min((float) smallestSide / (appIconSize + 2 * minOffset), scale);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700442
443 try {
444 Drawable icon = mutateOnMainThread(mManager.loadIcon(info, mIconCache));
445 if (icon != null) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700446 int hoffset = (int) ((tileW - appIconSize * iconScale) / 2) + x;
447 int yoffset = (int) ((tileH - appIconSize * iconScale) / 2);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700448 icon.setBounds(hoffset, yoffset,
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700449 hoffset + (int) (appIconSize * iconScale),
450 yoffset + (int) (appIconSize * iconScale));
Sunny Goyal4cad7532015-03-18 15:56:30 -0700451 icon.draw(c);
452 }
453 } catch (Resources.NotFoundException e) { }
Michael Jurka05713af2013-01-23 12:39:24 +0100454 c.setBitmap(null);
455 }
Hyunyoung Song41e33692015-06-15 12:26:54 -0700456 int imageHeight = Math.min(preview.getHeight(), previewHeight + mProfileBadgeMargin);
457 return mManager.getBadgeBitmap(info, preview, imageHeight);
Michael Jurka05713af2013-01-23 12:39:24 +0100458 }
459
460 private Bitmap generateShortcutPreview(
Adam Cohen2e6da152015-05-06 11:42:25 -0700461 Launcher launcher, ResolveInfo info, int maxWidth, int maxHeight, Bitmap preview) {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700462 final Canvas c = new Canvas();
463 if (preview == null) {
Michael Jurka05713af2013-01-23 12:39:24 +0100464 preview = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700465 c.setBitmap(preview);
466 } else if (preview.getWidth() != maxWidth || preview.getHeight() != maxHeight) {
467 throw new RuntimeException("Improperly sized bitmap passed as argument");
468 } else {
469 // Reusing bitmap. Clear it.
470 c.setBitmap(preview);
471 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100472 }
473
Sunny Goyal4cad7532015-03-18 15:56:30 -0700474 Drawable icon = mutateOnMainThread(mIconCache.getFullResIcon(info.activityInfo));
475 icon.setFilterBitmap(true);
476
Michael Jurka05713af2013-01-23 12:39:24 +0100477 // Draw a desaturated/scaled version of the icon in the background as a watermark
Sunny Goyal4cad7532015-03-18 15:56:30 -0700478 ColorMatrix colorMatrix = new ColorMatrix();
479 colorMatrix.setSaturation(0);
480 icon.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
481 icon.setAlpha((int) (255 * 0.06f));
482
483 Resources res = mContext.getResources();
484 int paddingTop = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_top);
485 int paddingLeft = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_left);
486 int paddingRight = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_right);
487 int scaledIconWidth = (maxWidth - paddingLeft - paddingRight);
488 icon.setBounds(paddingLeft, paddingTop,
489 paddingLeft + scaledIconWidth, paddingTop + scaledIconWidth);
490 icon.draw(c);
491
492 // Draw the final icon at top left corner.
493 // TODO: use top right for RTL
Adam Cohen2e6da152015-05-06 11:42:25 -0700494 int appIconSize = launcher.getDeviceProfile().iconSizePx;
495
Sunny Goyal4cad7532015-03-18 15:56:30 -0700496 icon.setAlpha(255);
497 icon.setColorFilter(null);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700498 icon.setBounds(0, 0, appIconSize, appIconSize);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700499 icon.draw(c);
500
Michael Jurka05713af2013-01-23 12:39:24 +0100501 c.setBitmap(null);
Michael Jurka05713af2013-01-23 12:39:24 +0100502 return preview;
503 }
504
Adrian Roos65d60e22014-04-15 21:07:49 +0200505 private Drawable mutateOnMainThread(final Drawable drawable) {
506 try {
507 return mMainThreadExecutor.submit(new Callable<Drawable>() {
508 @Override
509 public Drawable call() throws Exception {
510 return drawable.mutate();
511 }
512 }).get();
513 } catch (InterruptedException e) {
514 Thread.currentThread().interrupt();
515 throw new RuntimeException(e);
516 } catch (ExecutionException e) {
517 throw new RuntimeException(e);
518 }
519 }
Adrian Roos1f375ab2014-04-28 18:26:38 +0200520
Adrian Roos1f375ab2014-04-28 18:26:38 +0200521 /**
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700522 * @return an array of containing versionCode and lastUpdatedTime for the package.
Adrian Roos1f375ab2014-04-28 18:26:38 +0200523 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700524 @Thunk long[] getPackageVersion(String packageName) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700525 synchronized (mPackageVersions) {
526 long[] versions = mPackageVersions.get(packageName);
527 if (versions == null) {
528 versions = new long[2];
Adrian Roos1f375ab2014-04-28 18:26:38 +0200529 try {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700530 PackageInfo info = mContext.getPackageManager().getPackageInfo(packageName, 0);
531 versions[0] = info.versionCode;
532 versions[1] = info.lastUpdateTime;
533 } catch (NameNotFoundException e) {
534 Log.e(TAG, "PackageInfo not found", e);
535 }
536 mPackageVersions.put(packageName, versions);
537 }
538 return versions;
539 }
540 }
541
542 /**
543 * A request Id which can be used by the client to cancel any request.
544 */
545 public class PreviewLoadRequest {
546
Sunny Goyalb4cbea42015-06-16 15:10:36 -0700547 @Thunk final PreviewLoadTask mTask;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700548
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700549 public PreviewLoadRequest(PreviewLoadTask task) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700550 mTask = task;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700551 }
552
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700553 public void cleanup() {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700554 if (mTask != null) {
555 mTask.cancel(true);
556 }
557
Winson Chung05304db2015-05-18 16:53:20 -0700558 // This only handles the case where the PreviewLoadTask is cancelled after the task has
559 // successfully completed (including having written to disk when necessary). In the
560 // other cases where it is cancelled while the task is running, it will be cleaned up
561 // in the tasks's onCancelled() call, and if cancelled while the task is writing to
562 // disk, it will be cancelled in the task's onPostExecute() call.
563 if (mTask.mBitmapToRecycle != null) {
Hyunyoung Songe98f4a42015-06-16 10:45:24 -0700564 mWorkerHandler.post(new Runnable() {
565 @Override
566 public void run() {
567 synchronized (mUnusedBitmaps) {
568 mUnusedBitmaps.add(mTask.mBitmapToRecycle);
569 }
570 mTask.mBitmapToRecycle = null;
571 }
572 });
Adrian Roos1f375ab2014-04-28 18:26:38 +0200573 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700574 }
575 }
576
577 public class PreviewLoadTask extends AsyncTask<Void, Void, Bitmap> {
Sunny Goyal316490e2015-06-02 09:38:28 -0700578 @Thunk final WidgetCacheKey mKey;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700579 private final Object mInfo;
580 private final int mPreviewHeight;
581 private final int mPreviewWidth;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700582 private final WidgetCell mCaller;
Sunny Goyal316490e2015-06-02 09:38:28 -0700583 @Thunk long[] mVersions;
584 @Thunk Bitmap mBitmapToRecycle;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700585
586 PreviewLoadTask(WidgetCacheKey key, Object info, int previewWidth,
Hyunyoung Song3f471442015-04-08 19:01:34 -0700587 int previewHeight, WidgetCell caller) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700588 mKey = key;
589 mInfo = info;
590 mPreviewHeight = previewHeight;
591 mPreviewWidth = previewWidth;
592 mCaller = caller;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700593 if (DEBUG) {
594 Log.d(TAG, String.format("%s, %s, %d, %d",
595 mKey, mInfo, mPreviewHeight, mPreviewWidth));
596 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700597 }
598
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700599 @Override
600 protected Bitmap doInBackground(Void... params) {
601 Bitmap unusedBitmap = null;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700602
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700603 // If already cancelled before this gets to run in the background, then return early
604 if (isCancelled()) {
605 return null;
606 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700607 synchronized (mUnusedBitmaps) {
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700608 // Check if we can re-use a bitmap
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700609 for (Bitmap candidate : mUnusedBitmaps) {
610 if (candidate != null && candidate.isMutable() &&
611 candidate.getWidth() == mPreviewWidth &&
612 candidate.getHeight() == mPreviewHeight) {
613 unusedBitmap = candidate;
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700614 mUnusedBitmaps.remove(unusedBitmap);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700615 break;
616 }
617 }
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700618 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700619
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700620 // creating a bitmap is expensive. Do not do this inside synchronized block.
621 if (unusedBitmap == null) {
622 unusedBitmap = Bitmap.createBitmap(mPreviewWidth, mPreviewHeight, Config.ARGB_8888);
Adrian Roos1f375ab2014-04-28 18:26:38 +0200623 }
Winson Chung05304db2015-05-18 16:53:20 -0700624 // If cancelled now, don't bother reading the preview from the DB
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700625 if (isCancelled()) {
Winson Chung05304db2015-05-18 16:53:20 -0700626 return unusedBitmap;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700627 }
Winson Chung05304db2015-05-18 16:53:20 -0700628 Bitmap preview = readFromDb(mKey, unusedBitmap, this);
629 // Only consider generating the preview if we have not cancelled the task already
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700630 if (!isCancelled() && preview == null) {
631 // Fetch the version info before we generate the preview, so that, in-case the
632 // app was updated while we are generating the preview, we use the old version info,
633 // which would gets re-written next time.
Winson Chung05304db2015-05-18 16:53:20 -0700634 mVersions = getPackageVersion(mKey.componentName.getPackageName());
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700635
Adam Cohen2e6da152015-05-06 11:42:25 -0700636 Launcher launcher = (Launcher) mCaller.getContext();
637
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700638 // it's not in the db... we need to generate it
Adam Cohen2e6da152015-05-06 11:42:25 -0700639 preview = generatePreview(launcher, mInfo, unusedBitmap, mPreviewWidth, mPreviewHeight);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700640 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700641 return preview;
642 }
643
644 @Override
Winson Chung05304db2015-05-18 16:53:20 -0700645 protected void onPostExecute(final Bitmap preview) {
646 mCaller.applyPreview(preview);
647
648 // Write the generated preview to the DB in the worker thread
649 if (mVersions != null) {
650 mWorkerHandler.post(new Runnable() {
651 @Override
652 public void run() {
653 if (!isCancelled()) {
654 // If we are still using this preview, then write it to the DB and then
655 // let the normal clear mechanism recycle the bitmap
656 writeToDb(mKey, mVersions, preview);
657 mBitmapToRecycle = preview;
658 } else {
659 // If we've already cancelled, then skip writing the bitmap to the DB
660 // and manually add the bitmap back to the recycled set
661 synchronized (mUnusedBitmaps) {
662 mUnusedBitmaps.add(preview);
663 }
664 }
665 }
666 });
667 } else {
668 // If we don't need to write to disk, then ensure the preview gets recycled by
669 // the normal clear mechanism
670 mBitmapToRecycle = preview;
671 }
672 }
673
674 @Override
Hyunyoung Songe98f4a42015-06-16 10:45:24 -0700675 protected void onCancelled(final Bitmap preview) {
Winson Chung05304db2015-05-18 16:53:20 -0700676 // If we've cancelled while the task is running, then can return the bitmap to the
677 // recycled set immediately. Otherwise, it will be recycled after the preview is written
678 // to disk.
679 if (preview != null) {
Hyunyoung Songe98f4a42015-06-16 10:45:24 -0700680 mWorkerHandler.post(new Runnable() {
681 @Override
682 public void run() {
683 synchronized (mUnusedBitmaps) {
684 mUnusedBitmaps.add(preview);
685 }
686 }
687 });
Winson Chung05304db2015-05-18 16:53:20 -0700688 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700689 }
690 }
691
692 private static final class WidgetCacheKey extends ComponentKey {
693
694 // TODO: remove dependency on size
Sunny Goyal316490e2015-06-02 09:38:28 -0700695 @Thunk final String size;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700696
697 public WidgetCacheKey(ComponentName componentName, UserHandleCompat user, String size) {
698 super(componentName, user);
699 this.size = size;
700 }
701
702 @Override
703 public int hashCode() {
704 return super.hashCode() ^ size.hashCode();
705 }
706
707 @Override
708 public boolean equals(Object o) {
709 return super.equals(o) && ((WidgetCacheKey) o).size.equals(size);
Adrian Roos1f375ab2014-04-28 18:26:38 +0200710 }
711 }
Michael Jurka05713af2013-01-23 12:39:24 +0100712}