blob: abf6cbd5ad485a40e9846b7e77c8b513209c5ec2 [file] [log] [blame]
Daniel Sandler325dc232013-06-05 22:57:57 -04001package com.android.launcher3;
Michael Jurka05713af2013-01-23 12:39:24 +01002
Sunny Goyal6fe3eec2019-08-15 14:53:41 -07003import static com.android.launcher3.util.Executors.MAIN_EXECUTOR;
4import static com.android.launcher3.util.Executors.MODEL_EXECUTOR;
5
Michael Jurka05713af2013-01-23 12:39:24 +01006import android.content.ComponentName;
7import android.content.ContentValues;
8import android.content.Context;
Sunny Goyal5b0e6692015-03-19 14:31:19 -07009import android.content.pm.PackageInfo;
Sunny Goyal4ddc4012016-03-10 12:02:29 -080010import android.content.pm.PackageManager;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070011import android.content.pm.PackageManager.NameNotFoundException;
Michael Jurka05713af2013-01-23 12:39:24 +010012import android.content.res.Resources;
13import android.database.Cursor;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070014import android.database.SQLException;
Michael Jurka05713af2013-01-23 12:39:24 +010015import android.database.sqlite.SQLiteDatabase;
Michael Jurka05713af2013-01-23 12:39:24 +010016import android.graphics.Bitmap;
17import android.graphics.Bitmap.Config;
18import android.graphics.BitmapFactory;
19import android.graphics.Canvas;
Sunny Goyal7d87cb12017-02-13 10:44:43 -080020import android.graphics.Color;
Michael Jurka05713af2013-01-23 12:39:24 +010021import android.graphics.Paint;
22import android.graphics.PorterDuff;
Sunny Goyal92bbfa12017-02-07 15:06:32 -080023import android.graphics.PorterDuffXfermode;
Sunny Goyal7d87cb12017-02-13 10:44:43 -080024import android.graphics.Rect;
Sunny Goyal4cad7532015-03-18 15:56:30 -070025import android.graphics.RectF;
Michael Jurka05713af2013-01-23 12:39:24 +010026import android.graphics.drawable.Drawable;
27import android.os.AsyncTask;
Sunny Goyalc65a0082017-03-08 14:49:55 -080028import android.os.CancellationSignal;
Hyunyoung Song2bf3f372019-04-02 10:45:57 -070029import android.os.Process;
Sunny Goyal7c74e4a2016-12-15 15:53:17 -080030import android.os.UserHandle;
Michael Jurka05713af2013-01-23 12:39:24 +010031import android.util.Log;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070032import android.util.LongSparseArray;
Samuel Fufa15357962019-09-03 12:36:15 -070033import android.util.Pair;
Sunny Goyal383c5072015-06-12 21:18:53 -070034
Sunny Goyal6fe3eec2019-08-15 14:53:41 -070035import androidx.annotation.Nullable;
36
Sunny Goyalffe83f12014-08-14 17:39:34 -070037import com.android.launcher3.compat.AppWidgetManagerCompat;
Sunny Goyal782f0c92017-01-19 10:27:54 -080038import com.android.launcher3.compat.ShortcutConfigActivityInfo;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070039import com.android.launcher3.compat.UserManagerCompat;
Sunny Goyale62d2bb2018-11-06 10:28:37 -080040import com.android.launcher3.icons.GraphicsUtils;
Sunny Goyal6fe3eec2019-08-15 14:53:41 -070041import com.android.launcher3.icons.IconCache;
Hyunyoung Song48cb7bc2018-09-25 17:03:34 -070042import com.android.launcher3.icons.LauncherIcons;
43import com.android.launcher3.icons.ShadowGenerator;
Sunny Goyal4ddc4012016-03-10 12:02:29 -080044import com.android.launcher3.model.WidgetItem;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070045import com.android.launcher3.util.ComponentKey;
Sunny Goyal6fe3eec2019-08-15 14:53:41 -070046import com.android.launcher3.util.Executors;
Tony Wickham86222d22017-03-29 15:30:43 -070047import com.android.launcher3.util.PackageUserKey;
Sunny Goyal6388b2c2016-04-15 18:03:27 -070048import com.android.launcher3.util.Preconditions;
Sunny Goyal6f709362015-12-17 17:09:36 -080049import com.android.launcher3.util.SQLiteCacheHelper;
Adam Cohen091440a2015-03-18 14:16:05 -070050import com.android.launcher3.util.Thunk;
Hyunyoung Song3f471442015-04-08 19:01:34 -070051import com.android.launcher3.widget.WidgetCell;
Hyunyoung Song8821ca92015-05-04 16:28:20 -070052
53import java.util.ArrayList;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070054import java.util.Collections;
Michael Jurka05713af2013-01-23 12:39:24 +010055import java.util.HashMap;
56import java.util.HashSet;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070057import java.util.Set;
58import java.util.WeakHashMap;
Adrian Roos65d60e22014-04-15 21:07:49 +020059import java.util.concurrent.ExecutionException;
Michael Jurka05713af2013-01-23 12:39:24 +010060
Sunny Goyalffe83f12014-08-14 17:39:34 -070061public class WidgetPreviewLoader {
Michael Jurka05713af2013-01-23 12:39:24 +010062
Sunny Goyalffe83f12014-08-14 17:39:34 -070063 private static final String TAG = "WidgetPreviewLoader";
Hyunyoung Song3f471442015-04-08 19:01:34 -070064 private static final boolean DEBUG = false;
Sunny Goyalffe83f12014-08-14 17:39:34 -070065
Sunny Goyal5b0e6692015-03-19 14:31:19 -070066 private final HashMap<String, long[]> mPackageVersions = new HashMap<>();
Hyunyoung Song559d90d2015-04-28 15:06:45 -070067
68 /**
69 * Weak reference objects, do not prevent their referents from being made finalizable,
70 * finalized, and then reclaimed.
Hyunyoung Songe98f4a42015-06-16 10:45:24 -070071 * Note: synchronized block used for this variable is expensive and the block should always
72 * be posted to a background thread.
Hyunyoung Song559d90d2015-04-28 15:06:45 -070073 */
Sunny Goyal6fe3eec2019-08-15 14:53:41 -070074 @Thunk final Set<Bitmap> mUnusedBitmaps = Collections.newSetFromMap(new WeakHashMap<>());
Sunny Goyal4cad7532015-03-18 15:56:30 -070075
76 private final Context mContext;
Sunny Goyalffe83f12014-08-14 17:39:34 -070077 private final IconCache mIconCache;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070078 private final UserManagerCompat mUserManager;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070079 private final CacheDb mDb;
Michael Jurka05713af2013-01-23 12:39:24 +010080
Sunny Goyal383c5072015-06-12 21:18:53 -070081 public WidgetPreviewLoader(Context context, IconCache iconCache) {
Chris Wrenfd13c712013-09-27 15:45:19 -040082 mContext = context;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070083 mIconCache = iconCache;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070084 mUserManager = UserManagerCompat.getInstance(context);
85 mDb = new CacheDb(context);
Michael Jurka3f4e0702013-02-05 11:21:28 +010086 }
Sunny Goyalffe83f12014-08-14 17:39:34 -070087
Sunny Goyal5b0e6692015-03-19 14:31:19 -070088 /**
89 * Generates the widget preview on {@link AsyncTask#THREAD_POOL_EXECUTOR}. Must be
90 * called on UI thread
91 *
Sunny Goyal5b0e6692015-03-19 14:31:19 -070092 * @return a request id which can be used to cancel the request.
93 */
Sunny Goyalc65a0082017-03-08 14:49:55 -080094 public CancellationSignal getPreview(WidgetItem item, int previewWidth,
Sunny Goyalf1fbc3f2017-10-10 15:21:15 -070095 int previewHeight, WidgetCell caller) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -070096 String size = previewWidth + "x" + previewHeight;
Sunny Goyal4ddc4012016-03-10 12:02:29 -080097 WidgetCacheKey key = new WidgetCacheKey(item.componentName, item.user, size);
Michael Jurka3f4e0702013-02-05 11:21:28 +010098
Sunny Goyalf1fbc3f2017-10-10 15:21:15 -070099 PreviewLoadTask task = new PreviewLoadTask(key, item, previewWidth, previewHeight, caller);
Sunny Goyal6fe3eec2019-08-15 14:53:41 -0700100 task.executeOnExecutor(Executors.THREAD_POOL_EXECUTOR);
Sunny Goyalc65a0082017-03-08 14:49:55 -0800101
102 CancellationSignal signal = new CancellationSignal();
103 signal.setOnCancelListener(task);
104 return signal;
Michael Jurka05713af2013-01-23 12:39:24 +0100105 }
106
Hyunyoung Song2bf3f372019-04-02 10:45:57 -0700107 public void refresh() {
108 mDb.clear();
109
110 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700111 /**
112 * The DB holds the generated previews for various components. Previews can also have different
113 * sizes (landscape vs portrait).
114 */
Sunny Goyal6f709362015-12-17 17:09:36 -0800115 private static class CacheDb extends SQLiteCacheHelper {
Jon Miranda6cdc16c2017-06-27 14:04:01 -0700116 private static final int DB_VERSION = 9;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700117
118 private static final String TABLE_NAME = "shortcut_and_widget_previews";
119 private static final String COLUMN_COMPONENT = "componentName";
120 private static final String COLUMN_USER = "profileId";
121 private static final String COLUMN_SIZE = "size";
122 private static final String COLUMN_PACKAGE = "packageName";
123 private static final String COLUMN_LAST_UPDATED = "lastUpdated";
124 private static final String COLUMN_VERSION = "version";
125 private static final String COLUMN_PREVIEW_BITMAP = "preview_bitmap";
Michael Jurka05713af2013-01-23 12:39:24 +0100126
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100127 public CacheDb(Context context) {
Sunny Goyal6f709362015-12-17 17:09:36 -0800128 super(context, LauncherFiles.WIDGET_PREVIEWS_DB, DB_VERSION, TABLE_NAME);
Michael Jurka05713af2013-01-23 12:39:24 +0100129 }
130
131 @Override
Sunny Goyal6f709362015-12-17 17:09:36 -0800132 public void onCreateTable(SQLiteDatabase database) {
Michael Jurka32b7a092013-02-07 20:06:49 +0100133 database.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" +
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700134 COLUMN_COMPONENT + " TEXT NOT NULL, " +
135 COLUMN_USER + " INTEGER NOT NULL, " +
Michael Jurka05713af2013-01-23 12:39:24 +0100136 COLUMN_SIZE + " TEXT NOT NULL, " +
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700137 COLUMN_PACKAGE + " TEXT NOT NULL, " +
138 COLUMN_LAST_UPDATED + " INTEGER NOT NULL DEFAULT 0, " +
139 COLUMN_VERSION + " INTEGER NOT NULL DEFAULT 0, " +
140 COLUMN_PREVIEW_BITMAP + " BLOB, " +
141 "PRIMARY KEY (" + COLUMN_COMPONENT + ", " + COLUMN_USER + ", " + COLUMN_SIZE + ") " +
Michael Jurka32b7a092013-02-07 20:06:49 +0100142 ");");
Michael Jurka05713af2013-01-23 12:39:24 +0100143 }
Michael Jurka05713af2013-01-23 12:39:24 +0100144 }
145
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700146 @Thunk void writeToDb(WidgetCacheKey key, long[] versions, Bitmap preview) {
Michael Jurka05713af2013-01-23 12:39:24 +0100147 ContentValues values = new ContentValues();
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700148 values.put(CacheDb.COLUMN_COMPONENT, key.componentName.flattenToShortString());
149 values.put(CacheDb.COLUMN_USER, mUserManager.getSerialNumberForUser(key.user));
150 values.put(CacheDb.COLUMN_SIZE, key.size);
151 values.put(CacheDb.COLUMN_PACKAGE, key.componentName.getPackageName());
152 values.put(CacheDb.COLUMN_VERSION, versions[0]);
153 values.put(CacheDb.COLUMN_LAST_UPDATED, versions[1]);
Sunny Goyale62d2bb2018-11-06 10:28:37 -0800154 values.put(CacheDb.COLUMN_PREVIEW_BITMAP, GraphicsUtils.flattenBitmap(preview));
Sunny Goyal6f709362015-12-17 17:09:36 -0800155 mDb.insertOrReplace(values);
Michael Jurka05713af2013-01-23 12:39:24 +0100156 }
157
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800158 public void removePackage(String packageName, UserHandle user) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700159 removePackage(packageName, user, mUserManager.getSerialNumberForUser(user));
160 }
161
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800162 private void removePackage(String packageName, UserHandle user, long userSerial) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700163 synchronized(mPackageVersions) {
164 mPackageVersions.remove(packageName);
165 }
166
Sunny Goyal6f709362015-12-17 17:09:36 -0800167 mDb.delete(
168 CacheDb.COLUMN_PACKAGE + " = ? AND " + CacheDb.COLUMN_USER + " = ?",
169 new String[]{packageName, Long.toString(userSerial)});
Michael Jurka8ff02ca2013-11-01 14:19:27 +0100170 }
171
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700172 /**
173 * Updates the persistent DB:
174 * 1. Any preview generated for an old package version is removed
175 * 2. Any preview for an absent package is removed
176 * This ensures that we remove entries for packages which changed while the launcher was dead.
Tony Wickham86222d22017-03-29 15:30:43 -0700177 *
178 * @param packageUser if provided, specifies that list only contains previews for the
179 * given package/user, otherwise the list contains all previews
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700180 */
Tony Wickham86222d22017-03-29 15:30:43 -0700181 public void removeObsoletePreviews(ArrayList<? extends ComponentKey> list,
182 @Nullable PackageUserKey packageUser) {
Sunny Goyal6388b2c2016-04-15 18:03:27 -0700183 Preconditions.assertWorkerThread();
Hyunyoung Song8821ca92015-05-04 16:28:20 -0700184
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700185 LongSparseArray<HashSet<String>> validPackages = new LongSparseArray<>();
186
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800187 for (ComponentKey key : list) {
188 final long userId = mUserManager.getSerialNumberForUser(key.user);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700189 HashSet<String> packages = validPackages.get(userId);
190 if (packages == null) {
191 packages = new HashSet<>();
192 validPackages.put(userId, packages);
193 }
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800194 packages.add(key.componentName.getPackageName());
Michael Jurka05713af2013-01-23 12:39:24 +0100195 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700196
197 LongSparseArray<HashSet<String>> packagesToDelete = new LongSparseArray<>();
Tony Wickham86222d22017-03-29 15:30:43 -0700198 long passedUserId = packageUser == null ? 0
199 : mUserManager.getSerialNumberForUser(packageUser.mUser);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700200 Cursor c = null;
201 try {
Sunny Goyal6f709362015-12-17 17:09:36 -0800202 c = mDb.query(
203 new String[]{CacheDb.COLUMN_USER, CacheDb.COLUMN_PACKAGE,
204 CacheDb.COLUMN_LAST_UPDATED, CacheDb.COLUMN_VERSION},
205 null, null);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700206 while (c.moveToNext()) {
207 long userId = c.getLong(0);
208 String pkg = c.getString(1);
209 long lastUpdated = c.getLong(2);
210 long version = c.getLong(3);
211
Tony Wickham86222d22017-03-29 15:30:43 -0700212 if (packageUser != null && (!pkg.equals(packageUser.mPackageName)
213 || userId != passedUserId)) {
214 // This preview is associated with a different package/user, no need to remove.
215 continue;
216 }
217
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700218 HashSet<String> packages = validPackages.get(userId);
219 if (packages != null && packages.contains(pkg)) {
220 long[] versions = getPackageVersion(pkg);
221 if (versions[0] == version && versions[1] == lastUpdated) {
222 // Every thing checks out
223 continue;
224 }
225 }
226
227 // We need to delete this package.
228 packages = packagesToDelete.get(userId);
229 if (packages == null) {
230 packages = new HashSet<>();
231 packagesToDelete.put(userId, packages);
232 }
233 packages.add(pkg);
234 }
235
236 for (int i = 0; i < packagesToDelete.size(); i++) {
237 long userId = packagesToDelete.keyAt(i);
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800238 UserHandle user = mUserManager.getUserForSerialNumber(userId);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700239 for (String pkg : packagesToDelete.valueAt(i)) {
240 removePackage(pkg, user, userId);
241 }
242 }
243 } catch (SQLException e) {
Sunny Goyal6f709362015-12-17 17:09:36 -0800244 Log.e(TAG, "Error updating widget previews", e);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700245 } finally {
246 if (c != null) {
247 c.close();
248 }
249 }
250 }
251
Winson Chung05304db2015-05-18 16:53:20 -0700252 /**
253 * Reads the preview bitmap from the DB or null if the preview is not in the DB.
254 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700255 @Thunk Bitmap readFromDb(WidgetCacheKey key, Bitmap recycle, PreviewLoadTask loadTask) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700256 Cursor cursor = null;
257 try {
Sunny Goyal6f709362015-12-17 17:09:36 -0800258 cursor = mDb.query(
259 new String[]{CacheDb.COLUMN_PREVIEW_BITMAP},
260 CacheDb.COLUMN_COMPONENT + " = ? AND " + CacheDb.COLUMN_USER + " = ? AND "
261 + CacheDb.COLUMN_SIZE + " = ?",
262 new String[]{
Sunny Goyal3ef86912016-10-27 11:40:06 -0700263 key.componentName.flattenToShortString(),
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700264 Long.toString(mUserManager.getSerialNumberForUser(key.user)),
265 key.size
Sunny Goyal6f709362015-12-17 17:09:36 -0800266 });
Winson Chung05304db2015-05-18 16:53:20 -0700267 // If cancelled, skip getting the blob and decoding it into a bitmap
268 if (loadTask.isCancelled()) {
269 return null;
270 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700271 if (cursor.moveToNext()) {
272 byte[] blob = cursor.getBlob(0);
273 BitmapFactory.Options opts = new BitmapFactory.Options();
274 opts.inBitmap = recycle;
Michael Jurka6e27f642013-12-10 13:40:30 +0100275 try {
Winson Chung05304db2015-05-18 16:53:20 -0700276 if (!loadTask.isCancelled()) {
277 return BitmapFactory.decodeByteArray(blob, 0, blob.length, opts);
278 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700279 } catch (Exception e) {
280 return null;
Michael Jurka6e27f642013-12-10 13:40:30 +0100281 }
Michael Jurka05713af2013-01-23 12:39:24 +0100282 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700283 } catch (SQLException e) {
284 Log.w(TAG, "Error loading preview from DB", e);
285 } finally {
286 if (cursor != null) {
287 cursor.close();
288 }
289 }
290 return null;
Michael Jurka05713af2013-01-23 12:39:24 +0100291 }
292
Samuel Fufa15357962019-09-03 12:36:15 -0700293 /**
294 * Returns generatedPreview for a widget and if the preview should be saved in persistent
295 * storage.
296 * @param launcher
297 * @param item
298 * @param recycle
299 * @param previewWidth
300 * @param previewHeight
301 * @return Pair<Bitmap, Boolean>
302 */
303 private Pair<Bitmap, Boolean> generatePreview(BaseActivity launcher, WidgetItem item,
304 Bitmap recycle,
Adam Cohen2e6da152015-05-06 11:42:25 -0700305 int previewWidth, int previewHeight) {
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800306 if (item.widgetInfo != null) {
307 return generateWidgetPreview(launcher, item.widgetInfo,
Adam Cohen2e6da152015-05-06 11:42:25 -0700308 previewWidth, recycle, null);
Michael Jurka05713af2013-01-23 12:39:24 +0100309 } else {
Samuel Fufa15357962019-09-03 12:36:15 -0700310 return new Pair<>(generateShortcutPreview(launcher, item.activityInfo,
311 previewWidth, previewHeight, recycle), false);
Michael Jurka05713af2013-01-23 12:39:24 +0100312 }
313 }
314
Hyunyoung Song3e840f42016-03-01 11:57:44 -0800315 /**
316 * Generates the widget preview from either the {@link AppWidgetManagerCompat} or cache
317 * and add badge at the bottom right corner.
318 *
319 * @param launcher
320 * @param info information about the widget
321 * @param maxPreviewWidth width of the preview on either workspace or tray
322 * @param preview bitmap that can be recycled
323 * @param preScaledWidthOut return the width of the returned bitmap
Samuel Fufa15357962019-09-03 12:36:15 -0700324 * @return Pair<Bitmap (the preview) , Boolean (should be stored in db)>
Hyunyoung Song3e840f42016-03-01 11:57:44 -0800325 */
Samuel Fufa15357962019-09-03 12:36:15 -0700326 public Pair<Bitmap, Boolean> generateWidgetPreview(BaseActivity launcher,
327 LauncherAppWidgetProviderInfo info,
Sunny Goyal4cad7532015-03-18 15:56:30 -0700328 int maxPreviewWidth, Bitmap preview, int[] preScaledWidthOut) {
Michael Jurka05713af2013-01-23 12:39:24 +0100329 // Load the preview image if possible
Michael Jurka05713af2013-01-23 12:39:24 +0100330 if (maxPreviewWidth < 0) maxPreviewWidth = Integer.MAX_VALUE;
Michael Jurka05713af2013-01-23 12:39:24 +0100331
332 Drawable drawable = null;
Sunny Goyalffe83f12014-08-14 17:39:34 -0700333 if (info.previewImage != 0) {
Sunny Goyal2570d102016-10-27 11:38:45 -0700334 try {
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800335 drawable = info.loadPreviewImage(mContext, 0);
Sunny Goyal2570d102016-10-27 11:38:45 -0700336 } catch (OutOfMemoryError e) {
337 Log.w(TAG, "Error loading widget preview for: " + info.provider, e);
338 // During OutOfMemoryError, the previous heap stack is not affected. Catching
339 // an OOM error here should be safe & not affect other parts of launcher.
340 drawable = null;
341 }
Adrian Roosfa9ffc22014-05-12 15:59:59 +0200342 if (drawable != null) {
343 drawable = mutateOnMainThread(drawable);
344 } else {
Michael Jurka05713af2013-01-23 12:39:24 +0100345 Log.w(TAG, "Can't load widget preview drawable 0x" +
Sunny Goyalffe83f12014-08-14 17:39:34 -0700346 Integer.toHexString(info.previewImage) + " for provider: " + info.provider);
Michael Jurka05713af2013-01-23 12:39:24 +0100347 }
348 }
349
Sunny Goyal4cad7532015-03-18 15:56:30 -0700350 final boolean widgetPreviewExists = (drawable != null);
Sunny Goyal233ee962015-08-03 13:05:01 -0700351 final int spanX = info.spanX;
352 final int spanY = info.spanY;
Sunny Goyal4cad7532015-03-18 15:56:30 -0700353
Michael Jurka05713af2013-01-23 12:39:24 +0100354 int previewWidth;
355 int previewHeight;
Hyunyoung Song3e840f42016-03-01 11:57:44 -0800356
Samuel Fufa15357962019-09-03 12:36:15 -0700357 boolean savePreviewImage = widgetPreviewExists || info.previewImage == 0;
358
Roger Olsson4ac406d2018-04-12 10:08:01 +0200359 if (widgetPreviewExists && drawable.getIntrinsicWidth() > 0
360 && drawable.getIntrinsicHeight() > 0) {
Michael Jurka05713af2013-01-23 12:39:24 +0100361 previewWidth = drawable.getIntrinsicWidth();
362 previewHeight = drawable.getIntrinsicHeight();
363 } else {
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800364 DeviceProfile dp = launcher.getDeviceProfile();
365 int tileSize = Math.min(dp.cellWidthPx, dp.cellHeightPx);
366 previewWidth = tileSize * spanX;
367 previewHeight = tileSize * spanY;
Michael Jurka05713af2013-01-23 12:39:24 +0100368 }
369
370 // Scale to fit width only - let the widget preview be clipped in the
371 // vertical dimension
372 float scale = 1f;
373 if (preScaledWidthOut != null) {
374 preScaledWidthOut[0] = previewWidth;
375 }
376 if (previewWidth > maxPreviewWidth) {
Sunny Goyala2441e82017-01-14 13:40:15 -0800377 scale = maxPreviewWidth / (float) (previewWidth);
Michael Jurka05713af2013-01-23 12:39:24 +0100378 }
379 if (scale != 1f) {
Roger Olsson4ac406d2018-04-12 10:08:01 +0200380 previewWidth = Math.max((int)(scale * previewWidth), 1);
381 previewHeight = Math.max((int)(scale * previewHeight), 1);
Michael Jurka05713af2013-01-23 12:39:24 +0100382 }
383
384 // 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 -0700385 final Canvas c = new Canvas();
Michael Jurka05713af2013-01-23 12:39:24 +0100386 if (preview == null) {
387 preview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700388 c.setBitmap(preview);
389 } else {
Sunny Goyala2441e82017-01-14 13:40:15 -0800390 // We use the preview bitmap height to determine where the badge will be drawn in the
391 // UI. If its larger than what we need, resize the preview bitmap so that there are
392 // no transparent pixels between the preview and the badge.
393 if (preview.getHeight() > previewHeight) {
394 preview.reconfigure(preview.getWidth(), previewHeight, preview.getConfig());
395 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700396 // Reusing bitmap. Clear it.
397 c.setBitmap(preview);
398 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100399 }
400
401 // Draw the scaled preview into the final bitmap
Hyunyoung Songb9f932e2015-07-30 15:04:59 -0700402 int x = (preview.getWidth() - previewWidth) / 2;
Michael Jurka05713af2013-01-23 12:39:24 +0100403 if (widgetPreviewExists) {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700404 drawable.setBounds(x, 0, x + previewWidth, previewHeight);
405 drawable.draw(c);
Michael Jurka05713af2013-01-23 12:39:24 +0100406 } else {
Sunny Goyalb3648e02017-05-02 16:17:10 -0700407 RectF boxRect = drawBoxWithShadow(c, previewWidth, previewHeight);
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800408
409 // Draw horizontal and vertical lines to represent individual columns.
Sunny Goyalb3648e02017-05-02 16:17:10 -0700410 final Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800411 p.setStyle(Paint.Style.STROKE);
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800412 p.setStrokeWidth(mContext.getResources()
413 .getDimension(R.dimen.widget_preview_cell_divider_width));
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800414 p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
415
416 float t = boxRect.left;
417 float tileSize = boxRect.width() / spanX;
418 for (int i = 1; i < spanX; i++) {
419 t += tileSize;
420 c.drawLine(t, 0, t, previewHeight, p);
Michael Jurka05713af2013-01-23 12:39:24 +0100421 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700422
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800423 t = boxRect.top;
424 tileSize = boxRect.height() / spanY;
425 for (int i = 1; i < spanY; i++) {
426 t += tileSize;
427 c.drawLine(0, t, previewWidth, t, p);
428 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700429
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800430 // Draw icon in the center.
Sunny Goyal4cad7532015-03-18 15:56:30 -0700431 try {
Sunny Goyal952e63d2017-08-16 04:59:08 -0700432 Drawable icon =
433 mIconCache.getFullResIcon(info.provider.getPackageName(), info.icon);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700434 if (icon != null) {
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800435 int appIconSize = launcher.getDeviceProfile().iconSizePx;
436 int iconSize = (int) Math.min(appIconSize * scale,
437 Math.min(boxRect.width(), boxRect.height()));
438
Sunny Goyal1ba7e362015-10-26 10:42:12 -0700439 icon = mutateOnMainThread(icon);
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800440 int hoffset = (previewWidth - iconSize) / 2;
441 int yoffset = (previewHeight - iconSize) / 2;
442 icon.setBounds(hoffset, yoffset, hoffset + iconSize, yoffset + iconSize);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700443 icon.draw(c);
444 }
Samuel Fufa15357962019-09-03 12:36:15 -0700445 } catch (Resources.NotFoundException e) {
446 savePreviewImage = false;
447 }
Michael Jurka05713af2013-01-23 12:39:24 +0100448 c.setBitmap(null);
449 }
Samuel Fufa15357962019-09-03 12:36:15 -0700450 return new Pair<>(preview, savePreviewImage);
Michael Jurka05713af2013-01-23 12:39:24 +0100451 }
452
Sunny Goyalb3648e02017-05-02 16:17:10 -0700453 private RectF drawBoxWithShadow(Canvas c, int width, int height) {
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800454 Resources res = mContext.getResources();
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800455
Sunny Goyale463c8f2017-06-20 13:34:09 -0700456 ShadowGenerator.Builder builder = new ShadowGenerator.Builder(Color.WHITE);
457 builder.shadowBlur = res.getDimension(R.dimen.widget_preview_shadow_blur);
458 builder.radius = res.getDimension(R.dimen.widget_preview_corner_radius);
459 builder.keyShadowDistance = res.getDimension(R.dimen.widget_preview_key_shadow_distance);
460
461 builder.bounds.set(builder.shadowBlur, builder.shadowBlur,
462 width - builder.shadowBlur,
463 height - builder.shadowBlur - builder.keyShadowDistance);
464 builder.drawShadow(c);
465 return builder.bounds;
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800466 }
467
Sunny Goyal782f0c92017-01-19 10:27:54 -0800468 private Bitmap generateShortcutPreview(BaseActivity launcher, ShortcutConfigActivityInfo info,
469 int maxWidth, int maxHeight, Bitmap preview) {
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800470 int iconSize = launcher.getDeviceProfile().iconSizePx;
471 int padding = launcher.getResources()
472 .getDimensionPixelSize(R.dimen.widget_preview_shortcut_padding);
473
474 int size = iconSize + 2 * padding;
475 if (maxHeight < size || maxWidth < size) {
476 throw new RuntimeException("Max size is too small for preview");
477 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700478 final Canvas c = new Canvas();
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800479 if (preview == null || preview.getWidth() < size || preview.getHeight() < size) {
480 preview = Bitmap.createBitmap(size, size, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700481 c.setBitmap(preview);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700482 } else {
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800483 if (preview.getWidth() > size || preview.getHeight() > size) {
484 preview.reconfigure(size, size, preview.getConfig());
485 }
486
Sunny Goyal4cad7532015-03-18 15:56:30 -0700487 // Reusing bitmap. Clear it.
488 c.setBitmap(preview);
489 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100490 }
Sunny Goyalb3648e02017-05-02 16:17:10 -0700491 RectF boxRect = drawBoxWithShadow(c, size, size);
Michael Jurka05713af2013-01-23 12:39:24 +0100492
Sunny Goyal18a4e5a2018-01-09 15:34:38 -0800493 LauncherIcons li = LauncherIcons.obtain(mContext);
Hyunyoung Song2bf3f372019-04-02 10:45:57 -0700494 Bitmap icon = li.createBadgedIconBitmap(
495 mutateOnMainThread(info.getFullResIcon(mIconCache)),
496 Process.myUserHandle(), 0).icon;
Sunny Goyal18a4e5a2018-01-09 15:34:38 -0800497 li.recycle();
498
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800499 Rect src = new Rect(0, 0, icon.getWidth(), icon.getHeight());
Sunny Goyal4cad7532015-03-18 15:56:30 -0700500
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800501 boxRect.set(0, 0, iconSize, iconSize);
502 boxRect.offset(padding, padding);
Sunny Goyalb3648e02017-05-02 16:17:10 -0700503 c.drawBitmap(icon, src, boxRect,
504 new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG));
Michael Jurka05713af2013-01-23 12:39:24 +0100505 c.setBitmap(null);
Michael Jurka05713af2013-01-23 12:39:24 +0100506 return preview;
507 }
508
Adrian Roos65d60e22014-04-15 21:07:49 +0200509 private Drawable mutateOnMainThread(final Drawable drawable) {
510 try {
Sunny Goyal6fe3eec2019-08-15 14:53:41 -0700511 return MAIN_EXECUTOR.submit(drawable::mutate).get();
Adrian Roos65d60e22014-04-15 21:07:49 +0200512 } catch (InterruptedException e) {
513 Thread.currentThread().interrupt();
514 throw new RuntimeException(e);
515 } catch (ExecutionException e) {
516 throw new RuntimeException(e);
517 }
518 }
Adrian Roos1f375ab2014-04-28 18:26:38 +0200519
Adrian Roos1f375ab2014-04-28 18:26:38 +0200520 /**
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700521 * @return an array of containing versionCode and lastUpdatedTime for the package.
Adrian Roos1f375ab2014-04-28 18:26:38 +0200522 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700523 @Thunk long[] getPackageVersion(String packageName) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700524 synchronized (mPackageVersions) {
525 long[] versions = mPackageVersions.get(packageName);
526 if (versions == null) {
527 versions = new long[2];
Adrian Roos1f375ab2014-04-28 18:26:38 +0200528 try {
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800529 PackageInfo info = mContext.getPackageManager().getPackageInfo(packageName,
530 PackageManager.GET_UNINSTALLED_PACKAGES);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700531 versions[0] = info.versionCode;
532 versions[1] = info.lastUpdateTime;
533 } catch (NameNotFoundException e) {
534 Log.e(TAG, "PackageInfo not found", e);
535 }
536 mPackageVersions.put(packageName, versions);
537 }
538 return versions;
539 }
540 }
541
Sunny Goyalc65a0082017-03-08 14:49:55 -0800542 public class PreviewLoadTask extends AsyncTask<Void, Void, Bitmap>
543 implements CancellationSignal.OnCancelListener {
Sunny Goyal316490e2015-06-02 09:38:28 -0700544 @Thunk final WidgetCacheKey mKey;
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800545 private final WidgetItem mInfo;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700546 private final int mPreviewHeight;
547 private final int mPreviewWidth;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700548 private final WidgetCell mCaller;
Sunny Goyala2441e82017-01-14 13:40:15 -0800549 private final BaseActivity mActivity;
Sunny Goyal316490e2015-06-02 09:38:28 -0700550 @Thunk long[] mVersions;
551 @Thunk Bitmap mBitmapToRecycle;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700552
Samuel Fufa15357962019-09-03 12:36:15 -0700553 private boolean mSaveToDB = false;
554
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800555 PreviewLoadTask(WidgetCacheKey key, WidgetItem info, int previewWidth,
Sunny Goyalf1fbc3f2017-10-10 15:21:15 -0700556 int previewHeight, WidgetCell caller) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700557 mKey = key;
558 mInfo = info;
559 mPreviewHeight = previewHeight;
560 mPreviewWidth = previewWidth;
561 mCaller = caller;
Sunny Goyala2441e82017-01-14 13:40:15 -0800562 mActivity = BaseActivity.fromContext(mCaller.getContext());
Hyunyoung Song3f471442015-04-08 19:01:34 -0700563 if (DEBUG) {
564 Log.d(TAG, String.format("%s, %s, %d, %d",
565 mKey, mInfo, mPreviewHeight, mPreviewWidth));
566 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700567 }
568
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700569 @Override
570 protected Bitmap doInBackground(Void... params) {
571 Bitmap unusedBitmap = null;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700572
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700573 // If already cancelled before this gets to run in the background, then return early
574 if (isCancelled()) {
575 return null;
576 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700577 synchronized (mUnusedBitmaps) {
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700578 // Check if we can re-use a bitmap
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700579 for (Bitmap candidate : mUnusedBitmaps) {
580 if (candidate != null && candidate.isMutable() &&
581 candidate.getWidth() == mPreviewWidth &&
582 candidate.getHeight() == mPreviewHeight) {
583 unusedBitmap = candidate;
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700584 mUnusedBitmaps.remove(unusedBitmap);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700585 break;
586 }
587 }
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700588 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700589
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700590 // creating a bitmap is expensive. Do not do this inside synchronized block.
591 if (unusedBitmap == null) {
592 unusedBitmap = Bitmap.createBitmap(mPreviewWidth, mPreviewHeight, Config.ARGB_8888);
Adrian Roos1f375ab2014-04-28 18:26:38 +0200593 }
Winson Chung05304db2015-05-18 16:53:20 -0700594 // If cancelled now, don't bother reading the preview from the DB
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700595 if (isCancelled()) {
Winson Chung05304db2015-05-18 16:53:20 -0700596 return unusedBitmap;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700597 }
Winson Chung05304db2015-05-18 16:53:20 -0700598 Bitmap preview = readFromDb(mKey, unusedBitmap, this);
599 // Only consider generating the preview if we have not cancelled the task already
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700600 if (!isCancelled() && preview == null) {
601 // Fetch the version info before we generate the preview, so that, in-case the
602 // app was updated while we are generating the preview, we use the old version info,
603 // which would gets re-written next time.
Sunny Goyal65513ba2017-01-20 11:54:25 -0800604 boolean persistable = mInfo.activityInfo == null
605 || mInfo.activityInfo.isPersistable();
606 mVersions = persistable ? getPackageVersion(mKey.componentName.getPackageName())
607 : null;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700608
609 // it's not in the db... we need to generate it
Samuel Fufa15357962019-09-03 12:36:15 -0700610 Pair<Bitmap, Boolean> pair = generatePreview(mActivity, mInfo, unusedBitmap,
611 mPreviewWidth, mPreviewHeight);
612 preview = pair.first;
613 this.mSaveToDB = pair.second;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700614 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700615 return preview;
616 }
617
618 @Override
Winson Chung05304db2015-05-18 16:53:20 -0700619 protected void onPostExecute(final Bitmap preview) {
Sunny Goyalf1fbc3f2017-10-10 15:21:15 -0700620 mCaller.applyPreview(preview);
Winson Chung05304db2015-05-18 16:53:20 -0700621
622 // Write the generated preview to the DB in the worker thread
623 if (mVersions != null) {
Sunny Goyal6fe3eec2019-08-15 14:53:41 -0700624 MODEL_EXECUTOR.post(new Runnable() {
Winson Chung05304db2015-05-18 16:53:20 -0700625 @Override
626 public void run() {
Samuel Fufa15357962019-09-03 12:36:15 -0700627 if (!isCancelled() && mSaveToDB) {
Winson Chung05304db2015-05-18 16:53:20 -0700628 // If we are still using this preview, then write it to the DB and then
629 // let the normal clear mechanism recycle the bitmap
630 writeToDb(mKey, mVersions, preview);
631 mBitmapToRecycle = preview;
632 } else {
633 // If we've already cancelled, then skip writing the bitmap to the DB
634 // and manually add the bitmap back to the recycled set
635 synchronized (mUnusedBitmaps) {
636 mUnusedBitmaps.add(preview);
637 }
638 }
639 }
640 });
641 } else {
642 // If we don't need to write to disk, then ensure the preview gets recycled by
643 // the normal clear mechanism
644 mBitmapToRecycle = preview;
645 }
646 }
647
648 @Override
Hyunyoung Songe98f4a42015-06-16 10:45:24 -0700649 protected void onCancelled(final Bitmap preview) {
Winson Chung05304db2015-05-18 16:53:20 -0700650 // If we've cancelled while the task is running, then can return the bitmap to the
651 // recycled set immediately. Otherwise, it will be recycled after the preview is written
652 // to disk.
653 if (preview != null) {
Sunny Goyal6fe3eec2019-08-15 14:53:41 -0700654 MODEL_EXECUTOR.post(new Runnable() {
Hyunyoung Songe98f4a42015-06-16 10:45:24 -0700655 @Override
656 public void run() {
657 synchronized (mUnusedBitmaps) {
658 mUnusedBitmaps.add(preview);
659 }
660 }
661 });
Winson Chung05304db2015-05-18 16:53:20 -0700662 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700663 }
Sunny Goyalc65a0082017-03-08 14:49:55 -0800664
665 @Override
666 public void onCancel() {
667 cancel(true);
668
669 // This only handles the case where the PreviewLoadTask is cancelled after the task has
670 // successfully completed (including having written to disk when necessary). In the
671 // other cases where it is cancelled while the task is running, it will be cleaned up
672 // in the tasks's onCancelled() call, and if cancelled while the task is writing to
673 // disk, it will be cancelled in the task's onPostExecute() call.
674 if (mBitmapToRecycle != null) {
Sunny Goyal6fe3eec2019-08-15 14:53:41 -0700675 MODEL_EXECUTOR.post(new Runnable() {
Sunny Goyalc65a0082017-03-08 14:49:55 -0800676 @Override
677 public void run() {
678 synchronized (mUnusedBitmaps) {
679 mUnusedBitmaps.add(mBitmapToRecycle);
680 }
681 mBitmapToRecycle = null;
682 }
683 });
684 }
685 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700686 }
687
688 private static final class WidgetCacheKey extends ComponentKey {
689
Sunny Goyal316490e2015-06-02 09:38:28 -0700690 @Thunk final String size;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700691
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800692 public WidgetCacheKey(ComponentName componentName, UserHandle user, String size) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700693 super(componentName, user);
694 this.size = size;
695 }
696
697 @Override
698 public int hashCode() {
699 return super.hashCode() ^ size.hashCode();
700 }
701
702 @Override
703 public boolean equals(Object o) {
704 return super.equals(o) && ((WidgetCacheKey) o).size.equals(size);
Adrian Roos1f375ab2014-04-28 18:26:38 +0200705 }
706 }
Michael Jurka05713af2013-01-23 12:39:24 +0100707}