blob: 5c3ed9272a555730b982d1d4f3d5347c58106db9 [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;
27import android.util.Log;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070028import android.util.LongSparseArray;
Sunny Goyal4cad7532015-03-18 15:56:30 -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;
Adam Cohen091440a2015-03-18 14:16:05 -070034import com.android.launcher3.util.Thunk;
Hyunyoung Song3f471442015-04-08 19:01:34 -070035import com.android.launcher3.widget.WidgetCell;
Sunny Goyalffe83f12014-08-14 17:39:34 -070036
Michael Jurka05713af2013-01-23 12:39:24 +010037import java.lang.ref.WeakReference;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070038import java.util.Collections;
Michael Jurka05713af2013-01-23 12:39:24 +010039import java.util.HashMap;
40import java.util.HashSet;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070041import java.util.Set;
42import java.util.WeakHashMap;
Adrian Roos65d60e22014-04-15 21:07:49 +020043import java.util.concurrent.Callable;
44import java.util.concurrent.ExecutionException;
Michael Jurka05713af2013-01-23 12:39:24 +010045
Sunny Goyalffe83f12014-08-14 17:39:34 -070046public class WidgetPreviewLoader {
Michael Jurka05713af2013-01-23 12:39:24 +010047
Sunny Goyalffe83f12014-08-14 17:39:34 -070048 private static final String TAG = "WidgetPreviewLoader";
Hyunyoung Song3f471442015-04-08 19:01:34 -070049 private static final boolean DEBUG = false;
Sunny Goyalffe83f12014-08-14 17:39:34 -070050
51 private static final float WIDGET_PREVIEW_ICON_PADDING_PERCENTAGE = 0.25f;
Sunny Goyalffe83f12014-08-14 17:39:34 -070052
Sunny Goyal5b0e6692015-03-19 14:31:19 -070053 private final HashMap<String, long[]> mPackageVersions = new HashMap<>();
54 private final HashMap<WidgetCacheKey, WeakReference<Bitmap>> mLoadedPreviews = new HashMap<>();
55 private Set<Bitmap> mUnusedBitmaps = Collections.newSetFromMap(new WeakHashMap<Bitmap, Boolean>());
Sunny Goyal4cad7532015-03-18 15:56:30 -070056
57 private final Context mContext;
Sunny Goyalffe83f12014-08-14 17:39:34 -070058 private final IconCache mIconCache;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070059 private final UserManagerCompat mUserManager;
Sunny Goyalffe83f12014-08-14 17:39:34 -070060 private final AppWidgetManagerCompat mManager;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070061 private final CacheDb mDb;
Michael Jurka05713af2013-01-23 12:39:24 +010062
Adrian Roos65d60e22014-04-15 21:07:49 +020063 private final MainThreadExecutor mMainThreadExecutor = new MainThreadExecutor();
64
Sunny Goyal5b0e6692015-03-19 14:31:19 -070065 public WidgetPreviewLoader(Context context, IconCache iconCache) {
Chris Wrenfd13c712013-09-27 15:45:19 -040066 mContext = context;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070067 mIconCache = iconCache;
Sunny Goyalffe83f12014-08-14 17:39:34 -070068 mManager = AppWidgetManagerCompat.getInstance(context);
Sunny Goyal5b0e6692015-03-19 14:31:19 -070069 mUserManager = UserManagerCompat.getInstance(context);
70 mDb = new CacheDb(context);
Michael Jurka3f4e0702013-02-05 11:21:28 +010071 }
Sunny Goyalffe83f12014-08-14 17:39:34 -070072
Sunny Goyal5b0e6692015-03-19 14:31:19 -070073 /**
74 * Generates the widget preview on {@link AsyncTask#THREAD_POOL_EXECUTOR}. Must be
75 * called on UI thread
76 *
77 * @param o either {@link LauncherAppWidgetProviderInfo} or {@link ResolveInfo}
78 * @param immediateResult A bitmap array of size 1. If the result is already cached, it is
79 * set to the final result.
80 * @return a request id which can be used to cancel the request.
81 */
82 public PreviewLoadRequest getPreview(final Object o, int previewWidth, int previewHeight,
Hyunyoung Song3f471442015-04-08 19:01:34 -070083 WidgetCell caller, Bitmap[] immediateResult) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -070084 String size = previewWidth + "x" + previewHeight;
85 WidgetCacheKey key = getObjectKey(o, size);
Michael Jurka3f4e0702013-02-05 11:21:28 +010086
Sunny Goyal5b0e6692015-03-19 14:31:19 -070087 // Check if we have the preview loaded or not.
Michael Jurka5140cfa2013-02-15 14:50:15 +010088 synchronized (mLoadedPreviews) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -070089 WeakReference<Bitmap> ref = mLoadedPreviews.get(key);
90 if (ref != null && ref.get() != null) {
91 immediateResult[0] = ref.get();
92 return new PreviewLoadRequest(null, key);
Michael Jurka05713af2013-01-23 12:39:24 +010093 }
94 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -070095
96 PreviewLoadTask task = new PreviewLoadTask(key, o, previewWidth, previewHeight, caller);
97 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
98 return new PreviewLoadRequest(task, key);
Michael Jurka05713af2013-01-23 12:39:24 +010099 }
100
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700101 /**
102 * The DB holds the generated previews for various components. Previews can also have different
103 * sizes (landscape vs portrait).
104 */
105 private static class CacheDb extends SQLiteOpenHelper {
106 private static final int DB_VERSION = 3;
107
108 private static final String TABLE_NAME = "shortcut_and_widget_previews";
109 private static final String COLUMN_COMPONENT = "componentName";
110 private static final String COLUMN_USER = "profileId";
111 private static final String COLUMN_SIZE = "size";
112 private static final String COLUMN_PACKAGE = "packageName";
113 private static final String COLUMN_LAST_UPDATED = "lastUpdated";
114 private static final String COLUMN_VERSION = "version";
115 private static final String COLUMN_PREVIEW_BITMAP = "preview_bitmap";
Michael Jurka05713af2013-01-23 12:39:24 +0100116
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100117 public CacheDb(Context context) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700118 super(context, LauncherFiles.WIDGET_PREVIEWS_DB, null, DB_VERSION);
Michael Jurka05713af2013-01-23 12:39:24 +0100119 }
120
121 @Override
122 public void onCreate(SQLiteDatabase database) {
Michael Jurka32b7a092013-02-07 20:06:49 +0100123 database.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" +
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700124 COLUMN_COMPONENT + " TEXT NOT NULL, " +
125 COLUMN_USER + " INTEGER NOT NULL, " +
Michael Jurka05713af2013-01-23 12:39:24 +0100126 COLUMN_SIZE + " TEXT NOT NULL, " +
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700127 COLUMN_PACKAGE + " TEXT NOT NULL, " +
128 COLUMN_LAST_UPDATED + " INTEGER NOT NULL DEFAULT 0, " +
129 COLUMN_VERSION + " INTEGER NOT NULL DEFAULT 0, " +
130 COLUMN_PREVIEW_BITMAP + " BLOB, " +
131 "PRIMARY KEY (" + COLUMN_COMPONENT + ", " + COLUMN_USER + ", " + COLUMN_SIZE + ") " +
Michael Jurka32b7a092013-02-07 20:06:49 +0100132 ");");
Michael Jurka05713af2013-01-23 12:39:24 +0100133 }
134
135 @Override
136 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Michael Jurkae5919c52013-03-06 17:30:10 +0100137 if (oldVersion != newVersion) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700138 clearDB(db);
Michael Jurkae5919c52013-03-06 17:30:10 +0100139 }
Michael Jurka05713af2013-01-23 12:39:24 +0100140 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700141
142 @Override
143 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
144 if (oldVersion != newVersion) {
145 clearDB(db);
146 }
147 }
148
149 private void clearDB(SQLiteDatabase db) {
150 db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
151 onCreate(db);
152 }
Michael Jurka05713af2013-01-23 12:39:24 +0100153 }
154
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700155 private WidgetCacheKey getObjectKey(Object o, String size) {
Michael Jurka05713af2013-01-23 12:39:24 +0100156 // should cache the string builder
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700157 if (o instanceof LauncherAppWidgetProviderInfo) {
158 LauncherAppWidgetProviderInfo info = (LauncherAppWidgetProviderInfo) o;
159 return new WidgetCacheKey(info.provider, mManager.getUser(info), size);
Michael Jurka05713af2013-01-23 12:39:24 +0100160 } else {
161 ResolveInfo info = (ResolveInfo) o;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700162 return new WidgetCacheKey(
163 new ComponentName(info.activityInfo.packageName, info.activityInfo.name),
164 UserHandleCompat.myUserHandle(), size);
Michael Jurka05713af2013-01-23 12:39:24 +0100165 }
166 }
167
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700168 @Thunk void writeToDb(WidgetCacheKey key, long[] versions, Bitmap preview) {
Michael Jurka05713af2013-01-23 12:39:24 +0100169 ContentValues values = new ContentValues();
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700170 values.put(CacheDb.COLUMN_COMPONENT, key.componentName.flattenToShortString());
171 values.put(CacheDb.COLUMN_USER, mUserManager.getSerialNumberForUser(key.user));
172 values.put(CacheDb.COLUMN_SIZE, key.size);
173 values.put(CacheDb.COLUMN_PACKAGE, key.componentName.getPackageName());
174 values.put(CacheDb.COLUMN_VERSION, versions[0]);
175 values.put(CacheDb.COLUMN_LAST_UPDATED, versions[1]);
176 values.put(CacheDb.COLUMN_PREVIEW_BITMAP, Utilities.flattenBitmap(preview));
Michael Jurka05713af2013-01-23 12:39:24 +0100177
Michael Jurka6e27f642013-12-10 13:40:30 +0100178 try {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700179 mDb.getWritableDatabase().insertWithOnConflict(CacheDb.TABLE_NAME, null, values,
180 SQLiteDatabase.CONFLICT_REPLACE);
181 } catch (SQLException e) {
182 Log.e(TAG, "Error saving image to DB", e);
Michael Jurka6e27f642013-12-10 13:40:30 +0100183 }
Michael Jurka05713af2013-01-23 12:39:24 +0100184 }
185
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700186 public void removePackage(String packageName, UserHandleCompat user) {
187 removePackage(packageName, user, mUserManager.getSerialNumberForUser(user));
188 }
189
190 private void removePackage(String packageName, UserHandleCompat user, long userSerial) {
191 synchronized(mPackageVersions) {
192 mPackageVersions.remove(packageName);
193 }
194
195 synchronized (mLoadedPreviews) {
196 Set<WidgetCacheKey> keysToRemove = new HashSet<>();
197 for (WidgetCacheKey key : mLoadedPreviews.keySet()) {
198 if (key.componentName.getPackageName().equals(packageName) && key.user.equals(user)) {
199 keysToRemove.add(key);
200 }
201 }
202
203 for (WidgetCacheKey key : keysToRemove) {
204 WeakReference<Bitmap> req = mLoadedPreviews.remove(key);
205 if (req != null && req.get() != null) {
206 mUnusedBitmaps.add(req.get());
207 }
208 }
209 }
210
Michael Jurka6e27f642013-12-10 13:40:30 +0100211 try {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700212 mDb.getWritableDatabase().delete(CacheDb.TABLE_NAME,
213 CacheDb.COLUMN_PACKAGE + " = ? AND " + CacheDb.COLUMN_USER + " = ?",
214 new String[] {packageName, Long.toString(userSerial)});
215 } catch (SQLException e) {
216 Log.e(TAG, "Unable to delete items from DB", e);
Michael Jurka6e27f642013-12-10 13:40:30 +0100217 }
Michael Jurka8ff02ca2013-11-01 14:19:27 +0100218 }
219
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700220 /**
221 * Updates the persistent DB:
222 * 1. Any preview generated for an old package version is removed
223 * 2. Any preview for an absent package is removed
224 * This ensures that we remove entries for packages which changed while the launcher was dead.
225 */
226 public void removeObsoletePreviews() {
227 LongSparseArray<UserHandleCompat> userIdCache = new LongSparseArray<>();
228 LongSparseArray<HashSet<String>> validPackages = new LongSparseArray<>();
229
230 for (Object obj : LauncherModel.getSortedWidgetsAndShortcuts(mContext, false)) {
231 final UserHandleCompat user;
232 final String pkg;
233 if (obj instanceof ResolveInfo) {
234 user = UserHandleCompat.myUserHandle();
235 pkg = ((ResolveInfo) obj).activityInfo.packageName;
236 } else {
237 LauncherAppWidgetProviderInfo info = (LauncherAppWidgetProviderInfo) obj;
238 user = mManager.getUser(info);
239 pkg = info.provider.getPackageName();
240 }
241
242 int userIdIndex = userIdCache.indexOfValue(user);
243 final long userId;
244 if (userIdIndex < 0) {
245 userId = mUserManager.getSerialNumberForUser(user);
246 userIdCache.put(userId, user);
247 } else {
248 userId = userIdCache.keyAt(userIdIndex);
249 }
250
251 HashSet<String> packages = validPackages.get(userId);
252 if (packages == null) {
253 packages = new HashSet<>();
254 validPackages.put(userId, packages);
255 }
256 packages.add(pkg);
Michael Jurka05713af2013-01-23 12:39:24 +0100257 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700258
259 LongSparseArray<HashSet<String>> packagesToDelete = new LongSparseArray<>();
260 Cursor c = null;
261 try {
262 c = mDb.getReadableDatabase().query(CacheDb.TABLE_NAME,
263 new String[] {CacheDb.COLUMN_USER, CacheDb.COLUMN_PACKAGE,
264 CacheDb.COLUMN_LAST_UPDATED, CacheDb.COLUMN_VERSION},
265 null, null, null, null, null);
266 while (c.moveToNext()) {
267 long userId = c.getLong(0);
268 String pkg = c.getString(1);
269 long lastUpdated = c.getLong(2);
270 long version = c.getLong(3);
271
272 HashSet<String> packages = validPackages.get(userId);
273 if (packages != null && packages.contains(pkg)) {
274 long[] versions = getPackageVersion(pkg);
275 if (versions[0] == version && versions[1] == lastUpdated) {
276 // Every thing checks out
277 continue;
278 }
279 }
280
281 // We need to delete this package.
282 packages = packagesToDelete.get(userId);
283 if (packages == null) {
284 packages = new HashSet<>();
285 packagesToDelete.put(userId, packages);
286 }
287 packages.add(pkg);
288 }
289
290 for (int i = 0; i < packagesToDelete.size(); i++) {
291 long userId = packagesToDelete.keyAt(i);
292 UserHandleCompat user = mUserManager.getUserForSerialNumber(userId);
293 for (String pkg : packagesToDelete.valueAt(i)) {
294 removePackage(pkg, user, userId);
295 }
296 }
297 } catch (SQLException e) {
298 Log.e(TAG, "Error updatating widget previews", e);
299 } finally {
300 if (c != null) {
301 c.close();
302 }
303 }
304 }
305
306 private Bitmap readFromDb(WidgetCacheKey key, Bitmap recycle) {
307 Cursor cursor = null;
308 try {
309 cursor = mDb.getReadableDatabase().query(
310 CacheDb.TABLE_NAME,
311 new String[] { CacheDb.COLUMN_PREVIEW_BITMAP },
312 CacheDb.COLUMN_COMPONENT + " = ? AND " + CacheDb.COLUMN_USER + " = ? AND " + CacheDb.COLUMN_SIZE + " = ?",
313 new String[] {
314 key.componentName.flattenToString(),
315 Long.toString(mUserManager.getSerialNumberForUser(key.user)),
316 key.size
317 },
318 null, null, null);
319 if (cursor.moveToNext()) {
320 byte[] blob = cursor.getBlob(0);
321 BitmapFactory.Options opts = new BitmapFactory.Options();
322 opts.inBitmap = recycle;
Michael Jurka6e27f642013-12-10 13:40:30 +0100323 try {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700324 return BitmapFactory.decodeByteArray(blob, 0, blob.length, opts);
325 } catch (Exception e) {
326 return null;
Michael Jurka6e27f642013-12-10 13:40:30 +0100327 }
Michael Jurka05713af2013-01-23 12:39:24 +0100328 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700329 } catch (SQLException e) {
330 Log.w(TAG, "Error loading preview from DB", e);
331 } finally {
332 if (cursor != null) {
333 cursor.close();
334 }
335 }
336 return null;
Michael Jurka05713af2013-01-23 12:39:24 +0100337 }
338
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700339 private Bitmap generatePreview(Object info, Bitmap recycle, int previewWidth, int previewHeight) {
Adam Cohen59400422014-03-05 18:07:04 -0800340 if (info instanceof LauncherAppWidgetProviderInfo) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700341 return generateWidgetPreview((LauncherAppWidgetProviderInfo) info, previewWidth, recycle);
Michael Jurka05713af2013-01-23 12:39:24 +0100342 } else {
343 return generateShortcutPreview(
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700344 (ResolveInfo) info, previewWidth, previewHeight, recycle);
Michael Jurka05713af2013-01-23 12:39:24 +0100345 }
346 }
347
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700348 public Bitmap generateWidgetPreview(LauncherAppWidgetProviderInfo info,
349 int previewWidth, Bitmap preview) {
350 int maxWidth = Math.min(previewWidth, info.spanX
351 * LauncherAppState.getInstance().getDynamicGrid().getDeviceProfile().cellWidthPx);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700352 return generateWidgetPreview(info, maxWidth, preview, null);
Michael Jurka05713af2013-01-23 12:39:24 +0100353 }
354
Sunny Goyal4cad7532015-03-18 15:56:30 -0700355 public Bitmap generateWidgetPreview(LauncherAppWidgetProviderInfo info,
356 int maxPreviewWidth, Bitmap preview, int[] preScaledWidthOut) {
Michael Jurka05713af2013-01-23 12:39:24 +0100357 // Load the preview image if possible
Michael Jurka05713af2013-01-23 12:39:24 +0100358 if (maxPreviewWidth < 0) maxPreviewWidth = Integer.MAX_VALUE;
Michael Jurka05713af2013-01-23 12:39:24 +0100359
360 Drawable drawable = null;
Sunny Goyalffe83f12014-08-14 17:39:34 -0700361 if (info.previewImage != 0) {
362 drawable = mManager.loadPreview(info);
Adrian Roosfa9ffc22014-05-12 15:59:59 +0200363 if (drawable != null) {
364 drawable = mutateOnMainThread(drawable);
365 } else {
Michael Jurka05713af2013-01-23 12:39:24 +0100366 Log.w(TAG, "Can't load widget preview drawable 0x" +
Sunny Goyalffe83f12014-08-14 17:39:34 -0700367 Integer.toHexString(info.previewImage) + " for provider: " + info.provider);
Michael Jurka05713af2013-01-23 12:39:24 +0100368 }
369 }
370
Sunny Goyal4cad7532015-03-18 15:56:30 -0700371 final boolean widgetPreviewExists = (drawable != null);
372 final int spanX = info.spanX < 1 ? 1 : info.spanX;
373 final int spanY = info.spanY < 1 ? 1 : info.spanY;
374
Michael Jurka05713af2013-01-23 12:39:24 +0100375 int previewWidth;
376 int previewHeight;
Sunny Goyal4cad7532015-03-18 15:56:30 -0700377 Bitmap tileBitmap = null;
378
Michael Jurka05713af2013-01-23 12:39:24 +0100379 if (widgetPreviewExists) {
380 previewWidth = drawable.getIntrinsicWidth();
381 previewHeight = drawable.getIntrinsicHeight();
382 } else {
383 // Generate a preview image if we couldn't load one
Sunny Goyal4cad7532015-03-18 15:56:30 -0700384 tileBitmap = ((BitmapDrawable) mContext.getResources().getDrawable(
385 R.drawable.widget_tile)).getBitmap();
386 previewWidth = tileBitmap.getWidth() * spanX;
387 previewHeight = tileBitmap.getHeight() * spanY;
Michael Jurka05713af2013-01-23 12:39:24 +0100388 }
389
390 // Scale to fit width only - let the widget preview be clipped in the
391 // vertical dimension
392 float scale = 1f;
393 if (preScaledWidthOut != null) {
394 preScaledWidthOut[0] = previewWidth;
395 }
396 if (previewWidth > maxPreviewWidth) {
397 scale = maxPreviewWidth / (float) previewWidth;
398 }
399 if (scale != 1f) {
400 previewWidth = (int) (scale * previewWidth);
401 previewHeight = (int) (scale * previewHeight);
402 }
403
404 // 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 -0700405 final Canvas c = new Canvas();
Michael Jurka05713af2013-01-23 12:39:24 +0100406 if (preview == null) {
407 preview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700408 c.setBitmap(preview);
409 } else {
410 // Reusing bitmap. Clear it.
411 c.setBitmap(preview);
412 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100413 }
414
415 // Draw the scaled preview into the final bitmap
416 int x = (preview.getWidth() - previewWidth) / 2;
417 if (widgetPreviewExists) {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700418 drawable.setBounds(x, 0, x + previewWidth, previewHeight);
419 drawable.draw(c);
Michael Jurka05713af2013-01-23 12:39:24 +0100420 } else {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700421 final Paint p = new Paint();
422 p.setFilterBitmap(true);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700423 int appIconSize = LauncherAppState.getInstance().getDynamicGrid()
424 .getDeviceProfile().iconSizePx;
Michael Jurka05713af2013-01-23 12:39:24 +0100425
Sunny Goyal4cad7532015-03-18 15:56:30 -0700426 // draw the spanX x spanY tiles
427 final Rect src = new Rect(0, 0, tileBitmap.getWidth(), tileBitmap.getHeight());
428
429 float tileW = scale * tileBitmap.getWidth();
430 float tileH = scale * tileBitmap.getHeight();
431 final RectF dst = new RectF(0, 0, tileW, tileH);
432
433 float tx = x;
434 for (int i = 0; i < spanX; i++, tx += tileW) {
435 float ty = 0;
436 for (int j = 0; j < spanY; j++, ty += tileH) {
437 dst.offsetTo(tx, ty);
438 c.drawBitmap(tileBitmap, src, dst, p);
439 }
Michael Jurka05713af2013-01-23 12:39:24 +0100440 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700441
442 // Draw the icon in the top left corner
443 // TODO: use top right for RTL
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700444 int minOffset = (int) (appIconSize * WIDGET_PREVIEW_ICON_PADDING_PERCENTAGE);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700445 int smallestSide = Math.min(previewWidth, previewHeight);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700446 float iconScale = Math.min((float) smallestSide / (appIconSize + 2 * minOffset), scale);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700447
448 try {
449 Drawable icon = mutateOnMainThread(mManager.loadIcon(info, mIconCache));
450 if (icon != null) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700451 int hoffset = (int) ((tileW - appIconSize * iconScale) / 2) + x;
452 int yoffset = (int) ((tileH - appIconSize * iconScale) / 2);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700453 icon.setBounds(hoffset, yoffset,
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700454 hoffset + (int) (appIconSize * iconScale),
455 yoffset + (int) (appIconSize * iconScale));
Sunny Goyal4cad7532015-03-18 15:56:30 -0700456 icon.draw(c);
457 }
458 } catch (Resources.NotFoundException e) { }
Michael Jurka05713af2013-01-23 12:39:24 +0100459 c.setBitmap(null);
460 }
Sunny Goyalffe83f12014-08-14 17:39:34 -0700461 return mManager.getBadgeBitmap(info, preview);
Michael Jurka05713af2013-01-23 12:39:24 +0100462 }
463
464 private Bitmap generateShortcutPreview(
465 ResolveInfo info, int maxWidth, int maxHeight, Bitmap preview) {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700466 final Canvas c = new Canvas();
467 if (preview == null) {
Michael Jurka05713af2013-01-23 12:39:24 +0100468 preview = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700469 c.setBitmap(preview);
470 } else if (preview.getWidth() != maxWidth || preview.getHeight() != maxHeight) {
471 throw new RuntimeException("Improperly sized bitmap passed as argument");
472 } else {
473 // Reusing bitmap. Clear it.
474 c.setBitmap(preview);
475 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100476 }
477
Sunny Goyal4cad7532015-03-18 15:56:30 -0700478 Drawable icon = mutateOnMainThread(mIconCache.getFullResIcon(info.activityInfo));
479 icon.setFilterBitmap(true);
480
Michael Jurka05713af2013-01-23 12:39:24 +0100481 // Draw a desaturated/scaled version of the icon in the background as a watermark
Sunny Goyal4cad7532015-03-18 15:56:30 -0700482 ColorMatrix colorMatrix = new ColorMatrix();
483 colorMatrix.setSaturation(0);
484 icon.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
485 icon.setAlpha((int) (255 * 0.06f));
486
487 Resources res = mContext.getResources();
488 int paddingTop = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_top);
489 int paddingLeft = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_left);
490 int paddingRight = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_right);
491 int scaledIconWidth = (maxWidth - paddingLeft - paddingRight);
492 icon.setBounds(paddingLeft, paddingTop,
493 paddingLeft + scaledIconWidth, paddingTop + scaledIconWidth);
494 icon.draw(c);
495
496 // Draw the final icon at top left corner.
497 // TODO: use top right for RTL
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700498 int appIconSize = LauncherAppState.getInstance().getDynamicGrid()
499 .getDeviceProfile().iconSizePx;
Sunny Goyal4cad7532015-03-18 15:56:30 -0700500 icon.setAlpha(255);
501 icon.setColorFilter(null);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700502 icon.setBounds(0, 0, appIconSize, appIconSize);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700503 icon.draw(c);
504
Michael Jurka05713af2013-01-23 12:39:24 +0100505 c.setBitmap(null);
Michael Jurka05713af2013-01-23 12:39:24 +0100506 return preview;
507 }
508
Adrian Roos65d60e22014-04-15 21:07:49 +0200509 private Drawable mutateOnMainThread(final Drawable drawable) {
510 try {
511 return mMainThreadExecutor.submit(new Callable<Drawable>() {
512 @Override
513 public Drawable call() throws Exception {
514 return drawable.mutate();
515 }
516 }).get();
517 } catch (InterruptedException e) {
518 Thread.currentThread().interrupt();
519 throw new RuntimeException(e);
520 } catch (ExecutionException e) {
521 throw new RuntimeException(e);
522 }
523 }
Adrian Roos1f375ab2014-04-28 18:26:38 +0200524
Adrian Roos1f375ab2014-04-28 18:26:38 +0200525 /**
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700526 * @return an array of containing versionCode and lastUpdatedTime for the package.
Adrian Roos1f375ab2014-04-28 18:26:38 +0200527 */
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700528 private long[] getPackageVersion(String packageName) {
529 synchronized (mPackageVersions) {
530 long[] versions = mPackageVersions.get(packageName);
531 if (versions == null) {
532 versions = new long[2];
Adrian Roos1f375ab2014-04-28 18:26:38 +0200533 try {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700534 PackageInfo info = mContext.getPackageManager().getPackageInfo(packageName, 0);
535 versions[0] = info.versionCode;
536 versions[1] = info.lastUpdateTime;
537 } catch (NameNotFoundException e) {
538 Log.e(TAG, "PackageInfo not found", e);
539 }
540 mPackageVersions.put(packageName, versions);
541 }
542 return versions;
543 }
544 }
545
546 /**
547 * A request Id which can be used by the client to cancel any request.
548 */
549 public class PreviewLoadRequest {
550
551 private final PreviewLoadTask mTask;
552 private final WidgetCacheKey mKey;
553
554 public PreviewLoadRequest(PreviewLoadTask task, WidgetCacheKey key) {
555 mTask = task;
556 mKey = key;
557 }
558
559 public void cancel(boolean recycleImage) {
560 if (mTask != null) {
561 mTask.cancel(true);
562 }
563
564 if (recycleImage) {
565 synchronized(mLoadedPreviews) {
566 WeakReference<Bitmap> result = mLoadedPreviews.remove(mKey);
567 if (result != null && result.get() != null) {
568 mUnusedBitmaps.add(result.get());
Adrian Roos1f375ab2014-04-28 18:26:38 +0200569 }
Adrian Roos1f375ab2014-04-28 18:26:38 +0200570 }
571 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700572 }
573 }
574
575 public class PreviewLoadTask extends AsyncTask<Void, Void, Bitmap> {
576
577 private final WidgetCacheKey mKey;
578 private final Object mInfo;
579 private final int mPreviewHeight;
580 private final int mPreviewWidth;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700581 private final WidgetCell mCaller;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700582
583 PreviewLoadTask(WidgetCacheKey key, Object info, int previewWidth,
Hyunyoung Song3f471442015-04-08 19:01:34 -0700584 int previewHeight, WidgetCell caller) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700585 mKey = key;
586 mInfo = info;
587 mPreviewHeight = previewHeight;
588 mPreviewWidth = previewWidth;
589 mCaller = caller;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700590 if (DEBUG) {
591 Log.d(TAG, String.format("%s, %s, %d, %d",
592 mKey, mInfo, mPreviewHeight, mPreviewWidth));
593 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700594 }
595
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700596 @Override
597 protected Bitmap doInBackground(Void... params) {
598 Bitmap unusedBitmap = null;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700599
600 // TODO(hyunyoungs): Figure out why this path causes concurrency issue.
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700601 synchronized (mUnusedBitmaps) {
602 // Check if we can use a bitmap
603 for (Bitmap candidate : mUnusedBitmaps) {
604 if (candidate != null && candidate.isMutable() &&
605 candidate.getWidth() == mPreviewWidth &&
606 candidate.getHeight() == mPreviewHeight) {
607 unusedBitmap = candidate;
608 break;
609 }
610 }
611
612 if (unusedBitmap == null) {
613 unusedBitmap = Bitmap.createBitmap(mPreviewWidth, mPreviewHeight, Config.ARGB_8888);
614 } else {
615 mUnusedBitmaps.remove(unusedBitmap);
616 }
Adrian Roos1f375ab2014-04-28 18:26:38 +0200617 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700618 if (isCancelled()) {
619 return null;
620 }
621 Bitmap preview = readFromDb(mKey, unusedBitmap);
622 if (!isCancelled() && preview == null) {
623 // Fetch the version info before we generate the preview, so that, in-case the
624 // app was updated while we are generating the preview, we use the old version info,
625 // which would gets re-written next time.
626 long[] versions = getPackageVersion(mKey.componentName.getPackageName());
627
628 // it's not in the db... we need to generate it
629 preview = generatePreview(mInfo, unusedBitmap, mPreviewWidth, mPreviewHeight);
630
631 if (!isCancelled()) {
632 writeToDb(mKey, versions, preview);
633 }
634 }
635
636 return preview;
637 }
638
639 @Override
640 protected void onPostExecute(Bitmap result) {
641 synchronized(mLoadedPreviews) {
642 mLoadedPreviews.put(mKey, new WeakReference<Bitmap>(result));
643 }
644
645 mCaller.applyPreview(result);
646 }
647 }
648
649 private static final class WidgetCacheKey extends ComponentKey {
650
651 // TODO: remove dependency on size
652 private final String size;
653
654 public WidgetCacheKey(ComponentName componentName, UserHandleCompat user, String size) {
655 super(componentName, user);
656 this.size = size;
657 }
658
659 @Override
660 public int hashCode() {
661 return super.hashCode() ^ size.hashCode();
662 }
663
664 @Override
665 public boolean equals(Object o) {
666 return super.equals(o) && ((WidgetCacheKey) o).size.equals(size);
Adrian Roos1f375ab2014-04-28 18:26:38 +0200667 }
668 }
Michael Jurka05713af2013-01-23 12:39:24 +0100669}