1 package com.android.launcher3;
3 import android.appwidget.AppWidgetProviderInfo;
4 import android.content.ComponentName;
5 import android.content.ContentValues;
6 import android.content.Context;
7 import android.content.SharedPreferences;
8 import android.content.pm.ResolveInfo;
9 import android.content.res.Resources;
10 import android.database.Cursor;
11 import android.database.sqlite.SQLiteCantOpenDatabaseException;
12 import android.database.sqlite.SQLiteDatabase;
13 import android.database.sqlite.SQLiteDiskIOException;
14 import android.database.sqlite.SQLiteOpenHelper;
15 import android.database.sqlite.SQLiteReadOnlyDatabaseException;
16 import android.graphics.Bitmap;
17 import android.graphics.Bitmap.Config;
18 import android.graphics.BitmapFactory;
19 import android.graphics.BitmapShader;
20 import android.graphics.Canvas;
21 import android.graphics.ColorMatrix;
22 import android.graphics.ColorMatrixColorFilter;
23 import android.graphics.Paint;
24 import android.graphics.PorterDuff;
25 import android.graphics.Rect;
26 import android.graphics.Shader;
27 import android.graphics.drawable.BitmapDrawable;
28 import android.graphics.drawable.Drawable;
29 import android.os.AsyncTask;
30 import android.os.Build;
31 import android.util.Log;
32 import com.android.launcher3.compat.AppWidgetManagerCompat;
34 import java.io.ByteArrayOutputStream;
36 import java.io.IOException;
37 import java.lang.ref.SoftReference;
38 import java.lang.ref.WeakReference;
39 import java.util.ArrayList;
40 import java.util.Arrays;
41 import java.util.HashMap;
42 import java.util.HashSet;
43 import java.util.List;
44 import java.util.concurrent.Callable;
45 import java.util.concurrent.ExecutionException;
47 public class WidgetPreviewLoader {
49 private static abstract class SoftReferenceThreadLocal<T> {
50 private ThreadLocal<SoftReference<T>> mThreadLocal;
51 public SoftReferenceThreadLocal() {
52 mThreadLocal = new ThreadLocal<SoftReference<T>>();
55 abstract T initialValue();
57 public void set(T t) {
58 mThreadLocal.set(new SoftReference<T>(t));
62 SoftReference<T> reference = mThreadLocal.get();
64 if (reference == null) {
66 mThreadLocal.set(new SoftReference<T>(obj));
69 obj = reference.get();
72 mThreadLocal.set(new SoftReference<T>(obj));
79 private static class CanvasCache extends SoftReferenceThreadLocal<Canvas> {
81 protected Canvas initialValue() {
86 private static class PaintCache extends SoftReferenceThreadLocal<Paint> {
88 protected Paint initialValue() {
93 private static class BitmapCache extends SoftReferenceThreadLocal<Bitmap> {
95 protected Bitmap initialValue() {
100 private static class RectCache extends SoftReferenceThreadLocal<Rect> {
102 protected Rect initialValue() {
107 private static class BitmapFactoryOptionsCache extends
108 SoftReferenceThreadLocal<BitmapFactory.Options> {
110 protected BitmapFactory.Options initialValue() {
111 return new BitmapFactory.Options();
115 private static final String TAG = "WidgetPreviewLoader";
116 private static final String ANDROID_INCREMENTAL_VERSION_NAME_KEY = "android.incremental.version";
118 private static final float WIDGET_PREVIEW_ICON_PADDING_PERCENTAGE = 0.25f;
119 private static final HashSet<String> sInvalidPackages = new HashSet<String>();
121 // Used for drawing shortcut previews
122 private final BitmapCache mCachedShortcutPreviewBitmap = new BitmapCache();
123 private final PaintCache mCachedShortcutPreviewPaint = new PaintCache();
124 private final CanvasCache mCachedShortcutPreviewCanvas = new CanvasCache();
126 // Used for drawing widget previews
127 private final CanvasCache mCachedAppWidgetPreviewCanvas = new CanvasCache();
128 private final RectCache mCachedAppWidgetPreviewSrcRect = new RectCache();
129 private final RectCache mCachedAppWidgetPreviewDestRect = new RectCache();
130 private final PaintCache mCachedAppWidgetPreviewPaint = new PaintCache();
131 private final PaintCache mDefaultAppWidgetPreviewPaint = new PaintCache();
132 private final BitmapFactoryOptionsCache mCachedBitmapFactoryOptions = new BitmapFactoryOptionsCache();
134 private final HashMap<String, WeakReference<Bitmap>> mLoadedPreviews = new HashMap<String, WeakReference<Bitmap>>();
135 private final ArrayList<SoftReference<Bitmap>> mUnusedBitmaps = new ArrayList<SoftReference<Bitmap>>();
137 private final Context mContext;
138 private final int mAppIconSize;
139 private final IconCache mIconCache;
140 private final AppWidgetManagerCompat mManager;
142 private int mPreviewBitmapWidth;
143 private int mPreviewBitmapHeight;
144 private String mSize;
145 private PagedViewCellLayout mWidgetSpacingLayout;
147 private String mCachedSelectQuery;
152 private final MainThreadExecutor mMainThreadExecutor = new MainThreadExecutor();
154 public WidgetPreviewLoader(Context context) {
155 LauncherAppState app = LauncherAppState.getInstance();
156 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
159 mAppIconSize = grid.iconSizePx;
160 mIconCache = app.getIconCache();
161 mManager = AppWidgetManagerCompat.getInstance(context);
163 mDb = app.getWidgetPreviewCacheDb();
165 SharedPreferences sp = context.getSharedPreferences(
166 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
167 final String lastVersionName = sp.getString(ANDROID_INCREMENTAL_VERSION_NAME_KEY, null);
168 final String versionName = android.os.Build.VERSION.INCREMENTAL;
169 final boolean isLollipopOrGreater = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
170 if (!versionName.equals(lastVersionName)) {
172 // clear all the previews whenever the system version changes, to ensure that
173 // previews are up-to-date for any apps that might have been updated with the system
175 } catch (SQLiteReadOnlyDatabaseException e) {
176 if (isLollipopOrGreater) {
177 // Workaround for Bug. 18554839, if we fail to clear the db due to the read-only
178 // issue, then ignore this error and leave the old previews
183 SharedPreferences.Editor editor = sp.edit();
184 editor.putString(ANDROID_INCREMENTAL_VERSION_NAME_KEY, versionName);
190 public void recreateDb() {
191 LauncherAppState app = LauncherAppState.getInstance();
192 app.recreateWidgetPreviewDb();
193 mDb = app.getWidgetPreviewCacheDb();
196 public void setPreviewSize(int previewWidth, int previewHeight,
197 PagedViewCellLayout widgetSpacingLayout) {
198 mPreviewBitmapWidth = previewWidth;
199 mPreviewBitmapHeight = previewHeight;
200 mSize = previewWidth + "x" + previewHeight;
201 mWidgetSpacingLayout = widgetSpacingLayout;
204 public Bitmap getPreview(final Object o) {
205 final String name = getObjectName(o);
206 final String packageName = getObjectPackage(o);
207 // check if the package is valid
208 synchronized(sInvalidPackages) {
209 boolean packageValid = !sInvalidPackages.contains(packageName);
214 synchronized(mLoadedPreviews) {
215 // check if it exists in our existing cache
216 if (mLoadedPreviews.containsKey(name)) {
217 WeakReference<Bitmap> bitmapReference = mLoadedPreviews.get(name);
218 Bitmap bitmap = bitmapReference.get();
219 if (bitmap != null) {
225 Bitmap unusedBitmap = null;
226 synchronized(mUnusedBitmaps) {
227 // not in cache; we need to load it from the db
228 while (unusedBitmap == null && mUnusedBitmaps.size() > 0) {
229 Bitmap candidate = mUnusedBitmaps.remove(0).get();
230 if (candidate != null && candidate.isMutable() &&
231 candidate.getWidth() == mPreviewBitmapWidth &&
232 candidate.getHeight() == mPreviewBitmapHeight) {
233 unusedBitmap = candidate;
236 if (unusedBitmap != null) {
237 final Canvas c = mCachedAppWidgetPreviewCanvas.get();
238 c.setBitmap(unusedBitmap);
239 c.drawColor(0, PorterDuff.Mode.CLEAR);
244 if (unusedBitmap == null) {
245 unusedBitmap = Bitmap.createBitmap(mPreviewBitmapWidth, mPreviewBitmapHeight,
246 Bitmap.Config.ARGB_8888);
248 Bitmap preview = readFromDb(name, unusedBitmap);
250 if (preview != null) {
251 synchronized(mLoadedPreviews) {
252 mLoadedPreviews.put(name, new WeakReference<Bitmap>(preview));
256 // it's not in the db... we need to generate it
257 final Bitmap generatedPreview = generatePreview(o, unusedBitmap);
258 preview = generatedPreview;
259 if (preview != unusedBitmap) {
260 throw new RuntimeException("generatePreview is not recycling the bitmap " + o);
263 synchronized(mLoadedPreviews) {
264 mLoadedPreviews.put(name, new WeakReference<Bitmap>(preview));
267 // write to db on a thread pool... this can be done lazily and improves the performance
268 // of the first time widget previews are loaded
269 new AsyncTask<Void, Void, Void>() {
270 public Void doInBackground(Void ... args) {
271 writeToDb(o, generatedPreview);
274 }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
280 public void recycleBitmap(Object o, Bitmap bitmapToRecycle) {
281 String name = getObjectName(o);
282 synchronized (mLoadedPreviews) {
283 if (mLoadedPreviews.containsKey(name)) {
284 Bitmap b = mLoadedPreviews.get(name).get();
285 if (b == bitmapToRecycle) {
286 mLoadedPreviews.remove(name);
287 if (bitmapToRecycle.isMutable()) {
288 synchronized (mUnusedBitmaps) {
289 mUnusedBitmaps.add(new SoftReference<Bitmap>(b));
293 throw new RuntimeException("Bitmap passed in doesn't match up");
299 static class CacheDb extends SQLiteOpenHelper {
300 final static int DB_VERSION = 2;
301 final static String TABLE_NAME = "shortcut_and_widget_previews";
302 final static String COLUMN_NAME = "name";
303 final static String COLUMN_SIZE = "size";
304 final static String COLUMN_PREVIEW_BITMAP = "preview_bitmap";
307 public CacheDb(Context context) {
308 super(context, new File(context.getCacheDir(),
309 LauncherFiles.WIDGET_PREVIEWS_DB).getPath(), null, DB_VERSION);
310 // Store the context for later use
315 public void onCreate(SQLiteDatabase database) {
316 database.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" +
317 COLUMN_NAME + " TEXT NOT NULL, " +
318 COLUMN_SIZE + " TEXT NOT NULL, " +
319 COLUMN_PREVIEW_BITMAP + " BLOB NOT NULL, " +
320 "PRIMARY KEY (" + COLUMN_NAME + ", " + COLUMN_SIZE + ") " +
325 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
326 if (oldVersion != newVersion) {
327 // Delete all the records; they'll be repopulated as this is a cache
328 db.execSQL("DELETE FROM " + TABLE_NAME);
333 private static final String WIDGET_PREFIX = "Widget:";
334 private static final String SHORTCUT_PREFIX = "Shortcut:";
336 private static String getObjectName(Object o) {
337 // should cache the string builder
338 StringBuilder sb = new StringBuilder();
340 if (o instanceof AppWidgetProviderInfo) {
341 sb.append(WIDGET_PREFIX);
342 sb.append(((AppWidgetProviderInfo) o).toString());
343 output = sb.toString();
346 sb.append(SHORTCUT_PREFIX);
348 ResolveInfo info = (ResolveInfo) o;
349 sb.append(new ComponentName(info.activityInfo.packageName,
350 info.activityInfo.name).flattenToString());
351 output = sb.toString();
357 private String getObjectPackage(Object o) {
358 if (o instanceof AppWidgetProviderInfo) {
359 return ((AppWidgetProviderInfo) o).provider.getPackageName();
361 ResolveInfo info = (ResolveInfo) o;
362 return info.activityInfo.packageName;
366 private void writeToDb(Object o, Bitmap preview) {
367 String name = getObjectName(o);
368 SQLiteDatabase db = mDb.getWritableDatabase();
369 ContentValues values = new ContentValues();
371 values.put(CacheDb.COLUMN_NAME, name);
372 ByteArrayOutputStream stream = new ByteArrayOutputStream();
373 preview.compress(Bitmap.CompressFormat.PNG, 100, stream);
374 values.put(CacheDb.COLUMN_PREVIEW_BITMAP, stream.toByteArray());
375 values.put(CacheDb.COLUMN_SIZE, mSize);
377 db.insert(CacheDb.TABLE_NAME, null, values);
378 } catch (SQLiteDiskIOException e) {
380 } catch (SQLiteCantOpenDatabaseException e) {
386 private void clearDb() {
387 SQLiteDatabase db = mDb.getWritableDatabase();
390 db.delete(CacheDb.TABLE_NAME, null, null);
391 } catch (SQLiteDiskIOException e) {
392 } catch (SQLiteCantOpenDatabaseException e) {
398 public static void removePackageFromDb(final CacheDb cacheDb, final String packageName) {
399 synchronized(sInvalidPackages) {
400 sInvalidPackages.add(packageName);
402 new AsyncTask<Void, Void, Void>() {
403 public Void doInBackground(Void ... args) {
404 SQLiteDatabase db = cacheDb.getWritableDatabase();
406 db.delete(CacheDb.TABLE_NAME,
407 CacheDb.COLUMN_NAME + " LIKE ? OR " +
408 CacheDb.COLUMN_NAME + " LIKE ?", // SELECT query
410 WIDGET_PREFIX + packageName + "/%",
411 SHORTCUT_PREFIX + packageName + "/%"
412 } // args to SELECT query
414 } catch (SQLiteDiskIOException e) {
415 } catch (SQLiteCantOpenDatabaseException e) {
419 synchronized(sInvalidPackages) {
420 sInvalidPackages.remove(packageName);
424 }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
427 private static void removeItemFromDb(final CacheDb cacheDb, final String objectName) {
428 new AsyncTask<Void, Void, Void>() {
429 public Void doInBackground(Void ... args) {
430 SQLiteDatabase db = cacheDb.getWritableDatabase();
432 db.delete(CacheDb.TABLE_NAME,
433 CacheDb.COLUMN_NAME + " = ? ", // SELECT query
434 new String[] { objectName }); // args to SELECT query
435 } catch (SQLiteDiskIOException e) {
436 } catch (SQLiteCantOpenDatabaseException e) {
442 }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
445 private Bitmap readFromDb(String name, Bitmap b) {
446 if (mCachedSelectQuery == null) {
447 mCachedSelectQuery = CacheDb.COLUMN_NAME + " = ? AND " +
448 CacheDb.COLUMN_SIZE + " = ?";
450 SQLiteDatabase db = mDb.getReadableDatabase();
453 result = db.query(CacheDb.TABLE_NAME,
454 new String[] { CacheDb.COLUMN_PREVIEW_BITMAP }, // cols to return
455 mCachedSelectQuery, // select query
456 new String[] { name, mSize }, // args to select query
461 } catch (SQLiteDiskIOException e) {
464 } catch (SQLiteCantOpenDatabaseException e) {
468 if (result.getCount() > 0) {
469 result.moveToFirst();
470 byte[] blob = result.getBlob(0);
472 final BitmapFactory.Options opts = mCachedBitmapFactoryOptions.get();
474 opts.inSampleSize = 1;
476 return BitmapFactory.decodeByteArray(blob, 0, blob.length, opts);
477 } catch (IllegalArgumentException e) {
478 removeItemFromDb(mDb, name);
487 private Bitmap generatePreview(Object info, Bitmap preview) {
488 if (preview != null &&
489 (preview.getWidth() != mPreviewBitmapWidth ||
490 preview.getHeight() != mPreviewBitmapHeight)) {
491 throw new RuntimeException("Improperly sized bitmap passed as argument");
493 if (info instanceof AppWidgetProviderInfo) {
494 return generateWidgetPreview((AppWidgetProviderInfo) info, preview);
496 return generateShortcutPreview(
497 (ResolveInfo) info, mPreviewBitmapWidth, mPreviewBitmapHeight, preview);
501 public Bitmap generateWidgetPreview(AppWidgetProviderInfo info, Bitmap preview) {
502 int[] cellSpans = Launcher.getSpanForWidget(mContext, info);
503 int maxWidth = maxWidthForWidgetPreview(cellSpans[0]);
504 int maxHeight = maxHeightForWidgetPreview(cellSpans[1]);
505 return generateWidgetPreview(info, cellSpans[0], cellSpans[1],
506 maxWidth, maxHeight, preview, null);
509 public int maxWidthForWidgetPreview(int spanX) {
510 return Math.min(mPreviewBitmapWidth,
511 mWidgetSpacingLayout.estimateCellWidth(spanX));
514 public int maxHeightForWidgetPreview(int spanY) {
515 return Math.min(mPreviewBitmapHeight,
516 mWidgetSpacingLayout.estimateCellHeight(spanY));
519 public Bitmap generateWidgetPreview(AppWidgetProviderInfo info, int cellHSpan, int cellVSpan,
520 int maxPreviewWidth, int maxPreviewHeight, Bitmap preview, int[] preScaledWidthOut) {
521 // Load the preview image if possible
522 if (maxPreviewWidth < 0) maxPreviewWidth = Integer.MAX_VALUE;
523 if (maxPreviewHeight < 0) maxPreviewHeight = Integer.MAX_VALUE;
525 Drawable drawable = null;
526 if (info.previewImage != 0) {
527 drawable = mManager.loadPreview(info);
528 if (drawable != null) {
529 drawable = mutateOnMainThread(drawable);
531 Log.w(TAG, "Can't load widget preview drawable 0x" +
532 Integer.toHexString(info.previewImage) + " for provider: " + info.provider);
538 Bitmap defaultPreview = null;
539 boolean widgetPreviewExists = (drawable != null);
540 if (widgetPreviewExists) {
541 previewWidth = drawable.getIntrinsicWidth();
542 previewHeight = drawable.getIntrinsicHeight();
544 // Generate a preview image if we couldn't load one
545 if (cellHSpan < 1) cellHSpan = 1;
546 if (cellVSpan < 1) cellVSpan = 1;
548 // This Drawable is not directly drawn, so there's no need to mutate it.
549 BitmapDrawable previewDrawable = (BitmapDrawable) mContext.getResources()
550 .getDrawable(R.drawable.widget_tile);
551 final int previewDrawableWidth = previewDrawable
552 .getIntrinsicWidth();
553 final int previewDrawableHeight = previewDrawable
554 .getIntrinsicHeight();
555 previewWidth = previewDrawableWidth * cellHSpan;
556 previewHeight = previewDrawableHeight * cellVSpan;
558 defaultPreview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
559 final Canvas c = mCachedAppWidgetPreviewCanvas.get();
560 c.setBitmap(defaultPreview);
561 Paint p = mDefaultAppWidgetPreviewPaint.get();
564 p.setShader(new BitmapShader(previewDrawable.getBitmap(),
565 Shader.TileMode.REPEAT, Shader.TileMode.REPEAT));
566 mDefaultAppWidgetPreviewPaint.set(p);
568 final Rect dest = mCachedAppWidgetPreviewDestRect.get();
569 dest.set(0, 0, previewWidth, previewHeight);
573 // Draw the icon in the top left corner
574 int minOffset = (int) (mAppIconSize * WIDGET_PREVIEW_ICON_PADDING_PERCENTAGE);
575 int smallestSide = Math.min(previewWidth, previewHeight);
576 float iconScale = Math.min((float) smallestSide
577 / (mAppIconSize + 2 * minOffset), 1f);
580 Drawable icon = mManager.loadIcon(info, mIconCache);
582 int hoffset = (int) ((previewDrawableWidth - mAppIconSize * iconScale) / 2);
583 int yoffset = (int) ((previewDrawableHeight - mAppIconSize * iconScale) / 2);
584 icon = mutateOnMainThread(icon);
585 renderDrawableToBitmap(icon, defaultPreview, hoffset,
586 yoffset, (int) (mAppIconSize * iconScale),
587 (int) (mAppIconSize * iconScale));
589 } catch (Resources.NotFoundException e) {
593 // Scale to fit width only - let the widget preview be clipped in the
594 // vertical dimension
596 if (preScaledWidthOut != null) {
597 preScaledWidthOut[0] = previewWidth;
599 if (previewWidth > maxPreviewWidth) {
600 scale = maxPreviewWidth / (float) previewWidth;
603 previewWidth = (int) (scale * previewWidth);
604 previewHeight = (int) (scale * previewHeight);
607 // If a bitmap is passed in, we use it; otherwise, we create a bitmap of the right size
608 if (preview == null) {
609 preview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
612 // Draw the scaled preview into the final bitmap
613 int x = (preview.getWidth() - previewWidth) / 2;
614 if (widgetPreviewExists) {
615 renderDrawableToBitmap(drawable, preview, x, 0, previewWidth,
618 final Canvas c = mCachedAppWidgetPreviewCanvas.get();
619 final Rect src = mCachedAppWidgetPreviewSrcRect.get();
620 final Rect dest = mCachedAppWidgetPreviewDestRect.get();
621 c.setBitmap(preview);
622 src.set(0, 0, defaultPreview.getWidth(), defaultPreview.getHeight());
623 dest.set(x, 0, x + previewWidth, previewHeight);
625 Paint p = mCachedAppWidgetPreviewPaint.get();
628 p.setFilterBitmap(true);
629 mCachedAppWidgetPreviewPaint.set(p);
631 c.drawBitmap(defaultPreview, src, dest, p);
634 return mManager.getBadgeBitmap(info, preview);
637 private Bitmap generateShortcutPreview(
638 ResolveInfo info, int maxWidth, int maxHeight, Bitmap preview) {
639 Bitmap tempBitmap = mCachedShortcutPreviewBitmap.get();
640 final Canvas c = mCachedShortcutPreviewCanvas.get();
641 if (tempBitmap == null ||
642 tempBitmap.getWidth() != maxWidth ||
643 tempBitmap.getHeight() != maxHeight) {
644 tempBitmap = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
645 mCachedShortcutPreviewBitmap.set(tempBitmap);
647 c.setBitmap(tempBitmap);
648 c.drawColor(0, PorterDuff.Mode.CLEAR);
652 Drawable icon = mutateOnMainThread(mIconCache.getFullResIcon(info.activityInfo));
654 int paddingTop = mContext.
655 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_top);
656 int paddingLeft = mContext.
657 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_left);
658 int paddingRight = mContext.
659 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_right);
661 int scaledIconWidth = (maxWidth - paddingLeft - paddingRight);
663 renderDrawableToBitmap(
664 icon, tempBitmap, paddingLeft, paddingTop, scaledIconWidth, scaledIconWidth);
666 if (preview != null &&
667 (preview.getWidth() != maxWidth || preview.getHeight() != maxHeight)) {
668 throw new RuntimeException("Improperly sized bitmap passed as argument");
669 } else if (preview == null) {
670 preview = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
673 c.setBitmap(preview);
674 // Draw a desaturated/scaled version of the icon in the background as a watermark
675 Paint p = mCachedShortcutPreviewPaint.get();
678 ColorMatrix colorMatrix = new ColorMatrix();
679 colorMatrix.setSaturation(0);
680 p.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
681 p.setAlpha((int) (255 * 0.06f));
682 mCachedShortcutPreviewPaint.set(p);
684 c.drawBitmap(tempBitmap, 0, 0, p);
687 renderDrawableToBitmap(icon, preview, 0, 0, mAppIconSize, mAppIconSize);
692 private static void renderDrawableToBitmap(
693 Drawable d, Bitmap bitmap, int x, int y, int w, int h) {
694 if (bitmap != null) {
695 Canvas c = new Canvas(bitmap);
696 Rect oldBounds = d.copyBounds();
697 d.setBounds(x, y, x + w, y + h);
699 d.setBounds(oldBounds); // Restore the bounds
704 private Drawable mutateOnMainThread(final Drawable drawable) {
706 return mMainThreadExecutor.submit(new Callable<Drawable>() {
708 public Drawable call() throws Exception {
709 return drawable.mutate();
712 } catch (InterruptedException e) {
713 Thread.currentThread().interrupt();
714 throw new RuntimeException(e);
715 } catch (ExecutionException e) {
716 throw new RuntimeException(e);
720 private static final int MAX_OPEN_FILES = 1024;
721 private static final int SAMPLE_RATE = 23;
723 * Dumps all files that are open in this process without allocating a file descriptor.
725 private static void dumpOpenFiles() {
727 Log.i(TAG, "DUMP OF OPEN FILES (sample rate: 1 every " + SAMPLE_RATE + "):");
728 final String TYPE_APK = "apk";
729 final String TYPE_JAR = "jar";
730 final String TYPE_PIPE = "pipe";
731 final String TYPE_SOCKET = "socket";
732 final String TYPE_DB = "db";
733 final String TYPE_ANON_INODE = "anon_inode";
734 final String TYPE_DEV = "dev";
735 final String TYPE_NON_FS = "non-fs";
736 final String TYPE_OTHER = "other";
737 List<String> types = Arrays.asList(TYPE_APK, TYPE_JAR, TYPE_PIPE, TYPE_SOCKET, TYPE_DB,
738 TYPE_ANON_INODE, TYPE_DEV, TYPE_NON_FS, TYPE_OTHER);
739 int[] count = new int[types.size()];
740 int[] duplicates = new int[types.size()];
741 HashSet<String> files = new HashSet<String>();
743 for (int i = 0; i < MAX_OPEN_FILES; i++) {
744 // This is a gigantic hack but unfortunately the only way to resolve an fd
745 // to a file name. Note that we have to loop over all possible fds because
746 // reading the directory would require allocating a new fd. The kernel is
747 // currently implemented such that no fd is larger then the current rlimit,
748 // which is why it's safe to loop over them in such a way.
749 String fd = "/proc/self/fd/" + i;
751 // getCanonicalPath() uses readlink behind the scene which doesn't require
752 // a file descriptor.
753 String resolved = new File(fd).getCanonicalPath();
754 int type = types.indexOf(TYPE_OTHER);
755 if (resolved.startsWith("/dev/")) {
756 type = types.indexOf(TYPE_DEV);
757 } else if (resolved.endsWith(".apk")) {
758 type = types.indexOf(TYPE_APK);
759 } else if (resolved.endsWith(".jar")) {
760 type = types.indexOf(TYPE_JAR);
761 } else if (resolved.contains("/fd/pipe:")) {
762 type = types.indexOf(TYPE_PIPE);
763 } else if (resolved.contains("/fd/socket:")) {
764 type = types.indexOf(TYPE_SOCKET);
765 } else if (resolved.contains("/fd/anon_inode:")) {
766 type = types.indexOf(TYPE_ANON_INODE);
767 } else if (resolved.endsWith(".db") || resolved.contains("/databases/")) {
768 type = types.indexOf(TYPE_DB);
769 } else if (resolved.startsWith("/proc/") && resolved.contains("/fd/")) {
770 // Those are the files that don't point anywhere on the file system.
771 // getCanonicalPath() wrongly interprets these as relative symlinks and
772 // resolves them within /proc/<pid>/fd/.
773 type = types.indexOf(TYPE_NON_FS);
777 if (files.contains(resolved)) {
781 if (total % SAMPLE_RATE == 0) {
782 Log.i(TAG, " fd " + i + ": " + resolved
783 + " (" + types.get(type) + ")");
785 } catch (IOException e) {
786 // Ignoring exceptions for non-existing file descriptors.
789 for (int i = 0; i < types.size(); i++) {
790 Log.i(TAG, String.format("Open %10s files: %4d total, %4d duplicates",
791 types.get(i), count[i], duplicates[i]));
793 } catch (Throwable t) {
794 // Catch everything. This is called from an exception handler that we shouldn't upset.
795 Log.e(TAG, "Unable to log open files.", t);