blob: 6d1bc1a9c04d9cccb93462fcc6e6f3e263a04b9f [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;
Sunny Goyal4ddc4012016-03-10 12:02:29 -08007import android.content.pm.PackageManager;
Sunny Goyal5b0e6692015-03-19 14:31:19 -07008import android.content.pm.PackageManager.NameNotFoundException;
Michael Jurka05713af2013-01-23 12:39:24 +01009import 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;
Sunny Goyal7d87cb12017-02-13 10:44:43 -080017import android.graphics.Color;
Michael Jurka05713af2013-01-23 12:39:24 +010018import android.graphics.Paint;
19import android.graphics.PorterDuff;
Sunny Goyal92bbfa12017-02-07 15:06:32 -080020import android.graphics.PorterDuffXfermode;
Sunny Goyal7d87cb12017-02-13 10:44:43 -080021import 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.Drawable;
24import android.os.AsyncTask;
Sunny Goyalc65a0082017-03-08 14:49:55 -080025import android.os.CancellationSignal;
Winson Chung05304db2015-05-18 16:53:20 -070026import android.os.Handler;
Hyunyoung Song2bf3f372019-04-02 10:45:57 -070027import android.os.Process;
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 Goyal782f0c92017-01-19 10:27:54 -080033import com.android.launcher3.compat.ShortcutConfigActivityInfo;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070034import com.android.launcher3.compat.UserManagerCompat;
Sunny Goyale62d2bb2018-11-06 10:28:37 -080035import com.android.launcher3.icons.GraphicsUtils;
Hyunyoung Song48cb7bc2018-09-25 17:03:34 -070036import com.android.launcher3.icons.LauncherIcons;
37import com.android.launcher3.icons.ShadowGenerator;
Sunny Goyalf840f102018-09-21 14:41:05 -070038import com.android.launcher3.icons.IconCache;
Sunny Goyal4ddc4012016-03-10 12:02:29 -080039import com.android.launcher3.model.WidgetItem;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070040import com.android.launcher3.util.ComponentKey;
Tony Wickham86222d22017-03-29 15:30:43 -070041import com.android.launcher3.util.PackageUserKey;
Sunny Goyal6388b2c2016-04-15 18:03:27 -070042import com.android.launcher3.util.Preconditions;
Sunny Goyal6f709362015-12-17 17:09:36 -080043import com.android.launcher3.util.SQLiteCacheHelper;
Adam Cohen091440a2015-03-18 14:16:05 -070044import com.android.launcher3.util.Thunk;
Hyunyoung Song3f471442015-04-08 19:01:34 -070045import com.android.launcher3.widget.WidgetCell;
Hyunyoung Song8821ca92015-05-04 16:28:20 -070046
47import java.util.ArrayList;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070048import java.util.Collections;
Michael Jurka05713af2013-01-23 12:39:24 +010049import java.util.HashMap;
50import java.util.HashSet;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070051import java.util.Set;
52import java.util.WeakHashMap;
Adrian Roos65d60e22014-04-15 21:07:49 +020053import java.util.concurrent.Callable;
54import java.util.concurrent.ExecutionException;
Michael Jurka05713af2013-01-23 12:39:24 +010055
Sunny Goyald2303072018-08-14 15:21:45 -070056import androidx.annotation.Nullable;
57
Sunny Goyalffe83f12014-08-14 17:39:34 -070058public class WidgetPreviewLoader {
Michael Jurka05713af2013-01-23 12:39:24 +010059
Sunny Goyalffe83f12014-08-14 17:39:34 -070060 private static final String TAG = "WidgetPreviewLoader";
Hyunyoung Song3f471442015-04-08 19:01:34 -070061 private static final boolean DEBUG = false;
Sunny Goyalffe83f12014-08-14 17:39:34 -070062
Sunny Goyal5b0e6692015-03-19 14:31:19 -070063 private final HashMap<String, long[]> mPackageVersions = new HashMap<>();
Hyunyoung Song559d90d2015-04-28 15:06:45 -070064
65 /**
66 * Weak reference objects, do not prevent their referents from being made finalizable,
67 * finalized, and then reclaimed.
Hyunyoung Songe98f4a42015-06-16 10:45:24 -070068 * Note: synchronized block used for this variable is expensive and the block should always
69 * be posted to a background thread.
Hyunyoung Song559d90d2015-04-28 15:06:45 -070070 */
Sunny Goyalb4cbea42015-06-16 15:10:36 -070071 @Thunk final Set<Bitmap> mUnusedBitmaps =
Hyunyoung Song559d90d2015-04-28 15:06:45 -070072 Collections.newSetFromMap(new WeakHashMap<Bitmap, Boolean>());
Sunny Goyal4cad7532015-03-18 15:56:30 -070073
74 private final Context mContext;
Sunny Goyalffe83f12014-08-14 17:39:34 -070075 private final IconCache mIconCache;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070076 private final UserManagerCompat mUserManager;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070077 private final CacheDb mDb;
Michael Jurka05713af2013-01-23 12:39:24 +010078
Adrian Roos65d60e22014-04-15 21:07:49 +020079 private final MainThreadExecutor mMainThreadExecutor = new MainThreadExecutor();
Sunny Goyal316490e2015-06-02 09:38:28 -070080 @Thunk final Handler mWorkerHandler;
Adrian Roos65d60e22014-04-15 21:07:49 +020081
Sunny Goyal383c5072015-06-12 21:18:53 -070082 public WidgetPreviewLoader(Context context, IconCache iconCache) {
Chris Wrenfd13c712013-09-27 15:45:19 -040083 mContext = context;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070084 mIconCache = iconCache;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070085 mUserManager = UserManagerCompat.getInstance(context);
86 mDb = new CacheDb(context);
Winson Chung05304db2015-05-18 16:53:20 -070087 mWorkerHandler = new Handler(LauncherModel.getWorkerLooper());
Michael Jurka3f4e0702013-02-05 11:21:28 +010088 }
Sunny Goyalffe83f12014-08-14 17:39:34 -070089
Sunny Goyal5b0e6692015-03-19 14:31:19 -070090 /**
91 * Generates the widget preview on {@link AsyncTask#THREAD_POOL_EXECUTOR}. Must be
92 * called on UI thread
93 *
Sunny Goyal5b0e6692015-03-19 14:31:19 -070094 * @return a request id which can be used to cancel the request.
95 */
Sunny Goyalc65a0082017-03-08 14:49:55 -080096 public CancellationSignal getPreview(WidgetItem item, int previewWidth,
Sunny Goyalf1fbc3f2017-10-10 15:21:15 -070097 int previewHeight, WidgetCell caller) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -070098 String size = previewWidth + "x" + previewHeight;
Sunny Goyal4ddc4012016-03-10 12:02:29 -080099 WidgetCacheKey key = new WidgetCacheKey(item.componentName, item.user, size);
Michael Jurka3f4e0702013-02-05 11:21:28 +0100100
Sunny Goyalf1fbc3f2017-10-10 15:21:15 -0700101 PreviewLoadTask task = new PreviewLoadTask(key, item, previewWidth, previewHeight, caller);
Sunny Goyal8ac727b2015-09-23 15:38:09 -0700102 task.executeOnExecutor(Utilities.THREAD_POOL_EXECUTOR);
Sunny Goyalc65a0082017-03-08 14:49:55 -0800103
104 CancellationSignal signal = new CancellationSignal();
105 signal.setOnCancelListener(task);
106 return signal;
Michael Jurka05713af2013-01-23 12:39:24 +0100107 }
108
Hyunyoung Song2bf3f372019-04-02 10:45:57 -0700109 public void refresh() {
110 mDb.clear();
111
112 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700113 /**
114 * The DB holds the generated previews for various components. Previews can also have different
115 * sizes (landscape vs portrait).
116 */
Sunny Goyal6f709362015-12-17 17:09:36 -0800117 private static class CacheDb extends SQLiteCacheHelper {
Jon Miranda6cdc16c2017-06-27 14:04:01 -0700118 private static final int DB_VERSION = 9;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700119
120 private static final String TABLE_NAME = "shortcut_and_widget_previews";
121 private static final String COLUMN_COMPONENT = "componentName";
122 private static final String COLUMN_USER = "profileId";
123 private static final String COLUMN_SIZE = "size";
124 private static final String COLUMN_PACKAGE = "packageName";
125 private static final String COLUMN_LAST_UPDATED = "lastUpdated";
126 private static final String COLUMN_VERSION = "version";
127 private static final String COLUMN_PREVIEW_BITMAP = "preview_bitmap";
Michael Jurka05713af2013-01-23 12:39:24 +0100128
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100129 public CacheDb(Context context) {
Sunny Goyal6f709362015-12-17 17:09:36 -0800130 super(context, LauncherFiles.WIDGET_PREVIEWS_DB, DB_VERSION, TABLE_NAME);
Michael Jurka05713af2013-01-23 12:39:24 +0100131 }
132
133 @Override
Sunny Goyal6f709362015-12-17 17:09:36 -0800134 public void onCreateTable(SQLiteDatabase database) {
Michael Jurka32b7a092013-02-07 20:06:49 +0100135 database.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" +
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700136 COLUMN_COMPONENT + " TEXT NOT NULL, " +
137 COLUMN_USER + " INTEGER NOT NULL, " +
Michael Jurka05713af2013-01-23 12:39:24 +0100138 COLUMN_SIZE + " TEXT NOT NULL, " +
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700139 COLUMN_PACKAGE + " TEXT NOT NULL, " +
140 COLUMN_LAST_UPDATED + " INTEGER NOT NULL DEFAULT 0, " +
141 COLUMN_VERSION + " INTEGER NOT NULL DEFAULT 0, " +
142 COLUMN_PREVIEW_BITMAP + " BLOB, " +
143 "PRIMARY KEY (" + COLUMN_COMPONENT + ", " + COLUMN_USER + ", " + COLUMN_SIZE + ") " +
Michael Jurka32b7a092013-02-07 20:06:49 +0100144 ");");
Michael Jurka05713af2013-01-23 12:39:24 +0100145 }
Michael Jurka05713af2013-01-23 12:39:24 +0100146 }
147
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700148 @Thunk void writeToDb(WidgetCacheKey key, long[] versions, Bitmap preview) {
Michael Jurka05713af2013-01-23 12:39:24 +0100149 ContentValues values = new ContentValues();
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700150 values.put(CacheDb.COLUMN_COMPONENT, key.componentName.flattenToShortString());
151 values.put(CacheDb.COLUMN_USER, mUserManager.getSerialNumberForUser(key.user));
152 values.put(CacheDb.COLUMN_SIZE, key.size);
153 values.put(CacheDb.COLUMN_PACKAGE, key.componentName.getPackageName());
154 values.put(CacheDb.COLUMN_VERSION, versions[0]);
155 values.put(CacheDb.COLUMN_LAST_UPDATED, versions[1]);
Sunny Goyale62d2bb2018-11-06 10:28:37 -0800156 values.put(CacheDb.COLUMN_PREVIEW_BITMAP, GraphicsUtils.flattenBitmap(preview));
Sunny Goyal6f709362015-12-17 17:09:36 -0800157 mDb.insertOrReplace(values);
Michael Jurka05713af2013-01-23 12:39:24 +0100158 }
159
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800160 public void removePackage(String packageName, UserHandle user) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700161 removePackage(packageName, user, mUserManager.getSerialNumberForUser(user));
162 }
163
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800164 private void removePackage(String packageName, UserHandle user, long userSerial) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700165 synchronized(mPackageVersions) {
166 mPackageVersions.remove(packageName);
167 }
168
Sunny Goyal6f709362015-12-17 17:09:36 -0800169 mDb.delete(
170 CacheDb.COLUMN_PACKAGE + " = ? AND " + CacheDb.COLUMN_USER + " = ?",
171 new String[]{packageName, Long.toString(userSerial)});
Michael Jurka8ff02ca2013-11-01 14:19:27 +0100172 }
173
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700174 /**
175 * Updates the persistent DB:
176 * 1. Any preview generated for an old package version is removed
177 * 2. Any preview for an absent package is removed
178 * This ensures that we remove entries for packages which changed while the launcher was dead.
Tony Wickham86222d22017-03-29 15:30:43 -0700179 *
180 * @param packageUser if provided, specifies that list only contains previews for the
181 * given package/user, otherwise the list contains all previews
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700182 */
Tony Wickham86222d22017-03-29 15:30:43 -0700183 public void removeObsoletePreviews(ArrayList<? extends ComponentKey> list,
184 @Nullable PackageUserKey packageUser) {
Sunny Goyal6388b2c2016-04-15 18:03:27 -0700185 Preconditions.assertWorkerThread();
Hyunyoung Song8821ca92015-05-04 16:28:20 -0700186
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700187 LongSparseArray<HashSet<String>> validPackages = new LongSparseArray<>();
188
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800189 for (ComponentKey key : list) {
190 final long userId = mUserManager.getSerialNumberForUser(key.user);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700191 HashSet<String> packages = validPackages.get(userId);
192 if (packages == null) {
193 packages = new HashSet<>();
194 validPackages.put(userId, packages);
195 }
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800196 packages.add(key.componentName.getPackageName());
Michael Jurka05713af2013-01-23 12:39:24 +0100197 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700198
199 LongSparseArray<HashSet<String>> packagesToDelete = new LongSparseArray<>();
Tony Wickham86222d22017-03-29 15:30:43 -0700200 long passedUserId = packageUser == null ? 0
201 : mUserManager.getSerialNumberForUser(packageUser.mUser);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700202 Cursor c = null;
203 try {
Sunny Goyal6f709362015-12-17 17:09:36 -0800204 c = mDb.query(
205 new String[]{CacheDb.COLUMN_USER, CacheDb.COLUMN_PACKAGE,
206 CacheDb.COLUMN_LAST_UPDATED, CacheDb.COLUMN_VERSION},
207 null, null);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700208 while (c.moveToNext()) {
209 long userId = c.getLong(0);
210 String pkg = c.getString(1);
211 long lastUpdated = c.getLong(2);
212 long version = c.getLong(3);
213
Tony Wickham86222d22017-03-29 15:30:43 -0700214 if (packageUser != null && (!pkg.equals(packageUser.mPackageName)
215 || userId != passedUserId)) {
216 // This preview is associated with a different package/user, no need to remove.
217 continue;
218 }
219
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700220 HashSet<String> packages = validPackages.get(userId);
221 if (packages != null && packages.contains(pkg)) {
222 long[] versions = getPackageVersion(pkg);
223 if (versions[0] == version && versions[1] == lastUpdated) {
224 // Every thing checks out
225 continue;
226 }
227 }
228
229 // We need to delete this package.
230 packages = packagesToDelete.get(userId);
231 if (packages == null) {
232 packages = new HashSet<>();
233 packagesToDelete.put(userId, packages);
234 }
235 packages.add(pkg);
236 }
237
238 for (int i = 0; i < packagesToDelete.size(); i++) {
239 long userId = packagesToDelete.keyAt(i);
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800240 UserHandle user = mUserManager.getUserForSerialNumber(userId);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700241 for (String pkg : packagesToDelete.valueAt(i)) {
242 removePackage(pkg, user, userId);
243 }
244 }
245 } catch (SQLException e) {
Sunny Goyal6f709362015-12-17 17:09:36 -0800246 Log.e(TAG, "Error updating widget previews", e);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700247 } finally {
248 if (c != null) {
249 c.close();
250 }
251 }
252 }
253
Winson Chung05304db2015-05-18 16:53:20 -0700254 /**
255 * Reads the preview bitmap from the DB or null if the preview is not in the DB.
256 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700257 @Thunk Bitmap readFromDb(WidgetCacheKey key, Bitmap recycle, PreviewLoadTask loadTask) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700258 Cursor cursor = null;
259 try {
Sunny Goyal6f709362015-12-17 17:09:36 -0800260 cursor = mDb.query(
261 new String[]{CacheDb.COLUMN_PREVIEW_BITMAP},
262 CacheDb.COLUMN_COMPONENT + " = ? AND " + CacheDb.COLUMN_USER + " = ? AND "
263 + CacheDb.COLUMN_SIZE + " = ?",
264 new String[]{
Sunny Goyal3ef86912016-10-27 11:40:06 -0700265 key.componentName.flattenToShortString(),
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700266 Long.toString(mUserManager.getSerialNumberForUser(key.user)),
267 key.size
Sunny Goyal6f709362015-12-17 17:09:36 -0800268 });
Winson Chung05304db2015-05-18 16:53:20 -0700269 // If cancelled, skip getting the blob and decoding it into a bitmap
270 if (loadTask.isCancelled()) {
271 return null;
272 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700273 if (cursor.moveToNext()) {
274 byte[] blob = cursor.getBlob(0);
275 BitmapFactory.Options opts = new BitmapFactory.Options();
276 opts.inBitmap = recycle;
Michael Jurka6e27f642013-12-10 13:40:30 +0100277 try {
Winson Chung05304db2015-05-18 16:53:20 -0700278 if (!loadTask.isCancelled()) {
279 return BitmapFactory.decodeByteArray(blob, 0, blob.length, opts);
280 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700281 } catch (Exception e) {
282 return null;
Michael Jurka6e27f642013-12-10 13:40:30 +0100283 }
Michael Jurka05713af2013-01-23 12:39:24 +0100284 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700285 } catch (SQLException e) {
286 Log.w(TAG, "Error loading preview from DB", e);
287 } finally {
288 if (cursor != null) {
289 cursor.close();
290 }
291 }
292 return null;
Michael Jurka05713af2013-01-23 12:39:24 +0100293 }
294
Sunny Goyal27835952017-01-13 12:15:53 -0800295 private Bitmap generatePreview(BaseActivity launcher, WidgetItem item, Bitmap recycle,
Adam Cohen2e6da152015-05-06 11:42:25 -0700296 int previewWidth, int previewHeight) {
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800297 if (item.widgetInfo != null) {
298 return generateWidgetPreview(launcher, item.widgetInfo,
Adam Cohen2e6da152015-05-06 11:42:25 -0700299 previewWidth, recycle, null);
Michael Jurka05713af2013-01-23 12:39:24 +0100300 } else {
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800301 return generateShortcutPreview(launcher, item.activityInfo,
302 previewWidth, previewHeight, recycle);
Michael Jurka05713af2013-01-23 12:39:24 +0100303 }
304 }
305
Hyunyoung Song3e840f42016-03-01 11:57:44 -0800306 /**
307 * Generates the widget preview from either the {@link AppWidgetManagerCompat} or cache
308 * and add badge at the bottom right corner.
309 *
310 * @param launcher
311 * @param info information about the widget
312 * @param maxPreviewWidth width of the preview on either workspace or tray
313 * @param preview bitmap that can be recycled
314 * @param preScaledWidthOut return the width of the returned bitmap
315 * @return
316 */
Sunny Goyal27835952017-01-13 12:15:53 -0800317 public Bitmap generateWidgetPreview(BaseActivity launcher, LauncherAppWidgetProviderInfo info,
Sunny Goyal4cad7532015-03-18 15:56:30 -0700318 int maxPreviewWidth, Bitmap preview, int[] preScaledWidthOut) {
Michael Jurka05713af2013-01-23 12:39:24 +0100319 // Load the preview image if possible
Michael Jurka05713af2013-01-23 12:39:24 +0100320 if (maxPreviewWidth < 0) maxPreviewWidth = Integer.MAX_VALUE;
Michael Jurka05713af2013-01-23 12:39:24 +0100321
322 Drawable drawable = null;
Sunny Goyalffe83f12014-08-14 17:39:34 -0700323 if (info.previewImage != 0) {
Sunny Goyal2570d102016-10-27 11:38:45 -0700324 try {
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800325 drawable = info.loadPreviewImage(mContext, 0);
Sunny Goyal2570d102016-10-27 11:38:45 -0700326 } catch (OutOfMemoryError e) {
327 Log.w(TAG, "Error loading widget preview for: " + info.provider, e);
328 // During OutOfMemoryError, the previous heap stack is not affected. Catching
329 // an OOM error here should be safe & not affect other parts of launcher.
330 drawable = null;
331 }
Adrian Roosfa9ffc22014-05-12 15:59:59 +0200332 if (drawable != null) {
333 drawable = mutateOnMainThread(drawable);
334 } else {
Michael Jurka05713af2013-01-23 12:39:24 +0100335 Log.w(TAG, "Can't load widget preview drawable 0x" +
Sunny Goyalffe83f12014-08-14 17:39:34 -0700336 Integer.toHexString(info.previewImage) + " for provider: " + info.provider);
Michael Jurka05713af2013-01-23 12:39:24 +0100337 }
338 }
339
Sunny Goyal4cad7532015-03-18 15:56:30 -0700340 final boolean widgetPreviewExists = (drawable != null);
Sunny Goyal233ee962015-08-03 13:05:01 -0700341 final int spanX = info.spanX;
342 final int spanY = info.spanY;
Sunny Goyal4cad7532015-03-18 15:56:30 -0700343
Michael Jurka05713af2013-01-23 12:39:24 +0100344 int previewWidth;
345 int previewHeight;
Hyunyoung Song3e840f42016-03-01 11:57:44 -0800346
Roger Olsson4ac406d2018-04-12 10:08:01 +0200347 if (widgetPreviewExists && drawable.getIntrinsicWidth() > 0
348 && drawable.getIntrinsicHeight() > 0) {
Michael Jurka05713af2013-01-23 12:39:24 +0100349 previewWidth = drawable.getIntrinsicWidth();
350 previewHeight = drawable.getIntrinsicHeight();
351 } else {
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800352 DeviceProfile dp = launcher.getDeviceProfile();
353 int tileSize = Math.min(dp.cellWidthPx, dp.cellHeightPx);
354 previewWidth = tileSize * spanX;
355 previewHeight = tileSize * spanY;
Michael Jurka05713af2013-01-23 12:39:24 +0100356 }
357
358 // Scale to fit width only - let the widget preview be clipped in the
359 // vertical dimension
360 float scale = 1f;
361 if (preScaledWidthOut != null) {
362 preScaledWidthOut[0] = previewWidth;
363 }
364 if (previewWidth > maxPreviewWidth) {
Sunny Goyala2441e82017-01-14 13:40:15 -0800365 scale = maxPreviewWidth / (float) (previewWidth);
Michael Jurka05713af2013-01-23 12:39:24 +0100366 }
367 if (scale != 1f) {
Roger Olsson4ac406d2018-04-12 10:08:01 +0200368 previewWidth = Math.max((int)(scale * previewWidth), 1);
369 previewHeight = Math.max((int)(scale * previewHeight), 1);
Michael Jurka05713af2013-01-23 12:39:24 +0100370 }
371
372 // 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 -0700373 final Canvas c = new Canvas();
Michael Jurka05713af2013-01-23 12:39:24 +0100374 if (preview == null) {
375 preview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700376 c.setBitmap(preview);
377 } else {
Sunny Goyala2441e82017-01-14 13:40:15 -0800378 // We use the preview bitmap height to determine where the badge will be drawn in the
379 // UI. If its larger than what we need, resize the preview bitmap so that there are
380 // no transparent pixels between the preview and the badge.
381 if (preview.getHeight() > previewHeight) {
382 preview.reconfigure(preview.getWidth(), previewHeight, preview.getConfig());
383 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700384 // Reusing bitmap. Clear it.
385 c.setBitmap(preview);
386 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100387 }
388
389 // Draw the scaled preview into the final bitmap
Hyunyoung Songb9f932e2015-07-30 15:04:59 -0700390 int x = (preview.getWidth() - previewWidth) / 2;
Michael Jurka05713af2013-01-23 12:39:24 +0100391 if (widgetPreviewExists) {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700392 drawable.setBounds(x, 0, x + previewWidth, previewHeight);
393 drawable.draw(c);
Michael Jurka05713af2013-01-23 12:39:24 +0100394 } else {
Sunny Goyalb3648e02017-05-02 16:17:10 -0700395 RectF boxRect = drawBoxWithShadow(c, previewWidth, previewHeight);
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800396
397 // Draw horizontal and vertical lines to represent individual columns.
Sunny Goyalb3648e02017-05-02 16:17:10 -0700398 final Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800399 p.setStyle(Paint.Style.STROKE);
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800400 p.setStrokeWidth(mContext.getResources()
401 .getDimension(R.dimen.widget_preview_cell_divider_width));
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800402 p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
403
404 float t = boxRect.left;
405 float tileSize = boxRect.width() / spanX;
406 for (int i = 1; i < spanX; i++) {
407 t += tileSize;
408 c.drawLine(t, 0, t, previewHeight, p);
Michael Jurka05713af2013-01-23 12:39:24 +0100409 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700410
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800411 t = boxRect.top;
412 tileSize = boxRect.height() / spanY;
413 for (int i = 1; i < spanY; i++) {
414 t += tileSize;
415 c.drawLine(0, t, previewWidth, t, p);
416 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700417
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800418 // Draw icon in the center.
Sunny Goyal4cad7532015-03-18 15:56:30 -0700419 try {
Sunny Goyal952e63d2017-08-16 04:59:08 -0700420 Drawable icon =
421 mIconCache.getFullResIcon(info.provider.getPackageName(), info.icon);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700422 if (icon != null) {
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800423 int appIconSize = launcher.getDeviceProfile().iconSizePx;
424 int iconSize = (int) Math.min(appIconSize * scale,
425 Math.min(boxRect.width(), boxRect.height()));
426
Sunny Goyal1ba7e362015-10-26 10:42:12 -0700427 icon = mutateOnMainThread(icon);
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800428 int hoffset = (previewWidth - iconSize) / 2;
429 int yoffset = (previewHeight - iconSize) / 2;
430 icon.setBounds(hoffset, yoffset, hoffset + iconSize, yoffset + iconSize);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700431 icon.draw(c);
432 }
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800433 } catch (Resources.NotFoundException e) { }
Michael Jurka05713af2013-01-23 12:39:24 +0100434 c.setBitmap(null);
435 }
Sunny Goyala2441e82017-01-14 13:40:15 -0800436 return preview;
Michael Jurka05713af2013-01-23 12:39:24 +0100437 }
438
Sunny Goyalb3648e02017-05-02 16:17:10 -0700439 private RectF drawBoxWithShadow(Canvas c, int width, int height) {
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800440 Resources res = mContext.getResources();
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800441
Sunny Goyale463c8f2017-06-20 13:34:09 -0700442 ShadowGenerator.Builder builder = new ShadowGenerator.Builder(Color.WHITE);
443 builder.shadowBlur = res.getDimension(R.dimen.widget_preview_shadow_blur);
444 builder.radius = res.getDimension(R.dimen.widget_preview_corner_radius);
445 builder.keyShadowDistance = res.getDimension(R.dimen.widget_preview_key_shadow_distance);
446
447 builder.bounds.set(builder.shadowBlur, builder.shadowBlur,
448 width - builder.shadowBlur,
449 height - builder.shadowBlur - builder.keyShadowDistance);
450 builder.drawShadow(c);
451 return builder.bounds;
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800452 }
453
Sunny Goyal782f0c92017-01-19 10:27:54 -0800454 private Bitmap generateShortcutPreview(BaseActivity launcher, ShortcutConfigActivityInfo info,
455 int maxWidth, int maxHeight, Bitmap preview) {
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800456 int iconSize = launcher.getDeviceProfile().iconSizePx;
457 int padding = launcher.getResources()
458 .getDimensionPixelSize(R.dimen.widget_preview_shortcut_padding);
459
460 int size = iconSize + 2 * padding;
461 if (maxHeight < size || maxWidth < size) {
462 throw new RuntimeException("Max size is too small for preview");
463 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700464 final Canvas c = new Canvas();
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800465 if (preview == null || preview.getWidth() < size || preview.getHeight() < size) {
466 preview = Bitmap.createBitmap(size, size, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700467 c.setBitmap(preview);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700468 } else {
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800469 if (preview.getWidth() > size || preview.getHeight() > size) {
470 preview.reconfigure(size, size, preview.getConfig());
471 }
472
Sunny Goyal4cad7532015-03-18 15:56:30 -0700473 // Reusing bitmap. Clear it.
474 c.setBitmap(preview);
475 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100476 }
Sunny Goyalb3648e02017-05-02 16:17:10 -0700477 RectF boxRect = drawBoxWithShadow(c, size, size);
Michael Jurka05713af2013-01-23 12:39:24 +0100478
Sunny Goyal18a4e5a2018-01-09 15:34:38 -0800479 LauncherIcons li = LauncherIcons.obtain(mContext);
Hyunyoung Song2bf3f372019-04-02 10:45:57 -0700480 Bitmap icon = li.createBadgedIconBitmap(
481 mutateOnMainThread(info.getFullResIcon(mIconCache)),
482 Process.myUserHandle(), 0).icon;
Sunny Goyal18a4e5a2018-01-09 15:34:38 -0800483 li.recycle();
484
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800485 Rect src = new Rect(0, 0, icon.getWidth(), icon.getHeight());
Sunny Goyal4cad7532015-03-18 15:56:30 -0700486
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800487 boxRect.set(0, 0, iconSize, iconSize);
488 boxRect.offset(padding, padding);
Sunny Goyalb3648e02017-05-02 16:17:10 -0700489 c.drawBitmap(icon, src, boxRect,
490 new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG));
Michael Jurka05713af2013-01-23 12:39:24 +0100491 c.setBitmap(null);
Michael Jurka05713af2013-01-23 12:39:24 +0100492 return preview;
493 }
494
Adrian Roos65d60e22014-04-15 21:07:49 +0200495 private Drawable mutateOnMainThread(final Drawable drawable) {
496 try {
497 return mMainThreadExecutor.submit(new Callable<Drawable>() {
498 @Override
499 public Drawable call() throws Exception {
500 return drawable.mutate();
501 }
502 }).get();
503 } catch (InterruptedException e) {
504 Thread.currentThread().interrupt();
505 throw new RuntimeException(e);
506 } catch (ExecutionException e) {
507 throw new RuntimeException(e);
508 }
509 }
Adrian Roos1f375ab2014-04-28 18:26:38 +0200510
Adrian Roos1f375ab2014-04-28 18:26:38 +0200511 /**
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700512 * @return an array of containing versionCode and lastUpdatedTime for the package.
Adrian Roos1f375ab2014-04-28 18:26:38 +0200513 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700514 @Thunk long[] getPackageVersion(String packageName) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700515 synchronized (mPackageVersions) {
516 long[] versions = mPackageVersions.get(packageName);
517 if (versions == null) {
518 versions = new long[2];
Adrian Roos1f375ab2014-04-28 18:26:38 +0200519 try {
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800520 PackageInfo info = mContext.getPackageManager().getPackageInfo(packageName,
521 PackageManager.GET_UNINSTALLED_PACKAGES);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700522 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
Sunny Goyalc65a0082017-03-08 14:49:55 -0800533 public class PreviewLoadTask extends AsyncTask<Void, Void, Bitmap>
534 implements CancellationSignal.OnCancelListener {
Sunny Goyal316490e2015-06-02 09:38:28 -0700535 @Thunk final WidgetCacheKey mKey;
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800536 private final WidgetItem mInfo;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700537 private final int mPreviewHeight;
538 private final int mPreviewWidth;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700539 private final WidgetCell mCaller;
Sunny Goyala2441e82017-01-14 13:40:15 -0800540 private final BaseActivity mActivity;
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,
Sunny Goyalf1fbc3f2017-10-10 15:21:15 -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;
Sunny Goyala2441e82017-01-14 13:40:15 -0800551 mActivity = BaseActivity.fromContext(mCaller.getContext());
Hyunyoung Song3f471442015-04-08 19:01:34 -0700552 if (DEBUG) {
553 Log.d(TAG, String.format("%s, %s, %d, %d",
554 mKey, mInfo, mPreviewHeight, mPreviewWidth));
555 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700556 }
557
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700558 @Override
559 protected Bitmap doInBackground(Void... params) {
560 Bitmap unusedBitmap = null;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700561
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700562 // If already cancelled before this gets to run in the background, then return early
563 if (isCancelled()) {
564 return null;
565 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700566 synchronized (mUnusedBitmaps) {
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700567 // Check if we can re-use a bitmap
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700568 for (Bitmap candidate : mUnusedBitmaps) {
569 if (candidate != null && candidate.isMutable() &&
570 candidate.getWidth() == mPreviewWidth &&
571 candidate.getHeight() == mPreviewHeight) {
572 unusedBitmap = candidate;
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700573 mUnusedBitmaps.remove(unusedBitmap);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700574 break;
575 }
576 }
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700577 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700578
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700579 // creating a bitmap is expensive. Do not do this inside synchronized block.
580 if (unusedBitmap == null) {
581 unusedBitmap = Bitmap.createBitmap(mPreviewWidth, mPreviewHeight, Config.ARGB_8888);
Adrian Roos1f375ab2014-04-28 18:26:38 +0200582 }
Winson Chung05304db2015-05-18 16:53:20 -0700583 // If cancelled now, don't bother reading the preview from the DB
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700584 if (isCancelled()) {
Winson Chung05304db2015-05-18 16:53:20 -0700585 return unusedBitmap;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700586 }
Winson Chung05304db2015-05-18 16:53:20 -0700587 Bitmap preview = readFromDb(mKey, unusedBitmap, this);
588 // Only consider generating the preview if we have not cancelled the task already
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700589 if (!isCancelled() && preview == null) {
590 // Fetch the version info before we generate the preview, so that, in-case the
591 // app was updated while we are generating the preview, we use the old version info,
592 // which would gets re-written next time.
Sunny Goyal65513ba2017-01-20 11:54:25 -0800593 boolean persistable = mInfo.activityInfo == null
594 || mInfo.activityInfo.isPersistable();
595 mVersions = persistable ? getPackageVersion(mKey.componentName.getPackageName())
596 : null;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700597
598 // it's not in the db... we need to generate it
Sunny Goyala2441e82017-01-14 13:40:15 -0800599 preview = generatePreview(mActivity, mInfo, unusedBitmap, mPreviewWidth, mPreviewHeight);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700600 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700601 return preview;
602 }
603
604 @Override
Winson Chung05304db2015-05-18 16:53:20 -0700605 protected void onPostExecute(final Bitmap preview) {
Sunny Goyalf1fbc3f2017-10-10 15:21:15 -0700606 mCaller.applyPreview(preview);
Winson Chung05304db2015-05-18 16:53:20 -0700607
608 // Write the generated preview to the DB in the worker thread
609 if (mVersions != null) {
610 mWorkerHandler.post(new Runnable() {
611 @Override
612 public void run() {
613 if (!isCancelled()) {
614 // If we are still using this preview, then write it to the DB and then
615 // let the normal clear mechanism recycle the bitmap
616 writeToDb(mKey, mVersions, preview);
617 mBitmapToRecycle = preview;
618 } else {
619 // If we've already cancelled, then skip writing the bitmap to the DB
620 // and manually add the bitmap back to the recycled set
621 synchronized (mUnusedBitmaps) {
622 mUnusedBitmaps.add(preview);
623 }
624 }
625 }
626 });
627 } else {
628 // If we don't need to write to disk, then ensure the preview gets recycled by
629 // the normal clear mechanism
630 mBitmapToRecycle = preview;
631 }
632 }
633
634 @Override
Hyunyoung Songe98f4a42015-06-16 10:45:24 -0700635 protected void onCancelled(final Bitmap preview) {
Winson Chung05304db2015-05-18 16:53:20 -0700636 // If we've cancelled while the task is running, then can return the bitmap to the
637 // recycled set immediately. Otherwise, it will be recycled after the preview is written
638 // to disk.
639 if (preview != null) {
Hyunyoung Songe98f4a42015-06-16 10:45:24 -0700640 mWorkerHandler.post(new Runnable() {
641 @Override
642 public void run() {
643 synchronized (mUnusedBitmaps) {
644 mUnusedBitmaps.add(preview);
645 }
646 }
647 });
Winson Chung05304db2015-05-18 16:53:20 -0700648 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700649 }
Sunny Goyalc65a0082017-03-08 14:49:55 -0800650
651 @Override
652 public void onCancel() {
653 cancel(true);
654
655 // This only handles the case where the PreviewLoadTask is cancelled after the task has
656 // successfully completed (including having written to disk when necessary). In the
657 // other cases where it is cancelled while the task is running, it will be cleaned up
658 // in the tasks's onCancelled() call, and if cancelled while the task is writing to
659 // disk, it will be cancelled in the task's onPostExecute() call.
660 if (mBitmapToRecycle != null) {
661 mWorkerHandler.post(new Runnable() {
662 @Override
663 public void run() {
664 synchronized (mUnusedBitmaps) {
665 mUnusedBitmaps.add(mBitmapToRecycle);
666 }
667 mBitmapToRecycle = null;
668 }
669 });
670 }
671 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700672 }
673
674 private static final class WidgetCacheKey extends ComponentKey {
675
Sunny Goyal316490e2015-06-02 09:38:28 -0700676 @Thunk final String size;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700677
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800678 public WidgetCacheKey(ComponentName componentName, UserHandle user, String size) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700679 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}