blob: 0d13c69906183da55473c80ddd4dd4c7cad315da [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
Sunny Goyalfafca522014-11-03 11:30:01 -080019import android.annotation.TargetApi;
Michael Jurkaa805e1a2013-08-22 15:00:33 +020020import android.app.Activity;
Sunny Goyal594d76d2014-11-06 10:12:54 -080021import android.app.SearchManager;
22import android.appwidget.AppWidgetManager;
23import android.appwidget.AppWidgetProviderInfo;
Michael Jurkaa805e1a2013-08-22 15:00:33 +020024import android.content.ActivityNotFoundException;
Sunny Goyalc5c60ad2014-07-14 12:02:01 -070025import android.content.ComponentName;
Winson Chungaafa03c2010-06-11 17:34:16 -070026import android.content.Context;
Michael Jurkaa805e1a2013-08-22 15:00:33 +020027import android.content.Intent;
Rahul Chaturvedi7fc77ca2015-05-19 18:02:16 -070028import android.content.SharedPreferences;
Sunny Goyalc5c60ad2014-07-14 12:02:01 -070029import android.content.pm.ApplicationInfo;
30import android.content.pm.PackageInfo;
31import android.content.pm.PackageManager;
32import android.content.pm.PackageManager.NameNotFoundException;
33import android.content.pm.ResolveInfo;
Winson Chungaafa03c2010-06-11 17:34:16 -070034import android.content.res.Resources;
Sunny Goyal4fbc3822015-02-18 16:46:50 -080035import android.database.Cursor;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080036import android.graphics.Bitmap;
Sunny Goyal4fbc3822015-02-18 16:46:50 -080037import android.graphics.BitmapFactory;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080038import android.graphics.Canvas;
Sunny Goyal95abbb32014-08-04 10:53:22 -070039import android.graphics.Color;
Winson Chungc763c4e2013-07-19 13:49:06 -070040import android.graphics.Matrix;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080041import android.graphics.Paint;
Joe Onoratobf15cb42009-08-07 14:33:40 -070042import android.graphics.PaintFlagsDrawFilter;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080043import android.graphics.Rect;
Winson Chungaafa03c2010-06-11 17:34:16 -070044import android.graphics.drawable.BitmapDrawable;
45import android.graphics.drawable.Drawable;
46import android.graphics.drawable.PaintDrawable;
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -070047import android.os.Build;
Sunny Goyal4e5cc642015-06-25 16:37:44 -070048import android.os.Bundle;
Hyunyoung Song2bd3d7d2015-05-21 13:04:53 -070049import android.os.Process;
Sunny Goyal5c97f512015-05-19 16:03:28 -070050import android.text.TextUtils;
Adam Cohen2e6da152015-05-06 11:42:25 -070051import android.util.DisplayMetrics;
Michael Jurkaa805e1a2013-08-22 15:00:33 +020052import android.util.Log;
Sunny Goyal0fe505b2014-08-06 09:55:36 -070053import android.util.Pair;
Sunny Goyal95abbb32014-08-04 10:53:22 -070054import android.util.SparseArray;
Adam Cohen2e6da152015-05-06 11:42:25 -070055import android.util.TypedValue;
Winson Chungc763c4e2013-07-19 13:49:06 -070056import android.view.View;
Michael Jurkaa805e1a2013-08-22 15:00:33 +020057import android.widget.Toast;
Sunny Goyalb1622cc2015-06-10 16:00:42 -070058
Sunny Goyal5c97f512015-05-19 16:03:28 -070059import junit.framework.Assert;
60
Sunny Goyal5b0e6692015-03-19 14:31:19 -070061import java.io.ByteArrayOutputStream;
62import java.io.IOException;
Winson Chungc763c4e2013-07-19 13:49:06 -070063import java.util.ArrayList;
Sunny Goyal08f72612015-01-05 13:41:43 -080064import java.util.Comparator;
Sunny Goyalb1622cc2015-06-10 16:00:42 -070065import java.util.Locale;
Sunny Goyal4e5cc642015-06-25 16:37:44 -070066import java.util.Set;
Winson Chung82b016c2015-05-08 17:00:10 -070067import java.util.regex.Matcher;
68import java.util.regex.Pattern;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080069
70/**
71 * Various utilities shared amongst the Launcher's classes.
72 */
Mathew Inwood72fbec12013-11-19 15:45:07 +000073public final class Utilities {
Rahul Chaturvedi7fc77ca2015-05-19 18:02:16 -070074
Joe Onorato1291a8c2009-09-15 15:07:25 -040075 private static final String TAG = "Launcher.Utilities";
76
The Android Open Source Project31dd5032009-03-03 19:32:27 -080077 private static final Rect sOldBounds = new Rect();
Romain Guy89911d22009-09-28 18:48:49 -070078 private static final Canvas sCanvas = new Canvas();
The Android Open Source Project31dd5032009-03-03 19:32:27 -080079
Winson Chung82b016c2015-05-08 17:00:10 -070080 private static final Pattern sTrimPattern =
81 Pattern.compile("^[\\s|\\p{javaSpaceChar}]*(.*)[\\s|\\p{javaSpaceChar}]*$");
82
The Android Open Source Project31dd5032009-03-03 19:32:27 -080083 static {
84 sCanvas.setDrawFilter(new PaintFlagsDrawFilter(Paint.DITHER_FLAG,
85 Paint.FILTER_BITMAP_FLAG));
86 }
Joe Onorato6665c0f2009-09-02 15:27:24 -070087 static int sColors[] = { 0xffff0000, 0xff00ff00, 0xff0000ff };
88 static int sColorIndex = 0;
89
Sunny Goyal53d7ee42015-05-22 12:25:45 -070090 private static final int[] sLoc0 = new int[2];
91 private static final int[] sLoc1 = new int[2];
Michael Jurka7ad868b2013-12-12 15:04:25 +010092
93 // To turn on these properties, type
94 // adb shell setprop log.tag.PROPERTY_NAME [VERBOSE | SUPPRESS]
Sunny Goyal53d7ee42015-05-22 12:25:45 -070095 private static final String FORCE_ENABLE_ROTATION_PROPERTY = "launcher_force_rotate";
96 private static boolean sForceEnableRotation = isPropertyEnabled(FORCE_ENABLE_ROTATION_PROPERTY);
Michael Jurka7ad868b2013-12-12 15:04:25 +010097
Rahul Chaturvedi7fc77ca2015-05-19 18:02:16 -070098 public static final String ALLOW_ROTATION_PREFERENCE_KEY = "pref_allowRotation";
99
Sunny Goyal4bbf4192014-11-11 12:23:59 -0800100 public static boolean isPropertyEnabled(String propertyName) {
Michael Jurka7ad868b2013-12-12 15:04:25 +0100101 return Log.isLoggable(propertyName, Log.VERBOSE);
102 }
103
Rahul Chaturvedie863fed2015-06-15 14:09:42 -0400104 public static boolean isAllowRotationPrefEnabled(Context context, boolean multiProcess) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700105 SharedPreferences sharedPrefs = context.getSharedPreferences(
Rahul Chaturvedie863fed2015-06-15 14:09:42 -0400106 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE | (multiProcess ?
107 Context.MODE_MULTI_PROCESS : 0));
Rahul Chaturvedi7fc77ca2015-05-19 18:02:16 -0700108 boolean allowRotationPref = sharedPrefs.getBoolean(ALLOW_ROTATION_PREFERENCE_KEY, false);
109 return sForceEnableRotation || allowRotationPref;
110 }
111
112 public static boolean isRotationAllowedForDevice(Context context) {
113 return sForceEnableRotation || context.getResources().getBoolean(R.bool.allow_rotation);
Michael Jurka7ad868b2013-12-12 15:04:25 +0100114 }
115
Winson Chung0dbd7342013-10-13 22:46:20 -0700116 /**
Kenny Guyd794a3f2014-09-16 15:17:58 +0100117 * Indicates if the device is running LMP or higher.
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -0700118 */
Kenny Guyd794a3f2014-09-16 15:17:58 +0100119 public static boolean isLmpOrAbove() {
Brian Parfett1bc1ae62014-12-12 12:30:00 -0800120 return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -0700121 }
122
Adam Cohen15588932015-05-26 23:03:31 -0700123 public static boolean isLmpMR1OrAbove() {
124 // TODO(adamcohen): update to Build.VERSION_CODES.LOLLIPOP_MR1 once building against 22;
125 return Build.VERSION.SDK_INT >= 22;
126 }
127
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700128 public static Bitmap createIconBitmap(Cursor c, int iconIndex, Context context) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -0800129 byte[] data = c.getBlob(iconIndex);
130 try {
131 return createIconBitmap(BitmapFactory.decodeByteArray(data, 0, data.length), context);
132 } catch (Exception e) {
133 return null;
134 }
135 }
136
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -0700137 /**
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700138 * Returns a bitmap suitable for the all apps view. If the package or the resource do not
139 * exist, it returns null.
140 */
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700141 public static Bitmap createIconBitmap(String packageName, String resourceName,
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700142 Context context) {
143 PackageManager packageManager = context.getPackageManager();
144 // the resource
145 try {
146 Resources resources = packageManager.getResourcesForApplication(packageName);
147 if (resources != null) {
148 final int id = resources.getIdentifier(resourceName, null, null);
149 return createIconBitmap(
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700150 resources.getDrawableForDensity(id, LauncherAppState.getInstance()
151 .getInvariantDeviceProfile().fillResIconDpi), context);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700152 }
153 } catch (Exception e) {
154 // Icon not found.
155 }
156 return null;
157 }
158
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700159 private static int getIconBitmapSize() {
160 return LauncherAppState.getInstance().getInvariantDeviceProfile().iconBitmapSize;
161 }
162
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700163 /**
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700164 * Returns a bitmap which is of the appropriate size to be displayed as an icon
Michael Jurka931dc972011-08-05 15:08:15 -0700165 */
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700166 public static Bitmap createIconBitmap(Bitmap icon, Context context) {
167 final int iconBitmapSize = getIconBitmapSize();
168 if (iconBitmapSize == icon.getWidth() && iconBitmapSize == icon.getHeight()) {
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700169 return icon;
170 }
171 return createIconBitmap(new BitmapDrawable(context.getResources(), icon), context);
Michael Jurka931dc972011-08-05 15:08:15 -0700172 }
173
174 /**
175 * Returns a bitmap suitable for the all apps view.
Joe Onorato6665c0f2009-09-02 15:27:24 -0700176 */
Mathew Inwood72fbec12013-11-19 15:45:07 +0000177 public static Bitmap createIconBitmap(Drawable icon, Context context) {
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700178 synchronized (sCanvas) {
179 final int iconBitmapSize = getIconBitmapSize();
Joe Onorato6665c0f2009-09-02 15:27:24 -0700180
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700181 int width = iconBitmapSize;
182 int height = iconBitmapSize;
Joe Onorato6665c0f2009-09-02 15:27:24 -0700183
Joe Onorato6665c0f2009-09-02 15:27:24 -0700184 if (icon instanceof PaintDrawable) {
185 PaintDrawable painter = (PaintDrawable) icon;
186 painter.setIntrinsicWidth(width);
187 painter.setIntrinsicHeight(height);
188 } else if (icon instanceof BitmapDrawable) {
189 // Ensure the bitmap has a density.
190 BitmapDrawable bitmapDrawable = (BitmapDrawable) icon;
191 Bitmap bitmap = bitmapDrawable.getBitmap();
192 if (bitmap.getDensity() == Bitmap.DENSITY_NONE) {
193 bitmapDrawable.setTargetDensity(context.getResources().getDisplayMetrics());
194 }
195 }
196 int sourceWidth = icon.getIntrinsicWidth();
197 int sourceHeight = icon.getIntrinsicHeight();
Michael Jurka931dc972011-08-05 15:08:15 -0700198 if (sourceWidth > 0 && sourceHeight > 0) {
Winson Chung5f8afe62013-08-12 16:19:28 -0700199 // Scale the icon proportionally to the icon dimensions
200 final float ratio = (float) sourceWidth / sourceHeight;
201 if (sourceWidth > sourceHeight) {
202 height = (int) (width / ratio);
203 } else if (sourceHeight > sourceWidth) {
204 width = (int) (height * ratio);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700205 }
206 }
207
208 // no intrinsic size --> use default size
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700209 int textureWidth = iconBitmapSize;
210 int textureHeight = iconBitmapSize;
Joe Onorato6665c0f2009-09-02 15:27:24 -0700211
212 final Bitmap bitmap = Bitmap.createBitmap(textureWidth, textureHeight,
213 Bitmap.Config.ARGB_8888);
214 final Canvas canvas = sCanvas;
215 canvas.setBitmap(bitmap);
216
217 final int left = (textureWidth-width) / 2;
218 final int top = (textureHeight-height) / 2;
219
Michael Jurka3a9fced2012-04-13 14:44:29 -0700220 @SuppressWarnings("all") // suppress dead code warning
221 final boolean debug = false;
222 if (debug) {
Joe Onorato6665c0f2009-09-02 15:27:24 -0700223 // draw a big box for the icon for debugging
224 canvas.drawColor(sColors[sColorIndex]);
225 if (++sColorIndex >= sColors.length) sColorIndex = 0;
226 Paint debugPaint = new Paint();
227 debugPaint.setColor(0xffcccc00);
228 canvas.drawRect(left, top, left+width, top+height, debugPaint);
229 }
230
231 sOldBounds.set(icon.getBounds());
232 icon.setBounds(left, top, left+width, top+height);
233 icon.draw(canvas);
234 icon.setBounds(sOldBounds);
Adam Cohenaaf473c2011-08-03 12:02:47 -0700235 canvas.setBitmap(null);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700236
237 return bitmap;
238 }
239 }
240
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800241 /**
Winson Chungc763c4e2013-07-19 13:49:06 -0700242 * Given a coordinate relative to the descendant, find the coordinate in a parent view's
243 * coordinates.
244 *
245 * @param descendant The descendant to which the passed coordinate is relative.
246 * @param root The root view to make the coordinates relative to.
247 * @param coord The coordinate that we want mapped.
248 * @param includeRootScroll Whether or not to account for the scroll of the descendant:
249 * sometimes this is relevant as in a child's coordinates within the descendant.
250 * @return The factor by which this descendant is scaled relative to this DragLayer. Caution
251 * this scale factor is assumed to be equal in X and Y, and so if at any point this
252 * assumption fails, we will need to return a pair of scale factors.
253 */
254 public static float getDescendantCoordRelativeToParent(View descendant, View root,
255 int[] coord, boolean includeRootScroll) {
256 ArrayList<View> ancestorChain = new ArrayList<View>();
257
258 float[] pt = {coord[0], coord[1]};
259
260 View v = descendant;
261 while(v != root && v != null) {
262 ancestorChain.add(v);
263 v = (View) v.getParent();
264 }
265 ancestorChain.add(root);
266
267 float scale = 1.0f;
268 int count = ancestorChain.size();
269 for (int i = 0; i < count; i++) {
270 View v0 = ancestorChain.get(i);
Winson Chungc763c4e2013-07-19 13:49:06 -0700271 // For TextViews, scroll has a meaning which relates to the text position
272 // which is very strange... ignore the scroll.
273 if (v0 != descendant || includeRootScroll) {
274 pt[0] -= v0.getScrollX();
275 pt[1] -= v0.getScrollY();
276 }
277
278 v0.getMatrix().mapPoints(pt);
279 pt[0] += v0.getLeft();
280 pt[1] += v0.getTop();
281 scale *= v0.getScaleX();
282 }
283
284 coord[0] = (int) Math.round(pt[0]);
285 coord[1] = (int) Math.round(pt[1]);
286 return scale;
287 }
288
289 /**
290 * Inverse of {@link #getDescendantCoordRelativeToSelf(View, int[])}.
291 */
292 public static float mapCoordInSelfToDescendent(View descendant, View root,
293 int[] coord) {
294 ArrayList<View> ancestorChain = new ArrayList<View>();
295
296 float[] pt = {coord[0], coord[1]};
297
298 View v = descendant;
299 while(v != root) {
300 ancestorChain.add(v);
301 v = (View) v.getParent();
302 }
303 ancestorChain.add(root);
304
305 float scale = 1.0f;
306 Matrix inverse = new Matrix();
307 int count = ancestorChain.size();
308 for (int i = count - 1; i >= 0; i--) {
309 View ancestor = ancestorChain.get(i);
310 View next = i > 0 ? ancestorChain.get(i-1) : null;
311
312 pt[0] += ancestor.getScrollX();
313 pt[1] += ancestor.getScrollY();
314
315 if (next != null) {
316 pt[0] -= next.getLeft();
317 pt[1] -= next.getTop();
318 next.getMatrix().invert(inverse);
319 inverse.mapPoints(pt);
320 scale *= next.getScaleX();
321 }
322 }
323
324 coord[0] = (int) Math.round(pt[0]);
325 coord[1] = (int) Math.round(pt[1]);
326 return scale;
327 }
328
Jason Monk02dd7ae2014-04-15 15:23:31 -0400329 /**
330 * Utility method to determine whether the given point, in local coordinates,
331 * is inside the view, where the area of the view is expanded by the slop factor.
332 * This method is called while processing touch-move events to determine if the event
333 * is still within the view.
334 */
335 public static boolean pointInView(View v, float localX, float localY, float slop) {
336 return localX >= -slop && localY >= -slop && localX < (v.getWidth() + slop) &&
337 localY < (v.getHeight() + slop);
338 }
339
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
Adam Cohen63f1ec02014-08-12 09:23:13 -0700349 public static int[] getCenterDeltaInScreenSpace(View v0, View v1, int[] delta) {
350 v0.getLocationInWindow(sLoc0);
351 v1.getLocationInWindow(sLoc1);
352
353 sLoc0[0] += (v0.getMeasuredWidth() * v0.getScaleX()) / 2;
354 sLoc0[1] += (v0.getMeasuredHeight() * v0.getScaleY()) / 2;
355 sLoc1[0] += (v1.getMeasuredWidth() * v1.getScaleX()) / 2;
356 sLoc1[1] += (v1.getMeasuredHeight() * v1.getScaleY()) / 2;
357
358 if (delta == null) {
359 delta = new int[2];
360 }
361
362 delta[0] = sLoc1[0] - sLoc0[0];
363 delta[1] = sLoc1[1] - sLoc0[1];
364
365 return delta;
366 }
367
Winson Chung3a6e7f32013-10-09 15:50:52 -0700368 public static void scaleRectAboutCenter(Rect r, float scale) {
369 int cx = r.centerX();
370 int cy = r.centerY();
371 r.offset(-cx, -cy);
372 Utilities.scaleRect(r, scale);
373 r.offset(cx, cy);
374 }
375
Michael Jurkaa805e1a2013-08-22 15:00:33 +0200376 public static void startActivityForResultSafely(
377 Activity activity, Intent intent, int requestCode) {
378 try {
379 activity.startActivityForResult(intent, requestCode);
380 } catch (ActivityNotFoundException e) {
381 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
382 } catch (SecurityException e) {
383 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
384 Log.e(TAG, "Launcher does not have the permission to launch " + intent +
385 ". Make sure to create a MAIN intent-filter for the corresponding activity " +
386 "or use the exported attribute for this activity.", e);
387 }
388 }
Sunny Goyalc5c60ad2014-07-14 12:02:01 -0700389
390 static boolean isSystemApp(Context context, Intent intent) {
391 PackageManager pm = context.getPackageManager();
392 ComponentName cn = intent.getComponent();
393 String packageName = null;
394 if (cn == null) {
395 ResolveInfo info = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
396 if ((info != null) && (info.activityInfo != null)) {
397 packageName = info.activityInfo.packageName;
398 }
399 } else {
400 packageName = cn.getPackageName();
401 }
402 if (packageName != null) {
403 try {
404 PackageInfo info = pm.getPackageInfo(packageName, 0);
405 return (info != null) && (info.applicationInfo != null) &&
406 ((info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
407 } catch (NameNotFoundException e) {
408 return false;
409 }
410 } else {
411 return false;
412 }
413 }
Sunny Goyal95abbb32014-08-04 10:53:22 -0700414
415 /**
416 * This picks a dominant color, looking for high-saturation, high-value, repeated hues.
417 * @param bitmap The bitmap to scan
418 * @param samples The approximate max number of samples to use.
419 */
420 static int findDominantColorByHue(Bitmap bitmap, int samples) {
421 final int height = bitmap.getHeight();
422 final int width = bitmap.getWidth();
423 int sampleStride = (int) Math.sqrt((height * width) / samples);
424 if (sampleStride < 1) {
425 sampleStride = 1;
426 }
427
428 // This is an out-param, for getting the hsv values for an rgb
429 float[] hsv = new float[3];
430
431 // First get the best hue, by creating a histogram over 360 hue buckets,
432 // where each pixel contributes a score weighted by saturation, value, and alpha.
433 float[] hueScoreHistogram = new float[360];
434 float highScore = -1;
435 int bestHue = -1;
436
437 for (int y = 0; y < height; y += sampleStride) {
438 for (int x = 0; x < width; x += sampleStride) {
439 int argb = bitmap.getPixel(x, y);
440 int alpha = 0xFF & (argb >> 24);
441 if (alpha < 0x80) {
442 // Drop mostly-transparent pixels.
443 continue;
444 }
445 // Remove the alpha channel.
446 int rgb = argb | 0xFF000000;
447 Color.colorToHSV(rgb, hsv);
448 // Bucket colors by the 360 integer hues.
449 int hue = (int) hsv[0];
450 if (hue < 0 || hue >= hueScoreHistogram.length) {
451 // Defensively avoid array bounds violations.
452 continue;
453 }
454 float score = hsv[1] * hsv[2];
455 hueScoreHistogram[hue] += score;
456 if (hueScoreHistogram[hue] > highScore) {
457 highScore = hueScoreHistogram[hue];
458 bestHue = hue;
459 }
460 }
461 }
462
463 SparseArray<Float> rgbScores = new SparseArray<Float>();
464 int bestColor = 0xff000000;
465 highScore = -1;
466 // Go back over the RGB colors that match the winning hue,
467 // creating a histogram of weighted s*v scores, for up to 100*100 [s,v] buckets.
468 // The highest-scoring RGB color wins.
469 for (int y = 0; y < height; y += sampleStride) {
470 for (int x = 0; x < width; x += sampleStride) {
471 int rgb = bitmap.getPixel(x, y) | 0xff000000;
472 Color.colorToHSV(rgb, hsv);
473 int hue = (int) hsv[0];
474 if (hue == bestHue) {
475 float s = hsv[1];
476 float v = hsv[2];
477 int bucket = (int) (s * 100) + (int) (v * 10000);
478 // Score by cumulative saturation * value.
479 float score = s * v;
480 Float oldTotal = rgbScores.get(bucket);
481 float newTotal = oldTotal == null ? score : oldTotal + score;
482 rgbScores.put(bucket, newTotal);
483 if (newTotal > highScore) {
484 highScore = newTotal;
485 // All the colors in the winning bucket are very similar. Last in wins.
486 bestColor = rgb;
487 }
488 }
489 }
490 }
491 return bestColor;
492 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700493
494 /*
495 * Finds a system apk which had a broadcast receiver listening to a particular action.
496 * @param action intent action used to find the apk
497 * @return a pair of apk package name and the resources.
498 */
499 static Pair<String, Resources> findSystemApk(String action, PackageManager pm) {
500 final Intent intent = new Intent(action);
501 for (ResolveInfo info : pm.queryBroadcastReceivers(intent, 0)) {
502 if (info.activityInfo != null &&
503 (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
504 final String packageName = info.activityInfo.packageName;
505 try {
506 final Resources res = pm.getResourcesForApplication(packageName);
507 return Pair.create(packageName, res);
508 } catch (NameNotFoundException e) {
509 Log.w(TAG, "Failed to find resources for " + packageName);
510 }
511 }
512 }
513 return null;
514 }
Sunny Goyalfafca522014-11-03 11:30:01 -0800515
516 @TargetApi(Build.VERSION_CODES.KITKAT)
517 public static boolean isViewAttachedToWindow(View v) {
518 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
519 return v.isAttachedToWindow();
520 } else {
521 // A proxy call which returns null, if the view is not attached to the window.
522 return v.getKeyDispatcherState() != null;
523 }
524 }
Sunny Goyal594d76d2014-11-06 10:12:54 -0800525
526 /**
527 * Returns a widget with category {@link AppWidgetProviderInfo#WIDGET_CATEGORY_SEARCHBOX}
528 * provided by the same package which is set to be global search activity.
529 * If widgetCategory is not supported, or no such widget is found, returns the first widget
530 * provided by the package.
531 */
532 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
533 public static AppWidgetProviderInfo getSearchWidgetProvider(Context context) {
534 SearchManager searchManager =
535 (SearchManager) context.getSystemService(Context.SEARCH_SERVICE);
536 ComponentName searchComponent = searchManager.getGlobalSearchActivity();
537 if (searchComponent == null) return null;
538 String providerPkg = searchComponent.getPackageName();
539
540 AppWidgetProviderInfo defaultWidgetForSearchPackage = null;
541
542 AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
543 for (AppWidgetProviderInfo info : appWidgetManager.getInstalledProviders()) {
544 if (info.provider.getPackageName().equals(providerPkg)) {
545 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
546 if ((info.widgetCategory & AppWidgetProviderInfo.WIDGET_CATEGORY_SEARCHBOX) != 0) {
547 return info;
548 } else if (defaultWidgetForSearchPackage == null) {
549 defaultWidgetForSearchPackage = info;
550 }
551 } else {
552 return info;
553 }
554 }
555 }
556 return defaultWidgetForSearchPackage;
557 }
Sunny Goyal08f72612015-01-05 13:41:43 -0800558
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700559 /**
560 * Compresses the bitmap to a byte array for serialization.
561 */
562 public static byte[] flattenBitmap(Bitmap bitmap) {
563 // Try go guesstimate how much space the icon will take when serialized
564 // to avoid unnecessary allocations/copies during the write.
565 int size = bitmap.getWidth() * bitmap.getHeight() * 4;
566 ByteArrayOutputStream out = new ByteArrayOutputStream(size);
567 try {
568 bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
569 out.flush();
570 out.close();
571 return out.toByteArray();
572 } catch (IOException e) {
573 Log.w(TAG, "Could not write bitmap");
574 return null;
575 }
576 }
577
Sunny Goyal08f72612015-01-05 13:41:43 -0800578 public static final Comparator<ItemInfo> RANK_COMPARATOR = new Comparator<ItemInfo>() {
Sunny Goyal08f72612015-01-05 13:41:43 -0800579 @Override
580 public int compare(ItemInfo lhs, ItemInfo rhs) {
581 return lhs.rank - rhs.rank;
582 }
583 };
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700584
585 /**
586 * Find the first vacant cell, if there is one.
587 *
588 * @param vacant Holds the x and y coordinate of the vacant cell
589 * @param spanX Horizontal cell span.
590 * @param spanY Vertical cell span.
591 *
592 * @return true if a vacant cell was found
593 */
594 public static boolean findVacantCell(int[] vacant, int spanX, int spanY,
595 int xCount, int yCount, boolean[][] occupied) {
596
597 for (int y = 0; (y + spanY) <= yCount; y++) {
598 for (int x = 0; (x + spanX) <= xCount; x++) {
599 boolean available = !occupied[x][y];
600 out: for (int i = x; i < x + spanX; i++) {
601 for (int j = y; j < y + spanY; j++) {
602 available = available && !occupied[i][j];
603 if (!available) break out;
604 }
605 }
606
607 if (available) {
608 vacant[0] = x;
609 vacant[1] = y;
610 return true;
611 }
612 }
613 }
614
615 return false;
616 }
Winson Chung82b016c2015-05-08 17:00:10 -0700617
618 /**
619 * Trims the string, removing all whitespace at the beginning and end of the string.
620 * Non-breaking whitespaces are also removed.
621 */
622 public static String trim(CharSequence s) {
Winson Chungafa77e92015-05-15 12:04:03 -0700623 if (s == null) {
624 return null;
625 }
626
Winson Chung82b016c2015-05-08 17:00:10 -0700627 // Just strip any sequence of whitespace or java space characters from the beginning and end
628 Matcher m = sTrimPattern.matcher(s);
629 return m.replaceAll("$1");
630 }
Sunny Goyal70660032015-05-14 00:07:08 -0700631
Winson Chung2c6e5cc2015-06-01 14:38:24 -0700632 /**
633 * Calculates the height of a given string at a specific text size.
634 */
635 public static float calculateTextHeight(float textSizePx) {
636 Paint p = new Paint();
637 p.setTextSize(textSizePx);
638 Paint.FontMetrics fm = p.getFontMetrics();
639 return -fm.top + fm.bottom;
640 }
641
Winson Chungb1777442015-06-16 13:35:04 -0700642 /**
643 * Convenience println with multiple args.
644 */
645 public static void println(String key, Object... args) {
646 StringBuilder b = new StringBuilder();
647 b.append(key);
648 b.append(": ");
649 boolean isFirstArgument = true;
650 for (Object arg : args) {
651 if (isFirstArgument) {
652 isFirstArgument = false;
653 } else {
654 b.append(", ");
655 }
656 b.append(arg);
657 }
658 System.out.println(b.toString());
659 }
660
Sunny Goyal70660032015-05-14 00:07:08 -0700661 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
662 public static boolean isRtl(Resources res) {
663 return (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) &&
664 (res.getConfiguration().getLayoutDirection() == View.LAYOUT_DIRECTION_RTL);
665 }
Hyunyoung Song2bd3d7d2015-05-21 13:04:53 -0700666
667 public static void assertWorkerThread() {
668 if (LauncherAppState.isDogfoodBuild()) {
669 Assert.assertTrue(LauncherModel.sWorkerThread.getThreadId() == Process.myTid());
670 }
671 }
Sunny Goyal5c97f512015-05-19 16:03:28 -0700672
673 /**
674 * Returns true if the intent is a valid launch intent for a launcher activity of an app.
675 * This is used to identify shortcuts which are different from the ones exposed by the
676 * applications' manifest file.
677 *
678 * @param launchIntent The intent that will be launched when the shortcut is clicked.
679 */
680 public static boolean isLauncherAppTarget(Intent launchIntent) {
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700681 if (launchIntent != null
Sunny Goyal5c97f512015-05-19 16:03:28 -0700682 && Intent.ACTION_MAIN.equals(launchIntent.getAction())
683 && launchIntent.getComponent() != null
684 && launchIntent.getCategories() != null
685 && launchIntent.getCategories().size() == 1
686 && launchIntent.hasCategory(Intent.CATEGORY_LAUNCHER)
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700687 && TextUtils.isEmpty(launchIntent.getDataString())) {
688 // An app target can either have no extra or have ItemInfo.EXTRA_PROFILE.
689 Bundle extras = launchIntent.getExtras();
690 if (extras == null) {
691 return true;
692 } else {
693 Set<String> keys = extras.keySet();
694 return keys.size() == 1 && keys.contains(ItemInfo.EXTRA_PROFILE);
695 }
696 };
697 return false;
Sunny Goyal5c97f512015-05-19 16:03:28 -0700698 }
Adam Cohen2e6da152015-05-06 11:42:25 -0700699
700 public static float dpiFromPx(int size, DisplayMetrics metrics){
701 float densityRatio = (float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT;
702 return (size / densityRatio);
703 }
704 public static int pxFromDp(float size, DisplayMetrics metrics) {
705 return (int) Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
706 size, metrics));
707 }
708 public static int pxFromSp(float size, DisplayMetrics metrics) {
709 return (int) Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
710 size, metrics));
711 }
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700712
713 public static String createDbSelectionQuery(String columnName, Iterable<?> values) {
714 return String.format(Locale.ENGLISH, "%s IN (%s)", columnName, TextUtils.join(", ", values));
715 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800716}