blob: 60185c6581dfff3b3836cfe6924d1c5be384414a [file] [log] [blame]
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Daniel Sandler325dc232013-06-05 22:57:57 -040017package com.android.launcher3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080018
Michael Jurkaa805e1a2013-08-22 15:00:33 +020019import android.app.Activity;
20import android.content.ActivityNotFoundException;
Sunny Goyalc5c60ad2014-07-14 12:02:01 -070021import android.content.ComponentName;
Winson Chungaafa03c2010-06-11 17:34:16 -070022import android.content.Context;
Michael Jurkaa805e1a2013-08-22 15:00:33 +020023import android.content.Intent;
Sunny Goyalc5c60ad2014-07-14 12:02:01 -070024import android.content.pm.ApplicationInfo;
25import android.content.pm.PackageInfo;
26import android.content.pm.PackageManager;
27import android.content.pm.PackageManager.NameNotFoundException;
28import android.content.pm.ResolveInfo;
Winson Chungaafa03c2010-06-11 17:34:16 -070029import android.content.res.Resources;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080030import android.graphics.Bitmap;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080031import android.graphics.Canvas;
Sunny Goyal95abbb32014-08-04 10:53:22 -070032import android.graphics.Color;
Winson Chungc763c4e2013-07-19 13:49:06 -070033import android.graphics.Matrix;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080034import android.graphics.Paint;
Joe Onoratobf15cb42009-08-07 14:33:40 -070035import android.graphics.PaintFlagsDrawFilter;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080036import android.graphics.Rect;
Winson Chungaafa03c2010-06-11 17:34:16 -070037import android.graphics.drawable.BitmapDrawable;
38import android.graphics.drawable.Drawable;
39import android.graphics.drawable.PaintDrawable;
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -070040import android.os.Build;
Michael Jurkaa805e1a2013-08-22 15:00:33 +020041import android.util.Log;
Sunny Goyal0fe505b2014-08-06 09:55:36 -070042import android.util.Pair;
Sunny Goyal95abbb32014-08-04 10:53:22 -070043import android.util.SparseArray;
Winson Chungc763c4e2013-07-19 13:49:06 -070044import android.view.View;
Michael Jurkaa805e1a2013-08-22 15:00:33 +020045import android.widget.Toast;
Winson Chungc763c4e2013-07-19 13:49:06 -070046
47import java.util.ArrayList;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080048
49/**
50 * Various utilities shared amongst the Launcher's classes.
51 */
Mathew Inwood72fbec12013-11-19 15:45:07 +000052public final class Utilities {
Joe Onorato1291a8c2009-09-15 15:07:25 -040053 private static final String TAG = "Launcher.Utilities";
54
The Android Open Source Project31dd5032009-03-03 19:32:27 -080055 private static int sIconWidth = -1;
56 private static int sIconHeight = -1;
Adam Cohen61f560d2013-09-30 15:58:20 -070057 public static int sIconTextureWidth = -1;
58 public static int sIconTextureHeight = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080059
The Android Open Source Project31dd5032009-03-03 19:32:27 -080060 private static final Rect sOldBounds = new Rect();
Romain Guy89911d22009-09-28 18:48:49 -070061 private static final Canvas sCanvas = new Canvas();
The Android Open Source Project31dd5032009-03-03 19:32:27 -080062
63 static {
64 sCanvas.setDrawFilter(new PaintFlagsDrawFilter(Paint.DITHER_FLAG,
65 Paint.FILTER_BITMAP_FLAG));
66 }
Joe Onorato6665c0f2009-09-02 15:27:24 -070067 static int sColors[] = { 0xffff0000, 0xff00ff00, 0xff0000ff };
68 static int sColorIndex = 0;
69
Michael Jurka7ad868b2013-12-12 15:04:25 +010070
71 // To turn on these properties, type
72 // adb shell setprop log.tag.PROPERTY_NAME [VERBOSE | SUPPRESS]
73 static final String FORCE_ENABLE_ROTATION_PROPERTY = "launcher_force_rotate";
74 public static boolean sForceEnableRotation = isPropertyEnabled(FORCE_ENABLE_ROTATION_PROPERTY);
75
Joe Onorato6665c0f2009-09-02 15:27:24 -070076 /**
Winson Chung0dbd7342013-10-13 22:46:20 -070077 * Returns a FastBitmapDrawable with the icon, accurately sized.
78 */
Sunny Goyalc5c60ad2014-07-14 12:02:01 -070079 static FastBitmapDrawable createIconDrawable(Bitmap icon) {
Winson Chung0dbd7342013-10-13 22:46:20 -070080 FastBitmapDrawable d = new FastBitmapDrawable(icon);
Winson Chung54000492013-10-14 16:29:29 -070081 d.setFilterBitmap(true);
Winson Chung0dbd7342013-10-13 22:46:20 -070082 resizeIconDrawable(d);
83 return d;
84 }
85
86 /**
87 * Resizes an icon drawable to the correct icon size.
88 */
89 static void resizeIconDrawable(Drawable icon) {
90 icon.setBounds(0, 0, sIconTextureWidth, sIconTextureHeight);
91 }
92
Michael Jurka7ad868b2013-12-12 15:04:25 +010093 private static boolean isPropertyEnabled(String propertyName) {
94 return Log.isLoggable(propertyName, Log.VERBOSE);
95 }
96
97 public static boolean isRotationEnabled(Context c) {
98 boolean enableRotation = sForceEnableRotation ||
99 c.getResources().getBoolean(R.bool.allow_rotation);
100 return enableRotation;
101 }
102
Winson Chung0dbd7342013-10-13 22:46:20 -0700103 /**
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -0700104 * Indicates if the device is running LMP or not.
105 * TODO(sansid): Change the check to a VERSION_CODES code check once we have a version for L.
106 */
107 public static boolean isLmp() {
108 return "L".equals(Build.VERSION.CODENAME);
109 }
110
111 /**
Michael Jurka931dc972011-08-05 15:08:15 -0700112 * Returns a bitmap suitable for the all apps view. Used to convert pre-ICS
113 * icon bitmaps that are stored in the database (which were 74x74 pixels at hdpi size)
114 * to the proper size (48dp)
115 */
116 static Bitmap createIconBitmap(Bitmap icon, Context context) {
117 int textureWidth = sIconTextureWidth;
118 int textureHeight = sIconTextureHeight;
119 int sourceWidth = icon.getWidth();
120 int sourceHeight = icon.getHeight();
121 if (sourceWidth > textureWidth && sourceHeight > textureHeight) {
122 // Icon is bigger than it should be; clip it (solves the GB->ICS migration case)
123 return Bitmap.createBitmap(icon,
124 (sourceWidth - textureWidth) / 2,
125 (sourceHeight - textureHeight) / 2,
126 textureWidth, textureHeight);
127 } else if (sourceWidth == textureWidth && sourceHeight == textureHeight) {
128 // Icon is the right size, no need to change it
129 return icon;
130 } else {
131 // Icon is too small, render to a larger bitmap
Michael Jurka3a9fced2012-04-13 14:44:29 -0700132 final Resources resources = context.getResources();
133 return createIconBitmap(new BitmapDrawable(resources, icon), context);
Michael Jurka931dc972011-08-05 15:08:15 -0700134 }
135 }
136
137 /**
138 * Returns a bitmap suitable for the all apps view.
Joe Onorato6665c0f2009-09-02 15:27:24 -0700139 */
Mathew Inwood72fbec12013-11-19 15:45:07 +0000140 public static Bitmap createIconBitmap(Drawable icon, Context context) {
Joe Onorato6665c0f2009-09-02 15:27:24 -0700141 synchronized (sCanvas) { // we share the statics :-(
142 if (sIconWidth == -1) {
143 initStatics(context);
144 }
145
146 int width = sIconWidth;
147 int height = sIconHeight;
148
Joe Onorato6665c0f2009-09-02 15:27:24 -0700149 if (icon instanceof PaintDrawable) {
150 PaintDrawable painter = (PaintDrawable) icon;
151 painter.setIntrinsicWidth(width);
152 painter.setIntrinsicHeight(height);
153 } else if (icon instanceof BitmapDrawable) {
154 // Ensure the bitmap has a density.
155 BitmapDrawable bitmapDrawable = (BitmapDrawable) icon;
156 Bitmap bitmap = bitmapDrawable.getBitmap();
157 if (bitmap.getDensity() == Bitmap.DENSITY_NONE) {
158 bitmapDrawable.setTargetDensity(context.getResources().getDisplayMetrics());
159 }
160 }
161 int sourceWidth = icon.getIntrinsicWidth();
162 int sourceHeight = icon.getIntrinsicHeight();
Michael Jurka931dc972011-08-05 15:08:15 -0700163 if (sourceWidth > 0 && sourceHeight > 0) {
Winson Chung5f8afe62013-08-12 16:19:28 -0700164 // Scale the icon proportionally to the icon dimensions
165 final float ratio = (float) sourceWidth / sourceHeight;
166 if (sourceWidth > sourceHeight) {
167 height = (int) (width / ratio);
168 } else if (sourceHeight > sourceWidth) {
169 width = (int) (height * ratio);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700170 }
171 }
172
173 // no intrinsic size --> use default size
174 int textureWidth = sIconTextureWidth;
175 int textureHeight = sIconTextureHeight;
176
177 final Bitmap bitmap = Bitmap.createBitmap(textureWidth, textureHeight,
178 Bitmap.Config.ARGB_8888);
179 final Canvas canvas = sCanvas;
180 canvas.setBitmap(bitmap);
181
182 final int left = (textureWidth-width) / 2;
183 final int top = (textureHeight-height) / 2;
184
Michael Jurka3a9fced2012-04-13 14:44:29 -0700185 @SuppressWarnings("all") // suppress dead code warning
186 final boolean debug = false;
187 if (debug) {
Joe Onorato6665c0f2009-09-02 15:27:24 -0700188 // draw a big box for the icon for debugging
189 canvas.drawColor(sColors[sColorIndex]);
190 if (++sColorIndex >= sColors.length) sColorIndex = 0;
191 Paint debugPaint = new Paint();
192 debugPaint.setColor(0xffcccc00);
193 canvas.drawRect(left, top, left+width, top+height, debugPaint);
194 }
195
196 sOldBounds.set(icon.getBounds());
197 icon.setBounds(left, top, left+width, top+height);
198 icon.draw(canvas);
199 icon.setBounds(sOldBounds);
Adam Cohenaaf473c2011-08-03 12:02:47 -0700200 canvas.setBitmap(null);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700201
202 return bitmap;
203 }
204 }
205
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800206 /**
207 * Returns a Bitmap representing the thumbnail of the specified Bitmap.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800208 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800209 * @param bitmap The bitmap to get a thumbnail of.
210 * @param context The application's context.
211 *
212 * @return A thumbnail for the specified bitmap or the bitmap itself if the
213 * thumbnail could not be created.
214 */
Joe Onorato0589f0f2010-02-08 13:44:00 -0800215 static Bitmap resampleIconBitmap(Bitmap bitmap, Context context) {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400216 synchronized (sCanvas) { // we share the statics :-(
217 if (sIconWidth == -1) {
Joe Onorato6665c0f2009-09-02 15:27:24 -0700218 initStatics(context);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800219 }
220
Joe Onorato0589f0f2010-02-08 13:44:00 -0800221 if (bitmap.getWidth() == sIconWidth && bitmap.getHeight() == sIconHeight) {
222 return bitmap;
223 } else {
Michael Jurka3a9fced2012-04-13 14:44:29 -0700224 final Resources resources = context.getResources();
225 return createIconBitmap(new BitmapDrawable(resources, bitmap), context);
Joe Onorato9c1289c2009-08-17 11:03:03 -0400226 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400227 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800228 }
Joe Onoratobf15cb42009-08-07 14:33:40 -0700229
Winson Chungc763c4e2013-07-19 13:49:06 -0700230 /**
231 * Given a coordinate relative to the descendant, find the coordinate in a parent view's
232 * coordinates.
233 *
234 * @param descendant The descendant to which the passed coordinate is relative.
235 * @param root The root view to make the coordinates relative to.
236 * @param coord The coordinate that we want mapped.
237 * @param includeRootScroll Whether or not to account for the scroll of the descendant:
238 * sometimes this is relevant as in a child's coordinates within the descendant.
239 * @return The factor by which this descendant is scaled relative to this DragLayer. Caution
240 * this scale factor is assumed to be equal in X and Y, and so if at any point this
241 * assumption fails, we will need to return a pair of scale factors.
242 */
243 public static float getDescendantCoordRelativeToParent(View descendant, View root,
244 int[] coord, boolean includeRootScroll) {
245 ArrayList<View> ancestorChain = new ArrayList<View>();
246
247 float[] pt = {coord[0], coord[1]};
248
249 View v = descendant;
250 while(v != root && v != null) {
251 ancestorChain.add(v);
252 v = (View) v.getParent();
253 }
254 ancestorChain.add(root);
255
256 float scale = 1.0f;
257 int count = ancestorChain.size();
258 for (int i = 0; i < count; i++) {
259 View v0 = ancestorChain.get(i);
Winson Chungc763c4e2013-07-19 13:49:06 -0700260 // For TextViews, scroll has a meaning which relates to the text position
261 // which is very strange... ignore the scroll.
262 if (v0 != descendant || includeRootScroll) {
263 pt[0] -= v0.getScrollX();
264 pt[1] -= v0.getScrollY();
265 }
266
267 v0.getMatrix().mapPoints(pt);
268 pt[0] += v0.getLeft();
269 pt[1] += v0.getTop();
270 scale *= v0.getScaleX();
271 }
272
273 coord[0] = (int) Math.round(pt[0]);
274 coord[1] = (int) Math.round(pt[1]);
275 return scale;
276 }
277
278 /**
279 * Inverse of {@link #getDescendantCoordRelativeToSelf(View, int[])}.
280 */
281 public static float mapCoordInSelfToDescendent(View descendant, View root,
282 int[] coord) {
283 ArrayList<View> ancestorChain = new ArrayList<View>();
284
285 float[] pt = {coord[0], coord[1]};
286
287 View v = descendant;
288 while(v != root) {
289 ancestorChain.add(v);
290 v = (View) v.getParent();
291 }
292 ancestorChain.add(root);
293
294 float scale = 1.0f;
295 Matrix inverse = new Matrix();
296 int count = ancestorChain.size();
297 for (int i = count - 1; i >= 0; i--) {
298 View ancestor = ancestorChain.get(i);
299 View next = i > 0 ? ancestorChain.get(i-1) : null;
300
301 pt[0] += ancestor.getScrollX();
302 pt[1] += ancestor.getScrollY();
303
304 if (next != null) {
305 pt[0] -= next.getLeft();
306 pt[1] -= next.getTop();
307 next.getMatrix().invert(inverse);
308 inverse.mapPoints(pt);
309 scale *= next.getScaleX();
310 }
311 }
312
313 coord[0] = (int) Math.round(pt[0]);
314 coord[1] = (int) Math.round(pt[1]);
315 return scale;
316 }
317
Jason Monk02dd7ae2014-04-15 15:23:31 -0400318 /**
319 * Utility method to determine whether the given point, in local coordinates,
320 * is inside the view, where the area of the view is expanded by the slop factor.
321 * This method is called while processing touch-move events to determine if the event
322 * is still within the view.
323 */
324 public static boolean pointInView(View v, float localX, float localY, float slop) {
325 return localX >= -slop && localY >= -slop && localX < (v.getWidth() + slop) &&
326 localY < (v.getHeight() + slop);
327 }
328
Joe Onorato6665c0f2009-09-02 15:27:24 -0700329 private static void initStatics(Context context) {
330 final Resources resources = context.getResources();
Michael Jurkac9a96192010-11-01 11:52:08 -0700331 sIconWidth = sIconHeight = (int) resources.getDimension(R.dimen.app_icon_size);
Winson Chung4b825dcd2011-06-19 12:41:22 -0700332 sIconTextureWidth = sIconTextureHeight = sIconWidth;
Joe Onorato6665c0f2009-09-02 15:27:24 -0700333 }
334
Winson Chung5f8afe62013-08-12 16:19:28 -0700335 public static void setIconSize(int widthPx) {
336 sIconWidth = sIconHeight = widthPx;
337 sIconTextureWidth = sIconTextureHeight = widthPx;
Winson Chung97d85d22011-04-13 11:27:36 -0700338 }
Michael Jurkaa805e1a2013-08-22 15:00:33 +0200339
Winson Chung3a6e7f32013-10-09 15:50:52 -0700340 public static void scaleRect(Rect r, float scale) {
341 if (scale != 1.0f) {
342 r.left = (int) (r.left * scale + 0.5f);
343 r.top = (int) (r.top * scale + 0.5f);
344 r.right = (int) (r.right * scale + 0.5f);
345 r.bottom = (int) (r.bottom * scale + 0.5f);
346 }
347 }
348
349 public static void scaleRectAboutCenter(Rect r, float scale) {
350 int cx = r.centerX();
351 int cy = r.centerY();
352 r.offset(-cx, -cy);
353 Utilities.scaleRect(r, scale);
354 r.offset(cx, cy);
355 }
356
Michael Jurkaa805e1a2013-08-22 15:00:33 +0200357 public static void startActivityForResultSafely(
358 Activity activity, Intent intent, int requestCode) {
359 try {
360 activity.startActivityForResult(intent, requestCode);
361 } catch (ActivityNotFoundException e) {
362 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
363 } catch (SecurityException e) {
364 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
365 Log.e(TAG, "Launcher does not have the permission to launch " + intent +
366 ". Make sure to create a MAIN intent-filter for the corresponding activity " +
367 "or use the exported attribute for this activity.", e);
368 }
369 }
Sunny Goyalc5c60ad2014-07-14 12:02:01 -0700370
371 static boolean isSystemApp(Context context, Intent intent) {
372 PackageManager pm = context.getPackageManager();
373 ComponentName cn = intent.getComponent();
374 String packageName = null;
375 if (cn == null) {
376 ResolveInfo info = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
377 if ((info != null) && (info.activityInfo != null)) {
378 packageName = info.activityInfo.packageName;
379 }
380 } else {
381 packageName = cn.getPackageName();
382 }
383 if (packageName != null) {
384 try {
385 PackageInfo info = pm.getPackageInfo(packageName, 0);
386 return (info != null) && (info.applicationInfo != null) &&
387 ((info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
388 } catch (NameNotFoundException e) {
389 return false;
390 }
391 } else {
392 return false;
393 }
394 }
Sunny Goyal95abbb32014-08-04 10:53:22 -0700395
396 /**
397 * This picks a dominant color, looking for high-saturation, high-value, repeated hues.
398 * @param bitmap The bitmap to scan
399 * @param samples The approximate max number of samples to use.
400 */
401 static int findDominantColorByHue(Bitmap bitmap, int samples) {
402 final int height = bitmap.getHeight();
403 final int width = bitmap.getWidth();
404 int sampleStride = (int) Math.sqrt((height * width) / samples);
405 if (sampleStride < 1) {
406 sampleStride = 1;
407 }
408
409 // This is an out-param, for getting the hsv values for an rgb
410 float[] hsv = new float[3];
411
412 // First get the best hue, by creating a histogram over 360 hue buckets,
413 // where each pixel contributes a score weighted by saturation, value, and alpha.
414 float[] hueScoreHistogram = new float[360];
415 float highScore = -1;
416 int bestHue = -1;
417
418 for (int y = 0; y < height; y += sampleStride) {
419 for (int x = 0; x < width; x += sampleStride) {
420 int argb = bitmap.getPixel(x, y);
421 int alpha = 0xFF & (argb >> 24);
422 if (alpha < 0x80) {
423 // Drop mostly-transparent pixels.
424 continue;
425 }
426 // Remove the alpha channel.
427 int rgb = argb | 0xFF000000;
428 Color.colorToHSV(rgb, hsv);
429 // Bucket colors by the 360 integer hues.
430 int hue = (int) hsv[0];
431 if (hue < 0 || hue >= hueScoreHistogram.length) {
432 // Defensively avoid array bounds violations.
433 continue;
434 }
435 float score = hsv[1] * hsv[2];
436 hueScoreHistogram[hue] += score;
437 if (hueScoreHistogram[hue] > highScore) {
438 highScore = hueScoreHistogram[hue];
439 bestHue = hue;
440 }
441 }
442 }
443
444 SparseArray<Float> rgbScores = new SparseArray<Float>();
445 int bestColor = 0xff000000;
446 highScore = -1;
447 // Go back over the RGB colors that match the winning hue,
448 // creating a histogram of weighted s*v scores, for up to 100*100 [s,v] buckets.
449 // The highest-scoring RGB color wins.
450 for (int y = 0; y < height; y += sampleStride) {
451 for (int x = 0; x < width; x += sampleStride) {
452 int rgb = bitmap.getPixel(x, y) | 0xff000000;
453 Color.colorToHSV(rgb, hsv);
454 int hue = (int) hsv[0];
455 if (hue == bestHue) {
456 float s = hsv[1];
457 float v = hsv[2];
458 int bucket = (int) (s * 100) + (int) (v * 10000);
459 // Score by cumulative saturation * value.
460 float score = s * v;
461 Float oldTotal = rgbScores.get(bucket);
462 float newTotal = oldTotal == null ? score : oldTotal + score;
463 rgbScores.put(bucket, newTotal);
464 if (newTotal > highScore) {
465 highScore = newTotal;
466 // All the colors in the winning bucket are very similar. Last in wins.
467 bestColor = rgb;
468 }
469 }
470 }
471 }
472 return bestColor;
473 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700474
475 /*
476 * Finds a system apk which had a broadcast receiver listening to a particular action.
477 * @param action intent action used to find the apk
478 * @return a pair of apk package name and the resources.
479 */
480 static Pair<String, Resources> findSystemApk(String action, PackageManager pm) {
481 final Intent intent = new Intent(action);
482 for (ResolveInfo info : pm.queryBroadcastReceivers(intent, 0)) {
483 if (info.activityInfo != null &&
484 (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
485 final String packageName = info.activityInfo.packageName;
486 try {
487 final Resources res = pm.getResourcesForApplication(packageName);
488 return Pair.create(packageName, res);
489 } catch (NameNotFoundException e) {
490 Log.w(TAG, "Failed to find resources for " + packageName);
491 }
492 }
493 }
494 return null;
495 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800496}