blob: 5ce3233779ea24eda1f67ae3261d02e2b57ac51b [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
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100132 private CacheDb mDb;
Michael Jurka05713af2013-01-23 12:39:24 +0100133
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);
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100146 LauncherApplication app = (LauncherApplication) launcher.getApplicationContext();
147 mIconCache = app.getIconCache();
148 mDb = app.getWidgetPreviewCacheDb();
Michael Jurka3f4e0702013-02-05 11:21:28 +0100149 mLoadedPreviews = new HashMap<String, WeakReference<Bitmap>>();
150 mUnusedBitmaps = new ArrayList<SoftReference<Bitmap>>();
151 }
152
153 public void setPreviewSize(int previewWidth, int previewHeight,
154 PagedViewCellLayout widgetSpacingLayout) {
155 mPreviewBitmapWidth = previewWidth;
156 mPreviewBitmapHeight = previewHeight;
157 mSize = previewWidth + "x" + previewHeight;
158 mWidgetSpacingLayout = widgetSpacingLayout;
Michael Jurka05713af2013-01-23 12:39:24 +0100159 }
160
161 public Bitmap getPreview(final Object o) {
162 String name = getObjectName(o);
163 // check if the package is valid
164 boolean packageValid = true;
165 synchronized(sInvalidPackages) {
166 packageValid = !sInvalidPackages.contains(getObjectPackage(o));
167 }
168 if (!packageValid) {
169 return null;
170 }
171 if (packageValid) {
Michael Jurka3f4e0702013-02-05 11:21:28 +0100172 synchronized(mLoadedPreviews) {
Michael Jurka05713af2013-01-23 12:39:24 +0100173 // check if it exists in our existing cache
Michael Jurka3f4e0702013-02-05 11:21:28 +0100174 if (mLoadedPreviews.containsKey(name) && mLoadedPreviews.get(name).get() != null) {
175 return mLoadedPreviews.get(name).get();
Michael Jurka05713af2013-01-23 12:39:24 +0100176 }
177 }
178 }
179
180 Bitmap unusedBitmap = null;
Michael Jurka3f4e0702013-02-05 11:21:28 +0100181 synchronized(mUnusedBitmaps) {
Michael Jurka05713af2013-01-23 12:39:24 +0100182 // not in cache; we need to load it from the db
Michael Jurka3f4e0702013-02-05 11:21:28 +0100183 while ((unusedBitmap == null || !unusedBitmap.isMutable() ||
184 unusedBitmap.getWidth() != mPreviewBitmapWidth ||
185 unusedBitmap.getHeight() != mPreviewBitmapHeight)
186 && mUnusedBitmaps.size() > 0) {
187 unusedBitmap = mUnusedBitmaps.remove(0).get();
Michael Jurka05713af2013-01-23 12:39:24 +0100188 }
189 if (unusedBitmap != null) {
190 final Canvas c = mCachedAppWidgetPreviewCanvas.get();
191 c.setBitmap(unusedBitmap);
192 c.drawColor(0, PorterDuff.Mode.CLEAR);
193 c.setBitmap(null);
194 }
195 }
196
197 if (unusedBitmap == null) {
Michael Jurka3f4e0702013-02-05 11:21:28 +0100198 unusedBitmap = Bitmap.createBitmap(mPreviewBitmapWidth, mPreviewBitmapHeight,
Michael Jurka05713af2013-01-23 12:39:24 +0100199 Bitmap.Config.ARGB_8888);
200 }
201
202 Bitmap preview = null;
203
204 if (packageValid) {
205 preview = readFromDb(name, unusedBitmap);
206 }
207
208 if (preview != null) {
Michael Jurka3f4e0702013-02-05 11:21:28 +0100209 synchronized(mLoadedPreviews) {
210 mLoadedPreviews.put(name, new WeakReference<Bitmap>(preview));
Michael Jurka05713af2013-01-23 12:39:24 +0100211 }
212 return preview;
213 } else {
214 // it's not in the db... we need to generate it
215 final Bitmap generatedPreview = generatePreview(o, unusedBitmap);
216 preview = generatedPreview;
217 if (preview != unusedBitmap) {
218 throw new RuntimeException("generatePreview is not recycling the bitmap " + o);
219 }
220
Michael Jurka3f4e0702013-02-05 11:21:28 +0100221 synchronized(mLoadedPreviews) {
222 mLoadedPreviews.put(name, new WeakReference<Bitmap>(preview));
Michael Jurka05713af2013-01-23 12:39:24 +0100223 }
224
225 // write to db on a thread pool... this can be done lazily and improves the performance
226 // of the first time widget previews are loaded
227 new AsyncTask<Void, Void, Void>() {
228 public Void doInBackground(Void ... args) {
229 writeToDb(o, generatedPreview);
230 return null;
231 }
232 }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
233
234 return preview;
235 }
236 }
237
Michael Jurkaee8e99f2013-02-07 13:27:06 +0100238 public void recycleBitmap(Object o, Bitmap bitmapToRecycle) {
Michael Jurka05713af2013-01-23 12:39:24 +0100239 String name = getObjectName(o);
Michael Jurka5140cfa2013-02-15 14:50:15 +0100240 synchronized (mLoadedPreviews) {
241 if (mLoadedPreviews.containsKey(name)) {
Michael Jurka3f4e0702013-02-05 11:21:28 +0100242 Bitmap b = mLoadedPreviews.get(name).get();
Michael Jurkaee8e99f2013-02-07 13:27:06 +0100243 if (b == bitmapToRecycle) {
Michael Jurka3f4e0702013-02-05 11:21:28 +0100244 mLoadedPreviews.remove(name);
Michael Jurkaee8e99f2013-02-07 13:27:06 +0100245 if (bitmapToRecycle.isMutable()) {
Michael Jurka5140cfa2013-02-15 14:50:15 +0100246 synchronized (mUnusedBitmaps) {
247 mUnusedBitmaps.add(new SoftReference<Bitmap>(b));
248 }
Michael Jurka05713af2013-01-23 12:39:24 +0100249 }
250 } else {
251 throw new RuntimeException("Bitmap passed in doesn't match up");
252 }
253 }
254 }
255 }
256
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100257 static class CacheDb extends SQLiteOpenHelper {
Michael Jurkae5919c52013-03-06 17:30:10 +0100258 final static int DB_VERSION = 2;
Michael Jurka05713af2013-01-23 12:39:24 +0100259 final static String DB_NAME = "widgetpreviews.db";
260 final static String TABLE_NAME = "shortcut_and_widget_previews";
261 final static String COLUMN_NAME = "name";
262 final static String COLUMN_SIZE = "size";
263 final static String COLUMN_PREVIEW_BITMAP = "preview_bitmap";
264 Context mContext;
265
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100266 public CacheDb(Context context) {
Michael Jurka05713af2013-01-23 12:39:24 +0100267 super(context, new File(context.getCacheDir(), DB_NAME).getPath(), null, DB_VERSION);
268 // Store the context for later use
269 mContext = context;
270 }
271
272 @Override
273 public void onCreate(SQLiteDatabase database) {
Michael Jurka32b7a092013-02-07 20:06:49 +0100274 database.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" +
Michael Jurka05713af2013-01-23 12:39:24 +0100275 COLUMN_NAME + " TEXT NOT NULL, " +
276 COLUMN_SIZE + " TEXT NOT NULL, " +
277 COLUMN_PREVIEW_BITMAP + " BLOB NOT NULL, " +
278 "PRIMARY KEY (" + COLUMN_NAME + ", " + COLUMN_SIZE + ") " +
Michael Jurka32b7a092013-02-07 20:06:49 +0100279 ");");
Michael Jurka05713af2013-01-23 12:39:24 +0100280 }
281
282 @Override
283 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Michael Jurkae5919c52013-03-06 17:30:10 +0100284 if (oldVersion != newVersion) {
285 // Delete all the records; they'll be repopulated as this is a cache
286 db.execSQL("DELETE FROM " + TABLE_NAME);
287 }
Michael Jurka05713af2013-01-23 12:39:24 +0100288 }
289 }
290
291 private static final String WIDGET_PREFIX = "Widget:";
292 private static final String SHORTCUT_PREFIX = "Shortcut:";
293
294 private static String getObjectName(Object o) {
295 // should cache the string builder
296 StringBuilder sb = new StringBuilder();
297 String output;
298 if (o instanceof AppWidgetProviderInfo) {
299 sb.append(WIDGET_PREFIX);
300 sb.append(((AppWidgetProviderInfo) o).provider.flattenToString());
301 output = sb.toString();
302 sb.setLength(0);
303 } else {
304 sb.append(SHORTCUT_PREFIX);
305
306 ResolveInfo info = (ResolveInfo) o;
307 sb.append(new ComponentName(info.activityInfo.packageName,
308 info.activityInfo.name).flattenToString());
309 output = sb.toString();
310 sb.setLength(0);
311 }
312 return output;
313 }
314
315 private String getObjectPackage(Object o) {
316 if (o instanceof AppWidgetProviderInfo) {
317 return ((AppWidgetProviderInfo) o).provider.getPackageName();
318 } else {
319 ResolveInfo info = (ResolveInfo) o;
320 return info.activityInfo.packageName;
321 }
322 }
323
324 private void writeToDb(Object o, Bitmap preview) {
325 String name = getObjectName(o);
326 SQLiteDatabase db = mDb.getWritableDatabase();
327 ContentValues values = new ContentValues();
328
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100329 values.put(CacheDb.COLUMN_NAME, name);
Michael Jurka05713af2013-01-23 12:39:24 +0100330 ByteArrayOutputStream stream = new ByteArrayOutputStream();
331 preview.compress(Bitmap.CompressFormat.PNG, 100, stream);
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100332 values.put(CacheDb.COLUMN_PREVIEW_BITMAP, stream.toByteArray());
333 values.put(CacheDb.COLUMN_SIZE, mSize);
334 db.insert(CacheDb.TABLE_NAME, null, values);
Michael Jurka05713af2013-01-23 12:39:24 +0100335 }
336
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100337 public static void removeFromDb(final CacheDb cacheDb, final String packageName) {
Michael Jurka05713af2013-01-23 12:39:24 +0100338 synchronized(sInvalidPackages) {
339 sInvalidPackages.add(packageName);
340 }
341 new AsyncTask<Void, Void, Void>() {
342 public Void doInBackground(Void ... args) {
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100343 SQLiteDatabase db = cacheDb.getWritableDatabase();
344 db.delete(CacheDb.TABLE_NAME,
345 CacheDb.COLUMN_NAME + " LIKE ? OR " +
346 CacheDb.COLUMN_NAME + " LIKE ?", // SELECT query
Michael Jurka05713af2013-01-23 12:39:24 +0100347 new String[] {
348 WIDGET_PREFIX + packageName + "/%",
349 SHORTCUT_PREFIX + packageName + "/%"} // args to SELECT query
350 );
351 db.close();
352 synchronized(sInvalidPackages) {
353 sInvalidPackages.remove(packageName);
354 }
355 return null;
356 }
357 }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
358 }
359
Michael Jurka0247d142013-02-06 14:11:22 +0100360 public void closeDb() {
361 if (mDb != null) {
362 mDb.close();
363 }
364 }
365
Michael Jurka05713af2013-01-23 12:39:24 +0100366 private Bitmap readFromDb(String name, Bitmap b) {
367 if (mCachedSelectQuery == null) {
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100368 mCachedSelectQuery = CacheDb.COLUMN_NAME + " = ? AND " +
369 CacheDb.COLUMN_SIZE + " = ?";
Michael Jurka05713af2013-01-23 12:39:24 +0100370 }
371 SQLiteDatabase db = mDb.getReadableDatabase();
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100372 Cursor result = db.query(CacheDb.TABLE_NAME,
373 new String[] { CacheDb.COLUMN_PREVIEW_BITMAP }, // cols to return
Michael Jurka05713af2013-01-23 12:39:24 +0100374 mCachedSelectQuery, // select query
375 new String[] { name, mSize }, // args to select query
376 null,
377 null,
378 null,
379 null);
380 if (result.getCount() > 0) {
381 result.moveToFirst();
382 byte[] blob = result.getBlob(0);
383 result.close();
384 final BitmapFactory.Options opts = mCachedBitmapFactoryOptions.get();
385 opts.inBitmap = b;
386 opts.inSampleSize = 1;
387 Bitmap out = BitmapFactory.decodeByteArray(blob, 0, blob.length, opts);
388 return out;
389 } else {
390 result.close();
391 return null;
392 }
393 }
394
395 public Bitmap generatePreview(Object info, Bitmap preview) {
396 if (preview != null &&
Michael Jurka3f4e0702013-02-05 11:21:28 +0100397 (preview.getWidth() != mPreviewBitmapWidth ||
398 preview.getHeight() != mPreviewBitmapHeight)) {
Michael Jurka05713af2013-01-23 12:39:24 +0100399 throw new RuntimeException("Improperly sized bitmap passed as argument");
400 }
401 if (info instanceof AppWidgetProviderInfo) {
402 return generateWidgetPreview((AppWidgetProviderInfo) info, preview);
403 } else {
404 return generateShortcutPreview(
Michael Jurka3f4e0702013-02-05 11:21:28 +0100405 (ResolveInfo) info, mPreviewBitmapWidth, mPreviewBitmapHeight, preview);
Michael Jurka05713af2013-01-23 12:39:24 +0100406 }
407 }
408
409 public Bitmap generateWidgetPreview(AppWidgetProviderInfo info, Bitmap preview) {
Michael Jurka05713af2013-01-23 12:39:24 +0100410 int[] cellSpans = Launcher.getSpanForWidget(mLauncher, info);
411 int maxWidth = maxWidthForWidgetPreview(cellSpans[0]);
412 int maxHeight = maxHeightForWidgetPreview(cellSpans[1]);
413 return generateWidgetPreview(info.provider, info.previewImage, info.icon,
414 cellSpans[0], cellSpans[1], maxWidth, maxHeight, preview, null);
415 }
416
417 public int maxWidthForWidgetPreview(int spanX) {
Michael Jurka3f4e0702013-02-05 11:21:28 +0100418 return Math.min(mPreviewBitmapWidth,
Michael Jurka05713af2013-01-23 12:39:24 +0100419 mWidgetSpacingLayout.estimateCellWidth(spanX));
420 }
421
422 public int maxHeightForWidgetPreview(int spanY) {
Michael Jurka3f4e0702013-02-05 11:21:28 +0100423 return Math.min(mPreviewBitmapHeight,
Michael Jurka05713af2013-01-23 12:39:24 +0100424 mWidgetSpacingLayout.estimateCellHeight(spanY));
425 }
426
427 public Bitmap generateWidgetPreview(ComponentName provider, int previewImage,
428 int iconId, int cellHSpan, int cellVSpan, int maxPreviewWidth, int maxPreviewHeight,
429 Bitmap preview, int[] preScaledWidthOut) {
430 // Load the preview image if possible
431 String packageName = provider.getPackageName();
432 if (maxPreviewWidth < 0) maxPreviewWidth = Integer.MAX_VALUE;
433 if (maxPreviewHeight < 0) maxPreviewHeight = Integer.MAX_VALUE;
434
435 Drawable drawable = null;
436 if (previewImage != 0) {
437 drawable = mPackageManager.getDrawable(packageName, previewImage, null);
438 if (drawable == null) {
439 Log.w(TAG, "Can't load widget preview drawable 0x" +
440 Integer.toHexString(previewImage) + " for provider: " + provider);
441 }
442 }
443
444 int previewWidth;
445 int previewHeight;
446 Bitmap defaultPreview = null;
447 boolean widgetPreviewExists = (drawable != null);
448 if (widgetPreviewExists) {
449 previewWidth = drawable.getIntrinsicWidth();
450 previewHeight = drawable.getIntrinsicHeight();
451 } else {
452 // Generate a preview image if we couldn't load one
453 if (cellHSpan < 1) cellHSpan = 1;
454 if (cellVSpan < 1) cellVSpan = 1;
455
456 BitmapDrawable previewDrawable = (BitmapDrawable) mContext.getResources()
457 .getDrawable(R.drawable.widget_preview_tile);
458 final int previewDrawableWidth = previewDrawable
459 .getIntrinsicWidth();
460 final int previewDrawableHeight = previewDrawable
461 .getIntrinsicHeight();
462 previewWidth = previewDrawableWidth * cellHSpan; // subtract 2 dips
463 previewHeight = previewDrawableHeight * cellVSpan;
464
465 defaultPreview = Bitmap.createBitmap(previewWidth, previewHeight,
466 Config.ARGB_8888);
467 final Canvas c = mCachedAppWidgetPreviewCanvas.get();
468 c.setBitmap(defaultPreview);
469 previewDrawable.setBounds(0, 0, previewWidth, previewHeight);
470 previewDrawable.setTileModeXY(Shader.TileMode.REPEAT,
471 Shader.TileMode.REPEAT);
472 previewDrawable.draw(c);
473 c.setBitmap(null);
474
475 // Draw the icon in the top left corner
476 int minOffset = (int) (mAppIconSize * sWidgetPreviewIconPaddingPercentage);
477 int smallestSide = Math.min(previewWidth, previewHeight);
478 float iconScale = Math.min((float) smallestSide
479 / (mAppIconSize + 2 * minOffset), 1f);
480
481 try {
482 Drawable icon = null;
483 int hoffset =
484 (int) ((previewDrawableWidth - mAppIconSize * iconScale) / 2);
485 int yoffset =
486 (int) ((previewDrawableHeight - mAppIconSize * iconScale) / 2);
487 if (iconId > 0)
488 icon = mIconCache.getFullResIcon(packageName, iconId);
489 if (icon != null) {
490 renderDrawableToBitmap(icon, defaultPreview, hoffset,
491 yoffset, (int) (mAppIconSize * iconScale),
492 (int) (mAppIconSize * iconScale));
493 }
494 } catch (Resources.NotFoundException e) {
495 }
496 }
497
498 // Scale to fit width only - let the widget preview be clipped in the
499 // vertical dimension
500 float scale = 1f;
501 if (preScaledWidthOut != null) {
502 preScaledWidthOut[0] = previewWidth;
503 }
504 if (previewWidth > maxPreviewWidth) {
505 scale = maxPreviewWidth / (float) previewWidth;
506 }
507 if (scale != 1f) {
508 previewWidth = (int) (scale * previewWidth);
509 previewHeight = (int) (scale * previewHeight);
510 }
511
512 // If a bitmap is passed in, we use it; otherwise, we create a bitmap of the right size
513 if (preview == null) {
514 preview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
515 }
516
517 // Draw the scaled preview into the final bitmap
518 int x = (preview.getWidth() - previewWidth) / 2;
519 if (widgetPreviewExists) {
520 renderDrawableToBitmap(drawable, preview, x, 0, previewWidth,
521 previewHeight);
522 } else {
523 final Canvas c = mCachedAppWidgetPreviewCanvas.get();
524 final Rect src = mCachedAppWidgetPreviewSrcRect.get();
525 final Rect dest = mCachedAppWidgetPreviewDestRect.get();
526 c.setBitmap(preview);
527 src.set(0, 0, defaultPreview.getWidth(), defaultPreview.getHeight());
Michael Jurkae5919c52013-03-06 17:30:10 +0100528 dest.set(x, 0, x + previewWidth, previewHeight);
Michael Jurka05713af2013-01-23 12:39:24 +0100529
530 Paint p = mCachedAppWidgetPreviewPaint.get();
531 if (p == null) {
532 p = new Paint();
533 p.setFilterBitmap(true);
534 mCachedAppWidgetPreviewPaint.set(p);
535 }
536 c.drawBitmap(defaultPreview, src, dest, p);
537 c.setBitmap(null);
538 }
539 return preview;
540 }
541
542 private Bitmap generateShortcutPreview(
543 ResolveInfo info, int maxWidth, int maxHeight, Bitmap preview) {
544 Bitmap tempBitmap = mCachedShortcutPreviewBitmap.get();
545 final Canvas c = mCachedShortcutPreviewCanvas.get();
546 if (tempBitmap == null ||
547 tempBitmap.getWidth() != maxWidth ||
548 tempBitmap.getHeight() != maxHeight) {
549 tempBitmap = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
550 mCachedShortcutPreviewBitmap.set(tempBitmap);
551 } else {
552 c.setBitmap(tempBitmap);
553 c.drawColor(0, PorterDuff.Mode.CLEAR);
554 c.setBitmap(null);
555 }
556 // Render the icon
557 Drawable icon = mIconCache.getFullResIcon(info);
558
559 int paddingTop = mContext.
560 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_top);
561 int paddingLeft = mContext.
562 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_left);
563 int paddingRight = mContext.
564 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_right);
565
566 int scaledIconWidth = (maxWidth - paddingLeft - paddingRight);
567
568 renderDrawableToBitmap(
569 icon, tempBitmap, paddingLeft, paddingTop, scaledIconWidth, scaledIconWidth);
570
571 if (preview != null &&
572 (preview.getWidth() != maxWidth || preview.getHeight() != maxHeight)) {
573 throw new RuntimeException("Improperly sized bitmap passed as argument");
574 } else if (preview == null) {
575 preview = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
576 }
577
578 c.setBitmap(preview);
579 // Draw a desaturated/scaled version of the icon in the background as a watermark
580 Paint p = mCachedShortcutPreviewPaint.get();
581 if (p == null) {
582 p = new Paint();
583 ColorMatrix colorMatrix = new ColorMatrix();
584 colorMatrix.setSaturation(0);
585 p.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
586 p.setAlpha((int) (255 * 0.06f));
587 mCachedShortcutPreviewPaint.set(p);
588 }
589 c.drawBitmap(tempBitmap, 0, 0, p);
590 c.setBitmap(null);
591
592 renderDrawableToBitmap(icon, preview, 0, 0, mAppIconSize, mAppIconSize);
593
594 return preview;
595 }
596
597
598 public static void renderDrawableToBitmap(
599 Drawable d, Bitmap bitmap, int x, int y, int w, int h) {
600 renderDrawableToBitmap(d, bitmap, x, y, w, h, 1f);
601 }
602
603 private static void renderDrawableToBitmap(
604 Drawable d, Bitmap bitmap, int x, int y, int w, int h,
605 float scale) {
606 if (bitmap != null) {
607 Canvas c = new Canvas(bitmap);
608 c.scale(scale, scale);
609 Rect oldBounds = d.copyBounds();
610 d.setBounds(x, y, x + w, y + h);
611 d.draw(c);
612 d.setBounds(oldBounds); // Restore the bounds
613 c.setBitmap(null);
614 }
615 }
616
617}