blob: 84eb8bfa2deaa19ad762e7d6f26662eaca93438a [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;
57
The Android Open Source Project31dd5032009-03-03 19:32:27 -080058 private static final Rect sOldBounds = new Rect();
Romain Guy89911d22009-09-28 18:48:49 -070059 private static final Canvas sCanvas = new Canvas();
The Android Open Source Project31dd5032009-03-03 19:32:27 -080060
61 static {
62 sCanvas.setDrawFilter(new PaintFlagsDrawFilter(Paint.DITHER_FLAG,
63 Paint.FILTER_BITMAP_FLAG));
64 }
Joe Onorato6665c0f2009-09-02 15:27:24 -070065 static int sColors[] = { 0xffff0000, 0xff00ff00, 0xff0000ff };
66 static int sColorIndex = 0;
67
Adam Cohen63f1ec02014-08-12 09:23:13 -070068 static int[] sLoc0 = new int[2];
69 static int[] sLoc1 = new int[2];
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 Goyalffe83f12014-08-14 17:39:34 -070079 public 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) {
Sunny Goyal2fce90c2014-10-07 12:01:58 -070090 icon.setBounds(0, 0, sIconWidth, sIconHeight);
Winson Chung0dbd7342013-10-13 22:46:20 -070091 }
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 /**
Kenny Guyd794a3f2014-09-16 15:17:58 +0100104 * Indicates if the device is running LMP or higher.
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -0700105 */
Kenny Guyd794a3f2014-09-16 15:17:58 +0100106 public static boolean isLmpOrAbove() {
107 return Build.VERSION.SDK_INT >= Build.VERSION_CODES.L;
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -0700108 }
109
110 /**
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700111 * Returns a bitmap which is of the appropriate size to be displayed as an icon
Michael Jurka931dc972011-08-05 15:08:15 -0700112 */
113 static Bitmap createIconBitmap(Bitmap icon, Context context) {
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700114 synchronized (sCanvas) { // we share the statics :-(
115 if (sIconWidth == -1) {
116 initStatics(context);
117 }
Michael Jurka931dc972011-08-05 15:08:15 -0700118 }
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700119 if (sIconWidth == icon.getWidth() && sIconHeight == icon.getHeight()) {
120 return icon;
121 }
122 return createIconBitmap(new BitmapDrawable(context.getResources(), icon), context);
Michael Jurka931dc972011-08-05 15:08:15 -0700123 }
124
125 /**
126 * Returns a bitmap suitable for the all apps view.
Joe Onorato6665c0f2009-09-02 15:27:24 -0700127 */
Mathew Inwood72fbec12013-11-19 15:45:07 +0000128 public static Bitmap createIconBitmap(Drawable icon, Context context) {
Joe Onorato6665c0f2009-09-02 15:27:24 -0700129 synchronized (sCanvas) { // we share the statics :-(
130 if (sIconWidth == -1) {
131 initStatics(context);
132 }
133
134 int width = sIconWidth;
135 int height = sIconHeight;
136
Joe Onorato6665c0f2009-09-02 15:27:24 -0700137 if (icon instanceof PaintDrawable) {
138 PaintDrawable painter = (PaintDrawable) icon;
139 painter.setIntrinsicWidth(width);
140 painter.setIntrinsicHeight(height);
141 } else if (icon instanceof BitmapDrawable) {
142 // Ensure the bitmap has a density.
143 BitmapDrawable bitmapDrawable = (BitmapDrawable) icon;
144 Bitmap bitmap = bitmapDrawable.getBitmap();
145 if (bitmap.getDensity() == Bitmap.DENSITY_NONE) {
146 bitmapDrawable.setTargetDensity(context.getResources().getDisplayMetrics());
147 }
148 }
149 int sourceWidth = icon.getIntrinsicWidth();
150 int sourceHeight = icon.getIntrinsicHeight();
Michael Jurka931dc972011-08-05 15:08:15 -0700151 if (sourceWidth > 0 && sourceHeight > 0) {
Winson Chung5f8afe62013-08-12 16:19:28 -0700152 // Scale the icon proportionally to the icon dimensions
153 final float ratio = (float) sourceWidth / sourceHeight;
154 if (sourceWidth > sourceHeight) {
155 height = (int) (width / ratio);
156 } else if (sourceHeight > sourceWidth) {
157 width = (int) (height * ratio);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700158 }
159 }
160
161 // no intrinsic size --> use default size
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700162 int textureWidth = sIconWidth;
163 int textureHeight = sIconHeight;
Joe Onorato6665c0f2009-09-02 15:27:24 -0700164
165 final Bitmap bitmap = Bitmap.createBitmap(textureWidth, textureHeight,
166 Bitmap.Config.ARGB_8888);
167 final Canvas canvas = sCanvas;
168 canvas.setBitmap(bitmap);
169
170 final int left = (textureWidth-width) / 2;
171 final int top = (textureHeight-height) / 2;
172
Michael Jurka3a9fced2012-04-13 14:44:29 -0700173 @SuppressWarnings("all") // suppress dead code warning
174 final boolean debug = false;
175 if (debug) {
Joe Onorato6665c0f2009-09-02 15:27:24 -0700176 // draw a big box for the icon for debugging
177 canvas.drawColor(sColors[sColorIndex]);
178 if (++sColorIndex >= sColors.length) sColorIndex = 0;
179 Paint debugPaint = new Paint();
180 debugPaint.setColor(0xffcccc00);
181 canvas.drawRect(left, top, left+width, top+height, debugPaint);
182 }
183
184 sOldBounds.set(icon.getBounds());
185 icon.setBounds(left, top, left+width, top+height);
186 icon.draw(canvas);
187 icon.setBounds(sOldBounds);
Adam Cohenaaf473c2011-08-03 12:02:47 -0700188 canvas.setBitmap(null);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700189
190 return bitmap;
191 }
192 }
193
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800194 /**
Winson Chungc763c4e2013-07-19 13:49:06 -0700195 * Given a coordinate relative to the descendant, find the coordinate in a parent view's
196 * coordinates.
197 *
198 * @param descendant The descendant to which the passed coordinate is relative.
199 * @param root The root view to make the coordinates relative to.
200 * @param coord The coordinate that we want mapped.
201 * @param includeRootScroll Whether or not to account for the scroll of the descendant:
202 * sometimes this is relevant as in a child's coordinates within the descendant.
203 * @return The factor by which this descendant is scaled relative to this DragLayer. Caution
204 * this scale factor is assumed to be equal in X and Y, and so if at any point this
205 * assumption fails, we will need to return a pair of scale factors.
206 */
207 public static float getDescendantCoordRelativeToParent(View descendant, View root,
208 int[] coord, boolean includeRootScroll) {
209 ArrayList<View> ancestorChain = new ArrayList<View>();
210
211 float[] pt = {coord[0], coord[1]};
212
213 View v = descendant;
214 while(v != root && v != null) {
215 ancestorChain.add(v);
216 v = (View) v.getParent();
217 }
218 ancestorChain.add(root);
219
220 float scale = 1.0f;
221 int count = ancestorChain.size();
222 for (int i = 0; i < count; i++) {
223 View v0 = ancestorChain.get(i);
Winson Chungc763c4e2013-07-19 13:49:06 -0700224 // For TextViews, scroll has a meaning which relates to the text position
225 // which is very strange... ignore the scroll.
226 if (v0 != descendant || includeRootScroll) {
227 pt[0] -= v0.getScrollX();
228 pt[1] -= v0.getScrollY();
229 }
230
231 v0.getMatrix().mapPoints(pt);
232 pt[0] += v0.getLeft();
233 pt[1] += v0.getTop();
234 scale *= v0.getScaleX();
235 }
236
237 coord[0] = (int) Math.round(pt[0]);
238 coord[1] = (int) Math.round(pt[1]);
239 return scale;
240 }
241
242 /**
243 * Inverse of {@link #getDescendantCoordRelativeToSelf(View, int[])}.
244 */
245 public static float mapCoordInSelfToDescendent(View descendant, View root,
246 int[] coord) {
247 ArrayList<View> ancestorChain = new ArrayList<View>();
248
249 float[] pt = {coord[0], coord[1]};
250
251 View v = descendant;
252 while(v != root) {
253 ancestorChain.add(v);
254 v = (View) v.getParent();
255 }
256 ancestorChain.add(root);
257
258 float scale = 1.0f;
259 Matrix inverse = new Matrix();
260 int count = ancestorChain.size();
261 for (int i = count - 1; i >= 0; i--) {
262 View ancestor = ancestorChain.get(i);
263 View next = i > 0 ? ancestorChain.get(i-1) : null;
264
265 pt[0] += ancestor.getScrollX();
266 pt[1] += ancestor.getScrollY();
267
268 if (next != null) {
269 pt[0] -= next.getLeft();
270 pt[1] -= next.getTop();
271 next.getMatrix().invert(inverse);
272 inverse.mapPoints(pt);
273 scale *= next.getScaleX();
274 }
275 }
276
277 coord[0] = (int) Math.round(pt[0]);
278 coord[1] = (int) Math.round(pt[1]);
279 return scale;
280 }
281
Jason Monk02dd7ae2014-04-15 15:23:31 -0400282 /**
283 * Utility method to determine whether the given point, in local coordinates,
284 * is inside the view, where the area of the view is expanded by the slop factor.
285 * This method is called while processing touch-move events to determine if the event
286 * is still within the view.
287 */
288 public static boolean pointInView(View v, float localX, float localY, float slop) {
289 return localX >= -slop && localY >= -slop && localX < (v.getWidth() + slop) &&
290 localY < (v.getHeight() + slop);
291 }
292
Joe Onorato6665c0f2009-09-02 15:27:24 -0700293 private static void initStatics(Context context) {
294 final Resources resources = context.getResources();
Michael Jurkac9a96192010-11-01 11:52:08 -0700295 sIconWidth = sIconHeight = (int) resources.getDimension(R.dimen.app_icon_size);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700296 }
297
Winson Chung5f8afe62013-08-12 16:19:28 -0700298 public static void setIconSize(int widthPx) {
299 sIconWidth = sIconHeight = widthPx;
Winson Chung97d85d22011-04-13 11:27:36 -0700300 }
Michael Jurkaa805e1a2013-08-22 15:00:33 +0200301
Winson Chung3a6e7f32013-10-09 15:50:52 -0700302 public static void scaleRect(Rect r, float scale) {
303 if (scale != 1.0f) {
304 r.left = (int) (r.left * scale + 0.5f);
305 r.top = (int) (r.top * scale + 0.5f);
306 r.right = (int) (r.right * scale + 0.5f);
307 r.bottom = (int) (r.bottom * scale + 0.5f);
308 }
309 }
310
Adam Cohen63f1ec02014-08-12 09:23:13 -0700311 public static int[] getCenterDeltaInScreenSpace(View v0, View v1, int[] delta) {
312 v0.getLocationInWindow(sLoc0);
313 v1.getLocationInWindow(sLoc1);
314
315 sLoc0[0] += (v0.getMeasuredWidth() * v0.getScaleX()) / 2;
316 sLoc0[1] += (v0.getMeasuredHeight() * v0.getScaleY()) / 2;
317 sLoc1[0] += (v1.getMeasuredWidth() * v1.getScaleX()) / 2;
318 sLoc1[1] += (v1.getMeasuredHeight() * v1.getScaleY()) / 2;
319
320 if (delta == null) {
321 delta = new int[2];
322 }
323
324 delta[0] = sLoc1[0] - sLoc0[0];
325 delta[1] = sLoc1[1] - sLoc0[1];
326
327 return delta;
328 }
329
Winson Chung3a6e7f32013-10-09 15:50:52 -0700330 public static void scaleRectAboutCenter(Rect r, float scale) {
331 int cx = r.centerX();
332 int cy = r.centerY();
333 r.offset(-cx, -cy);
334 Utilities.scaleRect(r, scale);
335 r.offset(cx, cy);
336 }
337
Michael Jurkaa805e1a2013-08-22 15:00:33 +0200338 public static void startActivityForResultSafely(
339 Activity activity, Intent intent, int requestCode) {
340 try {
341 activity.startActivityForResult(intent, requestCode);
342 } catch (ActivityNotFoundException e) {
343 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
344 } catch (SecurityException e) {
345 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
346 Log.e(TAG, "Launcher does not have the permission to launch " + intent +
347 ". Make sure to create a MAIN intent-filter for the corresponding activity " +
348 "or use the exported attribute for this activity.", e);
349 }
350 }
Sunny Goyalc5c60ad2014-07-14 12:02:01 -0700351
352 static boolean isSystemApp(Context context, Intent intent) {
353 PackageManager pm = context.getPackageManager();
354 ComponentName cn = intent.getComponent();
355 String packageName = null;
356 if (cn == null) {
357 ResolveInfo info = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
358 if ((info != null) && (info.activityInfo != null)) {
359 packageName = info.activityInfo.packageName;
360 }
361 } else {
362 packageName = cn.getPackageName();
363 }
364 if (packageName != null) {
365 try {
366 PackageInfo info = pm.getPackageInfo(packageName, 0);
367 return (info != null) && (info.applicationInfo != null) &&
368 ((info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
369 } catch (NameNotFoundException e) {
370 return false;
371 }
372 } else {
373 return false;
374 }
375 }
Sunny Goyal95abbb32014-08-04 10:53:22 -0700376
377 /**
378 * This picks a dominant color, looking for high-saturation, high-value, repeated hues.
379 * @param bitmap The bitmap to scan
380 * @param samples The approximate max number of samples to use.
381 */
382 static int findDominantColorByHue(Bitmap bitmap, int samples) {
383 final int height = bitmap.getHeight();
384 final int width = bitmap.getWidth();
385 int sampleStride = (int) Math.sqrt((height * width) / samples);
386 if (sampleStride < 1) {
387 sampleStride = 1;
388 }
389
390 // This is an out-param, for getting the hsv values for an rgb
391 float[] hsv = new float[3];
392
393 // First get the best hue, by creating a histogram over 360 hue buckets,
394 // where each pixel contributes a score weighted by saturation, value, and alpha.
395 float[] hueScoreHistogram = new float[360];
396 float highScore = -1;
397 int bestHue = -1;
398
399 for (int y = 0; y < height; y += sampleStride) {
400 for (int x = 0; x < width; x += sampleStride) {
401 int argb = bitmap.getPixel(x, y);
402 int alpha = 0xFF & (argb >> 24);
403 if (alpha < 0x80) {
404 // Drop mostly-transparent pixels.
405 continue;
406 }
407 // Remove the alpha channel.
408 int rgb = argb | 0xFF000000;
409 Color.colorToHSV(rgb, hsv);
410 // Bucket colors by the 360 integer hues.
411 int hue = (int) hsv[0];
412 if (hue < 0 || hue >= hueScoreHistogram.length) {
413 // Defensively avoid array bounds violations.
414 continue;
415 }
416 float score = hsv[1] * hsv[2];
417 hueScoreHistogram[hue] += score;
418 if (hueScoreHistogram[hue] > highScore) {
419 highScore = hueScoreHistogram[hue];
420 bestHue = hue;
421 }
422 }
423 }
424
425 SparseArray<Float> rgbScores = new SparseArray<Float>();
426 int bestColor = 0xff000000;
427 highScore = -1;
428 // Go back over the RGB colors that match the winning hue,
429 // creating a histogram of weighted s*v scores, for up to 100*100 [s,v] buckets.
430 // The highest-scoring RGB color wins.
431 for (int y = 0; y < height; y += sampleStride) {
432 for (int x = 0; x < width; x += sampleStride) {
433 int rgb = bitmap.getPixel(x, y) | 0xff000000;
434 Color.colorToHSV(rgb, hsv);
435 int hue = (int) hsv[0];
436 if (hue == bestHue) {
437 float s = hsv[1];
438 float v = hsv[2];
439 int bucket = (int) (s * 100) + (int) (v * 10000);
440 // Score by cumulative saturation * value.
441 float score = s * v;
442 Float oldTotal = rgbScores.get(bucket);
443 float newTotal = oldTotal == null ? score : oldTotal + score;
444 rgbScores.put(bucket, newTotal);
445 if (newTotal > highScore) {
446 highScore = newTotal;
447 // All the colors in the winning bucket are very similar. Last in wins.
448 bestColor = rgb;
449 }
450 }
451 }
452 }
453 return bestColor;
454 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700455
456 /*
457 * Finds a system apk which had a broadcast receiver listening to a particular action.
458 * @param action intent action used to find the apk
459 * @return a pair of apk package name and the resources.
460 */
461 static Pair<String, Resources> findSystemApk(String action, PackageManager pm) {
462 final Intent intent = new Intent(action);
463 for (ResolveInfo info : pm.queryBroadcastReceivers(intent, 0)) {
464 if (info.activityInfo != null &&
465 (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
466 final String packageName = info.activityInfo.packageName;
467 try {
468 final Resources res = pm.getResourcesForApplication(packageName);
469 return Pair.create(packageName, res);
470 } catch (NameNotFoundException e) {
471 Log.w(TAG, "Failed to find resources for " + packageName);
472 }
473 }
474 }
475 return null;
476 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800477}