blob: d0c24cd83ca52dde316803513bdf4af6e808fb61 [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 Goyal5b0e6692015-03-19 14:31:19 -070059import java.io.ByteArrayOutputStream;
60import java.io.IOException;
Winson Chungc763c4e2013-07-19 13:49:06 -070061import java.util.ArrayList;
Sunny Goyal08f72612015-01-05 13:41:43 -080062import java.util.Comparator;
Sunny Goyalb1622cc2015-06-10 16:00:42 -070063import java.util.Locale;
Sunny Goyal4e5cc642015-06-25 16:37:44 -070064import java.util.Set;
Winson Chung82b016c2015-05-08 17:00:10 -070065import java.util.regex.Matcher;
66import java.util.regex.Pattern;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080067
68/**
69 * Various utilities shared amongst the Launcher's classes.
70 */
Mathew Inwood72fbec12013-11-19 15:45:07 +000071public final class Utilities {
Rahul Chaturvedi7fc77ca2015-05-19 18:02:16 -070072
Joe Onorato1291a8c2009-09-15 15:07:25 -040073 private static final String TAG = "Launcher.Utilities";
74
The Android Open Source Project31dd5032009-03-03 19:32:27 -080075 private static final Rect sOldBounds = new Rect();
Romain Guy89911d22009-09-28 18:48:49 -070076 private static final Canvas sCanvas = new Canvas();
The Android Open Source Project31dd5032009-03-03 19:32:27 -080077
Winson Chung82b016c2015-05-08 17:00:10 -070078 private static final Pattern sTrimPattern =
79 Pattern.compile("^[\\s|\\p{javaSpaceChar}]*(.*)[\\s|\\p{javaSpaceChar}]*$");
80
The Android Open Source Project31dd5032009-03-03 19:32:27 -080081 static {
82 sCanvas.setDrawFilter(new PaintFlagsDrawFilter(Paint.DITHER_FLAG,
83 Paint.FILTER_BITMAP_FLAG));
84 }
Joe Onorato6665c0f2009-09-02 15:27:24 -070085 static int sColors[] = { 0xffff0000, 0xff00ff00, 0xff0000ff };
86 static int sColorIndex = 0;
87
Sunny Goyal53d7ee42015-05-22 12:25:45 -070088 private static final int[] sLoc0 = new int[2];
89 private static final int[] sLoc1 = new int[2];
Michael Jurka7ad868b2013-12-12 15:04:25 +010090
91 // To turn on these properties, type
92 // adb shell setprop log.tag.PROPERTY_NAME [VERBOSE | SUPPRESS]
Sunny Goyal53d7ee42015-05-22 12:25:45 -070093 private static final String FORCE_ENABLE_ROTATION_PROPERTY = "launcher_force_rotate";
94 private static boolean sForceEnableRotation = isPropertyEnabled(FORCE_ENABLE_ROTATION_PROPERTY);
Michael Jurka7ad868b2013-12-12 15:04:25 +010095
Rahul Chaturvedi7fc77ca2015-05-19 18:02:16 -070096 public static final String ALLOW_ROTATION_PREFERENCE_KEY = "pref_allowRotation";
97
Sunny Goyal4bbf4192014-11-11 12:23:59 -080098 public static boolean isPropertyEnabled(String propertyName) {
Michael Jurka7ad868b2013-12-12 15:04:25 +010099 return Log.isLoggable(propertyName, Log.VERBOSE);
100 }
101
Rahul Chaturvedie863fed2015-06-15 14:09:42 -0400102 public static boolean isAllowRotationPrefEnabled(Context context, boolean multiProcess) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700103 SharedPreferences sharedPrefs = context.getSharedPreferences(
Rahul Chaturvedie863fed2015-06-15 14:09:42 -0400104 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE | (multiProcess ?
105 Context.MODE_MULTI_PROCESS : 0));
Rahul Chaturvedi7fc77ca2015-05-19 18:02:16 -0700106 boolean allowRotationPref = sharedPrefs.getBoolean(ALLOW_ROTATION_PREFERENCE_KEY, false);
107 return sForceEnableRotation || allowRotationPref;
108 }
109
110 public static boolean isRotationAllowedForDevice(Context context) {
111 return sForceEnableRotation || context.getResources().getBoolean(R.bool.allow_rotation);
Michael Jurka7ad868b2013-12-12 15:04:25 +0100112 }
113
Winson Chung0dbd7342013-10-13 22:46:20 -0700114 /**
Kenny Guyd794a3f2014-09-16 15:17:58 +0100115 * Indicates if the device is running LMP or higher.
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -0700116 */
Kenny Guyd794a3f2014-09-16 15:17:58 +0100117 public static boolean isLmpOrAbove() {
Brian Parfett1bc1ae62014-12-12 12:30:00 -0800118 return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -0700119 }
120
Adam Cohen15588932015-05-26 23:03:31 -0700121 public static boolean isLmpMR1OrAbove() {
122 // TODO(adamcohen): update to Build.VERSION_CODES.LOLLIPOP_MR1 once building against 22;
123 return Build.VERSION.SDK_INT >= 22;
124 }
125
Adam Cohen947e02b2015-05-22 19:23:34 -0700126 public static boolean isLmpMR1() {
127 // TODO(adamcohen): update to Build.VERSION_CODES.LOLLIPOP_MR1 once building against 22;
128 return Build.VERSION.SDK_INT == 22;
129 }
130
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700131 public static Bitmap createIconBitmap(Cursor c, int iconIndex, Context context) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -0800132 byte[] data = c.getBlob(iconIndex);
133 try {
134 return createIconBitmap(BitmapFactory.decodeByteArray(data, 0, data.length), context);
135 } catch (Exception e) {
136 return null;
137 }
138 }
139
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -0700140 /**
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700141 * Returns a bitmap suitable for the all apps view. If the package or the resource do not
142 * exist, it returns null.
143 */
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700144 public static Bitmap createIconBitmap(String packageName, String resourceName,
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700145 Context context) {
146 PackageManager packageManager = context.getPackageManager();
147 // the resource
148 try {
149 Resources resources = packageManager.getResourcesForApplication(packageName);
150 if (resources != null) {
151 final int id = resources.getIdentifier(resourceName, null, null);
152 return createIconBitmap(
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700153 resources.getDrawableForDensity(id, LauncherAppState.getInstance()
154 .getInvariantDeviceProfile().fillResIconDpi), context);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700155 }
156 } catch (Exception e) {
157 // Icon not found.
158 }
159 return null;
160 }
161
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700162 private static int getIconBitmapSize() {
163 return LauncherAppState.getInstance().getInvariantDeviceProfile().iconBitmapSize;
164 }
165
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700166 /**
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700167 * Returns a bitmap which is of the appropriate size to be displayed as an icon
Michael Jurka931dc972011-08-05 15:08:15 -0700168 */
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700169 public static Bitmap createIconBitmap(Bitmap icon, Context context) {
170 final int iconBitmapSize = getIconBitmapSize();
171 if (iconBitmapSize == icon.getWidth() && iconBitmapSize == icon.getHeight()) {
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700172 return icon;
173 }
174 return createIconBitmap(new BitmapDrawable(context.getResources(), icon), context);
Michael Jurka931dc972011-08-05 15:08:15 -0700175 }
176
177 /**
178 * Returns a bitmap suitable for the all apps view.
Joe Onorato6665c0f2009-09-02 15:27:24 -0700179 */
Mathew Inwood72fbec12013-11-19 15:45:07 +0000180 public static Bitmap createIconBitmap(Drawable icon, Context context) {
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700181 synchronized (sCanvas) {
182 final int iconBitmapSize = getIconBitmapSize();
Joe Onorato6665c0f2009-09-02 15:27:24 -0700183
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700184 int width = iconBitmapSize;
185 int height = iconBitmapSize;
Joe Onorato6665c0f2009-09-02 15:27:24 -0700186
Joe Onorato6665c0f2009-09-02 15:27:24 -0700187 if (icon instanceof PaintDrawable) {
188 PaintDrawable painter = (PaintDrawable) icon;
189 painter.setIntrinsicWidth(width);
190 painter.setIntrinsicHeight(height);
191 } else if (icon instanceof BitmapDrawable) {
192 // Ensure the bitmap has a density.
193 BitmapDrawable bitmapDrawable = (BitmapDrawable) icon;
194 Bitmap bitmap = bitmapDrawable.getBitmap();
195 if (bitmap.getDensity() == Bitmap.DENSITY_NONE) {
196 bitmapDrawable.setTargetDensity(context.getResources().getDisplayMetrics());
197 }
198 }
199 int sourceWidth = icon.getIntrinsicWidth();
200 int sourceHeight = icon.getIntrinsicHeight();
Michael Jurka931dc972011-08-05 15:08:15 -0700201 if (sourceWidth > 0 && sourceHeight > 0) {
Winson Chung5f8afe62013-08-12 16:19:28 -0700202 // Scale the icon proportionally to the icon dimensions
203 final float ratio = (float) sourceWidth / sourceHeight;
204 if (sourceWidth > sourceHeight) {
205 height = (int) (width / ratio);
206 } else if (sourceHeight > sourceWidth) {
207 width = (int) (height * ratio);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700208 }
209 }
210
211 // no intrinsic size --> use default size
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700212 int textureWidth = iconBitmapSize;
213 int textureHeight = iconBitmapSize;
Joe Onorato6665c0f2009-09-02 15:27:24 -0700214
215 final Bitmap bitmap = Bitmap.createBitmap(textureWidth, textureHeight,
216 Bitmap.Config.ARGB_8888);
217 final Canvas canvas = sCanvas;
218 canvas.setBitmap(bitmap);
219
220 final int left = (textureWidth-width) / 2;
221 final int top = (textureHeight-height) / 2;
222
Michael Jurka3a9fced2012-04-13 14:44:29 -0700223 @SuppressWarnings("all") // suppress dead code warning
224 final boolean debug = false;
225 if (debug) {
Joe Onorato6665c0f2009-09-02 15:27:24 -0700226 // draw a big box for the icon for debugging
227 canvas.drawColor(sColors[sColorIndex]);
228 if (++sColorIndex >= sColors.length) sColorIndex = 0;
229 Paint debugPaint = new Paint();
230 debugPaint.setColor(0xffcccc00);
231 canvas.drawRect(left, top, left+width, top+height, debugPaint);
232 }
233
234 sOldBounds.set(icon.getBounds());
235 icon.setBounds(left, top, left+width, top+height);
236 icon.draw(canvas);
237 icon.setBounds(sOldBounds);
Adam Cohenaaf473c2011-08-03 12:02:47 -0700238 canvas.setBitmap(null);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700239
240 return bitmap;
241 }
242 }
243
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800244 /**
Winson Chungc763c4e2013-07-19 13:49:06 -0700245 * Given a coordinate relative to the descendant, find the coordinate in a parent view's
246 * coordinates.
247 *
248 * @param descendant The descendant to which the passed coordinate is relative.
249 * @param root The root view to make the coordinates relative to.
250 * @param coord The coordinate that we want mapped.
251 * @param includeRootScroll Whether or not to account for the scroll of the descendant:
252 * sometimes this is relevant as in a child's coordinates within the descendant.
253 * @return The factor by which this descendant is scaled relative to this DragLayer. Caution
254 * this scale factor is assumed to be equal in X and Y, and so if at any point this
255 * assumption fails, we will need to return a pair of scale factors.
256 */
257 public static float getDescendantCoordRelativeToParent(View descendant, View root,
258 int[] coord, boolean includeRootScroll) {
259 ArrayList<View> ancestorChain = new ArrayList<View>();
260
261 float[] pt = {coord[0], coord[1]};
262
263 View v = descendant;
264 while(v != root && v != null) {
265 ancestorChain.add(v);
266 v = (View) v.getParent();
267 }
268 ancestorChain.add(root);
269
270 float scale = 1.0f;
271 int count = ancestorChain.size();
272 for (int i = 0; i < count; i++) {
273 View v0 = ancestorChain.get(i);
Winson Chungc763c4e2013-07-19 13:49:06 -0700274 // For TextViews, scroll has a meaning which relates to the text position
275 // which is very strange... ignore the scroll.
276 if (v0 != descendant || includeRootScroll) {
277 pt[0] -= v0.getScrollX();
278 pt[1] -= v0.getScrollY();
279 }
280
281 v0.getMatrix().mapPoints(pt);
282 pt[0] += v0.getLeft();
283 pt[1] += v0.getTop();
284 scale *= v0.getScaleX();
285 }
286
287 coord[0] = (int) Math.round(pt[0]);
288 coord[1] = (int) Math.round(pt[1]);
289 return scale;
290 }
291
292 /**
293 * Inverse of {@link #getDescendantCoordRelativeToSelf(View, int[])}.
294 */
295 public static float mapCoordInSelfToDescendent(View descendant, View root,
296 int[] coord) {
297 ArrayList<View> ancestorChain = new ArrayList<View>();
298
299 float[] pt = {coord[0], coord[1]};
300
301 View v = descendant;
302 while(v != root) {
303 ancestorChain.add(v);
304 v = (View) v.getParent();
305 }
306 ancestorChain.add(root);
307
308 float scale = 1.0f;
309 Matrix inverse = new Matrix();
310 int count = ancestorChain.size();
311 for (int i = count - 1; i >= 0; i--) {
312 View ancestor = ancestorChain.get(i);
313 View next = i > 0 ? ancestorChain.get(i-1) : null;
314
315 pt[0] += ancestor.getScrollX();
316 pt[1] += ancestor.getScrollY();
317
318 if (next != null) {
319 pt[0] -= next.getLeft();
320 pt[1] -= next.getTop();
321 next.getMatrix().invert(inverse);
322 inverse.mapPoints(pt);
323 scale *= next.getScaleX();
324 }
325 }
326
327 coord[0] = (int) Math.round(pt[0]);
328 coord[1] = (int) Math.round(pt[1]);
329 return scale;
330 }
331
Jason Monk02dd7ae2014-04-15 15:23:31 -0400332 /**
333 * Utility method to determine whether the given point, in local coordinates,
334 * is inside the view, where the area of the view is expanded by the slop factor.
335 * This method is called while processing touch-move events to determine if the event
336 * is still within the view.
337 */
338 public static boolean pointInView(View v, float localX, float localY, float slop) {
339 return localX >= -slop && localY >= -slop && localX < (v.getWidth() + slop) &&
340 localY < (v.getHeight() + slop);
341 }
342
Winson Chung3a6e7f32013-10-09 15:50:52 -0700343 public static void scaleRect(Rect r, float scale) {
344 if (scale != 1.0f) {
345 r.left = (int) (r.left * scale + 0.5f);
346 r.top = (int) (r.top * scale + 0.5f);
347 r.right = (int) (r.right * scale + 0.5f);
348 r.bottom = (int) (r.bottom * scale + 0.5f);
349 }
350 }
351
Adam Cohen63f1ec02014-08-12 09:23:13 -0700352 public static int[] getCenterDeltaInScreenSpace(View v0, View v1, int[] delta) {
353 v0.getLocationInWindow(sLoc0);
354 v1.getLocationInWindow(sLoc1);
355
356 sLoc0[0] += (v0.getMeasuredWidth() * v0.getScaleX()) / 2;
357 sLoc0[1] += (v0.getMeasuredHeight() * v0.getScaleY()) / 2;
358 sLoc1[0] += (v1.getMeasuredWidth() * v1.getScaleX()) / 2;
359 sLoc1[1] += (v1.getMeasuredHeight() * v1.getScaleY()) / 2;
360
361 if (delta == null) {
362 delta = new int[2];
363 }
364
365 delta[0] = sLoc1[0] - sLoc0[0];
366 delta[1] = sLoc1[1] - sLoc0[1];
367
368 return delta;
369 }
370
Winson Chung3a6e7f32013-10-09 15:50:52 -0700371 public static void scaleRectAboutCenter(Rect r, float scale) {
372 int cx = r.centerX();
373 int cy = r.centerY();
374 r.offset(-cx, -cy);
375 Utilities.scaleRect(r, scale);
376 r.offset(cx, cy);
377 }
378
Michael Jurkaa805e1a2013-08-22 15:00:33 +0200379 public static void startActivityForResultSafely(
380 Activity activity, Intent intent, int requestCode) {
381 try {
382 activity.startActivityForResult(intent, requestCode);
383 } catch (ActivityNotFoundException e) {
384 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
385 } catch (SecurityException e) {
386 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
387 Log.e(TAG, "Launcher does not have the permission to launch " + intent +
388 ". Make sure to create a MAIN intent-filter for the corresponding activity " +
389 "or use the exported attribute for this activity.", e);
390 }
391 }
Sunny Goyalc5c60ad2014-07-14 12:02:01 -0700392
393 static boolean isSystemApp(Context context, Intent intent) {
394 PackageManager pm = context.getPackageManager();
395 ComponentName cn = intent.getComponent();
396 String packageName = null;
397 if (cn == null) {
398 ResolveInfo info = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
399 if ((info != null) && (info.activityInfo != null)) {
400 packageName = info.activityInfo.packageName;
401 }
402 } else {
403 packageName = cn.getPackageName();
404 }
405 if (packageName != null) {
406 try {
407 PackageInfo info = pm.getPackageInfo(packageName, 0);
408 return (info != null) && (info.applicationInfo != null) &&
409 ((info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
410 } catch (NameNotFoundException e) {
411 return false;
412 }
413 } else {
414 return false;
415 }
416 }
Sunny Goyal95abbb32014-08-04 10:53:22 -0700417
418 /**
419 * This picks a dominant color, looking for high-saturation, high-value, repeated hues.
420 * @param bitmap The bitmap to scan
421 * @param samples The approximate max number of samples to use.
422 */
423 static int findDominantColorByHue(Bitmap bitmap, int samples) {
424 final int height = bitmap.getHeight();
425 final int width = bitmap.getWidth();
426 int sampleStride = (int) Math.sqrt((height * width) / samples);
427 if (sampleStride < 1) {
428 sampleStride = 1;
429 }
430
431 // This is an out-param, for getting the hsv values for an rgb
432 float[] hsv = new float[3];
433
434 // First get the best hue, by creating a histogram over 360 hue buckets,
435 // where each pixel contributes a score weighted by saturation, value, and alpha.
436 float[] hueScoreHistogram = new float[360];
437 float highScore = -1;
438 int bestHue = -1;
439
440 for (int y = 0; y < height; y += sampleStride) {
441 for (int x = 0; x < width; x += sampleStride) {
442 int argb = bitmap.getPixel(x, y);
443 int alpha = 0xFF & (argb >> 24);
444 if (alpha < 0x80) {
445 // Drop mostly-transparent pixels.
446 continue;
447 }
448 // Remove the alpha channel.
449 int rgb = argb | 0xFF000000;
450 Color.colorToHSV(rgb, hsv);
451 // Bucket colors by the 360 integer hues.
452 int hue = (int) hsv[0];
453 if (hue < 0 || hue >= hueScoreHistogram.length) {
454 // Defensively avoid array bounds violations.
455 continue;
456 }
457 float score = hsv[1] * hsv[2];
458 hueScoreHistogram[hue] += score;
459 if (hueScoreHistogram[hue] > highScore) {
460 highScore = hueScoreHistogram[hue];
461 bestHue = hue;
462 }
463 }
464 }
465
466 SparseArray<Float> rgbScores = new SparseArray<Float>();
467 int bestColor = 0xff000000;
468 highScore = -1;
469 // Go back over the RGB colors that match the winning hue,
470 // creating a histogram of weighted s*v scores, for up to 100*100 [s,v] buckets.
471 // The highest-scoring RGB color wins.
472 for (int y = 0; y < height; y += sampleStride) {
473 for (int x = 0; x < width; x += sampleStride) {
474 int rgb = bitmap.getPixel(x, y) | 0xff000000;
475 Color.colorToHSV(rgb, hsv);
476 int hue = (int) hsv[0];
477 if (hue == bestHue) {
478 float s = hsv[1];
479 float v = hsv[2];
480 int bucket = (int) (s * 100) + (int) (v * 10000);
481 // Score by cumulative saturation * value.
482 float score = s * v;
483 Float oldTotal = rgbScores.get(bucket);
484 float newTotal = oldTotal == null ? score : oldTotal + score;
485 rgbScores.put(bucket, newTotal);
486 if (newTotal > highScore) {
487 highScore = newTotal;
488 // All the colors in the winning bucket are very similar. Last in wins.
489 bestColor = rgb;
490 }
491 }
492 }
493 }
494 return bestColor;
495 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700496
497 /*
498 * Finds a system apk which had a broadcast receiver listening to a particular action.
499 * @param action intent action used to find the apk
500 * @return a pair of apk package name and the resources.
501 */
502 static Pair<String, Resources> findSystemApk(String action, PackageManager pm) {
503 final Intent intent = new Intent(action);
504 for (ResolveInfo info : pm.queryBroadcastReceivers(intent, 0)) {
505 if (info.activityInfo != null &&
506 (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
507 final String packageName = info.activityInfo.packageName;
508 try {
509 final Resources res = pm.getResourcesForApplication(packageName);
510 return Pair.create(packageName, res);
511 } catch (NameNotFoundException e) {
512 Log.w(TAG, "Failed to find resources for " + packageName);
513 }
514 }
515 }
516 return null;
517 }
Sunny Goyalfafca522014-11-03 11:30:01 -0800518
519 @TargetApi(Build.VERSION_CODES.KITKAT)
520 public static boolean isViewAttachedToWindow(View v) {
521 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
522 return v.isAttachedToWindow();
523 } else {
524 // A proxy call which returns null, if the view is not attached to the window.
525 return v.getKeyDispatcherState() != null;
526 }
527 }
Sunny Goyal594d76d2014-11-06 10:12:54 -0800528
529 /**
530 * Returns a widget with category {@link AppWidgetProviderInfo#WIDGET_CATEGORY_SEARCHBOX}
531 * provided by the same package which is set to be global search activity.
532 * If widgetCategory is not supported, or no such widget is found, returns the first widget
533 * provided by the package.
534 */
535 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
536 public static AppWidgetProviderInfo getSearchWidgetProvider(Context context) {
537 SearchManager searchManager =
538 (SearchManager) context.getSystemService(Context.SEARCH_SERVICE);
539 ComponentName searchComponent = searchManager.getGlobalSearchActivity();
540 if (searchComponent == null) return null;
541 String providerPkg = searchComponent.getPackageName();
542
543 AppWidgetProviderInfo defaultWidgetForSearchPackage = null;
544
545 AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
546 for (AppWidgetProviderInfo info : appWidgetManager.getInstalledProviders()) {
547 if (info.provider.getPackageName().equals(providerPkg)) {
548 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
549 if ((info.widgetCategory & AppWidgetProviderInfo.WIDGET_CATEGORY_SEARCHBOX) != 0) {
550 return info;
551 } else if (defaultWidgetForSearchPackage == null) {
552 defaultWidgetForSearchPackage = info;
553 }
554 } else {
555 return info;
556 }
557 }
558 }
559 return defaultWidgetForSearchPackage;
560 }
Sunny Goyal08f72612015-01-05 13:41:43 -0800561
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700562 /**
563 * Compresses the bitmap to a byte array for serialization.
564 */
565 public static byte[] flattenBitmap(Bitmap bitmap) {
566 // Try go guesstimate how much space the icon will take when serialized
567 // to avoid unnecessary allocations/copies during the write.
568 int size = bitmap.getWidth() * bitmap.getHeight() * 4;
569 ByteArrayOutputStream out = new ByteArrayOutputStream(size);
570 try {
571 bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
572 out.flush();
573 out.close();
574 return out.toByteArray();
575 } catch (IOException e) {
576 Log.w(TAG, "Could not write bitmap");
577 return null;
578 }
579 }
580
Sunny Goyal08f72612015-01-05 13:41:43 -0800581 public static final Comparator<ItemInfo> RANK_COMPARATOR = new Comparator<ItemInfo>() {
Sunny Goyal08f72612015-01-05 13:41:43 -0800582 @Override
583 public int compare(ItemInfo lhs, ItemInfo rhs) {
584 return lhs.rank - rhs.rank;
585 }
586 };
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700587
588 /**
589 * Find the first vacant cell, if there is one.
590 *
591 * @param vacant Holds the x and y coordinate of the vacant cell
592 * @param spanX Horizontal cell span.
593 * @param spanY Vertical cell span.
594 *
595 * @return true if a vacant cell was found
596 */
597 public static boolean findVacantCell(int[] vacant, int spanX, int spanY,
598 int xCount, int yCount, boolean[][] occupied) {
599
600 for (int y = 0; (y + spanY) <= yCount; y++) {
601 for (int x = 0; (x + spanX) <= xCount; x++) {
602 boolean available = !occupied[x][y];
603 out: for (int i = x; i < x + spanX; i++) {
604 for (int j = y; j < y + spanY; j++) {
605 available = available && !occupied[i][j];
606 if (!available) break out;
607 }
608 }
609
610 if (available) {
611 vacant[0] = x;
612 vacant[1] = y;
613 return true;
614 }
615 }
616 }
617
618 return false;
619 }
Winson Chung82b016c2015-05-08 17:00:10 -0700620
621 /**
622 * Trims the string, removing all whitespace at the beginning and end of the string.
623 * Non-breaking whitespaces are also removed.
624 */
625 public static String trim(CharSequence s) {
Winson Chungafa77e92015-05-15 12:04:03 -0700626 if (s == null) {
627 return null;
628 }
629
Winson Chung82b016c2015-05-08 17:00:10 -0700630 // Just strip any sequence of whitespace or java space characters from the beginning and end
631 Matcher m = sTrimPattern.matcher(s);
632 return m.replaceAll("$1");
633 }
Sunny Goyal70660032015-05-14 00:07:08 -0700634
Winson Chung2c6e5cc2015-06-01 14:38:24 -0700635 /**
636 * Calculates the height of a given string at a specific text size.
637 */
638 public static float calculateTextHeight(float textSizePx) {
639 Paint p = new Paint();
640 p.setTextSize(textSizePx);
641 Paint.FontMetrics fm = p.getFontMetrics();
642 return -fm.top + fm.bottom;
643 }
644
Winson Chungb1777442015-06-16 13:35:04 -0700645 /**
646 * Convenience println with multiple args.
647 */
648 public static void println(String key, Object... args) {
649 StringBuilder b = new StringBuilder();
650 b.append(key);
651 b.append(": ");
652 boolean isFirstArgument = true;
653 for (Object arg : args) {
654 if (isFirstArgument) {
655 isFirstArgument = false;
656 } else {
657 b.append(", ");
658 }
659 b.append(arg);
660 }
661 System.out.println(b.toString());
662 }
663
Sunny Goyal70660032015-05-14 00:07:08 -0700664 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
665 public static boolean isRtl(Resources res) {
666 return (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) &&
667 (res.getConfiguration().getLayoutDirection() == View.LAYOUT_DIRECTION_RTL);
668 }
Hyunyoung Song2bd3d7d2015-05-21 13:04:53 -0700669
670 public static void assertWorkerThread() {
Sunny Goyal11d49112015-06-26 14:00:57 -0700671 if (LauncherAppState.isDogfoodBuild() &&
672 (LauncherModel.sWorkerThread.getThreadId() != Process.myTid())) {
673 throw new IllegalStateException();
Hyunyoung Song2bd3d7d2015-05-21 13:04:53 -0700674 }
675 }
Sunny Goyal5c97f512015-05-19 16:03:28 -0700676
677 /**
678 * Returns true if the intent is a valid launch intent for a launcher activity of an app.
679 * This is used to identify shortcuts which are different from the ones exposed by the
680 * applications' manifest file.
681 *
682 * @param launchIntent The intent that will be launched when the shortcut is clicked.
683 */
684 public static boolean isLauncherAppTarget(Intent launchIntent) {
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700685 if (launchIntent != null
Sunny Goyal5c97f512015-05-19 16:03:28 -0700686 && Intent.ACTION_MAIN.equals(launchIntent.getAction())
687 && launchIntent.getComponent() != null
688 && launchIntent.getCategories() != null
689 && launchIntent.getCategories().size() == 1
690 && launchIntent.hasCategory(Intent.CATEGORY_LAUNCHER)
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700691 && TextUtils.isEmpty(launchIntent.getDataString())) {
692 // An app target can either have no extra or have ItemInfo.EXTRA_PROFILE.
693 Bundle extras = launchIntent.getExtras();
694 if (extras == null) {
695 return true;
696 } else {
697 Set<String> keys = extras.keySet();
698 return keys.size() == 1 && keys.contains(ItemInfo.EXTRA_PROFILE);
699 }
700 };
701 return false;
Sunny Goyal5c97f512015-05-19 16:03:28 -0700702 }
Adam Cohen2e6da152015-05-06 11:42:25 -0700703
704 public static float dpiFromPx(int size, DisplayMetrics metrics){
705 float densityRatio = (float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT;
706 return (size / densityRatio);
707 }
708 public static int pxFromDp(float size, DisplayMetrics metrics) {
709 return (int) Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
710 size, metrics));
711 }
712 public static int pxFromSp(float size, DisplayMetrics metrics) {
713 return (int) Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
714 size, metrics));
715 }
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700716
717 public static String createDbSelectionQuery(String columnName, Iterable<?> values) {
718 return String.format(Locale.ENGLISH, "%s IN (%s)", columnName, TextUtils.join(", ", values));
719 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800720}