blob: b27fa60b723987ffb3a06b5b858017d49ad5624c [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;
7import android.content.pm.PackageManager.NameNotFoundException;
Michael Jurka05713af2013-01-23 12:39:24 +01008import android.content.pm.ResolveInfo;
9import 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;
17import android.graphics.ColorMatrix;
18import android.graphics.ColorMatrixColorFilter;
19import android.graphics.Paint;
20import android.graphics.PorterDuff;
21import 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.BitmapDrawable;
24import android.graphics.drawable.Drawable;
25import android.os.AsyncTask;
Winson Chung05304db2015-05-18 16:53:20 -070026import android.os.Handler;
Michael Jurka05713af2013-01-23 12:39:24 +010027import android.util.Log;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070028import android.util.LongSparseArray;
Sunny Goyal383c5072015-06-12 21:18:53 -070029
Sunny Goyalffe83f12014-08-14 17:39:34 -070030import com.android.launcher3.compat.AppWidgetManagerCompat;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070031import com.android.launcher3.compat.UserHandleCompat;
32import com.android.launcher3.compat.UserManagerCompat;
33import com.android.launcher3.util.ComponentKey;
Sunny Goyal6f709362015-12-17 17:09:36 -080034import com.android.launcher3.util.SQLiteCacheHelper;
Adam Cohen091440a2015-03-18 14:16:05 -070035import com.android.launcher3.util.Thunk;
Hyunyoung Song3f471442015-04-08 19:01:34 -070036import com.android.launcher3.widget.WidgetCell;
Hyunyoung Song8821ca92015-05-04 16:28:20 -070037
38import java.util.ArrayList;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070039import java.util.Collections;
Michael Jurka05713af2013-01-23 12:39:24 +010040import java.util.HashMap;
41import java.util.HashSet;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070042import java.util.Set;
43import java.util.WeakHashMap;
Adrian Roos65d60e22014-04-15 21:07:49 +020044import java.util.concurrent.Callable;
45import java.util.concurrent.ExecutionException;
Michael Jurka05713af2013-01-23 12:39:24 +010046
Sunny Goyalffe83f12014-08-14 17:39:34 -070047public class WidgetPreviewLoader {
Michael Jurka05713af2013-01-23 12:39:24 +010048
Sunny Goyalffe83f12014-08-14 17:39:34 -070049 private static final String TAG = "WidgetPreviewLoader";
Hyunyoung Song3f471442015-04-08 19:01:34 -070050 private static final boolean DEBUG = false;
Sunny Goyalffe83f12014-08-14 17:39:34 -070051
52 private static final float WIDGET_PREVIEW_ICON_PADDING_PERCENTAGE = 0.25f;
Sunny Goyalffe83f12014-08-14 17:39:34 -070053
Sunny Goyal5b0e6692015-03-19 14:31:19 -070054 private final HashMap<String, long[]> mPackageVersions = new HashMap<>();
Hyunyoung Song559d90d2015-04-28 15:06:45 -070055
56 /**
57 * Weak reference objects, do not prevent their referents from being made finalizable,
58 * finalized, and then reclaimed.
Hyunyoung Songe98f4a42015-06-16 10:45:24 -070059 * Note: synchronized block used for this variable is expensive and the block should always
60 * be posted to a background thread.
Hyunyoung Song559d90d2015-04-28 15:06:45 -070061 */
Sunny Goyalb4cbea42015-06-16 15:10:36 -070062 @Thunk final Set<Bitmap> mUnusedBitmaps =
Hyunyoung Song559d90d2015-04-28 15:06:45 -070063 Collections.newSetFromMap(new WeakHashMap<Bitmap, Boolean>());
Sunny Goyal4cad7532015-03-18 15:56:30 -070064
65 private final Context mContext;
Sunny Goyalffe83f12014-08-14 17:39:34 -070066 private final IconCache mIconCache;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070067 private final UserManagerCompat mUserManager;
Sunny Goyalffe83f12014-08-14 17:39:34 -070068 private final AppWidgetManagerCompat mManager;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070069 private final CacheDb mDb;
Hyunyoung Song41e33692015-06-15 12:26:54 -070070 private final int mProfileBadgeMargin;
Michael Jurka05713af2013-01-23 12:39:24 +010071
Adrian Roos65d60e22014-04-15 21:07:49 +020072 private final MainThreadExecutor mMainThreadExecutor = new MainThreadExecutor();
Sunny Goyal316490e2015-06-02 09:38:28 -070073 @Thunk final Handler mWorkerHandler;
Adrian Roos65d60e22014-04-15 21:07:49 +020074
Sunny Goyal383c5072015-06-12 21:18:53 -070075 public WidgetPreviewLoader(Context context, IconCache iconCache) {
Chris Wrenfd13c712013-09-27 15:45:19 -040076 mContext = context;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070077 mIconCache = iconCache;
Sunny Goyalffe83f12014-08-14 17:39:34 -070078 mManager = AppWidgetManagerCompat.getInstance(context);
Sunny Goyal5b0e6692015-03-19 14:31:19 -070079 mUserManager = UserManagerCompat.getInstance(context);
80 mDb = new CacheDb(context);
Winson Chung05304db2015-05-18 16:53:20 -070081 mWorkerHandler = new Handler(LauncherModel.getWorkerLooper());
Hyunyoung Song41e33692015-06-15 12:26:54 -070082 mProfileBadgeMargin = context.getResources()
83 .getDimensionPixelSize(R.dimen.profile_badge_margin);
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 *
90 * @param o either {@link LauncherAppWidgetProviderInfo} or {@link ResolveInfo}
Sunny Goyal5b0e6692015-03-19 14:31:19 -070091 * @return a request id which can be used to cancel the request.
92 */
Adam Cohen2e6da152015-05-06 11:42:25 -070093 public PreviewLoadRequest getPreview(final Object o, int previewWidth,
94 int previewHeight, WidgetCell caller) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -070095 String size = previewWidth + "x" + previewHeight;
96 WidgetCacheKey key = getObjectKey(o, size);
Michael Jurka3f4e0702013-02-05 11:21:28 +010097
Sunny Goyal5b0e6692015-03-19 14:31:19 -070098 PreviewLoadTask task = new PreviewLoadTask(key, o, previewWidth, previewHeight, caller);
Sunny Goyal8ac727b2015-09-23 15:38:09 -070099 task.executeOnExecutor(Utilities.THREAD_POOL_EXECUTOR);
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700100 return new PreviewLoadRequest(task);
Michael Jurka05713af2013-01-23 12:39:24 +0100101 }
102
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700103 /**
104 * The DB holds the generated previews for various components. Previews can also have different
105 * sizes (landscape vs portrait).
106 */
Sunny Goyal6f709362015-12-17 17:09:36 -0800107 private static class CacheDb extends SQLiteCacheHelper {
Sunny Goyal2d648b02015-08-11 13:56:28 -0700108 private static final int DB_VERSION = 4;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700109
110 private static final String TABLE_NAME = "shortcut_and_widget_previews";
111 private static final String COLUMN_COMPONENT = "componentName";
112 private static final String COLUMN_USER = "profileId";
113 private static final String COLUMN_SIZE = "size";
114 private static final String COLUMN_PACKAGE = "packageName";
115 private static final String COLUMN_LAST_UPDATED = "lastUpdated";
116 private static final String COLUMN_VERSION = "version";
117 private static final String COLUMN_PREVIEW_BITMAP = "preview_bitmap";
Michael Jurka05713af2013-01-23 12:39:24 +0100118
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100119 public CacheDb(Context context) {
Sunny Goyal6f709362015-12-17 17:09:36 -0800120 super(context, LauncherFiles.WIDGET_PREVIEWS_DB, DB_VERSION, TABLE_NAME);
Michael Jurka05713af2013-01-23 12:39:24 +0100121 }
122
123 @Override
Sunny Goyal6f709362015-12-17 17:09:36 -0800124 public void onCreateTable(SQLiteDatabase database) {
Michael Jurka32b7a092013-02-07 20:06:49 +0100125 database.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" +
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700126 COLUMN_COMPONENT + " TEXT NOT NULL, " +
127 COLUMN_USER + " INTEGER NOT NULL, " +
Michael Jurka05713af2013-01-23 12:39:24 +0100128 COLUMN_SIZE + " TEXT NOT NULL, " +
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700129 COLUMN_PACKAGE + " TEXT NOT NULL, " +
130 COLUMN_LAST_UPDATED + " INTEGER NOT NULL DEFAULT 0, " +
131 COLUMN_VERSION + " INTEGER NOT NULL DEFAULT 0, " +
132 COLUMN_PREVIEW_BITMAP + " BLOB, " +
133 "PRIMARY KEY (" + COLUMN_COMPONENT + ", " + COLUMN_USER + ", " + COLUMN_SIZE + ") " +
Michael Jurka32b7a092013-02-07 20:06:49 +0100134 ");");
Michael Jurka05713af2013-01-23 12:39:24 +0100135 }
Michael Jurka05713af2013-01-23 12:39:24 +0100136 }
137
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700138 private WidgetCacheKey getObjectKey(Object o, String size) {
Michael Jurka05713af2013-01-23 12:39:24 +0100139 // should cache the string builder
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700140 if (o instanceof LauncherAppWidgetProviderInfo) {
141 LauncherAppWidgetProviderInfo info = (LauncherAppWidgetProviderInfo) o;
142 return new WidgetCacheKey(info.provider, mManager.getUser(info), size);
Michael Jurka05713af2013-01-23 12:39:24 +0100143 } else {
144 ResolveInfo info = (ResolveInfo) o;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700145 return new WidgetCacheKey(
146 new ComponentName(info.activityInfo.packageName, info.activityInfo.name),
147 UserHandleCompat.myUserHandle(), size);
Michael Jurka05713af2013-01-23 12:39:24 +0100148 }
149 }
150
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700151 @Thunk void writeToDb(WidgetCacheKey key, long[] versions, Bitmap preview) {
Michael Jurka05713af2013-01-23 12:39:24 +0100152 ContentValues values = new ContentValues();
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700153 values.put(CacheDb.COLUMN_COMPONENT, key.componentName.flattenToShortString());
154 values.put(CacheDb.COLUMN_USER, mUserManager.getSerialNumberForUser(key.user));
155 values.put(CacheDb.COLUMN_SIZE, key.size);
156 values.put(CacheDb.COLUMN_PACKAGE, key.componentName.getPackageName());
157 values.put(CacheDb.COLUMN_VERSION, versions[0]);
158 values.put(CacheDb.COLUMN_LAST_UPDATED, versions[1]);
159 values.put(CacheDb.COLUMN_PREVIEW_BITMAP, Utilities.flattenBitmap(preview));
Sunny Goyal6f709362015-12-17 17:09:36 -0800160 mDb.insertOrReplace(values);
Michael Jurka05713af2013-01-23 12:39:24 +0100161 }
162
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700163 public void removePackage(String packageName, UserHandleCompat user) {
164 removePackage(packageName, user, mUserManager.getSerialNumberForUser(user));
165 }
166
167 private void removePackage(String packageName, UserHandleCompat user, long userSerial) {
168 synchronized(mPackageVersions) {
169 mPackageVersions.remove(packageName);
170 }
171
Sunny Goyal6f709362015-12-17 17:09:36 -0800172 mDb.delete(
173 CacheDb.COLUMN_PACKAGE + " = ? AND " + CacheDb.COLUMN_USER + " = ?",
174 new String[]{packageName, Long.toString(userSerial)});
Michael Jurka8ff02ca2013-11-01 14:19:27 +0100175 }
176
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700177 /**
178 * Updates the persistent DB:
179 * 1. Any preview generated for an old package version is removed
180 * 2. Any preview for an absent package is removed
181 * This ensures that we remove entries for packages which changed while the launcher was dead.
182 */
Hyunyoung Song8821ca92015-05-04 16:28:20 -0700183 public void removeObsoletePreviews(ArrayList<Object> list) {
Hyunyoung Song2bd3d7d2015-05-21 13:04:53 -0700184 Utilities.assertWorkerThread();
Hyunyoung Song8821ca92015-05-04 16:28:20 -0700185
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700186 LongSparseArray<HashSet<String>> validPackages = new LongSparseArray<>();
187
Hyunyoung Song8821ca92015-05-04 16:28:20 -0700188 for (Object obj : list) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700189 final UserHandleCompat user;
190 final String pkg;
191 if (obj instanceof ResolveInfo) {
192 user = UserHandleCompat.myUserHandle();
193 pkg = ((ResolveInfo) obj).activityInfo.packageName;
194 } else {
195 LauncherAppWidgetProviderInfo info = (LauncherAppWidgetProviderInfo) obj;
196 user = mManager.getUser(info);
197 pkg = info.provider.getPackageName();
198 }
199
Sunny Goyala2a039b2015-08-05 13:22:21 -0700200 final long userId = mUserManager.getSerialNumberForUser(user);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700201 HashSet<String> packages = validPackages.get(userId);
202 if (packages == null) {
203 packages = new HashSet<>();
204 validPackages.put(userId, packages);
205 }
206 packages.add(pkg);
Michael Jurka05713af2013-01-23 12:39:24 +0100207 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700208
209 LongSparseArray<HashSet<String>> packagesToDelete = new LongSparseArray<>();
210 Cursor c = null;
211 try {
Sunny Goyal6f709362015-12-17 17:09:36 -0800212 c = mDb.query(
213 new String[]{CacheDb.COLUMN_USER, CacheDb.COLUMN_PACKAGE,
214 CacheDb.COLUMN_LAST_UPDATED, CacheDb.COLUMN_VERSION},
215 null, null);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700216 while (c.moveToNext()) {
217 long userId = c.getLong(0);
218 String pkg = c.getString(1);
219 long lastUpdated = c.getLong(2);
220 long version = c.getLong(3);
221
222 HashSet<String> packages = validPackages.get(userId);
223 if (packages != null && packages.contains(pkg)) {
224 long[] versions = getPackageVersion(pkg);
225 if (versions[0] == version && versions[1] == lastUpdated) {
226 // Every thing checks out
227 continue;
228 }
229 }
230
231 // We need to delete this package.
232 packages = packagesToDelete.get(userId);
233 if (packages == null) {
234 packages = new HashSet<>();
235 packagesToDelete.put(userId, packages);
236 }
237 packages.add(pkg);
238 }
239
240 for (int i = 0; i < packagesToDelete.size(); i++) {
241 long userId = packagesToDelete.keyAt(i);
242 UserHandleCompat user = mUserManager.getUserForSerialNumber(userId);
243 for (String pkg : packagesToDelete.valueAt(i)) {
244 removePackage(pkg, user, userId);
245 }
246 }
247 } catch (SQLException e) {
Sunny Goyal6f709362015-12-17 17:09:36 -0800248 Log.e(TAG, "Error updating widget previews", e);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700249 } finally {
250 if (c != null) {
251 c.close();
252 }
253 }
254 }
255
Winson Chung05304db2015-05-18 16:53:20 -0700256 /**
257 * Reads the preview bitmap from the DB or null if the preview is not in the DB.
258 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700259 @Thunk Bitmap readFromDb(WidgetCacheKey key, Bitmap recycle, PreviewLoadTask loadTask) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700260 Cursor cursor = null;
261 try {
Sunny Goyal6f709362015-12-17 17:09:36 -0800262 cursor = mDb.query(
263 new String[]{CacheDb.COLUMN_PREVIEW_BITMAP},
264 CacheDb.COLUMN_COMPONENT + " = ? AND " + CacheDb.COLUMN_USER + " = ? AND "
265 + CacheDb.COLUMN_SIZE + " = ?",
266 new String[]{
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700267 key.componentName.flattenToString(),
268 Long.toString(mUserManager.getSerialNumberForUser(key.user)),
269 key.size
Sunny Goyal6f709362015-12-17 17:09:36 -0800270 });
Winson Chung05304db2015-05-18 16:53:20 -0700271 // If cancelled, skip getting the blob and decoding it into a bitmap
272 if (loadTask.isCancelled()) {
273 return null;
274 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700275 if (cursor.moveToNext()) {
276 byte[] blob = cursor.getBlob(0);
277 BitmapFactory.Options opts = new BitmapFactory.Options();
278 opts.inBitmap = recycle;
Michael Jurka6e27f642013-12-10 13:40:30 +0100279 try {
Winson Chung05304db2015-05-18 16:53:20 -0700280 if (!loadTask.isCancelled()) {
281 return BitmapFactory.decodeByteArray(blob, 0, blob.length, opts);
282 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700283 } catch (Exception e) {
284 return null;
Michael Jurka6e27f642013-12-10 13:40:30 +0100285 }
Michael Jurka05713af2013-01-23 12:39:24 +0100286 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700287 } catch (SQLException e) {
288 Log.w(TAG, "Error loading preview from DB", e);
289 } finally {
290 if (cursor != null) {
291 cursor.close();
292 }
293 }
294 return null;
Michael Jurka05713af2013-01-23 12:39:24 +0100295 }
296
Sunny Goyal316490e2015-06-02 09:38:28 -0700297 @Thunk Bitmap generatePreview(Launcher launcher, Object info, Bitmap recycle,
Adam Cohen2e6da152015-05-06 11:42:25 -0700298 int previewWidth, int previewHeight) {
Adam Cohen59400422014-03-05 18:07:04 -0800299 if (info instanceof LauncherAppWidgetProviderInfo) {
Adam Cohen2e6da152015-05-06 11:42:25 -0700300 return generateWidgetPreview(launcher, (LauncherAppWidgetProviderInfo) info,
301 previewWidth, recycle, null);
Michael Jurka05713af2013-01-23 12:39:24 +0100302 } else {
Adam Cohen2e6da152015-05-06 11:42:25 -0700303 return generateShortcutPreview(launcher,
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700304 (ResolveInfo) info, previewWidth, previewHeight, recycle);
Michael Jurka05713af2013-01-23 12:39:24 +0100305 }
306 }
307
Adam Cohen2e6da152015-05-06 11:42:25 -0700308 public Bitmap generateWidgetPreview(Launcher launcher, LauncherAppWidgetProviderInfo info,
Sunny Goyal4cad7532015-03-18 15:56:30 -0700309 int maxPreviewWidth, Bitmap preview, int[] preScaledWidthOut) {
Michael Jurka05713af2013-01-23 12:39:24 +0100310 // Load the preview image if possible
Michael Jurka05713af2013-01-23 12:39:24 +0100311 if (maxPreviewWidth < 0) maxPreviewWidth = Integer.MAX_VALUE;
Michael Jurka05713af2013-01-23 12:39:24 +0100312
313 Drawable drawable = null;
Sunny Goyalffe83f12014-08-14 17:39:34 -0700314 if (info.previewImage != 0) {
315 drawable = mManager.loadPreview(info);
Adrian Roosfa9ffc22014-05-12 15:59:59 +0200316 if (drawable != null) {
317 drawable = mutateOnMainThread(drawable);
318 } else {
Michael Jurka05713af2013-01-23 12:39:24 +0100319 Log.w(TAG, "Can't load widget preview drawable 0x" +
Sunny Goyalffe83f12014-08-14 17:39:34 -0700320 Integer.toHexString(info.previewImage) + " for provider: " + info.provider);
Michael Jurka05713af2013-01-23 12:39:24 +0100321 }
322 }
323
Sunny Goyal4cad7532015-03-18 15:56:30 -0700324 final boolean widgetPreviewExists = (drawable != null);
Sunny Goyal233ee962015-08-03 13:05:01 -0700325 final int spanX = info.spanX;
326 final int spanY = info.spanY;
Sunny Goyal4cad7532015-03-18 15:56:30 -0700327
Michael Jurka05713af2013-01-23 12:39:24 +0100328 int previewWidth;
329 int previewHeight;
Sunny Goyal4cad7532015-03-18 15:56:30 -0700330 Bitmap tileBitmap = null;
331
Michael Jurka05713af2013-01-23 12:39:24 +0100332 if (widgetPreviewExists) {
333 previewWidth = drawable.getIntrinsicWidth();
334 previewHeight = drawable.getIntrinsicHeight();
335 } else {
336 // Generate a preview image if we couldn't load one
Sunny Goyal4cad7532015-03-18 15:56:30 -0700337 tileBitmap = ((BitmapDrawable) mContext.getResources().getDrawable(
338 R.drawable.widget_tile)).getBitmap();
339 previewWidth = tileBitmap.getWidth() * spanX;
340 previewHeight = tileBitmap.getHeight() * spanY;
Michael Jurka05713af2013-01-23 12:39:24 +0100341 }
342
343 // Scale to fit width only - let the widget preview be clipped in the
344 // vertical dimension
345 float scale = 1f;
346 if (preScaledWidthOut != null) {
347 preScaledWidthOut[0] = previewWidth;
348 }
349 if (previewWidth > maxPreviewWidth) {
Hyunyoung Songb9f932e2015-07-30 15:04:59 -0700350 scale = (maxPreviewWidth - 2 * mProfileBadgeMargin) / (float) (previewWidth);
Michael Jurka05713af2013-01-23 12:39:24 +0100351 }
352 if (scale != 1f) {
353 previewWidth = (int) (scale * previewWidth);
354 previewHeight = (int) (scale * previewHeight);
355 }
356
357 // 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 -0700358 final Canvas c = new Canvas();
Michael Jurka05713af2013-01-23 12:39:24 +0100359 if (preview == null) {
360 preview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700361 c.setBitmap(preview);
362 } else {
363 // Reusing bitmap. Clear it.
364 c.setBitmap(preview);
365 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100366 }
367
368 // Draw the scaled preview into the final bitmap
Hyunyoung Songb9f932e2015-07-30 15:04:59 -0700369 int x = (preview.getWidth() - previewWidth) / 2;
Michael Jurka05713af2013-01-23 12:39:24 +0100370 if (widgetPreviewExists) {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700371 drawable.setBounds(x, 0, x + previewWidth, previewHeight);
372 drawable.draw(c);
Michael Jurka05713af2013-01-23 12:39:24 +0100373 } else {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700374 final Paint p = new Paint();
375 p.setFilterBitmap(true);
Adam Cohen2e6da152015-05-06 11:42:25 -0700376 int appIconSize = launcher.getDeviceProfile().iconSizePx;
Michael Jurka05713af2013-01-23 12:39:24 +0100377
Sunny Goyal4cad7532015-03-18 15:56:30 -0700378 // draw the spanX x spanY tiles
379 final Rect src = new Rect(0, 0, tileBitmap.getWidth(), tileBitmap.getHeight());
380
381 float tileW = scale * tileBitmap.getWidth();
382 float tileH = scale * tileBitmap.getHeight();
383 final RectF dst = new RectF(0, 0, tileW, tileH);
384
385 float tx = x;
386 for (int i = 0; i < spanX; i++, tx += tileW) {
387 float ty = 0;
388 for (int j = 0; j < spanY; j++, ty += tileH) {
389 dst.offsetTo(tx, ty);
390 c.drawBitmap(tileBitmap, src, dst, p);
391 }
Michael Jurka05713af2013-01-23 12:39:24 +0100392 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700393
394 // Draw the icon in the top left corner
395 // TODO: use top right for RTL
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700396 int minOffset = (int) (appIconSize * WIDGET_PREVIEW_ICON_PADDING_PERCENTAGE);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700397 int smallestSide = Math.min(previewWidth, previewHeight);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700398 float iconScale = Math.min((float) smallestSide / (appIconSize + 2 * minOffset), scale);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700399
400 try {
Sunny Goyal1ba7e362015-10-26 10:42:12 -0700401 Drawable icon = mManager.loadIcon(info, mIconCache);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700402 if (icon != null) {
Sunny Goyal1ba7e362015-10-26 10:42:12 -0700403 icon = mutateOnMainThread(icon);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700404 int hoffset = (int) ((tileW - appIconSize * iconScale) / 2) + x;
405 int yoffset = (int) ((tileH - appIconSize * iconScale) / 2);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700406 icon.setBounds(hoffset, yoffset,
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700407 hoffset + (int) (appIconSize * iconScale),
408 yoffset + (int) (appIconSize * iconScale));
Sunny Goyal4cad7532015-03-18 15:56:30 -0700409 icon.draw(c);
410 }
411 } catch (Resources.NotFoundException e) { }
Michael Jurka05713af2013-01-23 12:39:24 +0100412 c.setBitmap(null);
413 }
Hyunyoung Song41e33692015-06-15 12:26:54 -0700414 int imageHeight = Math.min(preview.getHeight(), previewHeight + mProfileBadgeMargin);
415 return mManager.getBadgeBitmap(info, preview, imageHeight);
Michael Jurka05713af2013-01-23 12:39:24 +0100416 }
417
418 private Bitmap generateShortcutPreview(
Adam Cohen2e6da152015-05-06 11:42:25 -0700419 Launcher launcher, ResolveInfo info, int maxWidth, int maxHeight, Bitmap preview) {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700420 final Canvas c = new Canvas();
421 if (preview == null) {
Michael Jurka05713af2013-01-23 12:39:24 +0100422 preview = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700423 c.setBitmap(preview);
424 } else if (preview.getWidth() != maxWidth || preview.getHeight() != maxHeight) {
425 throw new RuntimeException("Improperly sized bitmap passed as argument");
426 } else {
427 // Reusing bitmap. Clear it.
428 c.setBitmap(preview);
429 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100430 }
431
Sunny Goyal4cad7532015-03-18 15:56:30 -0700432 Drawable icon = mutateOnMainThread(mIconCache.getFullResIcon(info.activityInfo));
433 icon.setFilterBitmap(true);
434
Michael Jurka05713af2013-01-23 12:39:24 +0100435 // Draw a desaturated/scaled version of the icon in the background as a watermark
Sunny Goyal4cad7532015-03-18 15:56:30 -0700436 ColorMatrix colorMatrix = new ColorMatrix();
437 colorMatrix.setSaturation(0);
438 icon.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
439 icon.setAlpha((int) (255 * 0.06f));
440
441 Resources res = mContext.getResources();
442 int paddingTop = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_top);
443 int paddingLeft = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_left);
444 int paddingRight = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_right);
445 int scaledIconWidth = (maxWidth - paddingLeft - paddingRight);
446 icon.setBounds(paddingLeft, paddingTop,
447 paddingLeft + scaledIconWidth, paddingTop + scaledIconWidth);
448 icon.draw(c);
449
450 // Draw the final icon at top left corner.
451 // TODO: use top right for RTL
Adam Cohen2e6da152015-05-06 11:42:25 -0700452 int appIconSize = launcher.getDeviceProfile().iconSizePx;
453
Sunny Goyal4cad7532015-03-18 15:56:30 -0700454 icon.setAlpha(255);
455 icon.setColorFilter(null);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700456 icon.setBounds(0, 0, appIconSize, appIconSize);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700457 icon.draw(c);
458
Michael Jurka05713af2013-01-23 12:39:24 +0100459 c.setBitmap(null);
Michael Jurka05713af2013-01-23 12:39:24 +0100460 return preview;
461 }
462
Adrian Roos65d60e22014-04-15 21:07:49 +0200463 private Drawable mutateOnMainThread(final Drawable drawable) {
464 try {
465 return mMainThreadExecutor.submit(new Callable<Drawable>() {
466 @Override
467 public Drawable call() throws Exception {
468 return drawable.mutate();
469 }
470 }).get();
471 } catch (InterruptedException e) {
472 Thread.currentThread().interrupt();
473 throw new RuntimeException(e);
474 } catch (ExecutionException e) {
475 throw new RuntimeException(e);
476 }
477 }
Adrian Roos1f375ab2014-04-28 18:26:38 +0200478
Adrian Roos1f375ab2014-04-28 18:26:38 +0200479 /**
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700480 * @return an array of containing versionCode and lastUpdatedTime for the package.
Adrian Roos1f375ab2014-04-28 18:26:38 +0200481 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700482 @Thunk long[] getPackageVersion(String packageName) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700483 synchronized (mPackageVersions) {
484 long[] versions = mPackageVersions.get(packageName);
485 if (versions == null) {
486 versions = new long[2];
Adrian Roos1f375ab2014-04-28 18:26:38 +0200487 try {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700488 PackageInfo info = mContext.getPackageManager().getPackageInfo(packageName, 0);
489 versions[0] = info.versionCode;
490 versions[1] = info.lastUpdateTime;
491 } catch (NameNotFoundException e) {
492 Log.e(TAG, "PackageInfo not found", e);
493 }
494 mPackageVersions.put(packageName, versions);
495 }
496 return versions;
497 }
498 }
499
500 /**
501 * A request Id which can be used by the client to cancel any request.
502 */
503 public class PreviewLoadRequest {
504
Sunny Goyalb4cbea42015-06-16 15:10:36 -0700505 @Thunk final PreviewLoadTask mTask;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700506
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700507 public PreviewLoadRequest(PreviewLoadTask task) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700508 mTask = task;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700509 }
510
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700511 public void cleanup() {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700512 if (mTask != null) {
513 mTask.cancel(true);
514 }
515
Winson Chung05304db2015-05-18 16:53:20 -0700516 // This only handles the case where the PreviewLoadTask is cancelled after the task has
517 // successfully completed (including having written to disk when necessary). In the
518 // other cases where it is cancelled while the task is running, it will be cleaned up
519 // in the tasks's onCancelled() call, and if cancelled while the task is writing to
520 // disk, it will be cancelled in the task's onPostExecute() call.
521 if (mTask.mBitmapToRecycle != null) {
Hyunyoung Songe98f4a42015-06-16 10:45:24 -0700522 mWorkerHandler.post(new Runnable() {
523 @Override
524 public void run() {
525 synchronized (mUnusedBitmaps) {
526 mUnusedBitmaps.add(mTask.mBitmapToRecycle);
527 }
528 mTask.mBitmapToRecycle = null;
529 }
530 });
Adrian Roos1f375ab2014-04-28 18:26:38 +0200531 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700532 }
533 }
534
535 public class PreviewLoadTask extends AsyncTask<Void, Void, Bitmap> {
Sunny Goyal316490e2015-06-02 09:38:28 -0700536 @Thunk final WidgetCacheKey mKey;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700537 private final Object mInfo;
538 private final int mPreviewHeight;
539 private final int mPreviewWidth;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700540 private final WidgetCell mCaller;
Sunny Goyal316490e2015-06-02 09:38:28 -0700541 @Thunk long[] mVersions;
542 @Thunk Bitmap mBitmapToRecycle;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700543
544 PreviewLoadTask(WidgetCacheKey key, Object info, int previewWidth,
Hyunyoung Song3f471442015-04-08 19:01:34 -0700545 int previewHeight, WidgetCell caller) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700546 mKey = key;
547 mInfo = info;
548 mPreviewHeight = previewHeight;
549 mPreviewWidth = previewWidth;
550 mCaller = caller;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700551 if (DEBUG) {
552 Log.d(TAG, String.format("%s, %s, %d, %d",
553 mKey, mInfo, mPreviewHeight, mPreviewWidth));
554 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700555 }
556
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700557 @Override
558 protected Bitmap doInBackground(Void... params) {
559 Bitmap unusedBitmap = null;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700560
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700561 // If already cancelled before this gets to run in the background, then return early
562 if (isCancelled()) {
563 return null;
564 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700565 synchronized (mUnusedBitmaps) {
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700566 // Check if we can re-use a bitmap
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700567 for (Bitmap candidate : mUnusedBitmaps) {
568 if (candidate != null && candidate.isMutable() &&
569 candidate.getWidth() == mPreviewWidth &&
570 candidate.getHeight() == mPreviewHeight) {
571 unusedBitmap = candidate;
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700572 mUnusedBitmaps.remove(unusedBitmap);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700573 break;
574 }
575 }
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700576 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700577
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700578 // creating a bitmap is expensive. Do not do this inside synchronized block.
579 if (unusedBitmap == null) {
580 unusedBitmap = Bitmap.createBitmap(mPreviewWidth, mPreviewHeight, Config.ARGB_8888);
Adrian Roos1f375ab2014-04-28 18:26:38 +0200581 }
Winson Chung05304db2015-05-18 16:53:20 -0700582 // If cancelled now, don't bother reading the preview from the DB
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700583 if (isCancelled()) {
Winson Chung05304db2015-05-18 16:53:20 -0700584 return unusedBitmap;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700585 }
Winson Chung05304db2015-05-18 16:53:20 -0700586 Bitmap preview = readFromDb(mKey, unusedBitmap, this);
587 // Only consider generating the preview if we have not cancelled the task already
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700588 if (!isCancelled() && preview == null) {
589 // Fetch the version info before we generate the preview, so that, in-case the
590 // app was updated while we are generating the preview, we use the old version info,
591 // which would gets re-written next time.
Winson Chung05304db2015-05-18 16:53:20 -0700592 mVersions = getPackageVersion(mKey.componentName.getPackageName());
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700593
Adam Cohen2e6da152015-05-06 11:42:25 -0700594 Launcher launcher = (Launcher) mCaller.getContext();
595
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700596 // it's not in the db... we need to generate it
Adam Cohen2e6da152015-05-06 11:42:25 -0700597 preview = generatePreview(launcher, mInfo, unusedBitmap, mPreviewWidth, mPreviewHeight);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700598 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700599 return preview;
600 }
601
602 @Override
Winson Chung05304db2015-05-18 16:53:20 -0700603 protected void onPostExecute(final Bitmap preview) {
604 mCaller.applyPreview(preview);
605
606 // Write the generated preview to the DB in the worker thread
607 if (mVersions != null) {
608 mWorkerHandler.post(new Runnable() {
609 @Override
610 public void run() {
611 if (!isCancelled()) {
612 // If we are still using this preview, then write it to the DB and then
613 // let the normal clear mechanism recycle the bitmap
614 writeToDb(mKey, mVersions, preview);
615 mBitmapToRecycle = preview;
616 } else {
617 // If we've already cancelled, then skip writing the bitmap to the DB
618 // and manually add the bitmap back to the recycled set
619 synchronized (mUnusedBitmaps) {
620 mUnusedBitmaps.add(preview);
621 }
622 }
623 }
624 });
625 } else {
626 // If we don't need to write to disk, then ensure the preview gets recycled by
627 // the normal clear mechanism
628 mBitmapToRecycle = preview;
629 }
630 }
631
632 @Override
Hyunyoung Songe98f4a42015-06-16 10:45:24 -0700633 protected void onCancelled(final Bitmap preview) {
Winson Chung05304db2015-05-18 16:53:20 -0700634 // If we've cancelled while the task is running, then can return the bitmap to the
635 // recycled set immediately. Otherwise, it will be recycled after the preview is written
636 // to disk.
637 if (preview != null) {
Hyunyoung Songe98f4a42015-06-16 10:45:24 -0700638 mWorkerHandler.post(new Runnable() {
639 @Override
640 public void run() {
641 synchronized (mUnusedBitmaps) {
642 mUnusedBitmaps.add(preview);
643 }
644 }
645 });
Winson Chung05304db2015-05-18 16:53:20 -0700646 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700647 }
648 }
649
650 private static final class WidgetCacheKey extends ComponentKey {
651
652 // TODO: remove dependency on size
Sunny Goyal316490e2015-06-02 09:38:28 -0700653 @Thunk final String size;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700654
655 public WidgetCacheKey(ComponentName componentName, UserHandleCompat user, String size) {
656 super(componentName, user);
657 this.size = size;
658 }
659
660 @Override
661 public int hashCode() {
662 return super.hashCode() ^ size.hashCode();
663 }
664
665 @Override
666 public boolean equals(Object o) {
667 return super.equals(o) && ((WidgetCacheKey) o).size.equals(size);
Adrian Roos1f375ab2014-04-28 18:26:38 +0200668 }
669 }
Michael Jurka05713af2013-01-23 12:39:24 +0100670}