blob: 10c10532667f8ceadbbcf59dfe683d322028da24 [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;
13import android.database.sqlite.SQLiteOpenHelper;
14import android.graphics.Bitmap;
15import android.graphics.Bitmap.Config;
16import android.graphics.BitmapFactory;
17import android.graphics.Canvas;
18import android.graphics.ColorMatrix;
19import android.graphics.ColorMatrixColorFilter;
20import android.graphics.Paint;
21import android.graphics.PorterDuff;
22import android.graphics.Rect;
Sunny Goyal4cad7532015-03-18 15:56:30 -070023import android.graphics.RectF;
Michael Jurka05713af2013-01-23 12:39:24 +010024import android.graphics.drawable.BitmapDrawable;
25import android.graphics.drawable.Drawable;
26import android.os.AsyncTask;
Winson Chung05304db2015-05-18 16:53:20 -070027import android.os.Handler;
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 Goyal5b0e6692015-03-19 14:31:19 -070032import com.android.launcher3.compat.UserHandleCompat;
33import com.android.launcher3.compat.UserManagerCompat;
34import com.android.launcher3.util.ComponentKey;
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 */
107 private static class CacheDb extends SQLiteOpenHelper {
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 Goyal5b0e6692015-03-19 14:31:19 -0700120 super(context, LauncherFiles.WIDGET_PREVIEWS_DB, null, DB_VERSION);
Michael Jurka05713af2013-01-23 12:39:24 +0100121 }
122
123 @Override
124 public void onCreate(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 }
136
137 @Override
138 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Michael Jurkae5919c52013-03-06 17:30:10 +0100139 if (oldVersion != newVersion) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700140 clearDB(db);
Michael Jurkae5919c52013-03-06 17:30:10 +0100141 }
Michael Jurka05713af2013-01-23 12:39:24 +0100142 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700143
144 @Override
145 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
146 if (oldVersion != newVersion) {
147 clearDB(db);
148 }
149 }
150
151 private void clearDB(SQLiteDatabase db) {
152 db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
153 onCreate(db);
154 }
Michael Jurka05713af2013-01-23 12:39:24 +0100155 }
156
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700157 private WidgetCacheKey getObjectKey(Object o, String size) {
Michael Jurka05713af2013-01-23 12:39:24 +0100158 // should cache the string builder
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700159 if (o instanceof LauncherAppWidgetProviderInfo) {
160 LauncherAppWidgetProviderInfo info = (LauncherAppWidgetProviderInfo) o;
161 return new WidgetCacheKey(info.provider, mManager.getUser(info), size);
Michael Jurka05713af2013-01-23 12:39:24 +0100162 } else {
163 ResolveInfo info = (ResolveInfo) o;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700164 return new WidgetCacheKey(
165 new ComponentName(info.activityInfo.packageName, info.activityInfo.name),
166 UserHandleCompat.myUserHandle(), size);
Michael Jurka05713af2013-01-23 12:39:24 +0100167 }
168 }
169
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700170 @Thunk void writeToDb(WidgetCacheKey key, long[] versions, Bitmap preview) {
Michael Jurka05713af2013-01-23 12:39:24 +0100171 ContentValues values = new ContentValues();
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700172 values.put(CacheDb.COLUMN_COMPONENT, key.componentName.flattenToShortString());
173 values.put(CacheDb.COLUMN_USER, mUserManager.getSerialNumberForUser(key.user));
174 values.put(CacheDb.COLUMN_SIZE, key.size);
175 values.put(CacheDb.COLUMN_PACKAGE, key.componentName.getPackageName());
176 values.put(CacheDb.COLUMN_VERSION, versions[0]);
177 values.put(CacheDb.COLUMN_LAST_UPDATED, versions[1]);
178 values.put(CacheDb.COLUMN_PREVIEW_BITMAP, Utilities.flattenBitmap(preview));
Michael Jurka05713af2013-01-23 12:39:24 +0100179
Michael Jurka6e27f642013-12-10 13:40:30 +0100180 try {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700181 mDb.getWritableDatabase().insertWithOnConflict(CacheDb.TABLE_NAME, null, values,
182 SQLiteDatabase.CONFLICT_REPLACE);
183 } catch (SQLException e) {
184 Log.e(TAG, "Error saving image to DB", e);
Michael Jurka6e27f642013-12-10 13:40:30 +0100185 }
Michael Jurka05713af2013-01-23 12:39:24 +0100186 }
187
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700188 public void removePackage(String packageName, UserHandleCompat user) {
189 removePackage(packageName, user, mUserManager.getSerialNumberForUser(user));
190 }
191
192 private void removePackage(String packageName, UserHandleCompat user, long userSerial) {
193 synchronized(mPackageVersions) {
194 mPackageVersions.remove(packageName);
195 }
196
Michael Jurka6e27f642013-12-10 13:40:30 +0100197 try {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700198 mDb.getWritableDatabase().delete(CacheDb.TABLE_NAME,
199 CacheDb.COLUMN_PACKAGE + " = ? AND " + CacheDb.COLUMN_USER + " = ?",
200 new String[] {packageName, Long.toString(userSerial)});
201 } catch (SQLException e) {
202 Log.e(TAG, "Unable to delete items from DB", e);
Michael Jurka6e27f642013-12-10 13:40:30 +0100203 }
Michael Jurka8ff02ca2013-11-01 14:19:27 +0100204 }
205
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700206 /**
207 * Updates the persistent DB:
208 * 1. Any preview generated for an old package version is removed
209 * 2. Any preview for an absent package is removed
210 * This ensures that we remove entries for packages which changed while the launcher was dead.
211 */
Hyunyoung Song8821ca92015-05-04 16:28:20 -0700212 public void removeObsoletePreviews(ArrayList<Object> list) {
Hyunyoung Song2bd3d7d2015-05-21 13:04:53 -0700213 Utilities.assertWorkerThread();
Hyunyoung Song8821ca92015-05-04 16:28:20 -0700214
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700215 LongSparseArray<HashSet<String>> validPackages = new LongSparseArray<>();
216
Hyunyoung Song8821ca92015-05-04 16:28:20 -0700217 for (Object obj : list) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700218 final UserHandleCompat user;
219 final String pkg;
220 if (obj instanceof ResolveInfo) {
221 user = UserHandleCompat.myUserHandle();
222 pkg = ((ResolveInfo) obj).activityInfo.packageName;
223 } else {
224 LauncherAppWidgetProviderInfo info = (LauncherAppWidgetProviderInfo) obj;
225 user = mManager.getUser(info);
226 pkg = info.provider.getPackageName();
227 }
228
Sunny Goyala2a039b2015-08-05 13:22:21 -0700229 final long userId = mUserManager.getSerialNumberForUser(user);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700230 HashSet<String> packages = validPackages.get(userId);
231 if (packages == null) {
232 packages = new HashSet<>();
233 validPackages.put(userId, packages);
234 }
235 packages.add(pkg);
Michael Jurka05713af2013-01-23 12:39:24 +0100236 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700237
238 LongSparseArray<HashSet<String>> packagesToDelete = new LongSparseArray<>();
239 Cursor c = null;
240 try {
241 c = mDb.getReadableDatabase().query(CacheDb.TABLE_NAME,
242 new String[] {CacheDb.COLUMN_USER, CacheDb.COLUMN_PACKAGE,
243 CacheDb.COLUMN_LAST_UPDATED, CacheDb.COLUMN_VERSION},
244 null, null, null, null, null);
245 while (c.moveToNext()) {
246 long userId = c.getLong(0);
247 String pkg = c.getString(1);
248 long lastUpdated = c.getLong(2);
249 long version = c.getLong(3);
250
251 HashSet<String> packages = validPackages.get(userId);
252 if (packages != null && packages.contains(pkg)) {
253 long[] versions = getPackageVersion(pkg);
254 if (versions[0] == version && versions[1] == lastUpdated) {
255 // Every thing checks out
256 continue;
257 }
258 }
259
260 // We need to delete this package.
261 packages = packagesToDelete.get(userId);
262 if (packages == null) {
263 packages = new HashSet<>();
264 packagesToDelete.put(userId, packages);
265 }
266 packages.add(pkg);
267 }
268
269 for (int i = 0; i < packagesToDelete.size(); i++) {
270 long userId = packagesToDelete.keyAt(i);
271 UserHandleCompat user = mUserManager.getUserForSerialNumber(userId);
272 for (String pkg : packagesToDelete.valueAt(i)) {
273 removePackage(pkg, user, userId);
274 }
275 }
276 } catch (SQLException e) {
277 Log.e(TAG, "Error updatating widget previews", e);
278 } finally {
279 if (c != null) {
280 c.close();
281 }
282 }
283 }
284
Winson Chung05304db2015-05-18 16:53:20 -0700285 /**
286 * Reads the preview bitmap from the DB or null if the preview is not in the DB.
287 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700288 @Thunk Bitmap readFromDb(WidgetCacheKey key, Bitmap recycle, PreviewLoadTask loadTask) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700289 Cursor cursor = null;
290 try {
291 cursor = mDb.getReadableDatabase().query(
292 CacheDb.TABLE_NAME,
293 new String[] { CacheDb.COLUMN_PREVIEW_BITMAP },
294 CacheDb.COLUMN_COMPONENT + " = ? AND " + CacheDb.COLUMN_USER + " = ? AND " + CacheDb.COLUMN_SIZE + " = ?",
295 new String[] {
296 key.componentName.flattenToString(),
297 Long.toString(mUserManager.getSerialNumberForUser(key.user)),
298 key.size
299 },
300 null, null, null);
Winson Chung05304db2015-05-18 16:53:20 -0700301 // If cancelled, skip getting the blob and decoding it into a bitmap
302 if (loadTask.isCancelled()) {
303 return null;
304 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700305 if (cursor.moveToNext()) {
306 byte[] blob = cursor.getBlob(0);
307 BitmapFactory.Options opts = new BitmapFactory.Options();
308 opts.inBitmap = recycle;
Michael Jurka6e27f642013-12-10 13:40:30 +0100309 try {
Winson Chung05304db2015-05-18 16:53:20 -0700310 if (!loadTask.isCancelled()) {
311 return BitmapFactory.decodeByteArray(blob, 0, blob.length, opts);
312 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700313 } catch (Exception e) {
314 return null;
Michael Jurka6e27f642013-12-10 13:40:30 +0100315 }
Michael Jurka05713af2013-01-23 12:39:24 +0100316 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700317 } catch (SQLException e) {
318 Log.w(TAG, "Error loading preview from DB", e);
319 } finally {
320 if (cursor != null) {
321 cursor.close();
322 }
323 }
324 return null;
Michael Jurka05713af2013-01-23 12:39:24 +0100325 }
326
Sunny Goyal316490e2015-06-02 09:38:28 -0700327 @Thunk Bitmap generatePreview(Launcher launcher, Object info, Bitmap recycle,
Adam Cohen2e6da152015-05-06 11:42:25 -0700328 int previewWidth, int previewHeight) {
Adam Cohen59400422014-03-05 18:07:04 -0800329 if (info instanceof LauncherAppWidgetProviderInfo) {
Adam Cohen2e6da152015-05-06 11:42:25 -0700330 return generateWidgetPreview(launcher, (LauncherAppWidgetProviderInfo) info,
331 previewWidth, recycle, null);
Michael Jurka05713af2013-01-23 12:39:24 +0100332 } else {
Adam Cohen2e6da152015-05-06 11:42:25 -0700333 return generateShortcutPreview(launcher,
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700334 (ResolveInfo) info, previewWidth, previewHeight, recycle);
Michael Jurka05713af2013-01-23 12:39:24 +0100335 }
336 }
337
Adam Cohen2e6da152015-05-06 11:42:25 -0700338 public Bitmap generateWidgetPreview(Launcher launcher, LauncherAppWidgetProviderInfo info,
Sunny Goyal4cad7532015-03-18 15:56:30 -0700339 int maxPreviewWidth, Bitmap preview, int[] preScaledWidthOut) {
Michael Jurka05713af2013-01-23 12:39:24 +0100340 // Load the preview image if possible
Michael Jurka05713af2013-01-23 12:39:24 +0100341 if (maxPreviewWidth < 0) maxPreviewWidth = Integer.MAX_VALUE;
Michael Jurka05713af2013-01-23 12:39:24 +0100342
343 Drawable drawable = null;
Sunny Goyalffe83f12014-08-14 17:39:34 -0700344 if (info.previewImage != 0) {
345 drawable = mManager.loadPreview(info);
Adrian Roosfa9ffc22014-05-12 15:59:59 +0200346 if (drawable != null) {
347 drawable = mutateOnMainThread(drawable);
348 } else {
Michael Jurka05713af2013-01-23 12:39:24 +0100349 Log.w(TAG, "Can't load widget preview drawable 0x" +
Sunny Goyalffe83f12014-08-14 17:39:34 -0700350 Integer.toHexString(info.previewImage) + " for provider: " + info.provider);
Michael Jurka05713af2013-01-23 12:39:24 +0100351 }
352 }
353
Sunny Goyal4cad7532015-03-18 15:56:30 -0700354 final boolean widgetPreviewExists = (drawable != null);
Sunny Goyal233ee962015-08-03 13:05:01 -0700355 final int spanX = info.spanX;
356 final int spanY = info.spanY;
Sunny Goyal4cad7532015-03-18 15:56:30 -0700357
Michael Jurka05713af2013-01-23 12:39:24 +0100358 int previewWidth;
359 int previewHeight;
Sunny Goyal4cad7532015-03-18 15:56:30 -0700360 Bitmap tileBitmap = null;
361
Michael Jurka05713af2013-01-23 12:39:24 +0100362 if (widgetPreviewExists) {
363 previewWidth = drawable.getIntrinsicWidth();
364 previewHeight = drawable.getIntrinsicHeight();
365 } else {
366 // Generate a preview image if we couldn't load one
Sunny Goyal4cad7532015-03-18 15:56:30 -0700367 tileBitmap = ((BitmapDrawable) mContext.getResources().getDrawable(
368 R.drawable.widget_tile)).getBitmap();
369 previewWidth = tileBitmap.getWidth() * spanX;
370 previewHeight = tileBitmap.getHeight() * spanY;
Michael Jurka05713af2013-01-23 12:39:24 +0100371 }
372
373 // Scale to fit width only - let the widget preview be clipped in the
374 // vertical dimension
375 float scale = 1f;
376 if (preScaledWidthOut != null) {
377 preScaledWidthOut[0] = previewWidth;
378 }
379 if (previewWidth > maxPreviewWidth) {
Hyunyoung Songb9f932e2015-07-30 15:04:59 -0700380 scale = (maxPreviewWidth - 2 * mProfileBadgeMargin) / (float) (previewWidth);
Michael Jurka05713af2013-01-23 12:39:24 +0100381 }
382 if (scale != 1f) {
383 previewWidth = (int) (scale * previewWidth);
384 previewHeight = (int) (scale * previewHeight);
385 }
386
387 // 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 -0700388 final Canvas c = new Canvas();
Michael Jurka05713af2013-01-23 12:39:24 +0100389 if (preview == null) {
390 preview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700391 c.setBitmap(preview);
392 } else {
393 // Reusing bitmap. Clear it.
394 c.setBitmap(preview);
395 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100396 }
397
398 // Draw the scaled preview into the final bitmap
Hyunyoung Songb9f932e2015-07-30 15:04:59 -0700399 int x = (preview.getWidth() - previewWidth) / 2;
Michael Jurka05713af2013-01-23 12:39:24 +0100400 if (widgetPreviewExists) {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700401 drawable.setBounds(x, 0, x + previewWidth, previewHeight);
402 drawable.draw(c);
Michael Jurka05713af2013-01-23 12:39:24 +0100403 } else {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700404 final Paint p = new Paint();
405 p.setFilterBitmap(true);
Adam Cohen2e6da152015-05-06 11:42:25 -0700406 int appIconSize = launcher.getDeviceProfile().iconSizePx;
Michael Jurka05713af2013-01-23 12:39:24 +0100407
Sunny Goyal4cad7532015-03-18 15:56:30 -0700408 // draw the spanX x spanY tiles
409 final Rect src = new Rect(0, 0, tileBitmap.getWidth(), tileBitmap.getHeight());
410
411 float tileW = scale * tileBitmap.getWidth();
412 float tileH = scale * tileBitmap.getHeight();
413 final RectF dst = new RectF(0, 0, tileW, tileH);
414
415 float tx = x;
416 for (int i = 0; i < spanX; i++, tx += tileW) {
417 float ty = 0;
418 for (int j = 0; j < spanY; j++, ty += tileH) {
419 dst.offsetTo(tx, ty);
420 c.drawBitmap(tileBitmap, src, dst, p);
421 }
Michael Jurka05713af2013-01-23 12:39:24 +0100422 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700423
424 // Draw the icon in the top left corner
425 // TODO: use top right for RTL
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700426 int minOffset = (int) (appIconSize * WIDGET_PREVIEW_ICON_PADDING_PERCENTAGE);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700427 int smallestSide = Math.min(previewWidth, previewHeight);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700428 float iconScale = Math.min((float) smallestSide / (appIconSize + 2 * minOffset), scale);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700429
430 try {
Sunny Goyal1ba7e362015-10-26 10:42:12 -0700431 Drawable icon = mManager.loadIcon(info, mIconCache);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700432 if (icon != null) {
Sunny Goyal1ba7e362015-10-26 10:42:12 -0700433 icon = mutateOnMainThread(icon);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700434 int hoffset = (int) ((tileW - appIconSize * iconScale) / 2) + x;
435 int yoffset = (int) ((tileH - appIconSize * iconScale) / 2);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700436 icon.setBounds(hoffset, yoffset,
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700437 hoffset + (int) (appIconSize * iconScale),
438 yoffset + (int) (appIconSize * iconScale));
Sunny Goyal4cad7532015-03-18 15:56:30 -0700439 icon.draw(c);
440 }
441 } catch (Resources.NotFoundException e) { }
Michael Jurka05713af2013-01-23 12:39:24 +0100442 c.setBitmap(null);
443 }
Hyunyoung Song41e33692015-06-15 12:26:54 -0700444 int imageHeight = Math.min(preview.getHeight(), previewHeight + mProfileBadgeMargin);
445 return mManager.getBadgeBitmap(info, preview, imageHeight);
Michael Jurka05713af2013-01-23 12:39:24 +0100446 }
447
448 private Bitmap generateShortcutPreview(
Adam Cohen2e6da152015-05-06 11:42:25 -0700449 Launcher launcher, ResolveInfo info, int maxWidth, int maxHeight, Bitmap preview) {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700450 final Canvas c = new Canvas();
451 if (preview == null) {
Michael Jurka05713af2013-01-23 12:39:24 +0100452 preview = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700453 c.setBitmap(preview);
454 } else if (preview.getWidth() != maxWidth || preview.getHeight() != maxHeight) {
455 throw new RuntimeException("Improperly sized bitmap passed as argument");
456 } else {
457 // Reusing bitmap. Clear it.
458 c.setBitmap(preview);
459 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100460 }
461
Sunny Goyal4cad7532015-03-18 15:56:30 -0700462 Drawable icon = mutateOnMainThread(mIconCache.getFullResIcon(info.activityInfo));
463 icon.setFilterBitmap(true);
464
Michael Jurka05713af2013-01-23 12:39:24 +0100465 // Draw a desaturated/scaled version of the icon in the background as a watermark
Sunny Goyal4cad7532015-03-18 15:56:30 -0700466 ColorMatrix colorMatrix = new ColorMatrix();
467 colorMatrix.setSaturation(0);
468 icon.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
469 icon.setAlpha((int) (255 * 0.06f));
470
471 Resources res = mContext.getResources();
472 int paddingTop = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_top);
473 int paddingLeft = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_left);
474 int paddingRight = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_right);
475 int scaledIconWidth = (maxWidth - paddingLeft - paddingRight);
476 icon.setBounds(paddingLeft, paddingTop,
477 paddingLeft + scaledIconWidth, paddingTop + scaledIconWidth);
478 icon.draw(c);
479
480 // Draw the final icon at top left corner.
481 // TODO: use top right for RTL
Adam Cohen2e6da152015-05-06 11:42:25 -0700482 int appIconSize = launcher.getDeviceProfile().iconSizePx;
483
Sunny Goyal4cad7532015-03-18 15:56:30 -0700484 icon.setAlpha(255);
485 icon.setColorFilter(null);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700486 icon.setBounds(0, 0, appIconSize, appIconSize);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700487 icon.draw(c);
488
Michael Jurka05713af2013-01-23 12:39:24 +0100489 c.setBitmap(null);
Michael Jurka05713af2013-01-23 12:39:24 +0100490 return preview;
491 }
492
Adrian Roos65d60e22014-04-15 21:07:49 +0200493 private Drawable mutateOnMainThread(final Drawable drawable) {
494 try {
495 return mMainThreadExecutor.submit(new Callable<Drawable>() {
496 @Override
497 public Drawable call() throws Exception {
498 return drawable.mutate();
499 }
500 }).get();
501 } catch (InterruptedException e) {
502 Thread.currentThread().interrupt();
503 throw new RuntimeException(e);
504 } catch (ExecutionException e) {
505 throw new RuntimeException(e);
506 }
507 }
Adrian Roos1f375ab2014-04-28 18:26:38 +0200508
Adrian Roos1f375ab2014-04-28 18:26:38 +0200509 /**
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700510 * @return an array of containing versionCode and lastUpdatedTime for the package.
Adrian Roos1f375ab2014-04-28 18:26:38 +0200511 */
Sunny Goyal316490e2015-06-02 09:38:28 -0700512 @Thunk long[] getPackageVersion(String packageName) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700513 synchronized (mPackageVersions) {
514 long[] versions = mPackageVersions.get(packageName);
515 if (versions == null) {
516 versions = new long[2];
Adrian Roos1f375ab2014-04-28 18:26:38 +0200517 try {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700518 PackageInfo info = mContext.getPackageManager().getPackageInfo(packageName, 0);
519 versions[0] = info.versionCode;
520 versions[1] = info.lastUpdateTime;
521 } catch (NameNotFoundException e) {
522 Log.e(TAG, "PackageInfo not found", e);
523 }
524 mPackageVersions.put(packageName, versions);
525 }
526 return versions;
527 }
528 }
529
530 /**
531 * A request Id which can be used by the client to cancel any request.
532 */
533 public class PreviewLoadRequest {
534
Sunny Goyalb4cbea42015-06-16 15:10:36 -0700535 @Thunk final PreviewLoadTask mTask;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700536
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700537 public PreviewLoadRequest(PreviewLoadTask task) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700538 mTask = task;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700539 }
540
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700541 public void cleanup() {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700542 if (mTask != null) {
543 mTask.cancel(true);
544 }
545
Winson Chung05304db2015-05-18 16:53:20 -0700546 // This only handles the case where the PreviewLoadTask is cancelled after the task has
547 // successfully completed (including having written to disk when necessary). In the
548 // other cases where it is cancelled while the task is running, it will be cleaned up
549 // in the tasks's onCancelled() call, and if cancelled while the task is writing to
550 // disk, it will be cancelled in the task's onPostExecute() call.
551 if (mTask.mBitmapToRecycle != null) {
Hyunyoung Songe98f4a42015-06-16 10:45:24 -0700552 mWorkerHandler.post(new Runnable() {
553 @Override
554 public void run() {
555 synchronized (mUnusedBitmaps) {
556 mUnusedBitmaps.add(mTask.mBitmapToRecycle);
557 }
558 mTask.mBitmapToRecycle = null;
559 }
560 });
Adrian Roos1f375ab2014-04-28 18:26:38 +0200561 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700562 }
563 }
564
565 public class PreviewLoadTask extends AsyncTask<Void, Void, Bitmap> {
Sunny Goyal316490e2015-06-02 09:38:28 -0700566 @Thunk final WidgetCacheKey mKey;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700567 private final Object mInfo;
568 private final int mPreviewHeight;
569 private final int mPreviewWidth;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700570 private final WidgetCell mCaller;
Sunny Goyal316490e2015-06-02 09:38:28 -0700571 @Thunk long[] mVersions;
572 @Thunk Bitmap mBitmapToRecycle;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700573
574 PreviewLoadTask(WidgetCacheKey key, Object info, int previewWidth,
Hyunyoung Song3f471442015-04-08 19:01:34 -0700575 int previewHeight, WidgetCell caller) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700576 mKey = key;
577 mInfo = info;
578 mPreviewHeight = previewHeight;
579 mPreviewWidth = previewWidth;
580 mCaller = caller;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700581 if (DEBUG) {
582 Log.d(TAG, String.format("%s, %s, %d, %d",
583 mKey, mInfo, mPreviewHeight, mPreviewWidth));
584 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700585 }
586
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700587 @Override
588 protected Bitmap doInBackground(Void... params) {
589 Bitmap unusedBitmap = null;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700590
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700591 // If already cancelled before this gets to run in the background, then return early
592 if (isCancelled()) {
593 return null;
594 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700595 synchronized (mUnusedBitmaps) {
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700596 // Check if we can re-use a bitmap
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700597 for (Bitmap candidate : mUnusedBitmaps) {
598 if (candidate != null && candidate.isMutable() &&
599 candidate.getWidth() == mPreviewWidth &&
600 candidate.getHeight() == mPreviewHeight) {
601 unusedBitmap = candidate;
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700602 mUnusedBitmaps.remove(unusedBitmap);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700603 break;
604 }
605 }
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700606 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700607
Hyunyoung Songf00d02b2015-06-05 13:30:19 -0700608 // creating a bitmap is expensive. Do not do this inside synchronized block.
609 if (unusedBitmap == null) {
610 unusedBitmap = Bitmap.createBitmap(mPreviewWidth, mPreviewHeight, Config.ARGB_8888);
Adrian Roos1f375ab2014-04-28 18:26:38 +0200611 }
Winson Chung05304db2015-05-18 16:53:20 -0700612 // If cancelled now, don't bother reading the preview from the DB
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700613 if (isCancelled()) {
Winson Chung05304db2015-05-18 16:53:20 -0700614 return unusedBitmap;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700615 }
Winson Chung05304db2015-05-18 16:53:20 -0700616 Bitmap preview = readFromDb(mKey, unusedBitmap, this);
617 // Only consider generating the preview if we have not cancelled the task already
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700618 if (!isCancelled() && preview == null) {
619 // Fetch the version info before we generate the preview, so that, in-case the
620 // app was updated while we are generating the preview, we use the old version info,
621 // which would gets re-written next time.
Winson Chung05304db2015-05-18 16:53:20 -0700622 mVersions = getPackageVersion(mKey.componentName.getPackageName());
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700623
Adam Cohen2e6da152015-05-06 11:42:25 -0700624 Launcher launcher = (Launcher) mCaller.getContext();
625
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700626 // it's not in the db... we need to generate it
Adam Cohen2e6da152015-05-06 11:42:25 -0700627 preview = generatePreview(launcher, mInfo, unusedBitmap, mPreviewWidth, mPreviewHeight);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700628 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700629 return preview;
630 }
631
632 @Override
Winson Chung05304db2015-05-18 16:53:20 -0700633 protected void onPostExecute(final Bitmap preview) {
634 mCaller.applyPreview(preview);
635
636 // Write the generated preview to the DB in the worker thread
637 if (mVersions != null) {
638 mWorkerHandler.post(new Runnable() {
639 @Override
640 public void run() {
641 if (!isCancelled()) {
642 // If we are still using this preview, then write it to the DB and then
643 // let the normal clear mechanism recycle the bitmap
644 writeToDb(mKey, mVersions, preview);
645 mBitmapToRecycle = preview;
646 } else {
647 // If we've already cancelled, then skip writing the bitmap to the DB
648 // and manually add the bitmap back to the recycled set
649 synchronized (mUnusedBitmaps) {
650 mUnusedBitmaps.add(preview);
651 }
652 }
653 }
654 });
655 } else {
656 // If we don't need to write to disk, then ensure the preview gets recycled by
657 // the normal clear mechanism
658 mBitmapToRecycle = preview;
659 }
660 }
661
662 @Override
Hyunyoung Songe98f4a42015-06-16 10:45:24 -0700663 protected void onCancelled(final Bitmap preview) {
Winson Chung05304db2015-05-18 16:53:20 -0700664 // If we've cancelled while the task is running, then can return the bitmap to the
665 // recycled set immediately. Otherwise, it will be recycled after the preview is written
666 // to disk.
667 if (preview != null) {
Hyunyoung Songe98f4a42015-06-16 10:45:24 -0700668 mWorkerHandler.post(new Runnable() {
669 @Override
670 public void run() {
671 synchronized (mUnusedBitmaps) {
672 mUnusedBitmaps.add(preview);
673 }
674 }
675 });
Winson Chung05304db2015-05-18 16:53:20 -0700676 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700677 }
678 }
679
680 private static final class WidgetCacheKey extends ComponentKey {
681
682 // TODO: remove dependency on size
Sunny Goyal316490e2015-06-02 09:38:28 -0700683 @Thunk final String size;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700684
685 public WidgetCacheKey(ComponentName componentName, UserHandleCompat user, String size) {
686 super(componentName, user);
687 this.size = size;
688 }
689
690 @Override
691 public int hashCode() {
692 return super.hashCode() ^ size.hashCode();
693 }
694
695 @Override
696 public boolean equals(Object o) {
697 return super.equals(o) && ((WidgetCacheKey) o).size.equals(size);
Adrian Roos1f375ab2014-04-28 18:26:38 +0200698 }
699 }
Michael Jurka05713af2013-01-23 12:39:24 +0100700}