blob: 48fe269c1339b0c6d81af82ff0679db73d8ec8c6 [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.PackageManager;
9import android.content.pm.ResolveInfo;
10import android.content.res.Resources;
11import android.database.Cursor;
Adrian Roos1f375ab2014-04-28 18:26:38 +020012import android.database.sqlite.SQLiteCantOpenDatabaseException;
Michael Jurka05713af2013-01-23 12:39:24 +010013import android.database.sqlite.SQLiteDatabase;
Michael Jurka6e27f642013-12-10 13:40:30 +010014import android.database.sqlite.SQLiteDiskIOException;
Michael Jurka05713af2013-01-23 12:39:24 +010015import android.database.sqlite.SQLiteOpenHelper;
16import 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;
30import android.util.Log;
31
Michael Jurka05713af2013-01-23 12:39:24 +010032import java.io.ByteArrayOutputStream;
33import java.io.File;
Adrian Roos1f375ab2014-04-28 18:26:38 +020034import java.io.IOException;
Michael Jurka05713af2013-01-23 12:39:24 +010035import java.lang.ref.SoftReference;
36import java.lang.ref.WeakReference;
37import java.util.ArrayList;
Adrian Roos1f375ab2014-04-28 18:26:38 +020038import java.util.Arrays;
Michael Jurka05713af2013-01-23 12:39:24 +010039import java.util.HashMap;
40import java.util.HashSet;
Adrian Roos1f375ab2014-04-28 18:26:38 +020041import java.util.List;
Adrian Roos65d60e22014-04-15 21:07:49 +020042import java.util.concurrent.Callable;
43import java.util.concurrent.ExecutionException;
Michael Jurka05713af2013-01-23 12:39:24 +010044
45abstract class SoftReferenceThreadLocal<T> {
46 private ThreadLocal<SoftReference<T>> mThreadLocal;
47 public SoftReferenceThreadLocal() {
48 mThreadLocal = new ThreadLocal<SoftReference<T>>();
49 }
50
51 abstract T initialValue();
52
53 public void set(T t) {
54 mThreadLocal.set(new SoftReference<T>(t));
55 }
56
57 public T get() {
58 SoftReference<T> reference = mThreadLocal.get();
59 T obj;
60 if (reference == null) {
61 obj = initialValue();
62 mThreadLocal.set(new SoftReference<T>(obj));
63 return obj;
64 } else {
65 obj = reference.get();
66 if (obj == null) {
67 obj = initialValue();
68 mThreadLocal.set(new SoftReference<T>(obj));
69 }
70 return obj;
71 }
72 }
73}
74
75class CanvasCache extends SoftReferenceThreadLocal<Canvas> {
76 @Override
77 protected Canvas initialValue() {
78 return new Canvas();
79 }
80}
81
82class PaintCache extends SoftReferenceThreadLocal<Paint> {
83 @Override
84 protected Paint initialValue() {
85 return null;
86 }
87}
88
89class BitmapCache extends SoftReferenceThreadLocal<Bitmap> {
90 @Override
91 protected Bitmap initialValue() {
92 return null;
93 }
94}
95
96class RectCache extends SoftReferenceThreadLocal<Rect> {
97 @Override
98 protected Rect initialValue() {
99 return new Rect();
100 }
101}
102
103class BitmapFactoryOptionsCache extends SoftReferenceThreadLocal<BitmapFactory.Options> {
104 @Override
105 protected BitmapFactory.Options initialValue() {
106 return new BitmapFactory.Options();
107 }
108}
109
110public class WidgetPreviewLoader {
111 static final String TAG = "WidgetPreviewLoader";
Michael Jurka8ff02ca2013-11-01 14:19:27 +0100112 static final String ANDROID_INCREMENTAL_VERSION_NAME_KEY = "android.incremental.version";
Michael Jurka05713af2013-01-23 12:39:24 +0100113
Michael Jurka3f4e0702013-02-05 11:21:28 +0100114 private int mPreviewBitmapWidth;
115 private int mPreviewBitmapHeight;
Michael Jurka05713af2013-01-23 12:39:24 +0100116 private String mSize;
117 private Context mContext;
Michael Jurka05713af2013-01-23 12:39:24 +0100118 private PackageManager mPackageManager;
119 private PagedViewCellLayout mWidgetSpacingLayout;
120
121 // Used for drawing shortcut previews
122 private BitmapCache mCachedShortcutPreviewBitmap = new BitmapCache();
123 private PaintCache mCachedShortcutPreviewPaint = new PaintCache();
124 private CanvasCache mCachedShortcutPreviewCanvas = new CanvasCache();
125
126 // Used for drawing widget previews
127 private CanvasCache mCachedAppWidgetPreviewCanvas = new CanvasCache();
128 private RectCache mCachedAppWidgetPreviewSrcRect = new RectCache();
129 private RectCache mCachedAppWidgetPreviewDestRect = new RectCache();
130 private PaintCache mCachedAppWidgetPreviewPaint = new PaintCache();
Adrian Roosfa4c7992014-03-19 15:58:14 +0100131 private PaintCache mDefaultAppWidgetPreviewPaint = new PaintCache();
Michael Jurka05713af2013-01-23 12:39:24 +0100132 private String mCachedSelectQuery;
133 private BitmapFactoryOptionsCache mCachedBitmapFactoryOptions = new BitmapFactoryOptionsCache();
134
135 private int mAppIconSize;
136 private IconCache mIconCache;
137
Adrian Roos5d2704f2014-03-18 23:09:12 +0100138 private static final float sWidgetPreviewIconPaddingPercentage = 0.25f;
Michael Jurka05713af2013-01-23 12:39:24 +0100139
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100140 private CacheDb mDb;
Michael Jurka05713af2013-01-23 12:39:24 +0100141
Adrian Roos5d2704f2014-03-18 23:09:12 +0100142 private final HashMap<String, WeakReference<Bitmap>> mLoadedPreviews;
143 private final ArrayList<SoftReference<Bitmap>> mUnusedBitmaps;
144 private final static HashSet<String> sInvalidPackages;
Michael Jurka05713af2013-01-23 12:39:24 +0100145
Adrian Roos65d60e22014-04-15 21:07:49 +0200146 private final MainThreadExecutor mMainThreadExecutor = new MainThreadExecutor();
147
Michael Jurka05713af2013-01-23 12:39:24 +0100148 static {
Michael Jurka05713af2013-01-23 12:39:24 +0100149 sInvalidPackages = new HashSet<String>();
150 }
151
Chris Wrenfd13c712013-09-27 15:45:19 -0400152 public WidgetPreviewLoader(Context context) {
Winson Chung5f8afe62013-08-12 16:19:28 -0700153 LauncherAppState app = LauncherAppState.getInstance();
154 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
155
Chris Wrenfd13c712013-09-27 15:45:19 -0400156 mContext = context;
Michael Jurka05713af2013-01-23 12:39:24 +0100157 mPackageManager = mContext.getPackageManager();
Winson Chung5f8afe62013-08-12 16:19:28 -0700158 mAppIconSize = grid.iconSizePx;
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100159 mIconCache = app.getIconCache();
160 mDb = app.getWidgetPreviewCacheDb();
Michael Jurka3f4e0702013-02-05 11:21:28 +0100161 mLoadedPreviews = new HashMap<String, WeakReference<Bitmap>>();
162 mUnusedBitmaps = new ArrayList<SoftReference<Bitmap>>();
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 }
Michael Jurka6e27f642013-12-10 13:40:30 +0100178
179 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);
331 sb.append(((AppWidgetProviderInfo) o).provider.flattenToString());
332 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
Michael Jurkaeb1bb922013-09-26 11:29:01 -0700416 public static void removeItemFromDb(final CacheDb cacheDb, final String objectName) {
417 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
476 public Bitmap generatePreview(Object info, Bitmap preview) {
477 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]);
494 return generateWidgetPreview(info.provider, info.previewImage, info.icon,
495 cellSpans[0], cellSpans[1], maxWidth, maxHeight, preview, null);
496 }
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
508 public Bitmap generateWidgetPreview(ComponentName provider, int previewImage,
509 int iconId, int cellHSpan, int cellVSpan, int maxPreviewWidth, int maxPreviewHeight,
510 Bitmap preview, int[] preScaledWidthOut) {
511 // Load the preview image if possible
512 String packageName = provider.getPackageName();
513 if (maxPreviewWidth < 0) maxPreviewWidth = Integer.MAX_VALUE;
514 if (maxPreviewHeight < 0) maxPreviewHeight = Integer.MAX_VALUE;
515
516 Drawable drawable = null;
517 if (previewImage != 0) {
Adrian Roos65d60e22014-04-15 21:07:49 +0200518 drawable = mutateOnMainThread(
519 mPackageManager.getDrawable(packageName, previewImage, null));
Michael Jurka05713af2013-01-23 12:39:24 +0100520 if (drawable == null) {
521 Log.w(TAG, "Can't load widget preview drawable 0x" +
522 Integer.toHexString(previewImage) + " for provider: " + provider);
523 }
524 }
525
526 int previewWidth;
527 int previewHeight;
528 Bitmap defaultPreview = null;
529 boolean widgetPreviewExists = (drawable != null);
530 if (widgetPreviewExists) {
531 previewWidth = drawable.getIntrinsicWidth();
532 previewHeight = drawable.getIntrinsicHeight();
533 } else {
534 // Generate a preview image if we couldn't load one
535 if (cellHSpan < 1) cellHSpan = 1;
536 if (cellVSpan < 1) cellVSpan = 1;
537
Adrian Roos65d60e22014-04-15 21:07:49 +0200538 // This Drawable is not directly drawn, so there's no need to mutate it.
Michael Jurka05713af2013-01-23 12:39:24 +0100539 BitmapDrawable previewDrawable = (BitmapDrawable) mContext.getResources()
Winson Chung6706ed82013-10-02 11:00:15 -0700540 .getDrawable(R.drawable.widget_tile);
Michael Jurka05713af2013-01-23 12:39:24 +0100541 final int previewDrawableWidth = previewDrawable
542 .getIntrinsicWidth();
543 final int previewDrawableHeight = previewDrawable
544 .getIntrinsicHeight();
Winson Chung45cab392013-10-02 17:45:32 -0700545 previewWidth = previewDrawableWidth * cellHSpan;
Michael Jurka05713af2013-01-23 12:39:24 +0100546 previewHeight = previewDrawableHeight * cellVSpan;
547
Adrian Roos5d2704f2014-03-18 23:09:12 +0100548 defaultPreview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
Michael Jurka05713af2013-01-23 12:39:24 +0100549 final Canvas c = mCachedAppWidgetPreviewCanvas.get();
550 c.setBitmap(defaultPreview);
Adrian Roosfa4c7992014-03-19 15:58:14 +0100551 Paint p = mDefaultAppWidgetPreviewPaint.get();
552 if (p == null) {
553 p = new Paint();
554 p.setShader(new BitmapShader(previewDrawable.getBitmap(),
555 Shader.TileMode.REPEAT, Shader.TileMode.REPEAT));
556 mDefaultAppWidgetPreviewPaint.set(p);
557 }
558 final Rect dest = mCachedAppWidgetPreviewDestRect.get();
559 dest.set(0, 0, previewWidth, previewHeight);
560 c.drawRect(dest, p);
Michael Jurka05713af2013-01-23 12:39:24 +0100561 c.setBitmap(null);
562
563 // Draw the icon in the top left corner
564 int minOffset = (int) (mAppIconSize * sWidgetPreviewIconPaddingPercentage);
565 int smallestSide = Math.min(previewWidth, previewHeight);
566 float iconScale = Math.min((float) smallestSide
567 / (mAppIconSize + 2 * minOffset), 1f);
568
569 try {
570 Drawable icon = null;
571 int hoffset =
572 (int) ((previewDrawableWidth - mAppIconSize * iconScale) / 2);
573 int yoffset =
574 (int) ((previewDrawableHeight - mAppIconSize * iconScale) / 2);
575 if (iconId > 0)
Adrian Roos65d60e22014-04-15 21:07:49 +0200576 icon = mutateOnMainThread(mIconCache.getFullResIcon(packageName, iconId));
Michael Jurka05713af2013-01-23 12:39:24 +0100577 if (icon != null) {
578 renderDrawableToBitmap(icon, defaultPreview, hoffset,
579 yoffset, (int) (mAppIconSize * iconScale),
580 (int) (mAppIconSize * iconScale));
581 }
582 } catch (Resources.NotFoundException e) {
583 }
584 }
585
586 // Scale to fit width only - let the widget preview be clipped in the
587 // vertical dimension
588 float scale = 1f;
589 if (preScaledWidthOut != null) {
590 preScaledWidthOut[0] = previewWidth;
591 }
592 if (previewWidth > maxPreviewWidth) {
593 scale = maxPreviewWidth / (float) previewWidth;
594 }
595 if (scale != 1f) {
596 previewWidth = (int) (scale * previewWidth);
597 previewHeight = (int) (scale * previewHeight);
598 }
599
600 // If a bitmap is passed in, we use it; otherwise, we create a bitmap of the right size
601 if (preview == null) {
602 preview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
603 }
604
605 // Draw the scaled preview into the final bitmap
606 int x = (preview.getWidth() - previewWidth) / 2;
607 if (widgetPreviewExists) {
608 renderDrawableToBitmap(drawable, preview, x, 0, previewWidth,
609 previewHeight);
610 } else {
611 final Canvas c = mCachedAppWidgetPreviewCanvas.get();
612 final Rect src = mCachedAppWidgetPreviewSrcRect.get();
613 final Rect dest = mCachedAppWidgetPreviewDestRect.get();
614 c.setBitmap(preview);
615 src.set(0, 0, defaultPreview.getWidth(), defaultPreview.getHeight());
Michael Jurkae5919c52013-03-06 17:30:10 +0100616 dest.set(x, 0, x + previewWidth, previewHeight);
Michael Jurka05713af2013-01-23 12:39:24 +0100617
618 Paint p = mCachedAppWidgetPreviewPaint.get();
619 if (p == null) {
620 p = new Paint();
621 p.setFilterBitmap(true);
622 mCachedAppWidgetPreviewPaint.set(p);
623 }
624 c.drawBitmap(defaultPreview, src, dest, p);
625 c.setBitmap(null);
626 }
627 return preview;
628 }
629
630 private Bitmap generateShortcutPreview(
631 ResolveInfo info, int maxWidth, int maxHeight, Bitmap preview) {
632 Bitmap tempBitmap = mCachedShortcutPreviewBitmap.get();
633 final Canvas c = mCachedShortcutPreviewCanvas.get();
634 if (tempBitmap == null ||
635 tempBitmap.getWidth() != maxWidth ||
636 tempBitmap.getHeight() != maxHeight) {
637 tempBitmap = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
638 mCachedShortcutPreviewBitmap.set(tempBitmap);
639 } else {
640 c.setBitmap(tempBitmap);
641 c.drawColor(0, PorterDuff.Mode.CLEAR);
642 c.setBitmap(null);
643 }
644 // Render the icon
Adrian Roos65d60e22014-04-15 21:07:49 +0200645 Drawable icon = mutateOnMainThread(mIconCache.getFullResIcon(info));
Michael Jurka05713af2013-01-23 12:39:24 +0100646
647 int paddingTop = mContext.
648 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_top);
649 int paddingLeft = mContext.
650 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_left);
651 int paddingRight = mContext.
652 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_right);
653
654 int scaledIconWidth = (maxWidth - paddingLeft - paddingRight);
655
656 renderDrawableToBitmap(
657 icon, tempBitmap, paddingLeft, paddingTop, scaledIconWidth, scaledIconWidth);
658
659 if (preview != null &&
660 (preview.getWidth() != maxWidth || preview.getHeight() != maxHeight)) {
661 throw new RuntimeException("Improperly sized bitmap passed as argument");
662 } else if (preview == null) {
663 preview = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
664 }
665
666 c.setBitmap(preview);
667 // Draw a desaturated/scaled version of the icon in the background as a watermark
668 Paint p = mCachedShortcutPreviewPaint.get();
669 if (p == null) {
670 p = new Paint();
671 ColorMatrix colorMatrix = new ColorMatrix();
672 colorMatrix.setSaturation(0);
673 p.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
674 p.setAlpha((int) (255 * 0.06f));
675 mCachedShortcutPreviewPaint.set(p);
676 }
677 c.drawBitmap(tempBitmap, 0, 0, p);
678 c.setBitmap(null);
679
680 renderDrawableToBitmap(icon, preview, 0, 0, mAppIconSize, mAppIconSize);
681
682 return preview;
683 }
684
685
686 public static void renderDrawableToBitmap(
687 Drawable d, Bitmap bitmap, int x, int y, int w, int h) {
688 renderDrawableToBitmap(d, bitmap, x, y, w, h, 1f);
689 }
690
691 private static void renderDrawableToBitmap(
692 Drawable d, Bitmap bitmap, int x, int y, int w, int h,
693 float scale) {
694 if (bitmap != null) {
695 Canvas c = new Canvas(bitmap);
696 c.scale(scale, scale);
697 Rect oldBounds = d.copyBounds();
698 d.setBounds(x, y, x + w, y + h);
699 d.draw(c);
700 d.setBounds(oldBounds); // Restore the bounds
701 c.setBitmap(null);
702 }
703 }
704
Adrian Roos65d60e22014-04-15 21:07:49 +0200705 private Drawable mutateOnMainThread(final Drawable drawable) {
706 try {
707 return mMainThreadExecutor.submit(new Callable<Drawable>() {
708 @Override
709 public Drawable call() throws Exception {
710 return drawable.mutate();
711 }
712 }).get();
713 } catch (InterruptedException e) {
714 Thread.currentThread().interrupt();
715 throw new RuntimeException(e);
716 } catch (ExecutionException e) {
717 throw new RuntimeException(e);
718 }
719 }
Adrian Roos1f375ab2014-04-28 18:26:38 +0200720
721 private static final int MAX_OPEN_FILES = 1024;
722 private static final int SAMPLE_RATE = 23;
723 /**
724 * Dumps all files that are open in this process without allocating a file descriptor.
725 */
726 private static void dumpOpenFiles() {
727 try {
728 Log.i(TAG, "DUMP OF OPEN FILES (sample rate: 1 every " + SAMPLE_RATE + "):");
729 final String TYPE_APK = "apk";
730 final String TYPE_JAR = "jar";
731 final String TYPE_PIPE = "pipe";
732 final String TYPE_SOCKET = "socket";
733 final String TYPE_DB = "db";
734 final String TYPE_ANON_INODE = "anon_inode";
735 final String TYPE_DEV = "dev";
736 final String TYPE_NON_FS = "non-fs";
737 final String TYPE_OTHER = "other";
738 List<String> types = Arrays.asList(TYPE_APK, TYPE_JAR, TYPE_PIPE, TYPE_SOCKET, TYPE_DB,
739 TYPE_ANON_INODE, TYPE_DEV, TYPE_NON_FS, TYPE_OTHER);
740 int[] count = new int[types.size()];
741 int[] duplicates = new int[types.size()];
742 HashSet<String> files = new HashSet<String>();
743 int total = 0;
744 for (int i = 0; i < MAX_OPEN_FILES; i++) {
745 // This is a gigantic hack but unfortunately the only way to resolve an fd
746 // to a file name. Note that we have to loop over all possible fds because
747 // reading the directory would require allocating a new fd. The kernel is
748 // currently implemented such that no fd is larger then the current rlimit,
749 // which is why it's safe to loop over them in such a way.
750 String fd = "/proc/self/fd/" + i;
751 try {
752 // getCanonicalPath() uses readlink behind the scene which doesn't require
753 // a file descriptor.
754 String resolved = new File(fd).getCanonicalPath();
755 int type = types.indexOf(TYPE_OTHER);
756 if (resolved.startsWith("/dev/")) {
757 type = types.indexOf(TYPE_DEV);
758 } else if (resolved.endsWith(".apk")) {
759 type = types.indexOf(TYPE_APK);
760 } else if (resolved.endsWith(".jar")) {
761 type = types.indexOf(TYPE_JAR);
762 } else if (resolved.contains("/fd/pipe:")) {
763 type = types.indexOf(TYPE_PIPE);
764 } else if (resolved.contains("/fd/socket:")) {
765 type = types.indexOf(TYPE_SOCKET);
766 } else if (resolved.contains("/fd/anon_inode:")) {
767 type = types.indexOf(TYPE_ANON_INODE);
768 } else if (resolved.endsWith(".db") || resolved.contains("/databases/")) {
769 type = types.indexOf(TYPE_DB);
770 } else if (resolved.startsWith("/proc/") && resolved.contains("/fd/")) {
771 // Those are the files that don't point anywhere on the file system.
772 // getCanonicalPath() wrongly interprets these as relative symlinks and
773 // resolves them within /proc/<pid>/fd/.
774 type = types.indexOf(TYPE_NON_FS);
775 }
776 count[type]++;
777 total++;
778 if (files.contains(resolved)) {
779 duplicates[type]++;
780 }
781 files.add(resolved);
782 if (total % SAMPLE_RATE == 0) {
783 Log.i(TAG, " fd " + i + ": " + resolved
784 + " (" + types.get(type) + ")");
785 }
786 } catch (IOException e) {
787 // Ignoring exceptions for non-existing file descriptors.
788 }
789 }
790 for (int i = 0; i < types.size(); i++) {
791 Log.i(TAG, String.format("Open %10s files: %4d total, %4d duplicates",
792 types.get(i), count[i], duplicates[i]));
793 }
794 } catch (Throwable t) {
795 // Catch everything. This is called from an exception handler that we shouldn't upset.
796 Log.e(TAG, "Unable to log open files.", t);
797 }
798 }
Michael Jurka05713af2013-01-23 12:39:24 +0100799}