blob: 1043e2ee0243986c12f13fafd14be7c8f0095a1b [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;
Sunny Goyalffe83f12014-08-14 17:39:34 -070035
Michael Jurka05713af2013-01-23 12:39:24 +010036import java.lang.ref.WeakReference;
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";
Sunny Goyalffe83f12014-08-14 17:39:34 -070048
49 private static final float WIDGET_PREVIEW_ICON_PADDING_PERCENTAGE = 0.25f;
Sunny Goyalffe83f12014-08-14 17:39:34 -070050
Sunny Goyal5b0e6692015-03-19 14:31:19 -070051 private final HashMap<String, long[]> mPackageVersions = new HashMap<>();
52 private final HashMap<WidgetCacheKey, WeakReference<Bitmap>> mLoadedPreviews = new HashMap<>();
53 private Set<Bitmap> mUnusedBitmaps = Collections.newSetFromMap(new WeakHashMap<Bitmap, Boolean>());
Sunny Goyal4cad7532015-03-18 15:56:30 -070054
55 private final Context mContext;
Sunny Goyalffe83f12014-08-14 17:39:34 -070056 private final IconCache mIconCache;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070057 private final UserManagerCompat mUserManager;
Sunny Goyalffe83f12014-08-14 17:39:34 -070058 private final AppWidgetManagerCompat mManager;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070059 private final CacheDb mDb;
Michael Jurka05713af2013-01-23 12:39:24 +010060
Adrian Roos65d60e22014-04-15 21:07:49 +020061 private final MainThreadExecutor mMainThreadExecutor = new MainThreadExecutor();
62
Sunny Goyal5b0e6692015-03-19 14:31:19 -070063 public WidgetPreviewLoader(Context context, IconCache iconCache) {
Chris Wrenfd13c712013-09-27 15:45:19 -040064 mContext = context;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070065 mIconCache = iconCache;
Sunny Goyalffe83f12014-08-14 17:39:34 -070066 mManager = AppWidgetManagerCompat.getInstance(context);
Sunny Goyal5b0e6692015-03-19 14:31:19 -070067 mUserManager = UserManagerCompat.getInstance(context);
68 mDb = new CacheDb(context);
Michael Jurka3f4e0702013-02-05 11:21:28 +010069 }
Sunny Goyalffe83f12014-08-14 17:39:34 -070070
Sunny Goyal5b0e6692015-03-19 14:31:19 -070071 /**
72 * Generates the widget preview on {@link AsyncTask#THREAD_POOL_EXECUTOR}. Must be
73 * called on UI thread
74 *
75 * @param o either {@link LauncherAppWidgetProviderInfo} or {@link ResolveInfo}
76 * @param immediateResult A bitmap array of size 1. If the result is already cached, it is
77 * set to the final result.
78 * @return a request id which can be used to cancel the request.
79 */
80 public PreviewLoadRequest getPreview(final Object o, int previewWidth, int previewHeight,
81 PagedViewWidget caller, Bitmap[] immediateResult) {
82 String size = previewWidth + "x" + previewHeight;
83 WidgetCacheKey key = getObjectKey(o, size);
Michael Jurka3f4e0702013-02-05 11:21:28 +010084
Sunny Goyal5b0e6692015-03-19 14:31:19 -070085 // Check if we have the preview loaded or not.
Michael Jurka5140cfa2013-02-15 14:50:15 +010086 synchronized (mLoadedPreviews) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -070087 WeakReference<Bitmap> ref = mLoadedPreviews.get(key);
88 if (ref != null && ref.get() != null) {
89 immediateResult[0] = ref.get();
90 return new PreviewLoadRequest(null, key);
Michael Jurka05713af2013-01-23 12:39:24 +010091 }
92 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -070093
94 PreviewLoadTask task = new PreviewLoadTask(key, o, previewWidth, previewHeight, caller);
95 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
96 return new PreviewLoadRequest(task, key);
Michael Jurka05713af2013-01-23 12:39:24 +010097 }
98
Sunny Goyal5b0e6692015-03-19 14:31:19 -070099 /**
100 * The DB holds the generated previews for various components. Previews can also have different
101 * sizes (landscape vs portrait).
102 */
103 private static class CacheDb extends SQLiteOpenHelper {
104 private static final int DB_VERSION = 3;
105
106 private static final String TABLE_NAME = "shortcut_and_widget_previews";
107 private static final String COLUMN_COMPONENT = "componentName";
108 private static final String COLUMN_USER = "profileId";
109 private static final String COLUMN_SIZE = "size";
110 private static final String COLUMN_PACKAGE = "packageName";
111 private static final String COLUMN_LAST_UPDATED = "lastUpdated";
112 private static final String COLUMN_VERSION = "version";
113 private static final String COLUMN_PREVIEW_BITMAP = "preview_bitmap";
Michael Jurka05713af2013-01-23 12:39:24 +0100114
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100115 public CacheDb(Context context) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700116 super(context, LauncherFiles.WIDGET_PREVIEWS_DB, null, DB_VERSION);
Michael Jurka05713af2013-01-23 12:39:24 +0100117 }
118
119 @Override
120 public void onCreate(SQLiteDatabase database) {
Michael Jurka32b7a092013-02-07 20:06:49 +0100121 database.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" +
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700122 COLUMN_COMPONENT + " TEXT NOT NULL, " +
123 COLUMN_USER + " INTEGER NOT NULL, " +
Michael Jurka05713af2013-01-23 12:39:24 +0100124 COLUMN_SIZE + " TEXT NOT NULL, " +
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700125 COLUMN_PACKAGE + " TEXT NOT NULL, " +
126 COLUMN_LAST_UPDATED + " INTEGER NOT NULL DEFAULT 0, " +
127 COLUMN_VERSION + " INTEGER NOT NULL DEFAULT 0, " +
128 COLUMN_PREVIEW_BITMAP + " BLOB, " +
129 "PRIMARY KEY (" + COLUMN_COMPONENT + ", " + COLUMN_USER + ", " + COLUMN_SIZE + ") " +
Michael Jurka32b7a092013-02-07 20:06:49 +0100130 ");");
Michael Jurka05713af2013-01-23 12:39:24 +0100131 }
132
133 @Override
134 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Michael Jurkae5919c52013-03-06 17:30:10 +0100135 if (oldVersion != newVersion) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700136 clearDB(db);
Michael Jurkae5919c52013-03-06 17:30:10 +0100137 }
Michael Jurka05713af2013-01-23 12:39:24 +0100138 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700139
140 @Override
141 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
142 if (oldVersion != newVersion) {
143 clearDB(db);
144 }
145 }
146
147 private void clearDB(SQLiteDatabase db) {
148 db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
149 onCreate(db);
150 }
Michael Jurka05713af2013-01-23 12:39:24 +0100151 }
152
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700153 private WidgetCacheKey getObjectKey(Object o, String size) {
Michael Jurka05713af2013-01-23 12:39:24 +0100154 // should cache the string builder
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700155 if (o instanceof LauncherAppWidgetProviderInfo) {
156 LauncherAppWidgetProviderInfo info = (LauncherAppWidgetProviderInfo) o;
157 return new WidgetCacheKey(info.provider, mManager.getUser(info), size);
Michael Jurka05713af2013-01-23 12:39:24 +0100158 } else {
159 ResolveInfo info = (ResolveInfo) o;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700160 return new WidgetCacheKey(
161 new ComponentName(info.activityInfo.packageName, info.activityInfo.name),
162 UserHandleCompat.myUserHandle(), size);
Michael Jurka05713af2013-01-23 12:39:24 +0100163 }
164 }
165
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700166 @Thunk void writeToDb(WidgetCacheKey key, long[] versions, Bitmap preview) {
Michael Jurka05713af2013-01-23 12:39:24 +0100167 ContentValues values = new ContentValues();
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700168 values.put(CacheDb.COLUMN_COMPONENT, key.componentName.flattenToShortString());
169 values.put(CacheDb.COLUMN_USER, mUserManager.getSerialNumberForUser(key.user));
170 values.put(CacheDb.COLUMN_SIZE, key.size);
171 values.put(CacheDb.COLUMN_PACKAGE, key.componentName.getPackageName());
172 values.put(CacheDb.COLUMN_VERSION, versions[0]);
173 values.put(CacheDb.COLUMN_LAST_UPDATED, versions[1]);
174 values.put(CacheDb.COLUMN_PREVIEW_BITMAP, Utilities.flattenBitmap(preview));
Michael Jurka05713af2013-01-23 12:39:24 +0100175
Michael Jurka6e27f642013-12-10 13:40:30 +0100176 try {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700177 mDb.getWritableDatabase().insertWithOnConflict(CacheDb.TABLE_NAME, null, values,
178 SQLiteDatabase.CONFLICT_REPLACE);
179 } catch (SQLException e) {
180 Log.e(TAG, "Error saving image to DB", e);
Michael Jurka6e27f642013-12-10 13:40:30 +0100181 }
Michael Jurka05713af2013-01-23 12:39:24 +0100182 }
183
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700184 public void removePackage(String packageName, UserHandleCompat user) {
185 removePackage(packageName, user, mUserManager.getSerialNumberForUser(user));
186 }
187
188 private void removePackage(String packageName, UserHandleCompat user, long userSerial) {
189 synchronized(mPackageVersions) {
190 mPackageVersions.remove(packageName);
191 }
192
193 synchronized (mLoadedPreviews) {
194 Set<WidgetCacheKey> keysToRemove = new HashSet<>();
195 for (WidgetCacheKey key : mLoadedPreviews.keySet()) {
196 if (key.componentName.getPackageName().equals(packageName) && key.user.equals(user)) {
197 keysToRemove.add(key);
198 }
199 }
200
201 for (WidgetCacheKey key : keysToRemove) {
202 WeakReference<Bitmap> req = mLoadedPreviews.remove(key);
203 if (req != null && req.get() != null) {
204 mUnusedBitmaps.add(req.get());
205 }
206 }
207 }
208
Michael Jurka6e27f642013-12-10 13:40:30 +0100209 try {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700210 mDb.getWritableDatabase().delete(CacheDb.TABLE_NAME,
211 CacheDb.COLUMN_PACKAGE + " = ? AND " + CacheDb.COLUMN_USER + " = ?",
212 new String[] {packageName, Long.toString(userSerial)});
213 } catch (SQLException e) {
214 Log.e(TAG, "Unable to delete items from DB", e);
Michael Jurka6e27f642013-12-10 13:40:30 +0100215 }
Michael Jurka8ff02ca2013-11-01 14:19:27 +0100216 }
217
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700218 /**
219 * Updates the persistent DB:
220 * 1. Any preview generated for an old package version is removed
221 * 2. Any preview for an absent package is removed
222 * This ensures that we remove entries for packages which changed while the launcher was dead.
223 */
224 public void removeObsoletePreviews() {
225 LongSparseArray<UserHandleCompat> userIdCache = new LongSparseArray<>();
226 LongSparseArray<HashSet<String>> validPackages = new LongSparseArray<>();
227
228 for (Object obj : LauncherModel.getSortedWidgetsAndShortcuts(mContext, false)) {
229 final UserHandleCompat user;
230 final String pkg;
231 if (obj instanceof ResolveInfo) {
232 user = UserHandleCompat.myUserHandle();
233 pkg = ((ResolveInfo) obj).activityInfo.packageName;
234 } else {
235 LauncherAppWidgetProviderInfo info = (LauncherAppWidgetProviderInfo) obj;
236 user = mManager.getUser(info);
237 pkg = info.provider.getPackageName();
238 }
239
240 int userIdIndex = userIdCache.indexOfValue(user);
241 final long userId;
242 if (userIdIndex < 0) {
243 userId = mUserManager.getSerialNumberForUser(user);
244 userIdCache.put(userId, user);
245 } else {
246 userId = userIdCache.keyAt(userIdIndex);
247 }
248
249 HashSet<String> packages = validPackages.get(userId);
250 if (packages == null) {
251 packages = new HashSet<>();
252 validPackages.put(userId, packages);
253 }
254 packages.add(pkg);
Michael Jurka05713af2013-01-23 12:39:24 +0100255 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700256
257 LongSparseArray<HashSet<String>> packagesToDelete = new LongSparseArray<>();
258 Cursor c = null;
259 try {
260 c = mDb.getReadableDatabase().query(CacheDb.TABLE_NAME,
261 new String[] {CacheDb.COLUMN_USER, CacheDb.COLUMN_PACKAGE,
262 CacheDb.COLUMN_LAST_UPDATED, CacheDb.COLUMN_VERSION},
263 null, null, null, null, null);
264 while (c.moveToNext()) {
265 long userId = c.getLong(0);
266 String pkg = c.getString(1);
267 long lastUpdated = c.getLong(2);
268 long version = c.getLong(3);
269
270 HashSet<String> packages = validPackages.get(userId);
271 if (packages != null && packages.contains(pkg)) {
272 long[] versions = getPackageVersion(pkg);
273 if (versions[0] == version && versions[1] == lastUpdated) {
274 // Every thing checks out
275 continue;
276 }
277 }
278
279 // We need to delete this package.
280 packages = packagesToDelete.get(userId);
281 if (packages == null) {
282 packages = new HashSet<>();
283 packagesToDelete.put(userId, packages);
284 }
285 packages.add(pkg);
286 }
287
288 for (int i = 0; i < packagesToDelete.size(); i++) {
289 long userId = packagesToDelete.keyAt(i);
290 UserHandleCompat user = mUserManager.getUserForSerialNumber(userId);
291 for (String pkg : packagesToDelete.valueAt(i)) {
292 removePackage(pkg, user, userId);
293 }
294 }
295 } catch (SQLException e) {
296 Log.e(TAG, "Error updatating widget previews", e);
297 } finally {
298 if (c != null) {
299 c.close();
300 }
301 }
302 }
303
304 private Bitmap readFromDb(WidgetCacheKey key, Bitmap recycle) {
305 Cursor cursor = null;
306 try {
307 cursor = mDb.getReadableDatabase().query(
308 CacheDb.TABLE_NAME,
309 new String[] { CacheDb.COLUMN_PREVIEW_BITMAP },
310 CacheDb.COLUMN_COMPONENT + " = ? AND " + CacheDb.COLUMN_USER + " = ? AND " + CacheDb.COLUMN_SIZE + " = ?",
311 new String[] {
312 key.componentName.flattenToString(),
313 Long.toString(mUserManager.getSerialNumberForUser(key.user)),
314 key.size
315 },
316 null, null, null);
317 if (cursor.moveToNext()) {
318 byte[] blob = cursor.getBlob(0);
319 BitmapFactory.Options opts = new BitmapFactory.Options();
320 opts.inBitmap = recycle;
Michael Jurka6e27f642013-12-10 13:40:30 +0100321 try {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700322 return BitmapFactory.decodeByteArray(blob, 0, blob.length, opts);
323 } catch (Exception e) {
324 return null;
Michael Jurka6e27f642013-12-10 13:40:30 +0100325 }
Michael Jurka05713af2013-01-23 12:39:24 +0100326 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700327 } catch (SQLException e) {
328 Log.w(TAG, "Error loading preview from DB", e);
329 } finally {
330 if (cursor != null) {
331 cursor.close();
332 }
333 }
334 return null;
Michael Jurka05713af2013-01-23 12:39:24 +0100335 }
336
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700337 private Bitmap generatePreview(Object info, Bitmap recycle, int previewWidth, int previewHeight) {
Adam Cohen59400422014-03-05 18:07:04 -0800338 if (info instanceof LauncherAppWidgetProviderInfo) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700339 return generateWidgetPreview((LauncherAppWidgetProviderInfo) info, previewWidth, recycle);
Michael Jurka05713af2013-01-23 12:39:24 +0100340 } else {
341 return generateShortcutPreview(
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700342 (ResolveInfo) info, previewWidth, previewHeight, recycle);
Michael Jurka05713af2013-01-23 12:39:24 +0100343 }
344 }
345
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700346 public Bitmap generateWidgetPreview(LauncherAppWidgetProviderInfo info,
347 int previewWidth, Bitmap preview) {
348 int maxWidth = Math.min(previewWidth, info.spanX
349 * LauncherAppState.getInstance().getDynamicGrid().getDeviceProfile().cellWidthPx);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700350 return generateWidgetPreview(info, maxWidth, preview, null);
Michael Jurka05713af2013-01-23 12:39:24 +0100351 }
352
Sunny Goyal4cad7532015-03-18 15:56:30 -0700353 public Bitmap generateWidgetPreview(LauncherAppWidgetProviderInfo info,
354 int maxPreviewWidth, Bitmap preview, int[] preScaledWidthOut) {
Michael Jurka05713af2013-01-23 12:39:24 +0100355 // Load the preview image if possible
Michael Jurka05713af2013-01-23 12:39:24 +0100356 if (maxPreviewWidth < 0) maxPreviewWidth = Integer.MAX_VALUE;
Michael Jurka05713af2013-01-23 12:39:24 +0100357
358 Drawable drawable = null;
Sunny Goyalffe83f12014-08-14 17:39:34 -0700359 if (info.previewImage != 0) {
360 drawable = mManager.loadPreview(info);
Adrian Roosfa9ffc22014-05-12 15:59:59 +0200361 if (drawable != null) {
362 drawable = mutateOnMainThread(drawable);
363 } else {
Michael Jurka05713af2013-01-23 12:39:24 +0100364 Log.w(TAG, "Can't load widget preview drawable 0x" +
Sunny Goyalffe83f12014-08-14 17:39:34 -0700365 Integer.toHexString(info.previewImage) + " for provider: " + info.provider);
Michael Jurka05713af2013-01-23 12:39:24 +0100366 }
367 }
368
Sunny Goyal4cad7532015-03-18 15:56:30 -0700369 final boolean widgetPreviewExists = (drawable != null);
370 final int spanX = info.spanX < 1 ? 1 : info.spanX;
371 final int spanY = info.spanY < 1 ? 1 : info.spanY;
372
Michael Jurka05713af2013-01-23 12:39:24 +0100373 int previewWidth;
374 int previewHeight;
Sunny Goyal4cad7532015-03-18 15:56:30 -0700375 Bitmap tileBitmap = null;
376
Michael Jurka05713af2013-01-23 12:39:24 +0100377 if (widgetPreviewExists) {
378 previewWidth = drawable.getIntrinsicWidth();
379 previewHeight = drawable.getIntrinsicHeight();
380 } else {
381 // Generate a preview image if we couldn't load one
Sunny Goyal4cad7532015-03-18 15:56:30 -0700382 tileBitmap = ((BitmapDrawable) mContext.getResources().getDrawable(
383 R.drawable.widget_tile)).getBitmap();
384 previewWidth = tileBitmap.getWidth() * spanX;
385 previewHeight = tileBitmap.getHeight() * spanY;
Michael Jurka05713af2013-01-23 12:39:24 +0100386 }
387
388 // Scale to fit width only - let the widget preview be clipped in the
389 // vertical dimension
390 float scale = 1f;
391 if (preScaledWidthOut != null) {
392 preScaledWidthOut[0] = previewWidth;
393 }
394 if (previewWidth > maxPreviewWidth) {
395 scale = maxPreviewWidth / (float) previewWidth;
396 }
397 if (scale != 1f) {
398 previewWidth = (int) (scale * previewWidth);
399 previewHeight = (int) (scale * previewHeight);
400 }
401
402 // 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 -0700403 final Canvas c = new Canvas();
Michael Jurka05713af2013-01-23 12:39:24 +0100404 if (preview == null) {
405 preview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700406 c.setBitmap(preview);
407 } else {
408 // Reusing bitmap. Clear it.
409 c.setBitmap(preview);
410 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100411 }
412
413 // Draw the scaled preview into the final bitmap
414 int x = (preview.getWidth() - previewWidth) / 2;
415 if (widgetPreviewExists) {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700416 drawable.setBounds(x, 0, x + previewWidth, previewHeight);
417 drawable.draw(c);
Michael Jurka05713af2013-01-23 12:39:24 +0100418 } else {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700419 final Paint p = new Paint();
420 p.setFilterBitmap(true);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700421 int appIconSize = LauncherAppState.getInstance().getDynamicGrid()
422 .getDeviceProfile().iconSizePx;
Michael Jurka05713af2013-01-23 12:39:24 +0100423
Sunny Goyal4cad7532015-03-18 15:56:30 -0700424 // draw the spanX x spanY tiles
425 final Rect src = new Rect(0, 0, tileBitmap.getWidth(), tileBitmap.getHeight());
426
427 float tileW = scale * tileBitmap.getWidth();
428 float tileH = scale * tileBitmap.getHeight();
429 final RectF dst = new RectF(0, 0, tileW, tileH);
430
431 float tx = x;
432 for (int i = 0; i < spanX; i++, tx += tileW) {
433 float ty = 0;
434 for (int j = 0; j < spanY; j++, ty += tileH) {
435 dst.offsetTo(tx, ty);
436 c.drawBitmap(tileBitmap, src, dst, p);
437 }
Michael Jurka05713af2013-01-23 12:39:24 +0100438 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700439
440 // Draw the icon in the top left corner
441 // TODO: use top right for RTL
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700442 int minOffset = (int) (appIconSize * WIDGET_PREVIEW_ICON_PADDING_PERCENTAGE);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700443 int smallestSide = Math.min(previewWidth, previewHeight);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700444 float iconScale = Math.min((float) smallestSide / (appIconSize + 2 * minOffset), scale);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700445
446 try {
447 Drawable icon = mutateOnMainThread(mManager.loadIcon(info, mIconCache));
448 if (icon != null) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700449 int hoffset = (int) ((tileW - appIconSize * iconScale) / 2) + x;
450 int yoffset = (int) ((tileH - appIconSize * iconScale) / 2);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700451 icon.setBounds(hoffset, yoffset,
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700452 hoffset + (int) (appIconSize * iconScale),
453 yoffset + (int) (appIconSize * iconScale));
Sunny Goyal4cad7532015-03-18 15:56:30 -0700454 icon.draw(c);
455 }
456 } catch (Resources.NotFoundException e) { }
Michael Jurka05713af2013-01-23 12:39:24 +0100457 c.setBitmap(null);
458 }
Sunny Goyalffe83f12014-08-14 17:39:34 -0700459 return mManager.getBadgeBitmap(info, preview);
Michael Jurka05713af2013-01-23 12:39:24 +0100460 }
461
462 private Bitmap generateShortcutPreview(
463 ResolveInfo info, int maxWidth, int maxHeight, Bitmap preview) {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700464 final Canvas c = new Canvas();
465 if (preview == null) {
Michael Jurka05713af2013-01-23 12:39:24 +0100466 preview = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700467 c.setBitmap(preview);
468 } else if (preview.getWidth() != maxWidth || preview.getHeight() != maxHeight) {
469 throw new RuntimeException("Improperly sized bitmap passed as argument");
470 } else {
471 // Reusing bitmap. Clear it.
472 c.setBitmap(preview);
473 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100474 }
475
Sunny Goyal4cad7532015-03-18 15:56:30 -0700476 Drawable icon = mutateOnMainThread(mIconCache.getFullResIcon(info.activityInfo));
477 icon.setFilterBitmap(true);
478
Michael Jurka05713af2013-01-23 12:39:24 +0100479 // Draw a desaturated/scaled version of the icon in the background as a watermark
Sunny Goyal4cad7532015-03-18 15:56:30 -0700480 ColorMatrix colorMatrix = new ColorMatrix();
481 colorMatrix.setSaturation(0);
482 icon.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
483 icon.setAlpha((int) (255 * 0.06f));
484
485 Resources res = mContext.getResources();
486 int paddingTop = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_top);
487 int paddingLeft = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_left);
488 int paddingRight = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_right);
489 int scaledIconWidth = (maxWidth - paddingLeft - paddingRight);
490 icon.setBounds(paddingLeft, paddingTop,
491 paddingLeft + scaledIconWidth, paddingTop + scaledIconWidth);
492 icon.draw(c);
493
494 // Draw the final icon at top left corner.
495 // TODO: use top right for RTL
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700496 int appIconSize = LauncherAppState.getInstance().getDynamicGrid()
497 .getDeviceProfile().iconSizePx;
Sunny Goyal4cad7532015-03-18 15:56:30 -0700498 icon.setAlpha(255);
499 icon.setColorFilter(null);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700500 icon.setBounds(0, 0, appIconSize, appIconSize);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700501 icon.draw(c);
502
Michael Jurka05713af2013-01-23 12:39:24 +0100503 c.setBitmap(null);
Michael Jurka05713af2013-01-23 12:39:24 +0100504 return preview;
505 }
506
Adrian Roos65d60e22014-04-15 21:07:49 +0200507 private Drawable mutateOnMainThread(final Drawable drawable) {
508 try {
509 return mMainThreadExecutor.submit(new Callable<Drawable>() {
510 @Override
511 public Drawable call() throws Exception {
512 return drawable.mutate();
513 }
514 }).get();
515 } catch (InterruptedException e) {
516 Thread.currentThread().interrupt();
517 throw new RuntimeException(e);
518 } catch (ExecutionException e) {
519 throw new RuntimeException(e);
520 }
521 }
Adrian Roos1f375ab2014-04-28 18:26:38 +0200522
Adrian Roos1f375ab2014-04-28 18:26:38 +0200523 /**
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700524 * @return an array of containing versionCode and lastUpdatedTime for the package.
Adrian Roos1f375ab2014-04-28 18:26:38 +0200525 */
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700526 private long[] getPackageVersion(String packageName) {
527 synchronized (mPackageVersions) {
528 long[] versions = mPackageVersions.get(packageName);
529 if (versions == null) {
530 versions = new long[2];
Adrian Roos1f375ab2014-04-28 18:26:38 +0200531 try {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700532 PackageInfo info = mContext.getPackageManager().getPackageInfo(packageName, 0);
533 versions[0] = info.versionCode;
534 versions[1] = info.lastUpdateTime;
535 } catch (NameNotFoundException e) {
536 Log.e(TAG, "PackageInfo not found", e);
537 }
538 mPackageVersions.put(packageName, versions);
539 }
540 return versions;
541 }
542 }
543
544 /**
545 * A request Id which can be used by the client to cancel any request.
546 */
547 public class PreviewLoadRequest {
548
549 private final PreviewLoadTask mTask;
550 private final WidgetCacheKey mKey;
551
552 public PreviewLoadRequest(PreviewLoadTask task, WidgetCacheKey key) {
553 mTask = task;
554 mKey = key;
555 }
556
557 public void cancel(boolean recycleImage) {
558 if (mTask != null) {
559 mTask.cancel(true);
560 }
561
562 if (recycleImage) {
563 synchronized(mLoadedPreviews) {
564 WeakReference<Bitmap> result = mLoadedPreviews.remove(mKey);
565 if (result != null && result.get() != null) {
566 mUnusedBitmaps.add(result.get());
Adrian Roos1f375ab2014-04-28 18:26:38 +0200567 }
Adrian Roos1f375ab2014-04-28 18:26:38 +0200568 }
569 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700570 }
571 }
572
573 public class PreviewLoadTask extends AsyncTask<Void, Void, Bitmap> {
574
575 private final WidgetCacheKey mKey;
576 private final Object mInfo;
577 private final int mPreviewHeight;
578 private final int mPreviewWidth;
579 private final PagedViewWidget mCaller;
580
581 PreviewLoadTask(WidgetCacheKey key, Object info, int previewWidth,
582 int previewHeight, PagedViewWidget caller) {
583 mKey = key;
584 mInfo = info;
585 mPreviewHeight = previewHeight;
586 mPreviewWidth = previewWidth;
587 mCaller = caller;
588 }
589
590
591 @Override
592 protected Bitmap doInBackground(Void... params) {
593 Bitmap unusedBitmap = null;
594 synchronized (mUnusedBitmaps) {
595 // Check if we can use a bitmap
596 for (Bitmap candidate : mUnusedBitmaps) {
597 if (candidate != null && candidate.isMutable() &&
598 candidate.getWidth() == mPreviewWidth &&
599 candidate.getHeight() == mPreviewHeight) {
600 unusedBitmap = candidate;
601 break;
602 }
603 }
604
605 if (unusedBitmap == null) {
606 unusedBitmap = Bitmap.createBitmap(mPreviewWidth, mPreviewHeight, Config.ARGB_8888);
607 } else {
608 mUnusedBitmaps.remove(unusedBitmap);
609 }
Adrian Roos1f375ab2014-04-28 18:26:38 +0200610 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700611
612 if (isCancelled()) {
613 return null;
614 }
615 Bitmap preview = readFromDb(mKey, unusedBitmap);
616 if (!isCancelled() && preview == null) {
617 // Fetch the version info before we generate the preview, so that, in-case the
618 // app was updated while we are generating the preview, we use the old version info,
619 // which would gets re-written next time.
620 long[] versions = getPackageVersion(mKey.componentName.getPackageName());
621
622 // it's not in the db... we need to generate it
623 preview = generatePreview(mInfo, unusedBitmap, mPreviewWidth, mPreviewHeight);
624
625 if (!isCancelled()) {
626 writeToDb(mKey, versions, preview);
627 }
628 }
629
630 return preview;
631 }
632
633 @Override
634 protected void onPostExecute(Bitmap result) {
635 synchronized(mLoadedPreviews) {
636 mLoadedPreviews.put(mKey, new WeakReference<Bitmap>(result));
637 }
638
639 mCaller.applyPreview(result);
640 }
641 }
642
643 private static final class WidgetCacheKey extends ComponentKey {
644
645 // TODO: remove dependency on size
646 private final String size;
647
648 public WidgetCacheKey(ComponentName componentName, UserHandleCompat user, String size) {
649 super(componentName, user);
650 this.size = size;
651 }
652
653 @Override
654 public int hashCode() {
655 return super.hashCode() ^ size.hashCode();
656 }
657
658 @Override
659 public boolean equals(Object o) {
660 return super.equals(o) && ((WidgetCacheKey) o).size.equals(size);
Adrian Roos1f375ab2014-04-28 18:26:38 +0200661 }
662 }
Michael Jurka05713af2013-01-23 12:39:24 +0100663}