blob: 5aa71902789d93a9965bdef81d904682aff9f564 [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
133 private final HashMap<String, WeakReference<Bitmap>> mLoadedPreviews = new HashMap<>();
134 private final ArrayList<SoftReference<Bitmap>> mUnusedBitmaps = new ArrayList<>();
135
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 DB_NAME = "widgetpreviews.db";
291 final static String TABLE_NAME = "shortcut_and_widget_previews";
292 final static String COLUMN_NAME = "name";
293 final static String COLUMN_SIZE = "size";
294 final static String COLUMN_PREVIEW_BITMAP = "preview_bitmap";
295 Context mContext;
296
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100297 public CacheDb(Context context) {
Michael Jurka05713af2013-01-23 12:39:24 +0100298 super(context, new File(context.getCacheDir(), DB_NAME).getPath(), null, DB_VERSION);
299 // 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);
336
337 ResolveInfo info = (ResolveInfo) o;
338 sb.append(new ComponentName(info.activityInfo.packageName,
339 info.activityInfo.name).flattenToString());
340 output = sb.toString();
341 sb.setLength(0);
342 }
343 return output;
344 }
345
346 private String getObjectPackage(Object o) {
347 if (o instanceof AppWidgetProviderInfo) {
348 return ((AppWidgetProviderInfo) o).provider.getPackageName();
349 } else {
350 ResolveInfo info = (ResolveInfo) o;
351 return info.activityInfo.packageName;
352 }
353 }
354
355 private void writeToDb(Object o, Bitmap preview) {
356 String name = getObjectName(o);
357 SQLiteDatabase db = mDb.getWritableDatabase();
358 ContentValues values = new ContentValues();
359
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100360 values.put(CacheDb.COLUMN_NAME, name);
Michael Jurka05713af2013-01-23 12:39:24 +0100361 ByteArrayOutputStream stream = new ByteArrayOutputStream();
362 preview.compress(Bitmap.CompressFormat.PNG, 100, stream);
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100363 values.put(CacheDb.COLUMN_PREVIEW_BITMAP, stream.toByteArray());
364 values.put(CacheDb.COLUMN_SIZE, mSize);
Michael Jurka6e27f642013-12-10 13:40:30 +0100365 try {
366 db.insert(CacheDb.TABLE_NAME, null, values);
367 } catch (SQLiteDiskIOException e) {
368 recreateDb();
Adrian Roos1f375ab2014-04-28 18:26:38 +0200369 } catch (SQLiteCantOpenDatabaseException e) {
370 dumpOpenFiles();
371 throw e;
Michael Jurka6e27f642013-12-10 13:40:30 +0100372 }
Michael Jurka05713af2013-01-23 12:39:24 +0100373 }
374
Michael Jurka8ff02ca2013-11-01 14:19:27 +0100375 private void clearDb() {
376 SQLiteDatabase db = mDb.getWritableDatabase();
377 // Delete everything
Michael Jurka6e27f642013-12-10 13:40:30 +0100378 try {
379 db.delete(CacheDb.TABLE_NAME, null, null);
380 } catch (SQLiteDiskIOException e) {
Adrian Roos1f375ab2014-04-28 18:26:38 +0200381 } catch (SQLiteCantOpenDatabaseException e) {
382 dumpOpenFiles();
383 throw e;
Michael Jurka6e27f642013-12-10 13:40:30 +0100384 }
Michael Jurka8ff02ca2013-11-01 14:19:27 +0100385 }
386
Michael Jurkaeb1bb922013-09-26 11:29:01 -0700387 public static void removePackageFromDb(final CacheDb cacheDb, final String packageName) {
Michael Jurka05713af2013-01-23 12:39:24 +0100388 synchronized(sInvalidPackages) {
389 sInvalidPackages.add(packageName);
390 }
391 new AsyncTask<Void, Void, Void>() {
392 public Void doInBackground(Void ... args) {
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100393 SQLiteDatabase db = cacheDb.getWritableDatabase();
Michael Jurka6e27f642013-12-10 13:40:30 +0100394 try {
395 db.delete(CacheDb.TABLE_NAME,
396 CacheDb.COLUMN_NAME + " LIKE ? OR " +
397 CacheDb.COLUMN_NAME + " LIKE ?", // SELECT query
398 new String[] {
399 WIDGET_PREFIX + packageName + "/%",
400 SHORTCUT_PREFIX + packageName + "/%"
401 } // args to SELECT query
402 );
403 } catch (SQLiteDiskIOException e) {
Adrian Roos1f375ab2014-04-28 18:26:38 +0200404 } catch (SQLiteCantOpenDatabaseException e) {
405 dumpOpenFiles();
406 throw e;
Michael Jurka6e27f642013-12-10 13:40:30 +0100407 }
Michael Jurka05713af2013-01-23 12:39:24 +0100408 synchronized(sInvalidPackages) {
409 sInvalidPackages.remove(packageName);
410 }
411 return null;
412 }
413 }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
414 }
415
Sunny Goyalffe83f12014-08-14 17:39:34 -0700416 private static void removeItemFromDb(final CacheDb cacheDb, final String objectName) {
Michael Jurkaeb1bb922013-09-26 11:29:01 -0700417 new AsyncTask<Void, Void, Void>() {
418 public Void doInBackground(Void ... args) {
419 SQLiteDatabase db = cacheDb.getWritableDatabase();
Michael Jurka6e27f642013-12-10 13:40:30 +0100420 try {
421 db.delete(CacheDb.TABLE_NAME,
422 CacheDb.COLUMN_NAME + " = ? ", // SELECT query
423 new String[] { objectName }); // args to SELECT query
424 } catch (SQLiteDiskIOException e) {
Adrian Roos1f375ab2014-04-28 18:26:38 +0200425 } catch (SQLiteCantOpenDatabaseException e) {
426 dumpOpenFiles();
427 throw e;
Michael Jurka6e27f642013-12-10 13:40:30 +0100428 }
Michael Jurkaeb1bb922013-09-26 11:29:01 -0700429 return null;
430 }
431 }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
432 }
433
Michael Jurka05713af2013-01-23 12:39:24 +0100434 private Bitmap readFromDb(String name, Bitmap b) {
435 if (mCachedSelectQuery == null) {
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100436 mCachedSelectQuery = CacheDb.COLUMN_NAME + " = ? AND " +
437 CacheDb.COLUMN_SIZE + " = ?";
Michael Jurka05713af2013-01-23 12:39:24 +0100438 }
439 SQLiteDatabase db = mDb.getReadableDatabase();
Michael Jurka6e27f642013-12-10 13:40:30 +0100440 Cursor result;
441 try {
442 result = db.query(CacheDb.TABLE_NAME,
443 new String[] { CacheDb.COLUMN_PREVIEW_BITMAP }, // cols to return
444 mCachedSelectQuery, // select query
445 new String[] { name, mSize }, // args to select query
446 null,
447 null,
448 null,
449 null);
450 } catch (SQLiteDiskIOException e) {
451 recreateDb();
452 return null;
Adrian Roos1f375ab2014-04-28 18:26:38 +0200453 } catch (SQLiteCantOpenDatabaseException e) {
454 dumpOpenFiles();
455 throw e;
Michael Jurka6e27f642013-12-10 13:40:30 +0100456 }
Michael Jurka05713af2013-01-23 12:39:24 +0100457 if (result.getCount() > 0) {
458 result.moveToFirst();
459 byte[] blob = result.getBlob(0);
460 result.close();
461 final BitmapFactory.Options opts = mCachedBitmapFactoryOptions.get();
462 opts.inBitmap = b;
463 opts.inSampleSize = 1;
Michael Jurkaeb1bb922013-09-26 11:29:01 -0700464 try {
465 return BitmapFactory.decodeByteArray(blob, 0, blob.length, opts);
466 } catch (IllegalArgumentException e) {
467 removeItemFromDb(mDb, name);
468 return null;
469 }
Michael Jurka05713af2013-01-23 12:39:24 +0100470 } else {
471 result.close();
472 return null;
473 }
474 }
475
Sunny Goyalffe83f12014-08-14 17:39:34 -0700476 private Bitmap generatePreview(Object info, Bitmap preview) {
Michael Jurka05713af2013-01-23 12:39:24 +0100477 if (preview != null &&
Michael Jurka3f4e0702013-02-05 11:21:28 +0100478 (preview.getWidth() != mPreviewBitmapWidth ||
479 preview.getHeight() != mPreviewBitmapHeight)) {
Michael Jurka05713af2013-01-23 12:39:24 +0100480 throw new RuntimeException("Improperly sized bitmap passed as argument");
481 }
482 if (info instanceof AppWidgetProviderInfo) {
483 return generateWidgetPreview((AppWidgetProviderInfo) info, preview);
484 } else {
485 return generateShortcutPreview(
Michael Jurka3f4e0702013-02-05 11:21:28 +0100486 (ResolveInfo) info, mPreviewBitmapWidth, mPreviewBitmapHeight, preview);
Michael Jurka05713af2013-01-23 12:39:24 +0100487 }
488 }
489
490 public Bitmap generateWidgetPreview(AppWidgetProviderInfo info, Bitmap preview) {
Chris Wrenfd13c712013-09-27 15:45:19 -0400491 int[] cellSpans = Launcher.getSpanForWidget(mContext, info);
Michael Jurka05713af2013-01-23 12:39:24 +0100492 int maxWidth = maxWidthForWidgetPreview(cellSpans[0]);
493 int maxHeight = maxHeightForWidgetPreview(cellSpans[1]);
Sunny Goyalffe83f12014-08-14 17:39:34 -0700494 return generateWidgetPreview(info, cellSpans[0], cellSpans[1],
495 maxWidth, maxHeight, preview, null);
Michael Jurka05713af2013-01-23 12:39:24 +0100496 }
497
498 public int maxWidthForWidgetPreview(int spanX) {
Michael Jurka3f4e0702013-02-05 11:21:28 +0100499 return Math.min(mPreviewBitmapWidth,
Michael Jurka05713af2013-01-23 12:39:24 +0100500 mWidgetSpacingLayout.estimateCellWidth(spanX));
501 }
502
503 public int maxHeightForWidgetPreview(int spanY) {
Michael Jurka3f4e0702013-02-05 11:21:28 +0100504 return Math.min(mPreviewBitmapHeight,
Michael Jurka05713af2013-01-23 12:39:24 +0100505 mWidgetSpacingLayout.estimateCellHeight(spanY));
506 }
507
Sunny Goyalffe83f12014-08-14 17:39:34 -0700508 public Bitmap generateWidgetPreview(AppWidgetProviderInfo info, int cellHSpan, int cellVSpan,
509 int maxPreviewWidth, int maxPreviewHeight, Bitmap preview, int[] preScaledWidthOut) {
Michael Jurka05713af2013-01-23 12:39:24 +0100510 // Load the preview image if possible
Michael Jurka05713af2013-01-23 12:39:24 +0100511 if (maxPreviewWidth < 0) maxPreviewWidth = Integer.MAX_VALUE;
512 if (maxPreviewHeight < 0) maxPreviewHeight = Integer.MAX_VALUE;
513
514 Drawable drawable = null;
Sunny Goyalffe83f12014-08-14 17:39:34 -0700515 if (info.previewImage != 0) {
516 drawable = mManager.loadPreview(info);
Adrian Roosfa9ffc22014-05-12 15:59:59 +0200517 if (drawable != null) {
518 drawable = mutateOnMainThread(drawable);
519 } else {
Michael Jurka05713af2013-01-23 12:39:24 +0100520 Log.w(TAG, "Can't load widget preview drawable 0x" +
Sunny Goyalffe83f12014-08-14 17:39:34 -0700521 Integer.toHexString(info.previewImage) + " for provider: " + info.provider);
Michael Jurka05713af2013-01-23 12:39:24 +0100522 }
523 }
524
525 int previewWidth;
526 int previewHeight;
527 Bitmap defaultPreview = null;
528 boolean widgetPreviewExists = (drawable != null);
529 if (widgetPreviewExists) {
530 previewWidth = drawable.getIntrinsicWidth();
531 previewHeight = drawable.getIntrinsicHeight();
532 } else {
533 // Generate a preview image if we couldn't load one
534 if (cellHSpan < 1) cellHSpan = 1;
535 if (cellVSpan < 1) cellVSpan = 1;
536
Adrian Roos65d60e22014-04-15 21:07:49 +0200537 // This Drawable is not directly drawn, so there's no need to mutate it.
Michael Jurka05713af2013-01-23 12:39:24 +0100538 BitmapDrawable previewDrawable = (BitmapDrawable) mContext.getResources()
Winson Chung6706ed82013-10-02 11:00:15 -0700539 .getDrawable(R.drawable.widget_tile);
Michael Jurka05713af2013-01-23 12:39:24 +0100540 final int previewDrawableWidth = previewDrawable
541 .getIntrinsicWidth();
542 final int previewDrawableHeight = previewDrawable
543 .getIntrinsicHeight();
Winson Chung45cab392013-10-02 17:45:32 -0700544 previewWidth = previewDrawableWidth * cellHSpan;
Michael Jurka05713af2013-01-23 12:39:24 +0100545 previewHeight = previewDrawableHeight * cellVSpan;
546
Adrian Roos5d2704f2014-03-18 23:09:12 +0100547 defaultPreview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
Michael Jurka05713af2013-01-23 12:39:24 +0100548 final Canvas c = mCachedAppWidgetPreviewCanvas.get();
549 c.setBitmap(defaultPreview);
Adrian Roosfa4c7992014-03-19 15:58:14 +0100550 Paint p = mDefaultAppWidgetPreviewPaint.get();
551 if (p == null) {
552 p = new Paint();
553 p.setShader(new BitmapShader(previewDrawable.getBitmap(),
554 Shader.TileMode.REPEAT, Shader.TileMode.REPEAT));
555 mDefaultAppWidgetPreviewPaint.set(p);
556 }
557 final Rect dest = mCachedAppWidgetPreviewDestRect.get();
558 dest.set(0, 0, previewWidth, previewHeight);
559 c.drawRect(dest, p);
Michael Jurka05713af2013-01-23 12:39:24 +0100560 c.setBitmap(null);
561
562 // Draw the icon in the top left corner
Sunny Goyalffe83f12014-08-14 17:39:34 -0700563 int minOffset = (int) (mAppIconSize * WIDGET_PREVIEW_ICON_PADDING_PERCENTAGE);
Michael Jurka05713af2013-01-23 12:39:24 +0100564 int smallestSide = Math.min(previewWidth, previewHeight);
565 float iconScale = Math.min((float) smallestSide
566 / (mAppIconSize + 2 * minOffset), 1f);
567
568 try {
Sunny Goyalffe83f12014-08-14 17:39:34 -0700569 Drawable icon = mManager.loadIcon(info, mIconCache);
Michael Jurka05713af2013-01-23 12:39:24 +0100570 if (icon != null) {
Sunny Goyalffe83f12014-08-14 17:39:34 -0700571 int hoffset = (int) ((previewDrawableWidth - mAppIconSize * iconScale) / 2);
572 int yoffset = (int) ((previewDrawableHeight - mAppIconSize * iconScale) / 2);
Adrian Roosfa9ffc22014-05-12 15:59:59 +0200573 icon = mutateOnMainThread(icon);
Michael Jurka05713af2013-01-23 12:39:24 +0100574 renderDrawableToBitmap(icon, defaultPreview, hoffset,
575 yoffset, (int) (mAppIconSize * iconScale),
576 (int) (mAppIconSize * iconScale));
577 }
578 } catch (Resources.NotFoundException e) {
579 }
580 }
581
582 // Scale to fit width only - let the widget preview be clipped in the
583 // vertical dimension
584 float scale = 1f;
585 if (preScaledWidthOut != null) {
586 preScaledWidthOut[0] = previewWidth;
587 }
588 if (previewWidth > maxPreviewWidth) {
589 scale = maxPreviewWidth / (float) previewWidth;
590 }
591 if (scale != 1f) {
592 previewWidth = (int) (scale * previewWidth);
593 previewHeight = (int) (scale * previewHeight);
594 }
595
596 // If a bitmap is passed in, we use it; otherwise, we create a bitmap of the right size
597 if (preview == null) {
598 preview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
599 }
600
601 // Draw the scaled preview into the final bitmap
602 int x = (preview.getWidth() - previewWidth) / 2;
603 if (widgetPreviewExists) {
604 renderDrawableToBitmap(drawable, preview, x, 0, previewWidth,
605 previewHeight);
606 } else {
607 final Canvas c = mCachedAppWidgetPreviewCanvas.get();
608 final Rect src = mCachedAppWidgetPreviewSrcRect.get();
609 final Rect dest = mCachedAppWidgetPreviewDestRect.get();
610 c.setBitmap(preview);
611 src.set(0, 0, defaultPreview.getWidth(), defaultPreview.getHeight());
Michael Jurkae5919c52013-03-06 17:30:10 +0100612 dest.set(x, 0, x + previewWidth, previewHeight);
Michael Jurka05713af2013-01-23 12:39:24 +0100613
614 Paint p = mCachedAppWidgetPreviewPaint.get();
615 if (p == null) {
616 p = new Paint();
617 p.setFilterBitmap(true);
618 mCachedAppWidgetPreviewPaint.set(p);
619 }
620 c.drawBitmap(defaultPreview, src, dest, p);
621 c.setBitmap(null);
622 }
Sunny Goyalffe83f12014-08-14 17:39:34 -0700623 return mManager.getBadgeBitmap(info, preview);
Michael Jurka05713af2013-01-23 12:39:24 +0100624 }
625
626 private Bitmap generateShortcutPreview(
627 ResolveInfo info, int maxWidth, int maxHeight, Bitmap preview) {
628 Bitmap tempBitmap = mCachedShortcutPreviewBitmap.get();
629 final Canvas c = mCachedShortcutPreviewCanvas.get();
630 if (tempBitmap == null ||
631 tempBitmap.getWidth() != maxWidth ||
632 tempBitmap.getHeight() != maxHeight) {
633 tempBitmap = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
634 mCachedShortcutPreviewBitmap.set(tempBitmap);
635 } else {
636 c.setBitmap(tempBitmap);
637 c.drawColor(0, PorterDuff.Mode.CLEAR);
638 c.setBitmap(null);
639 }
640 // Render the icon
Adrian Roos65d60e22014-04-15 21:07:49 +0200641 Drawable icon = mutateOnMainThread(mIconCache.getFullResIcon(info));
Michael Jurka05713af2013-01-23 12:39:24 +0100642
643 int paddingTop = mContext.
644 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_top);
645 int paddingLeft = mContext.
646 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_left);
647 int paddingRight = mContext.
648 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_right);
649
650 int scaledIconWidth = (maxWidth - paddingLeft - paddingRight);
651
652 renderDrawableToBitmap(
653 icon, tempBitmap, paddingLeft, paddingTop, scaledIconWidth, scaledIconWidth);
654
655 if (preview != null &&
656 (preview.getWidth() != maxWidth || preview.getHeight() != maxHeight)) {
657 throw new RuntimeException("Improperly sized bitmap passed as argument");
658 } else if (preview == null) {
659 preview = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
660 }
661
662 c.setBitmap(preview);
663 // Draw a desaturated/scaled version of the icon in the background as a watermark
664 Paint p = mCachedShortcutPreviewPaint.get();
665 if (p == null) {
666 p = new Paint();
667 ColorMatrix colorMatrix = new ColorMatrix();
668 colorMatrix.setSaturation(0);
669 p.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
670 p.setAlpha((int) (255 * 0.06f));
671 mCachedShortcutPreviewPaint.set(p);
672 }
673 c.drawBitmap(tempBitmap, 0, 0, p);
674 c.setBitmap(null);
675
676 renderDrawableToBitmap(icon, preview, 0, 0, mAppIconSize, mAppIconSize);
677
678 return preview;
679 }
680
Michael Jurka05713af2013-01-23 12:39:24 +0100681 private static void renderDrawableToBitmap(
Sunny Goyalffe83f12014-08-14 17:39:34 -0700682 Drawable d, Bitmap bitmap, int x, int y, int w, int h) {
Michael Jurka05713af2013-01-23 12:39:24 +0100683 if (bitmap != null) {
684 Canvas c = new Canvas(bitmap);
Michael Jurka05713af2013-01-23 12:39:24 +0100685 Rect oldBounds = d.copyBounds();
686 d.setBounds(x, y, x + w, y + h);
687 d.draw(c);
688 d.setBounds(oldBounds); // Restore the bounds
689 c.setBitmap(null);
690 }
691 }
692
Adrian Roos65d60e22014-04-15 21:07:49 +0200693 private Drawable mutateOnMainThread(final Drawable drawable) {
694 try {
695 return mMainThreadExecutor.submit(new Callable<Drawable>() {
696 @Override
697 public Drawable call() throws Exception {
698 return drawable.mutate();
699 }
700 }).get();
701 } catch (InterruptedException e) {
702 Thread.currentThread().interrupt();
703 throw new RuntimeException(e);
704 } catch (ExecutionException e) {
705 throw new RuntimeException(e);
706 }
707 }
Adrian Roos1f375ab2014-04-28 18:26:38 +0200708
709 private static final int MAX_OPEN_FILES = 1024;
710 private static final int SAMPLE_RATE = 23;
711 /**
712 * Dumps all files that are open in this process without allocating a file descriptor.
713 */
714 private static void dumpOpenFiles() {
715 try {
716 Log.i(TAG, "DUMP OF OPEN FILES (sample rate: 1 every " + SAMPLE_RATE + "):");
717 final String TYPE_APK = "apk";
718 final String TYPE_JAR = "jar";
719 final String TYPE_PIPE = "pipe";
720 final String TYPE_SOCKET = "socket";
721 final String TYPE_DB = "db";
722 final String TYPE_ANON_INODE = "anon_inode";
723 final String TYPE_DEV = "dev";
724 final String TYPE_NON_FS = "non-fs";
725 final String TYPE_OTHER = "other";
726 List<String> types = Arrays.asList(TYPE_APK, TYPE_JAR, TYPE_PIPE, TYPE_SOCKET, TYPE_DB,
727 TYPE_ANON_INODE, TYPE_DEV, TYPE_NON_FS, TYPE_OTHER);
728 int[] count = new int[types.size()];
729 int[] duplicates = new int[types.size()];
730 HashSet<String> files = new HashSet<String>();
731 int total = 0;
732 for (int i = 0; i < MAX_OPEN_FILES; i++) {
733 // This is a gigantic hack but unfortunately the only way to resolve an fd
734 // to a file name. Note that we have to loop over all possible fds because
735 // reading the directory would require allocating a new fd. The kernel is
736 // currently implemented such that no fd is larger then the current rlimit,
737 // which is why it's safe to loop over them in such a way.
738 String fd = "/proc/self/fd/" + i;
739 try {
740 // getCanonicalPath() uses readlink behind the scene which doesn't require
741 // a file descriptor.
742 String resolved = new File(fd).getCanonicalPath();
743 int type = types.indexOf(TYPE_OTHER);
744 if (resolved.startsWith("/dev/")) {
745 type = types.indexOf(TYPE_DEV);
746 } else if (resolved.endsWith(".apk")) {
747 type = types.indexOf(TYPE_APK);
748 } else if (resolved.endsWith(".jar")) {
749 type = types.indexOf(TYPE_JAR);
750 } else if (resolved.contains("/fd/pipe:")) {
751 type = types.indexOf(TYPE_PIPE);
752 } else if (resolved.contains("/fd/socket:")) {
753 type = types.indexOf(TYPE_SOCKET);
754 } else if (resolved.contains("/fd/anon_inode:")) {
755 type = types.indexOf(TYPE_ANON_INODE);
756 } else if (resolved.endsWith(".db") || resolved.contains("/databases/")) {
757 type = types.indexOf(TYPE_DB);
758 } else if (resolved.startsWith("/proc/") && resolved.contains("/fd/")) {
759 // Those are the files that don't point anywhere on the file system.
760 // getCanonicalPath() wrongly interprets these as relative symlinks and
761 // resolves them within /proc/<pid>/fd/.
762 type = types.indexOf(TYPE_NON_FS);
763 }
764 count[type]++;
765 total++;
766 if (files.contains(resolved)) {
767 duplicates[type]++;
768 }
769 files.add(resolved);
770 if (total % SAMPLE_RATE == 0) {
771 Log.i(TAG, " fd " + i + ": " + resolved
772 + " (" + types.get(type) + ")");
773 }
774 } catch (IOException e) {
775 // Ignoring exceptions for non-existing file descriptors.
776 }
777 }
778 for (int i = 0; i < types.size(); i++) {
779 Log.i(TAG, String.format("Open %10s files: %4d total, %4d duplicates",
780 types.get(i), count[i], duplicates[i]));
781 }
782 } catch (Throwable t) {
783 // Catch everything. This is called from an exception handler that we shouldn't upset.
784 Log.e(TAG, "Unable to log open files.", t);
785 }
786 }
Michael Jurka05713af2013-01-23 12:39:24 +0100787}