blob: 314dd8a60d32c4668f3945e053cc65330f7701e1 [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;
Michael Jurka05713af2013-01-23 12:39:24 +010013import android.graphics.Bitmap;
14import android.graphics.Bitmap.Config;
15import android.graphics.BitmapFactory;
16import android.graphics.Canvas;
17import android.graphics.ColorMatrix;
18import android.graphics.ColorMatrixColorFilter;
19import android.graphics.Paint;
20import android.graphics.PorterDuff;
21import android.graphics.Rect;
Sunny Goyal4cad7532015-03-18 15:56:30 -070022import android.graphics.RectF;
Michael Jurka05713af2013-01-23 12:39:24 +010023import android.graphics.drawable.BitmapDrawable;
24import android.graphics.drawable.Drawable;
25import android.os.AsyncTask;
Winson Chung05304db2015-05-18 16:53:20 -070026import android.os.Handler;
Michael Jurka05713af2013-01-23 12:39:24 +010027import android.util.Log;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070028import android.util.LongSparseArray;
Sunny Goyal383c5072015-06-12 21:18:53 -070029
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;
Sunny Goyal6f709362015-12-17 17:09:36 -080034import com.android.launcher3.util.SQLiteCacheHelper;
Adam Cohen091440a2015-03-18 14:16:05 -070035import com.android.launcher3.util.Thunk;
Hyunyoung Song3f471442015-04-08 19:01:34 -070036import com.android.launcher3.widget.WidgetCell;
Hyunyoung Song8821ca92015-05-04 16:28:20 -070037
38import java.util.ArrayList;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070039import java.util.Collections;
Michael Jurka05713af2013-01-23 12:39:24 +010040import java.util.HashMap;
41import java.util.HashSet;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070042import java.util.Set;
43import java.util.WeakHashMap;
Adrian Roos65d60e22014-04-15 21:07:49 +020044import java.util.concurrent.Callable;
45import java.util.concurrent.ExecutionException;
Michael Jurka05713af2013-01-23 12:39:24 +010046
Sunny Goyalffe83f12014-08-14 17:39:34 -070047public class WidgetPreviewLoader {
Michael Jurka05713af2013-01-23 12:39:24 +010048
Sunny Goyalffe83f12014-08-14 17:39:34 -070049 private static final String TAG = "WidgetPreviewLoader";
Hyunyoung Song3f471442015-04-08 19:01:34 -070050 private static final boolean DEBUG = false;
Sunny Goyalffe83f12014-08-14 17:39:34 -070051
52 private static final float WIDGET_PREVIEW_ICON_PADDING_PERCENTAGE = 0.25f;
Sunny Goyalffe83f12014-08-14 17:39:34 -070053
Sunny Goyal5b0e6692015-03-19 14:31:19 -070054 private final HashMap<String, long[]> mPackageVersions = new HashMap<>();
Hyunyoung Song559d90d2015-04-28 15:06:45 -070055
56 /**
57 * Weak reference objects, do not prevent their referents from being made finalizable,
58 * finalized, and then reclaimed.
Hyunyoung Songe98f4a42015-06-16 10:45:24 -070059 * Note: synchronized block used for this variable is expensive and the block should always
60 * be posted to a background thread.
Hyunyoung Song559d90d2015-04-28 15:06:45 -070061 */
Sunny Goyalb4cbea42015-06-16 15:10:36 -070062 @Thunk final Set<Bitmap> mUnusedBitmaps =
Hyunyoung Song559d90d2015-04-28 15:06:45 -070063 Collections.newSetFromMap(new WeakHashMap<Bitmap, Boolean>());
Sunny Goyal4cad7532015-03-18 15:56:30 -070064
65 private final Context mContext;
Sunny Goyalffe83f12014-08-14 17:39:34 -070066 private final IconCache mIconCache;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070067 private final UserManagerCompat mUserManager;
Hyunyoung Song3e840f42016-03-01 11:57:44 -080068 private final AppWidgetManagerCompat mWidgetManager;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070069 private final CacheDb mDb;
Hyunyoung Song41e33692015-06-15 12:26:54 -070070 private final int mProfileBadgeMargin;
Michael Jurka05713af2013-01-23 12:39:24 +010071
Adrian Roos65d60e22014-04-15 21:07:49 +020072 private final MainThreadExecutor mMainThreadExecutor = new MainThreadExecutor();
Sunny Goyal316490e2015-06-02 09:38:28 -070073 @Thunk final Handler mWorkerHandler;
Adrian Roos65d60e22014-04-15 21:07:49 +020074
Sunny Goyal383c5072015-06-12 21:18:53 -070075 public WidgetPreviewLoader(Context context, IconCache iconCache) {
Chris Wrenfd13c712013-09-27 15:45:19 -040076 mContext = context;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070077 mIconCache = iconCache;
Hyunyoung Song3e840f42016-03-01 11:57:44 -080078 mWidgetManager = AppWidgetManagerCompat.getInstance(context);
Sunny Goyal5b0e6692015-03-19 14:31:19 -070079 mUserManager = UserManagerCompat.getInstance(context);
80 mDb = new CacheDb(context);
Winson Chung05304db2015-05-18 16:53:20 -070081 mWorkerHandler = new Handler(LauncherModel.getWorkerLooper());
Hyunyoung Song41e33692015-06-15 12:26:54 -070082 mProfileBadgeMargin = context.getResources()
83 .getDimensionPixelSize(R.dimen.profile_badge_margin);
Michael Jurka3f4e0702013-02-05 11:21:28 +010084 }
Sunny Goyalffe83f12014-08-14 17:39:34 -070085
Sunny Goyal5b0e6692015-03-19 14:31:19 -070086 /**
87 * Generates the widget preview on {@link AsyncTask#THREAD_POOL_EXECUTOR}. Must be
88 * called on UI thread
89 *
90 * @param o either {@link LauncherAppWidgetProviderInfo} or {@link ResolveInfo}
Sunny Goyal5b0e6692015-03-19 14:31:19 -070091 * @return a request id which can be used to cancel the request.
92 */
Adam Cohen2e6da152015-05-06 11:42:25 -070093 public PreviewLoadRequest getPreview(final Object o, int previewWidth,
94 int previewHeight, WidgetCell caller) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -070095 String size = previewWidth + "x" + previewHeight;
96 WidgetCacheKey key = getObjectKey(o, size);
Michael Jurka3f4e0702013-02-05 11:21:28 +010097
Sunny Goyal5b0e6692015-03-19 14:31:19 -070098 PreviewLoadTask task = new PreviewLoadTask(key, o, previewWidth, previewHeight, caller);
Sunny Goyal8ac727b2015-09-23 15:38:09 -070099 task.executeOnExecutor(Utilities.THREAD_POOL_EXECUTOR);
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700100 return new PreviewLoadRequest(task);
Michael Jurka05713af2013-01-23 12:39:24 +0100101 }
102
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700103 /**
104 * The DB holds the generated previews for various components. Previews can also have different
105 * sizes (landscape vs portrait).
106 */
Sunny Goyal6f709362015-12-17 17:09:36 -0800107 private static class CacheDb extends SQLiteCacheHelper {
Sunny Goyal2d648b02015-08-11 13:56:28 -0700108 private static final int DB_VERSION = 4;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700109
110 private static final String TABLE_NAME = "shortcut_and_widget_previews";
111 private static final String COLUMN_COMPONENT = "componentName";
112 private static final String COLUMN_USER = "profileId";
113 private static final String COLUMN_SIZE = "size";
114 private static final String COLUMN_PACKAGE = "packageName";
115 private static final String COLUMN_LAST_UPDATED = "lastUpdated";
116 private static final String COLUMN_VERSION = "version";
117 private static final String COLUMN_PREVIEW_BITMAP = "preview_bitmap";
Michael Jurka05713af2013-01-23 12:39:24 +0100118
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100119 public CacheDb(Context context) {
Sunny Goyal6f709362015-12-17 17:09:36 -0800120 super(context, LauncherFiles.WIDGET_PREVIEWS_DB, DB_VERSION, TABLE_NAME);
Michael Jurka05713af2013-01-23 12:39:24 +0100121 }
122
123 @Override
Sunny Goyal6f709362015-12-17 17:09:36 -0800124 public void onCreateTable(SQLiteDatabase database) {
Michael Jurka32b7a092013-02-07 20:06:49 +0100125 database.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" +
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700126 COLUMN_COMPONENT + " TEXT NOT NULL, " +
127 COLUMN_USER + " INTEGER NOT NULL, " +
Michael Jurka05713af2013-01-23 12:39:24 +0100128 COLUMN_SIZE + " TEXT NOT NULL, " +
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700129 COLUMN_PACKAGE + " TEXT NOT NULL, " +
130 COLUMN_LAST_UPDATED + " INTEGER NOT NULL DEFAULT 0, " +
131 COLUMN_VERSION + " INTEGER NOT NULL DEFAULT 0, " +
132 COLUMN_PREVIEW_BITMAP + " BLOB, " +
133 "PRIMARY KEY (" + COLUMN_COMPONENT + ", " + COLUMN_USER + ", " + COLUMN_SIZE + ") " +
Michael Jurka32b7a092013-02-07 20:06:49 +0100134 ");");
Michael Jurka05713af2013-01-23 12:39:24 +0100135 }
Michael Jurka05713af2013-01-23 12:39:24 +0100136 }
137
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700138 private WidgetCacheKey getObjectKey(Object o, String size) {
Michael Jurka05713af2013-01-23 12:39:24 +0100139 // should cache the string builder
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700140 if (o instanceof LauncherAppWidgetProviderInfo) {
141 LauncherAppWidgetProviderInfo info = (LauncherAppWidgetProviderInfo) o;
Hyunyoung Song3e840f42016-03-01 11:57:44 -0800142 return new WidgetCacheKey(info.provider, mWidgetManager.getUser(info), size);
Michael Jurka05713af2013-01-23 12:39:24 +0100143 } else {
144 ResolveInfo info = (ResolveInfo) o;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700145 return new WidgetCacheKey(
146 new ComponentName(info.activityInfo.packageName, info.activityInfo.name),
147 UserHandleCompat.myUserHandle(), size);
Michael Jurka05713af2013-01-23 12:39:24 +0100148 }
149 }
150
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700151 @Thunk void writeToDb(WidgetCacheKey key, long[] versions, Bitmap preview) {
Michael Jurka05713af2013-01-23 12:39:24 +0100152 ContentValues values = new ContentValues();
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700153 values.put(CacheDb.COLUMN_COMPONENT, key.componentName.flattenToShortString());
154 values.put(CacheDb.COLUMN_USER, mUserManager.getSerialNumberForUser(key.user));
155 values.put(CacheDb.COLUMN_SIZE, key.size);
156 values.put(CacheDb.COLUMN_PACKAGE, key.componentName.getPackageName());
157 values.put(CacheDb.COLUMN_VERSION, versions[0]);
158 values.put(CacheDb.COLUMN_LAST_UPDATED, versions[1]);
159 values.put(CacheDb.COLUMN_PREVIEW_BITMAP, Utilities.flattenBitmap(preview));
Sunny Goyal6f709362015-12-17 17:09:36 -0800160 mDb.insertOrReplace(values);
Michael Jurka05713af2013-01-23 12:39:24 +0100161 }
162
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700163 public void removePackage(String packageName, UserHandleCompat user) {
164 removePackage(packageName, user, mUserManager.getSerialNumberForUser(user));
165 }
166
167 private void removePackage(String packageName, UserHandleCompat user, long userSerial) {
168 synchronized(mPackageVersions) {
169 mPackageVersions.remove(packageName);
170 }
171
Sunny Goyal6f709362015-12-17 17:09:36 -0800172 mDb.delete(
173 CacheDb.COLUMN_PACKAGE + " = ? AND " + CacheDb.COLUMN_USER + " = ?",
174 new String[]{packageName, Long.toString(userSerial)});
Michael Jurka8ff02ca2013-11-01 14:19:27 +0100175 }
176
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700177 /**
178 * Updates the persistent DB:
179 * 1. Any preview generated for an old package version is removed
180 * 2. Any preview for an absent package is removed
181 * This ensures that we remove entries for packages which changed while the launcher was dead.
182 */
Hyunyoung Song8821ca92015-05-04 16:28:20 -0700183 public void removeObsoletePreviews(ArrayList<Object> list) {
Hyunyoung Song2bd3d7d2015-05-21 13:04:53 -0700184 Utilities.assertWorkerThread();
Hyunyoung Song8821ca92015-05-04 16:28:20 -0700185
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700186 LongSparseArray<HashSet<String>> validPackages = new LongSparseArray<>();
187
Hyunyoung Song8821ca92015-05-04 16:28:20 -0700188 for (Object obj : list) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700189 final UserHandleCompat user;
190 final String pkg;
191 if (obj instanceof ResolveInfo) {
192 user = UserHandleCompat.myUserHandle();
193 pkg = ((ResolveInfo) obj).activityInfo.packageName;
194 } else {
195 LauncherAppWidgetProviderInfo info = (LauncherAppWidgetProviderInfo) obj;
Hyunyoung Song3e840f42016-03-01 11:57:44 -0800196 user = mWidgetManager.getUser(info);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700197 pkg = info.provider.getPackageName();
198 }
199
Sunny Goyala2a039b2015-08-05 13:22:21 -0700200 final long userId = mUserManager.getSerialNumberForUser(user);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700201 HashSet<String> packages = validPackages.get(userId);
202 if (packages == null) {
203 packages = new HashSet<>();
204 validPackages.put(userId, packages);
205 }
206 packages.add(pkg);
Michael Jurka05713af2013-01-23 12:39:24 +0100207 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700208
209 LongSparseArray<HashSet<String>> packagesToDelete = new LongSparseArray<>();
210 Cursor c = null;
211 try {
Sunny Goyal6f709362015-12-17 17:09:36 -0800212 c = mDb.query(
213 new String[]{CacheDb.COLUMN_USER, CacheDb.COLUMN_PACKAGE,
214 CacheDb.COLUMN_LAST_UPDATED, CacheDb.COLUMN_VERSION},
215 null, null);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700216 while (c.moveToNext()) {
217 long userId = c.getLong(0);
218 String pkg = c.getString(1);
219 long lastUpdated = c.getLong(2);
220 long version = c.getLong(3);
221
222 HashSet<String> packages = validPackages.get(userId);
223 if (packages != null && packages.contains(pkg)) {
224 long[] versions = getPackageVersion(pkg);
225 if (versions[0] == version && versions[1] == lastUpdated) {
226 // Every thing checks out
227 continue;
228 }
229 }
230
231 // We need to delete this package.
232 packages = packagesToDelete.get(userId);
233 if (packages == null) {
234 packages = new HashSet<>();
235 packagesToDelete.put(userId, packages);
236 }
237 packages.add(pkg);
238 }
239
240 for (int i = 0; i < packagesToDelete.size(); i++) {
241 long userId = packagesToDelete.keyAt(i);
242 UserHandleCompat user = mUserManager.getUserForSerialNumber(userId);
243 for (String pkg : packagesToDelete.valueAt(i)) {
244 removePackage(pkg, user, userId);
245 }
246 }
247 } catch (SQLException e) {
Sunny Goyal6f709362015-12-17 17:09:36 -0800248 Log.e(TAG, "Error updating widget previews", e);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700249 } finally {
250 if (c != null) {
251 c.close();
252 }
253 }
254 }
255
Winson Chung05304db2015-05-18 16:53:20 -0700256 /**
257 * Reads the preview bitmap from the DB or null if the preview is not in the DB.
258 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700259 @Thunk Bitmap readFromDb(WidgetCacheKey key, Bitmap recycle, PreviewLoadTask loadTask) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700260 Cursor cursor = null;
261 try {
Sunny Goyal6f709362015-12-17 17:09:36 -0800262 cursor = mDb.query(
263 new String[]{CacheDb.COLUMN_PREVIEW_BITMAP},
264 CacheDb.COLUMN_COMPONENT + " = ? AND " + CacheDb.COLUMN_USER + " = ? AND "
265 + CacheDb.COLUMN_SIZE + " = ?",
266 new String[]{
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700267 key.componentName.flattenToString(),
268 Long.toString(mUserManager.getSerialNumberForUser(key.user)),
269 key.size
Sunny Goyal6f709362015-12-17 17:09:36 -0800270 });
Winson Chung05304db2015-05-18 16:53:20 -0700271 // If cancelled, skip getting the blob and decoding it into a bitmap
272 if (loadTask.isCancelled()) {
273 return null;
274 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700275 if (cursor.moveToNext()) {
276 byte[] blob = cursor.getBlob(0);
277 BitmapFactory.Options opts = new BitmapFactory.Options();
278 opts.inBitmap = recycle;
Michael Jurka6e27f642013-12-10 13:40:30 +0100279 try {
Winson Chung05304db2015-05-18 16:53:20 -0700280 if (!loadTask.isCancelled()) {
281 return BitmapFactory.decodeByteArray(blob, 0, blob.length, opts);
282 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700283 } catch (Exception e) {
284 return null;
Michael Jurka6e27f642013-12-10 13:40:30 +0100285 }
Michael Jurka05713af2013-01-23 12:39:24 +0100286 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700287 } catch (SQLException e) {
288 Log.w(TAG, "Error loading preview from DB", e);
289 } finally {
290 if (cursor != null) {
291 cursor.close();
292 }
293 }
294 return null;
Michael Jurka05713af2013-01-23 12:39:24 +0100295 }
296
Sunny Goyal316490e2015-06-02 09:38:28 -0700297 @Thunk Bitmap generatePreview(Launcher launcher, Object info, Bitmap recycle,
Adam Cohen2e6da152015-05-06 11:42:25 -0700298 int previewWidth, int previewHeight) {
Adam Cohen59400422014-03-05 18:07:04 -0800299 if (info instanceof LauncherAppWidgetProviderInfo) {
Adam Cohen2e6da152015-05-06 11:42:25 -0700300 return generateWidgetPreview(launcher, (LauncherAppWidgetProviderInfo) info,
301 previewWidth, recycle, null);
Michael Jurka05713af2013-01-23 12:39:24 +0100302 } else {
Adam Cohen2e6da152015-05-06 11:42:25 -0700303 return generateShortcutPreview(launcher,
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700304 (ResolveInfo) info, previewWidth, previewHeight, recycle);
Michael Jurka05713af2013-01-23 12:39:24 +0100305 }
306 }
307
Hyunyoung Song3e840f42016-03-01 11:57:44 -0800308 /**
309 * Generates the widget preview from either the {@link AppWidgetManagerCompat} or cache
310 * and add badge at the bottom right corner.
311 *
312 * @param launcher
313 * @param info information about the widget
314 * @param maxPreviewWidth width of the preview on either workspace or tray
315 * @param preview bitmap that can be recycled
316 * @param preScaledWidthOut return the width of the returned bitmap
317 * @return
318 */
Adam Cohen2e6da152015-05-06 11:42:25 -0700319 public Bitmap generateWidgetPreview(Launcher launcher, LauncherAppWidgetProviderInfo info,
Sunny Goyal4cad7532015-03-18 15:56:30 -0700320 int maxPreviewWidth, Bitmap preview, int[] preScaledWidthOut) {
Michael Jurka05713af2013-01-23 12:39:24 +0100321 // Load the preview image if possible
Michael Jurka05713af2013-01-23 12:39:24 +0100322 if (maxPreviewWidth < 0) maxPreviewWidth = Integer.MAX_VALUE;
Michael Jurka05713af2013-01-23 12:39:24 +0100323
324 Drawable drawable = null;
Sunny Goyalffe83f12014-08-14 17:39:34 -0700325 if (info.previewImage != 0) {
Hyunyoung Song3e840f42016-03-01 11:57:44 -0800326 drawable = mWidgetManager.loadPreview(info);
Adrian Roosfa9ffc22014-05-12 15:59:59 +0200327 if (drawable != null) {
328 drawable = mutateOnMainThread(drawable);
329 } else {
Michael Jurka05713af2013-01-23 12:39:24 +0100330 Log.w(TAG, "Can't load widget preview drawable 0x" +
Sunny Goyalffe83f12014-08-14 17:39:34 -0700331 Integer.toHexString(info.previewImage) + " for provider: " + info.provider);
Michael Jurka05713af2013-01-23 12:39:24 +0100332 }
333 }
334
Sunny Goyal4cad7532015-03-18 15:56:30 -0700335 final boolean widgetPreviewExists = (drawable != null);
Sunny Goyal233ee962015-08-03 13:05:01 -0700336 final int spanX = info.spanX;
337 final int spanY = info.spanY;
Sunny Goyal4cad7532015-03-18 15:56:30 -0700338
Michael Jurka05713af2013-01-23 12:39:24 +0100339 int previewWidth;
340 int previewHeight;
Hyunyoung Song3e840f42016-03-01 11:57:44 -0800341
Sunny Goyal4cad7532015-03-18 15:56:30 -0700342 Bitmap tileBitmap = null;
343
Michael Jurka05713af2013-01-23 12:39:24 +0100344 if (widgetPreviewExists) {
345 previewWidth = drawable.getIntrinsicWidth();
346 previewHeight = drawable.getIntrinsicHeight();
347 } else {
348 // Generate a preview image if we couldn't load one
Sunny Goyal4cad7532015-03-18 15:56:30 -0700349 tileBitmap = ((BitmapDrawable) mContext.getResources().getDrawable(
350 R.drawable.widget_tile)).getBitmap();
351 previewWidth = tileBitmap.getWidth() * spanX;
352 previewHeight = tileBitmap.getHeight() * spanY;
Michael Jurka05713af2013-01-23 12:39:24 +0100353 }
354
355 // Scale to fit width only - let the widget preview be clipped in the
356 // vertical dimension
357 float scale = 1f;
358 if (preScaledWidthOut != null) {
359 preScaledWidthOut[0] = previewWidth;
360 }
361 if (previewWidth > maxPreviewWidth) {
Hyunyoung Songb9f932e2015-07-30 15:04:59 -0700362 scale = (maxPreviewWidth - 2 * mProfileBadgeMargin) / (float) (previewWidth);
Michael Jurka05713af2013-01-23 12:39:24 +0100363 }
364 if (scale != 1f) {
365 previewWidth = (int) (scale * previewWidth);
366 previewHeight = (int) (scale * previewHeight);
367 }
368
369 // 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 -0700370 final Canvas c = new Canvas();
Michael Jurka05713af2013-01-23 12:39:24 +0100371 if (preview == null) {
372 preview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700373 c.setBitmap(preview);
374 } else {
375 // Reusing bitmap. Clear it.
376 c.setBitmap(preview);
377 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100378 }
379
380 // Draw the scaled preview into the final bitmap
Hyunyoung Songb9f932e2015-07-30 15:04:59 -0700381 int x = (preview.getWidth() - previewWidth) / 2;
Michael Jurka05713af2013-01-23 12:39:24 +0100382 if (widgetPreviewExists) {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700383 drawable.setBounds(x, 0, x + previewWidth, previewHeight);
384 drawable.draw(c);
Michael Jurka05713af2013-01-23 12:39:24 +0100385 } else {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700386 final Paint p = new Paint();
387 p.setFilterBitmap(true);
Adam Cohen2e6da152015-05-06 11:42:25 -0700388 int appIconSize = launcher.getDeviceProfile().iconSizePx;
Michael Jurka05713af2013-01-23 12:39:24 +0100389
Sunny Goyal4cad7532015-03-18 15:56:30 -0700390 // draw the spanX x spanY tiles
391 final Rect src = new Rect(0, 0, tileBitmap.getWidth(), tileBitmap.getHeight());
392
393 float tileW = scale * tileBitmap.getWidth();
394 float tileH = scale * tileBitmap.getHeight();
395 final RectF dst = new RectF(0, 0, tileW, tileH);
396
397 float tx = x;
398 for (int i = 0; i < spanX; i++, tx += tileW) {
399 float ty = 0;
400 for (int j = 0; j < spanY; j++, ty += tileH) {
401 dst.offsetTo(tx, ty);
402 c.drawBitmap(tileBitmap, src, dst, p);
403 }
Michael Jurka05713af2013-01-23 12:39:24 +0100404 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700405
406 // Draw the icon in the top left corner
407 // TODO: use top right for RTL
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700408 int minOffset = (int) (appIconSize * WIDGET_PREVIEW_ICON_PADDING_PERCENTAGE);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700409 int smallestSide = Math.min(previewWidth, previewHeight);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700410 float iconScale = Math.min((float) smallestSide / (appIconSize + 2 * minOffset), scale);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700411
412 try {
Hyunyoung Song3e840f42016-03-01 11:57:44 -0800413 Drawable icon = mWidgetManager.loadIcon(info, mIconCache);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700414 if (icon != null) {
Sunny Goyal1ba7e362015-10-26 10:42:12 -0700415 icon = mutateOnMainThread(icon);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700416 int hoffset = (int) ((tileW - appIconSize * iconScale) / 2) + x;
417 int yoffset = (int) ((tileH - appIconSize * iconScale) / 2);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700418 icon.setBounds(hoffset, yoffset,
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700419 hoffset + (int) (appIconSize * iconScale),
420 yoffset + (int) (appIconSize * iconScale));
Sunny Goyal4cad7532015-03-18 15:56:30 -0700421 icon.draw(c);
422 }
Hyunyoung Song3e840f42016-03-01 11:57:44 -0800423 } catch (Resources.NotFoundException e) {
424 }
Michael Jurka05713af2013-01-23 12:39:24 +0100425 c.setBitmap(null);
426 }
Hyunyoung Song3e840f42016-03-01 11:57:44 -0800427 int imageWidth = Math.min(preview.getWidth(), previewWidth + mProfileBadgeMargin);
Hyunyoung Song41e33692015-06-15 12:26:54 -0700428 int imageHeight = Math.min(preview.getHeight(), previewHeight + mProfileBadgeMargin);
Hyunyoung Song3e840f42016-03-01 11:57:44 -0800429 return mWidgetManager.getBadgeBitmap(info, preview, imageWidth, imageHeight);
Michael Jurka05713af2013-01-23 12:39:24 +0100430 }
431
432 private Bitmap generateShortcutPreview(
Adam Cohen2e6da152015-05-06 11:42:25 -0700433 Launcher launcher, ResolveInfo info, int maxWidth, int maxHeight, Bitmap preview) {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700434 final Canvas c = new Canvas();
435 if (preview == null) {
Michael Jurka05713af2013-01-23 12:39:24 +0100436 preview = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700437 c.setBitmap(preview);
438 } else if (preview.getWidth() != maxWidth || preview.getHeight() != maxHeight) {
439 throw new RuntimeException("Improperly sized bitmap passed as argument");
440 } else {
441 // Reusing bitmap. Clear it.
442 c.setBitmap(preview);
443 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100444 }
445
Sunny Goyal4cad7532015-03-18 15:56:30 -0700446 Drawable icon = mutateOnMainThread(mIconCache.getFullResIcon(info.activityInfo));
447 icon.setFilterBitmap(true);
448
Michael Jurka05713af2013-01-23 12:39:24 +0100449 // Draw a desaturated/scaled version of the icon in the background as a watermark
Sunny Goyal4cad7532015-03-18 15:56:30 -0700450 ColorMatrix colorMatrix = new ColorMatrix();
451 colorMatrix.setSaturation(0);
452 icon.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
453 icon.setAlpha((int) (255 * 0.06f));
454
455 Resources res = mContext.getResources();
456 int paddingTop = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_top);
457 int paddingLeft = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_left);
458 int paddingRight = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_right);
459 int scaledIconWidth = (maxWidth - paddingLeft - paddingRight);
460 icon.setBounds(paddingLeft, paddingTop,
461 paddingLeft + scaledIconWidth, paddingTop + scaledIconWidth);
462 icon.draw(c);
463
464 // Draw the final icon at top left corner.
465 // TODO: use top right for RTL
Adam Cohen2e6da152015-05-06 11:42:25 -0700466 int appIconSize = launcher.getDeviceProfile().iconSizePx;
467
Sunny Goyal4cad7532015-03-18 15:56:30 -0700468 icon.setAlpha(255);
469 icon.setColorFilter(null);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700470 icon.setBounds(0, 0, appIconSize, appIconSize);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700471 icon.draw(c);
472
Michael Jurka05713af2013-01-23 12:39:24 +0100473 c.setBitmap(null);
Michael Jurka05713af2013-01-23 12:39:24 +0100474 return preview;
475 }
476
Adrian Roos65d60e22014-04-15 21:07:49 +0200477 private Drawable mutateOnMainThread(final Drawable drawable) {
478 try {
479 return mMainThreadExecutor.submit(new Callable<Drawable>() {
480 @Override
481 public Drawable call() throws Exception {
482 return drawable.mutate();
483 }
484 }).get();
485 } catch (InterruptedException e) {
486 Thread.currentThread().interrupt();
487 throw new RuntimeException(e);
488 } catch (ExecutionException e) {
489 throw new RuntimeException(e);
490 }
491 }
Adrian Roos1f375ab2014-04-28 18:26:38 +0200492
Adrian Roos1f375ab2014-04-28 18:26:38 +0200493 /**
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700494 * @return an array of containing versionCode and lastUpdatedTime for the package.
Adrian Roos1f375ab2014-04-28 18:26:38 +0200495 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700496 @Thunk long[] getPackageVersion(String packageName) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700497 synchronized (mPackageVersions) {
498 long[] versions = mPackageVersions.get(packageName);
499 if (versions == null) {
500 versions = new long[2];
Adrian Roos1f375ab2014-04-28 18:26:38 +0200501 try {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700502 PackageInfo info = mContext.getPackageManager().getPackageInfo(packageName, 0);
503 versions[0] = info.versionCode;
504 versions[1] = info.lastUpdateTime;
505 } catch (NameNotFoundException e) {
506 Log.e(TAG, "PackageInfo not found", e);
507 }
508 mPackageVersions.put(packageName, versions);
509 }
510 return versions;
511 }
512 }
513
514 /**
515 * A request Id which can be used by the client to cancel any request.
516 */
517 public class PreviewLoadRequest {
518
Sunny Goyalb4cbea42015-06-16 15:10:36 -0700519 @Thunk final PreviewLoadTask mTask;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700520
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700521 public PreviewLoadRequest(PreviewLoadTask task) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700522 mTask = task;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700523 }
524
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700525 public void cleanup() {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700526 if (mTask != null) {
527 mTask.cancel(true);
528 }
529
Winson Chung05304db2015-05-18 16:53:20 -0700530 // This only handles the case where the PreviewLoadTask is cancelled after the task has
531 // successfully completed (including having written to disk when necessary). In the
532 // other cases where it is cancelled while the task is running, it will be cleaned up
533 // in the tasks's onCancelled() call, and if cancelled while the task is writing to
534 // disk, it will be cancelled in the task's onPostExecute() call.
535 if (mTask.mBitmapToRecycle != null) {
Hyunyoung Songe98f4a42015-06-16 10:45:24 -0700536 mWorkerHandler.post(new Runnable() {
537 @Override
538 public void run() {
539 synchronized (mUnusedBitmaps) {
540 mUnusedBitmaps.add(mTask.mBitmapToRecycle);
541 }
542 mTask.mBitmapToRecycle = null;
543 }
544 });
Adrian Roos1f375ab2014-04-28 18:26:38 +0200545 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700546 }
547 }
548
549 public class PreviewLoadTask extends AsyncTask<Void, Void, Bitmap> {
Sunny Goyal316490e2015-06-02 09:38:28 -0700550 @Thunk final WidgetCacheKey mKey;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700551 private final Object mInfo;
552 private final int mPreviewHeight;
553 private final int mPreviewWidth;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700554 private final WidgetCell mCaller;
Sunny Goyal316490e2015-06-02 09:38:28 -0700555 @Thunk long[] mVersions;
556 @Thunk Bitmap mBitmapToRecycle;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700557
558 PreviewLoadTask(WidgetCacheKey key, Object info, int previewWidth,
Hyunyoung Song3f471442015-04-08 19:01:34 -0700559 int previewHeight, WidgetCell caller) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700560 mKey = key;
561 mInfo = info;
562 mPreviewHeight = previewHeight;
563 mPreviewWidth = previewWidth;
564 mCaller = caller;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700565 if (DEBUG) {
566 Log.d(TAG, String.format("%s, %s, %d, %d",
567 mKey, mInfo, mPreviewHeight, mPreviewWidth));
568 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700569 }
570
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700571 @Override
572 protected Bitmap doInBackground(Void... params) {
573 Bitmap unusedBitmap = null;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700574
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700575 // If already cancelled before this gets to run in the background, then return early
576 if (isCancelled()) {
577 return null;
578 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700579 synchronized (mUnusedBitmaps) {
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700580 // Check if we can re-use a bitmap
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700581 for (Bitmap candidate : mUnusedBitmaps) {
582 if (candidate != null && candidate.isMutable() &&
583 candidate.getWidth() == mPreviewWidth &&
584 candidate.getHeight() == mPreviewHeight) {
585 unusedBitmap = candidate;
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700586 mUnusedBitmaps.remove(unusedBitmap);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700587 break;
588 }
589 }
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700590 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700591
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700592 // creating a bitmap is expensive. Do not do this inside synchronized block.
593 if (unusedBitmap == null) {
594 unusedBitmap = Bitmap.createBitmap(mPreviewWidth, mPreviewHeight, Config.ARGB_8888);
Adrian Roos1f375ab2014-04-28 18:26:38 +0200595 }
Winson Chung05304db2015-05-18 16:53:20 -0700596 // If cancelled now, don't bother reading the preview from the DB
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700597 if (isCancelled()) {
Winson Chung05304db2015-05-18 16:53:20 -0700598 return unusedBitmap;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700599 }
Winson Chung05304db2015-05-18 16:53:20 -0700600 Bitmap preview = readFromDb(mKey, unusedBitmap, this);
601 // Only consider generating the preview if we have not cancelled the task already
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700602 if (!isCancelled() && preview == null) {
603 // Fetch the version info before we generate the preview, so that, in-case the
604 // app was updated while we are generating the preview, we use the old version info,
605 // which would gets re-written next time.
Winson Chung05304db2015-05-18 16:53:20 -0700606 mVersions = getPackageVersion(mKey.componentName.getPackageName());
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700607
Adam Cohen2e6da152015-05-06 11:42:25 -0700608 Launcher launcher = (Launcher) mCaller.getContext();
609
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700610 // it's not in the db... we need to generate it
Adam Cohen2e6da152015-05-06 11:42:25 -0700611 preview = generatePreview(launcher, mInfo, unusedBitmap, mPreviewWidth, mPreviewHeight);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700612 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700613 return preview;
614 }
615
616 @Override
Winson Chung05304db2015-05-18 16:53:20 -0700617 protected void onPostExecute(final Bitmap preview) {
618 mCaller.applyPreview(preview);
619
620 // Write the generated preview to the DB in the worker thread
621 if (mVersions != null) {
622 mWorkerHandler.post(new Runnable() {
623 @Override
624 public void run() {
625 if (!isCancelled()) {
626 // If we are still using this preview, then write it to the DB and then
627 // let the normal clear mechanism recycle the bitmap
628 writeToDb(mKey, mVersions, preview);
629 mBitmapToRecycle = preview;
630 } else {
631 // If we've already cancelled, then skip writing the bitmap to the DB
632 // and manually add the bitmap back to the recycled set
633 synchronized (mUnusedBitmaps) {
634 mUnusedBitmaps.add(preview);
635 }
636 }
637 }
638 });
639 } else {
640 // If we don't need to write to disk, then ensure the preview gets recycled by
641 // the normal clear mechanism
642 mBitmapToRecycle = preview;
643 }
644 }
645
646 @Override
Hyunyoung Songe98f4a42015-06-16 10:45:24 -0700647 protected void onCancelled(final Bitmap preview) {
Winson Chung05304db2015-05-18 16:53:20 -0700648 // If we've cancelled while the task is running, then can return the bitmap to the
649 // recycled set immediately. Otherwise, it will be recycled after the preview is written
650 // to disk.
651 if (preview != null) {
Hyunyoung Songe98f4a42015-06-16 10:45:24 -0700652 mWorkerHandler.post(new Runnable() {
653 @Override
654 public void run() {
655 synchronized (mUnusedBitmaps) {
656 mUnusedBitmaps.add(preview);
657 }
658 }
659 });
Winson Chung05304db2015-05-18 16:53:20 -0700660 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700661 }
662 }
663
664 private static final class WidgetCacheKey extends ComponentKey {
665
666 // TODO: remove dependency on size
Sunny Goyal316490e2015-06-02 09:38:28 -0700667 @Thunk final String size;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700668
669 public WidgetCacheKey(ComponentName componentName, UserHandleCompat user, String size) {
670 super(componentName, user);
671 this.size = size;
672 }
673
674 @Override
675 public int hashCode() {
676 return super.hashCode() ^ size.hashCode();
677 }
678
679 @Override
680 public boolean equals(Object o) {
681 return super.equals(o) && ((WidgetCacheKey) o).size.equals(size);
Adrian Roos1f375ab2014-04-28 18:26:38 +0200682 }
683 }
Michael Jurka05713af2013-01-23 12:39:24 +0100684}