OSDN Git Service

Merge remote-tracking branch \'goog/ub-now-lunchbox\' into lunchbox-release am: 853b5...
[android-x86/packages-apps-Trebuchet.git] / src / com / android / launcher3 / WidgetPreviewLoader.java
1 package com.android.launcher3;
2
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;
33
34 import java.io.ByteArrayOutputStream;
35 import java.io.File;
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;
46
47 public class WidgetPreviewLoader {
48
49     private static abstract class SoftReferenceThreadLocal<T> {
50         private ThreadLocal<SoftReference<T>> mThreadLocal;
51         public SoftReferenceThreadLocal() {
52             mThreadLocal = new ThreadLocal<SoftReference<T>>();
53         }
54
55         abstract T initialValue();
56
57         public void set(T t) {
58             mThreadLocal.set(new SoftReference<T>(t));
59         }
60
61         public T get() {
62             SoftReference<T> reference = mThreadLocal.get();
63             T obj;
64             if (reference == null) {
65                 obj = initialValue();
66                 mThreadLocal.set(new SoftReference<T>(obj));
67                 return obj;
68             } else {
69                 obj = reference.get();
70                 if (obj == null) {
71                     obj = initialValue();
72                     mThreadLocal.set(new SoftReference<T>(obj));
73                 }
74                 return obj;
75             }
76         }
77     }
78
79     private static class CanvasCache extends SoftReferenceThreadLocal<Canvas> {
80         @Override
81         protected Canvas initialValue() {
82             return new Canvas();
83         }
84     }
85
86     private static class PaintCache extends SoftReferenceThreadLocal<Paint> {
87         @Override
88         protected Paint initialValue() {
89             return null;
90         }
91     }
92
93     private static class BitmapCache extends SoftReferenceThreadLocal<Bitmap> {
94         @Override
95         protected Bitmap initialValue() {
96             return null;
97         }
98     }
99
100     private static class RectCache extends SoftReferenceThreadLocal<Rect> {
101         @Override
102         protected Rect initialValue() {
103             return new Rect();
104         }
105     }
106
107     private static class BitmapFactoryOptionsCache extends
108             SoftReferenceThreadLocal<BitmapFactory.Options> {
109         @Override
110         protected BitmapFactory.Options initialValue() {
111             return new BitmapFactory.Options();
112         }
113     }
114
115     private static final String TAG = "WidgetPreviewLoader";
116     private static final String ANDROID_INCREMENTAL_VERSION_NAME_KEY = "android.incremental.version";
117
118     private static final float WIDGET_PREVIEW_ICON_PADDING_PERCENTAGE = 0.25f;
119     private static final HashSet<String> sInvalidPackages = new HashSet<String>();
120
121     // Used for drawing shortcut previews
122     private final BitmapCache mCachedShortcutPreviewBitmap = new BitmapCache();
123     private final PaintCache mCachedShortcutPreviewPaint = new PaintCache();
124     private final CanvasCache mCachedShortcutPreviewCanvas = new CanvasCache();
125
126     // Used for drawing widget previews
127     private final CanvasCache mCachedAppWidgetPreviewCanvas = new CanvasCache();
128     private final RectCache mCachedAppWidgetPreviewSrcRect = new RectCache();
129     private final RectCache mCachedAppWidgetPreviewDestRect = new RectCache();
130     private final PaintCache mCachedAppWidgetPreviewPaint = new PaintCache();
131     private final PaintCache mDefaultAppWidgetPreviewPaint = new PaintCache();
132     private final BitmapFactoryOptionsCache mCachedBitmapFactoryOptions = new BitmapFactoryOptionsCache();
133
134     private final HashMap<String, WeakReference<Bitmap>> mLoadedPreviews = new HashMap<String, WeakReference<Bitmap>>();
135     private final ArrayList<SoftReference<Bitmap>> mUnusedBitmaps = new ArrayList<SoftReference<Bitmap>>();
136
137     private final Context mContext;
138     private final int mAppIconSize;
139     private final IconCache mIconCache;
140     private final AppWidgetManagerCompat mManager;
141
142     private int mPreviewBitmapWidth;
143     private int mPreviewBitmapHeight;
144     private String mSize;
145     private PagedViewCellLayout mWidgetSpacingLayout;
146
147     private String mCachedSelectQuery;
148
149
150     private CacheDb mDb;
151
152     private final MainThreadExecutor mMainThreadExecutor = new MainThreadExecutor();
153
154     public WidgetPreviewLoader(Context context) {
155         LauncherAppState app = LauncherAppState.getInstance();
156         DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
157
158         mContext = context;
159         mAppIconSize = grid.iconSizePx;
160         mIconCache = app.getIconCache();
161         mManager = AppWidgetManagerCompat.getInstance(context);
162
163         mDb = app.getWidgetPreviewCacheDb();
164
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)) {
171             try {
172                 // clear all the previews whenever the system version changes, to ensure that
173                 // previews are up-to-date for any apps that might have been updated with the system
174                 clearDb();
175             } catch (SQLiteReadOnlyDatabaseException e) {
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
179                 } else {
180                     throw e;
181                 }
182             } finally {
183                 SharedPreferences.Editor editor = sp.edit();
184                 editor.putString(ANDROID_INCREMENTAL_VERSION_NAME_KEY, versionName);
185                 editor.commit();
186             }
187         }
188     }
189
190     public void recreateDb() {
191         LauncherAppState app = LauncherAppState.getInstance();
192         app.recreateWidgetPreviewDb();
193         mDb = app.getWidgetPreviewCacheDb();
194     }
195
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;
202     }
203
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);
210             if (!packageValid) {
211                 return null;
212             }
213         }
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) {
220                     return bitmap;
221                 }
222             }
223         }
224
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;
234                 }
235             }
236             if (unusedBitmap != null) {
237                 final Canvas c = mCachedAppWidgetPreviewCanvas.get();
238                 c.setBitmap(unusedBitmap);
239                 c.drawColor(0, PorterDuff.Mode.CLEAR);
240                 c.setBitmap(null);
241             }
242         }
243
244         if (unusedBitmap == null) {
245             unusedBitmap = Bitmap.createBitmap(mPreviewBitmapWidth, mPreviewBitmapHeight,
246                     Bitmap.Config.ARGB_8888);
247         }
248         Bitmap preview = readFromDb(name, unusedBitmap);
249
250         if (preview != null) {
251             synchronized(mLoadedPreviews) {
252                 mLoadedPreviews.put(name, new WeakReference<Bitmap>(preview));
253             }
254             return preview;
255         } else {
256             // it's not in the db... we need to generate it
257             final Bitmap generatedPreview = generatePreview(o, unusedBitmap);
258             preview = generatedPreview;
259             if (preview != unusedBitmap) {
260                 throw new RuntimeException("generatePreview is not recycling the bitmap " + o);
261             }
262
263             synchronized(mLoadedPreviews) {
264                 mLoadedPreviews.put(name, new WeakReference<Bitmap>(preview));
265             }
266
267             // write to db on a thread pool... this can be done lazily and improves the performance
268             // of the first time widget previews are loaded
269             new AsyncTask<Void, Void, Void>() {
270                 public Void doInBackground(Void ... args) {
271                     writeToDb(o, generatedPreview);
272                     return null;
273                 }
274             }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
275
276             return preview;
277         }
278     }
279
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));
290                         }
291                     }
292                 } else {
293                     throw new RuntimeException("Bitmap passed in doesn't match up");
294                 }
295             }
296         }
297     }
298
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";
305         Context mContext;
306
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
311             mContext = context;
312         }
313
314         @Override
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 + ") " +
321                     ");");
322         }
323
324         @Override
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);
329             }
330         }
331     }
332
333     private static final String WIDGET_PREFIX = "Widget:";
334     private static final String SHORTCUT_PREFIX = "Shortcut:";
335
336     private static String getObjectName(Object o) {
337         // should cache the string builder
338         StringBuilder sb = new StringBuilder();
339         String output;
340         if (o instanceof AppWidgetProviderInfo) {
341             sb.append(WIDGET_PREFIX);
342             sb.append(((AppWidgetProviderInfo) o).toString());
343             output = sb.toString();
344             sb.setLength(0);
345         } else {
346             sb.append(SHORTCUT_PREFIX);
347
348             ResolveInfo info = (ResolveInfo) o;
349             sb.append(new ComponentName(info.activityInfo.packageName,
350                     info.activityInfo.name).flattenToString());
351             output = sb.toString();
352             sb.setLength(0);
353         }
354         return output;
355     }
356
357     private String getObjectPackage(Object o) {
358         if (o instanceof AppWidgetProviderInfo) {
359             return ((AppWidgetProviderInfo) o).provider.getPackageName();
360         } else {
361             ResolveInfo info = (ResolveInfo) o;
362             return info.activityInfo.packageName;
363         }
364     }
365
366     private void writeToDb(Object o, Bitmap preview) {
367         String name = getObjectName(o);
368         SQLiteDatabase db = mDb.getWritableDatabase();
369         ContentValues values = new ContentValues();
370
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);
376         try {
377             db.insert(CacheDb.TABLE_NAME, null, values);
378         } catch (SQLiteDiskIOException e) {
379             recreateDb();
380         } catch (SQLiteCantOpenDatabaseException e) {
381             dumpOpenFiles();
382             throw e;
383         }
384     }
385
386     private void clearDb() {
387         SQLiteDatabase db = mDb.getWritableDatabase();
388         // Delete everything
389         try {
390             db.delete(CacheDb.TABLE_NAME, null, null);
391         } catch (SQLiteDiskIOException e) {
392         } catch (SQLiteCantOpenDatabaseException e) {
393             dumpOpenFiles();
394             throw e;
395         }
396     }
397
398     public static void removePackageFromDb(final CacheDb cacheDb, final String packageName) {
399         synchronized(sInvalidPackages) {
400             sInvalidPackages.add(packageName);
401         }
402         new AsyncTask<Void, Void, Void>() {
403             public Void doInBackground(Void ... args) {
404                 SQLiteDatabase db = cacheDb.getWritableDatabase();
405                 try {
406                     db.delete(CacheDb.TABLE_NAME,
407                             CacheDb.COLUMN_NAME + " LIKE ? OR " +
408                             CacheDb.COLUMN_NAME + " LIKE ?", // SELECT query
409                             new String[] {
410                                     WIDGET_PREFIX + packageName + "/%",
411                                     SHORTCUT_PREFIX + packageName + "/%"
412                             } // args to SELECT query
413                     );
414                 } catch (SQLiteDiskIOException e) {
415                 } catch (SQLiteCantOpenDatabaseException e) {
416                     dumpOpenFiles();
417                     throw e;
418                 }
419                 synchronized(sInvalidPackages) {
420                     sInvalidPackages.remove(packageName);
421                 }
422                 return null;
423             }
424         }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
425     }
426
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();
431                 try {
432                     db.delete(CacheDb.TABLE_NAME,
433                             CacheDb.COLUMN_NAME + " = ? ", // SELECT query
434                             new String[] { objectName }); // args to SELECT query
435                 } catch (SQLiteDiskIOException e) {
436                 } catch (SQLiteCantOpenDatabaseException e) {
437                     dumpOpenFiles();
438                     throw e;
439                 }
440                 return null;
441             }
442         }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
443     }
444
445     private Bitmap readFromDb(String name, Bitmap b) {
446         if (mCachedSelectQuery == null) {
447             mCachedSelectQuery = CacheDb.COLUMN_NAME + " = ? AND " +
448                     CacheDb.COLUMN_SIZE + " = ?";
449         }
450         SQLiteDatabase db = mDb.getReadableDatabase();
451         Cursor result;
452         try {
453             result = db.query(CacheDb.TABLE_NAME,
454                     new String[] { CacheDb.COLUMN_PREVIEW_BITMAP }, // cols to return
455                     mCachedSelectQuery, // select query
456                     new String[] { name, mSize }, // args to select query
457                     null,
458                     null,
459                     null,
460                     null);
461         } catch (SQLiteDiskIOException e) {
462             recreateDb();
463             return null;
464         } catch (SQLiteCantOpenDatabaseException e) {
465             dumpOpenFiles();
466             throw e;
467         }
468         if (result.getCount() > 0) {
469             result.moveToFirst();
470             byte[] blob = result.getBlob(0);
471             result.close();
472             final BitmapFactory.Options opts = mCachedBitmapFactoryOptions.get();
473             opts.inBitmap = b;
474             opts.inSampleSize = 1;
475             try {
476                 return BitmapFactory.decodeByteArray(blob, 0, blob.length, opts);
477             } catch (IllegalArgumentException e) {
478                 removeItemFromDb(mDb, name);
479                 return null;
480             }
481         } else {
482             result.close();
483             return null;
484         }
485     }
486
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");
492         }
493         if (info instanceof AppWidgetProviderInfo) {
494             return generateWidgetPreview((AppWidgetProviderInfo) info, preview);
495         } else {
496             return generateShortcutPreview(
497                     (ResolveInfo) info, mPreviewBitmapWidth, mPreviewBitmapHeight, preview);
498         }
499     }
500
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);
507     }
508
509     public int maxWidthForWidgetPreview(int spanX) {
510         return Math.min(mPreviewBitmapWidth,
511                 mWidgetSpacingLayout.estimateCellWidth(spanX));
512     }
513
514     public int maxHeightForWidgetPreview(int spanY) {
515         return Math.min(mPreviewBitmapHeight,
516                 mWidgetSpacingLayout.estimateCellHeight(spanY));
517     }
518
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;
524
525         Drawable drawable = null;
526         if (info.previewImage != 0) {
527             drawable = mManager.loadPreview(info);
528             if (drawable != null) {
529                 drawable = mutateOnMainThread(drawable);
530             } else {
531                 Log.w(TAG, "Can't load widget preview drawable 0x" +
532                         Integer.toHexString(info.previewImage) + " for provider: " + info.provider);
533             }
534         }
535
536         int previewWidth;
537         int previewHeight;
538         Bitmap defaultPreview = null;
539         boolean widgetPreviewExists = (drawable != null);
540         if (widgetPreviewExists) {
541             previewWidth = drawable.getIntrinsicWidth();
542             previewHeight = drawable.getIntrinsicHeight();
543         } else {
544             // Generate a preview image if we couldn't load one
545             if (cellHSpan < 1) cellHSpan = 1;
546             if (cellVSpan < 1) cellVSpan = 1;
547
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;
557
558             defaultPreview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
559             final Canvas c = mCachedAppWidgetPreviewCanvas.get();
560             c.setBitmap(defaultPreview);
561             Paint p = mDefaultAppWidgetPreviewPaint.get();
562             if (p == null) {
563                 p = new Paint();
564                 p.setShader(new BitmapShader(previewDrawable.getBitmap(),
565                         Shader.TileMode.REPEAT, Shader.TileMode.REPEAT));
566                 mDefaultAppWidgetPreviewPaint.set(p);
567             }
568             final Rect dest = mCachedAppWidgetPreviewDestRect.get();
569             dest.set(0, 0, previewWidth, previewHeight);
570             c.drawRect(dest, p);
571             c.setBitmap(null);
572
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);
578
579             try {
580                 Drawable icon = mManager.loadIcon(info, mIconCache);
581                 if (icon != null) {
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));
588                 }
589             } catch (Resources.NotFoundException e) {
590             }
591         }
592
593         // Scale to fit width only - let the widget preview be clipped in the
594         // vertical dimension
595         float scale = 1f;
596         if (preScaledWidthOut != null) {
597             preScaledWidthOut[0] = previewWidth;
598         }
599         if (previewWidth > maxPreviewWidth) {
600             scale = maxPreviewWidth / (float) previewWidth;
601         }
602         if (scale != 1f) {
603             previewWidth = (int) (scale * previewWidth);
604             previewHeight = (int) (scale * previewHeight);
605         }
606
607         // If a bitmap is passed in, we use it; otherwise, we create a bitmap of the right size
608         if (preview == null) {
609             preview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
610         }
611
612         // Draw the scaled preview into the final bitmap
613         int x = (preview.getWidth() - previewWidth) / 2;
614         if (widgetPreviewExists) {
615             renderDrawableToBitmap(drawable, preview, x, 0, previewWidth,
616                     previewHeight);
617         } else {
618             final Canvas c = mCachedAppWidgetPreviewCanvas.get();
619             final Rect src = mCachedAppWidgetPreviewSrcRect.get();
620             final Rect dest = mCachedAppWidgetPreviewDestRect.get();
621             c.setBitmap(preview);
622             src.set(0, 0, defaultPreview.getWidth(), defaultPreview.getHeight());
623             dest.set(x, 0, x + previewWidth, previewHeight);
624
625             Paint p = mCachedAppWidgetPreviewPaint.get();
626             if (p == null) {
627                 p = new Paint();
628                 p.setFilterBitmap(true);
629                 mCachedAppWidgetPreviewPaint.set(p);
630             }
631             c.drawBitmap(defaultPreview, src, dest, p);
632             c.setBitmap(null);
633         }
634         return mManager.getBadgeBitmap(info, preview);
635     }
636
637     private Bitmap generateShortcutPreview(
638             ResolveInfo info, int maxWidth, int maxHeight, Bitmap preview) {
639         Bitmap tempBitmap = mCachedShortcutPreviewBitmap.get();
640         final Canvas c = mCachedShortcutPreviewCanvas.get();
641         if (tempBitmap == null ||
642                 tempBitmap.getWidth() != maxWidth ||
643                 tempBitmap.getHeight() != maxHeight) {
644             tempBitmap = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
645             mCachedShortcutPreviewBitmap.set(tempBitmap);
646         } else {
647             c.setBitmap(tempBitmap);
648             c.drawColor(0, PorterDuff.Mode.CLEAR);
649             c.setBitmap(null);
650         }
651         // Render the icon
652         Drawable icon = mutateOnMainThread(mIconCache.getFullResIcon(info.activityInfo));
653
654         int paddingTop = mContext.
655                 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_top);
656         int paddingLeft = mContext.
657                 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_left);
658         int paddingRight = mContext.
659                 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_right);
660
661         int scaledIconWidth = (maxWidth - paddingLeft - paddingRight);
662
663         renderDrawableToBitmap(
664                 icon, tempBitmap, paddingLeft, paddingTop, scaledIconWidth, scaledIconWidth);
665
666         if (preview != null &&
667                 (preview.getWidth() != maxWidth || preview.getHeight() != maxHeight)) {
668             throw new RuntimeException("Improperly sized bitmap passed as argument");
669         } else if (preview == null) {
670             preview = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
671         }
672
673         c.setBitmap(preview);
674         // Draw a desaturated/scaled version of the icon in the background as a watermark
675         Paint p = mCachedShortcutPreviewPaint.get();
676         if (p == null) {
677             p = new Paint();
678             ColorMatrix colorMatrix = new ColorMatrix();
679             colorMatrix.setSaturation(0);
680             p.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
681             p.setAlpha((int) (255 * 0.06f));
682             mCachedShortcutPreviewPaint.set(p);
683         }
684         c.drawBitmap(tempBitmap, 0, 0, p);
685         c.setBitmap(null);
686
687         renderDrawableToBitmap(icon, preview, 0, 0, mAppIconSize, mAppIconSize);
688
689         return preview;
690     }
691
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);
698             d.draw(c);
699             d.setBounds(oldBounds); // Restore the bounds
700             c.setBitmap(null);
701         }
702     }
703
704     private Drawable mutateOnMainThread(final Drawable drawable) {
705         try {
706             return mMainThreadExecutor.submit(new Callable<Drawable>() {
707                 @Override
708                 public Drawable call() throws Exception {
709                     return drawable.mutate();
710                 }
711             }).get();
712         } catch (InterruptedException e) {
713             Thread.currentThread().interrupt();
714             throw new RuntimeException(e);
715         } catch (ExecutionException e) {
716             throw new RuntimeException(e);
717         }
718     }
719
720     private static final int MAX_OPEN_FILES = 1024;
721     private static final int SAMPLE_RATE = 23;
722     /**
723      * Dumps all files that are open in this process without allocating a file descriptor.
724      */
725     private static void dumpOpenFiles() {
726         try {
727             Log.i(TAG, "DUMP OF OPEN FILES (sample rate: 1 every " + SAMPLE_RATE + "):");
728             final String TYPE_APK = "apk";
729             final String TYPE_JAR = "jar";
730             final String TYPE_PIPE = "pipe";
731             final String TYPE_SOCKET = "socket";
732             final String TYPE_DB = "db";
733             final String TYPE_ANON_INODE = "anon_inode";
734             final String TYPE_DEV = "dev";
735             final String TYPE_NON_FS = "non-fs";
736             final String TYPE_OTHER = "other";
737             List<String> types = Arrays.asList(TYPE_APK, TYPE_JAR, TYPE_PIPE, TYPE_SOCKET, TYPE_DB,
738                     TYPE_ANON_INODE, TYPE_DEV, TYPE_NON_FS, TYPE_OTHER);
739             int[] count = new int[types.size()];
740             int[] duplicates = new int[types.size()];
741             HashSet<String> files = new HashSet<String>();
742             int total = 0;
743             for (int i = 0; i < MAX_OPEN_FILES; i++) {
744                 // This is a gigantic hack but unfortunately the only way to resolve an fd
745                 // to a file name. Note that we have to loop over all possible fds because
746                 // reading the directory would require allocating a new fd. The kernel is
747                 // currently implemented such that no fd is larger then the current rlimit,
748                 // which is why it's safe to loop over them in such a way.
749                 String fd = "/proc/self/fd/" + i;
750                 try {
751                     // getCanonicalPath() uses readlink behind the scene which doesn't require
752                     // a file descriptor.
753                     String resolved = new File(fd).getCanonicalPath();
754                     int type = types.indexOf(TYPE_OTHER);
755                     if (resolved.startsWith("/dev/")) {
756                         type = types.indexOf(TYPE_DEV);
757                     } else if (resolved.endsWith(".apk")) {
758                         type = types.indexOf(TYPE_APK);
759                     } else if (resolved.endsWith(".jar")) {
760                         type = types.indexOf(TYPE_JAR);
761                     } else if (resolved.contains("/fd/pipe:")) {
762                         type = types.indexOf(TYPE_PIPE);
763                     } else if (resolved.contains("/fd/socket:")) {
764                         type = types.indexOf(TYPE_SOCKET);
765                     } else if (resolved.contains("/fd/anon_inode:")) {
766                         type = types.indexOf(TYPE_ANON_INODE);
767                     } else if (resolved.endsWith(".db") || resolved.contains("/databases/")) {
768                         type = types.indexOf(TYPE_DB);
769                     } else if (resolved.startsWith("/proc/") && resolved.contains("/fd/")) {
770                         // Those are the files that don't point anywhere on the file system.
771                         // getCanonicalPath() wrongly interprets these as relative symlinks and
772                         // resolves them within /proc/<pid>/fd/.
773                         type = types.indexOf(TYPE_NON_FS);
774                     }
775                     count[type]++;
776                     total++;
777                     if (files.contains(resolved)) {
778                         duplicates[type]++;
779                     }
780                     files.add(resolved);
781                     if (total % SAMPLE_RATE == 0) {
782                         Log.i(TAG, " fd " + i + ": " + resolved
783                                 + " (" + types.get(type) + ")");
784                     }
785                 } catch (IOException e) {
786                     // Ignoring exceptions for non-existing file descriptors.
787                 }
788             }
789             for (int i = 0; i < types.size(); i++) {
790                 Log.i(TAG, String.format("Open %10s files: %4d total, %4d duplicates",
791                         types.get(i), count[i], duplicates[i]));
792             }
793         } catch (Throwable t) {
794             // Catch everything. This is called from an exception handler that we shouldn't upset.
795             Log.e(TAG, "Unable to log open files.", t);
796         }
797     }
798 }