blob: 3128140394270c0f3ea7aba55190668d63498f81 [file] [log] [blame]
Daniel Sandler325dc232013-06-05 22:57:57 -04001package com.android.launcher3;
Michael Jurka05713af2013-01-23 12:39:24 +01002
3import android.appwidget.AppWidgetProviderInfo;
4import android.content.ComponentName;
5import android.content.ContentValues;
6import android.content.Context;
Michael Jurka8ff02ca2013-11-01 14:19:27 +01007import android.content.SharedPreferences;
Michael Jurka05713af2013-01-23 12:39:24 +01008import android.content.pm.ResolveInfo;
9import android.content.res.Resources;
10import android.database.Cursor;
Adrian Roos1f375ab2014-04-28 18:26:38 +020011import android.database.sqlite.SQLiteCantOpenDatabaseException;
Michael Jurka05713af2013-01-23 12:39:24 +010012import android.database.sqlite.SQLiteDatabase;
Michael Jurka6e27f642013-12-10 13:40:30 +010013import android.database.sqlite.SQLiteDiskIOException;
Michael Jurka05713af2013-01-23 12:39:24 +010014import android.database.sqlite.SQLiteOpenHelper;
Winson Chung5f059132014-12-01 15:05:17 -080015import android.database.sqlite.SQLiteReadOnlyDatabaseException;
Michael Jurka05713af2013-01-23 12:39:24 +010016import android.graphics.Bitmap;
17import android.graphics.Bitmap.Config;
18import android.graphics.BitmapFactory;
Adrian Roosfa4c7992014-03-19 15:58:14 +010019import android.graphics.BitmapShader;
Michael Jurka05713af2013-01-23 12:39:24 +010020import android.graphics.Canvas;
21import android.graphics.ColorMatrix;
22import android.graphics.ColorMatrixColorFilter;
23import android.graphics.Paint;
24import android.graphics.PorterDuff;
25import android.graphics.Rect;
26import android.graphics.Shader;
27import android.graphics.drawable.BitmapDrawable;
28import android.graphics.drawable.Drawable;
29import android.os.AsyncTask;
Winson Chung5f059132014-12-01 15:05:17 -080030import android.os.Build;
Michael Jurka05713af2013-01-23 12:39:24 +010031import android.util.Log;
Sunny Goyalffe83f12014-08-14 17:39:34 -070032import com.android.launcher3.compat.AppWidgetManagerCompat;
33
Michael Jurka05713af2013-01-23 12:39:24 +010034import java.io.ByteArrayOutputStream;
35import java.io.File;
Adrian Roos1f375ab2014-04-28 18:26:38 +020036import java.io.IOException;
Michael Jurka05713af2013-01-23 12:39:24 +010037import java.lang.ref.SoftReference;
38import java.lang.ref.WeakReference;
39import java.util.ArrayList;
Adrian Roos1f375ab2014-04-28 18:26:38 +020040import java.util.Arrays;
Michael Jurka05713af2013-01-23 12:39:24 +010041import java.util.HashMap;
42import java.util.HashSet;
Adrian Roos1f375ab2014-04-28 18:26:38 +020043import java.util.List;
Adrian Roos65d60e22014-04-15 21:07:49 +020044import java.util.concurrent.Callable;
45import java.util.concurrent.ExecutionException;
Michael Jurka05713af2013-01-23 12:39:24 +010046
Sunny Goyalffe83f12014-08-14 17:39:34 -070047public class WidgetPreviewLoader {
Michael Jurka05713af2013-01-23 12:39:24 +010048
Sunny Goyalffe83f12014-08-14 17:39:34 -070049 private static abstract class SoftReferenceThreadLocal<T> {
50 private ThreadLocal<SoftReference<T>> mThreadLocal;
51 public SoftReferenceThreadLocal() {
52 mThreadLocal = new ThreadLocal<SoftReference<T>>();
53 }
Michael Jurka05713af2013-01-23 12:39:24 +010054
Sunny Goyalffe83f12014-08-14 17:39:34 -070055 abstract T initialValue();
Michael Jurka05713af2013-01-23 12:39:24 +010056
Sunny Goyalffe83f12014-08-14 17:39:34 -070057 public void set(T t) {
58 mThreadLocal.set(new SoftReference<T>(t));
59 }
60
61 public T get() {
62 SoftReference<T> reference = mThreadLocal.get();
63 T obj;
64 if (reference == null) {
Michael Jurka05713af2013-01-23 12:39:24 +010065 obj = initialValue();
66 mThreadLocal.set(new SoftReference<T>(obj));
Sunny Goyalffe83f12014-08-14 17:39:34 -070067 return obj;
68 } else {
69 obj = reference.get();
70 if (obj == null) {
71 obj = initialValue();
72 mThreadLocal.set(new SoftReference<T>(obj));
73 }
74 return obj;
Michael Jurka05713af2013-01-23 12:39:24 +010075 }
Michael Jurka05713af2013-01-23 12:39:24 +010076 }
77 }
Michael Jurka05713af2013-01-23 12:39:24 +010078
Sunny Goyalffe83f12014-08-14 17:39:34 -070079 private static class CanvasCache extends SoftReferenceThreadLocal<Canvas> {
80 @Override
81 protected Canvas initialValue() {
82 return new Canvas();
83 }
Michael Jurka05713af2013-01-23 12:39:24 +010084 }
Michael Jurka05713af2013-01-23 12:39:24 +010085
Sunny Goyalffe83f12014-08-14 17:39:34 -070086 private static class PaintCache extends SoftReferenceThreadLocal<Paint> {
87 @Override
88 protected Paint initialValue() {
89 return null;
90 }
Michael Jurka05713af2013-01-23 12:39:24 +010091 }
Michael Jurka05713af2013-01-23 12:39:24 +010092
Sunny Goyalffe83f12014-08-14 17:39:34 -070093 private static class BitmapCache extends SoftReferenceThreadLocal<Bitmap> {
94 @Override
95 protected Bitmap initialValue() {
96 return null;
97 }
Michael Jurka05713af2013-01-23 12:39:24 +010098 }
Michael Jurka05713af2013-01-23 12:39:24 +010099
Sunny Goyalffe83f12014-08-14 17:39:34 -0700100 private static class RectCache extends SoftReferenceThreadLocal<Rect> {
101 @Override
102 protected Rect initialValue() {
103 return new Rect();
104 }
Michael Jurka05713af2013-01-23 12:39:24 +0100105 }
Michael Jurka05713af2013-01-23 12:39:24 +0100106
Sunny Goyalffe83f12014-08-14 17:39:34 -0700107 private static class BitmapFactoryOptionsCache extends
108 SoftReferenceThreadLocal<BitmapFactory.Options> {
109 @Override
110 protected BitmapFactory.Options initialValue() {
111 return new BitmapFactory.Options();
112 }
Michael Jurka05713af2013-01-23 12:39:24 +0100113 }
Michael Jurka05713af2013-01-23 12:39:24 +0100114
Sunny Goyalffe83f12014-08-14 17:39:34 -0700115 private static final String TAG = "WidgetPreviewLoader";
116 private static final String ANDROID_INCREMENTAL_VERSION_NAME_KEY = "android.incremental.version";
117
118 private static final float WIDGET_PREVIEW_ICON_PADDING_PERCENTAGE = 0.25f;
119 private static final HashSet<String> sInvalidPackages = new HashSet<String>();
120
121 // Used for drawing shortcut previews
122 private final BitmapCache mCachedShortcutPreviewBitmap = new BitmapCache();
123 private final PaintCache mCachedShortcutPreviewPaint = new PaintCache();
124 private final CanvasCache mCachedShortcutPreviewCanvas = new CanvasCache();
125
126 // Used for drawing widget previews
127 private final CanvasCache mCachedAppWidgetPreviewCanvas = new CanvasCache();
128 private final RectCache mCachedAppWidgetPreviewSrcRect = new RectCache();
129 private final RectCache mCachedAppWidgetPreviewDestRect = new RectCache();
130 private final PaintCache mCachedAppWidgetPreviewPaint = new PaintCache();
131 private final PaintCache mDefaultAppWidgetPreviewPaint = new PaintCache();
132 private final BitmapFactoryOptionsCache mCachedBitmapFactoryOptions = new BitmapFactoryOptionsCache();
133
Winson Chungb745afb2015-03-02 11:51:23 -0800134 private final HashMap<String, WeakReference<Bitmap>> mLoadedPreviews = new HashMap<>();
135 private final ArrayList<SoftReference<Bitmap>> mUnusedBitmaps = new ArrayList<>();
Sunny Goyalffe83f12014-08-14 17:39:34 -0700136
137 private final Context mContext;
138 private final int mAppIconSize;
139 private final IconCache mIconCache;
140 private final AppWidgetManagerCompat mManager;
Michael Jurka05713af2013-01-23 12:39:24 +0100141
Michael Jurka3f4e0702013-02-05 11:21:28 +0100142 private int mPreviewBitmapWidth;
143 private int mPreviewBitmapHeight;
Michael Jurka05713af2013-01-23 12:39:24 +0100144 private String mSize;
Michael Jurka05713af2013-01-23 12:39:24 +0100145 private PagedViewCellLayout mWidgetSpacingLayout;
146
Michael Jurka05713af2013-01-23 12:39:24 +0100147 private String mCachedSelectQuery;
Michael Jurka05713af2013-01-23 12:39:24 +0100148
Michael Jurka05713af2013-01-23 12:39:24 +0100149
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100150 private CacheDb mDb;
Michael Jurka05713af2013-01-23 12:39:24 +0100151
Adrian Roos65d60e22014-04-15 21:07:49 +0200152 private final MainThreadExecutor mMainThreadExecutor = new MainThreadExecutor();
153
Chris Wrenfd13c712013-09-27 15:45:19 -0400154 public WidgetPreviewLoader(Context context) {
Winson Chung5f8afe62013-08-12 16:19:28 -0700155 LauncherAppState app = LauncherAppState.getInstance();
156 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
157
Chris Wrenfd13c712013-09-27 15:45:19 -0400158 mContext = context;
Winson Chung5f8afe62013-08-12 16:19:28 -0700159 mAppIconSize = grid.iconSizePx;
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100160 mIconCache = app.getIconCache();
Sunny Goyalffe83f12014-08-14 17:39:34 -0700161 mManager = AppWidgetManagerCompat.getInstance(context);
162
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100163 mDb = app.getWidgetPreviewCacheDb();
Michael Jurka8ff02ca2013-11-01 14:19:27 +0100164
165 SharedPreferences sp = context.getSharedPreferences(
166 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
167 final String lastVersionName = sp.getString(ANDROID_INCREMENTAL_VERSION_NAME_KEY, null);
168 final String versionName = android.os.Build.VERSION.INCREMENTAL;
Adam Cohen02509452014-12-04 10:34:57 -0800169 final boolean isLollipopOrGreater = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
Michael Jurka8ff02ca2013-11-01 14:19:27 +0100170 if (!versionName.equals(lastVersionName)) {
Winson Chung5f059132014-12-01 15:05:17 -0800171 try {
172 // clear all the previews whenever the system version changes, to ensure that
173 // previews are up-to-date for any apps that might have been updated with the system
174 clearDb();
175 } catch (SQLiteReadOnlyDatabaseException e) {
Adam Cohen02509452014-12-04 10:34:57 -0800176 if (isLollipopOrGreater) {
Winson Chung5f059132014-12-01 15:05:17 -0800177 // Workaround for Bug. 18554839, if we fail to clear the db due to the read-only
178 // issue, then ignore this error and leave the old previews
179 } else {
180 throw e;
181 }
Winson Chung5f059132014-12-01 15:05:17 -0800182 } finally {
183 SharedPreferences.Editor editor = sp.edit();
184 editor.putString(ANDROID_INCREMENTAL_VERSION_NAME_KEY, versionName);
185 editor.commit();
186 }
Michael Jurka8ff02ca2013-11-01 14:19:27 +0100187 }
Michael Jurka3f4e0702013-02-05 11:21:28 +0100188 }
Sunny Goyalffe83f12014-08-14 17:39:34 -0700189
Michael Jurka6e27f642013-12-10 13:40:30 +0100190 public void recreateDb() {
191 LauncherAppState app = LauncherAppState.getInstance();
192 app.recreateWidgetPreviewDb();
193 mDb = app.getWidgetPreviewCacheDb();
194 }
Michael Jurka3f4e0702013-02-05 11:21:28 +0100195
196 public void setPreviewSize(int previewWidth, int previewHeight,
197 PagedViewCellLayout widgetSpacingLayout) {
198 mPreviewBitmapWidth = previewWidth;
199 mPreviewBitmapHeight = previewHeight;
200 mSize = previewWidth + "x" + previewHeight;
201 mWidgetSpacingLayout = widgetSpacingLayout;
Michael Jurka05713af2013-01-23 12:39:24 +0100202 }
203
204 public Bitmap getPreview(final Object o) {
Michael Jurkaeb1bb922013-09-26 11:29:01 -0700205 final String name = getObjectName(o);
206 final String packageName = getObjectPackage(o);
Michael Jurka05713af2013-01-23 12:39:24 +0100207 // check if the package is valid
Michael Jurka05713af2013-01-23 12:39:24 +0100208 synchronized(sInvalidPackages) {
Adrian Roos5d2704f2014-03-18 23:09:12 +0100209 boolean packageValid = !sInvalidPackages.contains(packageName);
210 if (!packageValid) {
211 return null;
212 }
Michael Jurka05713af2013-01-23 12:39:24 +0100213 }
Adrian Roos5d2704f2014-03-18 23:09:12 +0100214 synchronized(mLoadedPreviews) {
215 // check if it exists in our existing cache
216 if (mLoadedPreviews.containsKey(name)) {
217 WeakReference<Bitmap> bitmapReference = mLoadedPreviews.get(name);
218 Bitmap bitmap = bitmapReference.get();
219 if (bitmap != null) {
220 return bitmap;
Michael Jurka05713af2013-01-23 12:39:24 +0100221 }
222 }
223 }
224
225 Bitmap unusedBitmap = null;
Michael Jurka3f4e0702013-02-05 11:21:28 +0100226 synchronized(mUnusedBitmaps) {
Michael Jurka05713af2013-01-23 12:39:24 +0100227 // not in cache; we need to load it from the db
Adrian Roos5d2704f2014-03-18 23:09:12 +0100228 while (unusedBitmap == null && mUnusedBitmaps.size() > 0) {
229 Bitmap candidate = mUnusedBitmaps.remove(0).get();
230 if (candidate != null && candidate.isMutable() &&
231 candidate.getWidth() == mPreviewBitmapWidth &&
232 candidate.getHeight() == mPreviewBitmapHeight) {
233 unusedBitmap = candidate;
234 }
Michael Jurka05713af2013-01-23 12:39:24 +0100235 }
236 if (unusedBitmap != null) {
237 final Canvas c = mCachedAppWidgetPreviewCanvas.get();
238 c.setBitmap(unusedBitmap);
239 c.drawColor(0, PorterDuff.Mode.CLEAR);
240 c.setBitmap(null);
241 }
242 }
243
244 if (unusedBitmap == null) {
Michael Jurka3f4e0702013-02-05 11:21:28 +0100245 unusedBitmap = Bitmap.createBitmap(mPreviewBitmapWidth, mPreviewBitmapHeight,
Michael Jurka05713af2013-01-23 12:39:24 +0100246 Bitmap.Config.ARGB_8888);
247 }
Adrian Roos5d2704f2014-03-18 23:09:12 +0100248 Bitmap preview = readFromDb(name, unusedBitmap);
Michael Jurka05713af2013-01-23 12:39:24 +0100249
250 if (preview != null) {
Michael Jurka3f4e0702013-02-05 11:21:28 +0100251 synchronized(mLoadedPreviews) {
252 mLoadedPreviews.put(name, new WeakReference<Bitmap>(preview));
Michael Jurka05713af2013-01-23 12:39:24 +0100253 }
254 return preview;
255 } else {
256 // it's not in the db... we need to generate it
257 final Bitmap generatedPreview = generatePreview(o, unusedBitmap);
258 preview = generatedPreview;
259 if (preview != unusedBitmap) {
260 throw new RuntimeException("generatePreview is not recycling the bitmap " + o);
261 }
262
Michael Jurka3f4e0702013-02-05 11:21:28 +0100263 synchronized(mLoadedPreviews) {
264 mLoadedPreviews.put(name, new WeakReference<Bitmap>(preview));
Michael Jurka05713af2013-01-23 12:39:24 +0100265 }
266
267 // write to db on a thread pool... this can be done lazily and improves the performance
268 // of the first time widget previews are loaded
269 new AsyncTask<Void, Void, Void>() {
270 public Void doInBackground(Void ... args) {
271 writeToDb(o, generatedPreview);
272 return null;
273 }
274 }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
275
276 return preview;
277 }
278 }
279
Michael Jurkaee8e99f2013-02-07 13:27:06 +0100280 public void recycleBitmap(Object o, Bitmap bitmapToRecycle) {
Michael Jurka05713af2013-01-23 12:39:24 +0100281 String name = getObjectName(o);
Michael Jurka5140cfa2013-02-15 14:50:15 +0100282 synchronized (mLoadedPreviews) {
283 if (mLoadedPreviews.containsKey(name)) {
Michael Jurka3f4e0702013-02-05 11:21:28 +0100284 Bitmap b = mLoadedPreviews.get(name).get();
Michael Jurkaee8e99f2013-02-07 13:27:06 +0100285 if (b == bitmapToRecycle) {
Michael Jurka3f4e0702013-02-05 11:21:28 +0100286 mLoadedPreviews.remove(name);
Michael Jurkaee8e99f2013-02-07 13:27:06 +0100287 if (bitmapToRecycle.isMutable()) {
Michael Jurka5140cfa2013-02-15 14:50:15 +0100288 synchronized (mUnusedBitmaps) {
289 mUnusedBitmaps.add(new SoftReference<Bitmap>(b));
290 }
Michael Jurka05713af2013-01-23 12:39:24 +0100291 }
292 } else {
293 throw new RuntimeException("Bitmap passed in doesn't match up");
294 }
295 }
296 }
297 }
298
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100299 static class CacheDb extends SQLiteOpenHelper {
Michael Jurkae5919c52013-03-06 17:30:10 +0100300 final static int DB_VERSION = 2;
Michael Jurka05713af2013-01-23 12:39:24 +0100301 final static String TABLE_NAME = "shortcut_and_widget_previews";
302 final static String COLUMN_NAME = "name";
303 final static String COLUMN_SIZE = "size";
304 final static String COLUMN_PREVIEW_BITMAP = "preview_bitmap";
305 Context mContext;
306
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100307 public CacheDb(Context context) {
Helena Josol4fbbb3e2014-10-06 16:06:46 +0100308 super(context, new File(context.getCacheDir(),
309 LauncherFiles.WIDGET_PREVIEWS_DB).getPath(), null, DB_VERSION);
Michael Jurka05713af2013-01-23 12:39:24 +0100310 // Store the context for later use
311 mContext = context;
312 }
313
314 @Override
315 public void onCreate(SQLiteDatabase database) {
Michael Jurka32b7a092013-02-07 20:06:49 +0100316 database.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" +
Michael Jurka05713af2013-01-23 12:39:24 +0100317 COLUMN_NAME + " TEXT NOT NULL, " +
318 COLUMN_SIZE + " TEXT NOT NULL, " +
319 COLUMN_PREVIEW_BITMAP + " BLOB NOT NULL, " +
320 "PRIMARY KEY (" + COLUMN_NAME + ", " + COLUMN_SIZE + ") " +
Michael Jurka32b7a092013-02-07 20:06:49 +0100321 ");");
Michael Jurka05713af2013-01-23 12:39:24 +0100322 }
323
324 @Override
325 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Michael Jurkae5919c52013-03-06 17:30:10 +0100326 if (oldVersion != newVersion) {
327 // Delete all the records; they'll be repopulated as this is a cache
328 db.execSQL("DELETE FROM " + TABLE_NAME);
329 }
Michael Jurka05713af2013-01-23 12:39:24 +0100330 }
331 }
332
333 private static final String WIDGET_PREFIX = "Widget:";
334 private static final String SHORTCUT_PREFIX = "Shortcut:";
335
336 private static String getObjectName(Object o) {
337 // should cache the string builder
338 StringBuilder sb = new StringBuilder();
339 String output;
340 if (o instanceof AppWidgetProviderInfo) {
341 sb.append(WIDGET_PREFIX);
Sunny Goyalffe83f12014-08-14 17:39:34 -0700342 sb.append(((AppWidgetProviderInfo) o).toString());
Michael Jurka05713af2013-01-23 12:39:24 +0100343 output = sb.toString();
344 sb.setLength(0);
345 } else {
346 sb.append(SHORTCUT_PREFIX);
Michael Jurka05713af2013-01-23 12:39:24 +0100347 ResolveInfo info = (ResolveInfo) o;
348 sb.append(new ComponentName(info.activityInfo.packageName,
349 info.activityInfo.name).flattenToString());
350 output = sb.toString();
351 sb.setLength(0);
352 }
353 return output;
354 }
355
356 private String getObjectPackage(Object o) {
357 if (o instanceof AppWidgetProviderInfo) {
358 return ((AppWidgetProviderInfo) o).provider.getPackageName();
359 } else {
360 ResolveInfo info = (ResolveInfo) o;
361 return info.activityInfo.packageName;
362 }
363 }
364
365 private void writeToDb(Object o, Bitmap preview) {
366 String name = getObjectName(o);
367 SQLiteDatabase db = mDb.getWritableDatabase();
368 ContentValues values = new ContentValues();
369
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100370 values.put(CacheDb.COLUMN_NAME, name);
Michael Jurka05713af2013-01-23 12:39:24 +0100371 ByteArrayOutputStream stream = new ByteArrayOutputStream();
372 preview.compress(Bitmap.CompressFormat.PNG, 100, stream);
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100373 values.put(CacheDb.COLUMN_PREVIEW_BITMAP, stream.toByteArray());
374 values.put(CacheDb.COLUMN_SIZE, mSize);
Michael Jurka6e27f642013-12-10 13:40:30 +0100375 try {
376 db.insert(CacheDb.TABLE_NAME, null, values);
377 } catch (SQLiteDiskIOException e) {
378 recreateDb();
Adrian Roos1f375ab2014-04-28 18:26:38 +0200379 } catch (SQLiteCantOpenDatabaseException e) {
380 dumpOpenFiles();
381 throw e;
Michael Jurka6e27f642013-12-10 13:40:30 +0100382 }
Michael Jurka05713af2013-01-23 12:39:24 +0100383 }
384
Michael Jurka8ff02ca2013-11-01 14:19:27 +0100385 private void clearDb() {
386 SQLiteDatabase db = mDb.getWritableDatabase();
387 // Delete everything
Michael Jurka6e27f642013-12-10 13:40:30 +0100388 try {
389 db.delete(CacheDb.TABLE_NAME, null, null);
390 } catch (SQLiteDiskIOException e) {
Adrian Roos1f375ab2014-04-28 18:26:38 +0200391 } catch (SQLiteCantOpenDatabaseException e) {
392 dumpOpenFiles();
393 throw e;
Michael Jurka6e27f642013-12-10 13:40:30 +0100394 }
Michael Jurka8ff02ca2013-11-01 14:19:27 +0100395 }
396
Michael Jurkaeb1bb922013-09-26 11:29:01 -0700397 public static void removePackageFromDb(final CacheDb cacheDb, final String packageName) {
Michael Jurka05713af2013-01-23 12:39:24 +0100398 synchronized(sInvalidPackages) {
399 sInvalidPackages.add(packageName);
400 }
401 new AsyncTask<Void, Void, Void>() {
402 public Void doInBackground(Void ... args) {
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100403 SQLiteDatabase db = cacheDb.getWritableDatabase();
Michael Jurka6e27f642013-12-10 13:40:30 +0100404 try {
405 db.delete(CacheDb.TABLE_NAME,
406 CacheDb.COLUMN_NAME + " LIKE ? OR " +
407 CacheDb.COLUMN_NAME + " LIKE ?", // SELECT query
408 new String[] {
409 WIDGET_PREFIX + packageName + "/%",
410 SHORTCUT_PREFIX + packageName + "/%"
411 } // args to SELECT query
412 );
413 } catch (SQLiteDiskIOException e) {
Adrian Roos1f375ab2014-04-28 18:26:38 +0200414 } catch (SQLiteCantOpenDatabaseException e) {
415 dumpOpenFiles();
416 throw e;
Michael Jurka6e27f642013-12-10 13:40:30 +0100417 }
Michael Jurka05713af2013-01-23 12:39:24 +0100418 synchronized(sInvalidPackages) {
419 sInvalidPackages.remove(packageName);
420 }
421 return null;
422 }
423 }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
424 }
425
Sunny Goyalffe83f12014-08-14 17:39:34 -0700426 private static void removeItemFromDb(final CacheDb cacheDb, final String objectName) {
Michael Jurkaeb1bb922013-09-26 11:29:01 -0700427 new AsyncTask<Void, Void, Void>() {
428 public Void doInBackground(Void ... args) {
429 SQLiteDatabase db = cacheDb.getWritableDatabase();
Michael Jurka6e27f642013-12-10 13:40:30 +0100430 try {
431 db.delete(CacheDb.TABLE_NAME,
432 CacheDb.COLUMN_NAME + " = ? ", // SELECT query
433 new String[] { objectName }); // args to SELECT query
434 } catch (SQLiteDiskIOException e) {
Adrian Roos1f375ab2014-04-28 18:26:38 +0200435 } catch (SQLiteCantOpenDatabaseException e) {
436 dumpOpenFiles();
437 throw e;
Michael Jurka6e27f642013-12-10 13:40:30 +0100438 }
Michael Jurkaeb1bb922013-09-26 11:29:01 -0700439 return null;
440 }
441 }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
442 }
443
Michael Jurka05713af2013-01-23 12:39:24 +0100444 private Bitmap readFromDb(String name, Bitmap b) {
445 if (mCachedSelectQuery == null) {
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100446 mCachedSelectQuery = CacheDb.COLUMN_NAME + " = ? AND " +
447 CacheDb.COLUMN_SIZE + " = ?";
Michael Jurka05713af2013-01-23 12:39:24 +0100448 }
449 SQLiteDatabase db = mDb.getReadableDatabase();
Michael Jurka6e27f642013-12-10 13:40:30 +0100450 Cursor result;
451 try {
452 result = db.query(CacheDb.TABLE_NAME,
453 new String[] { CacheDb.COLUMN_PREVIEW_BITMAP }, // cols to return
454 mCachedSelectQuery, // select query
455 new String[] { name, mSize }, // args to select query
456 null,
457 null,
458 null,
459 null);
460 } catch (SQLiteDiskIOException e) {
461 recreateDb();
462 return null;
Adrian Roos1f375ab2014-04-28 18:26:38 +0200463 } catch (SQLiteCantOpenDatabaseException e) {
464 dumpOpenFiles();
465 throw e;
Michael Jurka6e27f642013-12-10 13:40:30 +0100466 }
Michael Jurka05713af2013-01-23 12:39:24 +0100467 if (result.getCount() > 0) {
468 result.moveToFirst();
469 byte[] blob = result.getBlob(0);
470 result.close();
471 final BitmapFactory.Options opts = mCachedBitmapFactoryOptions.get();
472 opts.inBitmap = b;
473 opts.inSampleSize = 1;
Michael Jurkaeb1bb922013-09-26 11:29:01 -0700474 try {
475 return BitmapFactory.decodeByteArray(blob, 0, blob.length, opts);
476 } catch (IllegalArgumentException e) {
477 removeItemFromDb(mDb, name);
478 return null;
479 }
Michael Jurka05713af2013-01-23 12:39:24 +0100480 } else {
481 result.close();
482 return null;
483 }
484 }
485
Sunny Goyalffe83f12014-08-14 17:39:34 -0700486 private Bitmap generatePreview(Object info, Bitmap preview) {
Michael Jurka05713af2013-01-23 12:39:24 +0100487 if (preview != null &&
Michael Jurka3f4e0702013-02-05 11:21:28 +0100488 (preview.getWidth() != mPreviewBitmapWidth ||
489 preview.getHeight() != mPreviewBitmapHeight)) {
Michael Jurka05713af2013-01-23 12:39:24 +0100490 throw new RuntimeException("Improperly sized bitmap passed as argument");
491 }
Adam Cohen59400422014-03-05 18:07:04 -0800492 if (info instanceof LauncherAppWidgetProviderInfo) {
493 return generateWidgetPreview((LauncherAppWidgetProviderInfo) info, preview);
Michael Jurka05713af2013-01-23 12:39:24 +0100494 } else {
495 return generateShortcutPreview(
Michael Jurka3f4e0702013-02-05 11:21:28 +0100496 (ResolveInfo) info, mPreviewBitmapWidth, mPreviewBitmapHeight, preview);
Michael Jurka05713af2013-01-23 12:39:24 +0100497 }
498 }
499
Adam Cohen59400422014-03-05 18:07:04 -0800500 public Bitmap generateWidgetPreview(LauncherAppWidgetProviderInfo info, Bitmap preview) {
501 int maxWidth = maxWidthForWidgetPreview(info.spanX);
502 int maxHeight = maxHeightForWidgetPreview(info.spanY);
503 return generateWidgetPreview(info, info.spanX, info.spanY, maxWidth,
504 maxHeight, preview, null);
Michael Jurka05713af2013-01-23 12:39:24 +0100505 }
506
507 public int maxWidthForWidgetPreview(int spanX) {
Michael Jurka3f4e0702013-02-05 11:21:28 +0100508 return Math.min(mPreviewBitmapWidth,
Michael Jurka05713af2013-01-23 12:39:24 +0100509 mWidgetSpacingLayout.estimateCellWidth(spanX));
510 }
511
512 public int maxHeightForWidgetPreview(int spanY) {
Michael Jurka3f4e0702013-02-05 11:21:28 +0100513 return Math.min(mPreviewBitmapHeight,
Michael Jurka05713af2013-01-23 12:39:24 +0100514 mWidgetSpacingLayout.estimateCellHeight(spanY));
515 }
516
Adam Cohen59400422014-03-05 18:07:04 -0800517 public Bitmap generateWidgetPreview(LauncherAppWidgetProviderInfo info, int cellHSpan, int cellVSpan,
Sunny Goyalffe83f12014-08-14 17:39:34 -0700518 int maxPreviewWidth, int maxPreviewHeight, Bitmap preview, int[] preScaledWidthOut) {
Michael Jurka05713af2013-01-23 12:39:24 +0100519 // Load the preview image if possible
Michael Jurka05713af2013-01-23 12:39:24 +0100520 if (maxPreviewWidth < 0) maxPreviewWidth = Integer.MAX_VALUE;
521 if (maxPreviewHeight < 0) maxPreviewHeight = Integer.MAX_VALUE;
522
523 Drawable drawable = null;
Sunny Goyalffe83f12014-08-14 17:39:34 -0700524 if (info.previewImage != 0) {
525 drawable = mManager.loadPreview(info);
Adrian Roosfa9ffc22014-05-12 15:59:59 +0200526 if (drawable != null) {
527 drawable = mutateOnMainThread(drawable);
528 } else {
Michael Jurka05713af2013-01-23 12:39:24 +0100529 Log.w(TAG, "Can't load widget preview drawable 0x" +
Sunny Goyalffe83f12014-08-14 17:39:34 -0700530 Integer.toHexString(info.previewImage) + " for provider: " + info.provider);
Michael Jurka05713af2013-01-23 12:39:24 +0100531 }
532 }
533
534 int previewWidth;
535 int previewHeight;
536 Bitmap defaultPreview = null;
537 boolean widgetPreviewExists = (drawable != null);
538 if (widgetPreviewExists) {
539 previewWidth = drawable.getIntrinsicWidth();
540 previewHeight = drawable.getIntrinsicHeight();
541 } else {
542 // Generate a preview image if we couldn't load one
543 if (cellHSpan < 1) cellHSpan = 1;
544 if (cellVSpan < 1) cellVSpan = 1;
545
Adrian Roos65d60e22014-04-15 21:07:49 +0200546 // This Drawable is not directly drawn, so there's no need to mutate it.
Michael Jurka05713af2013-01-23 12:39:24 +0100547 BitmapDrawable previewDrawable = (BitmapDrawable) mContext.getResources()
Winson Chung6706ed82013-10-02 11:00:15 -0700548 .getDrawable(R.drawable.widget_tile);
Michael Jurka05713af2013-01-23 12:39:24 +0100549 final int previewDrawableWidth = previewDrawable
550 .getIntrinsicWidth();
551 final int previewDrawableHeight = previewDrawable
552 .getIntrinsicHeight();
Winson Chung45cab392013-10-02 17:45:32 -0700553 previewWidth = previewDrawableWidth * cellHSpan;
Michael Jurka05713af2013-01-23 12:39:24 +0100554 previewHeight = previewDrawableHeight * cellVSpan;
555
Adrian Roos5d2704f2014-03-18 23:09:12 +0100556 defaultPreview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
Michael Jurka05713af2013-01-23 12:39:24 +0100557 final Canvas c = mCachedAppWidgetPreviewCanvas.get();
558 c.setBitmap(defaultPreview);
Adrian Roosfa4c7992014-03-19 15:58:14 +0100559 Paint p = mDefaultAppWidgetPreviewPaint.get();
560 if (p == null) {
561 p = new Paint();
562 p.setShader(new BitmapShader(previewDrawable.getBitmap(),
563 Shader.TileMode.REPEAT, Shader.TileMode.REPEAT));
564 mDefaultAppWidgetPreviewPaint.set(p);
565 }
566 final Rect dest = mCachedAppWidgetPreviewDestRect.get();
567 dest.set(0, 0, previewWidth, previewHeight);
568 c.drawRect(dest, p);
Michael Jurka05713af2013-01-23 12:39:24 +0100569 c.setBitmap(null);
570
571 // Draw the icon in the top left corner
Sunny Goyalffe83f12014-08-14 17:39:34 -0700572 int minOffset = (int) (mAppIconSize * WIDGET_PREVIEW_ICON_PADDING_PERCENTAGE);
Michael Jurka05713af2013-01-23 12:39:24 +0100573 int smallestSide = Math.min(previewWidth, previewHeight);
574 float iconScale = Math.min((float) smallestSide
575 / (mAppIconSize + 2 * minOffset), 1f);
576
577 try {
Sunny Goyalffe83f12014-08-14 17:39:34 -0700578 Drawable icon = mManager.loadIcon(info, mIconCache);
Michael Jurka05713af2013-01-23 12:39:24 +0100579 if (icon != null) {
Sunny Goyalffe83f12014-08-14 17:39:34 -0700580 int hoffset = (int) ((previewDrawableWidth - mAppIconSize * iconScale) / 2);
581 int yoffset = (int) ((previewDrawableHeight - mAppIconSize * iconScale) / 2);
Adrian Roosfa9ffc22014-05-12 15:59:59 +0200582 icon = mutateOnMainThread(icon);
Michael Jurka05713af2013-01-23 12:39:24 +0100583 renderDrawableToBitmap(icon, defaultPreview, hoffset,
584 yoffset, (int) (mAppIconSize * iconScale),
585 (int) (mAppIconSize * iconScale));
586 }
587 } catch (Resources.NotFoundException e) {
588 }
589 }
590
591 // Scale to fit width only - let the widget preview be clipped in the
592 // vertical dimension
593 float scale = 1f;
594 if (preScaledWidthOut != null) {
595 preScaledWidthOut[0] = previewWidth;
596 }
597 if (previewWidth > maxPreviewWidth) {
598 scale = maxPreviewWidth / (float) previewWidth;
599 }
600 if (scale != 1f) {
601 previewWidth = (int) (scale * previewWidth);
602 previewHeight = (int) (scale * previewHeight);
603 }
604
605 // If a bitmap is passed in, we use it; otherwise, we create a bitmap of the right size
606 if (preview == null) {
607 preview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
608 }
609
610 // Draw the scaled preview into the final bitmap
611 int x = (preview.getWidth() - previewWidth) / 2;
612 if (widgetPreviewExists) {
613 renderDrawableToBitmap(drawable, preview, x, 0, previewWidth,
614 previewHeight);
615 } else {
616 final Canvas c = mCachedAppWidgetPreviewCanvas.get();
617 final Rect src = mCachedAppWidgetPreviewSrcRect.get();
618 final Rect dest = mCachedAppWidgetPreviewDestRect.get();
619 c.setBitmap(preview);
620 src.set(0, 0, defaultPreview.getWidth(), defaultPreview.getHeight());
Michael Jurkae5919c52013-03-06 17:30:10 +0100621 dest.set(x, 0, x + previewWidth, previewHeight);
Michael Jurka05713af2013-01-23 12:39:24 +0100622
623 Paint p = mCachedAppWidgetPreviewPaint.get();
624 if (p == null) {
625 p = new Paint();
626 p.setFilterBitmap(true);
627 mCachedAppWidgetPreviewPaint.set(p);
628 }
629 c.drawBitmap(defaultPreview, src, dest, p);
630 c.setBitmap(null);
631 }
Sunny Goyalffe83f12014-08-14 17:39:34 -0700632 return mManager.getBadgeBitmap(info, preview);
Michael Jurka05713af2013-01-23 12:39:24 +0100633 }
634
635 private Bitmap generateShortcutPreview(
636 ResolveInfo info, int maxWidth, int maxHeight, Bitmap preview) {
637 Bitmap tempBitmap = mCachedShortcutPreviewBitmap.get();
638 final Canvas c = mCachedShortcutPreviewCanvas.get();
639 if (tempBitmap == null ||
640 tempBitmap.getWidth() != maxWidth ||
641 tempBitmap.getHeight() != maxHeight) {
642 tempBitmap = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
643 mCachedShortcutPreviewBitmap.set(tempBitmap);
644 } else {
645 c.setBitmap(tempBitmap);
646 c.drawColor(0, PorterDuff.Mode.CLEAR);
647 c.setBitmap(null);
648 }
649 // Render the icon
Sunny Goyal736f5af2014-10-16 14:07:29 -0700650 Drawable icon = mutateOnMainThread(mIconCache.getFullResIcon(info.activityInfo));
Michael Jurka05713af2013-01-23 12:39:24 +0100651
652 int paddingTop = mContext.
653 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_top);
654 int paddingLeft = mContext.
655 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_left);
656 int paddingRight = mContext.
657 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_right);
658
659 int scaledIconWidth = (maxWidth - paddingLeft - paddingRight);
660
661 renderDrawableToBitmap(
662 icon, tempBitmap, paddingLeft, paddingTop, scaledIconWidth, scaledIconWidth);
663
664 if (preview != null &&
665 (preview.getWidth() != maxWidth || preview.getHeight() != maxHeight)) {
666 throw new RuntimeException("Improperly sized bitmap passed as argument");
667 } else if (preview == null) {
668 preview = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
669 }
670
671 c.setBitmap(preview);
672 // Draw a desaturated/scaled version of the icon in the background as a watermark
673 Paint p = mCachedShortcutPreviewPaint.get();
674 if (p == null) {
675 p = new Paint();
676 ColorMatrix colorMatrix = new ColorMatrix();
677 colorMatrix.setSaturation(0);
678 p.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
679 p.setAlpha((int) (255 * 0.06f));
680 mCachedShortcutPreviewPaint.set(p);
681 }
682 c.drawBitmap(tempBitmap, 0, 0, p);
683 c.setBitmap(null);
684
685 renderDrawableToBitmap(icon, preview, 0, 0, mAppIconSize, mAppIconSize);
686
687 return preview;
688 }
689
Michael Jurka05713af2013-01-23 12:39:24 +0100690 private static void renderDrawableToBitmap(
Sunny Goyalffe83f12014-08-14 17:39:34 -0700691 Drawable d, Bitmap bitmap, int x, int y, int w, int h) {
Michael Jurka05713af2013-01-23 12:39:24 +0100692 if (bitmap != null) {
693 Canvas c = new Canvas(bitmap);
Michael Jurka05713af2013-01-23 12:39:24 +0100694 Rect oldBounds = d.copyBounds();
695 d.setBounds(x, y, x + w, y + h);
696 d.draw(c);
697 d.setBounds(oldBounds); // Restore the bounds
698 c.setBitmap(null);
699 }
700 }
701
Adrian Roos65d60e22014-04-15 21:07:49 +0200702 private Drawable mutateOnMainThread(final Drawable drawable) {
703 try {
704 return mMainThreadExecutor.submit(new Callable<Drawable>() {
705 @Override
706 public Drawable call() throws Exception {
707 return drawable.mutate();
708 }
709 }).get();
710 } catch (InterruptedException e) {
711 Thread.currentThread().interrupt();
712 throw new RuntimeException(e);
713 } catch (ExecutionException e) {
714 throw new RuntimeException(e);
715 }
716 }
Adrian Roos1f375ab2014-04-28 18:26:38 +0200717
718 private static final int MAX_OPEN_FILES = 1024;
719 private static final int SAMPLE_RATE = 23;
720 /**
721 * Dumps all files that are open in this process without allocating a file descriptor.
722 */
723 private static void dumpOpenFiles() {
724 try {
725 Log.i(TAG, "DUMP OF OPEN FILES (sample rate: 1 every " + SAMPLE_RATE + "):");
726 final String TYPE_APK = "apk";
727 final String TYPE_JAR = "jar";
728 final String TYPE_PIPE = "pipe";
729 final String TYPE_SOCKET = "socket";
730 final String TYPE_DB = "db";
731 final String TYPE_ANON_INODE = "anon_inode";
732 final String TYPE_DEV = "dev";
733 final String TYPE_NON_FS = "non-fs";
734 final String TYPE_OTHER = "other";
735 List<String> types = Arrays.asList(TYPE_APK, TYPE_JAR, TYPE_PIPE, TYPE_SOCKET, TYPE_DB,
736 TYPE_ANON_INODE, TYPE_DEV, TYPE_NON_FS, TYPE_OTHER);
737 int[] count = new int[types.size()];
738 int[] duplicates = new int[types.size()];
739 HashSet<String> files = new HashSet<String>();
740 int total = 0;
741 for (int i = 0; i < MAX_OPEN_FILES; i++) {
742 // This is a gigantic hack but unfortunately the only way to resolve an fd
743 // to a file name. Note that we have to loop over all possible fds because
744 // reading the directory would require allocating a new fd. The kernel is
745 // currently implemented such that no fd is larger then the current rlimit,
746 // which is why it's safe to loop over them in such a way.
747 String fd = "/proc/self/fd/" + i;
748 try {
749 // getCanonicalPath() uses readlink behind the scene which doesn't require
750 // a file descriptor.
751 String resolved = new File(fd).getCanonicalPath();
752 int type = types.indexOf(TYPE_OTHER);
753 if (resolved.startsWith("/dev/")) {
754 type = types.indexOf(TYPE_DEV);
755 } else if (resolved.endsWith(".apk")) {
756 type = types.indexOf(TYPE_APK);
757 } else if (resolved.endsWith(".jar")) {
758 type = types.indexOf(TYPE_JAR);
759 } else if (resolved.contains("/fd/pipe:")) {
760 type = types.indexOf(TYPE_PIPE);
761 } else if (resolved.contains("/fd/socket:")) {
762 type = types.indexOf(TYPE_SOCKET);
763 } else if (resolved.contains("/fd/anon_inode:")) {
764 type = types.indexOf(TYPE_ANON_INODE);
765 } else if (resolved.endsWith(".db") || resolved.contains("/databases/")) {
766 type = types.indexOf(TYPE_DB);
767 } else if (resolved.startsWith("/proc/") && resolved.contains("/fd/")) {
768 // Those are the files that don't point anywhere on the file system.
769 // getCanonicalPath() wrongly interprets these as relative symlinks and
770 // resolves them within /proc/<pid>/fd/.
771 type = types.indexOf(TYPE_NON_FS);
772 }
773 count[type]++;
774 total++;
775 if (files.contains(resolved)) {
776 duplicates[type]++;
777 }
778 files.add(resolved);
779 if (total % SAMPLE_RATE == 0) {
780 Log.i(TAG, " fd " + i + ": " + resolved
781 + " (" + types.get(type) + ")");
782 }
783 } catch (IOException e) {
784 // Ignoring exceptions for non-existing file descriptors.
785 }
786 }
787 for (int i = 0; i < types.size(); i++) {
788 Log.i(TAG, String.format("Open %10s files: %4d total, %4d duplicates",
789 types.get(i), count[i], duplicates[i]));
790 }
791 } catch (Throwable t) {
792 // Catch everything. This is called from an exception handler that we shouldn't upset.
793 Log.e(TAG, "Unable to log open files.", t);
794 }
795 }
Michael Jurka05713af2013-01-23 12:39:24 +0100796}