blob: a621771423f4ec6393dbb4b90b1c05bcfc9aed65 [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.
58 */
Sunny Goyal316490e2015-06-02 09:38:28 -070059 @Thunk Set<Bitmap> mUnusedBitmaps =
Hyunyoung Song559d90d2015-04-28 15:06:45 -070060 Collections.newSetFromMap(new WeakHashMap<Bitmap, Boolean>());
Sunny Goyal4cad7532015-03-18 15:56:30 -070061
62 private final Context mContext;
Sunny Goyalffe83f12014-08-14 17:39:34 -070063 private final IconCache mIconCache;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070064 private final UserManagerCompat mUserManager;
Sunny Goyalffe83f12014-08-14 17:39:34 -070065 private final AppWidgetManagerCompat mManager;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070066 private final CacheDb mDb;
Adam Cohen2e6da152015-05-06 11:42:25 -070067 private final InvariantDeviceProfile mDeviceProfile;
Michael Jurka05713af2013-01-23 12:39:24 +010068
Adrian Roos65d60e22014-04-15 21:07:49 +020069 private final MainThreadExecutor mMainThreadExecutor = new MainThreadExecutor();
Sunny Goyal316490e2015-06-02 09:38:28 -070070 @Thunk final Handler mWorkerHandler;
Adrian Roos65d60e22014-04-15 21:07:49 +020071
Adam Cohen2e6da152015-05-06 11:42:25 -070072 public WidgetPreviewLoader(Context context, InvariantDeviceProfile inv, IconCache iconCache) {
Chris Wrenfd13c712013-09-27 15:45:19 -040073 mContext = context;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070074 mIconCache = iconCache;
Sunny Goyalffe83f12014-08-14 17:39:34 -070075 mManager = AppWidgetManagerCompat.getInstance(context);
Sunny Goyal5b0e6692015-03-19 14:31:19 -070076 mUserManager = UserManagerCompat.getInstance(context);
77 mDb = new CacheDb(context);
Winson Chung05304db2015-05-18 16:53:20 -070078 mWorkerHandler = new Handler(LauncherModel.getWorkerLooper());
Adam Cohen2e6da152015-05-06 11:42:25 -070079 mDeviceProfile = inv;
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 */
Adam Cohen2e6da152015-05-06 11:42:25 -070089 public PreviewLoadRequest getPreview(final Object o, int previewWidth,
90 int previewHeight, 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 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700293 @Thunk 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 Goyal316490e2015-06-02 09:38:28 -0700332 @Thunk Bitmap generatePreview(Launcher launcher, Object info, Bitmap recycle,
Adam Cohen2e6da152015-05-06 11:42:25 -0700333 int previewWidth, int previewHeight) {
Adam Cohen59400422014-03-05 18:07:04 -0800334 if (info instanceof LauncherAppWidgetProviderInfo) {
Adam Cohen2e6da152015-05-06 11:42:25 -0700335 return generateWidgetPreview(launcher, (LauncherAppWidgetProviderInfo) info,
336 previewWidth, recycle, null);
Michael Jurka05713af2013-01-23 12:39:24 +0100337 } else {
Adam Cohen2e6da152015-05-06 11:42:25 -0700338 return generateShortcutPreview(launcher,
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700339 (ResolveInfo) info, previewWidth, previewHeight, recycle);
Michael Jurka05713af2013-01-23 12:39:24 +0100340 }
341 }
342
Adam Cohen2e6da152015-05-06 11:42:25 -0700343 public Bitmap generateWidgetPreview(Launcher launcher, LauncherAppWidgetProviderInfo info,
Sunny Goyal4cad7532015-03-18 15:56:30 -0700344 int maxPreviewWidth, Bitmap preview, int[] preScaledWidthOut) {
Michael Jurka05713af2013-01-23 12:39:24 +0100345 // Load the preview image if possible
Michael Jurka05713af2013-01-23 12:39:24 +0100346 if (maxPreviewWidth < 0) maxPreviewWidth = Integer.MAX_VALUE;
Michael Jurka05713af2013-01-23 12:39:24 +0100347
348 Drawable drawable = null;
Sunny Goyalffe83f12014-08-14 17:39:34 -0700349 if (info.previewImage != 0) {
350 drawable = mManager.loadPreview(info);
Adrian Roosfa9ffc22014-05-12 15:59:59 +0200351 if (drawable != null) {
352 drawable = mutateOnMainThread(drawable);
353 } else {
Michael Jurka05713af2013-01-23 12:39:24 +0100354 Log.w(TAG, "Can't load widget preview drawable 0x" +
Sunny Goyalffe83f12014-08-14 17:39:34 -0700355 Integer.toHexString(info.previewImage) + " for provider: " + info.provider);
Michael Jurka05713af2013-01-23 12:39:24 +0100356 }
357 }
358
Sunny Goyal4cad7532015-03-18 15:56:30 -0700359 final boolean widgetPreviewExists = (drawable != null);
Adam Cohen2e6da152015-05-06 11:42:25 -0700360 final int spanX = info.getSpanX(launcher) < 1 ? 1 : info.getSpanX(launcher);
361 final int spanY = info.getSpanY(launcher) < 1 ? 1 : info.getSpanY(launcher);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700362
Michael Jurka05713af2013-01-23 12:39:24 +0100363 int previewWidth;
364 int previewHeight;
Sunny Goyal4cad7532015-03-18 15:56:30 -0700365 Bitmap tileBitmap = null;
366
Michael Jurka05713af2013-01-23 12:39:24 +0100367 if (widgetPreviewExists) {
368 previewWidth = drawable.getIntrinsicWidth();
369 previewHeight = drawable.getIntrinsicHeight();
370 } else {
371 // Generate a preview image if we couldn't load one
Sunny Goyal4cad7532015-03-18 15:56:30 -0700372 tileBitmap = ((BitmapDrawable) mContext.getResources().getDrawable(
373 R.drawable.widget_tile)).getBitmap();
374 previewWidth = tileBitmap.getWidth() * spanX;
375 previewHeight = tileBitmap.getHeight() * spanY;
Michael Jurka05713af2013-01-23 12:39:24 +0100376 }
377
378 // Scale to fit width only - let the widget preview be clipped in the
379 // vertical dimension
380 float scale = 1f;
381 if (preScaledWidthOut != null) {
382 preScaledWidthOut[0] = previewWidth;
383 }
384 if (previewWidth > maxPreviewWidth) {
385 scale = maxPreviewWidth / (float) previewWidth;
386 }
387 if (scale != 1f) {
388 previewWidth = (int) (scale * previewWidth);
389 previewHeight = (int) (scale * previewHeight);
390 }
391
392 // 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 -0700393 final Canvas c = new Canvas();
Michael Jurka05713af2013-01-23 12:39:24 +0100394 if (preview == null) {
395 preview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700396 c.setBitmap(preview);
397 } else {
398 // Reusing bitmap. Clear it.
399 c.setBitmap(preview);
400 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100401 }
402
403 // Draw the scaled preview into the final bitmap
404 int x = (preview.getWidth() - previewWidth) / 2;
405 if (widgetPreviewExists) {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700406 drawable.setBounds(x, 0, x + previewWidth, previewHeight);
407 drawable.draw(c);
Michael Jurka05713af2013-01-23 12:39:24 +0100408 } else {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700409 final Paint p = new Paint();
410 p.setFilterBitmap(true);
Adam Cohen2e6da152015-05-06 11:42:25 -0700411 int appIconSize = launcher.getDeviceProfile().iconSizePx;
Michael Jurka05713af2013-01-23 12:39:24 +0100412
Sunny Goyal4cad7532015-03-18 15:56:30 -0700413 // draw the spanX x spanY tiles
414 final Rect src = new Rect(0, 0, tileBitmap.getWidth(), tileBitmap.getHeight());
415
416 float tileW = scale * tileBitmap.getWidth();
417 float tileH = scale * tileBitmap.getHeight();
418 final RectF dst = new RectF(0, 0, tileW, tileH);
419
420 float tx = x;
421 for (int i = 0; i < spanX; i++, tx += tileW) {
422 float ty = 0;
423 for (int j = 0; j < spanY; j++, ty += tileH) {
424 dst.offsetTo(tx, ty);
425 c.drawBitmap(tileBitmap, src, dst, p);
426 }
Michael Jurka05713af2013-01-23 12:39:24 +0100427 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700428
429 // Draw the icon in the top left corner
430 // TODO: use top right for RTL
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700431 int minOffset = (int) (appIconSize * WIDGET_PREVIEW_ICON_PADDING_PERCENTAGE);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700432 int smallestSide = Math.min(previewWidth, previewHeight);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700433 float iconScale = Math.min((float) smallestSide / (appIconSize + 2 * minOffset), scale);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700434
435 try {
436 Drawable icon = mutateOnMainThread(mManager.loadIcon(info, mIconCache));
437 if (icon != null) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700438 int hoffset = (int) ((tileW - appIconSize * iconScale) / 2) + x;
439 int yoffset = (int) ((tileH - appIconSize * iconScale) / 2);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700440 icon.setBounds(hoffset, yoffset,
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700441 hoffset + (int) (appIconSize * iconScale),
442 yoffset + (int) (appIconSize * iconScale));
Sunny Goyal4cad7532015-03-18 15:56:30 -0700443 icon.draw(c);
444 }
445 } catch (Resources.NotFoundException e) { }
Michael Jurka05713af2013-01-23 12:39:24 +0100446 c.setBitmap(null);
447 }
Hyunyoung Song6babf2e2015-05-14 17:08:45 -0700448 return mManager.getBadgeBitmap(info, preview, Math.min(preview.getHeight(), previewHeight));
Michael Jurka05713af2013-01-23 12:39:24 +0100449 }
450
451 private Bitmap generateShortcutPreview(
Adam Cohen2e6da152015-05-06 11:42:25 -0700452 Launcher launcher, ResolveInfo info, int maxWidth, int maxHeight, Bitmap preview) {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700453 final Canvas c = new Canvas();
454 if (preview == null) {
Michael Jurka05713af2013-01-23 12:39:24 +0100455 preview = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700456 c.setBitmap(preview);
457 } else if (preview.getWidth() != maxWidth || preview.getHeight() != maxHeight) {
458 throw new RuntimeException("Improperly sized bitmap passed as argument");
459 } else {
460 // Reusing bitmap. Clear it.
461 c.setBitmap(preview);
462 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100463 }
464
Sunny Goyal4cad7532015-03-18 15:56:30 -0700465 Drawable icon = mutateOnMainThread(mIconCache.getFullResIcon(info.activityInfo));
466 icon.setFilterBitmap(true);
467
Michael Jurka05713af2013-01-23 12:39:24 +0100468 // Draw a desaturated/scaled version of the icon in the background as a watermark
Sunny Goyal4cad7532015-03-18 15:56:30 -0700469 ColorMatrix colorMatrix = new ColorMatrix();
470 colorMatrix.setSaturation(0);
471 icon.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
472 icon.setAlpha((int) (255 * 0.06f));
473
474 Resources res = mContext.getResources();
475 int paddingTop = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_top);
476 int paddingLeft = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_left);
477 int paddingRight = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_right);
478 int scaledIconWidth = (maxWidth - paddingLeft - paddingRight);
479 icon.setBounds(paddingLeft, paddingTop,
480 paddingLeft + scaledIconWidth, paddingTop + scaledIconWidth);
481 icon.draw(c);
482
483 // Draw the final icon at top left corner.
484 // TODO: use top right for RTL
Adam Cohen2e6da152015-05-06 11:42:25 -0700485 int appIconSize = launcher.getDeviceProfile().iconSizePx;
486
Sunny Goyal4cad7532015-03-18 15:56:30 -0700487 icon.setAlpha(255);
488 icon.setColorFilter(null);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700489 icon.setBounds(0, 0, appIconSize, appIconSize);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700490 icon.draw(c);
491
Michael Jurka05713af2013-01-23 12:39:24 +0100492 c.setBitmap(null);
Michael Jurka05713af2013-01-23 12:39:24 +0100493 return preview;
494 }
495
Adrian Roos65d60e22014-04-15 21:07:49 +0200496 private Drawable mutateOnMainThread(final Drawable drawable) {
497 try {
498 return mMainThreadExecutor.submit(new Callable<Drawable>() {
499 @Override
500 public Drawable call() throws Exception {
501 return drawable.mutate();
502 }
503 }).get();
504 } catch (InterruptedException e) {
505 Thread.currentThread().interrupt();
506 throw new RuntimeException(e);
507 } catch (ExecutionException e) {
508 throw new RuntimeException(e);
509 }
510 }
Adrian Roos1f375ab2014-04-28 18:26:38 +0200511
Adrian Roos1f375ab2014-04-28 18:26:38 +0200512 /**
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700513 * @return an array of containing versionCode and lastUpdatedTime for the package.
Adrian Roos1f375ab2014-04-28 18:26:38 +0200514 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700515 @Thunk long[] getPackageVersion(String packageName) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700516 synchronized (mPackageVersions) {
517 long[] versions = mPackageVersions.get(packageName);
518 if (versions == null) {
519 versions = new long[2];
Adrian Roos1f375ab2014-04-28 18:26:38 +0200520 try {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700521 PackageInfo info = mContext.getPackageManager().getPackageInfo(packageName, 0);
522 versions[0] = info.versionCode;
523 versions[1] = info.lastUpdateTime;
524 } catch (NameNotFoundException e) {
525 Log.e(TAG, "PackageInfo not found", e);
526 }
527 mPackageVersions.put(packageName, versions);
528 }
529 return versions;
530 }
531 }
532
533 /**
534 * A request Id which can be used by the client to cancel any request.
535 */
536 public class PreviewLoadRequest {
537
538 private final PreviewLoadTask mTask;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700539
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700540 public PreviewLoadRequest(PreviewLoadTask task) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700541 mTask = task;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700542 }
543
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700544 public void cleanup() {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700545 if (mTask != null) {
546 mTask.cancel(true);
547 }
548
Winson Chung05304db2015-05-18 16:53:20 -0700549 // This only handles the case where the PreviewLoadTask is cancelled after the task has
550 // successfully completed (including having written to disk when necessary). In the
551 // other cases where it is cancelled while the task is running, it will be cleaned up
552 // in the tasks's onCancelled() call, and if cancelled while the task is writing to
553 // disk, it will be cancelled in the task's onPostExecute() call.
554 if (mTask.mBitmapToRecycle != null) {
555 synchronized (mUnusedBitmaps) {
556 mUnusedBitmaps.add(mTask.mBitmapToRecycle);
557 }
558 mTask.mBitmapToRecycle = null;
Adrian Roos1f375ab2014-04-28 18:26:38 +0200559 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700560 }
561 }
562
563 public class PreviewLoadTask extends AsyncTask<Void, Void, Bitmap> {
Sunny Goyal316490e2015-06-02 09:38:28 -0700564 @Thunk final WidgetCacheKey mKey;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700565 private final Object mInfo;
566 private final int mPreviewHeight;
567 private final int mPreviewWidth;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700568 private final WidgetCell mCaller;
Sunny Goyal316490e2015-06-02 09:38:28 -0700569 @Thunk long[] mVersions;
570 @Thunk Bitmap mBitmapToRecycle;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700571
572 PreviewLoadTask(WidgetCacheKey key, Object info, int previewWidth,
Hyunyoung Song3f471442015-04-08 19:01:34 -0700573 int previewHeight, WidgetCell caller) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700574 mKey = key;
575 mInfo = info;
576 mPreviewHeight = previewHeight;
577 mPreviewWidth = previewWidth;
578 mCaller = caller;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700579 if (DEBUG) {
580 Log.d(TAG, String.format("%s, %s, %d, %d",
581 mKey, mInfo, mPreviewHeight, mPreviewWidth));
582 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700583 }
584
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700585 @Override
586 protected Bitmap doInBackground(Void... params) {
587 Bitmap unusedBitmap = null;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700588
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700589 synchronized (mUnusedBitmaps) {
Winson Chung05304db2015-05-18 16:53:20 -0700590 // If already cancelled before this gets to run in the background, then return early
591 if (isCancelled()) {
592 return null;
593 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700594 // Check if we can use a bitmap
595 for (Bitmap candidate : mUnusedBitmaps) {
596 if (candidate != null && candidate.isMutable() &&
597 candidate.getWidth() == mPreviewWidth &&
598 candidate.getHeight() == mPreviewHeight) {
599 unusedBitmap = candidate;
600 break;
601 }
602 }
603
604 if (unusedBitmap == null) {
605 unusedBitmap = Bitmap.createBitmap(mPreviewWidth, mPreviewHeight, Config.ARGB_8888);
606 } else {
607 mUnusedBitmaps.remove(unusedBitmap);
608 }
Adrian Roos1f375ab2014-04-28 18:26:38 +0200609 }
Winson Chung05304db2015-05-18 16:53:20 -0700610 // If cancelled now, don't bother reading the preview from the DB
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700611 if (isCancelled()) {
Winson Chung05304db2015-05-18 16:53:20 -0700612 return unusedBitmap;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700613 }
Winson Chung05304db2015-05-18 16:53:20 -0700614 Bitmap preview = readFromDb(mKey, unusedBitmap, this);
615 // Only consider generating the preview if we have not cancelled the task already
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700616 if (!isCancelled() && preview == null) {
617 // Fetch the version info before we generate the preview, so that, in-case the
618 // app was updated while we are generating the preview, we use the old version info,
619 // which would gets re-written next time.
Winson Chung05304db2015-05-18 16:53:20 -0700620 mVersions = getPackageVersion(mKey.componentName.getPackageName());
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700621
Adam Cohen2e6da152015-05-06 11:42:25 -0700622 Launcher launcher = (Launcher) mCaller.getContext();
623
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700624 // it's not in the db... we need to generate it
Adam Cohen2e6da152015-05-06 11:42:25 -0700625 preview = generatePreview(launcher, mInfo, unusedBitmap, mPreviewWidth, mPreviewHeight);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700626 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700627 return preview;
628 }
629
630 @Override
Winson Chung05304db2015-05-18 16:53:20 -0700631 protected void onPostExecute(final Bitmap preview) {
632 mCaller.applyPreview(preview);
633
634 // Write the generated preview to the DB in the worker thread
635 if (mVersions != null) {
636 mWorkerHandler.post(new Runnable() {
637 @Override
638 public void run() {
639 if (!isCancelled()) {
640 // If we are still using this preview, then write it to the DB and then
641 // let the normal clear mechanism recycle the bitmap
642 writeToDb(mKey, mVersions, preview);
643 mBitmapToRecycle = preview;
644 } else {
645 // If we've already cancelled, then skip writing the bitmap to the DB
646 // and manually add the bitmap back to the recycled set
647 synchronized (mUnusedBitmaps) {
648 mUnusedBitmaps.add(preview);
649 }
650 }
651 }
652 });
653 } else {
654 // If we don't need to write to disk, then ensure the preview gets recycled by
655 // the normal clear mechanism
656 mBitmapToRecycle = preview;
657 }
658 }
659
660 @Override
661 protected void onCancelled(Bitmap preview) {
662 // If we've cancelled while the task is running, then can return the bitmap to the
663 // recycled set immediately. Otherwise, it will be recycled after the preview is written
664 // to disk.
665 if (preview != null) {
666 synchronized (mUnusedBitmaps) {
667 mUnusedBitmaps.add(preview);
668 }
669 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700670 }
671 }
672
673 private static final class WidgetCacheKey extends ComponentKey {
674
675 // TODO: remove dependency on size
Sunny Goyal316490e2015-06-02 09:38:28 -0700676 @Thunk final String size;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700677
678 public WidgetCacheKey(ComponentName componentName, UserHandleCompat user, String size) {
679 super(componentName, user);
680 this.size = size;
681 }
682
683 @Override
684 public int hashCode() {
685 return super.hashCode() ^ size.hashCode();
686 }
687
688 @Override
689 public boolean equals(Object o) {
690 return super.equals(o) && ((WidgetCacheKey) o).size.equals(size);
Adrian Roos1f375ab2014-04-28 18:26:38 +0200691 }
692 }
Michael Jurka05713af2013-01-23 12:39:24 +0100693}