blob: 0f62b31c177199c1135a60e417393023e1867926 [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 Goyal4ddc4012016-03-10 12:02:29 -08006import android.content.pm.ActivityInfo;
Sunny Goyal5b0e6692015-03-19 14:31:19 -07007import android.content.pm.PackageInfo;
Sunny Goyal4ddc4012016-03-10 12:02:29 -08008import android.content.pm.PackageManager;
Sunny Goyal5b0e6692015-03-19 14:31:19 -07009import android.content.pm.PackageManager.NameNotFoundException;
Michael Jurka05713af2013-01-23 12:39:24 +010010import android.content.res.Resources;
11import android.database.Cursor;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070012import android.database.SQLException;
Michael Jurka05713af2013-01-23 12:39:24 +010013import android.database.sqlite.SQLiteDatabase;
Michael Jurka05713af2013-01-23 12:39:24 +010014import 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;
Sunny Goyal7c74e4a2016-12-15 15:53:17 -080028import android.os.UserHandle;
Michael Jurka05713af2013-01-23 12:39:24 +010029import android.util.Log;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070030import android.util.LongSparseArray;
Sunny Goyal383c5072015-06-12 21:18:53 -070031
Sunny Goyalffe83f12014-08-14 17:39:34 -070032import com.android.launcher3.compat.AppWidgetManagerCompat;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070033import com.android.launcher3.compat.UserManagerCompat;
Sunny Goyal4ddc4012016-03-10 12:02:29 -080034import com.android.launcher3.model.WidgetItem;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070035import com.android.launcher3.util.ComponentKey;
Sunny Goyal6388b2c2016-04-15 18:03:27 -070036import com.android.launcher3.util.Preconditions;
Sunny Goyal6f709362015-12-17 17:09:36 -080037import com.android.launcher3.util.SQLiteCacheHelper;
Adam Cohen091440a2015-03-18 14:16:05 -070038import com.android.launcher3.util.Thunk;
Hyunyoung Song3f471442015-04-08 19:01:34 -070039import com.android.launcher3.widget.WidgetCell;
Hyunyoung Song8821ca92015-05-04 16:28:20 -070040
41import java.util.ArrayList;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070042import java.util.Collections;
Michael Jurka05713af2013-01-23 12:39:24 +010043import java.util.HashMap;
44import java.util.HashSet;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070045import java.util.Set;
46import java.util.WeakHashMap;
Adrian Roos65d60e22014-04-15 21:07:49 +020047import java.util.concurrent.Callable;
48import java.util.concurrent.ExecutionException;
Michael Jurka05713af2013-01-23 12:39:24 +010049
Sunny Goyalffe83f12014-08-14 17:39:34 -070050public class WidgetPreviewLoader {
Michael Jurka05713af2013-01-23 12:39:24 +010051
Sunny Goyalffe83f12014-08-14 17:39:34 -070052 private static final String TAG = "WidgetPreviewLoader";
Hyunyoung Song3f471442015-04-08 19:01:34 -070053 private static final boolean DEBUG = false;
Sunny Goyalffe83f12014-08-14 17:39:34 -070054
55 private static final float WIDGET_PREVIEW_ICON_PADDING_PERCENTAGE = 0.25f;
Sunny Goyalffe83f12014-08-14 17:39:34 -070056
Sunny Goyal5b0e6692015-03-19 14:31:19 -070057 private final HashMap<String, long[]> mPackageVersions = new HashMap<>();
Hyunyoung Song559d90d2015-04-28 15:06:45 -070058
59 /**
60 * Weak reference objects, do not prevent their referents from being made finalizable,
61 * finalized, and then reclaimed.
Hyunyoung Songe98f4a42015-06-16 10:45:24 -070062 * Note: synchronized block used for this variable is expensive and the block should always
63 * be posted to a background thread.
Hyunyoung Song559d90d2015-04-28 15:06:45 -070064 */
Sunny Goyalb4cbea42015-06-16 15:10:36 -070065 @Thunk final Set<Bitmap> mUnusedBitmaps =
Hyunyoung Song559d90d2015-04-28 15:06:45 -070066 Collections.newSetFromMap(new WeakHashMap<Bitmap, Boolean>());
Sunny Goyal4cad7532015-03-18 15:56:30 -070067
68 private final Context mContext;
Sunny Goyalffe83f12014-08-14 17:39:34 -070069 private final IconCache mIconCache;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070070 private final UserManagerCompat mUserManager;
Hyunyoung Song3e840f42016-03-01 11:57:44 -080071 private final AppWidgetManagerCompat mWidgetManager;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070072 private final CacheDb mDb;
Hyunyoung Song41e33692015-06-15 12:26:54 -070073 private final int mProfileBadgeMargin;
Michael Jurka05713af2013-01-23 12:39:24 +010074
Adrian Roos65d60e22014-04-15 21:07:49 +020075 private final MainThreadExecutor mMainThreadExecutor = new MainThreadExecutor();
Sunny Goyal316490e2015-06-02 09:38:28 -070076 @Thunk final Handler mWorkerHandler;
Adrian Roos65d60e22014-04-15 21:07:49 +020077
Sunny Goyal383c5072015-06-12 21:18:53 -070078 public WidgetPreviewLoader(Context context, IconCache iconCache) {
Chris Wrenfd13c712013-09-27 15:45:19 -040079 mContext = context;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070080 mIconCache = iconCache;
Hyunyoung Song3e840f42016-03-01 11:57:44 -080081 mWidgetManager = AppWidgetManagerCompat.getInstance(context);
Sunny Goyal5b0e6692015-03-19 14:31:19 -070082 mUserManager = UserManagerCompat.getInstance(context);
83 mDb = new CacheDb(context);
Winson Chung05304db2015-05-18 16:53:20 -070084 mWorkerHandler = new Handler(LauncherModel.getWorkerLooper());
Hyunyoung Song41e33692015-06-15 12:26:54 -070085 mProfileBadgeMargin = context.getResources()
86 .getDimensionPixelSize(R.dimen.profile_badge_margin);
Michael Jurka3f4e0702013-02-05 11:21:28 +010087 }
Sunny Goyalffe83f12014-08-14 17:39:34 -070088
Sunny Goyal5b0e6692015-03-19 14:31:19 -070089 /**
90 * Generates the widget preview on {@link AsyncTask#THREAD_POOL_EXECUTOR}. Must be
91 * called on UI thread
92 *
Sunny Goyal5b0e6692015-03-19 14:31:19 -070093 * @return a request id which can be used to cancel the request.
94 */
Sunny Goyal4ddc4012016-03-10 12:02:29 -080095 public PreviewLoadRequest getPreview(WidgetItem item, int previewWidth,
Adam Cohen2e6da152015-05-06 11:42:25 -070096 int previewHeight, WidgetCell caller) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -070097 String size = previewWidth + "x" + previewHeight;
Sunny Goyal4ddc4012016-03-10 12:02:29 -080098 WidgetCacheKey key = new WidgetCacheKey(item.componentName, item.user, size);
Michael Jurka3f4e0702013-02-05 11:21:28 +010099
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800100 PreviewLoadTask task = new PreviewLoadTask(key, item, previewWidth, previewHeight, caller);
Sunny Goyal8ac727b2015-09-23 15:38:09 -0700101 task.executeOnExecutor(Utilities.THREAD_POOL_EXECUTOR);
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700102 return new PreviewLoadRequest(task);
Michael Jurka05713af2013-01-23 12:39:24 +0100103 }
104
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700105 /**
106 * The DB holds the generated previews for various components. Previews can also have different
107 * sizes (landscape vs portrait).
108 */
Sunny Goyal6f709362015-12-17 17:09:36 -0800109 private static class CacheDb extends SQLiteCacheHelper {
Sunny Goyal2d648b02015-08-11 13:56:28 -0700110 private static final int DB_VERSION = 4;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700111
112 private static final String TABLE_NAME = "shortcut_and_widget_previews";
113 private static final String COLUMN_COMPONENT = "componentName";
114 private static final String COLUMN_USER = "profileId";
115 private static final String COLUMN_SIZE = "size";
116 private static final String COLUMN_PACKAGE = "packageName";
117 private static final String COLUMN_LAST_UPDATED = "lastUpdated";
118 private static final String COLUMN_VERSION = "version";
119 private static final String COLUMN_PREVIEW_BITMAP = "preview_bitmap";
Michael Jurka05713af2013-01-23 12:39:24 +0100120
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100121 public CacheDb(Context context) {
Sunny Goyal6f709362015-12-17 17:09:36 -0800122 super(context, LauncherFiles.WIDGET_PREVIEWS_DB, DB_VERSION, TABLE_NAME);
Michael Jurka05713af2013-01-23 12:39:24 +0100123 }
124
125 @Override
Sunny Goyal6f709362015-12-17 17:09:36 -0800126 public void onCreateTable(SQLiteDatabase database) {
Michael Jurka32b7a092013-02-07 20:06:49 +0100127 database.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" +
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700128 COLUMN_COMPONENT + " TEXT NOT NULL, " +
129 COLUMN_USER + " INTEGER NOT NULL, " +
Michael Jurka05713af2013-01-23 12:39:24 +0100130 COLUMN_SIZE + " TEXT NOT NULL, " +
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700131 COLUMN_PACKAGE + " TEXT NOT NULL, " +
132 COLUMN_LAST_UPDATED + " INTEGER NOT NULL DEFAULT 0, " +
133 COLUMN_VERSION + " INTEGER NOT NULL DEFAULT 0, " +
134 COLUMN_PREVIEW_BITMAP + " BLOB, " +
135 "PRIMARY KEY (" + COLUMN_COMPONENT + ", " + COLUMN_USER + ", " + COLUMN_SIZE + ") " +
Michael Jurka32b7a092013-02-07 20:06:49 +0100136 ");");
Michael Jurka05713af2013-01-23 12:39:24 +0100137 }
Michael Jurka05713af2013-01-23 12:39:24 +0100138 }
139
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700140 @Thunk void writeToDb(WidgetCacheKey key, long[] versions, Bitmap preview) {
Michael Jurka05713af2013-01-23 12:39:24 +0100141 ContentValues values = new ContentValues();
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700142 values.put(CacheDb.COLUMN_COMPONENT, key.componentName.flattenToShortString());
143 values.put(CacheDb.COLUMN_USER, mUserManager.getSerialNumberForUser(key.user));
144 values.put(CacheDb.COLUMN_SIZE, key.size);
145 values.put(CacheDb.COLUMN_PACKAGE, key.componentName.getPackageName());
146 values.put(CacheDb.COLUMN_VERSION, versions[0]);
147 values.put(CacheDb.COLUMN_LAST_UPDATED, versions[1]);
148 values.put(CacheDb.COLUMN_PREVIEW_BITMAP, Utilities.flattenBitmap(preview));
Sunny Goyal6f709362015-12-17 17:09:36 -0800149 mDb.insertOrReplace(values);
Michael Jurka05713af2013-01-23 12:39:24 +0100150 }
151
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800152 public void removePackage(String packageName, UserHandle user) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700153 removePackage(packageName, user, mUserManager.getSerialNumberForUser(user));
154 }
155
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800156 private void removePackage(String packageName, UserHandle user, long userSerial) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700157 synchronized(mPackageVersions) {
158 mPackageVersions.remove(packageName);
159 }
160
Sunny Goyal6f709362015-12-17 17:09:36 -0800161 mDb.delete(
162 CacheDb.COLUMN_PACKAGE + " = ? AND " + CacheDb.COLUMN_USER + " = ?",
163 new String[]{packageName, Long.toString(userSerial)});
Michael Jurka8ff02ca2013-11-01 14:19:27 +0100164 }
165
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700166 /**
167 * Updates the persistent DB:
168 * 1. Any preview generated for an old package version is removed
169 * 2. Any preview for an absent package is removed
170 * This ensures that we remove entries for packages which changed while the launcher was dead.
171 */
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800172 public void removeObsoletePreviews(ArrayList<? extends ComponentKey> list) {
Sunny Goyal6388b2c2016-04-15 18:03:27 -0700173 Preconditions.assertWorkerThread();
Hyunyoung Song8821ca92015-05-04 16:28:20 -0700174
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700175 LongSparseArray<HashSet<String>> validPackages = new LongSparseArray<>();
176
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800177 for (ComponentKey key : list) {
178 final long userId = mUserManager.getSerialNumberForUser(key.user);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700179 HashSet<String> packages = validPackages.get(userId);
180 if (packages == null) {
181 packages = new HashSet<>();
182 validPackages.put(userId, packages);
183 }
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800184 packages.add(key.componentName.getPackageName());
Michael Jurka05713af2013-01-23 12:39:24 +0100185 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700186
187 LongSparseArray<HashSet<String>> packagesToDelete = new LongSparseArray<>();
188 Cursor c = null;
189 try {
Sunny Goyal6f709362015-12-17 17:09:36 -0800190 c = mDb.query(
191 new String[]{CacheDb.COLUMN_USER, CacheDb.COLUMN_PACKAGE,
192 CacheDb.COLUMN_LAST_UPDATED, CacheDb.COLUMN_VERSION},
193 null, null);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700194 while (c.moveToNext()) {
195 long userId = c.getLong(0);
196 String pkg = c.getString(1);
197 long lastUpdated = c.getLong(2);
198 long version = c.getLong(3);
199
200 HashSet<String> packages = validPackages.get(userId);
201 if (packages != null && packages.contains(pkg)) {
202 long[] versions = getPackageVersion(pkg);
203 if (versions[0] == version && versions[1] == lastUpdated) {
204 // Every thing checks out
205 continue;
206 }
207 }
208
209 // We need to delete this package.
210 packages = packagesToDelete.get(userId);
211 if (packages == null) {
212 packages = new HashSet<>();
213 packagesToDelete.put(userId, packages);
214 }
215 packages.add(pkg);
216 }
217
218 for (int i = 0; i < packagesToDelete.size(); i++) {
219 long userId = packagesToDelete.keyAt(i);
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800220 UserHandle user = mUserManager.getUserForSerialNumber(userId);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700221 for (String pkg : packagesToDelete.valueAt(i)) {
222 removePackage(pkg, user, userId);
223 }
224 }
225 } catch (SQLException e) {
Sunny Goyal6f709362015-12-17 17:09:36 -0800226 Log.e(TAG, "Error updating widget previews", e);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700227 } finally {
228 if (c != null) {
229 c.close();
230 }
231 }
232 }
233
Winson Chung05304db2015-05-18 16:53:20 -0700234 /**
235 * Reads the preview bitmap from the DB or null if the preview is not in the DB.
236 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700237 @Thunk Bitmap readFromDb(WidgetCacheKey key, Bitmap recycle, PreviewLoadTask loadTask) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700238 Cursor cursor = null;
239 try {
Sunny Goyal6f709362015-12-17 17:09:36 -0800240 cursor = mDb.query(
241 new String[]{CacheDb.COLUMN_PREVIEW_BITMAP},
242 CacheDb.COLUMN_COMPONENT + " = ? AND " + CacheDb.COLUMN_USER + " = ? AND "
243 + CacheDb.COLUMN_SIZE + " = ?",
244 new String[]{
Sunny Goyal3ef86912016-10-27 11:40:06 -0700245 key.componentName.flattenToShortString(),
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700246 Long.toString(mUserManager.getSerialNumberForUser(key.user)),
247 key.size
Sunny Goyal6f709362015-12-17 17:09:36 -0800248 });
Winson Chung05304db2015-05-18 16:53:20 -0700249 // If cancelled, skip getting the blob and decoding it into a bitmap
250 if (loadTask.isCancelled()) {
251 return null;
252 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700253 if (cursor.moveToNext()) {
254 byte[] blob = cursor.getBlob(0);
255 BitmapFactory.Options opts = new BitmapFactory.Options();
256 opts.inBitmap = recycle;
Michael Jurka6e27f642013-12-10 13:40:30 +0100257 try {
Winson Chung05304db2015-05-18 16:53:20 -0700258 if (!loadTask.isCancelled()) {
259 return BitmapFactory.decodeByteArray(blob, 0, blob.length, opts);
260 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700261 } catch (Exception e) {
262 return null;
Michael Jurka6e27f642013-12-10 13:40:30 +0100263 }
Michael Jurka05713af2013-01-23 12:39:24 +0100264 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700265 } catch (SQLException e) {
266 Log.w(TAG, "Error loading preview from DB", e);
267 } finally {
268 if (cursor != null) {
269 cursor.close();
270 }
271 }
272 return null;
Michael Jurka05713af2013-01-23 12:39:24 +0100273 }
274
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800275 private Bitmap generatePreview(Launcher launcher, WidgetItem item, Bitmap recycle,
Adam Cohen2e6da152015-05-06 11:42:25 -0700276 int previewWidth, int previewHeight) {
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800277 if (item.widgetInfo != null) {
278 return generateWidgetPreview(launcher, item.widgetInfo,
Adam Cohen2e6da152015-05-06 11:42:25 -0700279 previewWidth, recycle, null);
Michael Jurka05713af2013-01-23 12:39:24 +0100280 } else {
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800281 return generateShortcutPreview(launcher, item.activityInfo,
282 previewWidth, previewHeight, recycle);
Michael Jurka05713af2013-01-23 12:39:24 +0100283 }
284 }
285
Hyunyoung Song3e840f42016-03-01 11:57:44 -0800286 /**
287 * Generates the widget preview from either the {@link AppWidgetManagerCompat} or cache
288 * and add badge at the bottom right corner.
289 *
290 * @param launcher
291 * @param info information about the widget
292 * @param maxPreviewWidth width of the preview on either workspace or tray
293 * @param preview bitmap that can be recycled
294 * @param preScaledWidthOut return the width of the returned bitmap
295 * @return
296 */
Adam Cohen2e6da152015-05-06 11:42:25 -0700297 public Bitmap generateWidgetPreview(Launcher launcher, LauncherAppWidgetProviderInfo info,
Sunny Goyal4cad7532015-03-18 15:56:30 -0700298 int maxPreviewWidth, Bitmap preview, int[] preScaledWidthOut) {
Michael Jurka05713af2013-01-23 12:39:24 +0100299 // Load the preview image if possible
Michael Jurka05713af2013-01-23 12:39:24 +0100300 if (maxPreviewWidth < 0) maxPreviewWidth = Integer.MAX_VALUE;
Michael Jurka05713af2013-01-23 12:39:24 +0100301
302 Drawable drawable = null;
Sunny Goyalffe83f12014-08-14 17:39:34 -0700303 if (info.previewImage != 0) {
Sunny Goyal2570d102016-10-27 11:38:45 -0700304 try {
Sunny Goyala52ecb02016-12-16 15:04:51 -0800305 drawable = info.loadPreviewImage(launcher.getApplicationContext(), 0);
Sunny Goyal2570d102016-10-27 11:38:45 -0700306 } catch (OutOfMemoryError e) {
307 Log.w(TAG, "Error loading widget preview for: " + info.provider, e);
308 // During OutOfMemoryError, the previous heap stack is not affected. Catching
309 // an OOM error here should be safe & not affect other parts of launcher.
310 drawable = null;
311 }
Adrian Roosfa9ffc22014-05-12 15:59:59 +0200312 if (drawable != null) {
313 drawable = mutateOnMainThread(drawable);
314 } else {
Michael Jurka05713af2013-01-23 12:39:24 +0100315 Log.w(TAG, "Can't load widget preview drawable 0x" +
Sunny Goyalffe83f12014-08-14 17:39:34 -0700316 Integer.toHexString(info.previewImage) + " for provider: " + info.provider);
Michael Jurka05713af2013-01-23 12:39:24 +0100317 }
318 }
319
Sunny Goyal4cad7532015-03-18 15:56:30 -0700320 final boolean widgetPreviewExists = (drawable != null);
Sunny Goyal233ee962015-08-03 13:05:01 -0700321 final int spanX = info.spanX;
322 final int spanY = info.spanY;
Sunny Goyal4cad7532015-03-18 15:56:30 -0700323
Michael Jurka05713af2013-01-23 12:39:24 +0100324 int previewWidth;
325 int previewHeight;
Hyunyoung Song3e840f42016-03-01 11:57:44 -0800326
Sunny Goyal4cad7532015-03-18 15:56:30 -0700327 Bitmap tileBitmap = null;
328
Michael Jurka05713af2013-01-23 12:39:24 +0100329 if (widgetPreviewExists) {
330 previewWidth = drawable.getIntrinsicWidth();
331 previewHeight = drawable.getIntrinsicHeight();
332 } else {
333 // Generate a preview image if we couldn't load one
Sunny Goyal4cad7532015-03-18 15:56:30 -0700334 tileBitmap = ((BitmapDrawable) mContext.getResources().getDrawable(
335 R.drawable.widget_tile)).getBitmap();
336 previewWidth = tileBitmap.getWidth() * spanX;
337 previewHeight = tileBitmap.getHeight() * spanY;
Michael Jurka05713af2013-01-23 12:39:24 +0100338 }
339
340 // Scale to fit width only - let the widget preview be clipped in the
341 // vertical dimension
342 float scale = 1f;
343 if (preScaledWidthOut != null) {
344 preScaledWidthOut[0] = previewWidth;
345 }
346 if (previewWidth > maxPreviewWidth) {
Hyunyoung Songb9f932e2015-07-30 15:04:59 -0700347 scale = (maxPreviewWidth - 2 * mProfileBadgeMargin) / (float) (previewWidth);
Michael Jurka05713af2013-01-23 12:39:24 +0100348 }
349 if (scale != 1f) {
350 previewWidth = (int) (scale * previewWidth);
351 previewHeight = (int) (scale * previewHeight);
352 }
353
354 // 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 -0700355 final Canvas c = new Canvas();
Michael Jurka05713af2013-01-23 12:39:24 +0100356 if (preview == null) {
357 preview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700358 c.setBitmap(preview);
359 } else {
360 // Reusing bitmap. Clear it.
361 c.setBitmap(preview);
362 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100363 }
364
365 // Draw the scaled preview into the final bitmap
Hyunyoung Songb9f932e2015-07-30 15:04:59 -0700366 int x = (preview.getWidth() - previewWidth) / 2;
Michael Jurka05713af2013-01-23 12:39:24 +0100367 if (widgetPreviewExists) {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700368 drawable.setBounds(x, 0, x + previewWidth, previewHeight);
369 drawable.draw(c);
Michael Jurka05713af2013-01-23 12:39:24 +0100370 } else {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700371 final Paint p = new Paint();
372 p.setFilterBitmap(true);
Adam Cohen2e6da152015-05-06 11:42:25 -0700373 int appIconSize = launcher.getDeviceProfile().iconSizePx;
Michael Jurka05713af2013-01-23 12:39:24 +0100374
Sunny Goyal4cad7532015-03-18 15:56:30 -0700375 // draw the spanX x spanY tiles
376 final Rect src = new Rect(0, 0, tileBitmap.getWidth(), tileBitmap.getHeight());
377
378 float tileW = scale * tileBitmap.getWidth();
379 float tileH = scale * tileBitmap.getHeight();
380 final RectF dst = new RectF(0, 0, tileW, tileH);
381
382 float tx = x;
383 for (int i = 0; i < spanX; i++, tx += tileW) {
384 float ty = 0;
385 for (int j = 0; j < spanY; j++, ty += tileH) {
386 dst.offsetTo(tx, ty);
387 c.drawBitmap(tileBitmap, src, dst, p);
388 }
Michael Jurka05713af2013-01-23 12:39:24 +0100389 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700390
391 // Draw the icon in the top left corner
392 // TODO: use top right for RTL
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700393 int minOffset = (int) (appIconSize * WIDGET_PREVIEW_ICON_PADDING_PERCENTAGE);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700394 int smallestSide = Math.min(previewWidth, previewHeight);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700395 float iconScale = Math.min((float) smallestSide / (appIconSize + 2 * minOffset), scale);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700396
397 try {
Sunny Goyala52ecb02016-12-16 15:04:51 -0800398 Drawable icon = info.getIcon(launcher, mIconCache);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700399 if (icon != null) {
Sunny Goyal1ba7e362015-10-26 10:42:12 -0700400 icon = mutateOnMainThread(icon);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700401 int hoffset = (int) ((tileW - appIconSize * iconScale) / 2) + x;
402 int yoffset = (int) ((tileH - appIconSize * iconScale) / 2);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700403 icon.setBounds(hoffset, yoffset,
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700404 hoffset + (int) (appIconSize * iconScale),
405 yoffset + (int) (appIconSize * iconScale));
Sunny Goyal4cad7532015-03-18 15:56:30 -0700406 icon.draw(c);
407 }
Hyunyoung Song3e840f42016-03-01 11:57:44 -0800408 } catch (Resources.NotFoundException e) {
409 }
Michael Jurka05713af2013-01-23 12:39:24 +0100410 c.setBitmap(null);
411 }
Hyunyoung Song3e840f42016-03-01 11:57:44 -0800412 int imageWidth = Math.min(preview.getWidth(), previewWidth + mProfileBadgeMargin);
Hyunyoung Song41e33692015-06-15 12:26:54 -0700413 int imageHeight = Math.min(preview.getHeight(), previewHeight + mProfileBadgeMargin);
Hyunyoung Song3e840f42016-03-01 11:57:44 -0800414 return mWidgetManager.getBadgeBitmap(info, preview, imageWidth, imageHeight);
Michael Jurka05713af2013-01-23 12:39:24 +0100415 }
416
417 private Bitmap generateShortcutPreview(
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800418 Launcher launcher, ActivityInfo info, int maxWidth, int maxHeight, Bitmap preview) {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700419 final Canvas c = new Canvas();
420 if (preview == null) {
Michael Jurka05713af2013-01-23 12:39:24 +0100421 preview = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700422 c.setBitmap(preview);
423 } else if (preview.getWidth() != maxWidth || preview.getHeight() != maxHeight) {
424 throw new RuntimeException("Improperly sized bitmap passed as argument");
425 } else {
426 // Reusing bitmap. Clear it.
427 c.setBitmap(preview);
428 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100429 }
430
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800431 Drawable icon = mutateOnMainThread(mIconCache.getFullResIcon(info));
Sunny Goyal4cad7532015-03-18 15:56:30 -0700432 icon.setFilterBitmap(true);
433
Michael Jurka05713af2013-01-23 12:39:24 +0100434 // Draw a desaturated/scaled version of the icon in the background as a watermark
Sunny Goyal4cad7532015-03-18 15:56:30 -0700435 ColorMatrix colorMatrix = new ColorMatrix();
436 colorMatrix.setSaturation(0);
437 icon.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
438 icon.setAlpha((int) (255 * 0.06f));
439
440 Resources res = mContext.getResources();
441 int paddingTop = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_top);
442 int paddingLeft = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_left);
443 int paddingRight = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_right);
444 int scaledIconWidth = (maxWidth - paddingLeft - paddingRight);
445 icon.setBounds(paddingLeft, paddingTop,
446 paddingLeft + scaledIconWidth, paddingTop + scaledIconWidth);
447 icon.draw(c);
448
449 // Draw the final icon at top left corner.
450 // TODO: use top right for RTL
Adam Cohen2e6da152015-05-06 11:42:25 -0700451 int appIconSize = launcher.getDeviceProfile().iconSizePx;
452
Sunny Goyal4cad7532015-03-18 15:56:30 -0700453 icon.setAlpha(255);
454 icon.setColorFilter(null);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700455 icon.setBounds(0, 0, appIconSize, appIconSize);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700456 icon.draw(c);
457
Michael Jurka05713af2013-01-23 12:39:24 +0100458 c.setBitmap(null);
Michael Jurka05713af2013-01-23 12:39:24 +0100459 return preview;
460 }
461
Adrian Roos65d60e22014-04-15 21:07:49 +0200462 private Drawable mutateOnMainThread(final Drawable drawable) {
463 try {
464 return mMainThreadExecutor.submit(new Callable<Drawable>() {
465 @Override
466 public Drawable call() throws Exception {
467 return drawable.mutate();
468 }
469 }).get();
470 } catch (InterruptedException e) {
471 Thread.currentThread().interrupt();
472 throw new RuntimeException(e);
473 } catch (ExecutionException e) {
474 throw new RuntimeException(e);
475 }
476 }
Adrian Roos1f375ab2014-04-28 18:26:38 +0200477
Adrian Roos1f375ab2014-04-28 18:26:38 +0200478 /**
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700479 * @return an array of containing versionCode and lastUpdatedTime for the package.
Adrian Roos1f375ab2014-04-28 18:26:38 +0200480 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700481 @Thunk long[] getPackageVersion(String packageName) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700482 synchronized (mPackageVersions) {
483 long[] versions = mPackageVersions.get(packageName);
484 if (versions == null) {
485 versions = new long[2];
Adrian Roos1f375ab2014-04-28 18:26:38 +0200486 try {
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800487 PackageInfo info = mContext.getPackageManager().getPackageInfo(packageName,
488 PackageManager.GET_UNINSTALLED_PACKAGES);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700489 versions[0] = info.versionCode;
490 versions[1] = info.lastUpdateTime;
491 } catch (NameNotFoundException e) {
492 Log.e(TAG, "PackageInfo not found", e);
493 }
494 mPackageVersions.put(packageName, versions);
495 }
496 return versions;
497 }
498 }
499
500 /**
501 * A request Id which can be used by the client to cancel any request.
502 */
503 public class PreviewLoadRequest {
504
Sunny Goyalb4cbea42015-06-16 15:10:36 -0700505 @Thunk final PreviewLoadTask mTask;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700506
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700507 public PreviewLoadRequest(PreviewLoadTask task) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700508 mTask = task;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700509 }
510
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700511 public void cleanup() {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700512 if (mTask != null) {
513 mTask.cancel(true);
514 }
515
Winson Chung05304db2015-05-18 16:53:20 -0700516 // This only handles the case where the PreviewLoadTask is cancelled after the task has
517 // successfully completed (including having written to disk when necessary). In the
518 // other cases where it is cancelled while the task is running, it will be cleaned up
519 // in the tasks's onCancelled() call, and if cancelled while the task is writing to
520 // disk, it will be cancelled in the task's onPostExecute() call.
521 if (mTask.mBitmapToRecycle != null) {
Hyunyoung Songe98f4a42015-06-16 10:45:24 -0700522 mWorkerHandler.post(new Runnable() {
523 @Override
524 public void run() {
525 synchronized (mUnusedBitmaps) {
526 mUnusedBitmaps.add(mTask.mBitmapToRecycle);
527 }
528 mTask.mBitmapToRecycle = null;
529 }
530 });
Adrian Roos1f375ab2014-04-28 18:26:38 +0200531 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700532 }
533 }
534
535 public class PreviewLoadTask extends AsyncTask<Void, Void, Bitmap> {
Sunny Goyal316490e2015-06-02 09:38:28 -0700536 @Thunk final WidgetCacheKey mKey;
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800537 private final WidgetItem mInfo;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700538 private final int mPreviewHeight;
539 private final int mPreviewWidth;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700540 private final WidgetCell mCaller;
Sunny Goyal316490e2015-06-02 09:38:28 -0700541 @Thunk long[] mVersions;
542 @Thunk Bitmap mBitmapToRecycle;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700543
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800544 PreviewLoadTask(WidgetCacheKey key, WidgetItem info, int previewWidth,
Hyunyoung Song3f471442015-04-08 19:01:34 -0700545 int previewHeight, WidgetCell caller) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700546 mKey = key;
547 mInfo = info;
548 mPreviewHeight = previewHeight;
549 mPreviewWidth = previewWidth;
550 mCaller = caller;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700551 if (DEBUG) {
552 Log.d(TAG, String.format("%s, %s, %d, %d",
553 mKey, mInfo, mPreviewHeight, mPreviewWidth));
554 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700555 }
556
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700557 @Override
558 protected Bitmap doInBackground(Void... params) {
559 Bitmap unusedBitmap = null;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700560
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700561 // If already cancelled before this gets to run in the background, then return early
562 if (isCancelled()) {
563 return null;
564 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700565 synchronized (mUnusedBitmaps) {
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700566 // Check if we can re-use a bitmap
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700567 for (Bitmap candidate : mUnusedBitmaps) {
568 if (candidate != null && candidate.isMutable() &&
569 candidate.getWidth() == mPreviewWidth &&
570 candidate.getHeight() == mPreviewHeight) {
571 unusedBitmap = candidate;
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700572 mUnusedBitmaps.remove(unusedBitmap);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700573 break;
574 }
575 }
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700576 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700577
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700578 // creating a bitmap is expensive. Do not do this inside synchronized block.
579 if (unusedBitmap == null) {
580 unusedBitmap = Bitmap.createBitmap(mPreviewWidth, mPreviewHeight, Config.ARGB_8888);
Adrian Roos1f375ab2014-04-28 18:26:38 +0200581 }
Winson Chung05304db2015-05-18 16:53:20 -0700582 // If cancelled now, don't bother reading the preview from the DB
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700583 if (isCancelled()) {
Winson Chung05304db2015-05-18 16:53:20 -0700584 return unusedBitmap;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700585 }
Winson Chung05304db2015-05-18 16:53:20 -0700586 Bitmap preview = readFromDb(mKey, unusedBitmap, this);
587 // Only consider generating the preview if we have not cancelled the task already
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700588 if (!isCancelled() && preview == null) {
589 // Fetch the version info before we generate the preview, so that, in-case the
590 // app was updated while we are generating the preview, we use the old version info,
591 // which would gets re-written next time.
Winson Chung05304db2015-05-18 16:53:20 -0700592 mVersions = getPackageVersion(mKey.componentName.getPackageName());
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700593
Andrew Sappersteinabef55a2016-06-19 12:49:00 -0700594 Launcher launcher = Launcher.getLauncher(mCaller.getContext());
Adam Cohen2e6da152015-05-06 11:42:25 -0700595
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700596 // it's not in the db... we need to generate it
Adam Cohen2e6da152015-05-06 11:42:25 -0700597 preview = generatePreview(launcher, mInfo, unusedBitmap, mPreviewWidth, mPreviewHeight);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700598 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700599 return preview;
600 }
601
602 @Override
Winson Chung05304db2015-05-18 16:53:20 -0700603 protected void onPostExecute(final Bitmap preview) {
604 mCaller.applyPreview(preview);
605
606 // Write the generated preview to the DB in the worker thread
607 if (mVersions != null) {
608 mWorkerHandler.post(new Runnable() {
609 @Override
610 public void run() {
611 if (!isCancelled()) {
612 // If we are still using this preview, then write it to the DB and then
613 // let the normal clear mechanism recycle the bitmap
614 writeToDb(mKey, mVersions, preview);
615 mBitmapToRecycle = preview;
616 } else {
617 // If we've already cancelled, then skip writing the bitmap to the DB
618 // and manually add the bitmap back to the recycled set
619 synchronized (mUnusedBitmaps) {
620 mUnusedBitmaps.add(preview);
621 }
622 }
623 }
624 });
625 } else {
626 // If we don't need to write to disk, then ensure the preview gets recycled by
627 // the normal clear mechanism
628 mBitmapToRecycle = preview;
629 }
630 }
631
632 @Override
Hyunyoung Songe98f4a42015-06-16 10:45:24 -0700633 protected void onCancelled(final Bitmap preview) {
Winson Chung05304db2015-05-18 16:53:20 -0700634 // If we've cancelled while the task is running, then can return the bitmap to the
635 // recycled set immediately. Otherwise, it will be recycled after the preview is written
636 // to disk.
637 if (preview != null) {
Hyunyoung Songe98f4a42015-06-16 10:45:24 -0700638 mWorkerHandler.post(new Runnable() {
639 @Override
640 public void run() {
641 synchronized (mUnusedBitmaps) {
642 mUnusedBitmaps.add(preview);
643 }
644 }
645 });
Winson Chung05304db2015-05-18 16:53:20 -0700646 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700647 }
648 }
649
650 private static final class WidgetCacheKey extends ComponentKey {
651
652 // TODO: remove dependency on size
Sunny Goyal316490e2015-06-02 09:38:28 -0700653 @Thunk final String size;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700654
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800655 public WidgetCacheKey(ComponentName componentName, UserHandle user, String size) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700656 super(componentName, user);
657 this.size = size;
658 }
659
660 @Override
661 public int hashCode() {
662 return super.hashCode() ^ size.hashCode();
663 }
664
665 @Override
666 public boolean equals(Object o) {
667 return super.equals(o) && ((WidgetCacheKey) o).size.equals(size);
Adrian Roos1f375ab2014-04-28 18:26:38 +0200668 }
669 }
Michael Jurka05713af2013-01-23 12:39:24 +0100670}