blob: b1bb1e85571d897fdb5d3d72651dc93f967cf088 [file] [log] [blame]
Daniel Sandler325dc232013-06-05 22:57:57 -04001package com.android.launcher3;
Michael Jurka05713af2013-01-23 12:39:24 +01002
3import android.appwidget.AppWidgetProviderInfo;
4import android.content.ComponentName;
5import android.content.ContentValues;
6import android.content.Context;
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
Michael Jurka05713af2013-01-23 12:39:24 +010028import java.io.ByteArrayOutputStream;
29import java.io.File;
30import java.lang.ref.SoftReference;
31import java.lang.ref.WeakReference;
32import java.util.ArrayList;
33import java.util.HashMap;
34import java.util.HashSet;
35
36abstract class SoftReferenceThreadLocal<T> {
37 private ThreadLocal<SoftReference<T>> mThreadLocal;
38 public SoftReferenceThreadLocal() {
39 mThreadLocal = new ThreadLocal<SoftReference<T>>();
40 }
41
42 abstract T initialValue();
43
44 public void set(T t) {
45 mThreadLocal.set(new SoftReference<T>(t));
46 }
47
48 public T get() {
49 SoftReference<T> reference = mThreadLocal.get();
50 T obj;
51 if (reference == null) {
52 obj = initialValue();
53 mThreadLocal.set(new SoftReference<T>(obj));
54 return obj;
55 } else {
56 obj = reference.get();
57 if (obj == null) {
58 obj = initialValue();
59 mThreadLocal.set(new SoftReference<T>(obj));
60 }
61 return obj;
62 }
63 }
64}
65
66class CanvasCache extends SoftReferenceThreadLocal<Canvas> {
67 @Override
68 protected Canvas initialValue() {
69 return new Canvas();
70 }
71}
72
73class PaintCache extends SoftReferenceThreadLocal<Paint> {
74 @Override
75 protected Paint initialValue() {
76 return null;
77 }
78}
79
80class BitmapCache extends SoftReferenceThreadLocal<Bitmap> {
81 @Override
82 protected Bitmap initialValue() {
83 return null;
84 }
85}
86
87class RectCache extends SoftReferenceThreadLocal<Rect> {
88 @Override
89 protected Rect initialValue() {
90 return new Rect();
91 }
92}
93
94class BitmapFactoryOptionsCache extends SoftReferenceThreadLocal<BitmapFactory.Options> {
95 @Override
96 protected BitmapFactory.Options initialValue() {
97 return new BitmapFactory.Options();
98 }
99}
100
101public class WidgetPreviewLoader {
102 static final String TAG = "WidgetPreviewLoader";
103
Michael Jurka3f4e0702013-02-05 11:21:28 +0100104 private int mPreviewBitmapWidth;
105 private int mPreviewBitmapHeight;
Michael Jurka05713af2013-01-23 12:39:24 +0100106 private String mSize;
107 private Context mContext;
108 private Launcher mLauncher;
109 private PackageManager mPackageManager;
110 private PagedViewCellLayout mWidgetSpacingLayout;
111
112 // Used for drawing shortcut previews
113 private BitmapCache mCachedShortcutPreviewBitmap = new BitmapCache();
114 private PaintCache mCachedShortcutPreviewPaint = new PaintCache();
115 private CanvasCache mCachedShortcutPreviewCanvas = new CanvasCache();
116
117 // Used for drawing widget previews
118 private CanvasCache mCachedAppWidgetPreviewCanvas = new CanvasCache();
119 private RectCache mCachedAppWidgetPreviewSrcRect = new RectCache();
120 private RectCache mCachedAppWidgetPreviewDestRect = new RectCache();
121 private PaintCache mCachedAppWidgetPreviewPaint = new PaintCache();
122 private String mCachedSelectQuery;
123 private BitmapFactoryOptionsCache mCachedBitmapFactoryOptions = new BitmapFactoryOptionsCache();
124
125 private int mAppIconSize;
126 private IconCache mIconCache;
127
128 private final float sWidgetPreviewIconPaddingPercentage = 0.25f;
129
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100130 private CacheDb mDb;
Michael Jurka05713af2013-01-23 12:39:24 +0100131
Michael Jurka3f4e0702013-02-05 11:21:28 +0100132 private HashMap<String, WeakReference<Bitmap>> mLoadedPreviews;
133 private ArrayList<SoftReference<Bitmap>> mUnusedBitmaps;
Michael Jurka05713af2013-01-23 12:39:24 +0100134 private static HashSet<String> sInvalidPackages;
135
136 static {
Michael Jurka05713af2013-01-23 12:39:24 +0100137 sInvalidPackages = new HashSet<String>();
138 }
139
Michael Jurka3f4e0702013-02-05 11:21:28 +0100140 public WidgetPreviewLoader(Launcher launcher) {
Winson Chung5f8afe62013-08-12 16:19:28 -0700141 LauncherAppState app = LauncherAppState.getInstance();
142 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
143
Michael Jurka05713af2013-01-23 12:39:24 +0100144 mContext = mLauncher = launcher;
145 mPackageManager = mContext.getPackageManager();
Winson Chung5f8afe62013-08-12 16:19:28 -0700146 mAppIconSize = grid.iconSizePx;
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100147 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) {
Michael Jurkaeb1bb922013-09-26 11:29:01 -0700162 final String name = getObjectName(o);
163 final String packageName = getObjectPackage(o);
Michael Jurka05713af2013-01-23 12:39:24 +0100164 // check if the package is valid
165 boolean packageValid = true;
166 synchronized(sInvalidPackages) {
Michael Jurkaeb1bb922013-09-26 11:29:01 -0700167 packageValid = !sInvalidPackages.contains(packageName);
Michael Jurka05713af2013-01-23 12:39:24 +0100168 }
169 if (!packageValid) {
170 return null;
171 }
172 if (packageValid) {
Michael Jurka3f4e0702013-02-05 11:21:28 +0100173 synchronized(mLoadedPreviews) {
Michael Jurka05713af2013-01-23 12:39:24 +0100174 // check if it exists in our existing cache
Michael Jurka3f4e0702013-02-05 11:21:28 +0100175 if (mLoadedPreviews.containsKey(name) && mLoadedPreviews.get(name).get() != null) {
176 return mLoadedPreviews.get(name).get();
Michael Jurka05713af2013-01-23 12:39:24 +0100177 }
178 }
179 }
180
181 Bitmap unusedBitmap = null;
Michael Jurka3f4e0702013-02-05 11:21:28 +0100182 synchronized(mUnusedBitmaps) {
Michael Jurka05713af2013-01-23 12:39:24 +0100183 // not in cache; we need to load it from the db
Michael Jurka3f4e0702013-02-05 11:21:28 +0100184 while ((unusedBitmap == null || !unusedBitmap.isMutable() ||
185 unusedBitmap.getWidth() != mPreviewBitmapWidth ||
186 unusedBitmap.getHeight() != mPreviewBitmapHeight)
187 && mUnusedBitmaps.size() > 0) {
188 unusedBitmap = mUnusedBitmaps.remove(0).get();
Michael Jurka05713af2013-01-23 12:39:24 +0100189 }
190 if (unusedBitmap != null) {
191 final Canvas c = mCachedAppWidgetPreviewCanvas.get();
192 c.setBitmap(unusedBitmap);
193 c.drawColor(0, PorterDuff.Mode.CLEAR);
194 c.setBitmap(null);
195 }
196 }
197
198 if (unusedBitmap == null) {
Michael Jurka3f4e0702013-02-05 11:21:28 +0100199 unusedBitmap = Bitmap.createBitmap(mPreviewBitmapWidth, mPreviewBitmapHeight,
Michael Jurka05713af2013-01-23 12:39:24 +0100200 Bitmap.Config.ARGB_8888);
201 }
202
203 Bitmap preview = null;
204
205 if (packageValid) {
206 preview = readFromDb(name, unusedBitmap);
207 }
208
209 if (preview != null) {
Michael Jurka3f4e0702013-02-05 11:21:28 +0100210 synchronized(mLoadedPreviews) {
211 mLoadedPreviews.put(name, new WeakReference<Bitmap>(preview));
Michael Jurka05713af2013-01-23 12:39:24 +0100212 }
213 return preview;
214 } else {
215 // it's not in the db... we need to generate it
216 final Bitmap generatedPreview = generatePreview(o, unusedBitmap);
217 preview = generatedPreview;
218 if (preview != unusedBitmap) {
219 throw new RuntimeException("generatePreview is not recycling the bitmap " + o);
220 }
221
Michael Jurka3f4e0702013-02-05 11:21:28 +0100222 synchronized(mLoadedPreviews) {
223 mLoadedPreviews.put(name, new WeakReference<Bitmap>(preview));
Michael Jurka05713af2013-01-23 12:39:24 +0100224 }
225
226 // write to db on a thread pool... this can be done lazily and improves the performance
227 // of the first time widget previews are loaded
228 new AsyncTask<Void, Void, Void>() {
229 public Void doInBackground(Void ... args) {
230 writeToDb(o, generatedPreview);
231 return null;
232 }
233 }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
234
235 return preview;
236 }
237 }
238
Michael Jurkaee8e99f2013-02-07 13:27:06 +0100239 public void recycleBitmap(Object o, Bitmap bitmapToRecycle) {
Michael Jurka05713af2013-01-23 12:39:24 +0100240 String name = getObjectName(o);
Michael Jurka5140cfa2013-02-15 14:50:15 +0100241 synchronized (mLoadedPreviews) {
242 if (mLoadedPreviews.containsKey(name)) {
Michael Jurka3f4e0702013-02-05 11:21:28 +0100243 Bitmap b = mLoadedPreviews.get(name).get();
Michael Jurkaee8e99f2013-02-07 13:27:06 +0100244 if (b == bitmapToRecycle) {
Michael Jurka3f4e0702013-02-05 11:21:28 +0100245 mLoadedPreviews.remove(name);
Michael Jurkaee8e99f2013-02-07 13:27:06 +0100246 if (bitmapToRecycle.isMutable()) {
Michael Jurka5140cfa2013-02-15 14:50:15 +0100247 synchronized (mUnusedBitmaps) {
248 mUnusedBitmaps.add(new SoftReference<Bitmap>(b));
249 }
Michael Jurka05713af2013-01-23 12:39:24 +0100250 }
251 } else {
252 throw new RuntimeException("Bitmap passed in doesn't match up");
253 }
254 }
255 }
256 }
257
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100258 static class CacheDb extends SQLiteOpenHelper {
Michael Jurkae5919c52013-03-06 17:30:10 +0100259 final static int DB_VERSION = 2;
Michael Jurka05713af2013-01-23 12:39:24 +0100260 final static String DB_NAME = "widgetpreviews.db";
261 final static String TABLE_NAME = "shortcut_and_widget_previews";
262 final static String COLUMN_NAME = "name";
263 final static String COLUMN_SIZE = "size";
264 final static String COLUMN_PREVIEW_BITMAP = "preview_bitmap";
265 Context mContext;
266
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100267 public CacheDb(Context context) {
Michael Jurka05713af2013-01-23 12:39:24 +0100268 super(context, new File(context.getCacheDir(), DB_NAME).getPath(), null, DB_VERSION);
269 // Store the context for later use
270 mContext = context;
271 }
272
273 @Override
274 public void onCreate(SQLiteDatabase database) {
Michael Jurka32b7a092013-02-07 20:06:49 +0100275 database.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" +
Michael Jurka05713af2013-01-23 12:39:24 +0100276 COLUMN_NAME + " TEXT NOT NULL, " +
277 COLUMN_SIZE + " TEXT NOT NULL, " +
278 COLUMN_PREVIEW_BITMAP + " BLOB NOT NULL, " +
279 "PRIMARY KEY (" + COLUMN_NAME + ", " + COLUMN_SIZE + ") " +
Michael Jurka32b7a092013-02-07 20:06:49 +0100280 ");");
Michael Jurka05713af2013-01-23 12:39:24 +0100281 }
282
283 @Override
284 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Michael Jurkae5919c52013-03-06 17:30:10 +0100285 if (oldVersion != newVersion) {
286 // Delete all the records; they'll be repopulated as this is a cache
287 db.execSQL("DELETE FROM " + TABLE_NAME);
288 }
Michael Jurka05713af2013-01-23 12:39:24 +0100289 }
290 }
291
292 private static final String WIDGET_PREFIX = "Widget:";
293 private static final String SHORTCUT_PREFIX = "Shortcut:";
294
295 private static String getObjectName(Object o) {
296 // should cache the string builder
297 StringBuilder sb = new StringBuilder();
298 String output;
299 if (o instanceof AppWidgetProviderInfo) {
300 sb.append(WIDGET_PREFIX);
301 sb.append(((AppWidgetProviderInfo) o).provider.flattenToString());
302 output = sb.toString();
303 sb.setLength(0);
304 } else {
305 sb.append(SHORTCUT_PREFIX);
306
307 ResolveInfo info = (ResolveInfo) o;
308 sb.append(new ComponentName(info.activityInfo.packageName,
309 info.activityInfo.name).flattenToString());
310 output = sb.toString();
311 sb.setLength(0);
312 }
313 return output;
314 }
315
316 private String getObjectPackage(Object o) {
317 if (o instanceof AppWidgetProviderInfo) {
318 return ((AppWidgetProviderInfo) o).provider.getPackageName();
319 } else {
320 ResolveInfo info = (ResolveInfo) o;
321 return info.activityInfo.packageName;
322 }
323 }
324
325 private void writeToDb(Object o, Bitmap preview) {
326 String name = getObjectName(o);
327 SQLiteDatabase db = mDb.getWritableDatabase();
328 ContentValues values = new ContentValues();
329
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100330 values.put(CacheDb.COLUMN_NAME, name);
Michael Jurka05713af2013-01-23 12:39:24 +0100331 ByteArrayOutputStream stream = new ByteArrayOutputStream();
332 preview.compress(Bitmap.CompressFormat.PNG, 100, stream);
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100333 values.put(CacheDb.COLUMN_PREVIEW_BITMAP, stream.toByteArray());
334 values.put(CacheDb.COLUMN_SIZE, mSize);
335 db.insert(CacheDb.TABLE_NAME, null, values);
Michael Jurka05713af2013-01-23 12:39:24 +0100336 }
337
Michael Jurkaeb1bb922013-09-26 11:29:01 -0700338 public static void removePackageFromDb(final CacheDb cacheDb, final String packageName) {
Michael Jurka05713af2013-01-23 12:39:24 +0100339 synchronized(sInvalidPackages) {
340 sInvalidPackages.add(packageName);
341 }
342 new AsyncTask<Void, Void, Void>() {
343 public Void doInBackground(Void ... args) {
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100344 SQLiteDatabase db = cacheDb.getWritableDatabase();
345 db.delete(CacheDb.TABLE_NAME,
346 CacheDb.COLUMN_NAME + " LIKE ? OR " +
347 CacheDb.COLUMN_NAME + " LIKE ?", // SELECT query
Michael Jurka05713af2013-01-23 12:39:24 +0100348 new String[] {
349 WIDGET_PREFIX + packageName + "/%",
350 SHORTCUT_PREFIX + packageName + "/%"} // args to SELECT query
351 );
Michael Jurka05713af2013-01-23 12:39:24 +0100352 synchronized(sInvalidPackages) {
353 sInvalidPackages.remove(packageName);
354 }
355 return null;
356 }
357 }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
358 }
359
Michael Jurkaeb1bb922013-09-26 11:29:01 -0700360 public static void removeItemFromDb(final CacheDb cacheDb, final String objectName) {
361 new AsyncTask<Void, Void, Void>() {
362 public Void doInBackground(Void ... args) {
363 SQLiteDatabase db = cacheDb.getWritableDatabase();
364 db.delete(CacheDb.TABLE_NAME,
365 CacheDb.COLUMN_NAME + " = ? ", // SELECT query
366 new String[] { objectName }); // args to SELECT query
367 return null;
368 }
369 }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
370 }
371
Michael Jurka05713af2013-01-23 12:39:24 +0100372 private Bitmap readFromDb(String name, Bitmap b) {
373 if (mCachedSelectQuery == null) {
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100374 mCachedSelectQuery = CacheDb.COLUMN_NAME + " = ? AND " +
375 CacheDb.COLUMN_SIZE + " = ?";
Michael Jurka05713af2013-01-23 12:39:24 +0100376 }
377 SQLiteDatabase db = mDb.getReadableDatabase();
Michael Jurkad9cb4a12013-03-19 12:01:06 +0100378 Cursor result = db.query(CacheDb.TABLE_NAME,
379 new String[] { CacheDb.COLUMN_PREVIEW_BITMAP }, // cols to return
Michael Jurka05713af2013-01-23 12:39:24 +0100380 mCachedSelectQuery, // select query
381 new String[] { name, mSize }, // args to select query
382 null,
383 null,
384 null,
385 null);
386 if (result.getCount() > 0) {
387 result.moveToFirst();
388 byte[] blob = result.getBlob(0);
389 result.close();
390 final BitmapFactory.Options opts = mCachedBitmapFactoryOptions.get();
391 opts.inBitmap = b;
392 opts.inSampleSize = 1;
Michael Jurkaeb1bb922013-09-26 11:29:01 -0700393 try {
394 return BitmapFactory.decodeByteArray(blob, 0, blob.length, opts);
395 } catch (IllegalArgumentException e) {
396 removeItemFromDb(mDb, name);
397 return null;
398 }
Michael Jurka05713af2013-01-23 12:39:24 +0100399 } else {
400 result.close();
401 return null;
402 }
403 }
404
405 public Bitmap generatePreview(Object info, Bitmap preview) {
406 if (preview != null &&
Michael Jurka3f4e0702013-02-05 11:21:28 +0100407 (preview.getWidth() != mPreviewBitmapWidth ||
408 preview.getHeight() != mPreviewBitmapHeight)) {
Michael Jurka05713af2013-01-23 12:39:24 +0100409 throw new RuntimeException("Improperly sized bitmap passed as argument");
410 }
411 if (info instanceof AppWidgetProviderInfo) {
412 return generateWidgetPreview((AppWidgetProviderInfo) info, preview);
413 } else {
414 return generateShortcutPreview(
Michael Jurka3f4e0702013-02-05 11:21:28 +0100415 (ResolveInfo) info, mPreviewBitmapWidth, mPreviewBitmapHeight, preview);
Michael Jurka05713af2013-01-23 12:39:24 +0100416 }
417 }
418
419 public Bitmap generateWidgetPreview(AppWidgetProviderInfo info, Bitmap preview) {
Michael Jurka05713af2013-01-23 12:39:24 +0100420 int[] cellSpans = Launcher.getSpanForWidget(mLauncher, info);
421 int maxWidth = maxWidthForWidgetPreview(cellSpans[0]);
422 int maxHeight = maxHeightForWidgetPreview(cellSpans[1]);
423 return generateWidgetPreview(info.provider, info.previewImage, info.icon,
424 cellSpans[0], cellSpans[1], maxWidth, maxHeight, preview, null);
425 }
426
427 public int maxWidthForWidgetPreview(int spanX) {
Michael Jurka3f4e0702013-02-05 11:21:28 +0100428 return Math.min(mPreviewBitmapWidth,
Michael Jurka05713af2013-01-23 12:39:24 +0100429 mWidgetSpacingLayout.estimateCellWidth(spanX));
430 }
431
432 public int maxHeightForWidgetPreview(int spanY) {
Michael Jurka3f4e0702013-02-05 11:21:28 +0100433 return Math.min(mPreviewBitmapHeight,
Michael Jurka05713af2013-01-23 12:39:24 +0100434 mWidgetSpacingLayout.estimateCellHeight(spanY));
435 }
436
437 public Bitmap generateWidgetPreview(ComponentName provider, int previewImage,
438 int iconId, int cellHSpan, int cellVSpan, int maxPreviewWidth, int maxPreviewHeight,
439 Bitmap preview, int[] preScaledWidthOut) {
440 // Load the preview image if possible
441 String packageName = provider.getPackageName();
442 if (maxPreviewWidth < 0) maxPreviewWidth = Integer.MAX_VALUE;
443 if (maxPreviewHeight < 0) maxPreviewHeight = Integer.MAX_VALUE;
444
445 Drawable drawable = null;
446 if (previewImage != 0) {
447 drawable = mPackageManager.getDrawable(packageName, previewImage, null);
448 if (drawable == null) {
449 Log.w(TAG, "Can't load widget preview drawable 0x" +
450 Integer.toHexString(previewImage) + " for provider: " + provider);
451 }
452 }
453
454 int previewWidth;
455 int previewHeight;
456 Bitmap defaultPreview = null;
457 boolean widgetPreviewExists = (drawable != null);
458 if (widgetPreviewExists) {
459 previewWidth = drawable.getIntrinsicWidth();
460 previewHeight = drawable.getIntrinsicHeight();
461 } else {
462 // Generate a preview image if we couldn't load one
463 if (cellHSpan < 1) cellHSpan = 1;
464 if (cellVSpan < 1) cellVSpan = 1;
465
466 BitmapDrawable previewDrawable = (BitmapDrawable) mContext.getResources()
Winson Chung6706ed82013-10-02 11:00:15 -0700467 .getDrawable(R.drawable.widget_tile);
Michael Jurka05713af2013-01-23 12:39:24 +0100468 final int previewDrawableWidth = previewDrawable
469 .getIntrinsicWidth();
470 final int previewDrawableHeight = previewDrawable
471 .getIntrinsicHeight();
472 previewWidth = previewDrawableWidth * cellHSpan; // subtract 2 dips
473 previewHeight = previewDrawableHeight * cellVSpan;
474
475 defaultPreview = Bitmap.createBitmap(previewWidth, previewHeight,
476 Config.ARGB_8888);
477 final Canvas c = mCachedAppWidgetPreviewCanvas.get();
478 c.setBitmap(defaultPreview);
479 previewDrawable.setBounds(0, 0, previewWidth, previewHeight);
480 previewDrawable.setTileModeXY(Shader.TileMode.REPEAT,
481 Shader.TileMode.REPEAT);
482 previewDrawable.draw(c);
483 c.setBitmap(null);
484
485 // Draw the icon in the top left corner
486 int minOffset = (int) (mAppIconSize * sWidgetPreviewIconPaddingPercentage);
487 int smallestSide = Math.min(previewWidth, previewHeight);
488 float iconScale = Math.min((float) smallestSide
489 / (mAppIconSize + 2 * minOffset), 1f);
490
491 try {
492 Drawable icon = null;
493 int hoffset =
494 (int) ((previewDrawableWidth - mAppIconSize * iconScale) / 2);
495 int yoffset =
496 (int) ((previewDrawableHeight - mAppIconSize * iconScale) / 2);
497 if (iconId > 0)
498 icon = mIconCache.getFullResIcon(packageName, iconId);
499 if (icon != null) {
500 renderDrawableToBitmap(icon, defaultPreview, hoffset,
501 yoffset, (int) (mAppIconSize * iconScale),
502 (int) (mAppIconSize * iconScale));
503 }
504 } catch (Resources.NotFoundException e) {
505 }
506 }
507
508 // Scale to fit width only - let the widget preview be clipped in the
509 // vertical dimension
510 float scale = 1f;
511 if (preScaledWidthOut != null) {
512 preScaledWidthOut[0] = previewWidth;
513 }
514 if (previewWidth > maxPreviewWidth) {
515 scale = maxPreviewWidth / (float) previewWidth;
516 }
517 if (scale != 1f) {
518 previewWidth = (int) (scale * previewWidth);
519 previewHeight = (int) (scale * previewHeight);
520 }
521
522 // If a bitmap is passed in, we use it; otherwise, we create a bitmap of the right size
523 if (preview == null) {
524 preview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
525 }
526
527 // Draw the scaled preview into the final bitmap
528 int x = (preview.getWidth() - previewWidth) / 2;
529 if (widgetPreviewExists) {
530 renderDrawableToBitmap(drawable, preview, x, 0, previewWidth,
531 previewHeight);
532 } else {
533 final Canvas c = mCachedAppWidgetPreviewCanvas.get();
534 final Rect src = mCachedAppWidgetPreviewSrcRect.get();
535 final Rect dest = mCachedAppWidgetPreviewDestRect.get();
536 c.setBitmap(preview);
537 src.set(0, 0, defaultPreview.getWidth(), defaultPreview.getHeight());
Michael Jurkae5919c52013-03-06 17:30:10 +0100538 dest.set(x, 0, x + previewWidth, previewHeight);
Michael Jurka05713af2013-01-23 12:39:24 +0100539
540 Paint p = mCachedAppWidgetPreviewPaint.get();
541 if (p == null) {
542 p = new Paint();
543 p.setFilterBitmap(true);
544 mCachedAppWidgetPreviewPaint.set(p);
545 }
546 c.drawBitmap(defaultPreview, src, dest, p);
547 c.setBitmap(null);
548 }
549 return preview;
550 }
551
552 private Bitmap generateShortcutPreview(
553 ResolveInfo info, int maxWidth, int maxHeight, Bitmap preview) {
554 Bitmap tempBitmap = mCachedShortcutPreviewBitmap.get();
555 final Canvas c = mCachedShortcutPreviewCanvas.get();
556 if (tempBitmap == null ||
557 tempBitmap.getWidth() != maxWidth ||
558 tempBitmap.getHeight() != maxHeight) {
559 tempBitmap = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
560 mCachedShortcutPreviewBitmap.set(tempBitmap);
561 } else {
562 c.setBitmap(tempBitmap);
563 c.drawColor(0, PorterDuff.Mode.CLEAR);
564 c.setBitmap(null);
565 }
566 // Render the icon
567 Drawable icon = mIconCache.getFullResIcon(info);
568
569 int paddingTop = mContext.
570 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_top);
571 int paddingLeft = mContext.
572 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_left);
573 int paddingRight = mContext.
574 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_right);
575
576 int scaledIconWidth = (maxWidth - paddingLeft - paddingRight);
577
578 renderDrawableToBitmap(
579 icon, tempBitmap, paddingLeft, paddingTop, scaledIconWidth, scaledIconWidth);
580
581 if (preview != null &&
582 (preview.getWidth() != maxWidth || preview.getHeight() != maxHeight)) {
583 throw new RuntimeException("Improperly sized bitmap passed as argument");
584 } else if (preview == null) {
585 preview = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
586 }
587
588 c.setBitmap(preview);
589 // Draw a desaturated/scaled version of the icon in the background as a watermark
590 Paint p = mCachedShortcutPreviewPaint.get();
591 if (p == null) {
592 p = new Paint();
593 ColorMatrix colorMatrix = new ColorMatrix();
594 colorMatrix.setSaturation(0);
595 p.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
596 p.setAlpha((int) (255 * 0.06f));
597 mCachedShortcutPreviewPaint.set(p);
598 }
599 c.drawBitmap(tempBitmap, 0, 0, p);
600 c.setBitmap(null);
601
602 renderDrawableToBitmap(icon, preview, 0, 0, mAppIconSize, mAppIconSize);
603
604 return preview;
605 }
606
607
608 public static void renderDrawableToBitmap(
609 Drawable d, Bitmap bitmap, int x, int y, int w, int h) {
610 renderDrawableToBitmap(d, bitmap, x, y, w, h, 1f);
611 }
612
613 private static void renderDrawableToBitmap(
614 Drawable d, Bitmap bitmap, int x, int y, int w, int h,
615 float scale) {
616 if (bitmap != null) {
617 Canvas c = new Canvas(bitmap);
618 c.scale(scale, scale);
619 Rect oldBounds = d.copyBounds();
620 d.setBounds(x, y, x + w, y + h);
621 d.draw(c);
622 d.setBounds(oldBounds); // Restore the bounds
623 c.setBitmap(null);
624 }
625 }
626
627}