blob: fc3b66887750b267f6a0dfe5a9bbfc989ea275e2 [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;
Sunny Goyal7d87cb12017-02-13 10:44:43 -080029import android.support.v4.graphics.ColorUtils;
Michael Jurka05713af2013-01-23 12:39:24 +010030import android.util.Log;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070031import android.util.LongSparseArray;
Sunny Goyal383c5072015-06-12 21:18:53 -070032
Sunny Goyalffe83f12014-08-14 17:39:34 -070033import com.android.launcher3.compat.AppWidgetManagerCompat;
Sunny Goyal782f0c92017-01-19 10:27:54 -080034import com.android.launcher3.compat.ShortcutConfigActivityInfo;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070035import com.android.launcher3.compat.UserManagerCompat;
Sunny Goyal7d87cb12017-02-13 10:44:43 -080036import com.android.launcher3.graphics.LauncherIcons;
Sunny Goyal92bbfa12017-02-07 15:06:32 -080037import com.android.launcher3.graphics.ShadowGenerator;
Sunny Goyal4ddc4012016-03-10 12:02:29 -080038import com.android.launcher3.model.WidgetItem;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070039import com.android.launcher3.util.ComponentKey;
Tony Wickham86222d22017-03-29 15:30:43 -070040import com.android.launcher3.util.PackageUserKey;
Sunny Goyal6388b2c2016-04-15 18:03:27 -070041import com.android.launcher3.util.Preconditions;
Sunny Goyal6f709362015-12-17 17:09:36 -080042import com.android.launcher3.util.SQLiteCacheHelper;
Adam Cohen091440a2015-03-18 14:16:05 -070043import com.android.launcher3.util.Thunk;
Hyunyoung Song3f471442015-04-08 19:01:34 -070044import com.android.launcher3.widget.WidgetCell;
Hyunyoung Song8821ca92015-05-04 16:28:20 -070045
46import java.util.ArrayList;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070047import java.util.Collections;
Michael Jurka05713af2013-01-23 12:39:24 +010048import java.util.HashMap;
49import java.util.HashSet;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070050import java.util.Set;
51import java.util.WeakHashMap;
Adrian Roos65d60e22014-04-15 21:07:49 +020052import java.util.concurrent.Callable;
53import java.util.concurrent.ExecutionException;
Michael Jurka05713af2013-01-23 12:39:24 +010054
Sunny Goyalffe83f12014-08-14 17:39:34 -070055public class WidgetPreviewLoader {
Michael Jurka05713af2013-01-23 12:39:24 +010056
Sunny Goyalffe83f12014-08-14 17:39:34 -070057 private static final String TAG = "WidgetPreviewLoader";
Hyunyoung Song3f471442015-04-08 19:01:34 -070058 private static final boolean DEBUG = false;
Sunny Goyalffe83f12014-08-14 17:39:34 -070059
Sunny Goyal5b0e6692015-03-19 14:31:19 -070060 private final HashMap<String, long[]> mPackageVersions = new HashMap<>();
Hyunyoung Song559d90d2015-04-28 15:06:45 -070061
62 /**
63 * Weak reference objects, do not prevent their referents from being made finalizable,
64 * finalized, and then reclaimed.
Hyunyoung Songe98f4a42015-06-16 10:45:24 -070065 * Note: synchronized block used for this variable is expensive and the block should always
66 * be posted to a background thread.
Hyunyoung Song559d90d2015-04-28 15:06:45 -070067 */
Sunny Goyalb4cbea42015-06-16 15:10:36 -070068 @Thunk final Set<Bitmap> mUnusedBitmaps =
Hyunyoung Song559d90d2015-04-28 15:06:45 -070069 Collections.newSetFromMap(new WeakHashMap<Bitmap, Boolean>());
Sunny Goyal4cad7532015-03-18 15:56:30 -070070
71 private final Context mContext;
Sunny Goyalffe83f12014-08-14 17:39:34 -070072 private final IconCache mIconCache;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070073 private final UserManagerCompat mUserManager;
Hyunyoung Song3e840f42016-03-01 11:57:44 -080074 private final AppWidgetManagerCompat mWidgetManager;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070075 private final CacheDb mDb;
Michael Jurka05713af2013-01-23 12:39:24 +010076
Adrian Roos65d60e22014-04-15 21:07:49 +020077 private final MainThreadExecutor mMainThreadExecutor = new MainThreadExecutor();
Sunny Goyal316490e2015-06-02 09:38:28 -070078 @Thunk final Handler mWorkerHandler;
Adrian Roos65d60e22014-04-15 21:07:49 +020079
Sunny Goyal383c5072015-06-12 21:18:53 -070080 public WidgetPreviewLoader(Context context, IconCache iconCache) {
Chris Wrenfd13c712013-09-27 15:45:19 -040081 mContext = context;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070082 mIconCache = iconCache;
Hyunyoung Song3e840f42016-03-01 11:57:44 -080083 mWidgetManager = AppWidgetManagerCompat.getInstance(context);
Sunny Goyal5b0e6692015-03-19 14:31:19 -070084 mUserManager = UserManagerCompat.getInstance(context);
85 mDb = new CacheDb(context);
Winson Chung05304db2015-05-18 16:53:20 -070086 mWorkerHandler = new Handler(LauncherModel.getWorkerLooper());
Michael Jurka3f4e0702013-02-05 11:21:28 +010087 }
Sunny Goyalffe83f12014-08-14 17:39:34 -070088
Sunny Goyal5b0e6692015-03-19 14:31:19 -070089 /**
90 * Generates the widget preview on {@link AsyncTask#THREAD_POOL_EXECUTOR}. Must be
91 * called on UI thread
92 *
Sunny Goyal5b0e6692015-03-19 14:31:19 -070093 * @return a request id which can be used to cancel the request.
94 */
Sunny Goyalc65a0082017-03-08 14:49:55 -080095 public CancellationSignal getPreview(WidgetItem item, int previewWidth,
Tony Wickham26b17462017-03-20 17:12:24 -070096 int previewHeight, WidgetCell caller, boolean animate) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -070097 String size = previewWidth + "x" + previewHeight;
Sunny Goyal4ddc4012016-03-10 12:02:29 -080098 WidgetCacheKey key = new WidgetCacheKey(item.componentName, item.user, size);
Michael Jurka3f4e0702013-02-05 11:21:28 +010099
Tony Wickham26b17462017-03-20 17:12:24 -0700100 PreviewLoadTask task = new PreviewLoadTask(key, item, previewWidth, previewHeight, caller,
101 animate);
Sunny Goyal8ac727b2015-09-23 15:38:09 -0700102 task.executeOnExecutor(Utilities.THREAD_POOL_EXECUTOR);
Sunny Goyalc65a0082017-03-08 14:49:55 -0800103
104 CancellationSignal signal = new CancellationSignal();
105 signal.setOnCancelListener(task);
106 return signal;
Michael Jurka05713af2013-01-23 12:39:24 +0100107 }
108
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700109 /**
110 * The DB holds the generated previews for various components. Previews can also have different
111 * sizes (landscape vs portrait).
112 */
Sunny Goyal6f709362015-12-17 17:09:36 -0800113 private static class CacheDb extends SQLiteCacheHelper {
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800114 private static final int DB_VERSION = 6;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700115
116 private static final String TABLE_NAME = "shortcut_and_widget_previews";
117 private static final String COLUMN_COMPONENT = "componentName";
118 private static final String COLUMN_USER = "profileId";
119 private static final String COLUMN_SIZE = "size";
120 private static final String COLUMN_PACKAGE = "packageName";
121 private static final String COLUMN_LAST_UPDATED = "lastUpdated";
122 private static final String COLUMN_VERSION = "version";
123 private static final String COLUMN_PREVIEW_BITMAP = "preview_bitmap";
Michael Jurka05713af2013-01-23 12:39:24 +0100124
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100125 public CacheDb(Context context) {
Sunny Goyal6f709362015-12-17 17:09:36 -0800126 super(context, LauncherFiles.WIDGET_PREVIEWS_DB, DB_VERSION, TABLE_NAME);
Michael Jurka05713af2013-01-23 12:39:24 +0100127 }
128
129 @Override
Sunny Goyal6f709362015-12-17 17:09:36 -0800130 public void onCreateTable(SQLiteDatabase database) {
Michael Jurka32b7a092013-02-07 20:06:49 +0100131 database.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" +
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700132 COLUMN_COMPONENT + " TEXT NOT NULL, " +
133 COLUMN_USER + " INTEGER NOT NULL, " +
Michael Jurka05713af2013-01-23 12:39:24 +0100134 COLUMN_SIZE + " TEXT NOT NULL, " +
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700135 COLUMN_PACKAGE + " TEXT NOT NULL, " +
136 COLUMN_LAST_UPDATED + " INTEGER NOT NULL DEFAULT 0, " +
137 COLUMN_VERSION + " INTEGER NOT NULL DEFAULT 0, " +
138 COLUMN_PREVIEW_BITMAP + " BLOB, " +
139 "PRIMARY KEY (" + COLUMN_COMPONENT + ", " + COLUMN_USER + ", " + COLUMN_SIZE + ") " +
Michael Jurka32b7a092013-02-07 20:06:49 +0100140 ");");
Michael Jurka05713af2013-01-23 12:39:24 +0100141 }
Michael Jurka05713af2013-01-23 12:39:24 +0100142 }
143
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700144 @Thunk void writeToDb(WidgetCacheKey key, long[] versions, Bitmap preview) {
Michael Jurka05713af2013-01-23 12:39:24 +0100145 ContentValues values = new ContentValues();
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700146 values.put(CacheDb.COLUMN_COMPONENT, key.componentName.flattenToShortString());
147 values.put(CacheDb.COLUMN_USER, mUserManager.getSerialNumberForUser(key.user));
148 values.put(CacheDb.COLUMN_SIZE, key.size);
149 values.put(CacheDb.COLUMN_PACKAGE, key.componentName.getPackageName());
150 values.put(CacheDb.COLUMN_VERSION, versions[0]);
151 values.put(CacheDb.COLUMN_LAST_UPDATED, versions[1]);
152 values.put(CacheDb.COLUMN_PREVIEW_BITMAP, Utilities.flattenBitmap(preview));
Sunny Goyal6f709362015-12-17 17:09:36 -0800153 mDb.insertOrReplace(values);
Michael Jurka05713af2013-01-23 12:39:24 +0100154 }
155
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800156 public void removePackage(String packageName, UserHandle user) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700157 removePackage(packageName, user, mUserManager.getSerialNumberForUser(user));
158 }
159
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800160 private void removePackage(String packageName, UserHandle user, long userSerial) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700161 synchronized(mPackageVersions) {
162 mPackageVersions.remove(packageName);
163 }
164
Sunny Goyal6f709362015-12-17 17:09:36 -0800165 mDb.delete(
166 CacheDb.COLUMN_PACKAGE + " = ? AND " + CacheDb.COLUMN_USER + " = ?",
167 new String[]{packageName, Long.toString(userSerial)});
Michael Jurka8ff02ca2013-11-01 14:19:27 +0100168 }
169
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700170 /**
171 * Updates the persistent DB:
172 * 1. Any preview generated for an old package version is removed
173 * 2. Any preview for an absent package is removed
174 * This ensures that we remove entries for packages which changed while the launcher was dead.
Tony Wickham86222d22017-03-29 15:30:43 -0700175 *
176 * @param packageUser if provided, specifies that list only contains previews for the
177 * given package/user, otherwise the list contains all previews
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700178 */
Tony Wickham86222d22017-03-29 15:30:43 -0700179 public void removeObsoletePreviews(ArrayList<? extends ComponentKey> list,
180 @Nullable PackageUserKey packageUser) {
Sunny Goyal6388b2c2016-04-15 18:03:27 -0700181 Preconditions.assertWorkerThread();
Hyunyoung Song8821ca92015-05-04 16:28:20 -0700182
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700183 LongSparseArray<HashSet<String>> validPackages = new LongSparseArray<>();
184
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800185 for (ComponentKey key : list) {
186 final long userId = mUserManager.getSerialNumberForUser(key.user);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700187 HashSet<String> packages = validPackages.get(userId);
188 if (packages == null) {
189 packages = new HashSet<>();
190 validPackages.put(userId, packages);
191 }
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800192 packages.add(key.componentName.getPackageName());
Michael Jurka05713af2013-01-23 12:39:24 +0100193 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700194
195 LongSparseArray<HashSet<String>> packagesToDelete = new LongSparseArray<>();
Tony Wickham86222d22017-03-29 15:30:43 -0700196 long passedUserId = packageUser == null ? 0
197 : mUserManager.getSerialNumberForUser(packageUser.mUser);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700198 Cursor c = null;
199 try {
Sunny Goyal6f709362015-12-17 17:09:36 -0800200 c = mDb.query(
201 new String[]{CacheDb.COLUMN_USER, CacheDb.COLUMN_PACKAGE,
202 CacheDb.COLUMN_LAST_UPDATED, CacheDb.COLUMN_VERSION},
203 null, null);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700204 while (c.moveToNext()) {
205 long userId = c.getLong(0);
206 String pkg = c.getString(1);
207 long lastUpdated = c.getLong(2);
208 long version = c.getLong(3);
209
Tony Wickham86222d22017-03-29 15:30:43 -0700210 if (packageUser != null && (!pkg.equals(packageUser.mPackageName)
211 || userId != passedUserId)) {
212 // This preview is associated with a different package/user, no need to remove.
213 continue;
214 }
215
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700216 HashSet<String> packages = validPackages.get(userId);
217 if (packages != null && packages.contains(pkg)) {
218 long[] versions = getPackageVersion(pkg);
219 if (versions[0] == version && versions[1] == lastUpdated) {
220 // Every thing checks out
221 continue;
222 }
223 }
224
225 // We need to delete this package.
226 packages = packagesToDelete.get(userId);
227 if (packages == null) {
228 packages = new HashSet<>();
229 packagesToDelete.put(userId, packages);
230 }
231 packages.add(pkg);
232 }
233
234 for (int i = 0; i < packagesToDelete.size(); i++) {
235 long userId = packagesToDelete.keyAt(i);
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800236 UserHandle user = mUserManager.getUserForSerialNumber(userId);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700237 for (String pkg : packagesToDelete.valueAt(i)) {
238 removePackage(pkg, user, userId);
239 }
240 }
241 } catch (SQLException e) {
Sunny Goyal6f709362015-12-17 17:09:36 -0800242 Log.e(TAG, "Error updating widget previews", e);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700243 } finally {
244 if (c != null) {
245 c.close();
246 }
247 }
248 }
249
Winson Chung05304db2015-05-18 16:53:20 -0700250 /**
251 * Reads the preview bitmap from the DB or null if the preview is not in the DB.
252 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700253 @Thunk Bitmap readFromDb(WidgetCacheKey key, Bitmap recycle, PreviewLoadTask loadTask) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700254 Cursor cursor = null;
255 try {
Sunny Goyal6f709362015-12-17 17:09:36 -0800256 cursor = mDb.query(
257 new String[]{CacheDb.COLUMN_PREVIEW_BITMAP},
258 CacheDb.COLUMN_COMPONENT + " = ? AND " + CacheDb.COLUMN_USER + " = ? AND "
259 + CacheDb.COLUMN_SIZE + " = ?",
260 new String[]{
Sunny Goyal3ef86912016-10-27 11:40:06 -0700261 key.componentName.flattenToShortString(),
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700262 Long.toString(mUserManager.getSerialNumberForUser(key.user)),
263 key.size
Sunny Goyal6f709362015-12-17 17:09:36 -0800264 });
Winson Chung05304db2015-05-18 16:53:20 -0700265 // If cancelled, skip getting the blob and decoding it into a bitmap
266 if (loadTask.isCancelled()) {
267 return null;
268 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700269 if (cursor.moveToNext()) {
270 byte[] blob = cursor.getBlob(0);
271 BitmapFactory.Options opts = new BitmapFactory.Options();
272 opts.inBitmap = recycle;
Michael Jurka6e27f642013-12-10 13:40:30 +0100273 try {
Winson Chung05304db2015-05-18 16:53:20 -0700274 if (!loadTask.isCancelled()) {
275 return BitmapFactory.decodeByteArray(blob, 0, blob.length, opts);
276 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700277 } catch (Exception e) {
278 return null;
Michael Jurka6e27f642013-12-10 13:40:30 +0100279 }
Michael Jurka05713af2013-01-23 12:39:24 +0100280 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700281 } catch (SQLException e) {
282 Log.w(TAG, "Error loading preview from DB", e);
283 } finally {
284 if (cursor != null) {
285 cursor.close();
286 }
287 }
288 return null;
Michael Jurka05713af2013-01-23 12:39:24 +0100289 }
290
Sunny Goyal27835952017-01-13 12:15:53 -0800291 private Bitmap generatePreview(BaseActivity launcher, WidgetItem item, Bitmap recycle,
Adam Cohen2e6da152015-05-06 11:42:25 -0700292 int previewWidth, int previewHeight) {
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800293 if (item.widgetInfo != null) {
294 return generateWidgetPreview(launcher, item.widgetInfo,
Adam Cohen2e6da152015-05-06 11:42:25 -0700295 previewWidth, recycle, null);
Michael Jurka05713af2013-01-23 12:39:24 +0100296 } else {
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800297 return generateShortcutPreview(launcher, item.activityInfo,
298 previewWidth, previewHeight, recycle);
Michael Jurka05713af2013-01-23 12:39:24 +0100299 }
300 }
301
Hyunyoung Song3e840f42016-03-01 11:57:44 -0800302 /**
303 * Generates the widget preview from either the {@link AppWidgetManagerCompat} or cache
304 * and add badge at the bottom right corner.
305 *
306 * @param launcher
307 * @param info information about the widget
308 * @param maxPreviewWidth width of the preview on either workspace or tray
309 * @param preview bitmap that can be recycled
310 * @param preScaledWidthOut return the width of the returned bitmap
311 * @return
312 */
Sunny Goyal27835952017-01-13 12:15:53 -0800313 public Bitmap generateWidgetPreview(BaseActivity launcher, LauncherAppWidgetProviderInfo info,
Sunny Goyal4cad7532015-03-18 15:56:30 -0700314 int maxPreviewWidth, Bitmap preview, int[] preScaledWidthOut) {
Michael Jurka05713af2013-01-23 12:39:24 +0100315 // Load the preview image if possible
Michael Jurka05713af2013-01-23 12:39:24 +0100316 if (maxPreviewWidth < 0) maxPreviewWidth = Integer.MAX_VALUE;
Michael Jurka05713af2013-01-23 12:39:24 +0100317
318 Drawable drawable = null;
Sunny Goyalffe83f12014-08-14 17:39:34 -0700319 if (info.previewImage != 0) {
Sunny Goyal2570d102016-10-27 11:38:45 -0700320 try {
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800321 drawable = info.loadPreviewImage(mContext, 0);
Sunny Goyal2570d102016-10-27 11:38:45 -0700322 } catch (OutOfMemoryError e) {
323 Log.w(TAG, "Error loading widget preview for: " + info.provider, e);
324 // During OutOfMemoryError, the previous heap stack is not affected. Catching
325 // an OOM error here should be safe & not affect other parts of launcher.
326 drawable = null;
327 }
Adrian Roosfa9ffc22014-05-12 15:59:59 +0200328 if (drawable != null) {
329 drawable = mutateOnMainThread(drawable);
330 } else {
Michael Jurka05713af2013-01-23 12:39:24 +0100331 Log.w(TAG, "Can't load widget preview drawable 0x" +
Sunny Goyalffe83f12014-08-14 17:39:34 -0700332 Integer.toHexString(info.previewImage) + " for provider: " + info.provider);
Michael Jurka05713af2013-01-23 12:39:24 +0100333 }
334 }
335
Sunny Goyal4cad7532015-03-18 15:56:30 -0700336 final boolean widgetPreviewExists = (drawable != null);
Sunny Goyal233ee962015-08-03 13:05:01 -0700337 final int spanX = info.spanX;
338 final int spanY = info.spanY;
Sunny Goyal4cad7532015-03-18 15:56:30 -0700339
Michael Jurka05713af2013-01-23 12:39:24 +0100340 int previewWidth;
341 int previewHeight;
Hyunyoung Song3e840f42016-03-01 11:57:44 -0800342
Michael Jurka05713af2013-01-23 12:39:24 +0100343 if (widgetPreviewExists) {
344 previewWidth = drawable.getIntrinsicWidth();
345 previewHeight = drawable.getIntrinsicHeight();
346 } else {
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800347 DeviceProfile dp = launcher.getDeviceProfile();
348 int tileSize = Math.min(dp.cellWidthPx, dp.cellHeightPx);
349 previewWidth = tileSize * spanX;
350 previewHeight = tileSize * spanY;
Michael Jurka05713af2013-01-23 12:39:24 +0100351 }
352
353 // Scale to fit width only - let the widget preview be clipped in the
354 // vertical dimension
355 float scale = 1f;
356 if (preScaledWidthOut != null) {
357 preScaledWidthOut[0] = previewWidth;
358 }
359 if (previewWidth > maxPreviewWidth) {
Sunny Goyala2441e82017-01-14 13:40:15 -0800360 scale = maxPreviewWidth / (float) (previewWidth);
Michael Jurka05713af2013-01-23 12:39:24 +0100361 }
362 if (scale != 1f) {
363 previewWidth = (int) (scale * previewWidth);
364 previewHeight = (int) (scale * previewHeight);
365 }
366
367 // 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 -0700368 final Canvas c = new Canvas();
Michael Jurka05713af2013-01-23 12:39:24 +0100369 if (preview == null) {
370 preview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700371 c.setBitmap(preview);
372 } else {
Sunny Goyala2441e82017-01-14 13:40:15 -0800373 // We use the preview bitmap height to determine where the badge will be drawn in the
374 // UI. If its larger than what we need, resize the preview bitmap so that there are
375 // no transparent pixels between the preview and the badge.
376 if (preview.getHeight() > previewHeight) {
377 preview.reconfigure(preview.getWidth(), previewHeight, preview.getConfig());
378 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700379 // Reusing bitmap. Clear it.
380 c.setBitmap(preview);
381 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100382 }
383
384 // Draw the scaled preview into the final bitmap
Hyunyoung Songb9f932e2015-07-30 15:04:59 -0700385 int x = (preview.getWidth() - previewWidth) / 2;
Michael Jurka05713af2013-01-23 12:39:24 +0100386 if (widgetPreviewExists) {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700387 drawable.setBounds(x, 0, x + previewWidth, previewHeight);
388 drawable.draw(c);
Michael Jurka05713af2013-01-23 12:39:24 +0100389 } else {
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800390 final Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800391 RectF boxRect = drawBoxWithShadow(c, p, previewWidth, previewHeight);
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800392
393 // Draw horizontal and vertical lines to represent individual columns.
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800394 p.setStyle(Paint.Style.STROKE);
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800395 p.setStrokeWidth(mContext.getResources()
396 .getDimension(R.dimen.widget_preview_cell_divider_width));
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800397 p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
398
399 float t = boxRect.left;
400 float tileSize = boxRect.width() / spanX;
401 for (int i = 1; i < spanX; i++) {
402 t += tileSize;
403 c.drawLine(t, 0, t, previewHeight, p);
Michael Jurka05713af2013-01-23 12:39:24 +0100404 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700405
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800406 t = boxRect.top;
407 tileSize = boxRect.height() / spanY;
408 for (int i = 1; i < spanY; i++) {
409 t += tileSize;
410 c.drawLine(0, t, previewWidth, t, p);
411 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700412
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800413 // Draw icon in the center.
Sunny Goyal4cad7532015-03-18 15:56:30 -0700414 try {
Sunny Goyala52ecb02016-12-16 15:04:51 -0800415 Drawable icon = info.getIcon(launcher, mIconCache);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700416 if (icon != null) {
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800417 int appIconSize = launcher.getDeviceProfile().iconSizePx;
418 int iconSize = (int) Math.min(appIconSize * scale,
419 Math.min(boxRect.width(), boxRect.height()));
420
Sunny Goyal1ba7e362015-10-26 10:42:12 -0700421 icon = mutateOnMainThread(icon);
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800422 int hoffset = (previewWidth - iconSize) / 2;
423 int yoffset = (previewHeight - iconSize) / 2;
424 icon.setBounds(hoffset, yoffset, hoffset + iconSize, yoffset + iconSize);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700425 icon.draw(c);
426 }
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800427 } catch (Resources.NotFoundException e) { }
Michael Jurka05713af2013-01-23 12:39:24 +0100428 c.setBitmap(null);
429 }
Sunny Goyala2441e82017-01-14 13:40:15 -0800430 return preview;
Michael Jurka05713af2013-01-23 12:39:24 +0100431 }
432
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800433 private RectF drawBoxWithShadow(Canvas c, Paint p, int width, int height) {
434 Resources res = mContext.getResources();
435 float shadowBlur = res.getDimension(R.dimen.widget_preview_shadow_blur);
436 float keyShadowDistance = res.getDimension(R.dimen.widget_preview_key_shadow_distance);
437 float corner = res.getDimension(R.dimen.widget_preview_corner_radius);
438
439 RectF bounds = new RectF(shadowBlur, shadowBlur,
440 width - shadowBlur, height - shadowBlur - keyShadowDistance);
441 p.setColor(Color.WHITE);
442
443 // Key shadow
444 p.setShadowLayer(shadowBlur, 0, keyShadowDistance,
445 ShadowGenerator.KEY_SHADOW_ALPHA << 24);
446 c.drawRoundRect(bounds, corner, corner, p);
447
448 // Ambient shadow
449 p.setShadowLayer(shadowBlur, 0, 0,
450 ColorUtils.setAlphaComponent(Color.BLACK, ShadowGenerator.AMBIENT_SHADOW_ALPHA));
451 c.drawRoundRect(bounds, corner, corner, p);
452
453 p.clearShadowLayer();
454 return bounds;
455 }
456
Sunny Goyal782f0c92017-01-19 10:27:54 -0800457 private Bitmap generateShortcutPreview(BaseActivity launcher, ShortcutConfigActivityInfo info,
458 int maxWidth, int maxHeight, Bitmap preview) {
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800459 int iconSize = launcher.getDeviceProfile().iconSizePx;
460 int padding = launcher.getResources()
461 .getDimensionPixelSize(R.dimen.widget_preview_shortcut_padding);
462
463 int size = iconSize + 2 * padding;
464 if (maxHeight < size || maxWidth < size) {
465 throw new RuntimeException("Max size is too small for preview");
466 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700467 final Canvas c = new Canvas();
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800468 if (preview == null || preview.getWidth() < size || preview.getHeight() < size) {
469 preview = Bitmap.createBitmap(size, size, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700470 c.setBitmap(preview);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700471 } else {
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800472 if (preview.getWidth() > size || preview.getHeight() > size) {
473 preview.reconfigure(size, size, preview.getConfig());
474 }
475
Sunny Goyal4cad7532015-03-18 15:56:30 -0700476 // Reusing bitmap. Clear it.
477 c.setBitmap(preview);
478 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100479 }
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800480 Paint p = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
481 RectF boxRect = drawBoxWithShadow(c, p, size, size);
Michael Jurka05713af2013-01-23 12:39:24 +0100482
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800483 Bitmap icon = LauncherIcons.createScaledBitmapWithoutShadow(
484 mutateOnMainThread(info.getFullResIcon(mIconCache)), mContext);
485 Rect src = new Rect(0, 0, icon.getWidth(), icon.getHeight());
Sunny Goyal4cad7532015-03-18 15:56:30 -0700486
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800487 boxRect.set(0, 0, iconSize, iconSize);
488 boxRect.offset(padding, padding);
489 c.drawBitmap(icon, src, boxRect, p);
Michael Jurka05713af2013-01-23 12:39:24 +0100490 c.setBitmap(null);
Michael Jurka05713af2013-01-23 12:39:24 +0100491 return preview;
492 }
493
Adrian Roos65d60e22014-04-15 21:07:49 +0200494 private Drawable mutateOnMainThread(final Drawable drawable) {
495 try {
496 return mMainThreadExecutor.submit(new Callable<Drawable>() {
497 @Override
498 public Drawable call() throws Exception {
499 return drawable.mutate();
500 }
501 }).get();
502 } catch (InterruptedException e) {
503 Thread.currentThread().interrupt();
504 throw new RuntimeException(e);
505 } catch (ExecutionException e) {
506 throw new RuntimeException(e);
507 }
508 }
Adrian Roos1f375ab2014-04-28 18:26:38 +0200509
Adrian Roos1f375ab2014-04-28 18:26:38 +0200510 /**
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700511 * @return an array of containing versionCode and lastUpdatedTime for the package.
Adrian Roos1f375ab2014-04-28 18:26:38 +0200512 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700513 @Thunk long[] getPackageVersion(String packageName) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700514 synchronized (mPackageVersions) {
515 long[] versions = mPackageVersions.get(packageName);
516 if (versions == null) {
517 versions = new long[2];
Adrian Roos1f375ab2014-04-28 18:26:38 +0200518 try {
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800519 PackageInfo info = mContext.getPackageManager().getPackageInfo(packageName,
520 PackageManager.GET_UNINSTALLED_PACKAGES);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700521 versions[0] = info.versionCode;
522 versions[1] = info.lastUpdateTime;
523 } catch (NameNotFoundException e) {
524 Log.e(TAG, "PackageInfo not found", e);
525 }
526 mPackageVersions.put(packageName, versions);
527 }
528 return versions;
529 }
530 }
531
Sunny Goyalc65a0082017-03-08 14:49:55 -0800532 public class PreviewLoadTask extends AsyncTask<Void, Void, Bitmap>
533 implements CancellationSignal.OnCancelListener {
Sunny Goyal316490e2015-06-02 09:38:28 -0700534 @Thunk final WidgetCacheKey mKey;
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800535 private final WidgetItem mInfo;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700536 private final int mPreviewHeight;
537 private final int mPreviewWidth;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700538 private final WidgetCell mCaller;
Tony Wickham26b17462017-03-20 17:12:24 -0700539 private final boolean mAnimatePreviewIn;
Sunny Goyala2441e82017-01-14 13:40:15 -0800540 private final BaseActivity mActivity;
Sunny Goyal316490e2015-06-02 09:38:28 -0700541 @Thunk long[] mVersions;
542 @Thunk Bitmap mBitmapToRecycle;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700543
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800544 PreviewLoadTask(WidgetCacheKey key, WidgetItem info, int previewWidth,
Tony Wickham26b17462017-03-20 17:12:24 -0700545 int previewHeight, WidgetCell caller, boolean animate) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700546 mKey = key;
547 mInfo = info;
548 mPreviewHeight = previewHeight;
549 mPreviewWidth = previewWidth;
550 mCaller = caller;
Tony Wickham26b17462017-03-20 17:12:24 -0700551 mAnimatePreviewIn = animate;
Sunny Goyala2441e82017-01-14 13:40:15 -0800552 mActivity = BaseActivity.fromContext(mCaller.getContext());
Hyunyoung Song3f471442015-04-08 19:01:34 -0700553 if (DEBUG) {
554 Log.d(TAG, String.format("%s, %s, %d, %d",
555 mKey, mInfo, mPreviewHeight, mPreviewWidth));
556 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700557 }
558
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700559 @Override
560 protected Bitmap doInBackground(Void... params) {
561 Bitmap unusedBitmap = null;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700562
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700563 // If already cancelled before this gets to run in the background, then return early
564 if (isCancelled()) {
565 return null;
566 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700567 synchronized (mUnusedBitmaps) {
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700568 // Check if we can re-use a bitmap
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700569 for (Bitmap candidate : mUnusedBitmaps) {
570 if (candidate != null && candidate.isMutable() &&
571 candidate.getWidth() == mPreviewWidth &&
572 candidate.getHeight() == mPreviewHeight) {
573 unusedBitmap = candidate;
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700574 mUnusedBitmaps.remove(unusedBitmap);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700575 break;
576 }
577 }
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700578 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700579
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700580 // creating a bitmap is expensive. Do not do this inside synchronized block.
581 if (unusedBitmap == null) {
582 unusedBitmap = Bitmap.createBitmap(mPreviewWidth, mPreviewHeight, Config.ARGB_8888);
Adrian Roos1f375ab2014-04-28 18:26:38 +0200583 }
Winson Chung05304db2015-05-18 16:53:20 -0700584 // If cancelled now, don't bother reading the preview from the DB
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700585 if (isCancelled()) {
Winson Chung05304db2015-05-18 16:53:20 -0700586 return unusedBitmap;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700587 }
Winson Chung05304db2015-05-18 16:53:20 -0700588 Bitmap preview = readFromDb(mKey, unusedBitmap, this);
589 // Only consider generating the preview if we have not cancelled the task already
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700590 if (!isCancelled() && preview == null) {
591 // Fetch the version info before we generate the preview, so that, in-case the
592 // app was updated while we are generating the preview, we use the old version info,
593 // which would gets re-written next time.
Sunny Goyal65513ba2017-01-20 11:54:25 -0800594 boolean persistable = mInfo.activityInfo == null
595 || mInfo.activityInfo.isPersistable();
596 mVersions = persistable ? getPackageVersion(mKey.componentName.getPackageName())
597 : null;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700598
599 // it's not in the db... we need to generate it
Sunny Goyala2441e82017-01-14 13:40:15 -0800600 preview = generatePreview(mActivity, mInfo, unusedBitmap, mPreviewWidth, mPreviewHeight);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700601 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700602 return preview;
603 }
604
605 @Override
Winson Chung05304db2015-05-18 16:53:20 -0700606 protected void onPostExecute(final Bitmap preview) {
Tony Wickham26b17462017-03-20 17:12:24 -0700607 mCaller.applyPreview(preview, mAnimatePreviewIn);
Winson Chung05304db2015-05-18 16:53:20 -0700608
609 // Write the generated preview to the DB in the worker thread
610 if (mVersions != null) {
611 mWorkerHandler.post(new Runnable() {
612 @Override
613 public void run() {
614 if (!isCancelled()) {
615 // If we are still using this preview, then write it to the DB and then
616 // let the normal clear mechanism recycle the bitmap
617 writeToDb(mKey, mVersions, preview);
618 mBitmapToRecycle = preview;
619 } else {
620 // If we've already cancelled, then skip writing the bitmap to the DB
621 // and manually add the bitmap back to the recycled set
622 synchronized (mUnusedBitmaps) {
623 mUnusedBitmaps.add(preview);
624 }
625 }
626 }
627 });
628 } else {
629 // If we don't need to write to disk, then ensure the preview gets recycled by
630 // the normal clear mechanism
631 mBitmapToRecycle = preview;
632 }
633 }
634
635 @Override
Hyunyoung Songe98f4a42015-06-16 10:45:24 -0700636 protected void onCancelled(final Bitmap preview) {
Winson Chung05304db2015-05-18 16:53:20 -0700637 // If we've cancelled while the task is running, then can return the bitmap to the
638 // recycled set immediately. Otherwise, it will be recycled after the preview is written
639 // to disk.
640 if (preview != null) {
Hyunyoung Songe98f4a42015-06-16 10:45:24 -0700641 mWorkerHandler.post(new Runnable() {
642 @Override
643 public void run() {
644 synchronized (mUnusedBitmaps) {
645 mUnusedBitmaps.add(preview);
646 }
647 }
648 });
Winson Chung05304db2015-05-18 16:53:20 -0700649 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700650 }
Sunny Goyalc65a0082017-03-08 14:49:55 -0800651
652 @Override
653 public void onCancel() {
654 cancel(true);
655
656 // This only handles the case where the PreviewLoadTask is cancelled after the task has
657 // successfully completed (including having written to disk when necessary). In the
658 // other cases where it is cancelled while the task is running, it will be cleaned up
659 // in the tasks's onCancelled() call, and if cancelled while the task is writing to
660 // disk, it will be cancelled in the task's onPostExecute() call.
661 if (mBitmapToRecycle != null) {
662 mWorkerHandler.post(new Runnable() {
663 @Override
664 public void run() {
665 synchronized (mUnusedBitmaps) {
666 mUnusedBitmaps.add(mBitmapToRecycle);
667 }
668 mBitmapToRecycle = null;
669 }
670 });
671 }
672 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700673 }
674
675 private static final class WidgetCacheKey extends ComponentKey {
676
Sunny Goyal316490e2015-06-02 09:38:28 -0700677 @Thunk final String size;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700678
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800679 public WidgetCacheKey(ComponentName componentName, UserHandle user, String size) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700680 super(componentName, user);
681 this.size = size;
682 }
683
684 @Override
685 public int hashCode() {
686 return super.hashCode() ^ size.hashCode();
687 }
688
689 @Override
690 public boolean equals(Object o) {
691 return super.equals(o) && ((WidgetCacheKey) o).size.equals(size);
Adrian Roos1f375ab2014-04-28 18:26:38 +0200692 }
693 }
Michael Jurka05713af2013-01-23 12:39:24 +0100694}