blob: bbcdaae3972d1e216956c586049afeaf6b575dbe [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;
Hyunyoung Song8821ca92015-05-04 16:28:20 -070028import android.os.Process;
Michael Jurka05713af2013-01-23 12:39:24 +010029import android.util.Log;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070030import android.util.LongSparseArray;
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 -070037import junit.framework.Assert;
38
39import java.util.ArrayList;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070040import java.util.Collections;
Michael Jurka05713af2013-01-23 12:39:24 +010041import java.util.HashMap;
42import java.util.HashSet;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070043import java.util.Set;
44import java.util.WeakHashMap;
Adrian Roos65d60e22014-04-15 21:07:49 +020045import java.util.concurrent.Callable;
46import java.util.concurrent.ExecutionException;
Michael Jurka05713af2013-01-23 12:39:24 +010047
Sunny Goyalffe83f12014-08-14 17:39:34 -070048public class WidgetPreviewLoader {
Michael Jurka05713af2013-01-23 12:39:24 +010049
Sunny Goyalffe83f12014-08-14 17:39:34 -070050 private static final String TAG = "WidgetPreviewLoader";
Hyunyoung Song3f471442015-04-08 19:01:34 -070051 private static final boolean DEBUG = false;
Sunny Goyalffe83f12014-08-14 17:39:34 -070052
53 private static final float WIDGET_PREVIEW_ICON_PADDING_PERCENTAGE = 0.25f;
Sunny Goyalffe83f12014-08-14 17:39:34 -070054
Sunny Goyal5b0e6692015-03-19 14:31:19 -070055 private final HashMap<String, long[]> mPackageVersions = new HashMap<>();
Hyunyoung Song559d90d2015-04-28 15:06:45 -070056
57 /**
58 * Weak reference objects, do not prevent their referents from being made finalizable,
59 * finalized, and then reclaimed.
60 */
61 private Set<Bitmap> mUnusedBitmaps =
62 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;
Michael Jurka05713af2013-01-23 12:39:24 +010069
Adrian Roos65d60e22014-04-15 21:07:49 +020070 private final MainThreadExecutor mMainThreadExecutor = new MainThreadExecutor();
Winson Chung05304db2015-05-18 16:53:20 -070071 private final Handler mWorkerHandler;
Adrian Roos65d60e22014-04-15 21:07:49 +020072
Sunny Goyal5b0e6692015-03-19 14:31:19 -070073 public WidgetPreviewLoader(Context context, IconCache iconCache) {
Chris Wrenfd13c712013-09-27 15:45:19 -040074 mContext = context;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070075 mIconCache = iconCache;
Sunny Goyalffe83f12014-08-14 17:39:34 -070076 mManager = AppWidgetManagerCompat.getInstance(context);
Sunny Goyal5b0e6692015-03-19 14:31:19 -070077 mUserManager = UserManagerCompat.getInstance(context);
78 mDb = new CacheDb(context);
Winson Chung05304db2015-05-18 16:53:20 -070079 mWorkerHandler = new Handler(LauncherModel.getWorkerLooper());
Michael Jurka3f4e0702013-02-05 11:21:28 +010080 }
Sunny Goyalffe83f12014-08-14 17:39:34 -070081
Sunny Goyal5b0e6692015-03-19 14:31:19 -070082 /**
83 * Generates the widget preview on {@link AsyncTask#THREAD_POOL_EXECUTOR}. Must be
84 * called on UI thread
85 *
86 * @param o either {@link LauncherAppWidgetProviderInfo} or {@link ResolveInfo}
Sunny Goyal5b0e6692015-03-19 14:31:19 -070087 * @return a request id which can be used to cancel the request.
88 */
89 public PreviewLoadRequest getPreview(final Object o, int previewWidth, int previewHeight,
Winson Chung78b19662015-05-15 14:12:04 -070090 WidgetCell caller) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -070091 String size = previewWidth + "x" + previewHeight;
92 WidgetCacheKey key = getObjectKey(o, size);
Michael Jurka3f4e0702013-02-05 11:21:28 +010093
Sunny Goyal5b0e6692015-03-19 14:31:19 -070094 PreviewLoadTask task = new PreviewLoadTask(key, o, previewWidth, previewHeight, caller);
95 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
Hyunyoung Song559d90d2015-04-28 15:06:45 -070096 return new PreviewLoadRequest(task);
Michael Jurka05713af2013-01-23 12:39:24 +010097 }
98
Sunny Goyal5b0e6692015-03-19 14:31:19 -070099 /**
100 * The DB holds the generated previews for various components. Previews can also have different
101 * sizes (landscape vs portrait).
102 */
103 private static class CacheDb extends SQLiteOpenHelper {
104 private static final int DB_VERSION = 3;
105
106 private static final String TABLE_NAME = "shortcut_and_widget_previews";
107 private static final String COLUMN_COMPONENT = "componentName";
108 private static final String COLUMN_USER = "profileId";
109 private static final String COLUMN_SIZE = "size";
110 private static final String COLUMN_PACKAGE = "packageName";
111 private static final String COLUMN_LAST_UPDATED = "lastUpdated";
112 private static final String COLUMN_VERSION = "version";
113 private static final String COLUMN_PREVIEW_BITMAP = "preview_bitmap";
Michael Jurka05713af2013-01-23 12:39:24 +0100114
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100115 public CacheDb(Context context) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700116 super(context, LauncherFiles.WIDGET_PREVIEWS_DB, null, DB_VERSION);
Michael Jurka05713af2013-01-23 12:39:24 +0100117 }
118
119 @Override
120 public void onCreate(SQLiteDatabase database) {
Michael Jurka32b7a092013-02-07 20:06:49 +0100121 database.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" +
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700122 COLUMN_COMPONENT + " TEXT NOT NULL, " +
123 COLUMN_USER + " INTEGER NOT NULL, " +
Michael Jurka05713af2013-01-23 12:39:24 +0100124 COLUMN_SIZE + " TEXT NOT NULL, " +
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700125 COLUMN_PACKAGE + " TEXT NOT NULL, " +
126 COLUMN_LAST_UPDATED + " INTEGER NOT NULL DEFAULT 0, " +
127 COLUMN_VERSION + " INTEGER NOT NULL DEFAULT 0, " +
128 COLUMN_PREVIEW_BITMAP + " BLOB, " +
129 "PRIMARY KEY (" + COLUMN_COMPONENT + ", " + COLUMN_USER + ", " + COLUMN_SIZE + ") " +
Michael Jurka32b7a092013-02-07 20:06:49 +0100130 ");");
Michael Jurka05713af2013-01-23 12:39:24 +0100131 }
132
133 @Override
134 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Michael Jurkae5919c52013-03-06 17:30:10 +0100135 if (oldVersion != newVersion) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700136 clearDB(db);
Michael Jurkae5919c52013-03-06 17:30:10 +0100137 }
Michael Jurka05713af2013-01-23 12:39:24 +0100138 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700139
140 @Override
141 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
142 if (oldVersion != newVersion) {
143 clearDB(db);
144 }
145 }
146
147 private void clearDB(SQLiteDatabase db) {
148 db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
149 onCreate(db);
150 }
Michael Jurka05713af2013-01-23 12:39:24 +0100151 }
152
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700153 private WidgetCacheKey getObjectKey(Object o, String size) {
Michael Jurka05713af2013-01-23 12:39:24 +0100154 // should cache the string builder
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700155 if (o instanceof LauncherAppWidgetProviderInfo) {
156 LauncherAppWidgetProviderInfo info = (LauncherAppWidgetProviderInfo) o;
157 return new WidgetCacheKey(info.provider, mManager.getUser(info), size);
Michael Jurka05713af2013-01-23 12:39:24 +0100158 } else {
159 ResolveInfo info = (ResolveInfo) o;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700160 return new WidgetCacheKey(
161 new ComponentName(info.activityInfo.packageName, info.activityInfo.name),
162 UserHandleCompat.myUserHandle(), size);
Michael Jurka05713af2013-01-23 12:39:24 +0100163 }
164 }
165
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700166 @Thunk void writeToDb(WidgetCacheKey key, long[] versions, Bitmap preview) {
Michael Jurka05713af2013-01-23 12:39:24 +0100167 ContentValues values = new ContentValues();
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700168 values.put(CacheDb.COLUMN_COMPONENT, key.componentName.flattenToShortString());
169 values.put(CacheDb.COLUMN_USER, mUserManager.getSerialNumberForUser(key.user));
170 values.put(CacheDb.COLUMN_SIZE, key.size);
171 values.put(CacheDb.COLUMN_PACKAGE, key.componentName.getPackageName());
172 values.put(CacheDb.COLUMN_VERSION, versions[0]);
173 values.put(CacheDb.COLUMN_LAST_UPDATED, versions[1]);
174 values.put(CacheDb.COLUMN_PREVIEW_BITMAP, Utilities.flattenBitmap(preview));
Michael Jurka05713af2013-01-23 12:39:24 +0100175
Michael Jurka6e27f642013-12-10 13:40:30 +0100176 try {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700177 mDb.getWritableDatabase().insertWithOnConflict(CacheDb.TABLE_NAME, null, values,
178 SQLiteDatabase.CONFLICT_REPLACE);
179 } catch (SQLException e) {
180 Log.e(TAG, "Error saving image to DB", e);
Michael Jurka6e27f642013-12-10 13:40:30 +0100181 }
Michael Jurka05713af2013-01-23 12:39:24 +0100182 }
183
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700184 public void removePackage(String packageName, UserHandleCompat user) {
185 removePackage(packageName, user, mUserManager.getSerialNumberForUser(user));
186 }
187
188 private void removePackage(String packageName, UserHandleCompat user, long userSerial) {
189 synchronized(mPackageVersions) {
190 mPackageVersions.remove(packageName);
191 }
192
Michael Jurka6e27f642013-12-10 13:40:30 +0100193 try {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700194 mDb.getWritableDatabase().delete(CacheDb.TABLE_NAME,
195 CacheDb.COLUMN_PACKAGE + " = ? AND " + CacheDb.COLUMN_USER + " = ?",
196 new String[] {packageName, Long.toString(userSerial)});
197 } catch (SQLException e) {
198 Log.e(TAG, "Unable to delete items from DB", e);
Michael Jurka6e27f642013-12-10 13:40:30 +0100199 }
Michael Jurka8ff02ca2013-11-01 14:19:27 +0100200 }
201
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700202 /**
203 * Updates the persistent DB:
204 * 1. Any preview generated for an old package version is removed
205 * 2. Any preview for an absent package is removed
206 * This ensures that we remove entries for packages which changed while the launcher was dead.
207 */
Hyunyoung Song8821ca92015-05-04 16:28:20 -0700208 public void removeObsoletePreviews(ArrayList<Object> list) {
209 // This method should always be called from the worker thread.
210 Assert.assertTrue(LauncherModel.sWorkerThread.getThreadId() == Process.myTid());
211
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700212 LongSparseArray<UserHandleCompat> userIdCache = new LongSparseArray<>();
213 LongSparseArray<HashSet<String>> validPackages = new LongSparseArray<>();
214
Hyunyoung Song8821ca92015-05-04 16:28:20 -0700215 for (Object obj : list) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700216 final UserHandleCompat user;
217 final String pkg;
218 if (obj instanceof ResolveInfo) {
219 user = UserHandleCompat.myUserHandle();
220 pkg = ((ResolveInfo) obj).activityInfo.packageName;
221 } else {
222 LauncherAppWidgetProviderInfo info = (LauncherAppWidgetProviderInfo) obj;
223 user = mManager.getUser(info);
224 pkg = info.provider.getPackageName();
225 }
226
227 int userIdIndex = userIdCache.indexOfValue(user);
228 final long userId;
229 if (userIdIndex < 0) {
230 userId = mUserManager.getSerialNumberForUser(user);
231 userIdCache.put(userId, user);
232 } else {
233 userId = userIdCache.keyAt(userIdIndex);
234 }
235
236 HashSet<String> packages = validPackages.get(userId);
237 if (packages == null) {
238 packages = new HashSet<>();
239 validPackages.put(userId, packages);
240 }
241 packages.add(pkg);
Michael Jurka05713af2013-01-23 12:39:24 +0100242 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700243
244 LongSparseArray<HashSet<String>> packagesToDelete = new LongSparseArray<>();
245 Cursor c = null;
246 try {
247 c = mDb.getReadableDatabase().query(CacheDb.TABLE_NAME,
248 new String[] {CacheDb.COLUMN_USER, CacheDb.COLUMN_PACKAGE,
249 CacheDb.COLUMN_LAST_UPDATED, CacheDb.COLUMN_VERSION},
250 null, null, null, null, null);
251 while (c.moveToNext()) {
252 long userId = c.getLong(0);
253 String pkg = c.getString(1);
254 long lastUpdated = c.getLong(2);
255 long version = c.getLong(3);
256
257 HashSet<String> packages = validPackages.get(userId);
258 if (packages != null && packages.contains(pkg)) {
259 long[] versions = getPackageVersion(pkg);
260 if (versions[0] == version && versions[1] == lastUpdated) {
261 // Every thing checks out
262 continue;
263 }
264 }
265
266 // We need to delete this package.
267 packages = packagesToDelete.get(userId);
268 if (packages == null) {
269 packages = new HashSet<>();
270 packagesToDelete.put(userId, packages);
271 }
272 packages.add(pkg);
273 }
274
275 for (int i = 0; i < packagesToDelete.size(); i++) {
276 long userId = packagesToDelete.keyAt(i);
277 UserHandleCompat user = mUserManager.getUserForSerialNumber(userId);
278 for (String pkg : packagesToDelete.valueAt(i)) {
279 removePackage(pkg, user, userId);
280 }
281 }
282 } catch (SQLException e) {
283 Log.e(TAG, "Error updatating widget previews", e);
284 } finally {
285 if (c != null) {
286 c.close();
287 }
288 }
289 }
290
Winson Chung05304db2015-05-18 16:53:20 -0700291 /**
292 * Reads the preview bitmap from the DB or null if the preview is not in the DB.
293 */
294 private Bitmap readFromDb(WidgetCacheKey key, Bitmap recycle, PreviewLoadTask loadTask) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700295 Cursor cursor = null;
296 try {
297 cursor = mDb.getReadableDatabase().query(
298 CacheDb.TABLE_NAME,
299 new String[] { CacheDb.COLUMN_PREVIEW_BITMAP },
300 CacheDb.COLUMN_COMPONENT + " = ? AND " + CacheDb.COLUMN_USER + " = ? AND " + CacheDb.COLUMN_SIZE + " = ?",
301 new String[] {
302 key.componentName.flattenToString(),
303 Long.toString(mUserManager.getSerialNumberForUser(key.user)),
304 key.size
305 },
306 null, null, null);
Winson Chung05304db2015-05-18 16:53:20 -0700307 // If cancelled, skip getting the blob and decoding it into a bitmap
308 if (loadTask.isCancelled()) {
309 return null;
310 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700311 if (cursor.moveToNext()) {
312 byte[] blob = cursor.getBlob(0);
313 BitmapFactory.Options opts = new BitmapFactory.Options();
314 opts.inBitmap = recycle;
Michael Jurka6e27f642013-12-10 13:40:30 +0100315 try {
Winson Chung05304db2015-05-18 16:53:20 -0700316 if (!loadTask.isCancelled()) {
317 return BitmapFactory.decodeByteArray(blob, 0, blob.length, opts);
318 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700319 } catch (Exception e) {
320 return null;
Michael Jurka6e27f642013-12-10 13:40:30 +0100321 }
Michael Jurka05713af2013-01-23 12:39:24 +0100322 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700323 } catch (SQLException e) {
324 Log.w(TAG, "Error loading preview from DB", e);
325 } finally {
326 if (cursor != null) {
327 cursor.close();
328 }
329 }
330 return null;
Michael Jurka05713af2013-01-23 12:39:24 +0100331 }
332
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700333 private Bitmap generatePreview(Object info, Bitmap recycle, int previewWidth, int previewHeight) {
Adam Cohen59400422014-03-05 18:07:04 -0800334 if (info instanceof LauncherAppWidgetProviderInfo) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700335 return generateWidgetPreview((LauncherAppWidgetProviderInfo) info, previewWidth, recycle);
Michael Jurka05713af2013-01-23 12:39:24 +0100336 } else {
337 return generateShortcutPreview(
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700338 (ResolveInfo) info, previewWidth, previewHeight, recycle);
Michael Jurka05713af2013-01-23 12:39:24 +0100339 }
340 }
341
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700342 public Bitmap generateWidgetPreview(LauncherAppWidgetProviderInfo info,
343 int previewWidth, Bitmap preview) {
344 int maxWidth = Math.min(previewWidth, info.spanX
345 * LauncherAppState.getInstance().getDynamicGrid().getDeviceProfile().cellWidthPx);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700346 return generateWidgetPreview(info, maxWidth, preview, null);
Michael Jurka05713af2013-01-23 12:39:24 +0100347 }
348
Sunny Goyal4cad7532015-03-18 15:56:30 -0700349 public Bitmap generateWidgetPreview(LauncherAppWidgetProviderInfo info,
350 int maxPreviewWidth, Bitmap preview, int[] preScaledWidthOut) {
Michael Jurka05713af2013-01-23 12:39:24 +0100351 // Load the preview image if possible
Michael Jurka05713af2013-01-23 12:39:24 +0100352 if (maxPreviewWidth < 0) maxPreviewWidth = Integer.MAX_VALUE;
Michael Jurka05713af2013-01-23 12:39:24 +0100353
354 Drawable drawable = null;
Sunny Goyalffe83f12014-08-14 17:39:34 -0700355 if (info.previewImage != 0) {
356 drawable = mManager.loadPreview(info);
Adrian Roosfa9ffc22014-05-12 15:59:59 +0200357 if (drawable != null) {
358 drawable = mutateOnMainThread(drawable);
359 } else {
Michael Jurka05713af2013-01-23 12:39:24 +0100360 Log.w(TAG, "Can't load widget preview drawable 0x" +
Sunny Goyalffe83f12014-08-14 17:39:34 -0700361 Integer.toHexString(info.previewImage) + " for provider: " + info.provider);
Michael Jurka05713af2013-01-23 12:39:24 +0100362 }
363 }
364
Sunny Goyal4cad7532015-03-18 15:56:30 -0700365 final boolean widgetPreviewExists = (drawable != null);
366 final int spanX = info.spanX < 1 ? 1 : info.spanX;
367 final int spanY = info.spanY < 1 ? 1 : info.spanY;
368
Michael Jurka05713af2013-01-23 12:39:24 +0100369 int previewWidth;
370 int previewHeight;
Sunny Goyal4cad7532015-03-18 15:56:30 -0700371 Bitmap tileBitmap = null;
372
Michael Jurka05713af2013-01-23 12:39:24 +0100373 if (widgetPreviewExists) {
374 previewWidth = drawable.getIntrinsicWidth();
375 previewHeight = drawable.getIntrinsicHeight();
376 } else {
377 // Generate a preview image if we couldn't load one
Sunny Goyal4cad7532015-03-18 15:56:30 -0700378 tileBitmap = ((BitmapDrawable) mContext.getResources().getDrawable(
379 R.drawable.widget_tile)).getBitmap();
380 previewWidth = tileBitmap.getWidth() * spanX;
381 previewHeight = tileBitmap.getHeight() * spanY;
Michael Jurka05713af2013-01-23 12:39:24 +0100382 }
383
384 // Scale to fit width only - let the widget preview be clipped in the
385 // vertical dimension
386 float scale = 1f;
387 if (preScaledWidthOut != null) {
388 preScaledWidthOut[0] = previewWidth;
389 }
390 if (previewWidth > maxPreviewWidth) {
391 scale = maxPreviewWidth / (float) previewWidth;
392 }
393 if (scale != 1f) {
394 previewWidth = (int) (scale * previewWidth);
395 previewHeight = (int) (scale * previewHeight);
396 }
397
398 // 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 -0700399 final Canvas c = new Canvas();
Michael Jurka05713af2013-01-23 12:39:24 +0100400 if (preview == null) {
401 preview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700402 c.setBitmap(preview);
403 } else {
404 // Reusing bitmap. Clear it.
405 c.setBitmap(preview);
406 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100407 }
408
409 // Draw the scaled preview into the final bitmap
410 int x = (preview.getWidth() - previewWidth) / 2;
411 if (widgetPreviewExists) {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700412 drawable.setBounds(x, 0, x + previewWidth, previewHeight);
413 drawable.draw(c);
Michael Jurka05713af2013-01-23 12:39:24 +0100414 } else {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700415 final Paint p = new Paint();
416 p.setFilterBitmap(true);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700417 int appIconSize = LauncherAppState.getInstance().getDynamicGrid()
418 .getDeviceProfile().iconSizePx;
Michael Jurka05713af2013-01-23 12:39:24 +0100419
Sunny Goyal4cad7532015-03-18 15:56:30 -0700420 // draw the spanX x spanY tiles
421 final Rect src = new Rect(0, 0, tileBitmap.getWidth(), tileBitmap.getHeight());
422
423 float tileW = scale * tileBitmap.getWidth();
424 float tileH = scale * tileBitmap.getHeight();
425 final RectF dst = new RectF(0, 0, tileW, tileH);
426
427 float tx = x;
428 for (int i = 0; i < spanX; i++, tx += tileW) {
429 float ty = 0;
430 for (int j = 0; j < spanY; j++, ty += tileH) {
431 dst.offsetTo(tx, ty);
432 c.drawBitmap(tileBitmap, src, dst, p);
433 }
Michael Jurka05713af2013-01-23 12:39:24 +0100434 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700435
436 // Draw the icon in the top left corner
437 // TODO: use top right for RTL
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700438 int minOffset = (int) (appIconSize * WIDGET_PREVIEW_ICON_PADDING_PERCENTAGE);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700439 int smallestSide = Math.min(previewWidth, previewHeight);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700440 float iconScale = Math.min((float) smallestSide / (appIconSize + 2 * minOffset), scale);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700441
442 try {
443 Drawable icon = mutateOnMainThread(mManager.loadIcon(info, mIconCache));
444 if (icon != null) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700445 int hoffset = (int) ((tileW - appIconSize * iconScale) / 2) + x;
446 int yoffset = (int) ((tileH - appIconSize * iconScale) / 2);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700447 icon.setBounds(hoffset, yoffset,
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700448 hoffset + (int) (appIconSize * iconScale),
449 yoffset + (int) (appIconSize * iconScale));
Sunny Goyal4cad7532015-03-18 15:56:30 -0700450 icon.draw(c);
451 }
452 } catch (Resources.NotFoundException e) { }
Michael Jurka05713af2013-01-23 12:39:24 +0100453 c.setBitmap(null);
454 }
Hyunyoung Song6babf2e2015-05-14 17:08:45 -0700455 return mManager.getBadgeBitmap(info, preview, Math.min(preview.getHeight(), previewHeight));
Michael Jurka05713af2013-01-23 12:39:24 +0100456 }
457
458 private Bitmap generateShortcutPreview(
459 ResolveInfo info, int maxWidth, int maxHeight, Bitmap preview) {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700460 final Canvas c = new Canvas();
461 if (preview == null) {
Michael Jurka05713af2013-01-23 12:39:24 +0100462 preview = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700463 c.setBitmap(preview);
464 } else if (preview.getWidth() != maxWidth || preview.getHeight() != maxHeight) {
465 throw new RuntimeException("Improperly sized bitmap passed as argument");
466 } else {
467 // Reusing bitmap. Clear it.
468 c.setBitmap(preview);
469 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100470 }
471
Sunny Goyal4cad7532015-03-18 15:56:30 -0700472 Drawable icon = mutateOnMainThread(mIconCache.getFullResIcon(info.activityInfo));
473 icon.setFilterBitmap(true);
474
Michael Jurka05713af2013-01-23 12:39:24 +0100475 // Draw a desaturated/scaled version of the icon in the background as a watermark
Sunny Goyal4cad7532015-03-18 15:56:30 -0700476 ColorMatrix colorMatrix = new ColorMatrix();
477 colorMatrix.setSaturation(0);
478 icon.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
479 icon.setAlpha((int) (255 * 0.06f));
480
481 Resources res = mContext.getResources();
482 int paddingTop = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_top);
483 int paddingLeft = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_left);
484 int paddingRight = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_right);
485 int scaledIconWidth = (maxWidth - paddingLeft - paddingRight);
486 icon.setBounds(paddingLeft, paddingTop,
487 paddingLeft + scaledIconWidth, paddingTop + scaledIconWidth);
488 icon.draw(c);
489
490 // Draw the final icon at top left corner.
491 // TODO: use top right for RTL
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700492 int appIconSize = LauncherAppState.getInstance().getDynamicGrid()
493 .getDeviceProfile().iconSizePx;
Sunny Goyal4cad7532015-03-18 15:56:30 -0700494 icon.setAlpha(255);
495 icon.setColorFilter(null);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700496 icon.setBounds(0, 0, appIconSize, appIconSize);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700497 icon.draw(c);
498
Michael Jurka05713af2013-01-23 12:39:24 +0100499 c.setBitmap(null);
Michael Jurka05713af2013-01-23 12:39:24 +0100500 return preview;
501 }
502
Adrian Roos65d60e22014-04-15 21:07:49 +0200503 private Drawable mutateOnMainThread(final Drawable drawable) {
504 try {
505 return mMainThreadExecutor.submit(new Callable<Drawable>() {
506 @Override
507 public Drawable call() throws Exception {
508 return drawable.mutate();
509 }
510 }).get();
511 } catch (InterruptedException e) {
512 Thread.currentThread().interrupt();
513 throw new RuntimeException(e);
514 } catch (ExecutionException e) {
515 throw new RuntimeException(e);
516 }
517 }
Adrian Roos1f375ab2014-04-28 18:26:38 +0200518
Adrian Roos1f375ab2014-04-28 18:26:38 +0200519 /**
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700520 * @return an array of containing versionCode and lastUpdatedTime for the package.
Adrian Roos1f375ab2014-04-28 18:26:38 +0200521 */
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700522 private long[] getPackageVersion(String packageName) {
523 synchronized (mPackageVersions) {
524 long[] versions = mPackageVersions.get(packageName);
525 if (versions == null) {
526 versions = new long[2];
Adrian Roos1f375ab2014-04-28 18:26:38 +0200527 try {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700528 PackageInfo info = mContext.getPackageManager().getPackageInfo(packageName, 0);
529 versions[0] = info.versionCode;
530 versions[1] = info.lastUpdateTime;
531 } catch (NameNotFoundException e) {
532 Log.e(TAG, "PackageInfo not found", e);
533 }
534 mPackageVersions.put(packageName, versions);
535 }
536 return versions;
537 }
538 }
539
540 /**
541 * A request Id which can be used by the client to cancel any request.
542 */
543 public class PreviewLoadRequest {
544
545 private final PreviewLoadTask mTask;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700546
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700547 public PreviewLoadRequest(PreviewLoadTask task) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700548 mTask = task;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700549 }
550
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700551 public void cleanup() {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700552 if (mTask != null) {
553 mTask.cancel(true);
554 }
555
Winson Chung05304db2015-05-18 16:53:20 -0700556 // This only handles the case where the PreviewLoadTask is cancelled after the task has
557 // successfully completed (including having written to disk when necessary). In the
558 // other cases where it is cancelled while the task is running, it will be cleaned up
559 // in the tasks's onCancelled() call, and if cancelled while the task is writing to
560 // disk, it will be cancelled in the task's onPostExecute() call.
561 if (mTask.mBitmapToRecycle != null) {
562 synchronized (mUnusedBitmaps) {
563 mUnusedBitmaps.add(mTask.mBitmapToRecycle);
564 }
565 mTask.mBitmapToRecycle = null;
Adrian Roos1f375ab2014-04-28 18:26:38 +0200566 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700567 }
568 }
569
570 public class PreviewLoadTask extends AsyncTask<Void, Void, Bitmap> {
571
572 private final WidgetCacheKey mKey;
573 private final Object mInfo;
574 private final int mPreviewHeight;
575 private final int mPreviewWidth;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700576 private final WidgetCell mCaller;
Winson Chung05304db2015-05-18 16:53:20 -0700577 private long[] mVersions;
578 private Bitmap mBitmapToRecycle;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700579
580 PreviewLoadTask(WidgetCacheKey key, Object info, int previewWidth,
Hyunyoung Song3f471442015-04-08 19:01:34 -0700581 int previewHeight, WidgetCell caller) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700582 mKey = key;
583 mInfo = info;
584 mPreviewHeight = previewHeight;
585 mPreviewWidth = previewWidth;
586 mCaller = caller;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700587 if (DEBUG) {
588 Log.d(TAG, String.format("%s, %s, %d, %d",
589 mKey, mInfo, mPreviewHeight, mPreviewWidth));
590 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700591 }
592
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700593 @Override
594 protected Bitmap doInBackground(Void... params) {
595 Bitmap unusedBitmap = null;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700596
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700597 synchronized (mUnusedBitmaps) {
Winson Chung05304db2015-05-18 16:53:20 -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 // Check if we can use a bitmap
603 for (Bitmap candidate : mUnusedBitmaps) {
604 if (candidate != null && candidate.isMutable() &&
605 candidate.getWidth() == mPreviewWidth &&
606 candidate.getHeight() == mPreviewHeight) {
607 unusedBitmap = candidate;
608 break;
609 }
610 }
611
612 if (unusedBitmap == null) {
613 unusedBitmap = Bitmap.createBitmap(mPreviewWidth, mPreviewHeight, Config.ARGB_8888);
614 } else {
615 mUnusedBitmaps.remove(unusedBitmap);
616 }
Adrian Roos1f375ab2014-04-28 18:26:38 +0200617 }
Winson Chung05304db2015-05-18 16:53:20 -0700618 // If cancelled now, don't bother reading the preview from the DB
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700619 if (isCancelled()) {
Winson Chung05304db2015-05-18 16:53:20 -0700620 return unusedBitmap;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700621 }
Winson Chung05304db2015-05-18 16:53:20 -0700622 Bitmap preview = readFromDb(mKey, unusedBitmap, this);
623 // Only consider generating the preview if we have not cancelled the task already
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700624 if (!isCancelled() && preview == null) {
625 // Fetch the version info before we generate the preview, so that, in-case the
626 // app was updated while we are generating the preview, we use the old version info,
627 // which would gets re-written next time.
Winson Chung05304db2015-05-18 16:53:20 -0700628 mVersions = getPackageVersion(mKey.componentName.getPackageName());
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700629
630 // it's not in the db... we need to generate it
631 preview = generatePreview(mInfo, unusedBitmap, mPreviewWidth, mPreviewHeight);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700632 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700633 return preview;
634 }
635
636 @Override
Winson Chung05304db2015-05-18 16:53:20 -0700637 protected void onPostExecute(final Bitmap preview) {
638 mCaller.applyPreview(preview);
639
640 // Write the generated preview to the DB in the worker thread
641 if (mVersions != null) {
642 mWorkerHandler.post(new Runnable() {
643 @Override
644 public void run() {
645 if (!isCancelled()) {
646 // If we are still using this preview, then write it to the DB and then
647 // let the normal clear mechanism recycle the bitmap
648 writeToDb(mKey, mVersions, preview);
649 mBitmapToRecycle = preview;
650 } else {
651 // If we've already cancelled, then skip writing the bitmap to the DB
652 // and manually add the bitmap back to the recycled set
653 synchronized (mUnusedBitmaps) {
654 mUnusedBitmaps.add(preview);
655 }
656 }
657 }
658 });
659 } else {
660 // If we don't need to write to disk, then ensure the preview gets recycled by
661 // the normal clear mechanism
662 mBitmapToRecycle = preview;
663 }
664 }
665
666 @Override
667 protected void onCancelled(Bitmap preview) {
668 // If we've cancelled while the task is running, then can return the bitmap to the
669 // recycled set immediately. Otherwise, it will be recycled after the preview is written
670 // to disk.
671 if (preview != null) {
672 synchronized (mUnusedBitmaps) {
673 mUnusedBitmaps.add(preview);
674 }
675 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700676 }
677 }
678
679 private static final class WidgetCacheKey extends ComponentKey {
680
681 // TODO: remove dependency on size
682 private final String size;
683
684 public WidgetCacheKey(ComponentName componentName, UserHandleCompat user, String size) {
685 super(componentName, user);
686 this.size = size;
687 }
688
689 @Override
690 public int hashCode() {
691 return super.hashCode() ^ size.hashCode();
692 }
693
694 @Override
695 public boolean equals(Object o) {
696 return super.equals(o) && ((WidgetCacheKey) o).size.equals(size);
Adrian Roos1f375ab2014-04-28 18:26:38 +0200697 }
698 }
Michael Jurka05713af2013-01-23 12:39:24 +0100699}