blob: 8f2d3edc31186fa0ee367118632f8c178be90654 [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;
15import android.graphics.Bitmap;
16import android.graphics.Bitmap.Config;
17import android.graphics.BitmapFactory;
Adrian Roosfa4c7992014-03-19 15:58:14 +010018import android.graphics.BitmapShader;
Michael Jurka05713af2013-01-23 12:39:24 +010019import android.graphics.Canvas;
20import android.graphics.ColorMatrix;
21import android.graphics.ColorMatrixColorFilter;
22import android.graphics.Paint;
23import android.graphics.PorterDuff;
24import android.graphics.Rect;
25import android.graphics.Shader;
26import android.graphics.drawable.BitmapDrawable;
27import android.graphics.drawable.Drawable;
28import android.os.AsyncTask;
29import android.util.Log;
30
Sunny Goyalffe83f12014-08-14 17:39:34 -070031import com.android.launcher3.compat.AppWidgetManagerCompat;
32
Michael Jurka05713af2013-01-23 12:39:24 +010033import java.io.ByteArrayOutputStream;
34import java.io.File;
Adrian Roos1f375ab2014-04-28 18:26:38 +020035import java.io.IOException;
Michael Jurka05713af2013-01-23 12:39:24 +010036import java.lang.ref.SoftReference;
37import java.lang.ref.WeakReference;
38import java.util.ArrayList;
Adrian Roos1f375ab2014-04-28 18:26:38 +020039import java.util.Arrays;
Michael Jurka05713af2013-01-23 12:39:24 +010040import java.util.HashMap;
41import java.util.HashSet;
Adrian Roos1f375ab2014-04-28 18:26:38 +020042import java.util.List;
Adrian Roos65d60e22014-04-15 21:07:49 +020043import java.util.concurrent.Callable;
44import java.util.concurrent.ExecutionException;
Michael Jurka05713af2013-01-23 12:39:24 +010045
Sunny Goyalffe83f12014-08-14 17:39:34 -070046public class WidgetPreviewLoader {
Michael Jurka05713af2013-01-23 12:39:24 +010047
Sunny Goyalffe83f12014-08-14 17:39:34 -070048 private static abstract class SoftReferenceThreadLocal<T> {
49 private ThreadLocal<SoftReference<T>> mThreadLocal;
50 public SoftReferenceThreadLocal() {
51 mThreadLocal = new ThreadLocal<SoftReference<T>>();
52 }
Michael Jurka05713af2013-01-23 12:39:24 +010053
Sunny Goyalffe83f12014-08-14 17:39:34 -070054 abstract T initialValue();
Michael Jurka05713af2013-01-23 12:39:24 +010055
Sunny Goyalffe83f12014-08-14 17:39:34 -070056 public void set(T t) {
57 mThreadLocal.set(new SoftReference<T>(t));
58 }
59
60 public T get() {
61 SoftReference<T> reference = mThreadLocal.get();
62 T obj;
63 if (reference == null) {
Michael Jurka05713af2013-01-23 12:39:24 +010064 obj = initialValue();
65 mThreadLocal.set(new SoftReference<T>(obj));
Sunny Goyalffe83f12014-08-14 17:39:34 -070066 return obj;
67 } else {
68 obj = reference.get();
69 if (obj == null) {
70 obj = initialValue();
71 mThreadLocal.set(new SoftReference<T>(obj));
72 }
73 return obj;
Michael Jurka05713af2013-01-23 12:39:24 +010074 }
Michael Jurka05713af2013-01-23 12:39:24 +010075 }
76 }
Michael Jurka05713af2013-01-23 12:39:24 +010077
Sunny Goyalffe83f12014-08-14 17:39:34 -070078 private static class CanvasCache extends SoftReferenceThreadLocal<Canvas> {
79 @Override
80 protected Canvas initialValue() {
81 return new Canvas();
82 }
Michael Jurka05713af2013-01-23 12:39:24 +010083 }
Michael Jurka05713af2013-01-23 12:39:24 +010084
Sunny Goyalffe83f12014-08-14 17:39:34 -070085 private static class PaintCache extends SoftReferenceThreadLocal<Paint> {
86 @Override
87 protected Paint initialValue() {
88 return null;
89 }
Michael Jurka05713af2013-01-23 12:39:24 +010090 }
Michael Jurka05713af2013-01-23 12:39:24 +010091
Sunny Goyalffe83f12014-08-14 17:39:34 -070092 private static class BitmapCache extends SoftReferenceThreadLocal<Bitmap> {
93 @Override
94 protected Bitmap initialValue() {
95 return null;
96 }
Michael Jurka05713af2013-01-23 12:39:24 +010097 }
Michael Jurka05713af2013-01-23 12:39:24 +010098
Sunny Goyalffe83f12014-08-14 17:39:34 -070099 private static class RectCache extends SoftReferenceThreadLocal<Rect> {
100 @Override
101 protected Rect initialValue() {
102 return new Rect();
103 }
Michael Jurka05713af2013-01-23 12:39:24 +0100104 }
Michael Jurka05713af2013-01-23 12:39:24 +0100105
Sunny Goyalffe83f12014-08-14 17:39:34 -0700106 private static class BitmapFactoryOptionsCache extends
107 SoftReferenceThreadLocal<BitmapFactory.Options> {
108 @Override
109 protected BitmapFactory.Options initialValue() {
110 return new BitmapFactory.Options();
111 }
Michael Jurka05713af2013-01-23 12:39:24 +0100112 }
Michael Jurka05713af2013-01-23 12:39:24 +0100113
Sunny Goyalffe83f12014-08-14 17:39:34 -0700114 private static final String TAG = "WidgetPreviewLoader";
115 private static final String ANDROID_INCREMENTAL_VERSION_NAME_KEY = "android.incremental.version";
116
117 private static final float WIDGET_PREVIEW_ICON_PADDING_PERCENTAGE = 0.25f;
118 private static final HashSet<String> sInvalidPackages = new HashSet<String>();
119
120 // Used for drawing shortcut previews
121 private final BitmapCache mCachedShortcutPreviewBitmap = new BitmapCache();
122 private final PaintCache mCachedShortcutPreviewPaint = new PaintCache();
123 private final CanvasCache mCachedShortcutPreviewCanvas = new CanvasCache();
124
125 // Used for drawing widget previews
126 private final CanvasCache mCachedAppWidgetPreviewCanvas = new CanvasCache();
127 private final RectCache mCachedAppWidgetPreviewSrcRect = new RectCache();
128 private final RectCache mCachedAppWidgetPreviewDestRect = new RectCache();
129 private final PaintCache mCachedAppWidgetPreviewPaint = new PaintCache();
130 private final PaintCache mDefaultAppWidgetPreviewPaint = new PaintCache();
131 private final BitmapFactoryOptionsCache mCachedBitmapFactoryOptions = new BitmapFactoryOptionsCache();
132
Sameer Padala8fd74832014-09-08 16:00:29 -0700133 private final HashMap<String, WeakReference<Bitmap>> mLoadedPreviews = new HashMap<String, WeakReference<Bitmap>>();
134 private final ArrayList<SoftReference<Bitmap>> mUnusedBitmaps = new ArrayList<SoftReference<Bitmap>>();
Sunny Goyalffe83f12014-08-14 17:39:34 -0700135
136 private final Context mContext;
137 private final int mAppIconSize;
138 private final IconCache mIconCache;
139 private final AppWidgetManagerCompat mManager;
Michael Jurka05713af2013-01-23 12:39:24 +0100140
Michael Jurka3f4e0702013-02-05 11:21:28 +0100141 private int mPreviewBitmapWidth;
142 private int mPreviewBitmapHeight;
Michael Jurka05713af2013-01-23 12:39:24 +0100143 private String mSize;
Michael Jurka05713af2013-01-23 12:39:24 +0100144 private PagedViewCellLayout mWidgetSpacingLayout;
145
Michael Jurka05713af2013-01-23 12:39:24 +0100146 private String mCachedSelectQuery;
Michael Jurka05713af2013-01-23 12:39:24 +0100147
Michael Jurka05713af2013-01-23 12:39:24 +0100148
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100149 private CacheDb mDb;
Michael Jurka05713af2013-01-23 12:39:24 +0100150
Adrian Roos65d60e22014-04-15 21:07:49 +0200151 private final MainThreadExecutor mMainThreadExecutor = new MainThreadExecutor();
152
Chris Wrenfd13c712013-09-27 15:45:19 -0400153 public WidgetPreviewLoader(Context context) {
Winson Chung5f8afe62013-08-12 16:19:28 -0700154 LauncherAppState app = LauncherAppState.getInstance();
155 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
156
Chris Wrenfd13c712013-09-27 15:45:19 -0400157 mContext = context;
Winson Chung5f8afe62013-08-12 16:19:28 -0700158 mAppIconSize = grid.iconSizePx;
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100159 mIconCache = app.getIconCache();
Sunny Goyalffe83f12014-08-14 17:39:34 -0700160 mManager = AppWidgetManagerCompat.getInstance(context);
161
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100162 mDb = app.getWidgetPreviewCacheDb();
Michael Jurka8ff02ca2013-11-01 14:19:27 +0100163
164 SharedPreferences sp = context.getSharedPreferences(
165 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
166 final String lastVersionName = sp.getString(ANDROID_INCREMENTAL_VERSION_NAME_KEY, null);
167 final String versionName = android.os.Build.VERSION.INCREMENTAL;
168 if (!versionName.equals(lastVersionName)) {
169 // clear all the previews whenever the system version changes, to ensure that previews
170 // are up-to-date for any apps that might have been updated with the system
171 clearDb();
172
173 SharedPreferences.Editor editor = sp.edit();
174 editor.putString(ANDROID_INCREMENTAL_VERSION_NAME_KEY, versionName);
175 editor.commit();
176 }
Michael Jurka3f4e0702013-02-05 11:21:28 +0100177 }
Sunny Goyalffe83f12014-08-14 17:39:34 -0700178
Michael Jurka6e27f642013-12-10 13:40:30 +0100179 public void recreateDb() {
180 LauncherAppState app = LauncherAppState.getInstance();
181 app.recreateWidgetPreviewDb();
182 mDb = app.getWidgetPreviewCacheDb();
183 }
Michael Jurka3f4e0702013-02-05 11:21:28 +0100184
185 public void setPreviewSize(int previewWidth, int previewHeight,
186 PagedViewCellLayout widgetSpacingLayout) {
187 mPreviewBitmapWidth = previewWidth;
188 mPreviewBitmapHeight = previewHeight;
189 mSize = previewWidth + "x" + previewHeight;
190 mWidgetSpacingLayout = widgetSpacingLayout;
Michael Jurka05713af2013-01-23 12:39:24 +0100191 }
192
193 public Bitmap getPreview(final Object o) {
Michael Jurkaeb1bb922013-09-26 11:29:01 -0700194 final String name = getObjectName(o);
195 final String packageName = getObjectPackage(o);
Michael Jurka05713af2013-01-23 12:39:24 +0100196 // check if the package is valid
Michael Jurka05713af2013-01-23 12:39:24 +0100197 synchronized(sInvalidPackages) {
Adrian Roos5d2704f2014-03-18 23:09:12 +0100198 boolean packageValid = !sInvalidPackages.contains(packageName);
199 if (!packageValid) {
200 return null;
201 }
Michael Jurka05713af2013-01-23 12:39:24 +0100202 }
Adrian Roos5d2704f2014-03-18 23:09:12 +0100203 synchronized(mLoadedPreviews) {
204 // check if it exists in our existing cache
205 if (mLoadedPreviews.containsKey(name)) {
206 WeakReference<Bitmap> bitmapReference = mLoadedPreviews.get(name);
207 Bitmap bitmap = bitmapReference.get();
208 if (bitmap != null) {
209 return bitmap;
Michael Jurka05713af2013-01-23 12:39:24 +0100210 }
211 }
212 }
213
214 Bitmap unusedBitmap = null;
Michael Jurka3f4e0702013-02-05 11:21:28 +0100215 synchronized(mUnusedBitmaps) {
Michael Jurka05713af2013-01-23 12:39:24 +0100216 // not in cache; we need to load it from the db
Adrian Roos5d2704f2014-03-18 23:09:12 +0100217 while (unusedBitmap == null && mUnusedBitmaps.size() > 0) {
218 Bitmap candidate = mUnusedBitmaps.remove(0).get();
219 if (candidate != null && candidate.isMutable() &&
220 candidate.getWidth() == mPreviewBitmapWidth &&
221 candidate.getHeight() == mPreviewBitmapHeight) {
222 unusedBitmap = candidate;
223 }
Michael Jurka05713af2013-01-23 12:39:24 +0100224 }
225 if (unusedBitmap != null) {
226 final Canvas c = mCachedAppWidgetPreviewCanvas.get();
227 c.setBitmap(unusedBitmap);
228 c.drawColor(0, PorterDuff.Mode.CLEAR);
229 c.setBitmap(null);
230 }
231 }
232
233 if (unusedBitmap == null) {
Michael Jurka3f4e0702013-02-05 11:21:28 +0100234 unusedBitmap = Bitmap.createBitmap(mPreviewBitmapWidth, mPreviewBitmapHeight,
Michael Jurka05713af2013-01-23 12:39:24 +0100235 Bitmap.Config.ARGB_8888);
236 }
Adrian Roos5d2704f2014-03-18 23:09:12 +0100237 Bitmap preview = readFromDb(name, unusedBitmap);
Michael Jurka05713af2013-01-23 12:39:24 +0100238
239 if (preview != null) {
Michael Jurka3f4e0702013-02-05 11:21:28 +0100240 synchronized(mLoadedPreviews) {
241 mLoadedPreviews.put(name, new WeakReference<Bitmap>(preview));
Michael Jurka05713af2013-01-23 12:39:24 +0100242 }
243 return preview;
244 } else {
245 // it's not in the db... we need to generate it
246 final Bitmap generatedPreview = generatePreview(o, unusedBitmap);
247 preview = generatedPreview;
248 if (preview != unusedBitmap) {
249 throw new RuntimeException("generatePreview is not recycling the bitmap " + o);
250 }
251
Michael Jurka3f4e0702013-02-05 11:21:28 +0100252 synchronized(mLoadedPreviews) {
253 mLoadedPreviews.put(name, new WeakReference<Bitmap>(preview));
Michael Jurka05713af2013-01-23 12:39:24 +0100254 }
255
256 // write to db on a thread pool... this can be done lazily and improves the performance
257 // of the first time widget previews are loaded
258 new AsyncTask<Void, Void, Void>() {
259 public Void doInBackground(Void ... args) {
260 writeToDb(o, generatedPreview);
261 return null;
262 }
263 }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
264
265 return preview;
266 }
267 }
268
Michael Jurkaee8e99f2013-02-07 13:27:06 +0100269 public void recycleBitmap(Object o, Bitmap bitmapToRecycle) {
Michael Jurka05713af2013-01-23 12:39:24 +0100270 String name = getObjectName(o);
Michael Jurka5140cfa2013-02-15 14:50:15 +0100271 synchronized (mLoadedPreviews) {
272 if (mLoadedPreviews.containsKey(name)) {
Michael Jurka3f4e0702013-02-05 11:21:28 +0100273 Bitmap b = mLoadedPreviews.get(name).get();
Michael Jurkaee8e99f2013-02-07 13:27:06 +0100274 if (b == bitmapToRecycle) {
Michael Jurka3f4e0702013-02-05 11:21:28 +0100275 mLoadedPreviews.remove(name);
Michael Jurkaee8e99f2013-02-07 13:27:06 +0100276 if (bitmapToRecycle.isMutable()) {
Michael Jurka5140cfa2013-02-15 14:50:15 +0100277 synchronized (mUnusedBitmaps) {
278 mUnusedBitmaps.add(new SoftReference<Bitmap>(b));
279 }
Michael Jurka05713af2013-01-23 12:39:24 +0100280 }
281 } else {
282 throw new RuntimeException("Bitmap passed in doesn't match up");
283 }
284 }
285 }
286 }
287
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100288 static class CacheDb extends SQLiteOpenHelper {
Michael Jurkae5919c52013-03-06 17:30:10 +0100289 final static int DB_VERSION = 2;
Michael Jurka05713af2013-01-23 12:39:24 +0100290 final static String TABLE_NAME = "shortcut_and_widget_previews";
291 final static String COLUMN_NAME = "name";
292 final static String COLUMN_SIZE = "size";
293 final static String COLUMN_PREVIEW_BITMAP = "preview_bitmap";
294 Context mContext;
295
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100296 public CacheDb(Context context) {
Helena Josol4fbbb3e2014-10-06 16:06:46 +0100297 super(context, new File(context.getCacheDir(),
298 LauncherFiles.WIDGET_PREVIEWS_DB).getPath(), null, DB_VERSION);
Michael Jurka05713af2013-01-23 12:39:24 +0100299 // Store the context for later use
300 mContext = context;
301 }
302
303 @Override
304 public void onCreate(SQLiteDatabase database) {
Michael Jurka32b7a092013-02-07 20:06:49 +0100305 database.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" +
Michael Jurka05713af2013-01-23 12:39:24 +0100306 COLUMN_NAME + " TEXT NOT NULL, " +
307 COLUMN_SIZE + " TEXT NOT NULL, " +
308 COLUMN_PREVIEW_BITMAP + " BLOB NOT NULL, " +
309 "PRIMARY KEY (" + COLUMN_NAME + ", " + COLUMN_SIZE + ") " +
Michael Jurka32b7a092013-02-07 20:06:49 +0100310 ");");
Michael Jurka05713af2013-01-23 12:39:24 +0100311 }
312
313 @Override
314 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Michael Jurkae5919c52013-03-06 17:30:10 +0100315 if (oldVersion != newVersion) {
316 // Delete all the records; they'll be repopulated as this is a cache
317 db.execSQL("DELETE FROM " + TABLE_NAME);
318 }
Michael Jurka05713af2013-01-23 12:39:24 +0100319 }
320 }
321
322 private static final String WIDGET_PREFIX = "Widget:";
323 private static final String SHORTCUT_PREFIX = "Shortcut:";
324
325 private static String getObjectName(Object o) {
326 // should cache the string builder
327 StringBuilder sb = new StringBuilder();
328 String output;
329 if (o instanceof AppWidgetProviderInfo) {
330 sb.append(WIDGET_PREFIX);
Sunny Goyalffe83f12014-08-14 17:39:34 -0700331 sb.append(((AppWidgetProviderInfo) o).toString());
Michael Jurka05713af2013-01-23 12:39:24 +0100332 output = sb.toString();
333 sb.setLength(0);
334 } else {
335 sb.append(SHORTCUT_PREFIX);
Michael Jurka05713af2013-01-23 12:39:24 +0100336 ResolveInfo info = (ResolveInfo) o;
337 sb.append(new ComponentName(info.activityInfo.packageName,
338 info.activityInfo.name).flattenToString());
339 output = sb.toString();
340 sb.setLength(0);
341 }
342 return output;
343 }
344
345 private String getObjectPackage(Object o) {
346 if (o instanceof AppWidgetProviderInfo) {
347 return ((AppWidgetProviderInfo) o).provider.getPackageName();
348 } else {
349 ResolveInfo info = (ResolveInfo) o;
350 return info.activityInfo.packageName;
351 }
352 }
353
354 private void writeToDb(Object o, Bitmap preview) {
355 String name = getObjectName(o);
356 SQLiteDatabase db = mDb.getWritableDatabase();
357 ContentValues values = new ContentValues();
358
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100359 values.put(CacheDb.COLUMN_NAME, name);
Michael Jurka05713af2013-01-23 12:39:24 +0100360 ByteArrayOutputStream stream = new ByteArrayOutputStream();
361 preview.compress(Bitmap.CompressFormat.PNG, 100, stream);
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100362 values.put(CacheDb.COLUMN_PREVIEW_BITMAP, stream.toByteArray());
363 values.put(CacheDb.COLUMN_SIZE, mSize);
Michael Jurka6e27f642013-12-10 13:40:30 +0100364 try {
365 db.insert(CacheDb.TABLE_NAME, null, values);
366 } catch (SQLiteDiskIOException e) {
367 recreateDb();
Adrian Roos1f375ab2014-04-28 18:26:38 +0200368 } catch (SQLiteCantOpenDatabaseException e) {
369 dumpOpenFiles();
370 throw e;
Michael Jurka6e27f642013-12-10 13:40:30 +0100371 }
Michael Jurka05713af2013-01-23 12:39:24 +0100372 }
373
Michael Jurka8ff02ca2013-11-01 14:19:27 +0100374 private void clearDb() {
375 SQLiteDatabase db = mDb.getWritableDatabase();
376 // Delete everything
Michael Jurka6e27f642013-12-10 13:40:30 +0100377 try {
378 db.delete(CacheDb.TABLE_NAME, null, null);
379 } catch (SQLiteDiskIOException e) {
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 Jurka8ff02ca2013-11-01 14:19:27 +0100384 }
385
Michael Jurkaeb1bb922013-09-26 11:29:01 -0700386 public static void removePackageFromDb(final CacheDb cacheDb, final String packageName) {
Michael Jurka05713af2013-01-23 12:39:24 +0100387 synchronized(sInvalidPackages) {
388 sInvalidPackages.add(packageName);
389 }
390 new AsyncTask<Void, Void, Void>() {
391 public Void doInBackground(Void ... args) {
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100392 SQLiteDatabase db = cacheDb.getWritableDatabase();
Michael Jurka6e27f642013-12-10 13:40:30 +0100393 try {
394 db.delete(CacheDb.TABLE_NAME,
395 CacheDb.COLUMN_NAME + " LIKE ? OR " +
396 CacheDb.COLUMN_NAME + " LIKE ?", // SELECT query
397 new String[] {
398 WIDGET_PREFIX + packageName + "/%",
399 SHORTCUT_PREFIX + packageName + "/%"
400 } // args to SELECT query
401 );
402 } catch (SQLiteDiskIOException e) {
Adrian Roos1f375ab2014-04-28 18:26:38 +0200403 } catch (SQLiteCantOpenDatabaseException e) {
404 dumpOpenFiles();
405 throw e;
Michael Jurka6e27f642013-12-10 13:40:30 +0100406 }
Michael Jurka05713af2013-01-23 12:39:24 +0100407 synchronized(sInvalidPackages) {
408 sInvalidPackages.remove(packageName);
409 }
410 return null;
411 }
412 }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
413 }
414
Sunny Goyalffe83f12014-08-14 17:39:34 -0700415 private static void removeItemFromDb(final CacheDb cacheDb, final String objectName) {
Michael Jurkaeb1bb922013-09-26 11:29:01 -0700416 new AsyncTask<Void, Void, Void>() {
417 public Void doInBackground(Void ... args) {
418 SQLiteDatabase db = cacheDb.getWritableDatabase();
Michael Jurka6e27f642013-12-10 13:40:30 +0100419 try {
420 db.delete(CacheDb.TABLE_NAME,
421 CacheDb.COLUMN_NAME + " = ? ", // SELECT query
422 new String[] { objectName }); // args to SELECT query
423 } catch (SQLiteDiskIOException e) {
Adrian Roos1f375ab2014-04-28 18:26:38 +0200424 } catch (SQLiteCantOpenDatabaseException e) {
425 dumpOpenFiles();
426 throw e;
Michael Jurka6e27f642013-12-10 13:40:30 +0100427 }
Michael Jurkaeb1bb922013-09-26 11:29:01 -0700428 return null;
429 }
430 }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
431 }
432
Michael Jurka05713af2013-01-23 12:39:24 +0100433 private Bitmap readFromDb(String name, Bitmap b) {
434 if (mCachedSelectQuery == null) {
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100435 mCachedSelectQuery = CacheDb.COLUMN_NAME + " = ? AND " +
436 CacheDb.COLUMN_SIZE + " = ?";
Michael Jurka05713af2013-01-23 12:39:24 +0100437 }
438 SQLiteDatabase db = mDb.getReadableDatabase();
Michael Jurka6e27f642013-12-10 13:40:30 +0100439 Cursor result;
440 try {
441 result = db.query(CacheDb.TABLE_NAME,
442 new String[] { CacheDb.COLUMN_PREVIEW_BITMAP }, // cols to return
443 mCachedSelectQuery, // select query
444 new String[] { name, mSize }, // args to select query
445 null,
446 null,
447 null,
448 null);
449 } catch (SQLiteDiskIOException e) {
450 recreateDb();
451 return null;
Adrian Roos1f375ab2014-04-28 18:26:38 +0200452 } catch (SQLiteCantOpenDatabaseException e) {
453 dumpOpenFiles();
454 throw e;
Michael Jurka6e27f642013-12-10 13:40:30 +0100455 }
Michael Jurka05713af2013-01-23 12:39:24 +0100456 if (result.getCount() > 0) {
457 result.moveToFirst();
458 byte[] blob = result.getBlob(0);
459 result.close();
460 final BitmapFactory.Options opts = mCachedBitmapFactoryOptions.get();
461 opts.inBitmap = b;
462 opts.inSampleSize = 1;
Michael Jurkaeb1bb922013-09-26 11:29:01 -0700463 try {
464 return BitmapFactory.decodeByteArray(blob, 0, blob.length, opts);
465 } catch (IllegalArgumentException e) {
466 removeItemFromDb(mDb, name);
467 return null;
468 }
Michael Jurka05713af2013-01-23 12:39:24 +0100469 } else {
470 result.close();
471 return null;
472 }
473 }
474
Sunny Goyalffe83f12014-08-14 17:39:34 -0700475 private Bitmap generatePreview(Object info, Bitmap preview) {
Michael Jurka05713af2013-01-23 12:39:24 +0100476 if (preview != null &&
Michael Jurka3f4e0702013-02-05 11:21:28 +0100477 (preview.getWidth() != mPreviewBitmapWidth ||
478 preview.getHeight() != mPreviewBitmapHeight)) {
Michael Jurka05713af2013-01-23 12:39:24 +0100479 throw new RuntimeException("Improperly sized bitmap passed as argument");
480 }
Adam Cohen59400422014-03-05 18:07:04 -0800481 if (info instanceof LauncherAppWidgetProviderInfo) {
482 return generateWidgetPreview((LauncherAppWidgetProviderInfo) info, preview);
Michael Jurka05713af2013-01-23 12:39:24 +0100483 } else {
484 return generateShortcutPreview(
Michael Jurka3f4e0702013-02-05 11:21:28 +0100485 (ResolveInfo) info, mPreviewBitmapWidth, mPreviewBitmapHeight, preview);
Michael Jurka05713af2013-01-23 12:39:24 +0100486 }
487 }
488
Adam Cohen59400422014-03-05 18:07:04 -0800489 public Bitmap generateWidgetPreview(LauncherAppWidgetProviderInfo info, Bitmap preview) {
490 int maxWidth = maxWidthForWidgetPreview(info.spanX);
491 int maxHeight = maxHeightForWidgetPreview(info.spanY);
492 return generateWidgetPreview(info, info.spanX, info.spanY, maxWidth,
493 maxHeight, preview, null);
Michael Jurka05713af2013-01-23 12:39:24 +0100494 }
495
496 public int maxWidthForWidgetPreview(int spanX) {
Michael Jurka3f4e0702013-02-05 11:21:28 +0100497 return Math.min(mPreviewBitmapWidth,
Michael Jurka05713af2013-01-23 12:39:24 +0100498 mWidgetSpacingLayout.estimateCellWidth(spanX));
499 }
500
501 public int maxHeightForWidgetPreview(int spanY) {
Michael Jurka3f4e0702013-02-05 11:21:28 +0100502 return Math.min(mPreviewBitmapHeight,
Michael Jurka05713af2013-01-23 12:39:24 +0100503 mWidgetSpacingLayout.estimateCellHeight(spanY));
504 }
505
Adam Cohen59400422014-03-05 18:07:04 -0800506 public Bitmap generateWidgetPreview(LauncherAppWidgetProviderInfo info, int cellHSpan, int cellVSpan,
Sunny Goyalffe83f12014-08-14 17:39:34 -0700507 int maxPreviewWidth, int maxPreviewHeight, Bitmap preview, int[] preScaledWidthOut) {
Michael Jurka05713af2013-01-23 12:39:24 +0100508 // Load the preview image if possible
Michael Jurka05713af2013-01-23 12:39:24 +0100509 if (maxPreviewWidth < 0) maxPreviewWidth = Integer.MAX_VALUE;
510 if (maxPreviewHeight < 0) maxPreviewHeight = Integer.MAX_VALUE;
511
512 Drawable drawable = null;
Sunny Goyalffe83f12014-08-14 17:39:34 -0700513 if (info.previewImage != 0) {
514 drawable = mManager.loadPreview(info);
Adrian Roosfa9ffc22014-05-12 15:59:59 +0200515 if (drawable != null) {
516 drawable = mutateOnMainThread(drawable);
517 } else {
Michael Jurka05713af2013-01-23 12:39:24 +0100518 Log.w(TAG, "Can't load widget preview drawable 0x" +
Sunny Goyalffe83f12014-08-14 17:39:34 -0700519 Integer.toHexString(info.previewImage) + " for provider: " + info.provider);
Michael Jurka05713af2013-01-23 12:39:24 +0100520 }
521 }
522
523 int previewWidth;
524 int previewHeight;
525 Bitmap defaultPreview = null;
526 boolean widgetPreviewExists = (drawable != null);
527 if (widgetPreviewExists) {
528 previewWidth = drawable.getIntrinsicWidth();
529 previewHeight = drawable.getIntrinsicHeight();
530 } else {
531 // Generate a preview image if we couldn't load one
532 if (cellHSpan < 1) cellHSpan = 1;
533 if (cellVSpan < 1) cellVSpan = 1;
534
Adrian Roos65d60e22014-04-15 21:07:49 +0200535 // This Drawable is not directly drawn, so there's no need to mutate it.
Michael Jurka05713af2013-01-23 12:39:24 +0100536 BitmapDrawable previewDrawable = (BitmapDrawable) mContext.getResources()
Winson Chung6706ed82013-10-02 11:00:15 -0700537 .getDrawable(R.drawable.widget_tile);
Michael Jurka05713af2013-01-23 12:39:24 +0100538 final int previewDrawableWidth = previewDrawable
539 .getIntrinsicWidth();
540 final int previewDrawableHeight = previewDrawable
541 .getIntrinsicHeight();
Winson Chung45cab392013-10-02 17:45:32 -0700542 previewWidth = previewDrawableWidth * cellHSpan;
Michael Jurka05713af2013-01-23 12:39:24 +0100543 previewHeight = previewDrawableHeight * cellVSpan;
544
Adrian Roos5d2704f2014-03-18 23:09:12 +0100545 defaultPreview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
Michael Jurka05713af2013-01-23 12:39:24 +0100546 final Canvas c = mCachedAppWidgetPreviewCanvas.get();
547 c.setBitmap(defaultPreview);
Adrian Roosfa4c7992014-03-19 15:58:14 +0100548 Paint p = mDefaultAppWidgetPreviewPaint.get();
549 if (p == null) {
550 p = new Paint();
551 p.setShader(new BitmapShader(previewDrawable.getBitmap(),
552 Shader.TileMode.REPEAT, Shader.TileMode.REPEAT));
553 mDefaultAppWidgetPreviewPaint.set(p);
554 }
555 final Rect dest = mCachedAppWidgetPreviewDestRect.get();
556 dest.set(0, 0, previewWidth, previewHeight);
557 c.drawRect(dest, p);
Michael Jurka05713af2013-01-23 12:39:24 +0100558 c.setBitmap(null);
559
560 // Draw the icon in the top left corner
Sunny Goyalffe83f12014-08-14 17:39:34 -0700561 int minOffset = (int) (mAppIconSize * WIDGET_PREVIEW_ICON_PADDING_PERCENTAGE);
Michael Jurka05713af2013-01-23 12:39:24 +0100562 int smallestSide = Math.min(previewWidth, previewHeight);
563 float iconScale = Math.min((float) smallestSide
564 / (mAppIconSize + 2 * minOffset), 1f);
565
566 try {
Sunny Goyalffe83f12014-08-14 17:39:34 -0700567 Drawable icon = mManager.loadIcon(info, mIconCache);
Michael Jurka05713af2013-01-23 12:39:24 +0100568 if (icon != null) {
Sunny Goyalffe83f12014-08-14 17:39:34 -0700569 int hoffset = (int) ((previewDrawableWidth - mAppIconSize * iconScale) / 2);
570 int yoffset = (int) ((previewDrawableHeight - mAppIconSize * iconScale) / 2);
Adrian Roosfa9ffc22014-05-12 15:59:59 +0200571 icon = mutateOnMainThread(icon);
Michael Jurka05713af2013-01-23 12:39:24 +0100572 renderDrawableToBitmap(icon, defaultPreview, hoffset,
573 yoffset, (int) (mAppIconSize * iconScale),
574 (int) (mAppIconSize * iconScale));
575 }
576 } catch (Resources.NotFoundException e) {
577 }
578 }
579
580 // Scale to fit width only - let the widget preview be clipped in the
581 // vertical dimension
582 float scale = 1f;
583 if (preScaledWidthOut != null) {
584 preScaledWidthOut[0] = previewWidth;
585 }
586 if (previewWidth > maxPreviewWidth) {
587 scale = maxPreviewWidth / (float) previewWidth;
588 }
589 if (scale != 1f) {
590 previewWidth = (int) (scale * previewWidth);
591 previewHeight = (int) (scale * previewHeight);
592 }
593
594 // If a bitmap is passed in, we use it; otherwise, we create a bitmap of the right size
595 if (preview == null) {
596 preview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
597 }
598
599 // Draw the scaled preview into the final bitmap
600 int x = (preview.getWidth() - previewWidth) / 2;
601 if (widgetPreviewExists) {
602 renderDrawableToBitmap(drawable, preview, x, 0, previewWidth,
603 previewHeight);
604 } else {
605 final Canvas c = mCachedAppWidgetPreviewCanvas.get();
606 final Rect src = mCachedAppWidgetPreviewSrcRect.get();
607 final Rect dest = mCachedAppWidgetPreviewDestRect.get();
608 c.setBitmap(preview);
609 src.set(0, 0, defaultPreview.getWidth(), defaultPreview.getHeight());
Michael Jurkae5919c52013-03-06 17:30:10 +0100610 dest.set(x, 0, x + previewWidth, previewHeight);
Michael Jurka05713af2013-01-23 12:39:24 +0100611
612 Paint p = mCachedAppWidgetPreviewPaint.get();
613 if (p == null) {
614 p = new Paint();
615 p.setFilterBitmap(true);
616 mCachedAppWidgetPreviewPaint.set(p);
617 }
618 c.drawBitmap(defaultPreview, src, dest, p);
619 c.setBitmap(null);
620 }
Sunny Goyalffe83f12014-08-14 17:39:34 -0700621 return mManager.getBadgeBitmap(info, preview);
Michael Jurka05713af2013-01-23 12:39:24 +0100622 }
623
624 private Bitmap generateShortcutPreview(
625 ResolveInfo info, int maxWidth, int maxHeight, Bitmap preview) {
626 Bitmap tempBitmap = mCachedShortcutPreviewBitmap.get();
627 final Canvas c = mCachedShortcutPreviewCanvas.get();
628 if (tempBitmap == null ||
629 tempBitmap.getWidth() != maxWidth ||
630 tempBitmap.getHeight() != maxHeight) {
631 tempBitmap = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
632 mCachedShortcutPreviewBitmap.set(tempBitmap);
633 } else {
634 c.setBitmap(tempBitmap);
635 c.drawColor(0, PorterDuff.Mode.CLEAR);
636 c.setBitmap(null);
637 }
638 // Render the icon
Sunny Goyal736f5af2014-10-16 14:07:29 -0700639 Drawable icon = mutateOnMainThread(mIconCache.getFullResIcon(info.activityInfo));
Michael Jurka05713af2013-01-23 12:39:24 +0100640
641 int paddingTop = mContext.
642 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_top);
643 int paddingLeft = mContext.
644 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_left);
645 int paddingRight = mContext.
646 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_right);
647
648 int scaledIconWidth = (maxWidth - paddingLeft - paddingRight);
649
650 renderDrawableToBitmap(
651 icon, tempBitmap, paddingLeft, paddingTop, scaledIconWidth, scaledIconWidth);
652
653 if (preview != null &&
654 (preview.getWidth() != maxWidth || preview.getHeight() != maxHeight)) {
655 throw new RuntimeException("Improperly sized bitmap passed as argument");
656 } else if (preview == null) {
657 preview = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
658 }
659
660 c.setBitmap(preview);
661 // Draw a desaturated/scaled version of the icon in the background as a watermark
662 Paint p = mCachedShortcutPreviewPaint.get();
663 if (p == null) {
664 p = new Paint();
665 ColorMatrix colorMatrix = new ColorMatrix();
666 colorMatrix.setSaturation(0);
667 p.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
668 p.setAlpha((int) (255 * 0.06f));
669 mCachedShortcutPreviewPaint.set(p);
670 }
671 c.drawBitmap(tempBitmap, 0, 0, p);
672 c.setBitmap(null);
673
674 renderDrawableToBitmap(icon, preview, 0, 0, mAppIconSize, mAppIconSize);
675
676 return preview;
677 }
678
Michael Jurka05713af2013-01-23 12:39:24 +0100679 private static void renderDrawableToBitmap(
Sunny Goyalffe83f12014-08-14 17:39:34 -0700680 Drawable d, Bitmap bitmap, int x, int y, int w, int h) {
Michael Jurka05713af2013-01-23 12:39:24 +0100681 if (bitmap != null) {
682 Canvas c = new Canvas(bitmap);
Michael Jurka05713af2013-01-23 12:39:24 +0100683 Rect oldBounds = d.copyBounds();
684 d.setBounds(x, y, x + w, y + h);
685 d.draw(c);
686 d.setBounds(oldBounds); // Restore the bounds
687 c.setBitmap(null);
688 }
689 }
690
Adrian Roos65d60e22014-04-15 21:07:49 +0200691 private Drawable mutateOnMainThread(final Drawable drawable) {
692 try {
693 return mMainThreadExecutor.submit(new Callable<Drawable>() {
694 @Override
695 public Drawable call() throws Exception {
696 return drawable.mutate();
697 }
698 }).get();
699 } catch (InterruptedException e) {
700 Thread.currentThread().interrupt();
701 throw new RuntimeException(e);
702 } catch (ExecutionException e) {
703 throw new RuntimeException(e);
704 }
705 }
Adrian Roos1f375ab2014-04-28 18:26:38 +0200706
707 private static final int MAX_OPEN_FILES = 1024;
708 private static final int SAMPLE_RATE = 23;
709 /**
710 * Dumps all files that are open in this process without allocating a file descriptor.
711 */
712 private static void dumpOpenFiles() {
713 try {
714 Log.i(TAG, "DUMP OF OPEN FILES (sample rate: 1 every " + SAMPLE_RATE + "):");
715 final String TYPE_APK = "apk";
716 final String TYPE_JAR = "jar";
717 final String TYPE_PIPE = "pipe";
718 final String TYPE_SOCKET = "socket";
719 final String TYPE_DB = "db";
720 final String TYPE_ANON_INODE = "anon_inode";
721 final String TYPE_DEV = "dev";
722 final String TYPE_NON_FS = "non-fs";
723 final String TYPE_OTHER = "other";
724 List<String> types = Arrays.asList(TYPE_APK, TYPE_JAR, TYPE_PIPE, TYPE_SOCKET, TYPE_DB,
725 TYPE_ANON_INODE, TYPE_DEV, TYPE_NON_FS, TYPE_OTHER);
726 int[] count = new int[types.size()];
727 int[] duplicates = new int[types.size()];
728 HashSet<String> files = new HashSet<String>();
729 int total = 0;
730 for (int i = 0; i < MAX_OPEN_FILES; i++) {
731 // This is a gigantic hack but unfortunately the only way to resolve an fd
732 // to a file name. Note that we have to loop over all possible fds because
733 // reading the directory would require allocating a new fd. The kernel is
734 // currently implemented such that no fd is larger then the current rlimit,
735 // which is why it's safe to loop over them in such a way.
736 String fd = "/proc/self/fd/" + i;
737 try {
738 // getCanonicalPath() uses readlink behind the scene which doesn't require
739 // a file descriptor.
740 String resolved = new File(fd).getCanonicalPath();
741 int type = types.indexOf(TYPE_OTHER);
742 if (resolved.startsWith("/dev/")) {
743 type = types.indexOf(TYPE_DEV);
744 } else if (resolved.endsWith(".apk")) {
745 type = types.indexOf(TYPE_APK);
746 } else if (resolved.endsWith(".jar")) {
747 type = types.indexOf(TYPE_JAR);
748 } else if (resolved.contains("/fd/pipe:")) {
749 type = types.indexOf(TYPE_PIPE);
750 } else if (resolved.contains("/fd/socket:")) {
751 type = types.indexOf(TYPE_SOCKET);
752 } else if (resolved.contains("/fd/anon_inode:")) {
753 type = types.indexOf(TYPE_ANON_INODE);
754 } else if (resolved.endsWith(".db") || resolved.contains("/databases/")) {
755 type = types.indexOf(TYPE_DB);
756 } else if (resolved.startsWith("/proc/") && resolved.contains("/fd/")) {
757 // Those are the files that don't point anywhere on the file system.
758 // getCanonicalPath() wrongly interprets these as relative symlinks and
759 // resolves them within /proc/<pid>/fd/.
760 type = types.indexOf(TYPE_NON_FS);
761 }
762 count[type]++;
763 total++;
764 if (files.contains(resolved)) {
765 duplicates[type]++;
766 }
767 files.add(resolved);
768 if (total % SAMPLE_RATE == 0) {
769 Log.i(TAG, " fd " + i + ": " + resolved
770 + " (" + types.get(type) + ")");
771 }
772 } catch (IOException e) {
773 // Ignoring exceptions for non-existing file descriptors.
774 }
775 }
776 for (int i = 0; i < types.size(); i++) {
777 Log.i(TAG, String.format("Open %10s files: %4d total, %4d duplicates",
778 types.get(i), count[i], duplicates[i]));
779 }
780 } catch (Throwable t) {
781 // Catch everything. This is called from an exception handler that we shouldn't upset.
782 Log.e(TAG, "Unable to log open files.", t);
783 }
784 }
Michael Jurka05713af2013-01-23 12:39:24 +0100785}