blob: 6c06e0fcca021a31d375b55f57ac0e7c060c62e1 [file] [log] [blame]
Michael Jurka05713af2013-01-23 12:39:24 +01001package com.android.launcher2;
2
3import android.appwidget.AppWidgetProviderInfo;
4import android.content.ComponentName;
5import android.content.ContentValues;
6import android.content.Context;
7import android.content.pm.PackageManager;
8import android.content.pm.ResolveInfo;
9import android.content.res.Resources;
10import android.database.Cursor;
11import android.database.sqlite.SQLiteDatabase;
12import android.database.sqlite.SQLiteOpenHelper;
13import android.graphics.Bitmap;
14import android.graphics.Bitmap.Config;
15import android.graphics.BitmapFactory;
16import android.graphics.Canvas;
17import android.graphics.ColorMatrix;
18import android.graphics.ColorMatrixColorFilter;
19import android.graphics.Paint;
20import android.graphics.PorterDuff;
21import android.graphics.Rect;
22import android.graphics.Shader;
23import android.graphics.drawable.BitmapDrawable;
24import android.graphics.drawable.Drawable;
25import android.os.AsyncTask;
26import android.util.Log;
27
28import com.android.launcher.R;
29
30import java.io.ByteArrayOutputStream;
31import java.io.File;
32import java.lang.ref.SoftReference;
33import java.lang.ref.WeakReference;
34import java.util.ArrayList;
35import java.util.HashMap;
36import java.util.HashSet;
37
38abstract class SoftReferenceThreadLocal<T> {
39 private ThreadLocal<SoftReference<T>> mThreadLocal;
40 public SoftReferenceThreadLocal() {
41 mThreadLocal = new ThreadLocal<SoftReference<T>>();
42 }
43
44 abstract T initialValue();
45
46 public void set(T t) {
47 mThreadLocal.set(new SoftReference<T>(t));
48 }
49
50 public T get() {
51 SoftReference<T> reference = mThreadLocal.get();
52 T obj;
53 if (reference == null) {
54 obj = initialValue();
55 mThreadLocal.set(new SoftReference<T>(obj));
56 return obj;
57 } else {
58 obj = reference.get();
59 if (obj == null) {
60 obj = initialValue();
61 mThreadLocal.set(new SoftReference<T>(obj));
62 }
63 return obj;
64 }
65 }
66}
67
68class CanvasCache extends SoftReferenceThreadLocal<Canvas> {
69 @Override
70 protected Canvas initialValue() {
71 return new Canvas();
72 }
73}
74
75class PaintCache extends SoftReferenceThreadLocal<Paint> {
76 @Override
77 protected Paint initialValue() {
78 return null;
79 }
80}
81
82class BitmapCache extends SoftReferenceThreadLocal<Bitmap> {
83 @Override
84 protected Bitmap initialValue() {
85 return null;
86 }
87}
88
89class RectCache extends SoftReferenceThreadLocal<Rect> {
90 @Override
91 protected Rect initialValue() {
92 return new Rect();
93 }
94}
95
96class BitmapFactoryOptionsCache extends SoftReferenceThreadLocal<BitmapFactory.Options> {
97 @Override
98 protected BitmapFactory.Options initialValue() {
99 return new BitmapFactory.Options();
100 }
101}
102
103public class WidgetPreviewLoader {
104 static final String TAG = "WidgetPreviewLoader";
105
Michael Jurka3f4e0702013-02-05 11:21:28 +0100106 private int mPreviewBitmapWidth;
107 private int mPreviewBitmapHeight;
Michael Jurka05713af2013-01-23 12:39:24 +0100108 private String mSize;
109 private Context mContext;
110 private Launcher mLauncher;
111 private PackageManager mPackageManager;
112 private PagedViewCellLayout mWidgetSpacingLayout;
113
114 // Used for drawing shortcut previews
115 private BitmapCache mCachedShortcutPreviewBitmap = new BitmapCache();
116 private PaintCache mCachedShortcutPreviewPaint = new PaintCache();
117 private CanvasCache mCachedShortcutPreviewCanvas = new CanvasCache();
118
119 // Used for drawing widget previews
120 private CanvasCache mCachedAppWidgetPreviewCanvas = new CanvasCache();
121 private RectCache mCachedAppWidgetPreviewSrcRect = new RectCache();
122 private RectCache mCachedAppWidgetPreviewDestRect = new RectCache();
123 private PaintCache mCachedAppWidgetPreviewPaint = new PaintCache();
124 private String mCachedSelectQuery;
125 private BitmapFactoryOptionsCache mCachedBitmapFactoryOptions = new BitmapFactoryOptionsCache();
126
127 private int mAppIconSize;
128 private IconCache mIconCache;
129
130 private final float sWidgetPreviewIconPaddingPercentage = 0.25f;
131
132 private WidgetPreviewCacheDb mDb;
133
Michael Jurka3f4e0702013-02-05 11:21:28 +0100134 private HashMap<String, WeakReference<Bitmap>> mLoadedPreviews;
135 private ArrayList<SoftReference<Bitmap>> mUnusedBitmaps;
Michael Jurka05713af2013-01-23 12:39:24 +0100136 private static HashSet<String> sInvalidPackages;
137
138 static {
Michael Jurka05713af2013-01-23 12:39:24 +0100139 sInvalidPackages = new HashSet<String>();
140 }
141
Michael Jurka3f4e0702013-02-05 11:21:28 +0100142 public WidgetPreviewLoader(Launcher launcher) {
Michael Jurka05713af2013-01-23 12:39:24 +0100143 mContext = mLauncher = launcher;
144 mPackageManager = mContext.getPackageManager();
145 mAppIconSize = mContext.getResources().getDimensionPixelSize(R.dimen.app_icon_size);
146 mIconCache = ((LauncherApplication) launcher.getApplicationContext()).getIconCache();
Michael Jurka05713af2013-01-23 12:39:24 +0100147 mDb = new WidgetPreviewCacheDb(mContext);
Michael Jurka3f4e0702013-02-05 11:21:28 +0100148 mLoadedPreviews = new HashMap<String, WeakReference<Bitmap>>();
149 mUnusedBitmaps = new ArrayList<SoftReference<Bitmap>>();
150 }
151
152 public void setPreviewSize(int previewWidth, int previewHeight,
153 PagedViewCellLayout widgetSpacingLayout) {
154 mPreviewBitmapWidth = previewWidth;
155 mPreviewBitmapHeight = previewHeight;
156 mSize = previewWidth + "x" + previewHeight;
157 mWidgetSpacingLayout = widgetSpacingLayout;
Michael Jurka05713af2013-01-23 12:39:24 +0100158 }
159
160 public Bitmap getPreview(final Object o) {
161 String name = getObjectName(o);
162 // check if the package is valid
163 boolean packageValid = true;
164 synchronized(sInvalidPackages) {
165 packageValid = !sInvalidPackages.contains(getObjectPackage(o));
166 }
167 if (!packageValid) {
168 return null;
169 }
170 if (packageValid) {
Michael Jurka3f4e0702013-02-05 11:21:28 +0100171 synchronized(mLoadedPreviews) {
Michael Jurka05713af2013-01-23 12:39:24 +0100172 // check if it exists in our existing cache
Michael Jurka3f4e0702013-02-05 11:21:28 +0100173 if (mLoadedPreviews.containsKey(name) && mLoadedPreviews.get(name).get() != null) {
174 return mLoadedPreviews.get(name).get();
Michael Jurka05713af2013-01-23 12:39:24 +0100175 }
176 }
177 }
178
179 Bitmap unusedBitmap = null;
Michael Jurka3f4e0702013-02-05 11:21:28 +0100180 synchronized(mUnusedBitmaps) {
Michael Jurka05713af2013-01-23 12:39:24 +0100181 // not in cache; we need to load it from the db
Michael Jurka3f4e0702013-02-05 11:21:28 +0100182 while ((unusedBitmap == null || !unusedBitmap.isMutable() ||
183 unusedBitmap.getWidth() != mPreviewBitmapWidth ||
184 unusedBitmap.getHeight() != mPreviewBitmapHeight)
185 && mUnusedBitmaps.size() > 0) {
186 unusedBitmap = mUnusedBitmaps.remove(0).get();
Michael Jurka05713af2013-01-23 12:39:24 +0100187 }
188 if (unusedBitmap != null) {
189 final Canvas c = mCachedAppWidgetPreviewCanvas.get();
190 c.setBitmap(unusedBitmap);
191 c.drawColor(0, PorterDuff.Mode.CLEAR);
192 c.setBitmap(null);
193 }
194 }
195
196 if (unusedBitmap == null) {
Michael Jurka3f4e0702013-02-05 11:21:28 +0100197 unusedBitmap = Bitmap.createBitmap(mPreviewBitmapWidth, mPreviewBitmapHeight,
Michael Jurka05713af2013-01-23 12:39:24 +0100198 Bitmap.Config.ARGB_8888);
199 }
200
201 Bitmap preview = null;
202
203 if (packageValid) {
204 preview = readFromDb(name, unusedBitmap);
205 }
206
207 if (preview != null) {
Michael Jurka3f4e0702013-02-05 11:21:28 +0100208 synchronized(mLoadedPreviews) {
209 mLoadedPreviews.put(name, new WeakReference<Bitmap>(preview));
Michael Jurka05713af2013-01-23 12:39:24 +0100210 }
211 return preview;
212 } else {
213 // it's not in the db... we need to generate it
214 final Bitmap generatedPreview = generatePreview(o, unusedBitmap);
215 preview = generatedPreview;
216 if (preview != unusedBitmap) {
217 throw new RuntimeException("generatePreview is not recycling the bitmap " + o);
218 }
219
Michael Jurka3f4e0702013-02-05 11:21:28 +0100220 synchronized(mLoadedPreviews) {
221 mLoadedPreviews.put(name, new WeakReference<Bitmap>(preview));
Michael Jurka05713af2013-01-23 12:39:24 +0100222 }
223
224 // write to db on a thread pool... this can be done lazily and improves the performance
225 // of the first time widget previews are loaded
226 new AsyncTask<Void, Void, Void>() {
227 public Void doInBackground(Void ... args) {
228 writeToDb(o, generatedPreview);
229 return null;
230 }
231 }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
232
233 return preview;
234 }
235 }
236
Michael Jurkaee8e99f2013-02-07 13:27:06 +0100237 public void recycleBitmap(Object o, Bitmap bitmapToRecycle) {
Michael Jurka05713af2013-01-23 12:39:24 +0100238 String name = getObjectName(o);
Michael Jurka5140cfa2013-02-15 14:50:15 +0100239 synchronized (mLoadedPreviews) {
240 if (mLoadedPreviews.containsKey(name)) {
Michael Jurka3f4e0702013-02-05 11:21:28 +0100241 Bitmap b = mLoadedPreviews.get(name).get();
Michael Jurkaee8e99f2013-02-07 13:27:06 +0100242 if (b == bitmapToRecycle) {
Michael Jurka3f4e0702013-02-05 11:21:28 +0100243 mLoadedPreviews.remove(name);
Michael Jurkaee8e99f2013-02-07 13:27:06 +0100244 if (bitmapToRecycle.isMutable()) {
Michael Jurka5140cfa2013-02-15 14:50:15 +0100245 synchronized (mUnusedBitmaps) {
246 mUnusedBitmaps.add(new SoftReference<Bitmap>(b));
247 }
Michael Jurka05713af2013-01-23 12:39:24 +0100248 }
249 } else {
250 throw new RuntimeException("Bitmap passed in doesn't match up");
251 }
252 }
253 }
254 }
255
256 static class WidgetPreviewCacheDb extends SQLiteOpenHelper {
257 final static int DB_VERSION = 1;
258 final static String DB_NAME = "widgetpreviews.db";
259 final static String TABLE_NAME = "shortcut_and_widget_previews";
260 final static String COLUMN_NAME = "name";
261 final static String COLUMN_SIZE = "size";
262 final static String COLUMN_PREVIEW_BITMAP = "preview_bitmap";
263 Context mContext;
264
265 public WidgetPreviewCacheDb(Context context) {
266 super(context, new File(context.getCacheDir(), DB_NAME).getPath(), null, DB_VERSION);
267 // Store the context for later use
268 mContext = context;
269 }
270
271 @Override
272 public void onCreate(SQLiteDatabase database) {
Michael Jurka32b7a092013-02-07 20:06:49 +0100273 database.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" +
Michael Jurka05713af2013-01-23 12:39:24 +0100274 COLUMN_NAME + " TEXT NOT NULL, " +
275 COLUMN_SIZE + " TEXT NOT NULL, " +
276 COLUMN_PREVIEW_BITMAP + " BLOB NOT NULL, " +
277 "PRIMARY KEY (" + COLUMN_NAME + ", " + COLUMN_SIZE + ") " +
Michael Jurka32b7a092013-02-07 20:06:49 +0100278 ");");
Michael Jurka05713af2013-01-23 12:39:24 +0100279 }
280
281 @Override
282 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
283 // We are still only on version 1
284 }
285 }
286
287 private static final String WIDGET_PREFIX = "Widget:";
288 private static final String SHORTCUT_PREFIX = "Shortcut:";
289
290 private static String getObjectName(Object o) {
291 // should cache the string builder
292 StringBuilder sb = new StringBuilder();
293 String output;
294 if (o instanceof AppWidgetProviderInfo) {
295 sb.append(WIDGET_PREFIX);
296 sb.append(((AppWidgetProviderInfo) o).provider.flattenToString());
297 output = sb.toString();
298 sb.setLength(0);
299 } else {
300 sb.append(SHORTCUT_PREFIX);
301
302 ResolveInfo info = (ResolveInfo) o;
303 sb.append(new ComponentName(info.activityInfo.packageName,
304 info.activityInfo.name).flattenToString());
305 output = sb.toString();
306 sb.setLength(0);
307 }
308 return output;
309 }
310
311 private String getObjectPackage(Object o) {
312 if (o instanceof AppWidgetProviderInfo) {
313 return ((AppWidgetProviderInfo) o).provider.getPackageName();
314 } else {
315 ResolveInfo info = (ResolveInfo) o;
316 return info.activityInfo.packageName;
317 }
318 }
319
320 private void writeToDb(Object o, Bitmap preview) {
321 String name = getObjectName(o);
322 SQLiteDatabase db = mDb.getWritableDatabase();
323 ContentValues values = new ContentValues();
324
325 values.put(WidgetPreviewCacheDb.COLUMN_NAME, name);
326 ByteArrayOutputStream stream = new ByteArrayOutputStream();
327 preview.compress(Bitmap.CompressFormat.PNG, 100, stream);
328 values.put(WidgetPreviewCacheDb.COLUMN_PREVIEW_BITMAP, stream.toByteArray());
329 values.put(WidgetPreviewCacheDb.COLUMN_SIZE, mSize);
330 db.insert(WidgetPreviewCacheDb.TABLE_NAME, null, values);
331 }
332
333 public static void removeFromDb(final Context mContext, final String packageName) {
334 synchronized(sInvalidPackages) {
335 sInvalidPackages.add(packageName);
336 }
337 new AsyncTask<Void, Void, Void>() {
338 public Void doInBackground(Void ... args) {
339 SQLiteDatabase db = new WidgetPreviewCacheDb(mContext).getWritableDatabase();
340 db.delete(WidgetPreviewCacheDb.TABLE_NAME,
341 WidgetPreviewCacheDb.COLUMN_NAME + " LIKE ? OR " +
342 WidgetPreviewCacheDb.COLUMN_NAME + " LIKE ?", // SELECT query
343 new String[] {
344 WIDGET_PREFIX + packageName + "/%",
345 SHORTCUT_PREFIX + packageName + "/%"} // args to SELECT query
346 );
347 db.close();
348 synchronized(sInvalidPackages) {
349 sInvalidPackages.remove(packageName);
350 }
351 return null;
352 }
353 }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
354 }
355
Michael Jurka0247d142013-02-06 14:11:22 +0100356 public void closeDb() {
357 if (mDb != null) {
358 mDb.close();
359 }
360 }
361
Michael Jurka05713af2013-01-23 12:39:24 +0100362 private Bitmap readFromDb(String name, Bitmap b) {
363 if (mCachedSelectQuery == null) {
364 mCachedSelectQuery = WidgetPreviewCacheDb.COLUMN_NAME + " = ? AND " +
365 WidgetPreviewCacheDb.COLUMN_SIZE + " = ?";
366 }
367 SQLiteDatabase db = mDb.getReadableDatabase();
368 Cursor result = db.query(WidgetPreviewCacheDb.TABLE_NAME,
369 new String[] { WidgetPreviewCacheDb.COLUMN_PREVIEW_BITMAP }, // cols to return
370 mCachedSelectQuery, // select query
371 new String[] { name, mSize }, // args to select query
372 null,
373 null,
374 null,
375 null);
376 if (result.getCount() > 0) {
377 result.moveToFirst();
378 byte[] blob = result.getBlob(0);
379 result.close();
380 final BitmapFactory.Options opts = mCachedBitmapFactoryOptions.get();
381 opts.inBitmap = b;
382 opts.inSampleSize = 1;
383 Bitmap out = BitmapFactory.decodeByteArray(blob, 0, blob.length, opts);
384 return out;
385 } else {
386 result.close();
387 return null;
388 }
389 }
390
391 public Bitmap generatePreview(Object info, Bitmap preview) {
392 if (preview != null &&
Michael Jurka3f4e0702013-02-05 11:21:28 +0100393 (preview.getWidth() != mPreviewBitmapWidth ||
394 preview.getHeight() != mPreviewBitmapHeight)) {
Michael Jurka05713af2013-01-23 12:39:24 +0100395 throw new RuntimeException("Improperly sized bitmap passed as argument");
396 }
397 if (info instanceof AppWidgetProviderInfo) {
398 return generateWidgetPreview((AppWidgetProviderInfo) info, preview);
399 } else {
400 return generateShortcutPreview(
Michael Jurka3f4e0702013-02-05 11:21:28 +0100401 (ResolveInfo) info, mPreviewBitmapWidth, mPreviewBitmapHeight, preview);
Michael Jurka05713af2013-01-23 12:39:24 +0100402 }
403 }
404
405 public Bitmap generateWidgetPreview(AppWidgetProviderInfo info, Bitmap preview) {
406 // should just read what's in the DB, and return it
407 // what's the method that's used?
408 // going to have to track down more or less how the DB stuff works
409 // when you long click on something, we're going to have to load the bigger preview at that
410 // time (worry about it later)
411 int[] cellSpans = Launcher.getSpanForWidget(mLauncher, info);
412 int maxWidth = maxWidthForWidgetPreview(cellSpans[0]);
413 int maxHeight = maxHeightForWidgetPreview(cellSpans[1]);
414 return generateWidgetPreview(info.provider, info.previewImage, info.icon,
415 cellSpans[0], cellSpans[1], maxWidth, maxHeight, preview, null);
416 }
417
418 public int maxWidthForWidgetPreview(int spanX) {
Michael Jurka3f4e0702013-02-05 11:21:28 +0100419 return Math.min(mPreviewBitmapWidth,
Michael Jurka05713af2013-01-23 12:39:24 +0100420 mWidgetSpacingLayout.estimateCellWidth(spanX));
421 }
422
423 public int maxHeightForWidgetPreview(int spanY) {
Michael Jurka3f4e0702013-02-05 11:21:28 +0100424 return Math.min(mPreviewBitmapHeight,
Michael Jurka05713af2013-01-23 12:39:24 +0100425 mWidgetSpacingLayout.estimateCellHeight(spanY));
426 }
427
428 public Bitmap generateWidgetPreview(ComponentName provider, int previewImage,
429 int iconId, int cellHSpan, int cellVSpan, int maxPreviewWidth, int maxPreviewHeight,
430 Bitmap preview, int[] preScaledWidthOut) {
431 // Load the preview image if possible
432 String packageName = provider.getPackageName();
433 if (maxPreviewWidth < 0) maxPreviewWidth = Integer.MAX_VALUE;
434 if (maxPreviewHeight < 0) maxPreviewHeight = Integer.MAX_VALUE;
435
436 Drawable drawable = null;
437 if (previewImage != 0) {
438 drawable = mPackageManager.getDrawable(packageName, previewImage, null);
439 if (drawable == null) {
440 Log.w(TAG, "Can't load widget preview drawable 0x" +
441 Integer.toHexString(previewImage) + " for provider: " + provider);
442 }
443 }
444
445 int previewWidth;
446 int previewHeight;
447 Bitmap defaultPreview = null;
448 boolean widgetPreviewExists = (drawable != null);
449 if (widgetPreviewExists) {
450 previewWidth = drawable.getIntrinsicWidth();
451 previewHeight = drawable.getIntrinsicHeight();
452 } else {
453 // Generate a preview image if we couldn't load one
454 if (cellHSpan < 1) cellHSpan = 1;
455 if (cellVSpan < 1) cellVSpan = 1;
456
457 BitmapDrawable previewDrawable = (BitmapDrawable) mContext.getResources()
458 .getDrawable(R.drawable.widget_preview_tile);
459 final int previewDrawableWidth = previewDrawable
460 .getIntrinsicWidth();
461 final int previewDrawableHeight = previewDrawable
462 .getIntrinsicHeight();
463 previewWidth = previewDrawableWidth * cellHSpan; // subtract 2 dips
464 previewHeight = previewDrawableHeight * cellVSpan;
465
466 defaultPreview = Bitmap.createBitmap(previewWidth, previewHeight,
467 Config.ARGB_8888);
468 final Canvas c = mCachedAppWidgetPreviewCanvas.get();
469 c.setBitmap(defaultPreview);
470 previewDrawable.setBounds(0, 0, previewWidth, previewHeight);
471 previewDrawable.setTileModeXY(Shader.TileMode.REPEAT,
472 Shader.TileMode.REPEAT);
473 previewDrawable.draw(c);
474 c.setBitmap(null);
475
476 // Draw the icon in the top left corner
477 int minOffset = (int) (mAppIconSize * sWidgetPreviewIconPaddingPercentage);
478 int smallestSide = Math.min(previewWidth, previewHeight);
479 float iconScale = Math.min((float) smallestSide
480 / (mAppIconSize + 2 * minOffset), 1f);
481
482 try {
483 Drawable icon = null;
484 int hoffset =
485 (int) ((previewDrawableWidth - mAppIconSize * iconScale) / 2);
486 int yoffset =
487 (int) ((previewDrawableHeight - mAppIconSize * iconScale) / 2);
488 if (iconId > 0)
489 icon = mIconCache.getFullResIcon(packageName, iconId);
490 if (icon != null) {
491 renderDrawableToBitmap(icon, defaultPreview, hoffset,
492 yoffset, (int) (mAppIconSize * iconScale),
493 (int) (mAppIconSize * iconScale));
494 }
495 } catch (Resources.NotFoundException e) {
496 }
497 }
498
499 // Scale to fit width only - let the widget preview be clipped in the
500 // vertical dimension
501 float scale = 1f;
502 if (preScaledWidthOut != null) {
503 preScaledWidthOut[0] = previewWidth;
504 }
505 if (previewWidth > maxPreviewWidth) {
506 scale = maxPreviewWidth / (float) previewWidth;
507 }
508 if (scale != 1f) {
509 previewWidth = (int) (scale * previewWidth);
510 previewHeight = (int) (scale * previewHeight);
511 }
512
513 // If a bitmap is passed in, we use it; otherwise, we create a bitmap of the right size
514 if (preview == null) {
515 preview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
516 }
517
518 // Draw the scaled preview into the final bitmap
519 int x = (preview.getWidth() - previewWidth) / 2;
520 if (widgetPreviewExists) {
521 renderDrawableToBitmap(drawable, preview, x, 0, previewWidth,
522 previewHeight);
523 } else {
524 final Canvas c = mCachedAppWidgetPreviewCanvas.get();
525 final Rect src = mCachedAppWidgetPreviewSrcRect.get();
526 final Rect dest = mCachedAppWidgetPreviewDestRect.get();
527 c.setBitmap(preview);
528 src.set(0, 0, defaultPreview.getWidth(), defaultPreview.getHeight());
529 dest.set(x, 0, previewWidth, previewHeight);
530
531 Paint p = mCachedAppWidgetPreviewPaint.get();
532 if (p == null) {
533 p = new Paint();
534 p.setFilterBitmap(true);
535 mCachedAppWidgetPreviewPaint.set(p);
536 }
537 c.drawBitmap(defaultPreview, src, dest, p);
538 c.setBitmap(null);
539 }
540 return preview;
541 }
542
543 private Bitmap generateShortcutPreview(
544 ResolveInfo info, int maxWidth, int maxHeight, Bitmap preview) {
545 Bitmap tempBitmap = mCachedShortcutPreviewBitmap.get();
546 final Canvas c = mCachedShortcutPreviewCanvas.get();
547 if (tempBitmap == null ||
548 tempBitmap.getWidth() != maxWidth ||
549 tempBitmap.getHeight() != maxHeight) {
550 tempBitmap = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
551 mCachedShortcutPreviewBitmap.set(tempBitmap);
552 } else {
553 c.setBitmap(tempBitmap);
554 c.drawColor(0, PorterDuff.Mode.CLEAR);
555 c.setBitmap(null);
556 }
557 // Render the icon
558 Drawable icon = mIconCache.getFullResIcon(info);
559
560 int paddingTop = mContext.
561 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_top);
562 int paddingLeft = mContext.
563 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_left);
564 int paddingRight = mContext.
565 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_right);
566
567 int scaledIconWidth = (maxWidth - paddingLeft - paddingRight);
568
569 renderDrawableToBitmap(
570 icon, tempBitmap, paddingLeft, paddingTop, scaledIconWidth, scaledIconWidth);
571
572 if (preview != null &&
573 (preview.getWidth() != maxWidth || preview.getHeight() != maxHeight)) {
574 throw new RuntimeException("Improperly sized bitmap passed as argument");
575 } else if (preview == null) {
576 preview = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
577 }
578
579 c.setBitmap(preview);
580 // Draw a desaturated/scaled version of the icon in the background as a watermark
581 Paint p = mCachedShortcutPreviewPaint.get();
582 if (p == null) {
583 p = new Paint();
584 ColorMatrix colorMatrix = new ColorMatrix();
585 colorMatrix.setSaturation(0);
586 p.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
587 p.setAlpha((int) (255 * 0.06f));
588 mCachedShortcutPreviewPaint.set(p);
589 }
590 c.drawBitmap(tempBitmap, 0, 0, p);
591 c.setBitmap(null);
592
593 renderDrawableToBitmap(icon, preview, 0, 0, mAppIconSize, mAppIconSize);
594
595 return preview;
596 }
597
598
599 public static void renderDrawableToBitmap(
600 Drawable d, Bitmap bitmap, int x, int y, int w, int h) {
601 renderDrawableToBitmap(d, bitmap, x, y, w, h, 1f);
602 }
603
604 private static void renderDrawableToBitmap(
605 Drawable d, Bitmap bitmap, int x, int y, int w, int h,
606 float scale) {
607 if (bitmap != null) {
608 Canvas c = new Canvas(bitmap);
609 c.scale(scale, scale);
610 Rect oldBounds = d.copyBounds();
611 d.setBounds(x, y, x + w, y + h);
612 d.draw(c);
613 d.setBounds(oldBounds); // Restore the bounds
614 c.setBitmap(null);
615 }
616 }
617
618}