blob: 4e6fe1f88633e424ac870a6315f764b57794251e [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;
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);
347
348 ResolveInfo info = (ResolveInfo) o;
349 sb.append(new ComponentName(info.activityInfo.packageName,
350 info.activityInfo.name).flattenToString());
351 output = sb.toString();
352 sb.setLength(0);
353 }
354 return output;
355 }
356
357 private String getObjectPackage(Object o) {
358 if (o instanceof AppWidgetProviderInfo) {
359 return ((AppWidgetProviderInfo) o).provider.getPackageName();
360 } else {
361 ResolveInfo info = (ResolveInfo) o;
362 return info.activityInfo.packageName;
363 }
364 }
365
366 private void writeToDb(Object o, Bitmap preview) {
367 String name = getObjectName(o);
368 SQLiteDatabase db = mDb.getWritableDatabase();
369 ContentValues values = new ContentValues();
370
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100371 values.put(CacheDb.COLUMN_NAME, name);
Michael Jurka05713af2013-01-23 12:39:24 +0100372 ByteArrayOutputStream stream = new ByteArrayOutputStream();
373 preview.compress(Bitmap.CompressFormat.PNG, 100, stream);
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100374 values.put(CacheDb.COLUMN_PREVIEW_BITMAP, stream.toByteArray());
375 values.put(CacheDb.COLUMN_SIZE, mSize);
Michael Jurka6e27f642013-12-10 13:40:30 +0100376 try {
377 db.insert(CacheDb.TABLE_NAME, null, values);
378 } catch (SQLiteDiskIOException e) {
379 recreateDb();
Adrian Roos1f375ab2014-04-28 18:26:38 +0200380 } catch (SQLiteCantOpenDatabaseException e) {
381 dumpOpenFiles();
382 throw e;
Michael Jurka6e27f642013-12-10 13:40:30 +0100383 }
Michael Jurka05713af2013-01-23 12:39:24 +0100384 }
385
Michael Jurka8ff02ca2013-11-01 14:19:27 +0100386 private void clearDb() {
387 SQLiteDatabase db = mDb.getWritableDatabase();
388 // Delete everything
Michael Jurka6e27f642013-12-10 13:40:30 +0100389 try {
390 db.delete(CacheDb.TABLE_NAME, null, null);
391 } catch (SQLiteDiskIOException e) {
Adrian Roos1f375ab2014-04-28 18:26:38 +0200392 } catch (SQLiteCantOpenDatabaseException e) {
393 dumpOpenFiles();
394 throw e;
Michael Jurka6e27f642013-12-10 13:40:30 +0100395 }
Michael Jurka8ff02ca2013-11-01 14:19:27 +0100396 }
397
Michael Jurkaeb1bb922013-09-26 11:29:01 -0700398 public static void removePackageFromDb(final CacheDb cacheDb, final String packageName) {
Michael Jurka05713af2013-01-23 12:39:24 +0100399 synchronized(sInvalidPackages) {
400 sInvalidPackages.add(packageName);
401 }
402 new AsyncTask<Void, Void, Void>() {
403 public Void doInBackground(Void ... args) {
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100404 SQLiteDatabase db = cacheDb.getWritableDatabase();
Michael Jurka6e27f642013-12-10 13:40:30 +0100405 try {
406 db.delete(CacheDb.TABLE_NAME,
407 CacheDb.COLUMN_NAME + " LIKE ? OR " +
408 CacheDb.COLUMN_NAME + " LIKE ?", // SELECT query
409 new String[] {
410 WIDGET_PREFIX + packageName + "/%",
411 SHORTCUT_PREFIX + packageName + "/%"
412 } // args to SELECT query
413 );
414 } catch (SQLiteDiskIOException e) {
Adrian Roos1f375ab2014-04-28 18:26:38 +0200415 } catch (SQLiteCantOpenDatabaseException e) {
416 dumpOpenFiles();
417 throw e;
Michael Jurka6e27f642013-12-10 13:40:30 +0100418 }
Michael Jurka05713af2013-01-23 12:39:24 +0100419 synchronized(sInvalidPackages) {
420 sInvalidPackages.remove(packageName);
421 }
422 return null;
423 }
424 }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
425 }
426
Sunny Goyalffe83f12014-08-14 17:39:34 -0700427 private static void removeItemFromDb(final CacheDb cacheDb, final String objectName) {
Michael Jurkaeb1bb922013-09-26 11:29:01 -0700428 new AsyncTask<Void, Void, Void>() {
429 public Void doInBackground(Void ... args) {
430 SQLiteDatabase db = cacheDb.getWritableDatabase();
Michael Jurka6e27f642013-12-10 13:40:30 +0100431 try {
432 db.delete(CacheDb.TABLE_NAME,
433 CacheDb.COLUMN_NAME + " = ? ", // SELECT query
434 new String[] { objectName }); // args to SELECT query
435 } catch (SQLiteDiskIOException e) {
Adrian Roos1f375ab2014-04-28 18:26:38 +0200436 } catch (SQLiteCantOpenDatabaseException e) {
437 dumpOpenFiles();
438 throw e;
Michael Jurka6e27f642013-12-10 13:40:30 +0100439 }
Michael Jurkaeb1bb922013-09-26 11:29:01 -0700440 return null;
441 }
442 }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
443 }
444
Michael Jurka05713af2013-01-23 12:39:24 +0100445 private Bitmap readFromDb(String name, Bitmap b) {
446 if (mCachedSelectQuery == null) {
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100447 mCachedSelectQuery = CacheDb.COLUMN_NAME + " = ? AND " +
448 CacheDb.COLUMN_SIZE + " = ?";
Michael Jurka05713af2013-01-23 12:39:24 +0100449 }
450 SQLiteDatabase db = mDb.getReadableDatabase();
Michael Jurka6e27f642013-12-10 13:40:30 +0100451 Cursor result;
452 try {
453 result = db.query(CacheDb.TABLE_NAME,
454 new String[] { CacheDb.COLUMN_PREVIEW_BITMAP }, // cols to return
455 mCachedSelectQuery, // select query
456 new String[] { name, mSize }, // args to select query
457 null,
458 null,
459 null,
460 null);
461 } catch (SQLiteDiskIOException e) {
462 recreateDb();
463 return null;
Adrian Roos1f375ab2014-04-28 18:26:38 +0200464 } catch (SQLiteCantOpenDatabaseException e) {
465 dumpOpenFiles();
466 throw e;
Michael Jurka6e27f642013-12-10 13:40:30 +0100467 }
Michael Jurka05713af2013-01-23 12:39:24 +0100468 if (result.getCount() > 0) {
469 result.moveToFirst();
470 byte[] blob = result.getBlob(0);
471 result.close();
472 final BitmapFactory.Options opts = mCachedBitmapFactoryOptions.get();
473 opts.inBitmap = b;
474 opts.inSampleSize = 1;
Michael Jurkaeb1bb922013-09-26 11:29:01 -0700475 try {
476 return BitmapFactory.decodeByteArray(blob, 0, blob.length, opts);
477 } catch (IllegalArgumentException e) {
478 removeItemFromDb(mDb, name);
479 return null;
480 }
Michael Jurka05713af2013-01-23 12:39:24 +0100481 } else {
482 result.close();
483 return null;
484 }
485 }
486
Sunny Goyalffe83f12014-08-14 17:39:34 -0700487 private Bitmap generatePreview(Object info, Bitmap preview) {
Michael Jurka05713af2013-01-23 12:39:24 +0100488 if (preview != null &&
Michael Jurka3f4e0702013-02-05 11:21:28 +0100489 (preview.getWidth() != mPreviewBitmapWidth ||
490 preview.getHeight() != mPreviewBitmapHeight)) {
Michael Jurka05713af2013-01-23 12:39:24 +0100491 throw new RuntimeException("Improperly sized bitmap passed as argument");
492 }
493 if (info instanceof AppWidgetProviderInfo) {
494 return generateWidgetPreview((AppWidgetProviderInfo) info, preview);
495 } else {
496 return generateShortcutPreview(
Michael Jurka3f4e0702013-02-05 11:21:28 +0100497 (ResolveInfo) info, mPreviewBitmapWidth, mPreviewBitmapHeight, preview);
Michael Jurka05713af2013-01-23 12:39:24 +0100498 }
499 }
500
501 public Bitmap generateWidgetPreview(AppWidgetProviderInfo info, Bitmap preview) {
Chris Wrenfd13c712013-09-27 15:45:19 -0400502 int[] cellSpans = Launcher.getSpanForWidget(mContext, info);
Michael Jurka05713af2013-01-23 12:39:24 +0100503 int maxWidth = maxWidthForWidgetPreview(cellSpans[0]);
504 int maxHeight = maxHeightForWidgetPreview(cellSpans[1]);
Sunny Goyalffe83f12014-08-14 17:39:34 -0700505 return generateWidgetPreview(info, cellSpans[0], cellSpans[1],
506 maxWidth, maxHeight, preview, null);
Michael Jurka05713af2013-01-23 12:39:24 +0100507 }
508
509 public int maxWidthForWidgetPreview(int spanX) {
Michael Jurka3f4e0702013-02-05 11:21:28 +0100510 return Math.min(mPreviewBitmapWidth,
Michael Jurka05713af2013-01-23 12:39:24 +0100511 mWidgetSpacingLayout.estimateCellWidth(spanX));
512 }
513
514 public int maxHeightForWidgetPreview(int spanY) {
Michael Jurka3f4e0702013-02-05 11:21:28 +0100515 return Math.min(mPreviewBitmapHeight,
Michael Jurka05713af2013-01-23 12:39:24 +0100516 mWidgetSpacingLayout.estimateCellHeight(spanY));
517 }
518
Sunny Goyalffe83f12014-08-14 17:39:34 -0700519 public Bitmap generateWidgetPreview(AppWidgetProviderInfo info, int cellHSpan, int cellVSpan,
520 int maxPreviewWidth, int maxPreviewHeight, Bitmap preview, int[] preScaledWidthOut) {
Michael Jurka05713af2013-01-23 12:39:24 +0100521 // Load the preview image if possible
Michael Jurka05713af2013-01-23 12:39:24 +0100522 if (maxPreviewWidth < 0) maxPreviewWidth = Integer.MAX_VALUE;
523 if (maxPreviewHeight < 0) maxPreviewHeight = Integer.MAX_VALUE;
524
525 Drawable drawable = null;
Sunny Goyalffe83f12014-08-14 17:39:34 -0700526 if (info.previewImage != 0) {
527 drawable = mManager.loadPreview(info);
Adrian Roosfa9ffc22014-05-12 15:59:59 +0200528 if (drawable != null) {
529 drawable = mutateOnMainThread(drawable);
530 } else {
Michael Jurka05713af2013-01-23 12:39:24 +0100531 Log.w(TAG, "Can't load widget preview drawable 0x" +
Sunny Goyalffe83f12014-08-14 17:39:34 -0700532 Integer.toHexString(info.previewImage) + " for provider: " + info.provider);
Michael Jurka05713af2013-01-23 12:39:24 +0100533 }
534 }
535
536 int previewWidth;
537 int previewHeight;
538 Bitmap defaultPreview = null;
539 boolean widgetPreviewExists = (drawable != null);
540 if (widgetPreviewExists) {
541 previewWidth = drawable.getIntrinsicWidth();
542 previewHeight = drawable.getIntrinsicHeight();
543 } else {
544 // Generate a preview image if we couldn't load one
545 if (cellHSpan < 1) cellHSpan = 1;
546 if (cellVSpan < 1) cellVSpan = 1;
547
Adrian Roos65d60e22014-04-15 21:07:49 +0200548 // This Drawable is not directly drawn, so there's no need to mutate it.
Michael Jurka05713af2013-01-23 12:39:24 +0100549 BitmapDrawable previewDrawable = (BitmapDrawable) mContext.getResources()
Winson Chung6706ed82013-10-02 11:00:15 -0700550 .getDrawable(R.drawable.widget_tile);
Michael Jurka05713af2013-01-23 12:39:24 +0100551 final int previewDrawableWidth = previewDrawable
552 .getIntrinsicWidth();
553 final int previewDrawableHeight = previewDrawable
554 .getIntrinsicHeight();
Winson Chung45cab392013-10-02 17:45:32 -0700555 previewWidth = previewDrawableWidth * cellHSpan;
Michael Jurka05713af2013-01-23 12:39:24 +0100556 previewHeight = previewDrawableHeight * cellVSpan;
557
Adrian Roos5d2704f2014-03-18 23:09:12 +0100558 defaultPreview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
Michael Jurka05713af2013-01-23 12:39:24 +0100559 final Canvas c = mCachedAppWidgetPreviewCanvas.get();
560 c.setBitmap(defaultPreview);
Adrian Roosfa4c7992014-03-19 15:58:14 +0100561 Paint p = mDefaultAppWidgetPreviewPaint.get();
562 if (p == null) {
563 p = new Paint();
564 p.setShader(new BitmapShader(previewDrawable.getBitmap(),
565 Shader.TileMode.REPEAT, Shader.TileMode.REPEAT));
566 mDefaultAppWidgetPreviewPaint.set(p);
567 }
568 final Rect dest = mCachedAppWidgetPreviewDestRect.get();
569 dest.set(0, 0, previewWidth, previewHeight);
570 c.drawRect(dest, p);
Michael Jurka05713af2013-01-23 12:39:24 +0100571 c.setBitmap(null);
572
573 // Draw the icon in the top left corner
Sunny Goyalffe83f12014-08-14 17:39:34 -0700574 int minOffset = (int) (mAppIconSize * WIDGET_PREVIEW_ICON_PADDING_PERCENTAGE);
Michael Jurka05713af2013-01-23 12:39:24 +0100575 int smallestSide = Math.min(previewWidth, previewHeight);
576 float iconScale = Math.min((float) smallestSide
577 / (mAppIconSize + 2 * minOffset), 1f);
578
579 try {
Sunny Goyalffe83f12014-08-14 17:39:34 -0700580 Drawable icon = mManager.loadIcon(info, mIconCache);
Michael Jurka05713af2013-01-23 12:39:24 +0100581 if (icon != null) {
Sunny Goyalffe83f12014-08-14 17:39:34 -0700582 int hoffset = (int) ((previewDrawableWidth - mAppIconSize * iconScale) / 2);
583 int yoffset = (int) ((previewDrawableHeight - mAppIconSize * iconScale) / 2);
Adrian Roosfa9ffc22014-05-12 15:59:59 +0200584 icon = mutateOnMainThread(icon);
Michael Jurka05713af2013-01-23 12:39:24 +0100585 renderDrawableToBitmap(icon, defaultPreview, hoffset,
586 yoffset, (int) (mAppIconSize * iconScale),
587 (int) (mAppIconSize * iconScale));
588 }
589 } catch (Resources.NotFoundException e) {
590 }
591 }
592
593 // Scale to fit width only - let the widget preview be clipped in the
594 // vertical dimension
595 float scale = 1f;
596 if (preScaledWidthOut != null) {
597 preScaledWidthOut[0] = previewWidth;
598 }
599 if (previewWidth > maxPreviewWidth) {
600 scale = maxPreviewWidth / (float) previewWidth;
601 }
602 if (scale != 1f) {
603 previewWidth = (int) (scale * previewWidth);
604 previewHeight = (int) (scale * previewHeight);
605 }
606
607 // If a bitmap is passed in, we use it; otherwise, we create a bitmap of the right size
608 if (preview == null) {
609 preview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
610 }
611
612 // Draw the scaled preview into the final bitmap
613 int x = (preview.getWidth() - previewWidth) / 2;
614 if (widgetPreviewExists) {
615 renderDrawableToBitmap(drawable, preview, x, 0, previewWidth,
616 previewHeight);
617 } else {
618 final Canvas c = mCachedAppWidgetPreviewCanvas.get();
619 final Rect src = mCachedAppWidgetPreviewSrcRect.get();
620 final Rect dest = mCachedAppWidgetPreviewDestRect.get();
621 c.setBitmap(preview);
622 src.set(0, 0, defaultPreview.getWidth(), defaultPreview.getHeight());
Michael Jurkae5919c52013-03-06 17:30:10 +0100623 dest.set(x, 0, x + previewWidth, previewHeight);
Michael Jurka05713af2013-01-23 12:39:24 +0100624
625 Paint p = mCachedAppWidgetPreviewPaint.get();
626 if (p == null) {
627 p = new Paint();
628 p.setFilterBitmap(true);
629 mCachedAppWidgetPreviewPaint.set(p);
630 }
631 c.drawBitmap(defaultPreview, src, dest, p);
632 c.setBitmap(null);
633 }
Sunny Goyalffe83f12014-08-14 17:39:34 -0700634 return mManager.getBadgeBitmap(info, preview);
Michael Jurka05713af2013-01-23 12:39:24 +0100635 }
636
637 private Bitmap generateShortcutPreview(
638 ResolveInfo info, int maxWidth, int maxHeight, Bitmap preview) {
639 Bitmap tempBitmap = mCachedShortcutPreviewBitmap.get();
640 final Canvas c = mCachedShortcutPreviewCanvas.get();
641 if (tempBitmap == null ||
642 tempBitmap.getWidth() != maxWidth ||
643 tempBitmap.getHeight() != maxHeight) {
644 tempBitmap = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
645 mCachedShortcutPreviewBitmap.set(tempBitmap);
646 } else {
647 c.setBitmap(tempBitmap);
648 c.drawColor(0, PorterDuff.Mode.CLEAR);
649 c.setBitmap(null);
650 }
651 // Render the icon
Sunny Goyal736f5af2014-10-16 14:07:29 -0700652 Drawable icon = mutateOnMainThread(mIconCache.getFullResIcon(info.activityInfo));
Michael Jurka05713af2013-01-23 12:39:24 +0100653
654 int paddingTop = mContext.
655 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_top);
656 int paddingLeft = mContext.
657 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_left);
658 int paddingRight = mContext.
659 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_right);
660
661 int scaledIconWidth = (maxWidth - paddingLeft - paddingRight);
662
663 renderDrawableToBitmap(
664 icon, tempBitmap, paddingLeft, paddingTop, scaledIconWidth, scaledIconWidth);
665
666 if (preview != null &&
667 (preview.getWidth() != maxWidth || preview.getHeight() != maxHeight)) {
668 throw new RuntimeException("Improperly sized bitmap passed as argument");
669 } else if (preview == null) {
670 preview = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
671 }
672
673 c.setBitmap(preview);
674 // Draw a desaturated/scaled version of the icon in the background as a watermark
675 Paint p = mCachedShortcutPreviewPaint.get();
676 if (p == null) {
677 p = new Paint();
678 ColorMatrix colorMatrix = new ColorMatrix();
679 colorMatrix.setSaturation(0);
680 p.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
681 p.setAlpha((int) (255 * 0.06f));
682 mCachedShortcutPreviewPaint.set(p);
683 }
684 c.drawBitmap(tempBitmap, 0, 0, p);
685 c.setBitmap(null);
686
687 renderDrawableToBitmap(icon, preview, 0, 0, mAppIconSize, mAppIconSize);
688
689 return preview;
690 }
691
Michael Jurka05713af2013-01-23 12:39:24 +0100692 private static void renderDrawableToBitmap(
Sunny Goyalffe83f12014-08-14 17:39:34 -0700693 Drawable d, Bitmap bitmap, int x, int y, int w, int h) {
Michael Jurka05713af2013-01-23 12:39:24 +0100694 if (bitmap != null) {
695 Canvas c = new Canvas(bitmap);
Michael Jurka05713af2013-01-23 12:39:24 +0100696 Rect oldBounds = d.copyBounds();
697 d.setBounds(x, y, x + w, y + h);
698 d.draw(c);
699 d.setBounds(oldBounds); // Restore the bounds
700 c.setBitmap(null);
701 }
702 }
703
Adrian Roos65d60e22014-04-15 21:07:49 +0200704 private Drawable mutateOnMainThread(final Drawable drawable) {
705 try {
706 return mMainThreadExecutor.submit(new Callable<Drawable>() {
707 @Override
708 public Drawable call() throws Exception {
709 return drawable.mutate();
710 }
711 }).get();
712 } catch (InterruptedException e) {
713 Thread.currentThread().interrupt();
714 throw new RuntimeException(e);
715 } catch (ExecutionException e) {
716 throw new RuntimeException(e);
717 }
718 }
Adrian Roos1f375ab2014-04-28 18:26:38 +0200719
720 private static final int MAX_OPEN_FILES = 1024;
721 private static final int SAMPLE_RATE = 23;
722 /**
723 * Dumps all files that are open in this process without allocating a file descriptor.
724 */
725 private static void dumpOpenFiles() {
726 try {
727 Log.i(TAG, "DUMP OF OPEN FILES (sample rate: 1 every " + SAMPLE_RATE + "):");
728 final String TYPE_APK = "apk";
729 final String TYPE_JAR = "jar";
730 final String TYPE_PIPE = "pipe";
731 final String TYPE_SOCKET = "socket";
732 final String TYPE_DB = "db";
733 final String TYPE_ANON_INODE = "anon_inode";
734 final String TYPE_DEV = "dev";
735 final String TYPE_NON_FS = "non-fs";
736 final String TYPE_OTHER = "other";
737 List<String> types = Arrays.asList(TYPE_APK, TYPE_JAR, TYPE_PIPE, TYPE_SOCKET, TYPE_DB,
738 TYPE_ANON_INODE, TYPE_DEV, TYPE_NON_FS, TYPE_OTHER);
739 int[] count = new int[types.size()];
740 int[] duplicates = new int[types.size()];
741 HashSet<String> files = new HashSet<String>();
742 int total = 0;
743 for (int i = 0; i < MAX_OPEN_FILES; i++) {
744 // This is a gigantic hack but unfortunately the only way to resolve an fd
745 // to a file name. Note that we have to loop over all possible fds because
746 // reading the directory would require allocating a new fd. The kernel is
747 // currently implemented such that no fd is larger then the current rlimit,
748 // which is why it's safe to loop over them in such a way.
749 String fd = "/proc/self/fd/" + i;
750 try {
751 // getCanonicalPath() uses readlink behind the scene which doesn't require
752 // a file descriptor.
753 String resolved = new File(fd).getCanonicalPath();
754 int type = types.indexOf(TYPE_OTHER);
755 if (resolved.startsWith("/dev/")) {
756 type = types.indexOf(TYPE_DEV);
757 } else if (resolved.endsWith(".apk")) {
758 type = types.indexOf(TYPE_APK);
759 } else if (resolved.endsWith(".jar")) {
760 type = types.indexOf(TYPE_JAR);
761 } else if (resolved.contains("/fd/pipe:")) {
762 type = types.indexOf(TYPE_PIPE);
763 } else if (resolved.contains("/fd/socket:")) {
764 type = types.indexOf(TYPE_SOCKET);
765 } else if (resolved.contains("/fd/anon_inode:")) {
766 type = types.indexOf(TYPE_ANON_INODE);
767 } else if (resolved.endsWith(".db") || resolved.contains("/databases/")) {
768 type = types.indexOf(TYPE_DB);
769 } else if (resolved.startsWith("/proc/") && resolved.contains("/fd/")) {
770 // Those are the files that don't point anywhere on the file system.
771 // getCanonicalPath() wrongly interprets these as relative symlinks and
772 // resolves them within /proc/<pid>/fd/.
773 type = types.indexOf(TYPE_NON_FS);
774 }
775 count[type]++;
776 total++;
777 if (files.contains(resolved)) {
778 duplicates[type]++;
779 }
780 files.add(resolved);
781 if (total % SAMPLE_RATE == 0) {
782 Log.i(TAG, " fd " + i + ": " + resolved
783 + " (" + types.get(type) + ")");
784 }
785 } catch (IOException e) {
786 // Ignoring exceptions for non-existing file descriptors.
787 }
788 }
789 for (int i = 0; i < types.size(); i++) {
790 Log.i(TAG, String.format("Open %10s files: %4d total, %4d duplicates",
791 types.get(i), count[i], duplicates[i]));
792 }
793 } catch (Throwable t) {
794 // Catch everything. This is called from an exception handler that we shouldn't upset.
795 Log.e(TAG, "Unable to log open files.", t);
796 }
797 }
Michael Jurka05713af2013-01-23 12:39:24 +0100798}