blob: 49e68d75a399dd83b882cdf3931c50758d546e7e [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;
Sunny Goyal7d87cb12017-02-13 10:44:43 -080028import android.support.v4.graphics.ColorUtils;
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;
Sunny Goyal6388b2c2016-04-15 18:03:27 -070039import com.android.launcher3.util.Preconditions;
Sunny Goyal6f709362015-12-17 17:09:36 -080040import com.android.launcher3.util.SQLiteCacheHelper;
Adam Cohen091440a2015-03-18 14:16:05 -070041import com.android.launcher3.util.Thunk;
Hyunyoung Song3f471442015-04-08 19:01:34 -070042import com.android.launcher3.widget.WidgetCell;
Hyunyoung Song8821ca92015-05-04 16:28:20 -070043
44import java.util.ArrayList;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070045import java.util.Collections;
Michael Jurka05713af2013-01-23 12:39:24 +010046import java.util.HashMap;
47import java.util.HashSet;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070048import java.util.Set;
49import java.util.WeakHashMap;
Adrian Roos65d60e22014-04-15 21:07:49 +020050import java.util.concurrent.Callable;
51import java.util.concurrent.ExecutionException;
Michael Jurka05713af2013-01-23 12:39:24 +010052
Sunny Goyalffe83f12014-08-14 17:39:34 -070053public class WidgetPreviewLoader {
Michael Jurka05713af2013-01-23 12:39:24 +010054
Sunny Goyalffe83f12014-08-14 17:39:34 -070055 private static final String TAG = "WidgetPreviewLoader";
Hyunyoung Song3f471442015-04-08 19:01:34 -070056 private static final boolean DEBUG = false;
Sunny Goyalffe83f12014-08-14 17:39:34 -070057
Sunny Goyal5b0e6692015-03-19 14:31:19 -070058 private final HashMap<String, long[]> mPackageVersions = new HashMap<>();
Hyunyoung Song559d90d2015-04-28 15:06:45 -070059
60 /**
61 * Weak reference objects, do not prevent their referents from being made finalizable,
62 * finalized, and then reclaimed.
Hyunyoung Songe98f4a42015-06-16 10:45:24 -070063 * Note: synchronized block used for this variable is expensive and the block should always
64 * be posted to a background thread.
Hyunyoung Song559d90d2015-04-28 15:06:45 -070065 */
Sunny Goyalb4cbea42015-06-16 15:10:36 -070066 @Thunk final Set<Bitmap> mUnusedBitmaps =
Hyunyoung Song559d90d2015-04-28 15:06:45 -070067 Collections.newSetFromMap(new WeakHashMap<Bitmap, Boolean>());
Sunny Goyal4cad7532015-03-18 15:56:30 -070068
69 private final Context mContext;
Sunny Goyalffe83f12014-08-14 17:39:34 -070070 private final IconCache mIconCache;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070071 private final UserManagerCompat mUserManager;
Hyunyoung Song3e840f42016-03-01 11:57:44 -080072 private final AppWidgetManagerCompat mWidgetManager;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070073 private final CacheDb mDb;
Michael Jurka05713af2013-01-23 12:39:24 +010074
Adrian Roos65d60e22014-04-15 21:07:49 +020075 private final MainThreadExecutor mMainThreadExecutor = new MainThreadExecutor();
Sunny Goyal316490e2015-06-02 09:38:28 -070076 @Thunk final Handler mWorkerHandler;
Adrian Roos65d60e22014-04-15 21:07:49 +020077
Sunny Goyal383c5072015-06-12 21:18:53 -070078 public WidgetPreviewLoader(Context context, IconCache iconCache) {
Chris Wrenfd13c712013-09-27 15:45:19 -040079 mContext = context;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070080 mIconCache = iconCache;
Hyunyoung Song3e840f42016-03-01 11:57:44 -080081 mWidgetManager = AppWidgetManagerCompat.getInstance(context);
Sunny Goyal5b0e6692015-03-19 14:31:19 -070082 mUserManager = UserManagerCompat.getInstance(context);
83 mDb = new CacheDb(context);
Winson Chung05304db2015-05-18 16:53:20 -070084 mWorkerHandler = new Handler(LauncherModel.getWorkerLooper());
Michael Jurka3f4e0702013-02-05 11:21:28 +010085 }
Sunny Goyalffe83f12014-08-14 17:39:34 -070086
Sunny Goyal5b0e6692015-03-19 14:31:19 -070087 /**
88 * Generates the widget preview on {@link AsyncTask#THREAD_POOL_EXECUTOR}. Must be
89 * called on UI thread
90 *
Sunny Goyal5b0e6692015-03-19 14:31:19 -070091 * @return a request id which can be used to cancel the request.
92 */
Sunny Goyalc65a0082017-03-08 14:49:55 -080093 public CancellationSignal getPreview(WidgetItem item, int previewWidth,
Tony Wickham26b17462017-03-20 17:12:24 -070094 int previewHeight, WidgetCell caller, boolean animate) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -070095 String size = previewWidth + "x" + previewHeight;
Sunny Goyal4ddc4012016-03-10 12:02:29 -080096 WidgetCacheKey key = new WidgetCacheKey(item.componentName, item.user, size);
Michael Jurka3f4e0702013-02-05 11:21:28 +010097
Tony Wickham26b17462017-03-20 17:12:24 -070098 PreviewLoadTask task = new PreviewLoadTask(key, item, previewWidth, previewHeight, caller,
99 animate);
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 {
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800112 private static final int DB_VERSION = 6;
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.
173 */
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800174 public void removeObsoletePreviews(ArrayList<? extends ComponentKey> list) {
Sunny Goyal6388b2c2016-04-15 18:03:27 -0700175 Preconditions.assertWorkerThread();
Hyunyoung Song8821ca92015-05-04 16:28:20 -0700176
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700177 LongSparseArray<HashSet<String>> validPackages = new LongSparseArray<>();
178
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800179 for (ComponentKey key : list) {
180 final long userId = mUserManager.getSerialNumberForUser(key.user);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700181 HashSet<String> packages = validPackages.get(userId);
182 if (packages == null) {
183 packages = new HashSet<>();
184 validPackages.put(userId, packages);
185 }
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800186 packages.add(key.componentName.getPackageName());
Michael Jurka05713af2013-01-23 12:39:24 +0100187 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700188
189 LongSparseArray<HashSet<String>> packagesToDelete = new LongSparseArray<>();
190 Cursor c = null;
191 try {
Sunny Goyal6f709362015-12-17 17:09:36 -0800192 c = mDb.query(
193 new String[]{CacheDb.COLUMN_USER, CacheDb.COLUMN_PACKAGE,
194 CacheDb.COLUMN_LAST_UPDATED, CacheDb.COLUMN_VERSION},
195 null, null);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700196 while (c.moveToNext()) {
197 long userId = c.getLong(0);
198 String pkg = c.getString(1);
199 long lastUpdated = c.getLong(2);
200 long version = c.getLong(3);
201
202 HashSet<String> packages = validPackages.get(userId);
203 if (packages != null && packages.contains(pkg)) {
204 long[] versions = getPackageVersion(pkg);
205 if (versions[0] == version && versions[1] == lastUpdated) {
206 // Every thing checks out
207 continue;
208 }
209 }
210
211 // We need to delete this package.
212 packages = packagesToDelete.get(userId);
213 if (packages == null) {
214 packages = new HashSet<>();
215 packagesToDelete.put(userId, packages);
216 }
217 packages.add(pkg);
218 }
219
220 for (int i = 0; i < packagesToDelete.size(); i++) {
221 long userId = packagesToDelete.keyAt(i);
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800222 UserHandle user = mUserManager.getUserForSerialNumber(userId);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700223 for (String pkg : packagesToDelete.valueAt(i)) {
224 removePackage(pkg, user, userId);
225 }
226 }
227 } catch (SQLException e) {
Sunny Goyal6f709362015-12-17 17:09:36 -0800228 Log.e(TAG, "Error updating widget previews", e);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700229 } finally {
230 if (c != null) {
231 c.close();
232 }
233 }
234 }
235
Winson Chung05304db2015-05-18 16:53:20 -0700236 /**
237 * Reads the preview bitmap from the DB or null if the preview is not in the DB.
238 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700239 @Thunk Bitmap readFromDb(WidgetCacheKey key, Bitmap recycle, PreviewLoadTask loadTask) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700240 Cursor cursor = null;
241 try {
Sunny Goyal6f709362015-12-17 17:09:36 -0800242 cursor = mDb.query(
243 new String[]{CacheDb.COLUMN_PREVIEW_BITMAP},
244 CacheDb.COLUMN_COMPONENT + " = ? AND " + CacheDb.COLUMN_USER + " = ? AND "
245 + CacheDb.COLUMN_SIZE + " = ?",
246 new String[]{
Sunny Goyal3ef86912016-10-27 11:40:06 -0700247 key.componentName.flattenToShortString(),
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700248 Long.toString(mUserManager.getSerialNumberForUser(key.user)),
249 key.size
Sunny Goyal6f709362015-12-17 17:09:36 -0800250 });
Winson Chung05304db2015-05-18 16:53:20 -0700251 // If cancelled, skip getting the blob and decoding it into a bitmap
252 if (loadTask.isCancelled()) {
253 return null;
254 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700255 if (cursor.moveToNext()) {
256 byte[] blob = cursor.getBlob(0);
257 BitmapFactory.Options opts = new BitmapFactory.Options();
258 opts.inBitmap = recycle;
Michael Jurka6e27f642013-12-10 13:40:30 +0100259 try {
Winson Chung05304db2015-05-18 16:53:20 -0700260 if (!loadTask.isCancelled()) {
261 return BitmapFactory.decodeByteArray(blob, 0, blob.length, opts);
262 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700263 } catch (Exception e) {
264 return null;
Michael Jurka6e27f642013-12-10 13:40:30 +0100265 }
Michael Jurka05713af2013-01-23 12:39:24 +0100266 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700267 } catch (SQLException e) {
268 Log.w(TAG, "Error loading preview from DB", e);
269 } finally {
270 if (cursor != null) {
271 cursor.close();
272 }
273 }
274 return null;
Michael Jurka05713af2013-01-23 12:39:24 +0100275 }
276
Sunny Goyal27835952017-01-13 12:15:53 -0800277 private Bitmap generatePreview(BaseActivity launcher, WidgetItem item, Bitmap recycle,
Adam Cohen2e6da152015-05-06 11:42:25 -0700278 int previewWidth, int previewHeight) {
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800279 if (item.widgetInfo != null) {
280 return generateWidgetPreview(launcher, item.widgetInfo,
Adam Cohen2e6da152015-05-06 11:42:25 -0700281 previewWidth, recycle, null);
Michael Jurka05713af2013-01-23 12:39:24 +0100282 } else {
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800283 return generateShortcutPreview(launcher, item.activityInfo,
284 previewWidth, previewHeight, recycle);
Michael Jurka05713af2013-01-23 12:39:24 +0100285 }
286 }
287
Hyunyoung Song3e840f42016-03-01 11:57:44 -0800288 /**
289 * Generates the widget preview from either the {@link AppWidgetManagerCompat} or cache
290 * and add badge at the bottom right corner.
291 *
292 * @param launcher
293 * @param info information about the widget
294 * @param maxPreviewWidth width of the preview on either workspace or tray
295 * @param preview bitmap that can be recycled
296 * @param preScaledWidthOut return the width of the returned bitmap
297 * @return
298 */
Sunny Goyal27835952017-01-13 12:15:53 -0800299 public Bitmap generateWidgetPreview(BaseActivity launcher, LauncherAppWidgetProviderInfo info,
Sunny Goyal4cad7532015-03-18 15:56:30 -0700300 int maxPreviewWidth, Bitmap preview, int[] preScaledWidthOut) {
Michael Jurka05713af2013-01-23 12:39:24 +0100301 // Load the preview image if possible
Michael Jurka05713af2013-01-23 12:39:24 +0100302 if (maxPreviewWidth < 0) maxPreviewWidth = Integer.MAX_VALUE;
Michael Jurka05713af2013-01-23 12:39:24 +0100303
304 Drawable drawable = null;
Sunny Goyalffe83f12014-08-14 17:39:34 -0700305 if (info.previewImage != 0) {
Sunny Goyal2570d102016-10-27 11:38:45 -0700306 try {
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800307 drawable = info.loadPreviewImage(mContext, 0);
Sunny Goyal2570d102016-10-27 11:38:45 -0700308 } catch (OutOfMemoryError e) {
309 Log.w(TAG, "Error loading widget preview for: " + info.provider, e);
310 // During OutOfMemoryError, the previous heap stack is not affected. Catching
311 // an OOM error here should be safe & not affect other parts of launcher.
312 drawable = null;
313 }
Adrian Roosfa9ffc22014-05-12 15:59:59 +0200314 if (drawable != null) {
315 drawable = mutateOnMainThread(drawable);
316 } else {
Michael Jurka05713af2013-01-23 12:39:24 +0100317 Log.w(TAG, "Can't load widget preview drawable 0x" +
Sunny Goyalffe83f12014-08-14 17:39:34 -0700318 Integer.toHexString(info.previewImage) + " for provider: " + info.provider);
Michael Jurka05713af2013-01-23 12:39:24 +0100319 }
320 }
321
Sunny Goyal4cad7532015-03-18 15:56:30 -0700322 final boolean widgetPreviewExists = (drawable != null);
Sunny Goyal233ee962015-08-03 13:05:01 -0700323 final int spanX = info.spanX;
324 final int spanY = info.spanY;
Sunny Goyal4cad7532015-03-18 15:56:30 -0700325
Michael Jurka05713af2013-01-23 12:39:24 +0100326 int previewWidth;
327 int previewHeight;
Hyunyoung Song3e840f42016-03-01 11:57:44 -0800328
Michael Jurka05713af2013-01-23 12:39:24 +0100329 if (widgetPreviewExists) {
330 previewWidth = drawable.getIntrinsicWidth();
331 previewHeight = drawable.getIntrinsicHeight();
332 } else {
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800333 DeviceProfile dp = launcher.getDeviceProfile();
334 int tileSize = Math.min(dp.cellWidthPx, dp.cellHeightPx);
335 previewWidth = tileSize * spanX;
336 previewHeight = tileSize * spanY;
Michael Jurka05713af2013-01-23 12:39:24 +0100337 }
338
339 // Scale to fit width only - let the widget preview be clipped in the
340 // vertical dimension
341 float scale = 1f;
342 if (preScaledWidthOut != null) {
343 preScaledWidthOut[0] = previewWidth;
344 }
345 if (previewWidth > maxPreviewWidth) {
Sunny Goyala2441e82017-01-14 13:40:15 -0800346 scale = maxPreviewWidth / (float) (previewWidth);
Michael Jurka05713af2013-01-23 12:39:24 +0100347 }
348 if (scale != 1f) {
349 previewWidth = (int) (scale * previewWidth);
350 previewHeight = (int) (scale * previewHeight);
351 }
352
353 // 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 -0700354 final Canvas c = new Canvas();
Michael Jurka05713af2013-01-23 12:39:24 +0100355 if (preview == null) {
356 preview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700357 c.setBitmap(preview);
358 } else {
Sunny Goyala2441e82017-01-14 13:40:15 -0800359 // We use the preview bitmap height to determine where the badge will be drawn in the
360 // UI. If its larger than what we need, resize the preview bitmap so that there are
361 // no transparent pixels between the preview and the badge.
362 if (preview.getHeight() > previewHeight) {
363 preview.reconfigure(preview.getWidth(), previewHeight, preview.getConfig());
364 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700365 // Reusing bitmap. Clear it.
366 c.setBitmap(preview);
367 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100368 }
369
370 // Draw the scaled preview into the final bitmap
Hyunyoung Songb9f932e2015-07-30 15:04:59 -0700371 int x = (preview.getWidth() - previewWidth) / 2;
Michael Jurka05713af2013-01-23 12:39:24 +0100372 if (widgetPreviewExists) {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700373 drawable.setBounds(x, 0, x + previewWidth, previewHeight);
374 drawable.draw(c);
Michael Jurka05713af2013-01-23 12:39:24 +0100375 } else {
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800376 final Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800377 RectF boxRect = drawBoxWithShadow(c, p, previewWidth, previewHeight);
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800378
379 // Draw horizontal and vertical lines to represent individual columns.
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800380 p.setStyle(Paint.Style.STROKE);
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800381 p.setStrokeWidth(mContext.getResources()
382 .getDimension(R.dimen.widget_preview_cell_divider_width));
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800383 p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
384
385 float t = boxRect.left;
386 float tileSize = boxRect.width() / spanX;
387 for (int i = 1; i < spanX; i++) {
388 t += tileSize;
389 c.drawLine(t, 0, t, previewHeight, p);
Michael Jurka05713af2013-01-23 12:39:24 +0100390 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700391
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800392 t = boxRect.top;
393 tileSize = boxRect.height() / spanY;
394 for (int i = 1; i < spanY; i++) {
395 t += tileSize;
396 c.drawLine(0, t, previewWidth, t, p);
397 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700398
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800399 // Draw icon in the center.
Sunny Goyal4cad7532015-03-18 15:56:30 -0700400 try {
Sunny Goyala52ecb02016-12-16 15:04:51 -0800401 Drawable icon = info.getIcon(launcher, mIconCache);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700402 if (icon != null) {
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800403 int appIconSize = launcher.getDeviceProfile().iconSizePx;
404 int iconSize = (int) Math.min(appIconSize * scale,
405 Math.min(boxRect.width(), boxRect.height()));
406
Sunny Goyal1ba7e362015-10-26 10:42:12 -0700407 icon = mutateOnMainThread(icon);
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800408 int hoffset = (previewWidth - iconSize) / 2;
409 int yoffset = (previewHeight - iconSize) / 2;
410 icon.setBounds(hoffset, yoffset, hoffset + iconSize, yoffset + iconSize);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700411 icon.draw(c);
412 }
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800413 } catch (Resources.NotFoundException e) { }
Michael Jurka05713af2013-01-23 12:39:24 +0100414 c.setBitmap(null);
415 }
Sunny Goyala2441e82017-01-14 13:40:15 -0800416 return preview;
Michael Jurka05713af2013-01-23 12:39:24 +0100417 }
418
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800419 private RectF drawBoxWithShadow(Canvas c, Paint p, int width, int height) {
420 Resources res = mContext.getResources();
421 float shadowBlur = res.getDimension(R.dimen.widget_preview_shadow_blur);
422 float keyShadowDistance = res.getDimension(R.dimen.widget_preview_key_shadow_distance);
423 float corner = res.getDimension(R.dimen.widget_preview_corner_radius);
424
425 RectF bounds = new RectF(shadowBlur, shadowBlur,
426 width - shadowBlur, height - shadowBlur - keyShadowDistance);
427 p.setColor(Color.WHITE);
428
429 // Key shadow
430 p.setShadowLayer(shadowBlur, 0, keyShadowDistance,
431 ShadowGenerator.KEY_SHADOW_ALPHA << 24);
432 c.drawRoundRect(bounds, corner, corner, p);
433
434 // Ambient shadow
435 p.setShadowLayer(shadowBlur, 0, 0,
436 ColorUtils.setAlphaComponent(Color.BLACK, ShadowGenerator.AMBIENT_SHADOW_ALPHA));
437 c.drawRoundRect(bounds, corner, corner, p);
438
439 p.clearShadowLayer();
440 return bounds;
441 }
442
Sunny Goyal782f0c92017-01-19 10:27:54 -0800443 private Bitmap generateShortcutPreview(BaseActivity launcher, ShortcutConfigActivityInfo info,
444 int maxWidth, int maxHeight, Bitmap preview) {
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800445 int iconSize = launcher.getDeviceProfile().iconSizePx;
446 int padding = launcher.getResources()
447 .getDimensionPixelSize(R.dimen.widget_preview_shortcut_padding);
448
449 int size = iconSize + 2 * padding;
450 if (maxHeight < size || maxWidth < size) {
451 throw new RuntimeException("Max size is too small for preview");
452 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700453 final Canvas c = new Canvas();
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800454 if (preview == null || preview.getWidth() < size || preview.getHeight() < size) {
455 preview = Bitmap.createBitmap(size, size, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700456 c.setBitmap(preview);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700457 } else {
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800458 if (preview.getWidth() > size || preview.getHeight() > size) {
459 preview.reconfigure(size, size, preview.getConfig());
460 }
461
Sunny Goyal4cad7532015-03-18 15:56:30 -0700462 // Reusing bitmap. Clear it.
463 c.setBitmap(preview);
464 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100465 }
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800466 Paint p = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
467 RectF boxRect = drawBoxWithShadow(c, p, size, size);
Michael Jurka05713af2013-01-23 12:39:24 +0100468
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800469 Bitmap icon = LauncherIcons.createScaledBitmapWithoutShadow(
470 mutateOnMainThread(info.getFullResIcon(mIconCache)), mContext);
471 Rect src = new Rect(0, 0, icon.getWidth(), icon.getHeight());
Sunny Goyal4cad7532015-03-18 15:56:30 -0700472
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800473 boxRect.set(0, 0, iconSize, iconSize);
474 boxRect.offset(padding, padding);
475 c.drawBitmap(icon, src, boxRect, p);
Michael Jurka05713af2013-01-23 12:39:24 +0100476 c.setBitmap(null);
Michael Jurka05713af2013-01-23 12:39:24 +0100477 return preview;
478 }
479
Adrian Roos65d60e22014-04-15 21:07:49 +0200480 private Drawable mutateOnMainThread(final Drawable drawable) {
481 try {
482 return mMainThreadExecutor.submit(new Callable<Drawable>() {
483 @Override
484 public Drawable call() throws Exception {
485 return drawable.mutate();
486 }
487 }).get();
488 } catch (InterruptedException e) {
489 Thread.currentThread().interrupt();
490 throw new RuntimeException(e);
491 } catch (ExecutionException e) {
492 throw new RuntimeException(e);
493 }
494 }
Adrian Roos1f375ab2014-04-28 18:26:38 +0200495
Adrian Roos1f375ab2014-04-28 18:26:38 +0200496 /**
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700497 * @return an array of containing versionCode and lastUpdatedTime for the package.
Adrian Roos1f375ab2014-04-28 18:26:38 +0200498 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700499 @Thunk long[] getPackageVersion(String packageName) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700500 synchronized (mPackageVersions) {
501 long[] versions = mPackageVersions.get(packageName);
502 if (versions == null) {
503 versions = new long[2];
Adrian Roos1f375ab2014-04-28 18:26:38 +0200504 try {
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800505 PackageInfo info = mContext.getPackageManager().getPackageInfo(packageName,
506 PackageManager.GET_UNINSTALLED_PACKAGES);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700507 versions[0] = info.versionCode;
508 versions[1] = info.lastUpdateTime;
509 } catch (NameNotFoundException e) {
510 Log.e(TAG, "PackageInfo not found", e);
511 }
512 mPackageVersions.put(packageName, versions);
513 }
514 return versions;
515 }
516 }
517
Sunny Goyalc65a0082017-03-08 14:49:55 -0800518 public class PreviewLoadTask extends AsyncTask<Void, Void, Bitmap>
519 implements CancellationSignal.OnCancelListener {
Sunny Goyal316490e2015-06-02 09:38:28 -0700520 @Thunk final WidgetCacheKey mKey;
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800521 private final WidgetItem mInfo;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700522 private final int mPreviewHeight;
523 private final int mPreviewWidth;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700524 private final WidgetCell mCaller;
Tony Wickham26b17462017-03-20 17:12:24 -0700525 private final boolean mAnimatePreviewIn;
Sunny Goyala2441e82017-01-14 13:40:15 -0800526 private final BaseActivity mActivity;
Sunny Goyal316490e2015-06-02 09:38:28 -0700527 @Thunk long[] mVersions;
528 @Thunk Bitmap mBitmapToRecycle;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700529
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800530 PreviewLoadTask(WidgetCacheKey key, WidgetItem info, int previewWidth,
Tony Wickham26b17462017-03-20 17:12:24 -0700531 int previewHeight, WidgetCell caller, boolean animate) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700532 mKey = key;
533 mInfo = info;
534 mPreviewHeight = previewHeight;
535 mPreviewWidth = previewWidth;
536 mCaller = caller;
Tony Wickham26b17462017-03-20 17:12:24 -0700537 mAnimatePreviewIn = animate;
Sunny Goyala2441e82017-01-14 13:40:15 -0800538 mActivity = BaseActivity.fromContext(mCaller.getContext());
Hyunyoung Song3f471442015-04-08 19:01:34 -0700539 if (DEBUG) {
540 Log.d(TAG, String.format("%s, %s, %d, %d",
541 mKey, mInfo, mPreviewHeight, mPreviewWidth));
542 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700543 }
544
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700545 @Override
546 protected Bitmap doInBackground(Void... params) {
547 Bitmap unusedBitmap = null;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700548
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700549 // If already cancelled before this gets to run in the background, then return early
550 if (isCancelled()) {
551 return null;
552 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700553 synchronized (mUnusedBitmaps) {
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700554 // Check if we can re-use a bitmap
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700555 for (Bitmap candidate : mUnusedBitmaps) {
556 if (candidate != null && candidate.isMutable() &&
557 candidate.getWidth() == mPreviewWidth &&
558 candidate.getHeight() == mPreviewHeight) {
559 unusedBitmap = candidate;
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700560 mUnusedBitmaps.remove(unusedBitmap);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700561 break;
562 }
563 }
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700564 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700565
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700566 // creating a bitmap is expensive. Do not do this inside synchronized block.
567 if (unusedBitmap == null) {
568 unusedBitmap = Bitmap.createBitmap(mPreviewWidth, mPreviewHeight, Config.ARGB_8888);
Adrian Roos1f375ab2014-04-28 18:26:38 +0200569 }
Winson Chung05304db2015-05-18 16:53:20 -0700570 // If cancelled now, don't bother reading the preview from the DB
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700571 if (isCancelled()) {
Winson Chung05304db2015-05-18 16:53:20 -0700572 return unusedBitmap;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700573 }
Winson Chung05304db2015-05-18 16:53:20 -0700574 Bitmap preview = readFromDb(mKey, unusedBitmap, this);
575 // Only consider generating the preview if we have not cancelled the task already
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700576 if (!isCancelled() && preview == null) {
577 // Fetch the version info before we generate the preview, so that, in-case the
578 // app was updated while we are generating the preview, we use the old version info,
579 // which would gets re-written next time.
Sunny Goyal65513ba2017-01-20 11:54:25 -0800580 boolean persistable = mInfo.activityInfo == null
581 || mInfo.activityInfo.isPersistable();
582 mVersions = persistable ? getPackageVersion(mKey.componentName.getPackageName())
583 : null;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700584
585 // it's not in the db... we need to generate it
Sunny Goyala2441e82017-01-14 13:40:15 -0800586 preview = generatePreview(mActivity, mInfo, unusedBitmap, mPreviewWidth, mPreviewHeight);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700587 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700588 return preview;
589 }
590
591 @Override
Winson Chung05304db2015-05-18 16:53:20 -0700592 protected void onPostExecute(final Bitmap preview) {
Tony Wickham26b17462017-03-20 17:12:24 -0700593 mCaller.applyPreview(preview, mAnimatePreviewIn);
Winson Chung05304db2015-05-18 16:53:20 -0700594
595 // Write the generated preview to the DB in the worker thread
596 if (mVersions != null) {
597 mWorkerHandler.post(new Runnable() {
598 @Override
599 public void run() {
600 if (!isCancelled()) {
601 // If we are still using this preview, then write it to the DB and then
602 // let the normal clear mechanism recycle the bitmap
603 writeToDb(mKey, mVersions, preview);
604 mBitmapToRecycle = preview;
605 } else {
606 // If we've already cancelled, then skip writing the bitmap to the DB
607 // and manually add the bitmap back to the recycled set
608 synchronized (mUnusedBitmaps) {
609 mUnusedBitmaps.add(preview);
610 }
611 }
612 }
613 });
614 } else {
615 // If we don't need to write to disk, then ensure the preview gets recycled by
616 // the normal clear mechanism
617 mBitmapToRecycle = preview;
618 }
619 }
620
621 @Override
Hyunyoung Songe98f4a42015-06-16 10:45:24 -0700622 protected void onCancelled(final Bitmap preview) {
Winson Chung05304db2015-05-18 16:53:20 -0700623 // If we've cancelled while the task is running, then can return the bitmap to the
624 // recycled set immediately. Otherwise, it will be recycled after the preview is written
625 // to disk.
626 if (preview != null) {
Hyunyoung Songe98f4a42015-06-16 10:45:24 -0700627 mWorkerHandler.post(new Runnable() {
628 @Override
629 public void run() {
630 synchronized (mUnusedBitmaps) {
631 mUnusedBitmaps.add(preview);
632 }
633 }
634 });
Winson Chung05304db2015-05-18 16:53:20 -0700635 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700636 }
Sunny Goyalc65a0082017-03-08 14:49:55 -0800637
638 @Override
639 public void onCancel() {
640 cancel(true);
641
642 // This only handles the case where the PreviewLoadTask is cancelled after the task has
643 // successfully completed (including having written to disk when necessary). In the
644 // other cases where it is cancelled while the task is running, it will be cleaned up
645 // in the tasks's onCancelled() call, and if cancelled while the task is writing to
646 // disk, it will be cancelled in the task's onPostExecute() call.
647 if (mBitmapToRecycle != null) {
648 mWorkerHandler.post(new Runnable() {
649 @Override
650 public void run() {
651 synchronized (mUnusedBitmaps) {
652 mUnusedBitmaps.add(mBitmapToRecycle);
653 }
654 mBitmapToRecycle = null;
655 }
656 });
657 }
658 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700659 }
660
661 private static final class WidgetCacheKey extends ComponentKey {
662
Sunny Goyal316490e2015-06-02 09:38:28 -0700663 @Thunk final String size;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700664
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800665 public WidgetCacheKey(ComponentName componentName, UserHandle user, String size) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700666 super(componentName, user);
667 this.size = size;
668 }
669
670 @Override
671 public int hashCode() {
672 return super.hashCode() ^ size.hashCode();
673 }
674
675 @Override
676 public boolean equals(Object o) {
677 return super.equals(o) && ((WidgetCacheKey) o).size.equals(size);
Adrian Roos1f375ab2014-04-28 18:26:38 +0200678 }
679 }
Michael Jurka05713af2013-01-23 12:39:24 +0100680}