blob: a658d585c0707a0396819f3094038b59a752119a [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;
Sunny Goyal7c74e4a2016-12-15 15:53:17 -080027import android.os.UserHandle;
Tony Wickham86222d22017-03-29 15:30:43 -070028import android.support.annotation.Nullable;
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 Goyal7d87cb12017-02-13 10:44:43 -080035import com.android.launcher3.graphics.LauncherIcons;
Sunny Goyal92bbfa12017-02-07 15:06:32 -080036import com.android.launcher3.graphics.ShadowGenerator;
Sunny Goyal4ddc4012016-03-10 12:02:29 -080037import com.android.launcher3.model.WidgetItem;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070038import com.android.launcher3.util.ComponentKey;
Tony Wickham86222d22017-03-29 15:30:43 -070039import com.android.launcher3.util.PackageUserKey;
Sunny Goyal6388b2c2016-04-15 18:03:27 -070040import com.android.launcher3.util.Preconditions;
Sunny Goyal6f709362015-12-17 17:09:36 -080041import com.android.launcher3.util.SQLiteCacheHelper;
Adam Cohen091440a2015-03-18 14:16:05 -070042import com.android.launcher3.util.Thunk;
Hyunyoung Song3f471442015-04-08 19:01:34 -070043import com.android.launcher3.widget.WidgetCell;
Hyunyoung Song8821ca92015-05-04 16:28:20 -070044
45import java.util.ArrayList;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070046import java.util.Collections;
Michael Jurka05713af2013-01-23 12:39:24 +010047import java.util.HashMap;
48import java.util.HashSet;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070049import java.util.Set;
50import java.util.WeakHashMap;
Adrian Roos65d60e22014-04-15 21:07:49 +020051import java.util.concurrent.Callable;
52import java.util.concurrent.ExecutionException;
Michael Jurka05713af2013-01-23 12:39:24 +010053
Sunny Goyalffe83f12014-08-14 17:39:34 -070054public class WidgetPreviewLoader {
Michael Jurka05713af2013-01-23 12:39:24 +010055
Sunny Goyalffe83f12014-08-14 17:39:34 -070056 private static final String TAG = "WidgetPreviewLoader";
Hyunyoung Song3f471442015-04-08 19:01:34 -070057 private static final boolean DEBUG = false;
Sunny Goyalffe83f12014-08-14 17:39:34 -070058
Sunny Goyal5b0e6692015-03-19 14:31:19 -070059 private final HashMap<String, long[]> mPackageVersions = new HashMap<>();
Hyunyoung Song559d90d2015-04-28 15:06:45 -070060
61 /**
62 * Weak reference objects, do not prevent their referents from being made finalizable,
63 * finalized, and then reclaimed.
Hyunyoung Songe98f4a42015-06-16 10:45:24 -070064 * Note: synchronized block used for this variable is expensive and the block should always
65 * be posted to a background thread.
Hyunyoung Song559d90d2015-04-28 15:06:45 -070066 */
Sunny Goyalb4cbea42015-06-16 15:10:36 -070067 @Thunk final Set<Bitmap> mUnusedBitmaps =
Hyunyoung Song559d90d2015-04-28 15:06:45 -070068 Collections.newSetFromMap(new WeakHashMap<Bitmap, Boolean>());
Sunny Goyal4cad7532015-03-18 15:56:30 -070069
70 private final Context mContext;
Sunny Goyalffe83f12014-08-14 17:39:34 -070071 private final IconCache mIconCache;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070072 private final UserManagerCompat mUserManager;
Hyunyoung Song3e840f42016-03-01 11:57:44 -080073 private final AppWidgetManagerCompat mWidgetManager;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070074 private final CacheDb mDb;
Michael Jurka05713af2013-01-23 12:39:24 +010075
Adrian Roos65d60e22014-04-15 21:07:49 +020076 private final MainThreadExecutor mMainThreadExecutor = new MainThreadExecutor();
Sunny Goyal316490e2015-06-02 09:38:28 -070077 @Thunk final Handler mWorkerHandler;
Adrian Roos65d60e22014-04-15 21:07:49 +020078
Sunny Goyal383c5072015-06-12 21:18:53 -070079 public WidgetPreviewLoader(Context context, IconCache iconCache) {
Chris Wrenfd13c712013-09-27 15:45:19 -040080 mContext = context;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070081 mIconCache = iconCache;
Hyunyoung Song3e840f42016-03-01 11:57:44 -080082 mWidgetManager = AppWidgetManagerCompat.getInstance(context);
Sunny Goyal5b0e6692015-03-19 14:31:19 -070083 mUserManager = UserManagerCompat.getInstance(context);
84 mDb = new CacheDb(context);
Winson Chung05304db2015-05-18 16:53:20 -070085 mWorkerHandler = new Handler(LauncherModel.getWorkerLooper());
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 Goyal8ac727b2015-09-23 15:38:09 -0700100 task.executeOnExecutor(Utilities.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
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700107 /**
108 * The DB holds the generated previews for various components. Previews can also have different
109 * sizes (landscape vs portrait).
110 */
Sunny Goyal6f709362015-12-17 17:09:36 -0800111 private static class CacheDb extends SQLiteCacheHelper {
Jon Miranda6cdc16c2017-06-27 14:04:01 -0700112 private static final int DB_VERSION = 9;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700113
114 private static final String TABLE_NAME = "shortcut_and_widget_previews";
115 private static final String COLUMN_COMPONENT = "componentName";
116 private static final String COLUMN_USER = "profileId";
117 private static final String COLUMN_SIZE = "size";
118 private static final String COLUMN_PACKAGE = "packageName";
119 private static final String COLUMN_LAST_UPDATED = "lastUpdated";
120 private static final String COLUMN_VERSION = "version";
121 private static final String COLUMN_PREVIEW_BITMAP = "preview_bitmap";
Michael Jurka05713af2013-01-23 12:39:24 +0100122
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100123 public CacheDb(Context context) {
Sunny Goyal6f709362015-12-17 17:09:36 -0800124 super(context, LauncherFiles.WIDGET_PREVIEWS_DB, DB_VERSION, TABLE_NAME);
Michael Jurka05713af2013-01-23 12:39:24 +0100125 }
126
127 @Override
Sunny Goyal6f709362015-12-17 17:09:36 -0800128 public void onCreateTable(SQLiteDatabase database) {
Michael Jurka32b7a092013-02-07 20:06:49 +0100129 database.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" +
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700130 COLUMN_COMPONENT + " TEXT NOT NULL, " +
131 COLUMN_USER + " INTEGER NOT NULL, " +
Michael Jurka05713af2013-01-23 12:39:24 +0100132 COLUMN_SIZE + " TEXT NOT NULL, " +
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700133 COLUMN_PACKAGE + " TEXT NOT NULL, " +
134 COLUMN_LAST_UPDATED + " INTEGER NOT NULL DEFAULT 0, " +
135 COLUMN_VERSION + " INTEGER NOT NULL DEFAULT 0, " +
136 COLUMN_PREVIEW_BITMAP + " BLOB, " +
137 "PRIMARY KEY (" + COLUMN_COMPONENT + ", " + COLUMN_USER + ", " + COLUMN_SIZE + ") " +
Michael Jurka32b7a092013-02-07 20:06:49 +0100138 ");");
Michael Jurka05713af2013-01-23 12:39:24 +0100139 }
Michael Jurka05713af2013-01-23 12:39:24 +0100140 }
141
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700142 @Thunk void writeToDb(WidgetCacheKey key, long[] versions, Bitmap preview) {
Michael Jurka05713af2013-01-23 12:39:24 +0100143 ContentValues values = new ContentValues();
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700144 values.put(CacheDb.COLUMN_COMPONENT, key.componentName.flattenToShortString());
145 values.put(CacheDb.COLUMN_USER, mUserManager.getSerialNumberForUser(key.user));
146 values.put(CacheDb.COLUMN_SIZE, key.size);
147 values.put(CacheDb.COLUMN_PACKAGE, key.componentName.getPackageName());
148 values.put(CacheDb.COLUMN_VERSION, versions[0]);
149 values.put(CacheDb.COLUMN_LAST_UPDATED, versions[1]);
150 values.put(CacheDb.COLUMN_PREVIEW_BITMAP, Utilities.flattenBitmap(preview));
Sunny Goyal6f709362015-12-17 17:09:36 -0800151 mDb.insertOrReplace(values);
Michael Jurka05713af2013-01-23 12:39:24 +0100152 }
153
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800154 public void removePackage(String packageName, UserHandle user) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700155 removePackage(packageName, user, mUserManager.getSerialNumberForUser(user));
156 }
157
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800158 private void removePackage(String packageName, UserHandle user, long userSerial) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700159 synchronized(mPackageVersions) {
160 mPackageVersions.remove(packageName);
161 }
162
Sunny Goyal6f709362015-12-17 17:09:36 -0800163 mDb.delete(
164 CacheDb.COLUMN_PACKAGE + " = ? AND " + CacheDb.COLUMN_USER + " = ?",
165 new String[]{packageName, Long.toString(userSerial)});
Michael Jurka8ff02ca2013-11-01 14:19:27 +0100166 }
167
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700168 /**
169 * Updates the persistent DB:
170 * 1. Any preview generated for an old package version is removed
171 * 2. Any preview for an absent package is removed
172 * This ensures that we remove entries for packages which changed while the launcher was dead.
Tony Wickham86222d22017-03-29 15:30:43 -0700173 *
174 * @param packageUser if provided, specifies that list only contains previews for the
175 * given package/user, otherwise the list contains all previews
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700176 */
Tony Wickham86222d22017-03-29 15:30:43 -0700177 public void removeObsoletePreviews(ArrayList<? extends ComponentKey> list,
178 @Nullable PackageUserKey packageUser) {
Sunny Goyal6388b2c2016-04-15 18:03:27 -0700179 Preconditions.assertWorkerThread();
Hyunyoung Song8821ca92015-05-04 16:28:20 -0700180
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700181 LongSparseArray<HashSet<String>> validPackages = new LongSparseArray<>();
182
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800183 for (ComponentKey key : list) {
184 final long userId = mUserManager.getSerialNumberForUser(key.user);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700185 HashSet<String> packages = validPackages.get(userId);
186 if (packages == null) {
187 packages = new HashSet<>();
188 validPackages.put(userId, packages);
189 }
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800190 packages.add(key.componentName.getPackageName());
Michael Jurka05713af2013-01-23 12:39:24 +0100191 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700192
193 LongSparseArray<HashSet<String>> packagesToDelete = new LongSparseArray<>();
Tony Wickham86222d22017-03-29 15:30:43 -0700194 long passedUserId = packageUser == null ? 0
195 : mUserManager.getSerialNumberForUser(packageUser.mUser);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700196 Cursor c = null;
197 try {
Sunny Goyal6f709362015-12-17 17:09:36 -0800198 c = mDb.query(
199 new String[]{CacheDb.COLUMN_USER, CacheDb.COLUMN_PACKAGE,
200 CacheDb.COLUMN_LAST_UPDATED, CacheDb.COLUMN_VERSION},
201 null, null);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700202 while (c.moveToNext()) {
203 long userId = c.getLong(0);
204 String pkg = c.getString(1);
205 long lastUpdated = c.getLong(2);
206 long version = c.getLong(3);
207
Tony Wickham86222d22017-03-29 15:30:43 -0700208 if (packageUser != null && (!pkg.equals(packageUser.mPackageName)
209 || userId != passedUserId)) {
210 // This preview is associated with a different package/user, no need to remove.
211 continue;
212 }
213
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700214 HashSet<String> packages = validPackages.get(userId);
215 if (packages != null && packages.contains(pkg)) {
216 long[] versions = getPackageVersion(pkg);
217 if (versions[0] == version && versions[1] == lastUpdated) {
218 // Every thing checks out
219 continue;
220 }
221 }
222
223 // We need to delete this package.
224 packages = packagesToDelete.get(userId);
225 if (packages == null) {
226 packages = new HashSet<>();
227 packagesToDelete.put(userId, packages);
228 }
229 packages.add(pkg);
230 }
231
232 for (int i = 0; i < packagesToDelete.size(); i++) {
233 long userId = packagesToDelete.keyAt(i);
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800234 UserHandle user = mUserManager.getUserForSerialNumber(userId);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700235 for (String pkg : packagesToDelete.valueAt(i)) {
236 removePackage(pkg, user, userId);
237 }
238 }
239 } catch (SQLException e) {
Sunny Goyal6f709362015-12-17 17:09:36 -0800240 Log.e(TAG, "Error updating widget previews", e);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700241 } finally {
242 if (c != null) {
243 c.close();
244 }
245 }
246 }
247
Winson Chung05304db2015-05-18 16:53:20 -0700248 /**
249 * Reads the preview bitmap from the DB or null if the preview is not in the DB.
250 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700251 @Thunk Bitmap readFromDb(WidgetCacheKey key, Bitmap recycle, PreviewLoadTask loadTask) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700252 Cursor cursor = null;
253 try {
Sunny Goyal6f709362015-12-17 17:09:36 -0800254 cursor = mDb.query(
255 new String[]{CacheDb.COLUMN_PREVIEW_BITMAP},
256 CacheDb.COLUMN_COMPONENT + " = ? AND " + CacheDb.COLUMN_USER + " = ? AND "
257 + CacheDb.COLUMN_SIZE + " = ?",
258 new String[]{
Sunny Goyal3ef86912016-10-27 11:40:06 -0700259 key.componentName.flattenToShortString(),
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700260 Long.toString(mUserManager.getSerialNumberForUser(key.user)),
261 key.size
Sunny Goyal6f709362015-12-17 17:09:36 -0800262 });
Winson Chung05304db2015-05-18 16:53:20 -0700263 // If cancelled, skip getting the blob and decoding it into a bitmap
264 if (loadTask.isCancelled()) {
265 return null;
266 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700267 if (cursor.moveToNext()) {
268 byte[] blob = cursor.getBlob(0);
269 BitmapFactory.Options opts = new BitmapFactory.Options();
270 opts.inBitmap = recycle;
Michael Jurka6e27f642013-12-10 13:40:30 +0100271 try {
Winson Chung05304db2015-05-18 16:53:20 -0700272 if (!loadTask.isCancelled()) {
273 return BitmapFactory.decodeByteArray(blob, 0, blob.length, opts);
274 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700275 } catch (Exception e) {
276 return null;
Michael Jurka6e27f642013-12-10 13:40:30 +0100277 }
Michael Jurka05713af2013-01-23 12:39:24 +0100278 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700279 } catch (SQLException e) {
280 Log.w(TAG, "Error loading preview from DB", e);
281 } finally {
282 if (cursor != null) {
283 cursor.close();
284 }
285 }
286 return null;
Michael Jurka05713af2013-01-23 12:39:24 +0100287 }
288
Sunny Goyal27835952017-01-13 12:15:53 -0800289 private Bitmap generatePreview(BaseActivity launcher, WidgetItem item, Bitmap recycle,
Adam Cohen2e6da152015-05-06 11:42:25 -0700290 int previewWidth, int previewHeight) {
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800291 if (item.widgetInfo != null) {
292 return generateWidgetPreview(launcher, item.widgetInfo,
Adam Cohen2e6da152015-05-06 11:42:25 -0700293 previewWidth, recycle, null);
Michael Jurka05713af2013-01-23 12:39:24 +0100294 } else {
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800295 return generateShortcutPreview(launcher, item.activityInfo,
296 previewWidth, previewHeight, recycle);
Michael Jurka05713af2013-01-23 12:39:24 +0100297 }
298 }
299
Hyunyoung Song3e840f42016-03-01 11:57:44 -0800300 /**
301 * Generates the widget preview from either the {@link AppWidgetManagerCompat} or cache
302 * and add badge at the bottom right corner.
303 *
304 * @param launcher
305 * @param info information about the widget
306 * @param maxPreviewWidth width of the preview on either workspace or tray
307 * @param preview bitmap that can be recycled
308 * @param preScaledWidthOut return the width of the returned bitmap
309 * @return
310 */
Sunny Goyal27835952017-01-13 12:15:53 -0800311 public Bitmap generateWidgetPreview(BaseActivity launcher, LauncherAppWidgetProviderInfo info,
Sunny Goyal4cad7532015-03-18 15:56:30 -0700312 int maxPreviewWidth, Bitmap preview, int[] preScaledWidthOut) {
Michael Jurka05713af2013-01-23 12:39:24 +0100313 // Load the preview image if possible
Michael Jurka05713af2013-01-23 12:39:24 +0100314 if (maxPreviewWidth < 0) maxPreviewWidth = Integer.MAX_VALUE;
Michael Jurka05713af2013-01-23 12:39:24 +0100315
316 Drawable drawable = null;
Sunny Goyalffe83f12014-08-14 17:39:34 -0700317 if (info.previewImage != 0) {
Sunny Goyal2570d102016-10-27 11:38:45 -0700318 try {
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800319 drawable = info.loadPreviewImage(mContext, 0);
Sunny Goyal2570d102016-10-27 11:38:45 -0700320 } catch (OutOfMemoryError e) {
321 Log.w(TAG, "Error loading widget preview for: " + info.provider, e);
322 // During OutOfMemoryError, the previous heap stack is not affected. Catching
323 // an OOM error here should be safe & not affect other parts of launcher.
324 drawable = null;
325 }
Adrian Roosfa9ffc22014-05-12 15:59:59 +0200326 if (drawable != null) {
327 drawable = mutateOnMainThread(drawable);
328 } else {
Michael Jurka05713af2013-01-23 12:39:24 +0100329 Log.w(TAG, "Can't load widget preview drawable 0x" +
Sunny Goyalffe83f12014-08-14 17:39:34 -0700330 Integer.toHexString(info.previewImage) + " for provider: " + info.provider);
Michael Jurka05713af2013-01-23 12:39:24 +0100331 }
332 }
333
Sunny Goyal4cad7532015-03-18 15:56:30 -0700334 final boolean widgetPreviewExists = (drawable != null);
Sunny Goyal233ee962015-08-03 13:05:01 -0700335 final int spanX = info.spanX;
336 final int spanY = info.spanY;
Sunny Goyal4cad7532015-03-18 15:56:30 -0700337
Michael Jurka05713af2013-01-23 12:39:24 +0100338 int previewWidth;
339 int previewHeight;
Hyunyoung Song3e840f42016-03-01 11:57:44 -0800340
Michael Jurka05713af2013-01-23 12:39:24 +0100341 if (widgetPreviewExists) {
342 previewWidth = drawable.getIntrinsicWidth();
343 previewHeight = drawable.getIntrinsicHeight();
344 } else {
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800345 DeviceProfile dp = launcher.getDeviceProfile();
346 int tileSize = Math.min(dp.cellWidthPx, dp.cellHeightPx);
347 previewWidth = tileSize * spanX;
348 previewHeight = tileSize * spanY;
Michael Jurka05713af2013-01-23 12:39:24 +0100349 }
350
351 // Scale to fit width only - let the widget preview be clipped in the
352 // vertical dimension
353 float scale = 1f;
354 if (preScaledWidthOut != null) {
355 preScaledWidthOut[0] = previewWidth;
356 }
357 if (previewWidth > maxPreviewWidth) {
Sunny Goyala2441e82017-01-14 13:40:15 -0800358 scale = maxPreviewWidth / (float) (previewWidth);
Michael Jurka05713af2013-01-23 12:39:24 +0100359 }
360 if (scale != 1f) {
361 previewWidth = (int) (scale * previewWidth);
362 previewHeight = (int) (scale * previewHeight);
363 }
364
365 // 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 -0700366 final Canvas c = new Canvas();
Michael Jurka05713af2013-01-23 12:39:24 +0100367 if (preview == null) {
368 preview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700369 c.setBitmap(preview);
370 } else {
Sunny Goyala2441e82017-01-14 13:40:15 -0800371 // We use the preview bitmap height to determine where the badge will be drawn in the
372 // UI. If its larger than what we need, resize the preview bitmap so that there are
373 // no transparent pixels between the preview and the badge.
374 if (preview.getHeight() > previewHeight) {
375 preview.reconfigure(preview.getWidth(), previewHeight, preview.getConfig());
376 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700377 // Reusing bitmap. Clear it.
378 c.setBitmap(preview);
379 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100380 }
381
382 // Draw the scaled preview into the final bitmap
Hyunyoung Songb9f932e2015-07-30 15:04:59 -0700383 int x = (preview.getWidth() - previewWidth) / 2;
Michael Jurka05713af2013-01-23 12:39:24 +0100384 if (widgetPreviewExists) {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700385 drawable.setBounds(x, 0, x + previewWidth, previewHeight);
386 drawable.draw(c);
Michael Jurka05713af2013-01-23 12:39:24 +0100387 } else {
Sunny Goyalb3648e02017-05-02 16:17:10 -0700388 RectF boxRect = drawBoxWithShadow(c, previewWidth, previewHeight);
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800389
390 // Draw horizontal and vertical lines to represent individual columns.
Sunny Goyalb3648e02017-05-02 16:17:10 -0700391 final Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800392 p.setStyle(Paint.Style.STROKE);
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800393 p.setStrokeWidth(mContext.getResources()
394 .getDimension(R.dimen.widget_preview_cell_divider_width));
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800395 p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
396
397 float t = boxRect.left;
398 float tileSize = boxRect.width() / spanX;
399 for (int i = 1; i < spanX; i++) {
400 t += tileSize;
401 c.drawLine(t, 0, t, previewHeight, p);
Michael Jurka05713af2013-01-23 12:39:24 +0100402 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700403
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800404 t = boxRect.top;
405 tileSize = boxRect.height() / spanY;
406 for (int i = 1; i < spanY; i++) {
407 t += tileSize;
408 c.drawLine(0, t, previewWidth, t, p);
409 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700410
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800411 // Draw icon in the center.
Sunny Goyal4cad7532015-03-18 15:56:30 -0700412 try {
Sunny Goyal952e63d2017-08-16 04:59:08 -0700413 Drawable icon =
414 mIconCache.getFullResIcon(info.provider.getPackageName(), info.icon);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700415 if (icon != null) {
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800416 int appIconSize = launcher.getDeviceProfile().iconSizePx;
417 int iconSize = (int) Math.min(appIconSize * scale,
418 Math.min(boxRect.width(), boxRect.height()));
419
Sunny Goyal1ba7e362015-10-26 10:42:12 -0700420 icon = mutateOnMainThread(icon);
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800421 int hoffset = (previewWidth - iconSize) / 2;
422 int yoffset = (previewHeight - iconSize) / 2;
423 icon.setBounds(hoffset, yoffset, hoffset + iconSize, yoffset + iconSize);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700424 icon.draw(c);
425 }
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800426 } catch (Resources.NotFoundException e) { }
Michael Jurka05713af2013-01-23 12:39:24 +0100427 c.setBitmap(null);
428 }
Sunny Goyala2441e82017-01-14 13:40:15 -0800429 return preview;
Michael Jurka05713af2013-01-23 12:39:24 +0100430 }
431
Sunny Goyalb3648e02017-05-02 16:17:10 -0700432 private RectF drawBoxWithShadow(Canvas c, int width, int height) {
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800433 Resources res = mContext.getResources();
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800434
Sunny Goyale463c8f2017-06-20 13:34:09 -0700435 ShadowGenerator.Builder builder = new ShadowGenerator.Builder(Color.WHITE);
436 builder.shadowBlur = res.getDimension(R.dimen.widget_preview_shadow_blur);
437 builder.radius = res.getDimension(R.dimen.widget_preview_corner_radius);
438 builder.keyShadowDistance = res.getDimension(R.dimen.widget_preview_key_shadow_distance);
439
440 builder.bounds.set(builder.shadowBlur, builder.shadowBlur,
441 width - builder.shadowBlur,
442 height - builder.shadowBlur - builder.keyShadowDistance);
443 builder.drawShadow(c);
444 return builder.bounds;
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800445 }
446
Sunny Goyal782f0c92017-01-19 10:27:54 -0800447 private Bitmap generateShortcutPreview(BaseActivity launcher, ShortcutConfigActivityInfo info,
448 int maxWidth, int maxHeight, Bitmap preview) {
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800449 int iconSize = launcher.getDeviceProfile().iconSizePx;
450 int padding = launcher.getResources()
451 .getDimensionPixelSize(R.dimen.widget_preview_shortcut_padding);
452
453 int size = iconSize + 2 * padding;
454 if (maxHeight < size || maxWidth < size) {
455 throw new RuntimeException("Max size is too small for preview");
456 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700457 final Canvas c = new Canvas();
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800458 if (preview == null || preview.getWidth() < size || preview.getHeight() < size) {
459 preview = Bitmap.createBitmap(size, size, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700460 c.setBitmap(preview);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700461 } else {
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800462 if (preview.getWidth() > size || preview.getHeight() > size) {
463 preview.reconfigure(size, size, preview.getConfig());
464 }
465
Sunny Goyal4cad7532015-03-18 15:56:30 -0700466 // Reusing bitmap. Clear it.
467 c.setBitmap(preview);
468 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100469 }
Sunny Goyalb3648e02017-05-02 16:17:10 -0700470 RectF boxRect = drawBoxWithShadow(c, size, size);
Michael Jurka05713af2013-01-23 12:39:24 +0100471
Sunny Goyal18a4e5a2018-01-09 15:34:38 -0800472 LauncherIcons li = LauncherIcons.obtain(mContext);
473 Bitmap icon = li.createScaledBitmapWithoutShadow(
474 mutateOnMainThread(info.getFullResIcon(mIconCache)), 0);
475 li.recycle();
476
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800477 Rect src = new Rect(0, 0, icon.getWidth(), icon.getHeight());
Sunny Goyal4cad7532015-03-18 15:56:30 -0700478
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800479 boxRect.set(0, 0, iconSize, iconSize);
480 boxRect.offset(padding, padding);
Sunny Goyalb3648e02017-05-02 16:17:10 -0700481 c.drawBitmap(icon, src, boxRect,
482 new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG));
Michael Jurka05713af2013-01-23 12:39:24 +0100483 c.setBitmap(null);
Michael Jurka05713af2013-01-23 12:39:24 +0100484 return preview;
485 }
486
Adrian Roos65d60e22014-04-15 21:07:49 +0200487 private Drawable mutateOnMainThread(final Drawable drawable) {
488 try {
489 return mMainThreadExecutor.submit(new Callable<Drawable>() {
490 @Override
491 public Drawable call() throws Exception {
492 return drawable.mutate();
493 }
494 }).get();
495 } catch (InterruptedException e) {
496 Thread.currentThread().interrupt();
497 throw new RuntimeException(e);
498 } catch (ExecutionException e) {
499 throw new RuntimeException(e);
500 }
501 }
Adrian Roos1f375ab2014-04-28 18:26:38 +0200502
Adrian Roos1f375ab2014-04-28 18:26:38 +0200503 /**
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700504 * @return an array of containing versionCode and lastUpdatedTime for the package.
Adrian Roos1f375ab2014-04-28 18:26:38 +0200505 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700506 @Thunk long[] getPackageVersion(String packageName) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700507 synchronized (mPackageVersions) {
508 long[] versions = mPackageVersions.get(packageName);
509 if (versions == null) {
510 versions = new long[2];
Adrian Roos1f375ab2014-04-28 18:26:38 +0200511 try {
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800512 PackageInfo info = mContext.getPackageManager().getPackageInfo(packageName,
513 PackageManager.GET_UNINSTALLED_PACKAGES);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700514 versions[0] = info.versionCode;
515 versions[1] = info.lastUpdateTime;
516 } catch (NameNotFoundException e) {
517 Log.e(TAG, "PackageInfo not found", e);
518 }
519 mPackageVersions.put(packageName, versions);
520 }
521 return versions;
522 }
523 }
524
Sunny Goyalc65a0082017-03-08 14:49:55 -0800525 public class PreviewLoadTask extends AsyncTask<Void, Void, Bitmap>
526 implements CancellationSignal.OnCancelListener {
Sunny Goyal316490e2015-06-02 09:38:28 -0700527 @Thunk final WidgetCacheKey mKey;
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800528 private final WidgetItem mInfo;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700529 private final int mPreviewHeight;
530 private final int mPreviewWidth;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700531 private final WidgetCell mCaller;
Sunny Goyala2441e82017-01-14 13:40:15 -0800532 private final BaseActivity mActivity;
Sunny Goyal316490e2015-06-02 09:38:28 -0700533 @Thunk long[] mVersions;
534 @Thunk Bitmap mBitmapToRecycle;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700535
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800536 PreviewLoadTask(WidgetCacheKey key, WidgetItem info, int previewWidth,
Sunny Goyalf1fbc3f2017-10-10 15:21:15 -0700537 int previewHeight, WidgetCell caller) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700538 mKey = key;
539 mInfo = info;
540 mPreviewHeight = previewHeight;
541 mPreviewWidth = previewWidth;
542 mCaller = caller;
Sunny Goyala2441e82017-01-14 13:40:15 -0800543 mActivity = BaseActivity.fromContext(mCaller.getContext());
Hyunyoung Song3f471442015-04-08 19:01:34 -0700544 if (DEBUG) {
545 Log.d(TAG, String.format("%s, %s, %d, %d",
546 mKey, mInfo, mPreviewHeight, mPreviewWidth));
547 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700548 }
549
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700550 @Override
551 protected Bitmap doInBackground(Void... params) {
552 Bitmap unusedBitmap = null;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700553
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700554 // If already cancelled before this gets to run in the background, then return early
555 if (isCancelled()) {
556 return null;
557 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700558 synchronized (mUnusedBitmaps) {
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700559 // Check if we can re-use a bitmap
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700560 for (Bitmap candidate : mUnusedBitmaps) {
561 if (candidate != null && candidate.isMutable() &&
562 candidate.getWidth() == mPreviewWidth &&
563 candidate.getHeight() == mPreviewHeight) {
564 unusedBitmap = candidate;
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700565 mUnusedBitmaps.remove(unusedBitmap);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700566 break;
567 }
568 }
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700569 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700570
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700571 // creating a bitmap is expensive. Do not do this inside synchronized block.
572 if (unusedBitmap == null) {
573 unusedBitmap = Bitmap.createBitmap(mPreviewWidth, mPreviewHeight, Config.ARGB_8888);
Adrian Roos1f375ab2014-04-28 18:26:38 +0200574 }
Winson Chung05304db2015-05-18 16:53:20 -0700575 // If cancelled now, don't bother reading the preview from the DB
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700576 if (isCancelled()) {
Winson Chung05304db2015-05-18 16:53:20 -0700577 return unusedBitmap;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700578 }
Winson Chung05304db2015-05-18 16:53:20 -0700579 Bitmap preview = readFromDb(mKey, unusedBitmap, this);
580 // Only consider generating the preview if we have not cancelled the task already
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700581 if (!isCancelled() && preview == null) {
582 // Fetch the version info before we generate the preview, so that, in-case the
583 // app was updated while we are generating the preview, we use the old version info,
584 // which would gets re-written next time.
Sunny Goyal65513ba2017-01-20 11:54:25 -0800585 boolean persistable = mInfo.activityInfo == null
586 || mInfo.activityInfo.isPersistable();
587 mVersions = persistable ? getPackageVersion(mKey.componentName.getPackageName())
588 : null;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700589
590 // it's not in the db... we need to generate it
Sunny Goyala2441e82017-01-14 13:40:15 -0800591 preview = generatePreview(mActivity, mInfo, unusedBitmap, mPreviewWidth, mPreviewHeight);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700592 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700593 return preview;
594 }
595
596 @Override
Winson Chung05304db2015-05-18 16:53:20 -0700597 protected void onPostExecute(final Bitmap preview) {
Sunny Goyalf1fbc3f2017-10-10 15:21:15 -0700598 mCaller.applyPreview(preview);
Winson Chung05304db2015-05-18 16:53:20 -0700599
600 // Write the generated preview to the DB in the worker thread
601 if (mVersions != null) {
602 mWorkerHandler.post(new Runnable() {
603 @Override
604 public void run() {
605 if (!isCancelled()) {
606 // If we are still using this preview, then write it to the DB and then
607 // let the normal clear mechanism recycle the bitmap
608 writeToDb(mKey, mVersions, preview);
609 mBitmapToRecycle = preview;
610 } else {
611 // If we've already cancelled, then skip writing the bitmap to the DB
612 // and manually add the bitmap back to the recycled set
613 synchronized (mUnusedBitmaps) {
614 mUnusedBitmaps.add(preview);
615 }
616 }
617 }
618 });
619 } else {
620 // If we don't need to write to disk, then ensure the preview gets recycled by
621 // the normal clear mechanism
622 mBitmapToRecycle = preview;
623 }
624 }
625
626 @Override
Hyunyoung Songe98f4a42015-06-16 10:45:24 -0700627 protected void onCancelled(final Bitmap preview) {
Winson Chung05304db2015-05-18 16:53:20 -0700628 // If we've cancelled while the task is running, then can return the bitmap to the
629 // recycled set immediately. Otherwise, it will be recycled after the preview is written
630 // to disk.
631 if (preview != null) {
Hyunyoung Songe98f4a42015-06-16 10:45:24 -0700632 mWorkerHandler.post(new Runnable() {
633 @Override
634 public void run() {
635 synchronized (mUnusedBitmaps) {
636 mUnusedBitmaps.add(preview);
637 }
638 }
639 });
Winson Chung05304db2015-05-18 16:53:20 -0700640 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700641 }
Sunny Goyalc65a0082017-03-08 14:49:55 -0800642
643 @Override
644 public void onCancel() {
645 cancel(true);
646
647 // This only handles the case where the PreviewLoadTask is cancelled after the task has
648 // successfully completed (including having written to disk when necessary). In the
649 // other cases where it is cancelled while the task is running, it will be cleaned up
650 // in the tasks's onCancelled() call, and if cancelled while the task is writing to
651 // disk, it will be cancelled in the task's onPostExecute() call.
652 if (mBitmapToRecycle != null) {
653 mWorkerHandler.post(new Runnable() {
654 @Override
655 public void run() {
656 synchronized (mUnusedBitmaps) {
657 mUnusedBitmaps.add(mBitmapToRecycle);
658 }
659 mBitmapToRecycle = null;
660 }
661 });
662 }
663 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700664 }
665
666 private static final class WidgetCacheKey extends ComponentKey {
667
Sunny Goyal316490e2015-06-02 09:38:28 -0700668 @Thunk final String size;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700669
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800670 public WidgetCacheKey(ComponentName componentName, UserHandle user, String size) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700671 super(componentName, user);
672 this.size = size;
673 }
674
675 @Override
676 public int hashCode() {
677 return super.hashCode() ^ size.hashCode();
678 }
679
680 @Override
681 public boolean equals(Object o) {
682 return super.equals(o) && ((WidgetCacheKey) o).size.equals(size);
Adrian Roos1f375ab2014-04-28 18:26:38 +0200683 }
684 }
Michael Jurka05713af2013-01-23 12:39:24 +0100685}