blob: 46405ada75b0987bb403f3cea7de77cc94812b7d [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.
Hyunyoung Songe98f4a42015-06-16 10:45:24 -070058 * Note: synchronized block used for this variable is expensive and the block should always
59 * be posted to a background thread.
Hyunyoung Song559d90d2015-04-28 15:06:45 -070060 */
Sunny Goyal316490e2015-06-02 09:38:28 -070061 @Thunk Set<Bitmap> mUnusedBitmaps =
Hyunyoung Song559d90d2015-04-28 15:06:45 -070062 Collections.newSetFromMap(new WeakHashMap<Bitmap, Boolean>());
Sunny Goyal4cad7532015-03-18 15:56:30 -070063
64 private final Context mContext;
Sunny Goyalffe83f12014-08-14 17:39:34 -070065 private final IconCache mIconCache;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070066 private final UserManagerCompat mUserManager;
Sunny Goyalffe83f12014-08-14 17:39:34 -070067 private final AppWidgetManagerCompat mManager;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070068 private final CacheDb mDb;
Hyunyoung Song41e33692015-06-15 12:26:54 -070069 private final int mProfileBadgeMargin;
Michael Jurka05713af2013-01-23 12:39:24 +010070
Adrian Roos65d60e22014-04-15 21:07:49 +020071 private final MainThreadExecutor mMainThreadExecutor = new MainThreadExecutor();
Sunny Goyal316490e2015-06-02 09:38:28 -070072 @Thunk final Handler mWorkerHandler;
Adrian Roos65d60e22014-04-15 21:07:49 +020073
Adam Cohen2e6da152015-05-06 11:42:25 -070074 public WidgetPreviewLoader(Context context, InvariantDeviceProfile inv, IconCache iconCache) {
Chris Wrenfd13c712013-09-27 15:45:19 -040075 mContext = context;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070076 mIconCache = iconCache;
Sunny Goyalffe83f12014-08-14 17:39:34 -070077 mManager = AppWidgetManagerCompat.getInstance(context);
Sunny Goyal5b0e6692015-03-19 14:31:19 -070078 mUserManager = UserManagerCompat.getInstance(context);
79 mDb = new CacheDb(context);
Winson Chung05304db2015-05-18 16:53:20 -070080 mWorkerHandler = new Handler(LauncherModel.getWorkerLooper());
Hyunyoung Song41e33692015-06-15 12:26:54 -070081 mProfileBadgeMargin = context.getResources()
82 .getDimensionPixelSize(R.dimen.profile_badge_margin);
Michael Jurka3f4e0702013-02-05 11:21:28 +010083 }
Sunny Goyalffe83f12014-08-14 17:39:34 -070084
Sunny Goyal5b0e6692015-03-19 14:31:19 -070085 /**
86 * Generates the widget preview on {@link AsyncTask#THREAD_POOL_EXECUTOR}. Must be
87 * called on UI thread
88 *
89 * @param o either {@link LauncherAppWidgetProviderInfo} or {@link ResolveInfo}
Sunny Goyal5b0e6692015-03-19 14:31:19 -070090 * @return a request id which can be used to cancel the request.
91 */
Adam Cohen2e6da152015-05-06 11:42:25 -070092 public PreviewLoadRequest getPreview(final Object o, int previewWidth,
93 int previewHeight, WidgetCell caller) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -070094 String size = previewWidth + "x" + previewHeight;
95 WidgetCacheKey key = getObjectKey(o, size);
Michael Jurka3f4e0702013-02-05 11:21:28 +010096
Sunny Goyal5b0e6692015-03-19 14:31:19 -070097 PreviewLoadTask task = new PreviewLoadTask(key, o, previewWidth, previewHeight, caller);
98 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
Hyunyoung Song559d90d2015-04-28 15:06:45 -070099 return new PreviewLoadRequest(task);
Michael Jurka05713af2013-01-23 12:39:24 +0100100 }
101
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700102 /**
103 * The DB holds the generated previews for various components. Previews can also have different
104 * sizes (landscape vs portrait).
105 */
106 private static class CacheDb extends SQLiteOpenHelper {
107 private static final int DB_VERSION = 3;
108
109 private static final String TABLE_NAME = "shortcut_and_widget_previews";
110 private static final String COLUMN_COMPONENT = "componentName";
111 private static final String COLUMN_USER = "profileId";
112 private static final String COLUMN_SIZE = "size";
113 private static final String COLUMN_PACKAGE = "packageName";
114 private static final String COLUMN_LAST_UPDATED = "lastUpdated";
115 private static final String COLUMN_VERSION = "version";
116 private static final String COLUMN_PREVIEW_BITMAP = "preview_bitmap";
Michael Jurka05713af2013-01-23 12:39:24 +0100117
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100118 public CacheDb(Context context) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700119 super(context, LauncherFiles.WIDGET_PREVIEWS_DB, null, DB_VERSION);
Michael Jurka05713af2013-01-23 12:39:24 +0100120 }
121
122 @Override
123 public void onCreate(SQLiteDatabase database) {
Michael Jurka32b7a092013-02-07 20:06:49 +0100124 database.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" +
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700125 COLUMN_COMPONENT + " TEXT NOT NULL, " +
126 COLUMN_USER + " INTEGER NOT NULL, " +
Michael Jurka05713af2013-01-23 12:39:24 +0100127 COLUMN_SIZE + " TEXT NOT NULL, " +
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700128 COLUMN_PACKAGE + " TEXT NOT NULL, " +
129 COLUMN_LAST_UPDATED + " INTEGER NOT NULL DEFAULT 0, " +
130 COLUMN_VERSION + " INTEGER NOT NULL DEFAULT 0, " +
131 COLUMN_PREVIEW_BITMAP + " BLOB, " +
132 "PRIMARY KEY (" + COLUMN_COMPONENT + ", " + COLUMN_USER + ", " + COLUMN_SIZE + ") " +
Michael Jurka32b7a092013-02-07 20:06:49 +0100133 ");");
Michael Jurka05713af2013-01-23 12:39:24 +0100134 }
135
136 @Override
137 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Michael Jurkae5919c52013-03-06 17:30:10 +0100138 if (oldVersion != newVersion) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700139 clearDB(db);
Michael Jurkae5919c52013-03-06 17:30:10 +0100140 }
Michael Jurka05713af2013-01-23 12:39:24 +0100141 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700142
143 @Override
144 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
145 if (oldVersion != newVersion) {
146 clearDB(db);
147 }
148 }
149
150 private void clearDB(SQLiteDatabase db) {
151 db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
152 onCreate(db);
153 }
Michael Jurka05713af2013-01-23 12:39:24 +0100154 }
155
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700156 private WidgetCacheKey getObjectKey(Object o, String size) {
Michael Jurka05713af2013-01-23 12:39:24 +0100157 // should cache the string builder
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700158 if (o instanceof LauncherAppWidgetProviderInfo) {
159 LauncherAppWidgetProviderInfo info = (LauncherAppWidgetProviderInfo) o;
160 return new WidgetCacheKey(info.provider, mManager.getUser(info), size);
Michael Jurka05713af2013-01-23 12:39:24 +0100161 } else {
162 ResolveInfo info = (ResolveInfo) o;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700163 return new WidgetCacheKey(
164 new ComponentName(info.activityInfo.packageName, info.activityInfo.name),
165 UserHandleCompat.myUserHandle(), size);
Michael Jurka05713af2013-01-23 12:39:24 +0100166 }
167 }
168
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700169 @Thunk void writeToDb(WidgetCacheKey key, long[] versions, Bitmap preview) {
Michael Jurka05713af2013-01-23 12:39:24 +0100170 ContentValues values = new ContentValues();
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700171 values.put(CacheDb.COLUMN_COMPONENT, key.componentName.flattenToShortString());
172 values.put(CacheDb.COLUMN_USER, mUserManager.getSerialNumberForUser(key.user));
173 values.put(CacheDb.COLUMN_SIZE, key.size);
174 values.put(CacheDb.COLUMN_PACKAGE, key.componentName.getPackageName());
175 values.put(CacheDb.COLUMN_VERSION, versions[0]);
176 values.put(CacheDb.COLUMN_LAST_UPDATED, versions[1]);
177 values.put(CacheDb.COLUMN_PREVIEW_BITMAP, Utilities.flattenBitmap(preview));
Michael Jurka05713af2013-01-23 12:39:24 +0100178
Michael Jurka6e27f642013-12-10 13:40:30 +0100179 try {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700180 mDb.getWritableDatabase().insertWithOnConflict(CacheDb.TABLE_NAME, null, values,
181 SQLiteDatabase.CONFLICT_REPLACE);
182 } catch (SQLException e) {
183 Log.e(TAG, "Error saving image to DB", e);
Michael Jurka6e27f642013-12-10 13:40:30 +0100184 }
Michael Jurka05713af2013-01-23 12:39:24 +0100185 }
186
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700187 public void removePackage(String packageName, UserHandleCompat user) {
188 removePackage(packageName, user, mUserManager.getSerialNumberForUser(user));
189 }
190
191 private void removePackage(String packageName, UserHandleCompat user, long userSerial) {
192 synchronized(mPackageVersions) {
193 mPackageVersions.remove(packageName);
194 }
195
Michael Jurka6e27f642013-12-10 13:40:30 +0100196 try {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700197 mDb.getWritableDatabase().delete(CacheDb.TABLE_NAME,
198 CacheDb.COLUMN_PACKAGE + " = ? AND " + CacheDb.COLUMN_USER + " = ?",
199 new String[] {packageName, Long.toString(userSerial)});
200 } catch (SQLException e) {
201 Log.e(TAG, "Unable to delete items from DB", e);
Michael Jurka6e27f642013-12-10 13:40:30 +0100202 }
Michael Jurka8ff02ca2013-11-01 14:19:27 +0100203 }
204
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700205 /**
206 * Updates the persistent DB:
207 * 1. Any preview generated for an old package version is removed
208 * 2. Any preview for an absent package is removed
209 * This ensures that we remove entries for packages which changed while the launcher was dead.
210 */
Hyunyoung Song8821ca92015-05-04 16:28:20 -0700211 public void removeObsoletePreviews(ArrayList<Object> list) {
Hyunyoung Song2bd3d7d2015-05-21 13:04:53 -0700212 Utilities.assertWorkerThread();
Hyunyoung Song8821ca92015-05-04 16:28:20 -0700213
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700214 LongSparseArray<UserHandleCompat> userIdCache = new LongSparseArray<>();
215 LongSparseArray<HashSet<String>> validPackages = new LongSparseArray<>();
216
Hyunyoung Song8821ca92015-05-04 16:28:20 -0700217 for (Object obj : list) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700218 final UserHandleCompat user;
219 final String pkg;
220 if (obj instanceof ResolveInfo) {
221 user = UserHandleCompat.myUserHandle();
222 pkg = ((ResolveInfo) obj).activityInfo.packageName;
223 } else {
224 LauncherAppWidgetProviderInfo info = (LauncherAppWidgetProviderInfo) obj;
225 user = mManager.getUser(info);
226 pkg = info.provider.getPackageName();
227 }
228
229 int userIdIndex = userIdCache.indexOfValue(user);
230 final long userId;
231 if (userIdIndex < 0) {
232 userId = mUserManager.getSerialNumberForUser(user);
233 userIdCache.put(userId, user);
234 } else {
235 userId = userIdCache.keyAt(userIdIndex);
236 }
237
238 HashSet<String> packages = validPackages.get(userId);
239 if (packages == null) {
240 packages = new HashSet<>();
241 validPackages.put(userId, packages);
242 }
243 packages.add(pkg);
Michael Jurka05713af2013-01-23 12:39:24 +0100244 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700245
246 LongSparseArray<HashSet<String>> packagesToDelete = new LongSparseArray<>();
247 Cursor c = null;
248 try {
249 c = mDb.getReadableDatabase().query(CacheDb.TABLE_NAME,
250 new String[] {CacheDb.COLUMN_USER, CacheDb.COLUMN_PACKAGE,
251 CacheDb.COLUMN_LAST_UPDATED, CacheDb.COLUMN_VERSION},
252 null, null, null, null, null);
253 while (c.moveToNext()) {
254 long userId = c.getLong(0);
255 String pkg = c.getString(1);
256 long lastUpdated = c.getLong(2);
257 long version = c.getLong(3);
258
259 HashSet<String> packages = validPackages.get(userId);
260 if (packages != null && packages.contains(pkg)) {
261 long[] versions = getPackageVersion(pkg);
262 if (versions[0] == version && versions[1] == lastUpdated) {
263 // Every thing checks out
264 continue;
265 }
266 }
267
268 // We need to delete this package.
269 packages = packagesToDelete.get(userId);
270 if (packages == null) {
271 packages = new HashSet<>();
272 packagesToDelete.put(userId, packages);
273 }
274 packages.add(pkg);
275 }
276
277 for (int i = 0; i < packagesToDelete.size(); i++) {
278 long userId = packagesToDelete.keyAt(i);
279 UserHandleCompat user = mUserManager.getUserForSerialNumber(userId);
280 for (String pkg : packagesToDelete.valueAt(i)) {
281 removePackage(pkg, user, userId);
282 }
283 }
284 } catch (SQLException e) {
285 Log.e(TAG, "Error updatating widget previews", e);
286 } finally {
287 if (c != null) {
288 c.close();
289 }
290 }
291 }
292
Winson Chung05304db2015-05-18 16:53:20 -0700293 /**
294 * Reads the preview bitmap from the DB or null if the preview is not in the DB.
295 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700296 @Thunk Bitmap readFromDb(WidgetCacheKey key, Bitmap recycle, PreviewLoadTask loadTask) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700297 Cursor cursor = null;
298 try {
299 cursor = mDb.getReadableDatabase().query(
300 CacheDb.TABLE_NAME,
301 new String[] { CacheDb.COLUMN_PREVIEW_BITMAP },
302 CacheDb.COLUMN_COMPONENT + " = ? AND " + CacheDb.COLUMN_USER + " = ? AND " + CacheDb.COLUMN_SIZE + " = ?",
303 new String[] {
304 key.componentName.flattenToString(),
305 Long.toString(mUserManager.getSerialNumberForUser(key.user)),
306 key.size
307 },
308 null, null, null);
Winson Chung05304db2015-05-18 16:53:20 -0700309 // If cancelled, skip getting the blob and decoding it into a bitmap
310 if (loadTask.isCancelled()) {
311 return null;
312 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700313 if (cursor.moveToNext()) {
314 byte[] blob = cursor.getBlob(0);
315 BitmapFactory.Options opts = new BitmapFactory.Options();
316 opts.inBitmap = recycle;
Michael Jurka6e27f642013-12-10 13:40:30 +0100317 try {
Winson Chung05304db2015-05-18 16:53:20 -0700318 if (!loadTask.isCancelled()) {
319 return BitmapFactory.decodeByteArray(blob, 0, blob.length, opts);
320 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700321 } catch (Exception e) {
322 return null;
Michael Jurka6e27f642013-12-10 13:40:30 +0100323 }
Michael Jurka05713af2013-01-23 12:39:24 +0100324 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700325 } catch (SQLException e) {
326 Log.w(TAG, "Error loading preview from DB", e);
327 } finally {
328 if (cursor != null) {
329 cursor.close();
330 }
331 }
332 return null;
Michael Jurka05713af2013-01-23 12:39:24 +0100333 }
334
Sunny Goyal316490e2015-06-02 09:38:28 -0700335 @Thunk Bitmap generatePreview(Launcher launcher, Object info, Bitmap recycle,
Adam Cohen2e6da152015-05-06 11:42:25 -0700336 int previewWidth, int previewHeight) {
Adam Cohen59400422014-03-05 18:07:04 -0800337 if (info instanceof LauncherAppWidgetProviderInfo) {
Adam Cohen2e6da152015-05-06 11:42:25 -0700338 return generateWidgetPreview(launcher, (LauncherAppWidgetProviderInfo) info,
339 previewWidth, recycle, null);
Michael Jurka05713af2013-01-23 12:39:24 +0100340 } else {
Adam Cohen2e6da152015-05-06 11:42:25 -0700341 return generateShortcutPreview(launcher,
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700342 (ResolveInfo) info, previewWidth, previewHeight, recycle);
Michael Jurka05713af2013-01-23 12:39:24 +0100343 }
344 }
345
Adam Cohen2e6da152015-05-06 11:42:25 -0700346 public Bitmap generateWidgetPreview(Launcher launcher, LauncherAppWidgetProviderInfo info,
Sunny Goyal4cad7532015-03-18 15:56:30 -0700347 int maxPreviewWidth, Bitmap preview, int[] preScaledWidthOut) {
Michael Jurka05713af2013-01-23 12:39:24 +0100348 // Load the preview image if possible
Michael Jurka05713af2013-01-23 12:39:24 +0100349 if (maxPreviewWidth < 0) maxPreviewWidth = Integer.MAX_VALUE;
Michael Jurka05713af2013-01-23 12:39:24 +0100350
351 Drawable drawable = null;
Sunny Goyalffe83f12014-08-14 17:39:34 -0700352 if (info.previewImage != 0) {
353 drawable = mManager.loadPreview(info);
Adrian Roosfa9ffc22014-05-12 15:59:59 +0200354 if (drawable != null) {
355 drawable = mutateOnMainThread(drawable);
356 } else {
Michael Jurka05713af2013-01-23 12:39:24 +0100357 Log.w(TAG, "Can't load widget preview drawable 0x" +
Sunny Goyalffe83f12014-08-14 17:39:34 -0700358 Integer.toHexString(info.previewImage) + " for provider: " + info.provider);
Michael Jurka05713af2013-01-23 12:39:24 +0100359 }
360 }
361
Sunny Goyal4cad7532015-03-18 15:56:30 -0700362 final boolean widgetPreviewExists = (drawable != null);
Adam Cohen2e6da152015-05-06 11:42:25 -0700363 final int spanX = info.getSpanX(launcher) < 1 ? 1 : info.getSpanX(launcher);
364 final int spanY = info.getSpanY(launcher) < 1 ? 1 : info.getSpanY(launcher);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700365
Michael Jurka05713af2013-01-23 12:39:24 +0100366 int previewWidth;
367 int previewHeight;
Sunny Goyal4cad7532015-03-18 15:56:30 -0700368 Bitmap tileBitmap = null;
369
Michael Jurka05713af2013-01-23 12:39:24 +0100370 if (widgetPreviewExists) {
371 previewWidth = drawable.getIntrinsicWidth();
372 previewHeight = drawable.getIntrinsicHeight();
373 } else {
374 // Generate a preview image if we couldn't load one
Sunny Goyal4cad7532015-03-18 15:56:30 -0700375 tileBitmap = ((BitmapDrawable) mContext.getResources().getDrawable(
376 R.drawable.widget_tile)).getBitmap();
377 previewWidth = tileBitmap.getWidth() * spanX;
378 previewHeight = tileBitmap.getHeight() * spanY;
Michael Jurka05713af2013-01-23 12:39:24 +0100379 }
380
381 // Scale to fit width only - let the widget preview be clipped in the
382 // vertical dimension
383 float scale = 1f;
384 if (preScaledWidthOut != null) {
385 preScaledWidthOut[0] = previewWidth;
386 }
387 if (previewWidth > maxPreviewWidth) {
388 scale = maxPreviewWidth / (float) previewWidth;
389 }
390 if (scale != 1f) {
391 previewWidth = (int) (scale * previewWidth);
392 previewHeight = (int) (scale * previewHeight);
393 }
394
395 // 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 -0700396 final Canvas c = new Canvas();
Michael Jurka05713af2013-01-23 12:39:24 +0100397 if (preview == null) {
398 preview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700399 c.setBitmap(preview);
400 } else {
401 // Reusing bitmap. Clear it.
402 c.setBitmap(preview);
403 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100404 }
405
406 // Draw the scaled preview into the final bitmap
Hyunyoung Song41e33692015-06-15 12:26:54 -0700407 int x = (preview.getWidth() - previewWidth - mProfileBadgeMargin) / 2;
Michael Jurka05713af2013-01-23 12:39:24 +0100408 if (widgetPreviewExists) {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700409 drawable.setBounds(x, 0, x + previewWidth, previewHeight);
410 drawable.draw(c);
Michael Jurka05713af2013-01-23 12:39:24 +0100411 } else {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700412 final Paint p = new Paint();
413 p.setFilterBitmap(true);
Adam Cohen2e6da152015-05-06 11:42:25 -0700414 int appIconSize = launcher.getDeviceProfile().iconSizePx;
Michael Jurka05713af2013-01-23 12:39:24 +0100415
Sunny Goyal4cad7532015-03-18 15:56:30 -0700416 // draw the spanX x spanY tiles
417 final Rect src = new Rect(0, 0, tileBitmap.getWidth(), tileBitmap.getHeight());
418
419 float tileW = scale * tileBitmap.getWidth();
420 float tileH = scale * tileBitmap.getHeight();
421 final RectF dst = new RectF(0, 0, tileW, tileH);
422
423 float tx = x;
424 for (int i = 0; i < spanX; i++, tx += tileW) {
425 float ty = 0;
426 for (int j = 0; j < spanY; j++, ty += tileH) {
427 dst.offsetTo(tx, ty);
428 c.drawBitmap(tileBitmap, src, dst, p);
429 }
Michael Jurka05713af2013-01-23 12:39:24 +0100430 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700431
432 // Draw the icon in the top left corner
433 // TODO: use top right for RTL
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700434 int minOffset = (int) (appIconSize * WIDGET_PREVIEW_ICON_PADDING_PERCENTAGE);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700435 int smallestSide = Math.min(previewWidth, previewHeight);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700436 float iconScale = Math.min((float) smallestSide / (appIconSize + 2 * minOffset), scale);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700437
438 try {
439 Drawable icon = mutateOnMainThread(mManager.loadIcon(info, mIconCache));
440 if (icon != null) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700441 int hoffset = (int) ((tileW - appIconSize * iconScale) / 2) + x;
442 int yoffset = (int) ((tileH - appIconSize * iconScale) / 2);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700443 icon.setBounds(hoffset, yoffset,
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700444 hoffset + (int) (appIconSize * iconScale),
445 yoffset + (int) (appIconSize * iconScale));
Sunny Goyal4cad7532015-03-18 15:56:30 -0700446 icon.draw(c);
447 }
448 } catch (Resources.NotFoundException e) { }
Michael Jurka05713af2013-01-23 12:39:24 +0100449 c.setBitmap(null);
450 }
Hyunyoung Song41e33692015-06-15 12:26:54 -0700451 int imageHeight = Math.min(preview.getHeight(), previewHeight + mProfileBadgeMargin);
452 return mManager.getBadgeBitmap(info, preview, imageHeight);
Michael Jurka05713af2013-01-23 12:39:24 +0100453 }
454
455 private Bitmap generateShortcutPreview(
Adam Cohen2e6da152015-05-06 11:42:25 -0700456 Launcher launcher, ResolveInfo info, int maxWidth, int maxHeight, Bitmap preview) {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700457 final Canvas c = new Canvas();
458 if (preview == null) {
Michael Jurka05713af2013-01-23 12:39:24 +0100459 preview = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700460 c.setBitmap(preview);
461 } else if (preview.getWidth() != maxWidth || preview.getHeight() != maxHeight) {
462 throw new RuntimeException("Improperly sized bitmap passed as argument");
463 } else {
464 // Reusing bitmap. Clear it.
465 c.setBitmap(preview);
466 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100467 }
468
Sunny Goyal4cad7532015-03-18 15:56:30 -0700469 Drawable icon = mutateOnMainThread(mIconCache.getFullResIcon(info.activityInfo));
470 icon.setFilterBitmap(true);
471
Michael Jurka05713af2013-01-23 12:39:24 +0100472 // Draw a desaturated/scaled version of the icon in the background as a watermark
Sunny Goyal4cad7532015-03-18 15:56:30 -0700473 ColorMatrix colorMatrix = new ColorMatrix();
474 colorMatrix.setSaturation(0);
475 icon.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
476 icon.setAlpha((int) (255 * 0.06f));
477
478 Resources res = mContext.getResources();
479 int paddingTop = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_top);
480 int paddingLeft = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_left);
481 int paddingRight = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_right);
482 int scaledIconWidth = (maxWidth - paddingLeft - paddingRight);
483 icon.setBounds(paddingLeft, paddingTop,
484 paddingLeft + scaledIconWidth, paddingTop + scaledIconWidth);
485 icon.draw(c);
486
487 // Draw the final icon at top left corner.
488 // TODO: use top right for RTL
Adam Cohen2e6da152015-05-06 11:42:25 -0700489 int appIconSize = launcher.getDeviceProfile().iconSizePx;
490
Sunny Goyal4cad7532015-03-18 15:56:30 -0700491 icon.setAlpha(255);
492 icon.setColorFilter(null);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700493 icon.setBounds(0, 0, appIconSize, appIconSize);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700494 icon.draw(c);
495
Michael Jurka05713af2013-01-23 12:39:24 +0100496 c.setBitmap(null);
Michael Jurka05713af2013-01-23 12:39:24 +0100497 return preview;
498 }
499
Adrian Roos65d60e22014-04-15 21:07:49 +0200500 private Drawable mutateOnMainThread(final Drawable drawable) {
501 try {
502 return mMainThreadExecutor.submit(new Callable<Drawable>() {
503 @Override
504 public Drawable call() throws Exception {
505 return drawable.mutate();
506 }
507 }).get();
508 } catch (InterruptedException e) {
509 Thread.currentThread().interrupt();
510 throw new RuntimeException(e);
511 } catch (ExecutionException e) {
512 throw new RuntimeException(e);
513 }
514 }
Adrian Roos1f375ab2014-04-28 18:26:38 +0200515
Adrian Roos1f375ab2014-04-28 18:26:38 +0200516 /**
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700517 * @return an array of containing versionCode and lastUpdatedTime for the package.
Adrian Roos1f375ab2014-04-28 18:26:38 +0200518 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700519 @Thunk long[] getPackageVersion(String packageName) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700520 synchronized (mPackageVersions) {
521 long[] versions = mPackageVersions.get(packageName);
522 if (versions == null) {
523 versions = new long[2];
Adrian Roos1f375ab2014-04-28 18:26:38 +0200524 try {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700525 PackageInfo info = mContext.getPackageManager().getPackageInfo(packageName, 0);
526 versions[0] = info.versionCode;
527 versions[1] = info.lastUpdateTime;
528 } catch (NameNotFoundException e) {
529 Log.e(TAG, "PackageInfo not found", e);
530 }
531 mPackageVersions.put(packageName, versions);
532 }
533 return versions;
534 }
535 }
536
537 /**
538 * A request Id which can be used by the client to cancel any request.
539 */
540 public class PreviewLoadRequest {
541
542 private final PreviewLoadTask mTask;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700543
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700544 public PreviewLoadRequest(PreviewLoadTask task) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700545 mTask = task;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700546 }
547
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700548 public void cleanup() {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700549 if (mTask != null) {
550 mTask.cancel(true);
551 }
552
Winson Chung05304db2015-05-18 16:53:20 -0700553 // This only handles the case where the PreviewLoadTask is cancelled after the task has
554 // successfully completed (including having written to disk when necessary). In the
555 // other cases where it is cancelled while the task is running, it will be cleaned up
556 // in the tasks's onCancelled() call, and if cancelled while the task is writing to
557 // disk, it will be cancelled in the task's onPostExecute() call.
558 if (mTask.mBitmapToRecycle != null) {
Hyunyoung Songe98f4a42015-06-16 10:45:24 -0700559 mWorkerHandler.post(new Runnable() {
560 @Override
561 public void run() {
562 synchronized (mUnusedBitmaps) {
563 mUnusedBitmaps.add(mTask.mBitmapToRecycle);
564 }
565 mTask.mBitmapToRecycle = null;
566 }
567 });
Adrian Roos1f375ab2014-04-28 18:26:38 +0200568 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700569 }
570 }
571
572 public class PreviewLoadTask extends AsyncTask<Void, Void, Bitmap> {
Sunny Goyal316490e2015-06-02 09:38:28 -0700573 @Thunk final WidgetCacheKey mKey;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700574 private final Object mInfo;
575 private final int mPreviewHeight;
576 private final int mPreviewWidth;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700577 private final WidgetCell mCaller;
Sunny Goyal316490e2015-06-02 09:38:28 -0700578 @Thunk long[] mVersions;
579 @Thunk Bitmap mBitmapToRecycle;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700580
581 PreviewLoadTask(WidgetCacheKey key, Object info, int previewWidth,
Hyunyoung Song3f471442015-04-08 19:01:34 -0700582 int previewHeight, WidgetCell caller) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700583 mKey = key;
584 mInfo = info;
585 mPreviewHeight = previewHeight;
586 mPreviewWidth = previewWidth;
587 mCaller = caller;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700588 if (DEBUG) {
589 Log.d(TAG, String.format("%s, %s, %d, %d",
590 mKey, mInfo, mPreviewHeight, mPreviewWidth));
591 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700592 }
593
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700594 @Override
595 protected Bitmap doInBackground(Void... params) {
596 Bitmap unusedBitmap = null;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700597
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700598 // If already cancelled before this gets to run in the background, then return early
599 if (isCancelled()) {
600 return null;
601 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700602 synchronized (mUnusedBitmaps) {
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700603 // Check if we can re-use a bitmap
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700604 for (Bitmap candidate : mUnusedBitmaps) {
605 if (candidate != null && candidate.isMutable() &&
606 candidate.getWidth() == mPreviewWidth &&
607 candidate.getHeight() == mPreviewHeight) {
608 unusedBitmap = candidate;
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700609 mUnusedBitmaps.remove(unusedBitmap);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700610 break;
611 }
612 }
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700613 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700614
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700615 // creating a bitmap is expensive. Do not do this inside synchronized block.
616 if (unusedBitmap == null) {
617 unusedBitmap = Bitmap.createBitmap(mPreviewWidth, mPreviewHeight, Config.ARGB_8888);
Adrian Roos1f375ab2014-04-28 18:26:38 +0200618 }
Winson Chung05304db2015-05-18 16:53:20 -0700619 // If cancelled now, don't bother reading the preview from the DB
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700620 if (isCancelled()) {
Winson Chung05304db2015-05-18 16:53:20 -0700621 return unusedBitmap;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700622 }
Winson Chung05304db2015-05-18 16:53:20 -0700623 Bitmap preview = readFromDb(mKey, unusedBitmap, this);
624 // Only consider generating the preview if we have not cancelled the task already
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700625 if (!isCancelled() && preview == null) {
626 // Fetch the version info before we generate the preview, so that, in-case the
627 // app was updated while we are generating the preview, we use the old version info,
628 // which would gets re-written next time.
Winson Chung05304db2015-05-18 16:53:20 -0700629 mVersions = getPackageVersion(mKey.componentName.getPackageName());
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700630
Adam Cohen2e6da152015-05-06 11:42:25 -0700631 Launcher launcher = (Launcher) mCaller.getContext();
632
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700633 // it's not in the db... we need to generate it
Adam Cohen2e6da152015-05-06 11:42:25 -0700634 preview = generatePreview(launcher, mInfo, unusedBitmap, mPreviewWidth, mPreviewHeight);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700635 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700636 return preview;
637 }
638
639 @Override
Winson Chung05304db2015-05-18 16:53:20 -0700640 protected void onPostExecute(final Bitmap preview) {
641 mCaller.applyPreview(preview);
642
643 // Write the generated preview to the DB in the worker thread
644 if (mVersions != null) {
645 mWorkerHandler.post(new Runnable() {
646 @Override
647 public void run() {
648 if (!isCancelled()) {
649 // If we are still using this preview, then write it to the DB and then
650 // let the normal clear mechanism recycle the bitmap
651 writeToDb(mKey, mVersions, preview);
652 mBitmapToRecycle = preview;
653 } else {
654 // If we've already cancelled, then skip writing the bitmap to the DB
655 // and manually add the bitmap back to the recycled set
656 synchronized (mUnusedBitmaps) {
657 mUnusedBitmaps.add(preview);
658 }
659 }
660 }
661 });
662 } else {
663 // If we don't need to write to disk, then ensure the preview gets recycled by
664 // the normal clear mechanism
665 mBitmapToRecycle = preview;
666 }
667 }
668
669 @Override
Hyunyoung Songe98f4a42015-06-16 10:45:24 -0700670 protected void onCancelled(final Bitmap preview) {
Winson Chung05304db2015-05-18 16:53:20 -0700671 // If we've cancelled while the task is running, then can return the bitmap to the
672 // recycled set immediately. Otherwise, it will be recycled after the preview is written
673 // to disk.
674 if (preview != null) {
Hyunyoung Songe98f4a42015-06-16 10:45:24 -0700675 mWorkerHandler.post(new Runnable() {
676 @Override
677 public void run() {
678 synchronized (mUnusedBitmaps) {
679 mUnusedBitmaps.add(preview);
680 }
681 }
682 });
Winson Chung05304db2015-05-18 16:53:20 -0700683 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700684 }
685 }
686
687 private static final class WidgetCacheKey extends ComponentKey {
688
689 // TODO: remove dependency on size
Sunny Goyal316490e2015-06-02 09:38:28 -0700690 @Thunk final String size;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700691
692 public WidgetCacheKey(ComponentName componentName, UserHandleCompat user, String size) {
693 super(componentName, user);
694 this.size = size;
695 }
696
697 @Override
698 public int hashCode() {
699 return super.hashCode() ^ size.hashCode();
700 }
701
702 @Override
703 public boolean equals(Object o) {
704 return super.equals(o) && ((WidgetCacheKey) o).size.equals(size);
Adrian Roos1f375ab2014-04-28 18:26:38 +0200705 }
706 }
Michael Jurka05713af2013-01-23 12:39:24 +0100707}