blob: 412cbcd6d535144de218b62a6ea85ec665416f2a [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
Sunny Goyal5b0e6692015-03-19 14:31:19 -070037import java.util.Collections;
Michael Jurka05713af2013-01-23 12:39:24 +010038import java.util.HashMap;
39import java.util.HashSet;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070040import java.util.Set;
41import java.util.WeakHashMap;
Adrian Roos65d60e22014-04-15 21:07:49 +020042import java.util.concurrent.Callable;
43import java.util.concurrent.ExecutionException;
Michael Jurka05713af2013-01-23 12:39:24 +010044
Sunny Goyalffe83f12014-08-14 17:39:34 -070045public class WidgetPreviewLoader {
Michael Jurka05713af2013-01-23 12:39:24 +010046
Sunny Goyalffe83f12014-08-14 17:39:34 -070047 private static final String TAG = "WidgetPreviewLoader";
Hyunyoung Song3f471442015-04-08 19:01:34 -070048 private static final boolean DEBUG = false;
Sunny Goyalffe83f12014-08-14 17:39:34 -070049
50 private static final float WIDGET_PREVIEW_ICON_PADDING_PERCENTAGE = 0.25f;
Sunny Goyalffe83f12014-08-14 17:39:34 -070051
Sunny Goyal5b0e6692015-03-19 14:31:19 -070052 private final HashMap<String, long[]> mPackageVersions = new HashMap<>();
Hyunyoung Song559d90d2015-04-28 15:06:45 -070053
54 /**
55 * Weak reference objects, do not prevent their referents from being made finalizable,
56 * finalized, and then reclaimed.
57 */
58 private Set<Bitmap> mUnusedBitmaps =
59 Collections.newSetFromMap(new WeakHashMap<Bitmap, Boolean>());
Sunny Goyal4cad7532015-03-18 15:56:30 -070060
61 private final Context mContext;
Sunny Goyalffe83f12014-08-14 17:39:34 -070062 private final IconCache mIconCache;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070063 private final UserManagerCompat mUserManager;
Sunny Goyalffe83f12014-08-14 17:39:34 -070064 private final AppWidgetManagerCompat mManager;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070065 private final CacheDb mDb;
Michael Jurka05713af2013-01-23 12:39:24 +010066
Adrian Roos65d60e22014-04-15 21:07:49 +020067 private final MainThreadExecutor mMainThreadExecutor = new MainThreadExecutor();
68
Sunny Goyal5b0e6692015-03-19 14:31:19 -070069 public WidgetPreviewLoader(Context context, IconCache iconCache) {
Chris Wrenfd13c712013-09-27 15:45:19 -040070 mContext = context;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070071 mIconCache = iconCache;
Sunny Goyalffe83f12014-08-14 17:39:34 -070072 mManager = AppWidgetManagerCompat.getInstance(context);
Sunny Goyal5b0e6692015-03-19 14:31:19 -070073 mUserManager = UserManagerCompat.getInstance(context);
74 mDb = new CacheDb(context);
Michael Jurka3f4e0702013-02-05 11:21:28 +010075 }
Sunny Goyalffe83f12014-08-14 17:39:34 -070076
Sunny Goyal5b0e6692015-03-19 14:31:19 -070077 /**
78 * Generates the widget preview on {@link AsyncTask#THREAD_POOL_EXECUTOR}. Must be
79 * called on UI thread
80 *
81 * @param o either {@link LauncherAppWidgetProviderInfo} or {@link ResolveInfo}
82 * @param immediateResult A bitmap array of size 1. If the result is already cached, it is
83 * set to the final result.
84 * @return a request id which can be used to cancel the request.
85 */
86 public PreviewLoadRequest getPreview(final Object o, int previewWidth, int previewHeight,
Hyunyoung Song3f471442015-04-08 19:01:34 -070087 WidgetCell caller, Bitmap[] immediateResult) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -070088 String size = previewWidth + "x" + previewHeight;
89 WidgetCacheKey key = getObjectKey(o, size);
Michael Jurka3f4e0702013-02-05 11:21:28 +010090
Sunny Goyal5b0e6692015-03-19 14:31:19 -070091 PreviewLoadTask task = new PreviewLoadTask(key, o, previewWidth, previewHeight, caller);
92 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
Hyunyoung Song559d90d2015-04-28 15:06:45 -070093 return new PreviewLoadRequest(task);
Michael Jurka05713af2013-01-23 12:39:24 +010094 }
95
Sunny Goyal5b0e6692015-03-19 14:31:19 -070096 /**
97 * The DB holds the generated previews for various components. Previews can also have different
98 * sizes (landscape vs portrait).
99 */
100 private static class CacheDb extends SQLiteOpenHelper {
101 private static final int DB_VERSION = 3;
102
103 private static final String TABLE_NAME = "shortcut_and_widget_previews";
104 private static final String COLUMN_COMPONENT = "componentName";
105 private static final String COLUMN_USER = "profileId";
106 private static final String COLUMN_SIZE = "size";
107 private static final String COLUMN_PACKAGE = "packageName";
108 private static final String COLUMN_LAST_UPDATED = "lastUpdated";
109 private static final String COLUMN_VERSION = "version";
110 private static final String COLUMN_PREVIEW_BITMAP = "preview_bitmap";
Michael Jurka05713af2013-01-23 12:39:24 +0100111
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100112 public CacheDb(Context context) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700113 super(context, LauncherFiles.WIDGET_PREVIEWS_DB, null, DB_VERSION);
Michael Jurka05713af2013-01-23 12:39:24 +0100114 }
115
116 @Override
117 public void onCreate(SQLiteDatabase database) {
Michael Jurka32b7a092013-02-07 20:06:49 +0100118 database.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" +
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700119 COLUMN_COMPONENT + " TEXT NOT NULL, " +
120 COLUMN_USER + " INTEGER NOT NULL, " +
Michael Jurka05713af2013-01-23 12:39:24 +0100121 COLUMN_SIZE + " TEXT NOT NULL, " +
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700122 COLUMN_PACKAGE + " TEXT NOT NULL, " +
123 COLUMN_LAST_UPDATED + " INTEGER NOT NULL DEFAULT 0, " +
124 COLUMN_VERSION + " INTEGER NOT NULL DEFAULT 0, " +
125 COLUMN_PREVIEW_BITMAP + " BLOB, " +
126 "PRIMARY KEY (" + COLUMN_COMPONENT + ", " + COLUMN_USER + ", " + COLUMN_SIZE + ") " +
Michael Jurka32b7a092013-02-07 20:06:49 +0100127 ");");
Michael Jurka05713af2013-01-23 12:39:24 +0100128 }
129
130 @Override
131 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Michael Jurkae5919c52013-03-06 17:30:10 +0100132 if (oldVersion != newVersion) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700133 clearDB(db);
Michael Jurkae5919c52013-03-06 17:30:10 +0100134 }
Michael Jurka05713af2013-01-23 12:39:24 +0100135 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700136
137 @Override
138 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
139 if (oldVersion != newVersion) {
140 clearDB(db);
141 }
142 }
143
144 private void clearDB(SQLiteDatabase db) {
145 db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
146 onCreate(db);
147 }
Michael Jurka05713af2013-01-23 12:39:24 +0100148 }
149
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700150 private WidgetCacheKey getObjectKey(Object o, String size) {
Michael Jurka05713af2013-01-23 12:39:24 +0100151 // should cache the string builder
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700152 if (o instanceof LauncherAppWidgetProviderInfo) {
153 LauncherAppWidgetProviderInfo info = (LauncherAppWidgetProviderInfo) o;
154 return new WidgetCacheKey(info.provider, mManager.getUser(info), size);
Michael Jurka05713af2013-01-23 12:39:24 +0100155 } else {
156 ResolveInfo info = (ResolveInfo) o;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700157 return new WidgetCacheKey(
158 new ComponentName(info.activityInfo.packageName, info.activityInfo.name),
159 UserHandleCompat.myUserHandle(), size);
Michael Jurka05713af2013-01-23 12:39:24 +0100160 }
161 }
162
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700163 @Thunk void writeToDb(WidgetCacheKey key, long[] versions, Bitmap preview) {
Michael Jurka05713af2013-01-23 12:39:24 +0100164 ContentValues values = new ContentValues();
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700165 values.put(CacheDb.COLUMN_COMPONENT, key.componentName.flattenToShortString());
166 values.put(CacheDb.COLUMN_USER, mUserManager.getSerialNumberForUser(key.user));
167 values.put(CacheDb.COLUMN_SIZE, key.size);
168 values.put(CacheDb.COLUMN_PACKAGE, key.componentName.getPackageName());
169 values.put(CacheDb.COLUMN_VERSION, versions[0]);
170 values.put(CacheDb.COLUMN_LAST_UPDATED, versions[1]);
171 values.put(CacheDb.COLUMN_PREVIEW_BITMAP, Utilities.flattenBitmap(preview));
Michael Jurka05713af2013-01-23 12:39:24 +0100172
Michael Jurka6e27f642013-12-10 13:40:30 +0100173 try {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700174 mDb.getWritableDatabase().insertWithOnConflict(CacheDb.TABLE_NAME, null, values,
175 SQLiteDatabase.CONFLICT_REPLACE);
176 } catch (SQLException e) {
177 Log.e(TAG, "Error saving image to DB", e);
Michael Jurka6e27f642013-12-10 13:40:30 +0100178 }
Michael Jurka05713af2013-01-23 12:39:24 +0100179 }
180
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700181 public void removePackage(String packageName, UserHandleCompat user) {
182 removePackage(packageName, user, mUserManager.getSerialNumberForUser(user));
183 }
184
185 private void removePackage(String packageName, UserHandleCompat user, long userSerial) {
186 synchronized(mPackageVersions) {
187 mPackageVersions.remove(packageName);
188 }
189
Michael Jurka6e27f642013-12-10 13:40:30 +0100190 try {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700191 mDb.getWritableDatabase().delete(CacheDb.TABLE_NAME,
192 CacheDb.COLUMN_PACKAGE + " = ? AND " + CacheDb.COLUMN_USER + " = ?",
193 new String[] {packageName, Long.toString(userSerial)});
194 } catch (SQLException e) {
195 Log.e(TAG, "Unable to delete items from DB", e);
Michael Jurka6e27f642013-12-10 13:40:30 +0100196 }
Michael Jurka8ff02ca2013-11-01 14:19:27 +0100197 }
198
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700199 /**
200 * Updates the persistent DB:
201 * 1. Any preview generated for an old package version is removed
202 * 2. Any preview for an absent package is removed
203 * This ensures that we remove entries for packages which changed while the launcher was dead.
204 */
205 public void removeObsoletePreviews() {
206 LongSparseArray<UserHandleCompat> userIdCache = new LongSparseArray<>();
207 LongSparseArray<HashSet<String>> validPackages = new LongSparseArray<>();
208
209 for (Object obj : LauncherModel.getSortedWidgetsAndShortcuts(mContext, false)) {
210 final UserHandleCompat user;
211 final String pkg;
212 if (obj instanceof ResolveInfo) {
213 user = UserHandleCompat.myUserHandle();
214 pkg = ((ResolveInfo) obj).activityInfo.packageName;
215 } else {
216 LauncherAppWidgetProviderInfo info = (LauncherAppWidgetProviderInfo) obj;
217 user = mManager.getUser(info);
218 pkg = info.provider.getPackageName();
219 }
220
221 int userIdIndex = userIdCache.indexOfValue(user);
222 final long userId;
223 if (userIdIndex < 0) {
224 userId = mUserManager.getSerialNumberForUser(user);
225 userIdCache.put(userId, user);
226 } else {
227 userId = userIdCache.keyAt(userIdIndex);
228 }
229
230 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
285 private Bitmap readFromDb(WidgetCacheKey key, Bitmap recycle) {
286 Cursor cursor = null;
287 try {
288 cursor = mDb.getReadableDatabase().query(
289 CacheDb.TABLE_NAME,
290 new String[] { CacheDb.COLUMN_PREVIEW_BITMAP },
291 CacheDb.COLUMN_COMPONENT + " = ? AND " + CacheDb.COLUMN_USER + " = ? AND " + CacheDb.COLUMN_SIZE + " = ?",
292 new String[] {
293 key.componentName.flattenToString(),
294 Long.toString(mUserManager.getSerialNumberForUser(key.user)),
295 key.size
296 },
297 null, null, null);
298 if (cursor.moveToNext()) {
299 byte[] blob = cursor.getBlob(0);
300 BitmapFactory.Options opts = new BitmapFactory.Options();
301 opts.inBitmap = recycle;
Michael Jurka6e27f642013-12-10 13:40:30 +0100302 try {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700303 return BitmapFactory.decodeByteArray(blob, 0, blob.length, opts);
304 } catch (Exception e) {
305 return null;
Michael Jurka6e27f642013-12-10 13:40:30 +0100306 }
Michael Jurka05713af2013-01-23 12:39:24 +0100307 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700308 } catch (SQLException e) {
309 Log.w(TAG, "Error loading preview from DB", e);
310 } finally {
311 if (cursor != null) {
312 cursor.close();
313 }
314 }
315 return null;
Michael Jurka05713af2013-01-23 12:39:24 +0100316 }
317
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700318 private Bitmap generatePreview(Object info, Bitmap recycle, int previewWidth, int previewHeight) {
Adam Cohen59400422014-03-05 18:07:04 -0800319 if (info instanceof LauncherAppWidgetProviderInfo) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700320 return generateWidgetPreview((LauncherAppWidgetProviderInfo) info, previewWidth, recycle);
Michael Jurka05713af2013-01-23 12:39:24 +0100321 } else {
322 return generateShortcutPreview(
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700323 (ResolveInfo) info, previewWidth, previewHeight, recycle);
Michael Jurka05713af2013-01-23 12:39:24 +0100324 }
325 }
326
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700327 public Bitmap generateWidgetPreview(LauncherAppWidgetProviderInfo info,
328 int previewWidth, Bitmap preview) {
329 int maxWidth = Math.min(previewWidth, info.spanX
330 * LauncherAppState.getInstance().getDynamicGrid().getDeviceProfile().cellWidthPx);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700331 return generateWidgetPreview(info, maxWidth, preview, null);
Michael Jurka05713af2013-01-23 12:39:24 +0100332 }
333
Sunny Goyal4cad7532015-03-18 15:56:30 -0700334 public Bitmap generateWidgetPreview(LauncherAppWidgetProviderInfo info,
335 int maxPreviewWidth, Bitmap preview, int[] preScaledWidthOut) {
Michael Jurka05713af2013-01-23 12:39:24 +0100336 // Load the preview image if possible
Michael Jurka05713af2013-01-23 12:39:24 +0100337 if (maxPreviewWidth < 0) maxPreviewWidth = Integer.MAX_VALUE;
Michael Jurka05713af2013-01-23 12:39:24 +0100338
339 Drawable drawable = null;
Sunny Goyalffe83f12014-08-14 17:39:34 -0700340 if (info.previewImage != 0) {
341 drawable = mManager.loadPreview(info);
Adrian Roosfa9ffc22014-05-12 15:59:59 +0200342 if (drawable != null) {
343 drawable = mutateOnMainThread(drawable);
344 } else {
Michael Jurka05713af2013-01-23 12:39:24 +0100345 Log.w(TAG, "Can't load widget preview drawable 0x" +
Sunny Goyalffe83f12014-08-14 17:39:34 -0700346 Integer.toHexString(info.previewImage) + " for provider: " + info.provider);
Michael Jurka05713af2013-01-23 12:39:24 +0100347 }
348 }
349
Sunny Goyal4cad7532015-03-18 15:56:30 -0700350 final boolean widgetPreviewExists = (drawable != null);
351 final int spanX = info.spanX < 1 ? 1 : info.spanX;
352 final int spanY = info.spanY < 1 ? 1 : info.spanY;
353
Michael Jurka05713af2013-01-23 12:39:24 +0100354 int previewWidth;
355 int previewHeight;
Sunny Goyal4cad7532015-03-18 15:56:30 -0700356 Bitmap tileBitmap = null;
357
Michael Jurka05713af2013-01-23 12:39:24 +0100358 if (widgetPreviewExists) {
359 previewWidth = drawable.getIntrinsicWidth();
360 previewHeight = drawable.getIntrinsicHeight();
361 } else {
362 // Generate a preview image if we couldn't load one
Sunny Goyal4cad7532015-03-18 15:56:30 -0700363 tileBitmap = ((BitmapDrawable) mContext.getResources().getDrawable(
364 R.drawable.widget_tile)).getBitmap();
365 previewWidth = tileBitmap.getWidth() * spanX;
366 previewHeight = tileBitmap.getHeight() * spanY;
Michael Jurka05713af2013-01-23 12:39:24 +0100367 }
368
369 // Scale to fit width only - let the widget preview be clipped in the
370 // vertical dimension
371 float scale = 1f;
372 if (preScaledWidthOut != null) {
373 preScaledWidthOut[0] = previewWidth;
374 }
375 if (previewWidth > maxPreviewWidth) {
376 scale = maxPreviewWidth / (float) previewWidth;
377 }
378 if (scale != 1f) {
379 previewWidth = (int) (scale * previewWidth);
380 previewHeight = (int) (scale * previewHeight);
381 }
382
383 // 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 -0700384 final Canvas c = new Canvas();
Michael Jurka05713af2013-01-23 12:39:24 +0100385 if (preview == null) {
386 preview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700387 c.setBitmap(preview);
388 } else {
389 // Reusing bitmap. Clear it.
390 c.setBitmap(preview);
391 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100392 }
393
394 // Draw the scaled preview into the final bitmap
395 int x = (preview.getWidth() - previewWidth) / 2;
396 if (widgetPreviewExists) {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700397 drawable.setBounds(x, 0, x + previewWidth, previewHeight);
398 drawable.draw(c);
Michael Jurka05713af2013-01-23 12:39:24 +0100399 } else {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700400 final Paint p = new Paint();
401 p.setFilterBitmap(true);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700402 int appIconSize = LauncherAppState.getInstance().getDynamicGrid()
403 .getDeviceProfile().iconSizePx;
Michael Jurka05713af2013-01-23 12:39:24 +0100404
Sunny Goyal4cad7532015-03-18 15:56:30 -0700405 // draw the spanX x spanY tiles
406 final Rect src = new Rect(0, 0, tileBitmap.getWidth(), tileBitmap.getHeight());
407
408 float tileW = scale * tileBitmap.getWidth();
409 float tileH = scale * tileBitmap.getHeight();
410 final RectF dst = new RectF(0, 0, tileW, tileH);
411
412 float tx = x;
413 for (int i = 0; i < spanX; i++, tx += tileW) {
414 float ty = 0;
415 for (int j = 0; j < spanY; j++, ty += tileH) {
416 dst.offsetTo(tx, ty);
417 c.drawBitmap(tileBitmap, src, dst, p);
418 }
Michael Jurka05713af2013-01-23 12:39:24 +0100419 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700420
421 // Draw the icon in the top left corner
422 // TODO: use top right for RTL
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700423 int minOffset = (int) (appIconSize * WIDGET_PREVIEW_ICON_PADDING_PERCENTAGE);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700424 int smallestSide = Math.min(previewWidth, previewHeight);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700425 float iconScale = Math.min((float) smallestSide / (appIconSize + 2 * minOffset), scale);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700426
427 try {
428 Drawable icon = mutateOnMainThread(mManager.loadIcon(info, mIconCache));
429 if (icon != null) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700430 int hoffset = (int) ((tileW - appIconSize * iconScale) / 2) + x;
431 int yoffset = (int) ((tileH - appIconSize * iconScale) / 2);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700432 icon.setBounds(hoffset, yoffset,
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700433 hoffset + (int) (appIconSize * iconScale),
434 yoffset + (int) (appIconSize * iconScale));
Sunny Goyal4cad7532015-03-18 15:56:30 -0700435 icon.draw(c);
436 }
437 } catch (Resources.NotFoundException e) { }
Michael Jurka05713af2013-01-23 12:39:24 +0100438 c.setBitmap(null);
439 }
Sunny Goyalffe83f12014-08-14 17:39:34 -0700440 return mManager.getBadgeBitmap(info, preview);
Michael Jurka05713af2013-01-23 12:39:24 +0100441 }
442
443 private Bitmap generateShortcutPreview(
444 ResolveInfo info, int maxWidth, int maxHeight, Bitmap preview) {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700445 final Canvas c = new Canvas();
446 if (preview == null) {
Michael Jurka05713af2013-01-23 12:39:24 +0100447 preview = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700448 c.setBitmap(preview);
449 } else if (preview.getWidth() != maxWidth || preview.getHeight() != maxHeight) {
450 throw new RuntimeException("Improperly sized bitmap passed as argument");
451 } else {
452 // Reusing bitmap. Clear it.
453 c.setBitmap(preview);
454 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100455 }
456
Sunny Goyal4cad7532015-03-18 15:56:30 -0700457 Drawable icon = mutateOnMainThread(mIconCache.getFullResIcon(info.activityInfo));
458 icon.setFilterBitmap(true);
459
Michael Jurka05713af2013-01-23 12:39:24 +0100460 // Draw a desaturated/scaled version of the icon in the background as a watermark
Sunny Goyal4cad7532015-03-18 15:56:30 -0700461 ColorMatrix colorMatrix = new ColorMatrix();
462 colorMatrix.setSaturation(0);
463 icon.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
464 icon.setAlpha((int) (255 * 0.06f));
465
466 Resources res = mContext.getResources();
467 int paddingTop = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_top);
468 int paddingLeft = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_left);
469 int paddingRight = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_right);
470 int scaledIconWidth = (maxWidth - paddingLeft - paddingRight);
471 icon.setBounds(paddingLeft, paddingTop,
472 paddingLeft + scaledIconWidth, paddingTop + scaledIconWidth);
473 icon.draw(c);
474
475 // Draw the final icon at top left corner.
476 // TODO: use top right for RTL
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700477 int appIconSize = LauncherAppState.getInstance().getDynamicGrid()
478 .getDeviceProfile().iconSizePx;
Sunny Goyal4cad7532015-03-18 15:56:30 -0700479 icon.setAlpha(255);
480 icon.setColorFilter(null);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700481 icon.setBounds(0, 0, appIconSize, appIconSize);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700482 icon.draw(c);
483
Michael Jurka05713af2013-01-23 12:39:24 +0100484 c.setBitmap(null);
Michael Jurka05713af2013-01-23 12:39:24 +0100485 return preview;
486 }
487
Adrian Roos65d60e22014-04-15 21:07:49 +0200488 private Drawable mutateOnMainThread(final Drawable drawable) {
489 try {
490 return mMainThreadExecutor.submit(new Callable<Drawable>() {
491 @Override
492 public Drawable call() throws Exception {
493 return drawable.mutate();
494 }
495 }).get();
496 } catch (InterruptedException e) {
497 Thread.currentThread().interrupt();
498 throw new RuntimeException(e);
499 } catch (ExecutionException e) {
500 throw new RuntimeException(e);
501 }
502 }
Adrian Roos1f375ab2014-04-28 18:26:38 +0200503
Adrian Roos1f375ab2014-04-28 18:26:38 +0200504 /**
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700505 * @return an array of containing versionCode and lastUpdatedTime for the package.
Adrian Roos1f375ab2014-04-28 18:26:38 +0200506 */
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700507 private long[] getPackageVersion(String packageName) {
508 synchronized (mPackageVersions) {
509 long[] versions = mPackageVersions.get(packageName);
510 if (versions == null) {
511 versions = new long[2];
Adrian Roos1f375ab2014-04-28 18:26:38 +0200512 try {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700513 PackageInfo info = mContext.getPackageManager().getPackageInfo(packageName, 0);
514 versions[0] = info.versionCode;
515 versions[1] = info.lastUpdateTime;
516 } catch (NameNotFoundException e) {
517 Log.e(TAG, "PackageInfo not found", e);
518 }
519 mPackageVersions.put(packageName, versions);
520 }
521 return versions;
522 }
523 }
524
525 /**
526 * A request Id which can be used by the client to cancel any request.
527 */
528 public class PreviewLoadRequest {
529
530 private final PreviewLoadTask mTask;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700531
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700532 public PreviewLoadRequest(PreviewLoadTask task) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700533 mTask = task;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700534 }
535
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700536 public void cleanup() {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700537 if (mTask != null) {
538 mTask.cancel(true);
539 }
540
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700541 if (mTask.mBitmap == null) {
542 return;
Adrian Roos1f375ab2014-04-28 18:26:38 +0200543 }
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700544
545 // The preview is no longer bound to any view, move it to {@link WeakReference} list.
546 synchronized(mUnusedBitmaps) {
547 mUnusedBitmaps.add(mTask.mBitmap);
548 }
549 mTask.mBitmap = null;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700550 }
551 }
552
553 public class PreviewLoadTask extends AsyncTask<Void, Void, Bitmap> {
554
555 private final WidgetCacheKey mKey;
556 private final Object mInfo;
557 private final int mPreviewHeight;
558 private final int mPreviewWidth;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700559 private final WidgetCell mCaller;
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700560 private Bitmap mBitmap;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700561
562 PreviewLoadTask(WidgetCacheKey key, Object info, int previewWidth,
Hyunyoung Song3f471442015-04-08 19:01:34 -0700563 int previewHeight, WidgetCell caller) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700564 mKey = key;
565 mInfo = info;
566 mPreviewHeight = previewHeight;
567 mPreviewWidth = previewWidth;
568 mCaller = caller;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700569 if (DEBUG) {
570 Log.d(TAG, String.format("%s, %s, %d, %d",
571 mKey, mInfo, mPreviewHeight, mPreviewWidth));
572 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700573 }
574
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700575 @Override
576 protected Bitmap doInBackground(Void... params) {
577 Bitmap unusedBitmap = null;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700578
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700579 synchronized (mUnusedBitmaps) {
580 // Check if we can use a bitmap
581 for (Bitmap candidate : mUnusedBitmaps) {
582 if (candidate != null && candidate.isMutable() &&
583 candidate.getWidth() == mPreviewWidth &&
584 candidate.getHeight() == mPreviewHeight) {
585 unusedBitmap = candidate;
586 break;
587 }
588 }
589
590 if (unusedBitmap == null) {
591 unusedBitmap = Bitmap.createBitmap(mPreviewWidth, mPreviewHeight, Config.ARGB_8888);
592 } else {
593 mUnusedBitmaps.remove(unusedBitmap);
594 }
Adrian Roos1f375ab2014-04-28 18:26:38 +0200595 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700596 if (isCancelled()) {
597 return null;
598 }
599 Bitmap preview = readFromDb(mKey, unusedBitmap);
600 if (!isCancelled() && preview == null) {
601 // Fetch the version info before we generate the preview, so that, in-case the
602 // app was updated while we are generating the preview, we use the old version info,
603 // which would gets re-written next time.
604 long[] versions = getPackageVersion(mKey.componentName.getPackageName());
605
606 // it's not in the db... we need to generate it
607 preview = generatePreview(mInfo, unusedBitmap, mPreviewWidth, mPreviewHeight);
608
609 if (!isCancelled()) {
610 writeToDb(mKey, versions, preview);
611 }
612 }
613
614 return preview;
615 }
616
617 @Override
618 protected void onPostExecute(Bitmap result) {
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700619 mBitmap = result;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700620 mCaller.applyPreview(result);
621 }
622 }
623
624 private static final class WidgetCacheKey extends ComponentKey {
625
626 // TODO: remove dependency on size
627 private final String size;
628
629 public WidgetCacheKey(ComponentName componentName, UserHandleCompat user, String size) {
630 super(componentName, user);
631 this.size = size;
632 }
633
634 @Override
635 public int hashCode() {
636 return super.hashCode() ^ size.hashCode();
637 }
638
639 @Override
640 public boolean equals(Object o) {
641 return super.equals(o) && ((WidgetCacheKey) o).size.equals(size);
Adrian Roos1f375ab2014-04-28 18:26:38 +0200642 }
643 }
Michael Jurka05713af2013-01-23 12:39:24 +0100644}