blob: 93bfeaffdcda077d1d02557a71c24c8639b6f701 [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;
Hyunyoung Song8821ca92015-05-04 16:28:20 -070027import android.os.Process;
Michael Jurka05713af2013-01-23 12:39:24 +010028import android.util.Log;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070029import android.util.LongSparseArray;
Sunny Goyal4cad7532015-03-18 15:56:30 -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;
Sunny Goyalffe83f12014-08-14 17:39:34 -070037
Hyunyoung Song8821ca92015-05-04 16:28:20 -070038import junit.framework.Assert;
39
40import java.util.ArrayList;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070041import java.util.Collections;
Michael Jurka05713af2013-01-23 12:39:24 +010042import java.util.HashMap;
43import java.util.HashSet;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070044import java.util.Set;
45import java.util.WeakHashMap;
Adrian Roos65d60e22014-04-15 21:07:49 +020046import java.util.concurrent.Callable;
47import java.util.concurrent.ExecutionException;
Michael Jurka05713af2013-01-23 12:39:24 +010048
Sunny Goyalffe83f12014-08-14 17:39:34 -070049public class WidgetPreviewLoader {
Michael Jurka05713af2013-01-23 12:39:24 +010050
Sunny Goyalffe83f12014-08-14 17:39:34 -070051 private static final String TAG = "WidgetPreviewLoader";
Hyunyoung Song3f471442015-04-08 19:01:34 -070052 private static final boolean DEBUG = false;
Sunny Goyalffe83f12014-08-14 17:39:34 -070053
54 private static final float WIDGET_PREVIEW_ICON_PADDING_PERCENTAGE = 0.25f;
Sunny Goyalffe83f12014-08-14 17:39:34 -070055
Sunny Goyal5b0e6692015-03-19 14:31:19 -070056 private final HashMap<String, long[]> mPackageVersions = new HashMap<>();
Hyunyoung Song559d90d2015-04-28 15:06:45 -070057
58 /**
59 * Weak reference objects, do not prevent their referents from being made finalizable,
60 * finalized, and then reclaimed.
61 */
62 private Set<Bitmap> mUnusedBitmaps =
63 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;
Michael Jurka05713af2013-01-23 12:39:24 +010070
Adrian Roos65d60e22014-04-15 21:07:49 +020071 private final MainThreadExecutor mMainThreadExecutor = new MainThreadExecutor();
72
Sunny Goyal5b0e6692015-03-19 14:31:19 -070073 public WidgetPreviewLoader(Context context, IconCache iconCache) {
Chris Wrenfd13c712013-09-27 15:45:19 -040074 mContext = context;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070075 mIconCache = iconCache;
Sunny Goyalffe83f12014-08-14 17:39:34 -070076 mManager = AppWidgetManagerCompat.getInstance(context);
Sunny Goyal5b0e6692015-03-19 14:31:19 -070077 mUserManager = UserManagerCompat.getInstance(context);
78 mDb = new CacheDb(context);
Michael Jurka3f4e0702013-02-05 11:21:28 +010079 }
Sunny Goyalffe83f12014-08-14 17:39:34 -070080
Sunny Goyal5b0e6692015-03-19 14:31:19 -070081 /**
82 * Generates the widget preview on {@link AsyncTask#THREAD_POOL_EXECUTOR}. Must be
83 * called on UI thread
84 *
85 * @param o either {@link LauncherAppWidgetProviderInfo} or {@link ResolveInfo}
86 * @param immediateResult A bitmap array of size 1. If the result is already cached, it is
87 * set to the final result.
88 * @return a request id which can be used to cancel the request.
89 */
90 public PreviewLoadRequest getPreview(final Object o, int previewWidth, int previewHeight,
Hyunyoung Song3f471442015-04-08 19:01:34 -070091 WidgetCell caller, Bitmap[] immediateResult) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -070092 String size = previewWidth + "x" + previewHeight;
93 WidgetCacheKey key = getObjectKey(o, size);
Michael Jurka3f4e0702013-02-05 11:21:28 +010094
Sunny Goyal5b0e6692015-03-19 14:31:19 -070095 PreviewLoadTask task = new PreviewLoadTask(key, o, previewWidth, previewHeight, caller);
96 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
Hyunyoung Song559d90d2015-04-28 15:06:45 -070097 return new PreviewLoadRequest(task);
Michael Jurka05713af2013-01-23 12:39:24 +010098 }
99
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700100 /**
101 * The DB holds the generated previews for various components. Previews can also have different
102 * sizes (landscape vs portrait).
103 */
104 private static class CacheDb extends SQLiteOpenHelper {
105 private static final int DB_VERSION = 3;
106
107 private static final String TABLE_NAME = "shortcut_and_widget_previews";
108 private static final String COLUMN_COMPONENT = "componentName";
109 private static final String COLUMN_USER = "profileId";
110 private static final String COLUMN_SIZE = "size";
111 private static final String COLUMN_PACKAGE = "packageName";
112 private static final String COLUMN_LAST_UPDATED = "lastUpdated";
113 private static final String COLUMN_VERSION = "version";
114 private static final String COLUMN_PREVIEW_BITMAP = "preview_bitmap";
Michael Jurka05713af2013-01-23 12:39:24 +0100115
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100116 public CacheDb(Context context) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700117 super(context, LauncherFiles.WIDGET_PREVIEWS_DB, null, DB_VERSION);
Michael Jurka05713af2013-01-23 12:39:24 +0100118 }
119
120 @Override
121 public void onCreate(SQLiteDatabase database) {
Michael Jurka32b7a092013-02-07 20:06:49 +0100122 database.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" +
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700123 COLUMN_COMPONENT + " TEXT NOT NULL, " +
124 COLUMN_USER + " INTEGER NOT NULL, " +
Michael Jurka05713af2013-01-23 12:39:24 +0100125 COLUMN_SIZE + " TEXT NOT NULL, " +
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700126 COLUMN_PACKAGE + " TEXT NOT NULL, " +
127 COLUMN_LAST_UPDATED + " INTEGER NOT NULL DEFAULT 0, " +
128 COLUMN_VERSION + " INTEGER NOT NULL DEFAULT 0, " +
129 COLUMN_PREVIEW_BITMAP + " BLOB, " +
130 "PRIMARY KEY (" + COLUMN_COMPONENT + ", " + COLUMN_USER + ", " + COLUMN_SIZE + ") " +
Michael Jurka32b7a092013-02-07 20:06:49 +0100131 ");");
Michael Jurka05713af2013-01-23 12:39:24 +0100132 }
133
134 @Override
135 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Michael Jurkae5919c52013-03-06 17:30:10 +0100136 if (oldVersion != newVersion) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700137 clearDB(db);
Michael Jurkae5919c52013-03-06 17:30:10 +0100138 }
Michael Jurka05713af2013-01-23 12:39:24 +0100139 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700140
141 @Override
142 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
143 if (oldVersion != newVersion) {
144 clearDB(db);
145 }
146 }
147
148 private void clearDB(SQLiteDatabase db) {
149 db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
150 onCreate(db);
151 }
Michael Jurka05713af2013-01-23 12:39:24 +0100152 }
153
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700154 private WidgetCacheKey getObjectKey(Object o, String size) {
Michael Jurka05713af2013-01-23 12:39:24 +0100155 // should cache the string builder
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700156 if (o instanceof LauncherAppWidgetProviderInfo) {
157 LauncherAppWidgetProviderInfo info = (LauncherAppWidgetProviderInfo) o;
158 return new WidgetCacheKey(info.provider, mManager.getUser(info), size);
Michael Jurka05713af2013-01-23 12:39:24 +0100159 } else {
160 ResolveInfo info = (ResolveInfo) o;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700161 return new WidgetCacheKey(
162 new ComponentName(info.activityInfo.packageName, info.activityInfo.name),
163 UserHandleCompat.myUserHandle(), size);
Michael Jurka05713af2013-01-23 12:39:24 +0100164 }
165 }
166
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700167 @Thunk void writeToDb(WidgetCacheKey key, long[] versions, Bitmap preview) {
Michael Jurka05713af2013-01-23 12:39:24 +0100168 ContentValues values = new ContentValues();
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700169 values.put(CacheDb.COLUMN_COMPONENT, key.componentName.flattenToShortString());
170 values.put(CacheDb.COLUMN_USER, mUserManager.getSerialNumberForUser(key.user));
171 values.put(CacheDb.COLUMN_SIZE, key.size);
172 values.put(CacheDb.COLUMN_PACKAGE, key.componentName.getPackageName());
173 values.put(CacheDb.COLUMN_VERSION, versions[0]);
174 values.put(CacheDb.COLUMN_LAST_UPDATED, versions[1]);
175 values.put(CacheDb.COLUMN_PREVIEW_BITMAP, Utilities.flattenBitmap(preview));
Michael Jurka05713af2013-01-23 12:39:24 +0100176
Michael Jurka6e27f642013-12-10 13:40:30 +0100177 try {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700178 mDb.getWritableDatabase().insertWithOnConflict(CacheDb.TABLE_NAME, null, values,
179 SQLiteDatabase.CONFLICT_REPLACE);
180 } catch (SQLException e) {
181 Log.e(TAG, "Error saving image to DB", e);
Michael Jurka6e27f642013-12-10 13:40:30 +0100182 }
Michael Jurka05713af2013-01-23 12:39:24 +0100183 }
184
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700185 public void removePackage(String packageName, UserHandleCompat user) {
186 removePackage(packageName, user, mUserManager.getSerialNumberForUser(user));
187 }
188
189 private void removePackage(String packageName, UserHandleCompat user, long userSerial) {
190 synchronized(mPackageVersions) {
191 mPackageVersions.remove(packageName);
192 }
193
Michael Jurka6e27f642013-12-10 13:40:30 +0100194 try {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700195 mDb.getWritableDatabase().delete(CacheDb.TABLE_NAME,
196 CacheDb.COLUMN_PACKAGE + " = ? AND " + CacheDb.COLUMN_USER + " = ?",
197 new String[] {packageName, Long.toString(userSerial)});
198 } catch (SQLException e) {
199 Log.e(TAG, "Unable to delete items from DB", e);
Michael Jurka6e27f642013-12-10 13:40:30 +0100200 }
Michael Jurka8ff02ca2013-11-01 14:19:27 +0100201 }
202
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700203 /**
204 * Updates the persistent DB:
205 * 1. Any preview generated for an old package version is removed
206 * 2. Any preview for an absent package is removed
207 * This ensures that we remove entries for packages which changed while the launcher was dead.
208 */
Hyunyoung Song8821ca92015-05-04 16:28:20 -0700209 public void removeObsoletePreviews(ArrayList<Object> list) {
210 // This method should always be called from the worker thread.
211 Assert.assertTrue(LauncherModel.sWorkerThread.getThreadId() == Process.myTid());
212
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700213 LongSparseArray<UserHandleCompat> userIdCache = new LongSparseArray<>();
214 LongSparseArray<HashSet<String>> validPackages = new LongSparseArray<>();
215
Hyunyoung Song8821ca92015-05-04 16:28:20 -0700216 for (Object obj : list) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700217 final UserHandleCompat user;
218 final String pkg;
219 if (obj instanceof ResolveInfo) {
220 user = UserHandleCompat.myUserHandle();
221 pkg = ((ResolveInfo) obj).activityInfo.packageName;
222 } else {
223 LauncherAppWidgetProviderInfo info = (LauncherAppWidgetProviderInfo) obj;
224 user = mManager.getUser(info);
225 pkg = info.provider.getPackageName();
226 }
227
228 int userIdIndex = userIdCache.indexOfValue(user);
229 final long userId;
230 if (userIdIndex < 0) {
231 userId = mUserManager.getSerialNumberForUser(user);
232 userIdCache.put(userId, user);
233 } else {
234 userId = userIdCache.keyAt(userIdIndex);
235 }
236
237 HashSet<String> packages = validPackages.get(userId);
238 if (packages == null) {
239 packages = new HashSet<>();
240 validPackages.put(userId, packages);
241 }
242 packages.add(pkg);
Michael Jurka05713af2013-01-23 12:39:24 +0100243 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700244
245 LongSparseArray<HashSet<String>> packagesToDelete = new LongSparseArray<>();
246 Cursor c = null;
247 try {
248 c = mDb.getReadableDatabase().query(CacheDb.TABLE_NAME,
249 new String[] {CacheDb.COLUMN_USER, CacheDb.COLUMN_PACKAGE,
250 CacheDb.COLUMN_LAST_UPDATED, CacheDb.COLUMN_VERSION},
251 null, null, null, null, null);
252 while (c.moveToNext()) {
253 long userId = c.getLong(0);
254 String pkg = c.getString(1);
255 long lastUpdated = c.getLong(2);
256 long version = c.getLong(3);
257
258 HashSet<String> packages = validPackages.get(userId);
259 if (packages != null && packages.contains(pkg)) {
260 long[] versions = getPackageVersion(pkg);
261 if (versions[0] == version && versions[1] == lastUpdated) {
262 // Every thing checks out
263 continue;
264 }
265 }
266
267 // We need to delete this package.
268 packages = packagesToDelete.get(userId);
269 if (packages == null) {
270 packages = new HashSet<>();
271 packagesToDelete.put(userId, packages);
272 }
273 packages.add(pkg);
274 }
275
276 for (int i = 0; i < packagesToDelete.size(); i++) {
277 long userId = packagesToDelete.keyAt(i);
278 UserHandleCompat user = mUserManager.getUserForSerialNumber(userId);
279 for (String pkg : packagesToDelete.valueAt(i)) {
280 removePackage(pkg, user, userId);
281 }
282 }
283 } catch (SQLException e) {
284 Log.e(TAG, "Error updatating widget previews", e);
285 } finally {
286 if (c != null) {
287 c.close();
288 }
289 }
290 }
291
292 private Bitmap readFromDb(WidgetCacheKey key, Bitmap recycle) {
293 Cursor cursor = null;
294 try {
295 cursor = mDb.getReadableDatabase().query(
296 CacheDb.TABLE_NAME,
297 new String[] { CacheDb.COLUMN_PREVIEW_BITMAP },
298 CacheDb.COLUMN_COMPONENT + " = ? AND " + CacheDb.COLUMN_USER + " = ? AND " + CacheDb.COLUMN_SIZE + " = ?",
299 new String[] {
300 key.componentName.flattenToString(),
301 Long.toString(mUserManager.getSerialNumberForUser(key.user)),
302 key.size
303 },
304 null, null, null);
305 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 {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700310 return BitmapFactory.decodeByteArray(blob, 0, blob.length, opts);
311 } catch (Exception e) {
312 return null;
Michael Jurka6e27f642013-12-10 13:40:30 +0100313 }
Michael Jurka05713af2013-01-23 12:39:24 +0100314 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700315 } catch (SQLException e) {
316 Log.w(TAG, "Error loading preview from DB", e);
317 } finally {
318 if (cursor != null) {
319 cursor.close();
320 }
321 }
322 return null;
Michael Jurka05713af2013-01-23 12:39:24 +0100323 }
324
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700325 private Bitmap generatePreview(Object info, Bitmap recycle, int previewWidth, int previewHeight) {
Adam Cohen59400422014-03-05 18:07:04 -0800326 if (info instanceof LauncherAppWidgetProviderInfo) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700327 return generateWidgetPreview((LauncherAppWidgetProviderInfo) info, previewWidth, recycle);
Michael Jurka05713af2013-01-23 12:39:24 +0100328 } else {
329 return generateShortcutPreview(
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700330 (ResolveInfo) info, previewWidth, previewHeight, recycle);
Michael Jurka05713af2013-01-23 12:39:24 +0100331 }
332 }
333
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700334 public Bitmap generateWidgetPreview(LauncherAppWidgetProviderInfo info,
335 int previewWidth, Bitmap preview) {
336 int maxWidth = Math.min(previewWidth, info.spanX
337 * LauncherAppState.getInstance().getDynamicGrid().getDeviceProfile().cellWidthPx);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700338 return generateWidgetPreview(info, maxWidth, preview, null);
Michael Jurka05713af2013-01-23 12:39:24 +0100339 }
340
Sunny Goyal4cad7532015-03-18 15:56:30 -0700341 public Bitmap generateWidgetPreview(LauncherAppWidgetProviderInfo info,
342 int maxPreviewWidth, Bitmap preview, int[] preScaledWidthOut) {
Michael Jurka05713af2013-01-23 12:39:24 +0100343 // Load the preview image if possible
Michael Jurka05713af2013-01-23 12:39:24 +0100344 if (maxPreviewWidth < 0) maxPreviewWidth = Integer.MAX_VALUE;
Michael Jurka05713af2013-01-23 12:39:24 +0100345
346 Drawable drawable = null;
Sunny Goyalffe83f12014-08-14 17:39:34 -0700347 if (info.previewImage != 0) {
348 drawable = mManager.loadPreview(info);
Adrian Roosfa9ffc22014-05-12 15:59:59 +0200349 if (drawable != null) {
350 drawable = mutateOnMainThread(drawable);
351 } else {
Michael Jurka05713af2013-01-23 12:39:24 +0100352 Log.w(TAG, "Can't load widget preview drawable 0x" +
Sunny Goyalffe83f12014-08-14 17:39:34 -0700353 Integer.toHexString(info.previewImage) + " for provider: " + info.provider);
Michael Jurka05713af2013-01-23 12:39:24 +0100354 }
355 }
356
Sunny Goyal4cad7532015-03-18 15:56:30 -0700357 final boolean widgetPreviewExists = (drawable != null);
358 final int spanX = info.spanX < 1 ? 1 : info.spanX;
359 final int spanY = info.spanY < 1 ? 1 : info.spanY;
360
Michael Jurka05713af2013-01-23 12:39:24 +0100361 int previewWidth;
362 int previewHeight;
Sunny Goyal4cad7532015-03-18 15:56:30 -0700363 Bitmap tileBitmap = null;
364
Michael Jurka05713af2013-01-23 12:39:24 +0100365 if (widgetPreviewExists) {
366 previewWidth = drawable.getIntrinsicWidth();
367 previewHeight = drawable.getIntrinsicHeight();
368 } else {
369 // Generate a preview image if we couldn't load one
Sunny Goyal4cad7532015-03-18 15:56:30 -0700370 tileBitmap = ((BitmapDrawable) mContext.getResources().getDrawable(
371 R.drawable.widget_tile)).getBitmap();
372 previewWidth = tileBitmap.getWidth() * spanX;
373 previewHeight = tileBitmap.getHeight() * spanY;
Michael Jurka05713af2013-01-23 12:39:24 +0100374 }
375
376 // Scale to fit width only - let the widget preview be clipped in the
377 // vertical dimension
378 float scale = 1f;
379 if (preScaledWidthOut != null) {
380 preScaledWidthOut[0] = previewWidth;
381 }
382 if (previewWidth > maxPreviewWidth) {
383 scale = maxPreviewWidth / (float) previewWidth;
384 }
385 if (scale != 1f) {
386 previewWidth = (int) (scale * previewWidth);
387 previewHeight = (int) (scale * previewHeight);
388 }
389
390 // 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 -0700391 final Canvas c = new Canvas();
Michael Jurka05713af2013-01-23 12:39:24 +0100392 if (preview == null) {
393 preview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700394 c.setBitmap(preview);
395 } else {
396 // Reusing bitmap. Clear it.
397 c.setBitmap(preview);
398 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100399 }
400
401 // Draw the scaled preview into the final bitmap
402 int x = (preview.getWidth() - previewWidth) / 2;
403 if (widgetPreviewExists) {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700404 drawable.setBounds(x, 0, x + previewWidth, previewHeight);
405 drawable.draw(c);
Michael Jurka05713af2013-01-23 12:39:24 +0100406 } else {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700407 final Paint p = new Paint();
408 p.setFilterBitmap(true);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700409 int appIconSize = LauncherAppState.getInstance().getDynamicGrid()
410 .getDeviceProfile().iconSizePx;
Michael Jurka05713af2013-01-23 12:39:24 +0100411
Sunny Goyal4cad7532015-03-18 15:56:30 -0700412 // draw the spanX x spanY tiles
413 final Rect src = new Rect(0, 0, tileBitmap.getWidth(), tileBitmap.getHeight());
414
415 float tileW = scale * tileBitmap.getWidth();
416 float tileH = scale * tileBitmap.getHeight();
417 final RectF dst = new RectF(0, 0, tileW, tileH);
418
419 float tx = x;
420 for (int i = 0; i < spanX; i++, tx += tileW) {
421 float ty = 0;
422 for (int j = 0; j < spanY; j++, ty += tileH) {
423 dst.offsetTo(tx, ty);
424 c.drawBitmap(tileBitmap, src, dst, p);
425 }
Michael Jurka05713af2013-01-23 12:39:24 +0100426 }
Sunny Goyal4cad7532015-03-18 15:56:30 -0700427
428 // Draw the icon in the top left corner
429 // TODO: use top right for RTL
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700430 int minOffset = (int) (appIconSize * WIDGET_PREVIEW_ICON_PADDING_PERCENTAGE);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700431 int smallestSide = Math.min(previewWidth, previewHeight);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700432 float iconScale = Math.min((float) smallestSide / (appIconSize + 2 * minOffset), scale);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700433
434 try {
435 Drawable icon = mutateOnMainThread(mManager.loadIcon(info, mIconCache));
436 if (icon != null) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700437 int hoffset = (int) ((tileW - appIconSize * iconScale) / 2) + x;
438 int yoffset = (int) ((tileH - appIconSize * iconScale) / 2);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700439 icon.setBounds(hoffset, yoffset,
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700440 hoffset + (int) (appIconSize * iconScale),
441 yoffset + (int) (appIconSize * iconScale));
Sunny Goyal4cad7532015-03-18 15:56:30 -0700442 icon.draw(c);
443 }
444 } catch (Resources.NotFoundException e) { }
Michael Jurka05713af2013-01-23 12:39:24 +0100445 c.setBitmap(null);
446 }
Sunny Goyalffe83f12014-08-14 17:39:34 -0700447 return mManager.getBadgeBitmap(info, preview);
Michael Jurka05713af2013-01-23 12:39:24 +0100448 }
449
450 private Bitmap generateShortcutPreview(
451 ResolveInfo info, int maxWidth, int maxHeight, Bitmap preview) {
Sunny Goyal4cad7532015-03-18 15:56:30 -0700452 final Canvas c = new Canvas();
453 if (preview == null) {
Michael Jurka05713af2013-01-23 12:39:24 +0100454 preview = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700455 c.setBitmap(preview);
456 } else if (preview.getWidth() != maxWidth || preview.getHeight() != maxHeight) {
457 throw new RuntimeException("Improperly sized bitmap passed as argument");
458 } else {
459 // Reusing bitmap. Clear it.
460 c.setBitmap(preview);
461 c.drawColor(0, PorterDuff.Mode.CLEAR);
Michael Jurka05713af2013-01-23 12:39:24 +0100462 }
463
Sunny Goyal4cad7532015-03-18 15:56:30 -0700464 Drawable icon = mutateOnMainThread(mIconCache.getFullResIcon(info.activityInfo));
465 icon.setFilterBitmap(true);
466
Michael Jurka05713af2013-01-23 12:39:24 +0100467 // Draw a desaturated/scaled version of the icon in the background as a watermark
Sunny Goyal4cad7532015-03-18 15:56:30 -0700468 ColorMatrix colorMatrix = new ColorMatrix();
469 colorMatrix.setSaturation(0);
470 icon.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
471 icon.setAlpha((int) (255 * 0.06f));
472
473 Resources res = mContext.getResources();
474 int paddingTop = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_top);
475 int paddingLeft = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_left);
476 int paddingRight = res.getDimensionPixelOffset(R.dimen.shortcut_preview_padding_right);
477 int scaledIconWidth = (maxWidth - paddingLeft - paddingRight);
478 icon.setBounds(paddingLeft, paddingTop,
479 paddingLeft + scaledIconWidth, paddingTop + scaledIconWidth);
480 icon.draw(c);
481
482 // Draw the final icon at top left corner.
483 // TODO: use top right for RTL
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700484 int appIconSize = LauncherAppState.getInstance().getDynamicGrid()
485 .getDeviceProfile().iconSizePx;
Sunny Goyal4cad7532015-03-18 15:56:30 -0700486 icon.setAlpha(255);
487 icon.setColorFilter(null);
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700488 icon.setBounds(0, 0, appIconSize, appIconSize);
Sunny Goyal4cad7532015-03-18 15:56:30 -0700489 icon.draw(c);
490
Michael Jurka05713af2013-01-23 12:39:24 +0100491 c.setBitmap(null);
Michael Jurka05713af2013-01-23 12:39:24 +0100492 return preview;
493 }
494
Adrian Roos65d60e22014-04-15 21:07:49 +0200495 private Drawable mutateOnMainThread(final Drawable drawable) {
496 try {
497 return mMainThreadExecutor.submit(new Callable<Drawable>() {
498 @Override
499 public Drawable call() throws Exception {
500 return drawable.mutate();
501 }
502 }).get();
503 } catch (InterruptedException e) {
504 Thread.currentThread().interrupt();
505 throw new RuntimeException(e);
506 } catch (ExecutionException e) {
507 throw new RuntimeException(e);
508 }
509 }
Adrian Roos1f375ab2014-04-28 18:26:38 +0200510
Adrian Roos1f375ab2014-04-28 18:26:38 +0200511 /**
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700512 * @return an array of containing versionCode and lastUpdatedTime for the package.
Adrian Roos1f375ab2014-04-28 18:26:38 +0200513 */
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700514 private long[] getPackageVersion(String packageName) {
515 synchronized (mPackageVersions) {
516 long[] versions = mPackageVersions.get(packageName);
517 if (versions == null) {
518 versions = new long[2];
Adrian Roos1f375ab2014-04-28 18:26:38 +0200519 try {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700520 PackageInfo info = mContext.getPackageManager().getPackageInfo(packageName, 0);
521 versions[0] = info.versionCode;
522 versions[1] = info.lastUpdateTime;
523 } catch (NameNotFoundException e) {
524 Log.e(TAG, "PackageInfo not found", e);
525 }
526 mPackageVersions.put(packageName, versions);
527 }
528 return versions;
529 }
530 }
531
532 /**
533 * A request Id which can be used by the client to cancel any request.
534 */
535 public class PreviewLoadRequest {
536
537 private final PreviewLoadTask mTask;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700538
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700539 public PreviewLoadRequest(PreviewLoadTask task) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700540 mTask = task;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700541 }
542
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700543 public void cleanup() {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700544 if (mTask != null) {
545 mTask.cancel(true);
546 }
547
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700548 if (mTask.mBitmap == null) {
549 return;
Adrian Roos1f375ab2014-04-28 18:26:38 +0200550 }
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700551
552 // The preview is no longer bound to any view, move it to {@link WeakReference} list.
553 synchronized(mUnusedBitmaps) {
554 mUnusedBitmaps.add(mTask.mBitmap);
555 }
556 mTask.mBitmap = null;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700557 }
558 }
559
560 public class PreviewLoadTask extends AsyncTask<Void, Void, Bitmap> {
561
562 private final WidgetCacheKey mKey;
563 private final Object mInfo;
564 private final int mPreviewHeight;
565 private final int mPreviewWidth;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700566 private final WidgetCell mCaller;
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700567 private Bitmap mBitmap;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700568
569 PreviewLoadTask(WidgetCacheKey key, Object info, int previewWidth,
Hyunyoung Song3f471442015-04-08 19:01:34 -0700570 int previewHeight, WidgetCell caller) {
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700571 mKey = key;
572 mInfo = info;
573 mPreviewHeight = previewHeight;
574 mPreviewWidth = previewWidth;
575 mCaller = caller;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700576 if (DEBUG) {
577 Log.d(TAG, String.format("%s, %s, %d, %d",
578 mKey, mInfo, mPreviewHeight, mPreviewWidth));
579 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700580 }
581
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700582 @Override
583 protected Bitmap doInBackground(Void... params) {
584 Bitmap unusedBitmap = null;
Hyunyoung Song3f471442015-04-08 19:01:34 -0700585
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700586 synchronized (mUnusedBitmaps) {
587 // Check if we can use a bitmap
588 for (Bitmap candidate : mUnusedBitmaps) {
589 if (candidate != null && candidate.isMutable() &&
590 candidate.getWidth() == mPreviewWidth &&
591 candidate.getHeight() == mPreviewHeight) {
592 unusedBitmap = candidate;
593 break;
594 }
595 }
596
597 if (unusedBitmap == null) {
598 unusedBitmap = Bitmap.createBitmap(mPreviewWidth, mPreviewHeight, Config.ARGB_8888);
599 } else {
600 mUnusedBitmaps.remove(unusedBitmap);
601 }
Adrian Roos1f375ab2014-04-28 18:26:38 +0200602 }
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700603 if (isCancelled()) {
604 return null;
605 }
606 Bitmap preview = readFromDb(mKey, unusedBitmap);
607 if (!isCancelled() && preview == null) {
608 // Fetch the version info before we generate the preview, so that, in-case the
609 // app was updated while we are generating the preview, we use the old version info,
610 // which would gets re-written next time.
611 long[] versions = getPackageVersion(mKey.componentName.getPackageName());
612
613 // it's not in the db... we need to generate it
614 preview = generatePreview(mInfo, unusedBitmap, mPreviewWidth, mPreviewHeight);
615
616 if (!isCancelled()) {
617 writeToDb(mKey, versions, preview);
618 }
619 }
620
621 return preview;
622 }
623
624 @Override
625 protected void onPostExecute(Bitmap result) {
Hyunyoung Song559d90d2015-04-28 15:06:45 -0700626 mBitmap = result;
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700627 mCaller.applyPreview(result);
628 }
629 }
630
631 private static final class WidgetCacheKey extends ComponentKey {
632
633 // TODO: remove dependency on size
634 private final String size;
635
636 public WidgetCacheKey(ComponentName componentName, UserHandleCompat user, String size) {
637 super(componentName, user);
638 this.size = size;
639 }
640
641 @Override
642 public int hashCode() {
643 return super.hashCode() ^ size.hashCode();
644 }
645
646 @Override
647 public boolean equals(Object o) {
648 return super.equals(o) && ((WidgetCacheKey) o).size.equals(size);
Adrian Roos1f375ab2014-04-28 18:26:38 +0200649 }
650 }
Michael Jurka05713af2013-01-23 12:39:24 +0100651}