blob: 5ee1f2615bf392be53315d66e59d00eaba7ca3f8 [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) {
Hyunyoung Song2bd3d7d2015-05-21 13:04:53 -0700209 Utilities.assertWorkerThread();
Hyunyoung Song8821ca92015-05-04 16:28:20 -0700210
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700211 LongSparseArray<UserHandleCompat> userIdCache = new LongSparseArray<>();
212 LongSparseArray<HashSet<String>> validPackages = new LongSparseArray<>();
213
Hyunyoung Song8821ca92015-05-04 16:28:20 -0700214 for (Object obj : list) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700215 final UserHandleCompat user;
216 final String pkg;
217 if (obj instanceof ResolveInfo) {
218 user = UserHandleCompat.myUserHandle();
219 pkg = ((ResolveInfo) obj).activityInfo.packageName;
220 } else {
221 LauncherAppWidgetProviderInfo info = (LauncherAppWidgetProviderInfo) obj;
222 user = mManager.getUser(info);
223 pkg = info.provider.getPackageName();
224 }
225
226 int userIdIndex = userIdCache.indexOfValue(user);
227 final long userId;
228 if (userIdIndex < 0) {
229 userId = mUserManager.getSerialNumberForUser(user);
230 userIdCache.put(userId, user);
231 } else {
232 userId = userIdCache.keyAt(userIdIndex);
233 }
234
235 HashSet<String> packages = validPackages.get(userId);
236 if (packages == null) {
237 packages = new HashSet<>();
238 validPackages.put(userId, packages);
239 }
240 packages.add(pkg);
Michael Jurka05713af2013-01-23 12:39:24 +0100241 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700242
243 LongSparseArray<HashSet<String>> packagesToDelete = new LongSparseArray<>();
244 Cursor c = null;
245 try {
246 c = mDb.getReadableDatabase().query(CacheDb.TABLE_NAME,
247 new String[] {CacheDb.COLUMN_USER, CacheDb.COLUMN_PACKAGE,
248 CacheDb.COLUMN_LAST_UPDATED, CacheDb.COLUMN_VERSION},
249 null, null, null, null, null);
250 while (c.moveToNext()) {
251 long userId = c.getLong(0);
252 String pkg = c.getString(1);
253 long lastUpdated = c.getLong(2);
254 long version = c.getLong(3);
255
256 HashSet<String> packages = validPackages.get(userId);
257 if (packages != null && packages.contains(pkg)) {
258 long[] versions = getPackageVersion(pkg);
259 if (versions[0] == version && versions[1] == lastUpdated) {
260 // Every thing checks out
261 continue;
262 }
263 }
264
265 // We need to delete this package.
266 packages = packagesToDelete.get(userId);
267 if (packages == null) {
268 packages = new HashSet<>();
269 packagesToDelete.put(userId, packages);
270 }
271 packages.add(pkg);
272 }
273
274 for (int i = 0; i < packagesToDelete.size(); i++) {
275 long userId = packagesToDelete.keyAt(i);
276 UserHandleCompat user = mUserManager.getUserForSerialNumber(userId);
277 for (String pkg : packagesToDelete.valueAt(i)) {
278 removePackage(pkg, user, userId);
279 }
280 }
281 } catch (SQLException e) {
282 Log.e(TAG, "Error updatating widget previews", e);
283 } finally {
284 if (c != null) {
285 c.close();
286 }
287 }
288 }
289
Winson Chung05304db2015-05-18 16:53:20 -0700290 /**
291 * Reads the preview bitmap from the DB or null if the preview is not in the DB.
292 */
293 private Bitmap readFromDb(WidgetCacheKey key, Bitmap recycle, PreviewLoadTask loadTask) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700294 Cursor cursor = null;
295 try {
296 cursor = mDb.getReadableDatabase().query(
297 CacheDb.TABLE_NAME,
298 new String[] { CacheDb.COLUMN_PREVIEW_BITMAP },
299 CacheDb.COLUMN_COMPONENT + " = ? AND " + CacheDb.COLUMN_USER + " = ? AND " + CacheDb.COLUMN_SIZE + " = ?",
300 new String[] {
301 key.componentName.flattenToString(),
302 Long.toString(mUserManager.getSerialNumberForUser(key.user)),
303 key.size
304 },
305 null, null, null);
Winson Chung05304db2015-05-18 16:53:20 -0700306 // If cancelled, skip getting the blob and decoding it into a bitmap
307 if (loadTask.isCancelled()) {
308 return null;
309 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700310 if (cursor.moveToNext()) {
311 byte[] blob = cursor.getBlob(0);
312 BitmapFactory.Options opts = new BitmapFactory.Options();
313 opts.inBitmap = recycle;
Michael Jurka6e27f642013-12-10 13:40:30 +0100314 try {
Winson Chung05304db2015-05-18 16:53:20 -0700315 if (!loadTask.isCancelled()) {
316 return BitmapFactory.decodeByteArray(blob, 0, blob.length, opts);
317 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700318 } catch (Exception e) {
319 return null;
Michael Jurka6e27f642013-12-10 13:40:30 +0100320 }
Michael Jurka05713af2013-01-23 12:39:24 +0100321 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700322 } catch (SQLException e) {
323 Log.w(TAG, "Error loading preview from DB", e);
324 } finally {
325 if (cursor != null) {
326 cursor.close();
327 }
328 }
329 return null;
Michael Jurka05713af2013-01-23 12:39:24 +0100330 }
331
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700332 private Bitmap generatePreview(Object info, Bitmap recycle, int previewWidth, int previewHeight) {
Adam Cohen59400422014-03-05 18:07:04 -0800333 if (info instanceof LauncherAppWidgetProviderInfo) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700334 return generateWidgetPreview((LauncherAppWidgetProviderInfo) info, previewWidth, recycle);
Michael Jurka05713af2013-01-23 12:39:24 +0100335 } else {
336 return generateShortcutPreview(
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700337 (ResolveInfo) info, previewWidth, previewHeight, recycle);
Michael Jurka05713af2013-01-23 12:39:24 +0100338 }
339 }
340
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700341 public Bitmap generateWidgetPreview(LauncherAppWidgetProviderInfo info,
342 int previewWidth, Bitmap preview) {
343 int maxWidth = Math.min(previewWidth, info.spanX
344 * LauncherAppState.getInstance().getDynamicGrid().getDeviceProfile().cellWidthPx);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700345 return generateWidgetPreview(info, maxWidth, preview, null);
Michael Jurka05713af2013-01-23 12:39:24 +0100346 }
347
Sunny Goyal4cad7532015-03-18 15:56:30 -0700348 public Bitmap generateWidgetPreview(LauncherAppWidgetProviderInfo info,
349 int maxPreviewWidth, Bitmap preview, int[] preScaledWidthOut) {
Michael Jurka05713af2013-01-23 12:39:24 +0100350 // Load the preview image if possible
Michael Jurka05713af2013-01-23 12:39:24 +0100351 if (maxPreviewWidth < 0) maxPreviewWidth = Integer.MAX_VALUE;
Michael Jurka05713af2013-01-23 12:39:24 +0100352
353 Drawable drawable = null;
Sunny Goyalffe83f12014-08-14 17:39:34 -0700354 if (info.previewImage != 0) {
355 drawable = mManager.loadPreview(info);
Adrian Roosfa9ffc22014-05-12 15:59:59 +0200356 if (drawable != null) {
357 drawable = mutateOnMainThread(drawable);
358 } else {
Michael Jurka05713af2013-01-23 12:39:24 +0100359 Log.w(TAG, "Can't load widget preview drawable 0x" +
Sunny Goyalffe83f12014-08-14 17:39:34 -0700360 Integer.toHexString(info.previewImage) + " for provider: " + info.provider);
Michael Jurka05713af2013-01-23 12:39:24 +0100361 }
362 }
363
Sunny Goyal4cad7532015-03-18 15:56:30 -0700364 final boolean widgetPreviewExists = (drawable != null);
365 final int spanX = info.spanX < 1 ? 1 : info.spanX;
366 final int spanY = info.spanY < 1 ? 1 : info.spanY;
367
Michael Jurka05713af2013-01-23 12:39:24 +0100368 int previewWidth;
369 int previewHeight;
Sunny Goyal4cad7532015-03-18 15:56:30 -0700370 Bitmap tileBitmap = null;
371
Michael Jurka05713af2013-01-23 12:39:24 +0100372 if (widgetPreviewExists) {
373 previewWidth = drawable.getIntrinsicWidth();
374 previewHeight = drawable.getIntrinsicHeight();
375 } else {
376 // Generate a preview image if we couldn't load one
Sunny Goyal4cad7532015-03-18 15:56:30 -0700377 tileBitmap = ((BitmapDrawable) mContext.getResources().getDrawable(
378 R.drawable.widget_tile)).getBitmap();
379 previewWidth = tileBitmap.getWidth() * spanX;
380 previewHeight = tileBitmap.getHeight() * spanY;
Michael Jurka05713af2013-01-23 12:39:24 +0100381 }
382
383 // Scale to fit width only - let the widget preview be clipped in the
384 // vertical dimension
385 float scale = 1f;
386 if (preScaledWidthOut != null) {
387 preScaledWidthOut[0] = previewWidth;
388 }
389 if (previewWidth > maxPreviewWidth) {
390 scale = maxPreviewWidth / (float) previewWidth;
391 }
392 if (scale != 1f) {
393 previewWidth = (int) (scale * previewWidth);
394 previewHeight = (int) (scale * previewHeight);
395 }
396
397 // 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 -0700398 final Canvas c = new Canvas();
Michael Jurka05713af2013-01-23 12:39:24 +0100399 if (preview == null) {
400 preview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700401 c.setBitmap(preview);
402 } else {
403 // Reusing bitmap. Clear it.
404 c.setBitmap(preview);
405 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100406 }
407
408 // Draw the scaled preview into the final bitmap
409 int x = (preview.getWidth() - previewWidth) / 2;
410 if (widgetPreviewExists) {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700411 drawable.setBounds(x, 0, x + previewWidth, previewHeight);
412 drawable.draw(c);
Michael Jurka05713af2013-01-23 12:39:24 +0100413 } else {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700414 final Paint p = new Paint();
415 p.setFilterBitmap(true);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700416 int appIconSize = LauncherAppState.getInstance().getDynamicGrid()
417 .getDeviceProfile().iconSizePx;
Michael Jurka05713af2013-01-23 12:39:24 +0100418
Sunny Goyal4cad7532015-03-18 15:56:30 -0700419 // draw the spanX x spanY tiles
420 final Rect src = new Rect(0, 0, tileBitmap.getWidth(), tileBitmap.getHeight());
421
422 float tileW = scale * tileBitmap.getWidth();
423 float tileH = scale * tileBitmap.getHeight();
424 final RectF dst = new RectF(0, 0, tileW, tileH);
425
426 float tx = x;
427 for (int i = 0; i < spanX; i++, tx += tileW) {
428 float ty = 0;
429 for (int j = 0; j < spanY; j++, ty += tileH) {
430 dst.offsetTo(tx, ty);
431 c.drawBitmap(tileBitmap, src, dst, p);
432 }
Michael Jurka05713af2013-01-23 12:39:24 +0100433 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700434
435 // Draw the icon in the top left corner
436 // TODO: use top right for RTL
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700437 int minOffset = (int) (appIconSize * WIDGET_PREVIEW_ICON_PADDING_PERCENTAGE);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700438 int smallestSide = Math.min(previewWidth, previewHeight);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700439 float iconScale = Math.min((float) smallestSide / (appIconSize + 2 * minOffset), scale);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700440
441 try {
442 Drawable icon = mutateOnMainThread(mManager.loadIcon(info, mIconCache));
443 if (icon != null) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700444 int hoffset = (int) ((tileW - appIconSize * iconScale) / 2) + x;
445 int yoffset = (int) ((tileH - appIconSize * iconScale) / 2);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700446 icon.setBounds(hoffset, yoffset,
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700447 hoffset + (int) (appIconSize * iconScale),
448 yoffset + (int) (appIconSize * iconScale));
Sunny Goyal4cad7532015-03-18 15:56:30 -0700449 icon.draw(c);
450 }
451 } catch (Resources.NotFoundException e) { }
Michael Jurka05713af2013-01-23 12:39:24 +0100452 c.setBitmap(null);
453 }
Hyunyoung Song6babf2e2015-05-14 17:08:45 -0700454 return mManager.getBadgeBitmap(info, preview, Math.min(preview.getHeight(), previewHeight));
Michael Jurka05713af2013-01-23 12:39:24 +0100455 }
456
457 private Bitmap generateShortcutPreview(
458 ResolveInfo info, int maxWidth, int maxHeight, Bitmap preview) {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700459 final Canvas c = new Canvas();
460 if (preview == null) {
Michael Jurka05713af2013-01-23 12:39:24 +0100461 preview = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700462 c.setBitmap(preview);
463 } else if (preview.getWidth() != maxWidth || preview.getHeight() != maxHeight) {
464 throw new RuntimeException("Improperly sized bitmap passed as argument");
465 } else {
466 // Reusing bitmap. Clear it.
467 c.setBitmap(preview);
468 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100469 }
470
Sunny Goyal4cad7532015-03-18 15:56:30 -0700471 Drawable icon = mutateOnMainThread(mIconCache.getFullResIcon(info.activityInfo));
472 icon.setFilterBitmap(true);
473
Michael Jurka05713af2013-01-23 12:39:24 +0100474 // Draw a desaturated/scaled version of the icon in the background as a watermark
Sunny Goyal4cad7532015-03-18 15:56:30 -0700475 ColorMatrix colorMatrix = new ColorMatrix();
476 colorMatrix.setSaturation(0);
477 icon.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
478 icon.setAlpha((int) (255 * 0.06f));
479
480 Resources res = mContext.getResources();
481 int paddingTop = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_top);
482 int paddingLeft = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_left);
483 int paddingRight = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_right);
484 int scaledIconWidth = (maxWidth - paddingLeft - paddingRight);
485 icon.setBounds(paddingLeft, paddingTop,
486 paddingLeft + scaledIconWidth, paddingTop + scaledIconWidth);
487 icon.draw(c);
488
489 // Draw the final icon at top left corner.
490 // TODO: use top right for RTL
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700491 int appIconSize = LauncherAppState.getInstance().getDynamicGrid()
492 .getDeviceProfile().iconSizePx;
Sunny Goyal4cad7532015-03-18 15:56:30 -0700493 icon.setAlpha(255);
494 icon.setColorFilter(null);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700495 icon.setBounds(0, 0, appIconSize, appIconSize);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700496 icon.draw(c);
497
Michael Jurka05713af2013-01-23 12:39:24 +0100498 c.setBitmap(null);
Michael Jurka05713af2013-01-23 12:39:24 +0100499 return preview;
500 }
501
Adrian Roos65d60e22014-04-15 21:07:49 +0200502 private Drawable mutateOnMainThread(final Drawable drawable) {
503 try {
504 return mMainThreadExecutor.submit(new Callable<Drawable>() {
505 @Override
506 public Drawable call() throws Exception {
507 return drawable.mutate();
508 }
509 }).get();
510 } catch (InterruptedException e) {
511 Thread.currentThread().interrupt();
512 throw new RuntimeException(e);
513 } catch (ExecutionException e) {
514 throw new RuntimeException(e);
515 }
516 }
Adrian Roos1f375ab2014-04-28 18:26:38 +0200517
Adrian Roos1f375ab2014-04-28 18:26:38 +0200518 /**
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700519 * @return an array of containing versionCode and lastUpdatedTime for the package.
Adrian Roos1f375ab2014-04-28 18:26:38 +0200520 */
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700521 private long[] getPackageVersion(String packageName) {
522 synchronized (mPackageVersions) {
523 long[] versions = mPackageVersions.get(packageName);
524 if (versions == null) {
525 versions = new long[2];
Adrian Roos1f375ab2014-04-28 18:26:38 +0200526 try {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700527 PackageInfo info = mContext.getPackageManager().getPackageInfo(packageName, 0);
528 versions[0] = info.versionCode;
529 versions[1] = info.lastUpdateTime;
530 } catch (NameNotFoundException e) {
531 Log.e(TAG, "PackageInfo not found", e);
532 }
533 mPackageVersions.put(packageName, versions);
534 }
535 return versions;
536 }
537 }
538
539 /**
540 * A request Id which can be used by the client to cancel any request.
541 */
542 public class PreviewLoadRequest {
543
544 private final PreviewLoadTask mTask;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700545
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700546 public PreviewLoadRequest(PreviewLoadTask task) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700547 mTask = task;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700548 }
549
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700550 public void cleanup() {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700551 if (mTask != null) {
552 mTask.cancel(true);
553 }
554
Winson Chung05304db2015-05-18 16:53:20 -0700555 // This only handles the case where the PreviewLoadTask is cancelled after the task has
556 // successfully completed (including having written to disk when necessary). In the
557 // other cases where it is cancelled while the task is running, it will be cleaned up
558 // in the tasks's onCancelled() call, and if cancelled while the task is writing to
559 // disk, it will be cancelled in the task's onPostExecute() call.
560 if (mTask.mBitmapToRecycle != null) {
561 synchronized (mUnusedBitmaps) {
562 mUnusedBitmaps.add(mTask.mBitmapToRecycle);
563 }
564 mTask.mBitmapToRecycle = null;
Adrian Roos1f375ab2014-04-28 18:26:38 +0200565 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700566 }
567 }
568
569 public class PreviewLoadTask extends AsyncTask<Void, Void, Bitmap> {
570
571 private final WidgetCacheKey mKey;
572 private final Object mInfo;
573 private final int mPreviewHeight;
574 private final int mPreviewWidth;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700575 private final WidgetCell mCaller;
Winson Chung05304db2015-05-18 16:53:20 -0700576 private long[] mVersions;
577 private Bitmap mBitmapToRecycle;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700578
579 PreviewLoadTask(WidgetCacheKey key, Object info, int previewWidth,
Hyunyoung Song3f471442015-04-08 19:01:34 -0700580 int previewHeight, WidgetCell caller) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700581 mKey = key;
582 mInfo = info;
583 mPreviewHeight = previewHeight;
584 mPreviewWidth = previewWidth;
585 mCaller = caller;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700586 if (DEBUG) {
587 Log.d(TAG, String.format("%s, %s, %d, %d",
588 mKey, mInfo, mPreviewHeight, mPreviewWidth));
589 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700590 }
591
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700592 @Override
593 protected Bitmap doInBackground(Void... params) {
594 Bitmap unusedBitmap = null;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700595
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700596 synchronized (mUnusedBitmaps) {
Winson Chung05304db2015-05-18 16:53:20 -0700597 // If already cancelled before this gets to run in the background, then return early
598 if (isCancelled()) {
599 return null;
600 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700601 // Check if we can use a bitmap
602 for (Bitmap candidate : mUnusedBitmaps) {
603 if (candidate != null && candidate.isMutable() &&
604 candidate.getWidth() == mPreviewWidth &&
605 candidate.getHeight() == mPreviewHeight) {
606 unusedBitmap = candidate;
607 break;
608 }
609 }
610
611 if (unusedBitmap == null) {
612 unusedBitmap = Bitmap.createBitmap(mPreviewWidth, mPreviewHeight, Config.ARGB_8888);
613 } else {
614 mUnusedBitmaps.remove(unusedBitmap);
615 }
Adrian Roos1f375ab2014-04-28 18:26:38 +0200616 }
Winson Chung05304db2015-05-18 16:53:20 -0700617 // If cancelled now, don't bother reading the preview from the DB
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700618 if (isCancelled()) {
Winson Chung05304db2015-05-18 16:53:20 -0700619 return unusedBitmap;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700620 }
Winson Chung05304db2015-05-18 16:53:20 -0700621 Bitmap preview = readFromDb(mKey, unusedBitmap, this);
622 // Only consider generating the preview if we have not cancelled the task already
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700623 if (!isCancelled() && preview == null) {
624 // Fetch the version info before we generate the preview, so that, in-case the
625 // app was updated while we are generating the preview, we use the old version info,
626 // which would gets re-written next time.
Winson Chung05304db2015-05-18 16:53:20 -0700627 mVersions = getPackageVersion(mKey.componentName.getPackageName());
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700628
629 // it's not in the db... we need to generate it
630 preview = generatePreview(mInfo, unusedBitmap, mPreviewWidth, mPreviewHeight);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700631 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700632 return preview;
633 }
634
635 @Override
Winson Chung05304db2015-05-18 16:53:20 -0700636 protected void onPostExecute(final Bitmap preview) {
637 mCaller.applyPreview(preview);
638
639 // Write the generated preview to the DB in the worker thread
640 if (mVersions != null) {
641 mWorkerHandler.post(new Runnable() {
642 @Override
643 public void run() {
644 if (!isCancelled()) {
645 // If we are still using this preview, then write it to the DB and then
646 // let the normal clear mechanism recycle the bitmap
647 writeToDb(mKey, mVersions, preview);
648 mBitmapToRecycle = preview;
649 } else {
650 // If we've already cancelled, then skip writing the bitmap to the DB
651 // and manually add the bitmap back to the recycled set
652 synchronized (mUnusedBitmaps) {
653 mUnusedBitmaps.add(preview);
654 }
655 }
656 }
657 });
658 } else {
659 // If we don't need to write to disk, then ensure the preview gets recycled by
660 // the normal clear mechanism
661 mBitmapToRecycle = preview;
662 }
663 }
664
665 @Override
666 protected void onCancelled(Bitmap preview) {
667 // If we've cancelled while the task is running, then can return the bitmap to the
668 // recycled set immediately. Otherwise, it will be recycled after the preview is written
669 // to disk.
670 if (preview != null) {
671 synchronized (mUnusedBitmaps) {
672 mUnusedBitmaps.add(preview);
673 }
674 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700675 }
676 }
677
678 private static final class WidgetCacheKey extends ComponentKey {
679
680 // TODO: remove dependency on size
681 private final String size;
682
683 public WidgetCacheKey(ComponentName componentName, UserHandleCompat user, String size) {
684 super(componentName, user);
685 this.size = size;
686 }
687
688 @Override
689 public int hashCode() {
690 return super.hashCode() ^ size.hashCode();
691 }
692
693 @Override
694 public boolean equals(Object o) {
695 return super.equals(o) && ((WidgetCacheKey) o).size.equals(size);
Adrian Roos1f375ab2014-04-28 18:26:38 +0200696 }
697 }
Michael Jurka05713af2013-01-23 12:39:24 +0100698}