blob: c525cd4bc05aee1c7635bfc7d510705b469e9539 [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;
Hyunyoung Song09204172017-04-27 11:43:47 -070025import android.os.Build;
Sunny Goyalc65a0082017-03-08 14:49:55 -080026import android.os.CancellationSignal;
Winson Chung05304db2015-05-18 16:53:20 -070027import android.os.Handler;
Sunny Goyal7c74e4a2016-12-15 15:53:17 -080028import android.os.UserHandle;
Tony Wickham86222d22017-03-29 15:30:43 -070029import android.support.annotation.Nullable;
Sunny Goyal7d87cb12017-02-13 10:44:43 -080030import android.support.v4.graphics.ColorUtils;
Michael Jurka05713af2013-01-23 12:39:24 +010031import android.util.Log;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070032import android.util.LongSparseArray;
Sunny Goyal383c5072015-06-12 21:18:53 -070033
Sunny Goyalffe83f12014-08-14 17:39:34 -070034import com.android.launcher3.compat.AppWidgetManagerCompat;
Sunny Goyal782f0c92017-01-19 10:27:54 -080035import com.android.launcher3.compat.ShortcutConfigActivityInfo;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070036import com.android.launcher3.compat.UserManagerCompat;
Sunny Goyal7d87cb12017-02-13 10:44:43 -080037import com.android.launcher3.graphics.LauncherIcons;
Sunny Goyal92bbfa12017-02-07 15:06:32 -080038import com.android.launcher3.graphics.ShadowGenerator;
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 Goyalffe83f12014-08-14 17:39:34 -070056public class WidgetPreviewLoader {
Michael Jurka05713af2013-01-23 12:39:24 +010057
Sunny Goyalffe83f12014-08-14 17:39:34 -070058 private static final String TAG = "WidgetPreviewLoader";
Hyunyoung Song3f471442015-04-08 19:01:34 -070059 private static final boolean DEBUG = false;
Sunny Goyalffe83f12014-08-14 17:39:34 -070060
Sunny Goyal5b0e6692015-03-19 14:31:19 -070061 private final HashMap<String, long[]> mPackageVersions = new HashMap<>();
Hyunyoung Song559d90d2015-04-28 15:06:45 -070062
63 /**
64 * Weak reference objects, do not prevent their referents from being made finalizable,
65 * finalized, and then reclaimed.
Hyunyoung Songe98f4a42015-06-16 10:45:24 -070066 * Note: synchronized block used for this variable is expensive and the block should always
67 * be posted to a background thread.
Hyunyoung Song559d90d2015-04-28 15:06:45 -070068 */
Sunny Goyalb4cbea42015-06-16 15:10:36 -070069 @Thunk final Set<Bitmap> mUnusedBitmaps =
Hyunyoung Song559d90d2015-04-28 15:06:45 -070070 Collections.newSetFromMap(new WeakHashMap<Bitmap, Boolean>());
Sunny Goyal4cad7532015-03-18 15:56:30 -070071
72 private final Context mContext;
Sunny Goyalffe83f12014-08-14 17:39:34 -070073 private final IconCache mIconCache;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070074 private final UserManagerCompat mUserManager;
Hyunyoung Song3e840f42016-03-01 11:57:44 -080075 private final AppWidgetManagerCompat mWidgetManager;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070076 private final CacheDb mDb;
Michael Jurka05713af2013-01-23 12:39:24 +010077
Adrian Roos65d60e22014-04-15 21:07:49 +020078 private final MainThreadExecutor mMainThreadExecutor = new MainThreadExecutor();
Sunny Goyal316490e2015-06-02 09:38:28 -070079 @Thunk final Handler mWorkerHandler;
Adrian Roos65d60e22014-04-15 21:07:49 +020080
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;
Hyunyoung Song3e840f42016-03-01 11:57:44 -080084 mWidgetManager = AppWidgetManagerCompat.getInstance(context);
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,
Tony Wickham26b17462017-03-20 17:12:24 -070097 int previewHeight, WidgetCell caller, boolean animate) {
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
Tony Wickham26b17462017-03-20 17:12:24 -0700101 PreviewLoadTask task = new PreviewLoadTask(key, item, previewWidth, previewHeight, caller,
102 animate);
Sunny Goyal8ac727b2015-09-23 15:38:09 -0700103 task.executeOnExecutor(Utilities.THREAD_POOL_EXECUTOR);
Sunny Goyalc65a0082017-03-08 14:49:55 -0800104
105 CancellationSignal signal = new CancellationSignal();
106 signal.setOnCancelListener(task);
107 return signal;
Michael Jurka05713af2013-01-23 12:39:24 +0100108 }
109
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700110 /**
111 * The DB holds the generated previews for various components. Previews can also have different
112 * sizes (landscape vs portrait).
113 */
Sunny Goyal6f709362015-12-17 17:09:36 -0800114 private static class CacheDb extends SQLiteCacheHelper {
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800115 private static final int DB_VERSION = 6;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700116
117 private static final String TABLE_NAME = "shortcut_and_widget_previews";
118 private static final String COLUMN_COMPONENT = "componentName";
119 private static final String COLUMN_USER = "profileId";
120 private static final String COLUMN_SIZE = "size";
121 private static final String COLUMN_PACKAGE = "packageName";
122 private static final String COLUMN_LAST_UPDATED = "lastUpdated";
123 private static final String COLUMN_VERSION = "version";
124 private static final String COLUMN_PREVIEW_BITMAP = "preview_bitmap";
Michael Jurka05713af2013-01-23 12:39:24 +0100125
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100126 public CacheDb(Context context) {
Sunny Goyal6f709362015-12-17 17:09:36 -0800127 super(context, LauncherFiles.WIDGET_PREVIEWS_DB, DB_VERSION, TABLE_NAME);
Michael Jurka05713af2013-01-23 12:39:24 +0100128 }
129
130 @Override
Sunny Goyal6f709362015-12-17 17:09:36 -0800131 public void onCreateTable(SQLiteDatabase database) {
Michael Jurka32b7a092013-02-07 20:06:49 +0100132 database.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" +
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700133 COLUMN_COMPONENT + " TEXT NOT NULL, " +
134 COLUMN_USER + " INTEGER NOT NULL, " +
Michael Jurka05713af2013-01-23 12:39:24 +0100135 COLUMN_SIZE + " TEXT NOT NULL, " +
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700136 COLUMN_PACKAGE + " TEXT NOT NULL, " +
137 COLUMN_LAST_UPDATED + " INTEGER NOT NULL DEFAULT 0, " +
138 COLUMN_VERSION + " INTEGER NOT NULL DEFAULT 0, " +
139 COLUMN_PREVIEW_BITMAP + " BLOB, " +
140 "PRIMARY KEY (" + COLUMN_COMPONENT + ", " + COLUMN_USER + ", " + COLUMN_SIZE + ") " +
Michael Jurka32b7a092013-02-07 20:06:49 +0100141 ");");
Michael Jurka05713af2013-01-23 12:39:24 +0100142 }
Michael Jurka05713af2013-01-23 12:39:24 +0100143 }
144
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700145 @Thunk void writeToDb(WidgetCacheKey key, long[] versions, Bitmap preview) {
Michael Jurka05713af2013-01-23 12:39:24 +0100146 ContentValues values = new ContentValues();
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700147 values.put(CacheDb.COLUMN_COMPONENT, key.componentName.flattenToShortString());
148 values.put(CacheDb.COLUMN_USER, mUserManager.getSerialNumberForUser(key.user));
149 values.put(CacheDb.COLUMN_SIZE, key.size);
150 values.put(CacheDb.COLUMN_PACKAGE, key.componentName.getPackageName());
151 values.put(CacheDb.COLUMN_VERSION, versions[0]);
152 values.put(CacheDb.COLUMN_LAST_UPDATED, versions[1]);
153 values.put(CacheDb.COLUMN_PREVIEW_BITMAP, Utilities.flattenBitmap(preview));
Sunny Goyal6f709362015-12-17 17:09:36 -0800154 mDb.insertOrReplace(values);
Michael Jurka05713af2013-01-23 12:39:24 +0100155 }
156
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800157 public void removePackage(String packageName, UserHandle user) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700158 removePackage(packageName, user, mUserManager.getSerialNumberForUser(user));
159 }
160
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800161 private void removePackage(String packageName, UserHandle user, long userSerial) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700162 synchronized(mPackageVersions) {
163 mPackageVersions.remove(packageName);
164 }
165
Sunny Goyal6f709362015-12-17 17:09:36 -0800166 mDb.delete(
167 CacheDb.COLUMN_PACKAGE + " = ? AND " + CacheDb.COLUMN_USER + " = ?",
168 new String[]{packageName, Long.toString(userSerial)});
Michael Jurka8ff02ca2013-11-01 14:19:27 +0100169 }
170
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700171 /**
172 * Updates the persistent DB:
173 * 1. Any preview generated for an old package version is removed
174 * 2. Any preview for an absent package is removed
175 * This ensures that we remove entries for packages which changed while the launcher was dead.
Tony Wickham86222d22017-03-29 15:30:43 -0700176 *
177 * @param packageUser if provided, specifies that list only contains previews for the
178 * given package/user, otherwise the list contains all previews
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700179 */
Tony Wickham86222d22017-03-29 15:30:43 -0700180 public void removeObsoletePreviews(ArrayList<? extends ComponentKey> list,
181 @Nullable PackageUserKey packageUser) {
Sunny Goyal6388b2c2016-04-15 18:03:27 -0700182 Preconditions.assertWorkerThread();
Hyunyoung Song8821ca92015-05-04 16:28:20 -0700183
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700184 LongSparseArray<HashSet<String>> validPackages = new LongSparseArray<>();
185
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800186 for (ComponentKey key : list) {
187 final long userId = mUserManager.getSerialNumberForUser(key.user);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700188 HashSet<String> packages = validPackages.get(userId);
189 if (packages == null) {
190 packages = new HashSet<>();
191 validPackages.put(userId, packages);
192 }
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800193 packages.add(key.componentName.getPackageName());
Michael Jurka05713af2013-01-23 12:39:24 +0100194 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700195
196 LongSparseArray<HashSet<String>> packagesToDelete = new LongSparseArray<>();
Tony Wickham86222d22017-03-29 15:30:43 -0700197 long passedUserId = packageUser == null ? 0
198 : mUserManager.getSerialNumberForUser(packageUser.mUser);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700199 Cursor c = null;
200 try {
Sunny Goyal6f709362015-12-17 17:09:36 -0800201 c = mDb.query(
202 new String[]{CacheDb.COLUMN_USER, CacheDb.COLUMN_PACKAGE,
203 CacheDb.COLUMN_LAST_UPDATED, CacheDb.COLUMN_VERSION},
204 null, null);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700205 while (c.moveToNext()) {
206 long userId = c.getLong(0);
207 String pkg = c.getString(1);
208 long lastUpdated = c.getLong(2);
209 long version = c.getLong(3);
210
Tony Wickham86222d22017-03-29 15:30:43 -0700211 if (packageUser != null && (!pkg.equals(packageUser.mPackageName)
212 || userId != passedUserId)) {
213 // This preview is associated with a different package/user, no need to remove.
214 continue;
215 }
216
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700217 HashSet<String> packages = validPackages.get(userId);
218 if (packages != null && packages.contains(pkg)) {
219 long[] versions = getPackageVersion(pkg);
220 if (versions[0] == version && versions[1] == lastUpdated) {
221 // Every thing checks out
222 continue;
223 }
224 }
225
226 // We need to delete this package.
227 packages = packagesToDelete.get(userId);
228 if (packages == null) {
229 packages = new HashSet<>();
230 packagesToDelete.put(userId, packages);
231 }
232 packages.add(pkg);
233 }
234
235 for (int i = 0; i < packagesToDelete.size(); i++) {
236 long userId = packagesToDelete.keyAt(i);
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800237 UserHandle user = mUserManager.getUserForSerialNumber(userId);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700238 for (String pkg : packagesToDelete.valueAt(i)) {
239 removePackage(pkg, user, userId);
240 }
241 }
242 } catch (SQLException e) {
Sunny Goyal6f709362015-12-17 17:09:36 -0800243 Log.e(TAG, "Error updating widget previews", e);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700244 } finally {
245 if (c != null) {
246 c.close();
247 }
248 }
249 }
250
Winson Chung05304db2015-05-18 16:53:20 -0700251 /**
252 * Reads the preview bitmap from the DB or null if the preview is not in the DB.
253 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700254 @Thunk Bitmap readFromDb(WidgetCacheKey key, Bitmap recycle, PreviewLoadTask loadTask) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700255 Cursor cursor = null;
256 try {
Sunny Goyal6f709362015-12-17 17:09:36 -0800257 cursor = mDb.query(
258 new String[]{CacheDb.COLUMN_PREVIEW_BITMAP},
259 CacheDb.COLUMN_COMPONENT + " = ? AND " + CacheDb.COLUMN_USER + " = ? AND "
260 + CacheDb.COLUMN_SIZE + " = ?",
261 new String[]{
Sunny Goyal3ef86912016-10-27 11:40:06 -0700262 key.componentName.flattenToShortString(),
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700263 Long.toString(mUserManager.getSerialNumberForUser(key.user)),
264 key.size
Sunny Goyal6f709362015-12-17 17:09:36 -0800265 });
Winson Chung05304db2015-05-18 16:53:20 -0700266 // If cancelled, skip getting the blob and decoding it into a bitmap
267 if (loadTask.isCancelled()) {
268 return null;
269 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700270 if (cursor.moveToNext()) {
271 byte[] blob = cursor.getBlob(0);
272 BitmapFactory.Options opts = new BitmapFactory.Options();
273 opts.inBitmap = recycle;
Michael Jurka6e27f642013-12-10 13:40:30 +0100274 try {
Winson Chung05304db2015-05-18 16:53:20 -0700275 if (!loadTask.isCancelled()) {
276 return BitmapFactory.decodeByteArray(blob, 0, blob.length, opts);
277 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700278 } catch (Exception e) {
279 return null;
Michael Jurka6e27f642013-12-10 13:40:30 +0100280 }
Michael Jurka05713af2013-01-23 12:39:24 +0100281 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700282 } catch (SQLException e) {
283 Log.w(TAG, "Error loading preview from DB", e);
284 } finally {
285 if (cursor != null) {
286 cursor.close();
287 }
288 }
289 return null;
Michael Jurka05713af2013-01-23 12:39:24 +0100290 }
291
Sunny Goyal27835952017-01-13 12:15:53 -0800292 private Bitmap generatePreview(BaseActivity launcher, WidgetItem item, Bitmap recycle,
Adam Cohen2e6da152015-05-06 11:42:25 -0700293 int previewWidth, int previewHeight) {
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800294 if (item.widgetInfo != null) {
295 return generateWidgetPreview(launcher, item.widgetInfo,
Adam Cohen2e6da152015-05-06 11:42:25 -0700296 previewWidth, recycle, null);
Michael Jurka05713af2013-01-23 12:39:24 +0100297 } else {
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800298 return generateShortcutPreview(launcher, item.activityInfo,
299 previewWidth, previewHeight, recycle);
Michael Jurka05713af2013-01-23 12:39:24 +0100300 }
301 }
302
Hyunyoung Song3e840f42016-03-01 11:57:44 -0800303 /**
304 * Generates the widget preview from either the {@link AppWidgetManagerCompat} or cache
305 * and add badge at the bottom right corner.
306 *
307 * @param launcher
308 * @param info information about the widget
309 * @param maxPreviewWidth width of the preview on either workspace or tray
310 * @param preview bitmap that can be recycled
311 * @param preScaledWidthOut return the width of the returned bitmap
312 * @return
313 */
Sunny Goyal27835952017-01-13 12:15:53 -0800314 public Bitmap generateWidgetPreview(BaseActivity launcher, LauncherAppWidgetProviderInfo info,
Sunny Goyal4cad7532015-03-18 15:56:30 -0700315 int maxPreviewWidth, Bitmap preview, int[] preScaledWidthOut) {
Michael Jurka05713af2013-01-23 12:39:24 +0100316 // Load the preview image if possible
Michael Jurka05713af2013-01-23 12:39:24 +0100317 if (maxPreviewWidth < 0) maxPreviewWidth = Integer.MAX_VALUE;
Michael Jurka05713af2013-01-23 12:39:24 +0100318
319 Drawable drawable = null;
Sunny Goyalffe83f12014-08-14 17:39:34 -0700320 if (info.previewImage != 0) {
Sunny Goyal2570d102016-10-27 11:38:45 -0700321 try {
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800322 drawable = info.loadPreviewImage(mContext, 0);
Sunny Goyal2570d102016-10-27 11:38:45 -0700323 } catch (OutOfMemoryError e) {
324 Log.w(TAG, "Error loading widget preview for: " + info.provider, e);
325 // During OutOfMemoryError, the previous heap stack is not affected. Catching
326 // an OOM error here should be safe & not affect other parts of launcher.
327 drawable = null;
328 }
Adrian Roosfa9ffc22014-05-12 15:59:59 +0200329 if (drawable != null) {
330 drawable = mutateOnMainThread(drawable);
331 } else {
Michael Jurka05713af2013-01-23 12:39:24 +0100332 Log.w(TAG, "Can't load widget preview drawable 0x" +
Sunny Goyalffe83f12014-08-14 17:39:34 -0700333 Integer.toHexString(info.previewImage) + " for provider: " + info.provider);
Michael Jurka05713af2013-01-23 12:39:24 +0100334 }
335 }
336
Sunny Goyal4cad7532015-03-18 15:56:30 -0700337 final boolean widgetPreviewExists = (drawable != null);
Sunny Goyal233ee962015-08-03 13:05:01 -0700338 final int spanX = info.spanX;
339 final int spanY = info.spanY;
Sunny Goyal4cad7532015-03-18 15:56:30 -0700340
Michael Jurka05713af2013-01-23 12:39:24 +0100341 int previewWidth;
342 int previewHeight;
Hyunyoung Song3e840f42016-03-01 11:57:44 -0800343
Michael Jurka05713af2013-01-23 12:39:24 +0100344 if (widgetPreviewExists) {
345 previewWidth = drawable.getIntrinsicWidth();
346 previewHeight = drawable.getIntrinsicHeight();
347 } else {
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800348 DeviceProfile dp = launcher.getDeviceProfile();
349 int tileSize = Math.min(dp.cellWidthPx, dp.cellHeightPx);
350 previewWidth = tileSize * spanX;
351 previewHeight = tileSize * spanY;
Michael Jurka05713af2013-01-23 12:39:24 +0100352 }
353
354 // Scale to fit width only - let the widget preview be clipped in the
355 // vertical dimension
356 float scale = 1f;
357 if (preScaledWidthOut != null) {
358 preScaledWidthOut[0] = previewWidth;
359 }
360 if (previewWidth > maxPreviewWidth) {
Sunny Goyala2441e82017-01-14 13:40:15 -0800361 scale = maxPreviewWidth / (float) (previewWidth);
Michael Jurka05713af2013-01-23 12:39:24 +0100362 }
363 if (scale != 1f) {
364 previewWidth = (int) (scale * previewWidth);
365 previewHeight = (int) (scale * previewHeight);
366 }
367
368 // 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 -0700369 final Canvas c = new Canvas();
Michael Jurka05713af2013-01-23 12:39:24 +0100370 if (preview == null) {
371 preview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700372 c.setBitmap(preview);
373 } else {
Sunny Goyala2441e82017-01-14 13:40:15 -0800374 // We use the preview bitmap height to determine where the badge will be drawn in the
375 // UI. If its larger than what we need, resize the preview bitmap so that there are
376 // no transparent pixels between the preview and the badge.
377 if (preview.getHeight() > previewHeight) {
378 preview.reconfigure(preview.getWidth(), previewHeight, preview.getConfig());
379 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700380 // Reusing bitmap. Clear it.
381 c.setBitmap(preview);
382 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100383 }
384
385 // Draw the scaled preview into the final bitmap
Hyunyoung Songb9f932e2015-07-30 15:04:59 -0700386 int x = (preview.getWidth() - previewWidth) / 2;
Michael Jurka05713af2013-01-23 12:39:24 +0100387 if (widgetPreviewExists) {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700388 drawable.setBounds(x, 0, x + previewWidth, previewHeight);
389 drawable.draw(c);
Michael Jurka05713af2013-01-23 12:39:24 +0100390 } else {
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800391 final Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800392 RectF boxRect = drawBoxWithShadow(c, p, previewWidth, previewHeight);
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800393
394 // Draw horizontal and vertical lines to represent individual columns.
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800395 p.setStyle(Paint.Style.STROKE);
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800396 p.setStrokeWidth(mContext.getResources()
397 .getDimension(R.dimen.widget_preview_cell_divider_width));
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800398 p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
399
400 float t = boxRect.left;
401 float tileSize = boxRect.width() / spanX;
402 for (int i = 1; i < spanX; i++) {
403 t += tileSize;
404 c.drawLine(t, 0, t, previewHeight, p);
Michael Jurka05713af2013-01-23 12:39:24 +0100405 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700406
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800407 t = boxRect.top;
408 tileSize = boxRect.height() / spanY;
409 for (int i = 1; i < spanY; i++) {
410 t += tileSize;
411 c.drawLine(0, t, previewWidth, t, p);
412 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700413
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800414 // Draw icon in the center.
Sunny Goyal4cad7532015-03-18 15:56:30 -0700415 try {
Sunny Goyala52ecb02016-12-16 15:04:51 -0800416 Drawable icon = info.getIcon(launcher, mIconCache);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700417 if (icon != null) {
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800418 int appIconSize = launcher.getDeviceProfile().iconSizePx;
419 int iconSize = (int) Math.min(appIconSize * scale,
420 Math.min(boxRect.width(), boxRect.height()));
421
Sunny Goyal1ba7e362015-10-26 10:42:12 -0700422 icon = mutateOnMainThread(icon);
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800423 int hoffset = (previewWidth - iconSize) / 2;
424 int yoffset = (previewHeight - iconSize) / 2;
425 icon.setBounds(hoffset, yoffset, hoffset + iconSize, yoffset + iconSize);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700426 icon.draw(c);
427 }
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800428 } catch (Resources.NotFoundException e) { }
Michael Jurka05713af2013-01-23 12:39:24 +0100429 c.setBitmap(null);
430 }
Sunny Goyala2441e82017-01-14 13:40:15 -0800431 return preview;
Michael Jurka05713af2013-01-23 12:39:24 +0100432 }
433
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800434 private RectF drawBoxWithShadow(Canvas c, Paint p, int width, int height) {
435 Resources res = mContext.getResources();
436 float shadowBlur = res.getDimension(R.dimen.widget_preview_shadow_blur);
437 float keyShadowDistance = res.getDimension(R.dimen.widget_preview_key_shadow_distance);
438 float corner = res.getDimension(R.dimen.widget_preview_corner_radius);
439
440 RectF bounds = new RectF(shadowBlur, shadowBlur,
441 width - shadowBlur, height - shadowBlur - keyShadowDistance);
442 p.setColor(Color.WHITE);
443
444 // Key shadow
Hyunyoung Song09204172017-04-27 11:43:47 -0700445 p.setShadowLayer(shadowBlur, 0, keyShadowDistance,
446 ShadowGenerator.KEY_SHADOW_ALPHA << 24);
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800447 c.drawRoundRect(bounds, corner, corner, p);
448
449 // Ambient shadow
Hyunyoung Song09204172017-04-27 11:43:47 -0700450 p.setShadowLayer(shadowBlur, 0, 0,
451 ColorUtils.setAlphaComponent(Color.BLACK, ShadowGenerator.AMBIENT_SHADOW_ALPHA));
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800452 c.drawRoundRect(bounds, corner, corner, p);
453
454 p.clearShadowLayer();
455 return bounds;
456 }
457
Sunny Goyal782f0c92017-01-19 10:27:54 -0800458 private Bitmap generateShortcutPreview(BaseActivity launcher, ShortcutConfigActivityInfo info,
459 int maxWidth, int maxHeight, Bitmap preview) {
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800460 int iconSize = launcher.getDeviceProfile().iconSizePx;
461 int padding = launcher.getResources()
462 .getDimensionPixelSize(R.dimen.widget_preview_shortcut_padding);
463
464 int size = iconSize + 2 * padding;
465 if (maxHeight < size || maxWidth < size) {
466 throw new RuntimeException("Max size is too small for preview");
467 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700468 final Canvas c = new Canvas();
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800469 if (preview == null || preview.getWidth() < size || preview.getHeight() < size) {
470 preview = Bitmap.createBitmap(size, size, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700471 c.setBitmap(preview);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700472 } else {
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800473 if (preview.getWidth() > size || preview.getHeight() > size) {
474 preview.reconfigure(size, size, preview.getConfig());
475 }
476
Sunny Goyal4cad7532015-03-18 15:56:30 -0700477 // Reusing bitmap. Clear it.
478 c.setBitmap(preview);
479 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100480 }
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800481 Paint p = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
482 RectF boxRect = drawBoxWithShadow(c, p, size, size);
Michael Jurka05713af2013-01-23 12:39:24 +0100483
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800484 Bitmap icon = LauncherIcons.createScaledBitmapWithoutShadow(
Hyunyoung Song09204172017-04-27 11:43:47 -0700485 mutateOnMainThread(info.getFullResIcon(mIconCache)), mContext, Build.VERSION_CODES.O);
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800486 Rect src = new Rect(0, 0, icon.getWidth(), icon.getHeight());
Sunny Goyal4cad7532015-03-18 15:56:30 -0700487
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800488 boxRect.set(0, 0, iconSize, iconSize);
489 boxRect.offset(padding, padding);
490 c.drawBitmap(icon, src, boxRect, p);
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;
Tony Wickham26b17462017-03-20 17:12:24 -0700540 private final boolean mAnimatePreviewIn;
Sunny Goyala2441e82017-01-14 13:40:15 -0800541 private final BaseActivity mActivity;
Sunny Goyal316490e2015-06-02 09:38:28 -0700542 @Thunk long[] mVersions;
543 @Thunk Bitmap mBitmapToRecycle;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700544
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800545 PreviewLoadTask(WidgetCacheKey key, WidgetItem info, int previewWidth,
Tony Wickham26b17462017-03-20 17:12:24 -0700546 int previewHeight, WidgetCell caller, boolean animate) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700547 mKey = key;
548 mInfo = info;
549 mPreviewHeight = previewHeight;
550 mPreviewWidth = previewWidth;
551 mCaller = caller;
Tony Wickham26b17462017-03-20 17:12:24 -0700552 mAnimatePreviewIn = animate;
Sunny Goyala2441e82017-01-14 13:40:15 -0800553 mActivity = BaseActivity.fromContext(mCaller.getContext());
Hyunyoung Song3f471442015-04-08 19:01:34 -0700554 if (DEBUG) {
555 Log.d(TAG, String.format("%s, %s, %d, %d",
556 mKey, mInfo, mPreviewHeight, mPreviewWidth));
557 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700558 }
559
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700560 @Override
561 protected Bitmap doInBackground(Void... params) {
562 Bitmap unusedBitmap = null;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700563
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700564 // If already cancelled before this gets to run in the background, then return early
565 if (isCancelled()) {
566 return null;
567 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700568 synchronized (mUnusedBitmaps) {
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700569 // Check if we can re-use a bitmap
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700570 for (Bitmap candidate : mUnusedBitmaps) {
571 if (candidate != null && candidate.isMutable() &&
572 candidate.getWidth() == mPreviewWidth &&
573 candidate.getHeight() == mPreviewHeight) {
574 unusedBitmap = candidate;
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700575 mUnusedBitmaps.remove(unusedBitmap);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700576 break;
577 }
578 }
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700579 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700580
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700581 // creating a bitmap is expensive. Do not do this inside synchronized block.
582 if (unusedBitmap == null) {
583 unusedBitmap = Bitmap.createBitmap(mPreviewWidth, mPreviewHeight, Config.ARGB_8888);
Adrian Roos1f375ab2014-04-28 18:26:38 +0200584 }
Winson Chung05304db2015-05-18 16:53:20 -0700585 // If cancelled now, don't bother reading the preview from the DB
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700586 if (isCancelled()) {
Winson Chung05304db2015-05-18 16:53:20 -0700587 return unusedBitmap;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700588 }
Winson Chung05304db2015-05-18 16:53:20 -0700589 Bitmap preview = readFromDb(mKey, unusedBitmap, this);
590 // Only consider generating the preview if we have not cancelled the task already
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700591 if (!isCancelled() && preview == null) {
592 // Fetch the version info before we generate the preview, so that, in-case the
593 // app was updated while we are generating the preview, we use the old version info,
594 // which would gets re-written next time.
Sunny Goyal65513ba2017-01-20 11:54:25 -0800595 boolean persistable = mInfo.activityInfo == null
596 || mInfo.activityInfo.isPersistable();
597 mVersions = persistable ? getPackageVersion(mKey.componentName.getPackageName())
598 : null;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700599
600 // it's not in the db... we need to generate it
Sunny Goyala2441e82017-01-14 13:40:15 -0800601 preview = generatePreview(mActivity, mInfo, unusedBitmap, mPreviewWidth, mPreviewHeight);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700602 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700603 return preview;
604 }
605
606 @Override
Winson Chung05304db2015-05-18 16:53:20 -0700607 protected void onPostExecute(final Bitmap preview) {
Tony Wickham26b17462017-03-20 17:12:24 -0700608 mCaller.applyPreview(preview, mAnimatePreviewIn);
Winson Chung05304db2015-05-18 16:53:20 -0700609
610 // Write the generated preview to the DB in the worker thread
611 if (mVersions != null) {
612 mWorkerHandler.post(new Runnable() {
613 @Override
614 public void run() {
615 if (!isCancelled()) {
616 // If we are still using this preview, then write it to the DB and then
617 // let the normal clear mechanism recycle the bitmap
618 writeToDb(mKey, mVersions, preview);
619 mBitmapToRecycle = preview;
620 } else {
621 // If we've already cancelled, then skip writing the bitmap to the DB
622 // and manually add the bitmap back to the recycled set
623 synchronized (mUnusedBitmaps) {
624 mUnusedBitmaps.add(preview);
625 }
626 }
627 }
628 });
629 } else {
630 // If we don't need to write to disk, then ensure the preview gets recycled by
631 // the normal clear mechanism
632 mBitmapToRecycle = preview;
633 }
634 }
635
636 @Override
Hyunyoung Songe98f4a42015-06-16 10:45:24 -0700637 protected void onCancelled(final Bitmap preview) {
Winson Chung05304db2015-05-18 16:53:20 -0700638 // If we've cancelled while the task is running, then can return the bitmap to the
639 // recycled set immediately. Otherwise, it will be recycled after the preview is written
640 // to disk.
641 if (preview != null) {
Hyunyoung Songe98f4a42015-06-16 10:45:24 -0700642 mWorkerHandler.post(new Runnable() {
643 @Override
644 public void run() {
645 synchronized (mUnusedBitmaps) {
646 mUnusedBitmaps.add(preview);
647 }
648 }
649 });
Winson Chung05304db2015-05-18 16:53:20 -0700650 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700651 }
Sunny Goyalc65a0082017-03-08 14:49:55 -0800652
653 @Override
654 public void onCancel() {
655 cancel(true);
656
657 // This only handles the case where the PreviewLoadTask is cancelled after the task has
658 // successfully completed (including having written to disk when necessary). In the
659 // other cases where it is cancelled while the task is running, it will be cleaned up
660 // in the tasks's onCancelled() call, and if cancelled while the task is writing to
661 // disk, it will be cancelled in the task's onPostExecute() call.
662 if (mBitmapToRecycle != null) {
663 mWorkerHandler.post(new Runnable() {
664 @Override
665 public void run() {
666 synchronized (mUnusedBitmaps) {
667 mUnusedBitmaps.add(mBitmapToRecycle);
668 }
669 mBitmapToRecycle = null;
670 }
671 });
672 }
673 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700674 }
675
676 private static final class WidgetCacheKey extends ComponentKey {
677
Sunny Goyal316490e2015-06-02 09:38:28 -0700678 @Thunk final String size;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700679
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800680 public WidgetCacheKey(ComponentName componentName, UserHandle user, String size) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700681 super(componentName, user);
682 this.size = size;
683 }
684
685 @Override
686 public int hashCode() {
687 return super.hashCode() ^ size.hashCode();
688 }
689
690 @Override
691 public boolean equals(Object o) {
692 return super.equals(o) && ((WidgetCacheKey) o).size.equals(size);
Adrian Roos1f375ab2014-04-28 18:26:38 +0200693 }
694 }
Michael Jurka05713af2013-01-23 12:39:24 +0100695}