blob: 689cc9b3eb5b48389b189a875d75ed56932e585c [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;
Winson Chung05304db2015-05-18 16:53:20 -070025import android.os.Handler;
Sunny Goyal7c74e4a2016-12-15 15:53:17 -080026import android.os.UserHandle;
Sunny Goyal7d87cb12017-02-13 10:44:43 -080027import android.support.v4.graphics.ColorUtils;
Michael Jurka05713af2013-01-23 12:39:24 +010028import android.util.Log;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070029import android.util.LongSparseArray;
Sunny Goyal383c5072015-06-12 21:18:53 -070030
Sunny Goyalffe83f12014-08-14 17:39:34 -070031import com.android.launcher3.compat.AppWidgetManagerCompat;
Sunny Goyal782f0c92017-01-19 10:27:54 -080032import com.android.launcher3.compat.ShortcutConfigActivityInfo;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070033import com.android.launcher3.compat.UserManagerCompat;
Sunny Goyal7d87cb12017-02-13 10:44:43 -080034import com.android.launcher3.graphics.LauncherIcons;
Sunny Goyal92bbfa12017-02-07 15:06:32 -080035import com.android.launcher3.graphics.ShadowGenerator;
Sunny Goyal4ddc4012016-03-10 12:02:29 -080036import com.android.launcher3.model.WidgetItem;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070037import com.android.launcher3.util.ComponentKey;
Sunny Goyal6388b2c2016-04-15 18:03:27 -070038import com.android.launcher3.util.Preconditions;
Sunny Goyal6f709362015-12-17 17:09:36 -080039import com.android.launcher3.util.SQLiteCacheHelper;
Adam Cohen091440a2015-03-18 14:16:05 -070040import com.android.launcher3.util.Thunk;
Hyunyoung Song3f471442015-04-08 19:01:34 -070041import com.android.launcher3.widget.WidgetCell;
Hyunyoung Song8821ca92015-05-04 16:28:20 -070042
43import java.util.ArrayList;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070044import java.util.Collections;
Michael Jurka05713af2013-01-23 12:39:24 +010045import java.util.HashMap;
46import java.util.HashSet;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070047import java.util.Set;
48import java.util.WeakHashMap;
Adrian Roos65d60e22014-04-15 21:07:49 +020049import java.util.concurrent.Callable;
50import java.util.concurrent.ExecutionException;
Michael Jurka05713af2013-01-23 12:39:24 +010051
Sunny Goyalffe83f12014-08-14 17:39:34 -070052public class WidgetPreviewLoader {
Michael Jurka05713af2013-01-23 12:39:24 +010053
Sunny Goyalffe83f12014-08-14 17:39:34 -070054 private static final String TAG = "WidgetPreviewLoader";
Hyunyoung Song3f471442015-04-08 19:01:34 -070055 private static final boolean DEBUG = false;
Sunny Goyalffe83f12014-08-14 17:39:34 -070056
Sunny Goyal5b0e6692015-03-19 14:31:19 -070057 private final HashMap<String, long[]> mPackageVersions = new HashMap<>();
Hyunyoung Song559d90d2015-04-28 15:06:45 -070058
59 /**
60 * Weak reference objects, do not prevent their referents from being made finalizable,
61 * finalized, and then reclaimed.
Hyunyoung Songe98f4a42015-06-16 10:45:24 -070062 * Note: synchronized block used for this variable is expensive and the block should always
63 * be posted to a background thread.
Hyunyoung Song559d90d2015-04-28 15:06:45 -070064 */
Sunny Goyalb4cbea42015-06-16 15:10:36 -070065 @Thunk final Set<Bitmap> mUnusedBitmaps =
Hyunyoung Song559d90d2015-04-28 15:06:45 -070066 Collections.newSetFromMap(new WeakHashMap<Bitmap, Boolean>());
Sunny Goyal4cad7532015-03-18 15:56:30 -070067
68 private final Context mContext;
Sunny Goyalffe83f12014-08-14 17:39:34 -070069 private final IconCache mIconCache;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070070 private final UserManagerCompat mUserManager;
Hyunyoung Song3e840f42016-03-01 11:57:44 -080071 private final AppWidgetManagerCompat mWidgetManager;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070072 private final CacheDb mDb;
Michael Jurka05713af2013-01-23 12:39:24 +010073
Adrian Roos65d60e22014-04-15 21:07:49 +020074 private final MainThreadExecutor mMainThreadExecutor = new MainThreadExecutor();
Sunny Goyal316490e2015-06-02 09:38:28 -070075 @Thunk final Handler mWorkerHandler;
Adrian Roos65d60e22014-04-15 21:07:49 +020076
Sunny Goyal383c5072015-06-12 21:18:53 -070077 public WidgetPreviewLoader(Context context, IconCache iconCache) {
Chris Wrenfd13c712013-09-27 15:45:19 -040078 mContext = context;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070079 mIconCache = iconCache;
Hyunyoung Song3e840f42016-03-01 11:57:44 -080080 mWidgetManager = AppWidgetManagerCompat.getInstance(context);
Sunny Goyal5b0e6692015-03-19 14:31:19 -070081 mUserManager = UserManagerCompat.getInstance(context);
82 mDb = new CacheDb(context);
Winson Chung05304db2015-05-18 16:53:20 -070083 mWorkerHandler = new Handler(LauncherModel.getWorkerLooper());
Michael Jurka3f4e0702013-02-05 11:21:28 +010084 }
Sunny Goyalffe83f12014-08-14 17:39:34 -070085
Sunny Goyal5b0e6692015-03-19 14:31:19 -070086 /**
87 * Generates the widget preview on {@link AsyncTask#THREAD_POOL_EXECUTOR}. Must be
88 * called on UI thread
89 *
Sunny Goyal5b0e6692015-03-19 14:31:19 -070090 * @return a request id which can be used to cancel the request.
91 */
Sunny Goyal4ddc4012016-03-10 12:02:29 -080092 public PreviewLoadRequest getPreview(WidgetItem item, int previewWidth,
Adam Cohen2e6da152015-05-06 11:42:25 -070093 int previewHeight, WidgetCell caller) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -070094 String size = previewWidth + "x" + previewHeight;
Sunny Goyal4ddc4012016-03-10 12:02:29 -080095 WidgetCacheKey key = new WidgetCacheKey(item.componentName, item.user, size);
Michael Jurka3f4e0702013-02-05 11:21:28 +010096
Sunny Goyal4ddc4012016-03-10 12:02:29 -080097 PreviewLoadTask task = new PreviewLoadTask(key, item, previewWidth, previewHeight, caller);
Sunny Goyal8ac727b2015-09-23 15:38:09 -070098 task.executeOnExecutor(Utilities.THREAD_POOL_EXECUTOR);
Hyunyoung Song559d90d2015-04-28 15:06:45 -070099 return new PreviewLoadRequest(task);
Michael Jurka05713af2013-01-23 12:39:24 +0100100 }
101
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700102 /**
103 * The DB holds the generated previews for various components. Previews can also have different
104 * sizes (landscape vs portrait).
105 */
Sunny Goyal6f709362015-12-17 17:09:36 -0800106 private static class CacheDb extends SQLiteCacheHelper {
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800107 private static final int DB_VERSION = 6;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700108
109 private static final String TABLE_NAME = "shortcut_and_widget_previews";
110 private static final String COLUMN_COMPONENT = "componentName";
111 private static final String COLUMN_USER = "profileId";
112 private static final String COLUMN_SIZE = "size";
113 private static final String COLUMN_PACKAGE = "packageName";
114 private static final String COLUMN_LAST_UPDATED = "lastUpdated";
115 private static final String COLUMN_VERSION = "version";
116 private static final String COLUMN_PREVIEW_BITMAP = "preview_bitmap";
Michael Jurka05713af2013-01-23 12:39:24 +0100117
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100118 public CacheDb(Context context) {
Sunny Goyal6f709362015-12-17 17:09:36 -0800119 super(context, LauncherFiles.WIDGET_PREVIEWS_DB, DB_VERSION, TABLE_NAME);
Michael Jurka05713af2013-01-23 12:39:24 +0100120 }
121
122 @Override
Sunny Goyal6f709362015-12-17 17:09:36 -0800123 public void onCreateTable(SQLiteDatabase database) {
Michael Jurka32b7a092013-02-07 20:06:49 +0100124 database.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" +
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700125 COLUMN_COMPONENT + " TEXT NOT NULL, " +
126 COLUMN_USER + " INTEGER NOT NULL, " +
Michael Jurka05713af2013-01-23 12:39:24 +0100127 COLUMN_SIZE + " TEXT NOT NULL, " +
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700128 COLUMN_PACKAGE + " TEXT NOT NULL, " +
129 COLUMN_LAST_UPDATED + " INTEGER NOT NULL DEFAULT 0, " +
130 COLUMN_VERSION + " INTEGER NOT NULL DEFAULT 0, " +
131 COLUMN_PREVIEW_BITMAP + " BLOB, " +
132 "PRIMARY KEY (" + COLUMN_COMPONENT + ", " + COLUMN_USER + ", " + COLUMN_SIZE + ") " +
Michael Jurka32b7a092013-02-07 20:06:49 +0100133 ");");
Michael Jurka05713af2013-01-23 12:39:24 +0100134 }
Michael Jurka05713af2013-01-23 12:39:24 +0100135 }
136
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700137 @Thunk void writeToDb(WidgetCacheKey key, long[] versions, Bitmap preview) {
Michael Jurka05713af2013-01-23 12:39:24 +0100138 ContentValues values = new ContentValues();
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700139 values.put(CacheDb.COLUMN_COMPONENT, key.componentName.flattenToShortString());
140 values.put(CacheDb.COLUMN_USER, mUserManager.getSerialNumberForUser(key.user));
141 values.put(CacheDb.COLUMN_SIZE, key.size);
142 values.put(CacheDb.COLUMN_PACKAGE, key.componentName.getPackageName());
143 values.put(CacheDb.COLUMN_VERSION, versions[0]);
144 values.put(CacheDb.COLUMN_LAST_UPDATED, versions[1]);
145 values.put(CacheDb.COLUMN_PREVIEW_BITMAP, Utilities.flattenBitmap(preview));
Sunny Goyal6f709362015-12-17 17:09:36 -0800146 mDb.insertOrReplace(values);
Michael Jurka05713af2013-01-23 12:39:24 +0100147 }
148
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800149 public void removePackage(String packageName, UserHandle user) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700150 removePackage(packageName, user, mUserManager.getSerialNumberForUser(user));
151 }
152
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800153 private void removePackage(String packageName, UserHandle user, long userSerial) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700154 synchronized(mPackageVersions) {
155 mPackageVersions.remove(packageName);
156 }
157
Sunny Goyal6f709362015-12-17 17:09:36 -0800158 mDb.delete(
159 CacheDb.COLUMN_PACKAGE + " = ? AND " + CacheDb.COLUMN_USER + " = ?",
160 new String[]{packageName, Long.toString(userSerial)});
Michael Jurka8ff02ca2013-11-01 14:19:27 +0100161 }
162
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700163 /**
164 * Updates the persistent DB:
165 * 1. Any preview generated for an old package version is removed
166 * 2. Any preview for an absent package is removed
167 * This ensures that we remove entries for packages which changed while the launcher was dead.
168 */
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800169 public void removeObsoletePreviews(ArrayList<? extends ComponentKey> list) {
Sunny Goyal6388b2c2016-04-15 18:03:27 -0700170 Preconditions.assertWorkerThread();
Hyunyoung Song8821ca92015-05-04 16:28:20 -0700171
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700172 LongSparseArray<HashSet<String>> validPackages = new LongSparseArray<>();
173
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800174 for (ComponentKey key : list) {
175 final long userId = mUserManager.getSerialNumberForUser(key.user);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700176 HashSet<String> packages = validPackages.get(userId);
177 if (packages == null) {
178 packages = new HashSet<>();
179 validPackages.put(userId, packages);
180 }
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800181 packages.add(key.componentName.getPackageName());
Michael Jurka05713af2013-01-23 12:39:24 +0100182 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700183
184 LongSparseArray<HashSet<String>> packagesToDelete = new LongSparseArray<>();
185 Cursor c = null;
186 try {
Sunny Goyal6f709362015-12-17 17:09:36 -0800187 c = mDb.query(
188 new String[]{CacheDb.COLUMN_USER, CacheDb.COLUMN_PACKAGE,
189 CacheDb.COLUMN_LAST_UPDATED, CacheDb.COLUMN_VERSION},
190 null, null);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700191 while (c.moveToNext()) {
192 long userId = c.getLong(0);
193 String pkg = c.getString(1);
194 long lastUpdated = c.getLong(2);
195 long version = c.getLong(3);
196
197 HashSet<String> packages = validPackages.get(userId);
198 if (packages != null && packages.contains(pkg)) {
199 long[] versions = getPackageVersion(pkg);
200 if (versions[0] == version && versions[1] == lastUpdated) {
201 // Every thing checks out
202 continue;
203 }
204 }
205
206 // We need to delete this package.
207 packages = packagesToDelete.get(userId);
208 if (packages == null) {
209 packages = new HashSet<>();
210 packagesToDelete.put(userId, packages);
211 }
212 packages.add(pkg);
213 }
214
215 for (int i = 0; i < packagesToDelete.size(); i++) {
216 long userId = packagesToDelete.keyAt(i);
Sunny Goyal7c74e4a2016-12-15 15:53:17 -0800217 UserHandle user = mUserManager.getUserForSerialNumber(userId);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700218 for (String pkg : packagesToDelete.valueAt(i)) {
219 removePackage(pkg, user, userId);
220 }
221 }
222 } catch (SQLException e) {
Sunny Goyal6f709362015-12-17 17:09:36 -0800223 Log.e(TAG, "Error updating widget previews", e);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700224 } finally {
225 if (c != null) {
226 c.close();
227 }
228 }
229 }
230
Winson Chung05304db2015-05-18 16:53:20 -0700231 /**
232 * Reads the preview bitmap from the DB or null if the preview is not in the DB.
233 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700234 @Thunk Bitmap readFromDb(WidgetCacheKey key, Bitmap recycle, PreviewLoadTask loadTask) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700235 Cursor cursor = null;
236 try {
Sunny Goyal6f709362015-12-17 17:09:36 -0800237 cursor = mDb.query(
238 new String[]{CacheDb.COLUMN_PREVIEW_BITMAP},
239 CacheDb.COLUMN_COMPONENT + " = ? AND " + CacheDb.COLUMN_USER + " = ? AND "
240 + CacheDb.COLUMN_SIZE + " = ?",
241 new String[]{
Sunny Goyal3ef86912016-10-27 11:40:06 -0700242 key.componentName.flattenToShortString(),
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700243 Long.toString(mUserManager.getSerialNumberForUser(key.user)),
244 key.size
Sunny Goyal6f709362015-12-17 17:09:36 -0800245 });
Winson Chung05304db2015-05-18 16:53:20 -0700246 // If cancelled, skip getting the blob and decoding it into a bitmap
247 if (loadTask.isCancelled()) {
248 return null;
249 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700250 if (cursor.moveToNext()) {
251 byte[] blob = cursor.getBlob(0);
252 BitmapFactory.Options opts = new BitmapFactory.Options();
253 opts.inBitmap = recycle;
Michael Jurka6e27f642013-12-10 13:40:30 +0100254 try {
Winson Chung05304db2015-05-18 16:53:20 -0700255 if (!loadTask.isCancelled()) {
256 return BitmapFactory.decodeByteArray(blob, 0, blob.length, opts);
257 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700258 } catch (Exception e) {
259 return null;
Michael Jurka6e27f642013-12-10 13:40:30 +0100260 }
Michael Jurka05713af2013-01-23 12:39:24 +0100261 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700262 } catch (SQLException e) {
263 Log.w(TAG, "Error loading preview from DB", e);
264 } finally {
265 if (cursor != null) {
266 cursor.close();
267 }
268 }
269 return null;
Michael Jurka05713af2013-01-23 12:39:24 +0100270 }
271
Sunny Goyal27835952017-01-13 12:15:53 -0800272 private Bitmap generatePreview(BaseActivity launcher, WidgetItem item, Bitmap recycle,
Adam Cohen2e6da152015-05-06 11:42:25 -0700273 int previewWidth, int previewHeight) {
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800274 if (item.widgetInfo != null) {
275 return generateWidgetPreview(launcher, item.widgetInfo,
Adam Cohen2e6da152015-05-06 11:42:25 -0700276 previewWidth, recycle, null);
Michael Jurka05713af2013-01-23 12:39:24 +0100277 } else {
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800278 return generateShortcutPreview(launcher, item.activityInfo,
279 previewWidth, previewHeight, recycle);
Michael Jurka05713af2013-01-23 12:39:24 +0100280 }
281 }
282
Hyunyoung Song3e840f42016-03-01 11:57:44 -0800283 /**
284 * Generates the widget preview from either the {@link AppWidgetManagerCompat} or cache
285 * and add badge at the bottom right corner.
286 *
287 * @param launcher
288 * @param info information about the widget
289 * @param maxPreviewWidth width of the preview on either workspace or tray
290 * @param preview bitmap that can be recycled
291 * @param preScaledWidthOut return the width of the returned bitmap
292 * @return
293 */
Sunny Goyal27835952017-01-13 12:15:53 -0800294 public Bitmap generateWidgetPreview(BaseActivity launcher, LauncherAppWidgetProviderInfo info,
Sunny Goyal4cad7532015-03-18 15:56:30 -0700295 int maxPreviewWidth, Bitmap preview, int[] preScaledWidthOut) {
Michael Jurka05713af2013-01-23 12:39:24 +0100296 // Load the preview image if possible
Michael Jurka05713af2013-01-23 12:39:24 +0100297 if (maxPreviewWidth < 0) maxPreviewWidth = Integer.MAX_VALUE;
Michael Jurka05713af2013-01-23 12:39:24 +0100298
299 Drawable drawable = null;
Sunny Goyalffe83f12014-08-14 17:39:34 -0700300 if (info.previewImage != 0) {
Sunny Goyal2570d102016-10-27 11:38:45 -0700301 try {
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800302 drawable = info.loadPreviewImage(mContext, 0);
Sunny Goyal2570d102016-10-27 11:38:45 -0700303 } catch (OutOfMemoryError e) {
304 Log.w(TAG, "Error loading widget preview for: " + info.provider, e);
305 // During OutOfMemoryError, the previous heap stack is not affected. Catching
306 // an OOM error here should be safe & not affect other parts of launcher.
307 drawable = null;
308 }
Adrian Roosfa9ffc22014-05-12 15:59:59 +0200309 if (drawable != null) {
310 drawable = mutateOnMainThread(drawable);
311 } else {
Michael Jurka05713af2013-01-23 12:39:24 +0100312 Log.w(TAG, "Can't load widget preview drawable 0x" +
Sunny Goyalffe83f12014-08-14 17:39:34 -0700313 Integer.toHexString(info.previewImage) + " for provider: " + info.provider);
Michael Jurka05713af2013-01-23 12:39:24 +0100314 }
315 }
316
Sunny Goyal4cad7532015-03-18 15:56:30 -0700317 final boolean widgetPreviewExists = (drawable != null);
Sunny Goyal233ee962015-08-03 13:05:01 -0700318 final int spanX = info.spanX;
319 final int spanY = info.spanY;
Sunny Goyal4cad7532015-03-18 15:56:30 -0700320
Michael Jurka05713af2013-01-23 12:39:24 +0100321 int previewWidth;
322 int previewHeight;
Hyunyoung Song3e840f42016-03-01 11:57:44 -0800323
Michael Jurka05713af2013-01-23 12:39:24 +0100324 if (widgetPreviewExists) {
325 previewWidth = drawable.getIntrinsicWidth();
326 previewHeight = drawable.getIntrinsicHeight();
327 } else {
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800328 DeviceProfile dp = launcher.getDeviceProfile();
329 int tileSize = Math.min(dp.cellWidthPx, dp.cellHeightPx);
330 previewWidth = tileSize * spanX;
331 previewHeight = tileSize * spanY;
Michael Jurka05713af2013-01-23 12:39:24 +0100332 }
333
334 // Scale to fit width only - let the widget preview be clipped in the
335 // vertical dimension
336 float scale = 1f;
337 if (preScaledWidthOut != null) {
338 preScaledWidthOut[0] = previewWidth;
339 }
340 if (previewWidth > maxPreviewWidth) {
Sunny Goyala2441e82017-01-14 13:40:15 -0800341 scale = maxPreviewWidth / (float) (previewWidth);
Michael Jurka05713af2013-01-23 12:39:24 +0100342 }
343 if (scale != 1f) {
344 previewWidth = (int) (scale * previewWidth);
345 previewHeight = (int) (scale * previewHeight);
346 }
347
348 // 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 -0700349 final Canvas c = new Canvas();
Michael Jurka05713af2013-01-23 12:39:24 +0100350 if (preview == null) {
351 preview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700352 c.setBitmap(preview);
353 } else {
Sunny Goyala2441e82017-01-14 13:40:15 -0800354 // We use the preview bitmap height to determine where the badge will be drawn in the
355 // UI. If its larger than what we need, resize the preview bitmap so that there are
356 // no transparent pixels between the preview and the badge.
357 if (preview.getHeight() > previewHeight) {
358 preview.reconfigure(preview.getWidth(), previewHeight, preview.getConfig());
359 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700360 // Reusing bitmap. Clear it.
361 c.setBitmap(preview);
362 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100363 }
364
365 // Draw the scaled preview into the final bitmap
Hyunyoung Songb9f932e2015-07-30 15:04:59 -0700366 int x = (preview.getWidth() - previewWidth) / 2;
Michael Jurka05713af2013-01-23 12:39:24 +0100367 if (widgetPreviewExists) {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700368 drawable.setBounds(x, 0, x + previewWidth, previewHeight);
369 drawable.draw(c);
Michael Jurka05713af2013-01-23 12:39:24 +0100370 } else {
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800371 final Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800372 RectF boxRect = drawBoxWithShadow(c, p, previewWidth, previewHeight);
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800373
374 // Draw horizontal and vertical lines to represent individual columns.
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800375 p.setStyle(Paint.Style.STROKE);
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800376 p.setStrokeWidth(mContext.getResources()
377 .getDimension(R.dimen.widget_preview_cell_divider_width));
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800378 p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
379
380 float t = boxRect.left;
381 float tileSize = boxRect.width() / spanX;
382 for (int i = 1; i < spanX; i++) {
383 t += tileSize;
384 c.drawLine(t, 0, t, previewHeight, p);
Michael Jurka05713af2013-01-23 12:39:24 +0100385 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700386
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800387 t = boxRect.top;
388 tileSize = boxRect.height() / spanY;
389 for (int i = 1; i < spanY; i++) {
390 t += tileSize;
391 c.drawLine(0, t, previewWidth, t, p);
392 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700393
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800394 // Draw icon in the center.
Sunny Goyal4cad7532015-03-18 15:56:30 -0700395 try {
Sunny Goyala52ecb02016-12-16 15:04:51 -0800396 Drawable icon = info.getIcon(launcher, mIconCache);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700397 if (icon != null) {
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800398 int appIconSize = launcher.getDeviceProfile().iconSizePx;
399 int iconSize = (int) Math.min(appIconSize * scale,
400 Math.min(boxRect.width(), boxRect.height()));
401
Sunny Goyal1ba7e362015-10-26 10:42:12 -0700402 icon = mutateOnMainThread(icon);
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800403 int hoffset = (previewWidth - iconSize) / 2;
404 int yoffset = (previewHeight - iconSize) / 2;
405 icon.setBounds(hoffset, yoffset, hoffset + iconSize, yoffset + iconSize);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700406 icon.draw(c);
407 }
Sunny Goyal92bbfa12017-02-07 15:06:32 -0800408 } catch (Resources.NotFoundException e) { }
Michael Jurka05713af2013-01-23 12:39:24 +0100409 c.setBitmap(null);
410 }
Sunny Goyala2441e82017-01-14 13:40:15 -0800411 return preview;
Michael Jurka05713af2013-01-23 12:39:24 +0100412 }
413
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800414 private RectF drawBoxWithShadow(Canvas c, Paint p, int width, int height) {
415 Resources res = mContext.getResources();
416 float shadowBlur = res.getDimension(R.dimen.widget_preview_shadow_blur);
417 float keyShadowDistance = res.getDimension(R.dimen.widget_preview_key_shadow_distance);
418 float corner = res.getDimension(R.dimen.widget_preview_corner_radius);
419
420 RectF bounds = new RectF(shadowBlur, shadowBlur,
421 width - shadowBlur, height - shadowBlur - keyShadowDistance);
422 p.setColor(Color.WHITE);
423
424 // Key shadow
425 p.setShadowLayer(shadowBlur, 0, keyShadowDistance,
426 ShadowGenerator.KEY_SHADOW_ALPHA << 24);
427 c.drawRoundRect(bounds, corner, corner, p);
428
429 // Ambient shadow
430 p.setShadowLayer(shadowBlur, 0, 0,
431 ColorUtils.setAlphaComponent(Color.BLACK, ShadowGenerator.AMBIENT_SHADOW_ALPHA));
432 c.drawRoundRect(bounds, corner, corner, p);
433
434 p.clearShadowLayer();
435 return bounds;
436 }
437
Sunny Goyal782f0c92017-01-19 10:27:54 -0800438 private Bitmap generateShortcutPreview(BaseActivity launcher, ShortcutConfigActivityInfo info,
439 int maxWidth, int maxHeight, Bitmap preview) {
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800440 int iconSize = launcher.getDeviceProfile().iconSizePx;
441 int padding = launcher.getResources()
442 .getDimensionPixelSize(R.dimen.widget_preview_shortcut_padding);
443
444 int size = iconSize + 2 * padding;
445 if (maxHeight < size || maxWidth < size) {
446 throw new RuntimeException("Max size is too small for preview");
447 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700448 final Canvas c = new Canvas();
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800449 if (preview == null || preview.getWidth() < size || preview.getHeight() < size) {
450 preview = Bitmap.createBitmap(size, size, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700451 c.setBitmap(preview);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700452 } else {
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800453 if (preview.getWidth() > size || preview.getHeight() > size) {
454 preview.reconfigure(size, size, preview.getConfig());
455 }
456
Sunny Goyal4cad7532015-03-18 15:56:30 -0700457 // Reusing bitmap. Clear it.
458 c.setBitmap(preview);
459 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100460 }
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800461 Paint p = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
462 RectF boxRect = drawBoxWithShadow(c, p, size, size);
Michael Jurka05713af2013-01-23 12:39:24 +0100463
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800464 Bitmap icon = LauncherIcons.createScaledBitmapWithoutShadow(
465 mutateOnMainThread(info.getFullResIcon(mIconCache)), mContext);
466 Rect src = new Rect(0, 0, icon.getWidth(), icon.getHeight());
Sunny Goyal4cad7532015-03-18 15:56:30 -0700467
Sunny Goyal7d87cb12017-02-13 10:44:43 -0800468 boxRect.set(0, 0, iconSize, iconSize);
469 boxRect.offset(padding, padding);
470 c.drawBitmap(icon, src, boxRect, p);
Michael Jurka05713af2013-01-23 12:39:24 +0100471 c.setBitmap(null);
Michael Jurka05713af2013-01-23 12:39:24 +0100472 return preview;
473 }
474
Adrian Roos65d60e22014-04-15 21:07:49 +0200475 private Drawable mutateOnMainThread(final Drawable drawable) {
476 try {
477 return mMainThreadExecutor.submit(new Callable<Drawable>() {
478 @Override
479 public Drawable call() throws Exception {
480 return drawable.mutate();
481 }
482 }).get();
483 } catch (InterruptedException e) {
484 Thread.currentThread().interrupt();
485 throw new RuntimeException(e);
486 } catch (ExecutionException e) {
487 throw new RuntimeException(e);
488 }
489 }
Adrian Roos1f375ab2014-04-28 18:26:38 +0200490
Adrian Roos1f375ab2014-04-28 18:26:38 +0200491 /**
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700492 * @return an array of containing versionCode and lastUpdatedTime for the package.
Adrian Roos1f375ab2014-04-28 18:26:38 +0200493 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700494 @Thunk long[] getPackageVersion(String packageName) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700495 synchronized (mPackageVersions) {
496 long[] versions = mPackageVersions.get(packageName);
497 if (versions == null) {
498 versions = new long[2];
Adrian Roos1f375ab2014-04-28 18:26:38 +0200499 try {
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800500 PackageInfo info = mContext.getPackageManager().getPackageInfo(packageName,
501 PackageManager.GET_UNINSTALLED_PACKAGES);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700502 versions[0] = info.versionCode;
503 versions[1] = info.lastUpdateTime;
504 } catch (NameNotFoundException e) {
505 Log.e(TAG, "PackageInfo not found", e);
506 }
507 mPackageVersions.put(packageName, versions);
508 }
509 return versions;
510 }
511 }
512
513 /**
514 * A request Id which can be used by the client to cancel any request.
515 */
516 public class PreviewLoadRequest {
517
Sunny Goyalb4cbea42015-06-16 15:10:36 -0700518 @Thunk final PreviewLoadTask mTask;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700519
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700520 public PreviewLoadRequest(PreviewLoadTask task) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700521 mTask = task;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700522 }
523
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700524 public void cleanup() {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700525 if (mTask != null) {
526 mTask.cancel(true);
527 }
528
Winson Chung05304db2015-05-18 16:53:20 -0700529 // This only handles the case where the PreviewLoadTask is cancelled after the task has
530 // successfully completed (including having written to disk when necessary). In the
531 // other cases where it is cancelled while the task is running, it will be cleaned up
532 // in the tasks's onCancelled() call, and if cancelled while the task is writing to
533 // disk, it will be cancelled in the task's onPostExecute() call.
534 if (mTask.mBitmapToRecycle != null) {
Hyunyoung Songe98f4a42015-06-16 10:45:24 -0700535 mWorkerHandler.post(new Runnable() {
536 @Override
537 public void run() {
538 synchronized (mUnusedBitmaps) {
539 mUnusedBitmaps.add(mTask.mBitmapToRecycle);
540 }
541 mTask.mBitmapToRecycle = null;
542 }
543 });
Adrian Roos1f375ab2014-04-28 18:26:38 +0200544 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700545 }
546 }
547
548 public class PreviewLoadTask extends AsyncTask<Void, Void, Bitmap> {
Sunny Goyal316490e2015-06-02 09:38:28 -0700549 @Thunk final WidgetCacheKey mKey;
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800550 private final WidgetItem mInfo;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700551 private final int mPreviewHeight;
552 private final int mPreviewWidth;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700553 private final WidgetCell mCaller;
Sunny Goyala2441e82017-01-14 13:40:15 -0800554 private final BaseActivity mActivity;
Sunny Goyal316490e2015-06-02 09:38:28 -0700555 @Thunk long[] mVersions;
556 @Thunk Bitmap mBitmapToRecycle;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700557
Sunny Goyal4ddc4012016-03-10 12:02:29 -0800558 PreviewLoadTask(WidgetCacheKey key, WidgetItem info, int previewWidth,
Hyunyoung Song3f471442015-04-08 19:01:34 -0700559 int previewHeight, WidgetCell caller) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700560 mKey = key;
561 mInfo = info;
562 mPreviewHeight = previewHeight;
563 mPreviewWidth = previewWidth;
564 mCaller = caller;
Sunny Goyala2441e82017-01-14 13:40:15 -0800565 mActivity = BaseActivity.fromContext(mCaller.getContext());
Hyunyoung Song3f471442015-04-08 19:01:34 -0700566 if (DEBUG) {
567 Log.d(TAG, String.format("%s, %s, %d, %d",
568 mKey, mInfo, mPreviewHeight, mPreviewWidth));
569 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700570 }
571
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700572 @Override
573 protected Bitmap doInBackground(Void... params) {
574 Bitmap unusedBitmap = null;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700575
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700576 // If already cancelled before this gets to run in the background, then return early
577 if (isCancelled()) {
578 return null;
579 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700580 synchronized (mUnusedBitmaps) {
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700581 // Check if we can re-use a bitmap
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700582 for (Bitmap candidate : mUnusedBitmaps) {
583 if (candidate != null && candidate.isMutable() &&
584 candidate.getWidth() == mPreviewWidth &&
585 candidate.getHeight() == mPreviewHeight) {
586 unusedBitmap = candidate;
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700587 mUnusedBitmaps.remove(unusedBitmap);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700588 break;
589 }
590 }
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700591 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700592
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700593 // creating a bitmap is expensive. Do not do this inside synchronized block.
594 if (unusedBitmap == null) {
595 unusedBitmap = Bitmap.createBitmap(mPreviewWidth, mPreviewHeight, Config.ARGB_8888);
Adrian Roos1f375ab2014-04-28 18:26:38 +0200596 }
Winson Chung05304db2015-05-18 16:53:20 -0700597 // If cancelled now, don't bother reading the preview from the DB
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700598 if (isCancelled()) {
Winson Chung05304db2015-05-18 16:53:20 -0700599 return unusedBitmap;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700600 }
Winson Chung05304db2015-05-18 16:53:20 -0700601 Bitmap preview = readFromDb(mKey, unusedBitmap, this);
602 // Only consider generating the preview if we have not cancelled the task already
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700603 if (!isCancelled() && preview == null) {
604 // Fetch the version info before we generate the preview, so that, in-case the
605 // app was updated while we are generating the preview, we use the old version info,
606 // which would gets re-written next time.
Sunny Goyal65513ba2017-01-20 11:54:25 -0800607 boolean persistable = mInfo.activityInfo == null
608 || mInfo.activityInfo.isPersistable();
609 mVersions = persistable ? getPackageVersion(mKey.componentName.getPackageName())
610 : null;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700611
612 // it's not in the db... we need to generate it
Sunny Goyala2441e82017-01-14 13:40:15 -0800613 preview = generatePreview(mActivity, mInfo, unusedBitmap, mPreviewWidth, mPreviewHeight);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700614 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700615 return preview;
616 }
617
618 @Override
Winson Chung05304db2015-05-18 16:53:20 -0700619 protected void onPostExecute(final Bitmap preview) {
620 mCaller.applyPreview(preview);
621
622 // Write the generated preview to the DB in the worker thread
623 if (mVersions != null) {
624 mWorkerHandler.post(new Runnable() {
625 @Override
626 public void run() {
627 if (!isCancelled()) {
628 // If we are still using this preview, then write it to the DB and then
629 // let the normal clear mechanism recycle the bitmap
630 writeToDb(mKey, mVersions, preview);
631 mBitmapToRecycle = preview;
632 } else {
633 // If we've already cancelled, then skip writing the bitmap to the DB
634 // and manually add the bitmap back to the recycled set
635 synchronized (mUnusedBitmaps) {
636 mUnusedBitmaps.add(preview);
637 }
638 }
639 }
640 });
641 } else {
642 // If we don't need to write to disk, then ensure the preview gets recycled by
643 // the normal clear mechanism
644 mBitmapToRecycle = preview;
645 }
646 }
647
648 @Override
Hyunyoung Songe98f4a42015-06-16 10:45:24 -0700649 protected void onCancelled(final Bitmap preview) {
Winson Chung05304db2015-05-18 16:53:20 -0700650 // If we've cancelled while the task is running, then can return the bitmap to the
651 // recycled set immediately. Otherwise, it will be recycled after the preview is written
652 // to disk.
653 if (preview != null) {
Hyunyoung Songe98f4a42015-06-16 10:45:24 -0700654 mWorkerHandler.post(new Runnable() {
655 @Override
656 public void run() {
657 synchronized (mUnusedBitmaps) {
658 mUnusedBitmaps.add(preview);
659 }
660 }
661 });
Winson Chung05304db2015-05-18 16:53:20 -0700662 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700663 }
664 }
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}