blob: c3c0649f0151bcf1266426524748ecbdb881bbe3 [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
Sameer Padala8fd74832014-09-08 16:00:29 -0700134 private final HashMap<String, WeakReference<Bitmap>> mLoadedPreviews = new HashMap<String, WeakReference<Bitmap>>();
135 private final ArrayList<SoftReference<Bitmap>> mUnusedBitmaps = new ArrayList<SoftReference<Bitmap>>();
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;
Winson Chung5f059132014-12-01 15:05:17 -0800169 final boolean isLollipop = 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) {
176 if (isLollipop) {
177 // 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 }
182 } catch (Exception e) {
183 throw e;
184 } finally {
185 SharedPreferences.Editor editor = sp.edit();
186 editor.putString(ANDROID_INCREMENTAL_VERSION_NAME_KEY, versionName);
187 editor.commit();
188 }
Michael Jurka8ff02ca2013-11-01 14:19:27 +0100189 }
Michael Jurka3f4e0702013-02-05 11:21:28 +0100190 }
Sunny Goyalffe83f12014-08-14 17:39:34 -0700191
Michael Jurka6e27f642013-12-10 13:40:30 +0100192 public void recreateDb() {
193 LauncherAppState app = LauncherAppState.getInstance();
194 app.recreateWidgetPreviewDb();
195 mDb = app.getWidgetPreviewCacheDb();
196 }
Michael Jurka3f4e0702013-02-05 11:21:28 +0100197
198 public void setPreviewSize(int previewWidth, int previewHeight,
199 PagedViewCellLayout widgetSpacingLayout) {
200 mPreviewBitmapWidth = previewWidth;
201 mPreviewBitmapHeight = previewHeight;
202 mSize = previewWidth + "x" + previewHeight;
203 mWidgetSpacingLayout = widgetSpacingLayout;
Michael Jurka05713af2013-01-23 12:39:24 +0100204 }
205
206 public Bitmap getPreview(final Object o) {
Michael Jurkaeb1bb922013-09-26 11:29:01 -0700207 final String name = getObjectName(o);
208 final String packageName = getObjectPackage(o);
Michael Jurka05713af2013-01-23 12:39:24 +0100209 // check if the package is valid
Michael Jurka05713af2013-01-23 12:39:24 +0100210 synchronized(sInvalidPackages) {
Adrian Roos5d2704f2014-03-18 23:09:12 +0100211 boolean packageValid = !sInvalidPackages.contains(packageName);
212 if (!packageValid) {
213 return null;
214 }
Michael Jurka05713af2013-01-23 12:39:24 +0100215 }
Adrian Roos5d2704f2014-03-18 23:09:12 +0100216 synchronized(mLoadedPreviews) {
217 // check if it exists in our existing cache
218 if (mLoadedPreviews.containsKey(name)) {
219 WeakReference<Bitmap> bitmapReference = mLoadedPreviews.get(name);
220 Bitmap bitmap = bitmapReference.get();
221 if (bitmap != null) {
222 return bitmap;
Michael Jurka05713af2013-01-23 12:39:24 +0100223 }
224 }
225 }
226
227 Bitmap unusedBitmap = null;
Michael Jurka3f4e0702013-02-05 11:21:28 +0100228 synchronized(mUnusedBitmaps) {
Michael Jurka05713af2013-01-23 12:39:24 +0100229 // not in cache; we need to load it from the db
Adrian Roos5d2704f2014-03-18 23:09:12 +0100230 while (unusedBitmap == null && mUnusedBitmaps.size() > 0) {
231 Bitmap candidate = mUnusedBitmaps.remove(0).get();
232 if (candidate != null && candidate.isMutable() &&
233 candidate.getWidth() == mPreviewBitmapWidth &&
234 candidate.getHeight() == mPreviewBitmapHeight) {
235 unusedBitmap = candidate;
236 }
Michael Jurka05713af2013-01-23 12:39:24 +0100237 }
238 if (unusedBitmap != null) {
239 final Canvas c = mCachedAppWidgetPreviewCanvas.get();
240 c.setBitmap(unusedBitmap);
241 c.drawColor(0, PorterDuff.Mode.CLEAR);
242 c.setBitmap(null);
243 }
244 }
245
246 if (unusedBitmap == null) {
Michael Jurka3f4e0702013-02-05 11:21:28 +0100247 unusedBitmap = Bitmap.createBitmap(mPreviewBitmapWidth, mPreviewBitmapHeight,
Michael Jurka05713af2013-01-23 12:39:24 +0100248 Bitmap.Config.ARGB_8888);
249 }
Adrian Roos5d2704f2014-03-18 23:09:12 +0100250 Bitmap preview = readFromDb(name, unusedBitmap);
Michael Jurka05713af2013-01-23 12:39:24 +0100251
252 if (preview != null) {
Michael Jurka3f4e0702013-02-05 11:21:28 +0100253 synchronized(mLoadedPreviews) {
254 mLoadedPreviews.put(name, new WeakReference<Bitmap>(preview));
Michael Jurka05713af2013-01-23 12:39:24 +0100255 }
256 return preview;
257 } else {
258 // it's not in the db... we need to generate it
259 final Bitmap generatedPreview = generatePreview(o, unusedBitmap);
260 preview = generatedPreview;
261 if (preview != unusedBitmap) {
262 throw new RuntimeException("generatePreview is not recycling the bitmap " + o);
263 }
264
Michael Jurka3f4e0702013-02-05 11:21:28 +0100265 synchronized(mLoadedPreviews) {
266 mLoadedPreviews.put(name, new WeakReference<Bitmap>(preview));
Michael Jurka05713af2013-01-23 12:39:24 +0100267 }
268
269 // write to db on a thread pool... this can be done lazily and improves the performance
270 // of the first time widget previews are loaded
271 new AsyncTask<Void, Void, Void>() {
272 public Void doInBackground(Void ... args) {
273 writeToDb(o, generatedPreview);
274 return null;
275 }
276 }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
277
278 return preview;
279 }
280 }
281
Michael Jurkaee8e99f2013-02-07 13:27:06 +0100282 public void recycleBitmap(Object o, Bitmap bitmapToRecycle) {
Michael Jurka05713af2013-01-23 12:39:24 +0100283 String name = getObjectName(o);
Michael Jurka5140cfa2013-02-15 14:50:15 +0100284 synchronized (mLoadedPreviews) {
285 if (mLoadedPreviews.containsKey(name)) {
Michael Jurka3f4e0702013-02-05 11:21:28 +0100286 Bitmap b = mLoadedPreviews.get(name).get();
Michael Jurkaee8e99f2013-02-07 13:27:06 +0100287 if (b == bitmapToRecycle) {
Michael Jurka3f4e0702013-02-05 11:21:28 +0100288 mLoadedPreviews.remove(name);
Michael Jurkaee8e99f2013-02-07 13:27:06 +0100289 if (bitmapToRecycle.isMutable()) {
Michael Jurka5140cfa2013-02-15 14:50:15 +0100290 synchronized (mUnusedBitmaps) {
291 mUnusedBitmaps.add(new SoftReference<Bitmap>(b));
292 }
Michael Jurka05713af2013-01-23 12:39:24 +0100293 }
294 } else {
295 throw new RuntimeException("Bitmap passed in doesn't match up");
296 }
297 }
298 }
299 }
300
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100301 static class CacheDb extends SQLiteOpenHelper {
Michael Jurkae5919c52013-03-06 17:30:10 +0100302 final static int DB_VERSION = 2;
Michael Jurka05713af2013-01-23 12:39:24 +0100303 final static String TABLE_NAME = "shortcut_and_widget_previews";
304 final static String COLUMN_NAME = "name";
305 final static String COLUMN_SIZE = "size";
306 final static String COLUMN_PREVIEW_BITMAP = "preview_bitmap";
307 Context mContext;
308
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100309 public CacheDb(Context context) {
Helena Josol4fbbb3e2014-10-06 16:06:46 +0100310 super(context, new File(context.getCacheDir(),
311 LauncherFiles.WIDGET_PREVIEWS_DB).getPath(), null, DB_VERSION);
Michael Jurka05713af2013-01-23 12:39:24 +0100312 // Store the context for later use
313 mContext = context;
314 }
315
316 @Override
317 public void onCreate(SQLiteDatabase database) {
Michael Jurka32b7a092013-02-07 20:06:49 +0100318 database.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" +
Michael Jurka05713af2013-01-23 12:39:24 +0100319 COLUMN_NAME + " TEXT NOT NULL, " +
320 COLUMN_SIZE + " TEXT NOT NULL, " +
321 COLUMN_PREVIEW_BITMAP + " BLOB NOT NULL, " +
322 "PRIMARY KEY (" + COLUMN_NAME + ", " + COLUMN_SIZE + ") " +
Michael Jurka32b7a092013-02-07 20:06:49 +0100323 ");");
Michael Jurka05713af2013-01-23 12:39:24 +0100324 }
325
326 @Override
327 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Michael Jurkae5919c52013-03-06 17:30:10 +0100328 if (oldVersion != newVersion) {
329 // Delete all the records; they'll be repopulated as this is a cache
330 db.execSQL("DELETE FROM " + TABLE_NAME);
331 }
Michael Jurka05713af2013-01-23 12:39:24 +0100332 }
333 }
334
335 private static final String WIDGET_PREFIX = "Widget:";
336 private static final String SHORTCUT_PREFIX = "Shortcut:";
337
338 private static String getObjectName(Object o) {
339 // should cache the string builder
340 StringBuilder sb = new StringBuilder();
341 String output;
342 if (o instanceof AppWidgetProviderInfo) {
343 sb.append(WIDGET_PREFIX);
Sunny Goyalffe83f12014-08-14 17:39:34 -0700344 sb.append(((AppWidgetProviderInfo) o).toString());
Michael Jurka05713af2013-01-23 12:39:24 +0100345 output = sb.toString();
346 sb.setLength(0);
347 } else {
348 sb.append(SHORTCUT_PREFIX);
349
350 ResolveInfo info = (ResolveInfo) o;
351 sb.append(new ComponentName(info.activityInfo.packageName,
352 info.activityInfo.name).flattenToString());
353 output = sb.toString();
354 sb.setLength(0);
355 }
356 return output;
357 }
358
359 private String getObjectPackage(Object o) {
360 if (o instanceof AppWidgetProviderInfo) {
361 return ((AppWidgetProviderInfo) o).provider.getPackageName();
362 } else {
363 ResolveInfo info = (ResolveInfo) o;
364 return info.activityInfo.packageName;
365 }
366 }
367
368 private void writeToDb(Object o, Bitmap preview) {
369 String name = getObjectName(o);
370 SQLiteDatabase db = mDb.getWritableDatabase();
371 ContentValues values = new ContentValues();
372
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100373 values.put(CacheDb.COLUMN_NAME, name);
Michael Jurka05713af2013-01-23 12:39:24 +0100374 ByteArrayOutputStream stream = new ByteArrayOutputStream();
375 preview.compress(Bitmap.CompressFormat.PNG, 100, stream);
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100376 values.put(CacheDb.COLUMN_PREVIEW_BITMAP, stream.toByteArray());
377 values.put(CacheDb.COLUMN_SIZE, mSize);
Michael Jurka6e27f642013-12-10 13:40:30 +0100378 try {
379 db.insert(CacheDb.TABLE_NAME, null, values);
380 } catch (SQLiteDiskIOException e) {
381 recreateDb();
Adrian Roos1f375ab2014-04-28 18:26:38 +0200382 } catch (SQLiteCantOpenDatabaseException e) {
383 dumpOpenFiles();
384 throw e;
Michael Jurka6e27f642013-12-10 13:40:30 +0100385 }
Michael Jurka05713af2013-01-23 12:39:24 +0100386 }
387
Michael Jurka8ff02ca2013-11-01 14:19:27 +0100388 private void clearDb() {
389 SQLiteDatabase db = mDb.getWritableDatabase();
390 // Delete everything
Michael Jurka6e27f642013-12-10 13:40:30 +0100391 try {
392 db.delete(CacheDb.TABLE_NAME, null, null);
393 } catch (SQLiteDiskIOException e) {
Adrian Roos1f375ab2014-04-28 18:26:38 +0200394 } catch (SQLiteCantOpenDatabaseException e) {
395 dumpOpenFiles();
396 throw e;
Michael Jurka6e27f642013-12-10 13:40:30 +0100397 }
Michael Jurka8ff02ca2013-11-01 14:19:27 +0100398 }
399
Michael Jurkaeb1bb922013-09-26 11:29:01 -0700400 public static void removePackageFromDb(final CacheDb cacheDb, final String packageName) {
Michael Jurka05713af2013-01-23 12:39:24 +0100401 synchronized(sInvalidPackages) {
402 sInvalidPackages.add(packageName);
403 }
404 new AsyncTask<Void, Void, Void>() {
405 public Void doInBackground(Void ... args) {
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100406 SQLiteDatabase db = cacheDb.getWritableDatabase();
Michael Jurka6e27f642013-12-10 13:40:30 +0100407 try {
408 db.delete(CacheDb.TABLE_NAME,
409 CacheDb.COLUMN_NAME + " LIKE ? OR " +
410 CacheDb.COLUMN_NAME + " LIKE ?", // SELECT query
411 new String[] {
412 WIDGET_PREFIX + packageName + "/%",
413 SHORTCUT_PREFIX + packageName + "/%"
414 } // args to SELECT query
415 );
416 } catch (SQLiteDiskIOException e) {
Adrian Roos1f375ab2014-04-28 18:26:38 +0200417 } catch (SQLiteCantOpenDatabaseException e) {
418 dumpOpenFiles();
419 throw e;
Michael Jurka6e27f642013-12-10 13:40:30 +0100420 }
Michael Jurka05713af2013-01-23 12:39:24 +0100421 synchronized(sInvalidPackages) {
422 sInvalidPackages.remove(packageName);
423 }
424 return null;
425 }
426 }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
427 }
428
Sunny Goyalffe83f12014-08-14 17:39:34 -0700429 private static void removeItemFromDb(final CacheDb cacheDb, final String objectName) {
Michael Jurkaeb1bb922013-09-26 11:29:01 -0700430 new AsyncTask<Void, Void, Void>() {
431 public Void doInBackground(Void ... args) {
432 SQLiteDatabase db = cacheDb.getWritableDatabase();
Michael Jurka6e27f642013-12-10 13:40:30 +0100433 try {
434 db.delete(CacheDb.TABLE_NAME,
435 CacheDb.COLUMN_NAME + " = ? ", // SELECT query
436 new String[] { objectName }); // args to SELECT query
437 } catch (SQLiteDiskIOException e) {
Adrian Roos1f375ab2014-04-28 18:26:38 +0200438 } catch (SQLiteCantOpenDatabaseException e) {
439 dumpOpenFiles();
440 throw e;
Michael Jurka6e27f642013-12-10 13:40:30 +0100441 }
Michael Jurkaeb1bb922013-09-26 11:29:01 -0700442 return null;
443 }
444 }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
445 }
446
Michael Jurka05713af2013-01-23 12:39:24 +0100447 private Bitmap readFromDb(String name, Bitmap b) {
448 if (mCachedSelectQuery == null) {
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100449 mCachedSelectQuery = CacheDb.COLUMN_NAME + " = ? AND " +
450 CacheDb.COLUMN_SIZE + " = ?";
Michael Jurka05713af2013-01-23 12:39:24 +0100451 }
452 SQLiteDatabase db = mDb.getReadableDatabase();
Michael Jurka6e27f642013-12-10 13:40:30 +0100453 Cursor result;
454 try {
455 result = db.query(CacheDb.TABLE_NAME,
456 new String[] { CacheDb.COLUMN_PREVIEW_BITMAP }, // cols to return
457 mCachedSelectQuery, // select query
458 new String[] { name, mSize }, // args to select query
459 null,
460 null,
461 null,
462 null);
463 } catch (SQLiteDiskIOException e) {
464 recreateDb();
465 return null;
Adrian Roos1f375ab2014-04-28 18:26:38 +0200466 } catch (SQLiteCantOpenDatabaseException e) {
467 dumpOpenFiles();
468 throw e;
Michael Jurka6e27f642013-12-10 13:40:30 +0100469 }
Michael Jurka05713af2013-01-23 12:39:24 +0100470 if (result.getCount() > 0) {
471 result.moveToFirst();
472 byte[] blob = result.getBlob(0);
473 result.close();
474 final BitmapFactory.Options opts = mCachedBitmapFactoryOptions.get();
475 opts.inBitmap = b;
476 opts.inSampleSize = 1;
Michael Jurkaeb1bb922013-09-26 11:29:01 -0700477 try {
478 return BitmapFactory.decodeByteArray(blob, 0, blob.length, opts);
479 } catch (IllegalArgumentException e) {
480 removeItemFromDb(mDb, name);
481 return null;
482 }
Michael Jurka05713af2013-01-23 12:39:24 +0100483 } else {
484 result.close();
485 return null;
486 }
487 }
488
Sunny Goyalffe83f12014-08-14 17:39:34 -0700489 private Bitmap generatePreview(Object info, Bitmap preview) {
Michael Jurka05713af2013-01-23 12:39:24 +0100490 if (preview != null &&
Michael Jurka3f4e0702013-02-05 11:21:28 +0100491 (preview.getWidth() != mPreviewBitmapWidth ||
492 preview.getHeight() != mPreviewBitmapHeight)) {
Michael Jurka05713af2013-01-23 12:39:24 +0100493 throw new RuntimeException("Improperly sized bitmap passed as argument");
494 }
495 if (info instanceof AppWidgetProviderInfo) {
496 return generateWidgetPreview((AppWidgetProviderInfo) info, preview);
497 } else {
498 return generateShortcutPreview(
Michael Jurka3f4e0702013-02-05 11:21:28 +0100499 (ResolveInfo) info, mPreviewBitmapWidth, mPreviewBitmapHeight, preview);
Michael Jurka05713af2013-01-23 12:39:24 +0100500 }
501 }
502
503 public Bitmap generateWidgetPreview(AppWidgetProviderInfo info, Bitmap preview) {
Chris Wrenfd13c712013-09-27 15:45:19 -0400504 int[] cellSpans = Launcher.getSpanForWidget(mContext, info);
Michael Jurka05713af2013-01-23 12:39:24 +0100505 int maxWidth = maxWidthForWidgetPreview(cellSpans[0]);
506 int maxHeight = maxHeightForWidgetPreview(cellSpans[1]);
Sunny Goyalffe83f12014-08-14 17:39:34 -0700507 return generateWidgetPreview(info, cellSpans[0], cellSpans[1],
508 maxWidth, maxHeight, preview, null);
Michael Jurka05713af2013-01-23 12:39:24 +0100509 }
510
511 public int maxWidthForWidgetPreview(int spanX) {
Michael Jurka3f4e0702013-02-05 11:21:28 +0100512 return Math.min(mPreviewBitmapWidth,
Michael Jurka05713af2013-01-23 12:39:24 +0100513 mWidgetSpacingLayout.estimateCellWidth(spanX));
514 }
515
516 public int maxHeightForWidgetPreview(int spanY) {
Michael Jurka3f4e0702013-02-05 11:21:28 +0100517 return Math.min(mPreviewBitmapHeight,
Michael Jurka05713af2013-01-23 12:39:24 +0100518 mWidgetSpacingLayout.estimateCellHeight(spanY));
519 }
520
Sunny Goyalffe83f12014-08-14 17:39:34 -0700521 public Bitmap generateWidgetPreview(AppWidgetProviderInfo info, int cellHSpan, int cellVSpan,
522 int maxPreviewWidth, int maxPreviewHeight, Bitmap preview, int[] preScaledWidthOut) {
Michael Jurka05713af2013-01-23 12:39:24 +0100523 // Load the preview image if possible
Michael Jurka05713af2013-01-23 12:39:24 +0100524 if (maxPreviewWidth < 0) maxPreviewWidth = Integer.MAX_VALUE;
525 if (maxPreviewHeight < 0) maxPreviewHeight = Integer.MAX_VALUE;
526
527 Drawable drawable = null;
Sunny Goyalffe83f12014-08-14 17:39:34 -0700528 if (info.previewImage != 0) {
529 drawable = mManager.loadPreview(info);
Adrian Roosfa9ffc22014-05-12 15:59:59 +0200530 if (drawable != null) {
531 drawable = mutateOnMainThread(drawable);
532 } else {
Michael Jurka05713af2013-01-23 12:39:24 +0100533 Log.w(TAG, "Can't load widget preview drawable 0x" +
Sunny Goyalffe83f12014-08-14 17:39:34 -0700534 Integer.toHexString(info.previewImage) + " for provider: " + info.provider);
Michael Jurka05713af2013-01-23 12:39:24 +0100535 }
536 }
537
538 int previewWidth;
539 int previewHeight;
540 Bitmap defaultPreview = null;
541 boolean widgetPreviewExists = (drawable != null);
542 if (widgetPreviewExists) {
543 previewWidth = drawable.getIntrinsicWidth();
544 previewHeight = drawable.getIntrinsicHeight();
545 } else {
546 // Generate a preview image if we couldn't load one
547 if (cellHSpan < 1) cellHSpan = 1;
548 if (cellVSpan < 1) cellVSpan = 1;
549
Adrian Roos65d60e22014-04-15 21:07:49 +0200550 // This Drawable is not directly drawn, so there's no need to mutate it.
Michael Jurka05713af2013-01-23 12:39:24 +0100551 BitmapDrawable previewDrawable = (BitmapDrawable) mContext.getResources()
Winson Chung6706ed82013-10-02 11:00:15 -0700552 .getDrawable(R.drawable.widget_tile);
Michael Jurka05713af2013-01-23 12:39:24 +0100553 final int previewDrawableWidth = previewDrawable
554 .getIntrinsicWidth();
555 final int previewDrawableHeight = previewDrawable
556 .getIntrinsicHeight();
Winson Chung45cab392013-10-02 17:45:32 -0700557 previewWidth = previewDrawableWidth * cellHSpan;
Michael Jurka05713af2013-01-23 12:39:24 +0100558 previewHeight = previewDrawableHeight * cellVSpan;
559
Adrian Roos5d2704f2014-03-18 23:09:12 +0100560 defaultPreview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
Michael Jurka05713af2013-01-23 12:39:24 +0100561 final Canvas c = mCachedAppWidgetPreviewCanvas.get();
562 c.setBitmap(defaultPreview);
Adrian Roosfa4c7992014-03-19 15:58:14 +0100563 Paint p = mDefaultAppWidgetPreviewPaint.get();
564 if (p == null) {
565 p = new Paint();
566 p.setShader(new BitmapShader(previewDrawable.getBitmap(),
567 Shader.TileMode.REPEAT, Shader.TileMode.REPEAT));
568 mDefaultAppWidgetPreviewPaint.set(p);
569 }
570 final Rect dest = mCachedAppWidgetPreviewDestRect.get();
571 dest.set(0, 0, previewWidth, previewHeight);
572 c.drawRect(dest, p);
Michael Jurka05713af2013-01-23 12:39:24 +0100573 c.setBitmap(null);
574
575 // Draw the icon in the top left corner
Sunny Goyalffe83f12014-08-14 17:39:34 -0700576 int minOffset = (int) (mAppIconSize * WIDGET_PREVIEW_ICON_PADDING_PERCENTAGE);
Michael Jurka05713af2013-01-23 12:39:24 +0100577 int smallestSide = Math.min(previewWidth, previewHeight);
578 float iconScale = Math.min((float) smallestSide
579 / (mAppIconSize + 2 * minOffset), 1f);
580
581 try {
Sunny Goyalffe83f12014-08-14 17:39:34 -0700582 Drawable icon = mManager.loadIcon(info, mIconCache);
Michael Jurka05713af2013-01-23 12:39:24 +0100583 if (icon != null) {
Sunny Goyalffe83f12014-08-14 17:39:34 -0700584 int hoffset = (int) ((previewDrawableWidth - mAppIconSize * iconScale) / 2);
585 int yoffset = (int) ((previewDrawableHeight - mAppIconSize * iconScale) / 2);
Adrian Roosfa9ffc22014-05-12 15:59:59 +0200586 icon = mutateOnMainThread(icon);
Michael Jurka05713af2013-01-23 12:39:24 +0100587 renderDrawableToBitmap(icon, defaultPreview, hoffset,
588 yoffset, (int) (mAppIconSize * iconScale),
589 (int) (mAppIconSize * iconScale));
590 }
591 } catch (Resources.NotFoundException e) {
592 }
593 }
594
595 // Scale to fit width only - let the widget preview be clipped in the
596 // vertical dimension
597 float scale = 1f;
598 if (preScaledWidthOut != null) {
599 preScaledWidthOut[0] = previewWidth;
600 }
601 if (previewWidth > maxPreviewWidth) {
602 scale = maxPreviewWidth / (float) previewWidth;
603 }
604 if (scale != 1f) {
605 previewWidth = (int) (scale * previewWidth);
606 previewHeight = (int) (scale * previewHeight);
607 }
608
609 // If a bitmap is passed in, we use it; otherwise, we create a bitmap of the right size
610 if (preview == null) {
611 preview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
612 }
613
614 // Draw the scaled preview into the final bitmap
615 int x = (preview.getWidth() - previewWidth) / 2;
616 if (widgetPreviewExists) {
617 renderDrawableToBitmap(drawable, preview, x, 0, previewWidth,
618 previewHeight);
619 } else {
620 final Canvas c = mCachedAppWidgetPreviewCanvas.get();
621 final Rect src = mCachedAppWidgetPreviewSrcRect.get();
622 final Rect dest = mCachedAppWidgetPreviewDestRect.get();
623 c.setBitmap(preview);
624 src.set(0, 0, defaultPreview.getWidth(), defaultPreview.getHeight());
Michael Jurkae5919c52013-03-06 17:30:10 +0100625 dest.set(x, 0, x + previewWidth, previewHeight);
Michael Jurka05713af2013-01-23 12:39:24 +0100626
627 Paint p = mCachedAppWidgetPreviewPaint.get();
628 if (p == null) {
629 p = new Paint();
630 p.setFilterBitmap(true);
631 mCachedAppWidgetPreviewPaint.set(p);
632 }
633 c.drawBitmap(defaultPreview, src, dest, p);
634 c.setBitmap(null);
635 }
Sunny Goyalffe83f12014-08-14 17:39:34 -0700636 return mManager.getBadgeBitmap(info, preview);
Michael Jurka05713af2013-01-23 12:39:24 +0100637 }
638
639 private Bitmap generateShortcutPreview(
640 ResolveInfo info, int maxWidth, int maxHeight, Bitmap preview) {
641 Bitmap tempBitmap = mCachedShortcutPreviewBitmap.get();
642 final Canvas c = mCachedShortcutPreviewCanvas.get();
643 if (tempBitmap == null ||
644 tempBitmap.getWidth() != maxWidth ||
645 tempBitmap.getHeight() != maxHeight) {
646 tempBitmap = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
647 mCachedShortcutPreviewBitmap.set(tempBitmap);
648 } else {
649 c.setBitmap(tempBitmap);
650 c.drawColor(0, PorterDuff.Mode.CLEAR);
651 c.setBitmap(null);
652 }
653 // Render the icon
Sunny Goyal736f5af2014-10-16 14:07:29 -0700654 Drawable icon = mutateOnMainThread(mIconCache.getFullResIcon(info.activityInfo));
Michael Jurka05713af2013-01-23 12:39:24 +0100655
656 int paddingTop = mContext.
657 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_top);
658 int paddingLeft = mContext.
659 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_left);
660 int paddingRight = mContext.
661 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_right);
662
663 int scaledIconWidth = (maxWidth - paddingLeft - paddingRight);
664
665 renderDrawableToBitmap(
666 icon, tempBitmap, paddingLeft, paddingTop, scaledIconWidth, scaledIconWidth);
667
668 if (preview != null &&
669 (preview.getWidth() != maxWidth || preview.getHeight() != maxHeight)) {
670 throw new RuntimeException("Improperly sized bitmap passed as argument");
671 } else if (preview == null) {
672 preview = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
673 }
674
675 c.setBitmap(preview);
676 // Draw a desaturated/scaled version of the icon in the background as a watermark
677 Paint p = mCachedShortcutPreviewPaint.get();
678 if (p == null) {
679 p = new Paint();
680 ColorMatrix colorMatrix = new ColorMatrix();
681 colorMatrix.setSaturation(0);
682 p.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
683 p.setAlpha((int) (255 * 0.06f));
684 mCachedShortcutPreviewPaint.set(p);
685 }
686 c.drawBitmap(tempBitmap, 0, 0, p);
687 c.setBitmap(null);
688
689 renderDrawableToBitmap(icon, preview, 0, 0, mAppIconSize, mAppIconSize);
690
691 return preview;
692 }
693
Michael Jurka05713af2013-01-23 12:39:24 +0100694 private static void renderDrawableToBitmap(
Sunny Goyalffe83f12014-08-14 17:39:34 -0700695 Drawable d, Bitmap bitmap, int x, int y, int w, int h) {
Michael Jurka05713af2013-01-23 12:39:24 +0100696 if (bitmap != null) {
697 Canvas c = new Canvas(bitmap);
Michael Jurka05713af2013-01-23 12:39:24 +0100698 Rect oldBounds = d.copyBounds();
699 d.setBounds(x, y, x + w, y + h);
700 d.draw(c);
701 d.setBounds(oldBounds); // Restore the bounds
702 c.setBitmap(null);
703 }
704 }
705
Adrian Roos65d60e22014-04-15 21:07:49 +0200706 private Drawable mutateOnMainThread(final Drawable drawable) {
707 try {
708 return mMainThreadExecutor.submit(new Callable<Drawable>() {
709 @Override
710 public Drawable call() throws Exception {
711 return drawable.mutate();
712 }
713 }).get();
714 } catch (InterruptedException e) {
715 Thread.currentThread().interrupt();
716 throw new RuntimeException(e);
717 } catch (ExecutionException e) {
718 throw new RuntimeException(e);
719 }
720 }
Adrian Roos1f375ab2014-04-28 18:26:38 +0200721
722 private static final int MAX_OPEN_FILES = 1024;
723 private static final int SAMPLE_RATE = 23;
724 /**
725 * Dumps all files that are open in this process without allocating a file descriptor.
726 */
727 private static void dumpOpenFiles() {
728 try {
729 Log.i(TAG, "DUMP OF OPEN FILES (sample rate: 1 every " + SAMPLE_RATE + "):");
730 final String TYPE_APK = "apk";
731 final String TYPE_JAR = "jar";
732 final String TYPE_PIPE = "pipe";
733 final String TYPE_SOCKET = "socket";
734 final String TYPE_DB = "db";
735 final String TYPE_ANON_INODE = "anon_inode";
736 final String TYPE_DEV = "dev";
737 final String TYPE_NON_FS = "non-fs";
738 final String TYPE_OTHER = "other";
739 List<String> types = Arrays.asList(TYPE_APK, TYPE_JAR, TYPE_PIPE, TYPE_SOCKET, TYPE_DB,
740 TYPE_ANON_INODE, TYPE_DEV, TYPE_NON_FS, TYPE_OTHER);
741 int[] count = new int[types.size()];
742 int[] duplicates = new int[types.size()];
743 HashSet<String> files = new HashSet<String>();
744 int total = 0;
745 for (int i = 0; i < MAX_OPEN_FILES; i++) {
746 // This is a gigantic hack but unfortunately the only way to resolve an fd
747 // to a file name. Note that we have to loop over all possible fds because
748 // reading the directory would require allocating a new fd. The kernel is
749 // currently implemented such that no fd is larger then the current rlimit,
750 // which is why it's safe to loop over them in such a way.
751 String fd = "/proc/self/fd/" + i;
752 try {
753 // getCanonicalPath() uses readlink behind the scene which doesn't require
754 // a file descriptor.
755 String resolved = new File(fd).getCanonicalPath();
756 int type = types.indexOf(TYPE_OTHER);
757 if (resolved.startsWith("/dev/")) {
758 type = types.indexOf(TYPE_DEV);
759 } else if (resolved.endsWith(".apk")) {
760 type = types.indexOf(TYPE_APK);
761 } else if (resolved.endsWith(".jar")) {
762 type = types.indexOf(TYPE_JAR);
763 } else if (resolved.contains("/fd/pipe:")) {
764 type = types.indexOf(TYPE_PIPE);
765 } else if (resolved.contains("/fd/socket:")) {
766 type = types.indexOf(TYPE_SOCKET);
767 } else if (resolved.contains("/fd/anon_inode:")) {
768 type = types.indexOf(TYPE_ANON_INODE);
769 } else if (resolved.endsWith(".db") || resolved.contains("/databases/")) {
770 type = types.indexOf(TYPE_DB);
771 } else if (resolved.startsWith("/proc/") && resolved.contains("/fd/")) {
772 // Those are the files that don't point anywhere on the file system.
773 // getCanonicalPath() wrongly interprets these as relative symlinks and
774 // resolves them within /proc/<pid>/fd/.
775 type = types.indexOf(TYPE_NON_FS);
776 }
777 count[type]++;
778 total++;
779 if (files.contains(resolved)) {
780 duplicates[type]++;
781 }
782 files.add(resolved);
783 if (total % SAMPLE_RATE == 0) {
784 Log.i(TAG, " fd " + i + ": " + resolved
785 + " (" + types.get(type) + ")");
786 }
787 } catch (IOException e) {
788 // Ignoring exceptions for non-existing file descriptors.
789 }
790 }
791 for (int i = 0; i < types.size(); i++) {
792 Log.i(TAG, String.format("Open %10s files: %4d total, %4d duplicates",
793 types.get(i), count[i], duplicates[i]));
794 }
795 } catch (Throwable t) {
796 // Catch everything. This is called from an exception handler that we shouldn't upset.
797 Log.e(TAG, "Unable to log open files.", t);
798 }
799 }
Michael Jurka05713af2013-01-23 12:39:24 +0100800}