blob: 9f47e138d46db36e40dc96ec91409b7cad26279e [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;
Sunny Goyalc5c60ad2014-07-14 12:02:01 -070028import android.content.pm.ApplicationInfo;
29import android.content.pm.PackageInfo;
30import android.content.pm.PackageManager;
31import android.content.pm.PackageManager.NameNotFoundException;
32import android.content.pm.ResolveInfo;
Winson Chungaafa03c2010-06-11 17:34:16 -070033import android.content.res.Resources;
Sunny Goyal4fbc3822015-02-18 16:46:50 -080034import android.database.Cursor;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080035import android.graphics.Bitmap;
Sunny Goyal4fbc3822015-02-18 16:46:50 -080036import android.graphics.BitmapFactory;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080037import android.graphics.Canvas;
Sunny Goyal95abbb32014-08-04 10:53:22 -070038import android.graphics.Color;
Winson Chungc763c4e2013-07-19 13:49:06 -070039import android.graphics.Matrix;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080040import android.graphics.Paint;
Joe Onoratobf15cb42009-08-07 14:33:40 -070041import android.graphics.PaintFlagsDrawFilter;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080042import android.graphics.Rect;
Winson Chungaafa03c2010-06-11 17:34:16 -070043import android.graphics.drawable.BitmapDrawable;
44import android.graphics.drawable.Drawable;
45import android.graphics.drawable.PaintDrawable;
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -070046import android.os.Build;
Hyunyoung Song2bd3d7d2015-05-21 13:04:53 -070047import android.os.Process;
Sunny Goyal5c97f512015-05-19 16:03:28 -070048import android.text.TextUtils;
Michael Jurkaa805e1a2013-08-22 15:00:33 +020049import android.util.Log;
Sunny Goyal0fe505b2014-08-06 09:55:36 -070050import android.util.Pair;
Sunny Goyal95abbb32014-08-04 10:53:22 -070051import android.util.SparseArray;
Winson Chungc763c4e2013-07-19 13:49:06 -070052import android.view.View;
Michael Jurkaa805e1a2013-08-22 15:00:33 +020053import android.widget.Toast;
Winson Chungc763c4e2013-07-19 13:49:06 -070054
Sunny Goyal5c97f512015-05-19 16:03:28 -070055import junit.framework.Assert;
56
Sunny Goyal5b0e6692015-03-19 14:31:19 -070057import java.io.ByteArrayOutputStream;
58import java.io.IOException;
Winson Chungc763c4e2013-07-19 13:49:06 -070059import java.util.ArrayList;
Sunny Goyal08f72612015-01-05 13:41:43 -080060import java.util.Comparator;
Winson Chung82b016c2015-05-08 17:00:10 -070061import java.util.regex.Matcher;
62import java.util.regex.Pattern;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080063
64/**
65 * Various utilities shared amongst the Launcher's classes.
66 */
Mathew Inwood72fbec12013-11-19 15:45:07 +000067public final class Utilities {
Joe Onorato1291a8c2009-09-15 15:07:25 -040068 private static final String TAG = "Launcher.Utilities";
69
The Android Open Source Project31dd5032009-03-03 19:32:27 -080070 private static int sIconWidth = -1;
71 private static int sIconHeight = -1;
72
The Android Open Source Project31dd5032009-03-03 19:32:27 -080073 private static final Rect sOldBounds = new Rect();
Romain Guy89911d22009-09-28 18:48:49 -070074 private static final Canvas sCanvas = new Canvas();
The Android Open Source Project31dd5032009-03-03 19:32:27 -080075
Winson Chung82b016c2015-05-08 17:00:10 -070076 private static final Pattern sTrimPattern =
77 Pattern.compile("^[\\s|\\p{javaSpaceChar}]*(.*)[\\s|\\p{javaSpaceChar}]*$");
78
The Android Open Source Project31dd5032009-03-03 19:32:27 -080079 static {
80 sCanvas.setDrawFilter(new PaintFlagsDrawFilter(Paint.DITHER_FLAG,
81 Paint.FILTER_BITMAP_FLAG));
82 }
Joe Onorato6665c0f2009-09-02 15:27:24 -070083 static int sColors[] = { 0xffff0000, 0xff00ff00, 0xff0000ff };
84 static int sColorIndex = 0;
85
Adam Cohen63f1ec02014-08-12 09:23:13 -070086 static int[] sLoc0 = new int[2];
87 static int[] sLoc1 = new int[2];
Michael Jurka7ad868b2013-12-12 15:04:25 +010088
89 // To turn on these properties, type
90 // adb shell setprop log.tag.PROPERTY_NAME [VERBOSE | SUPPRESS]
91 static final String FORCE_ENABLE_ROTATION_PROPERTY = "launcher_force_rotate";
92 public static boolean sForceEnableRotation = isPropertyEnabled(FORCE_ENABLE_ROTATION_PROPERTY);
93
Joe Onorato6665c0f2009-09-02 15:27:24 -070094 /**
Winson Chung0dbd7342013-10-13 22:46:20 -070095 * Returns a FastBitmapDrawable with the icon, accurately sized.
96 */
Sunny Goyalffe83f12014-08-14 17:39:34 -070097 public static FastBitmapDrawable createIconDrawable(Bitmap icon) {
Winson Chung0dbd7342013-10-13 22:46:20 -070098 FastBitmapDrawable d = new FastBitmapDrawable(icon);
Winson Chung54000492013-10-14 16:29:29 -070099 d.setFilterBitmap(true);
Winson Chung0dbd7342013-10-13 22:46:20 -0700100 resizeIconDrawable(d);
101 return d;
102 }
103
104 /**
105 * Resizes an icon drawable to the correct icon size.
106 */
107 static void resizeIconDrawable(Drawable icon) {
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700108 icon.setBounds(0, 0, sIconWidth, sIconHeight);
Winson Chung0dbd7342013-10-13 22:46:20 -0700109 }
110
Sunny Goyal4bbf4192014-11-11 12:23:59 -0800111 public static boolean isPropertyEnabled(String propertyName) {
Michael Jurka7ad868b2013-12-12 15:04:25 +0100112 return Log.isLoggable(propertyName, Log.VERBOSE);
113 }
114
115 public static boolean isRotationEnabled(Context c) {
116 boolean enableRotation = sForceEnableRotation ||
117 c.getResources().getBoolean(R.bool.allow_rotation);
118 return enableRotation;
119 }
120
Winson Chung0dbd7342013-10-13 22:46:20 -0700121 /**
Kenny Guyd794a3f2014-09-16 15:17:58 +0100122 * Indicates if the device is running LMP or higher.
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -0700123 */
Kenny Guyd794a3f2014-09-16 15:17:58 +0100124 public static boolean isLmpOrAbove() {
Brian Parfett1bc1ae62014-12-12 12:30:00 -0800125 return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -0700126 }
127
Sunny Goyal4fbc3822015-02-18 16:46:50 -0800128 static Bitmap createIconBitmap(Cursor c, int iconIndex, Context context) {
129 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 */
141 static Bitmap createIconBitmap(String packageName, String resourceName, IconCache cache,
142 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(
150 resources.getDrawableForDensity(id, cache.getFullResIconDpi()), context);
151 }
152 } catch (Exception e) {
153 // Icon not found.
154 }
155 return null;
156 }
157
158 /**
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700159 * Returns a bitmap which is of the appropriate size to be displayed as an icon
Michael Jurka931dc972011-08-05 15:08:15 -0700160 */
161 static Bitmap createIconBitmap(Bitmap icon, Context context) {
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700162 synchronized (sCanvas) { // we share the statics :-(
163 if (sIconWidth == -1) {
164 initStatics(context);
165 }
Michael Jurka931dc972011-08-05 15:08:15 -0700166 }
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700167 if (sIconWidth == icon.getWidth() && sIconHeight == icon.getHeight()) {
168 return icon;
169 }
170 return createIconBitmap(new BitmapDrawable(context.getResources(), icon), context);
Michael Jurka931dc972011-08-05 15:08:15 -0700171 }
172
173 /**
174 * Returns a bitmap suitable for the all apps view.
Joe Onorato6665c0f2009-09-02 15:27:24 -0700175 */
Mathew Inwood72fbec12013-11-19 15:45:07 +0000176 public static Bitmap createIconBitmap(Drawable icon, Context context) {
Joe Onorato6665c0f2009-09-02 15:27:24 -0700177 synchronized (sCanvas) { // we share the statics :-(
178 if (sIconWidth == -1) {
179 initStatics(context);
180 }
181
182 int width = sIconWidth;
183 int height = sIconHeight;
184
Joe Onorato6665c0f2009-09-02 15:27:24 -0700185 if (icon instanceof PaintDrawable) {
186 PaintDrawable painter = (PaintDrawable) icon;
187 painter.setIntrinsicWidth(width);
188 painter.setIntrinsicHeight(height);
189 } else if (icon instanceof BitmapDrawable) {
190 // Ensure the bitmap has a density.
191 BitmapDrawable bitmapDrawable = (BitmapDrawable) icon;
192 Bitmap bitmap = bitmapDrawable.getBitmap();
193 if (bitmap.getDensity() == Bitmap.DENSITY_NONE) {
194 bitmapDrawable.setTargetDensity(context.getResources().getDisplayMetrics());
195 }
196 }
197 int sourceWidth = icon.getIntrinsicWidth();
198 int sourceHeight = icon.getIntrinsicHeight();
Michael Jurka931dc972011-08-05 15:08:15 -0700199 if (sourceWidth > 0 && sourceHeight > 0) {
Winson Chung5f8afe62013-08-12 16:19:28 -0700200 // Scale the icon proportionally to the icon dimensions
201 final float ratio = (float) sourceWidth / sourceHeight;
202 if (sourceWidth > sourceHeight) {
203 height = (int) (width / ratio);
204 } else if (sourceHeight > sourceWidth) {
205 width = (int) (height * ratio);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700206 }
207 }
208
209 // no intrinsic size --> use default size
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700210 int textureWidth = sIconWidth;
211 int textureHeight = sIconHeight;
Joe Onorato6665c0f2009-09-02 15:27:24 -0700212
213 final Bitmap bitmap = Bitmap.createBitmap(textureWidth, textureHeight,
214 Bitmap.Config.ARGB_8888);
215 final Canvas canvas = sCanvas;
216 canvas.setBitmap(bitmap);
217
218 final int left = (textureWidth-width) / 2;
219 final int top = (textureHeight-height) / 2;
220
Michael Jurka3a9fced2012-04-13 14:44:29 -0700221 @SuppressWarnings("all") // suppress dead code warning
222 final boolean debug = false;
223 if (debug) {
Joe Onorato6665c0f2009-09-02 15:27:24 -0700224 // draw a big box for the icon for debugging
225 canvas.drawColor(sColors[sColorIndex]);
226 if (++sColorIndex >= sColors.length) sColorIndex = 0;
227 Paint debugPaint = new Paint();
228 debugPaint.setColor(0xffcccc00);
229 canvas.drawRect(left, top, left+width, top+height, debugPaint);
230 }
231
232 sOldBounds.set(icon.getBounds());
233 icon.setBounds(left, top, left+width, top+height);
234 icon.draw(canvas);
235 icon.setBounds(sOldBounds);
Adam Cohenaaf473c2011-08-03 12:02:47 -0700236 canvas.setBitmap(null);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700237
238 return bitmap;
239 }
240 }
241
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800242 /**
Winson Chungc763c4e2013-07-19 13:49:06 -0700243 * Given a coordinate relative to the descendant, find the coordinate in a parent view's
244 * coordinates.
245 *
246 * @param descendant The descendant to which the passed coordinate is relative.
247 * @param root The root view to make the coordinates relative to.
248 * @param coord The coordinate that we want mapped.
249 * @param includeRootScroll Whether or not to account for the scroll of the descendant:
250 * sometimes this is relevant as in a child's coordinates within the descendant.
251 * @return The factor by which this descendant is scaled relative to this DragLayer. Caution
252 * this scale factor is assumed to be equal in X and Y, and so if at any point this
253 * assumption fails, we will need to return a pair of scale factors.
254 */
255 public static float getDescendantCoordRelativeToParent(View descendant, View root,
256 int[] coord, boolean includeRootScroll) {
257 ArrayList<View> ancestorChain = new ArrayList<View>();
258
259 float[] pt = {coord[0], coord[1]};
260
261 View v = descendant;
262 while(v != root && v != null) {
263 ancestorChain.add(v);
264 v = (View) v.getParent();
265 }
266 ancestorChain.add(root);
267
268 float scale = 1.0f;
269 int count = ancestorChain.size();
270 for (int i = 0; i < count; i++) {
271 View v0 = ancestorChain.get(i);
Winson Chungc763c4e2013-07-19 13:49:06 -0700272 // For TextViews, scroll has a meaning which relates to the text position
273 // which is very strange... ignore the scroll.
274 if (v0 != descendant || includeRootScroll) {
275 pt[0] -= v0.getScrollX();
276 pt[1] -= v0.getScrollY();
277 }
278
279 v0.getMatrix().mapPoints(pt);
280 pt[0] += v0.getLeft();
281 pt[1] += v0.getTop();
282 scale *= v0.getScaleX();
283 }
284
285 coord[0] = (int) Math.round(pt[0]);
286 coord[1] = (int) Math.round(pt[1]);
287 return scale;
288 }
289
290 /**
291 * Inverse of {@link #getDescendantCoordRelativeToSelf(View, int[])}.
292 */
293 public static float mapCoordInSelfToDescendent(View descendant, View root,
294 int[] coord) {
295 ArrayList<View> ancestorChain = new ArrayList<View>();
296
297 float[] pt = {coord[0], coord[1]};
298
299 View v = descendant;
300 while(v != root) {
301 ancestorChain.add(v);
302 v = (View) v.getParent();
303 }
304 ancestorChain.add(root);
305
306 float scale = 1.0f;
307 Matrix inverse = new Matrix();
308 int count = ancestorChain.size();
309 for (int i = count - 1; i >= 0; i--) {
310 View ancestor = ancestorChain.get(i);
311 View next = i > 0 ? ancestorChain.get(i-1) : null;
312
313 pt[0] += ancestor.getScrollX();
314 pt[1] += ancestor.getScrollY();
315
316 if (next != null) {
317 pt[0] -= next.getLeft();
318 pt[1] -= next.getTop();
319 next.getMatrix().invert(inverse);
320 inverse.mapPoints(pt);
321 scale *= next.getScaleX();
322 }
323 }
324
325 coord[0] = (int) Math.round(pt[0]);
326 coord[1] = (int) Math.round(pt[1]);
327 return scale;
328 }
329
Jason Monk02dd7ae2014-04-15 15:23:31 -0400330 /**
331 * Utility method to determine whether the given point, in local coordinates,
332 * is inside the view, where the area of the view is expanded by the slop factor.
333 * This method is called while processing touch-move events to determine if the event
334 * is still within the view.
335 */
336 public static boolean pointInView(View v, float localX, float localY, float slop) {
337 return localX >= -slop && localY >= -slop && localX < (v.getWidth() + slop) &&
338 localY < (v.getHeight() + slop);
339 }
340
Joe Onorato6665c0f2009-09-02 15:27:24 -0700341 private static void initStatics(Context context) {
342 final Resources resources = context.getResources();
Michael Jurkac9a96192010-11-01 11:52:08 -0700343 sIconWidth = sIconHeight = (int) resources.getDimension(R.dimen.app_icon_size);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700344 }
345
Winson Chung5f8afe62013-08-12 16:19:28 -0700346 public static void setIconSize(int widthPx) {
347 sIconWidth = sIconHeight = widthPx;
Winson Chung97d85d22011-04-13 11:27:36 -0700348 }
Michael Jurkaa805e1a2013-08-22 15:00:33 +0200349
Winson Chung3a6e7f32013-10-09 15:50:52 -0700350 public static void scaleRect(Rect r, float scale) {
351 if (scale != 1.0f) {
352 r.left = (int) (r.left * scale + 0.5f);
353 r.top = (int) (r.top * scale + 0.5f);
354 r.right = (int) (r.right * scale + 0.5f);
355 r.bottom = (int) (r.bottom * scale + 0.5f);
356 }
357 }
358
Adam Cohen63f1ec02014-08-12 09:23:13 -0700359 public static int[] getCenterDeltaInScreenSpace(View v0, View v1, int[] delta) {
360 v0.getLocationInWindow(sLoc0);
361 v1.getLocationInWindow(sLoc1);
362
363 sLoc0[0] += (v0.getMeasuredWidth() * v0.getScaleX()) / 2;
364 sLoc0[1] += (v0.getMeasuredHeight() * v0.getScaleY()) / 2;
365 sLoc1[0] += (v1.getMeasuredWidth() * v1.getScaleX()) / 2;
366 sLoc1[1] += (v1.getMeasuredHeight() * v1.getScaleY()) / 2;
367
368 if (delta == null) {
369 delta = new int[2];
370 }
371
372 delta[0] = sLoc1[0] - sLoc0[0];
373 delta[1] = sLoc1[1] - sLoc0[1];
374
375 return delta;
376 }
377
Winson Chung3a6e7f32013-10-09 15:50:52 -0700378 public static void scaleRectAboutCenter(Rect r, float scale) {
379 int cx = r.centerX();
380 int cy = r.centerY();
381 r.offset(-cx, -cy);
382 Utilities.scaleRect(r, scale);
383 r.offset(cx, cy);
384 }
385
Michael Jurkaa805e1a2013-08-22 15:00:33 +0200386 public static void startActivityForResultSafely(
387 Activity activity, Intent intent, int requestCode) {
388 try {
389 activity.startActivityForResult(intent, requestCode);
390 } catch (ActivityNotFoundException e) {
391 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
392 } catch (SecurityException e) {
393 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
394 Log.e(TAG, "Launcher does not have the permission to launch " + intent +
395 ". Make sure to create a MAIN intent-filter for the corresponding activity " +
396 "or use the exported attribute for this activity.", e);
397 }
398 }
Sunny Goyalc5c60ad2014-07-14 12:02:01 -0700399
400 static boolean isSystemApp(Context context, Intent intent) {
401 PackageManager pm = context.getPackageManager();
402 ComponentName cn = intent.getComponent();
403 String packageName = null;
404 if (cn == null) {
405 ResolveInfo info = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
406 if ((info != null) && (info.activityInfo != null)) {
407 packageName = info.activityInfo.packageName;
408 }
409 } else {
410 packageName = cn.getPackageName();
411 }
412 if (packageName != null) {
413 try {
414 PackageInfo info = pm.getPackageInfo(packageName, 0);
415 return (info != null) && (info.applicationInfo != null) &&
416 ((info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
417 } catch (NameNotFoundException e) {
418 return false;
419 }
420 } else {
421 return false;
422 }
423 }
Sunny Goyal95abbb32014-08-04 10:53:22 -0700424
425 /**
426 * This picks a dominant color, looking for high-saturation, high-value, repeated hues.
427 * @param bitmap The bitmap to scan
428 * @param samples The approximate max number of samples to use.
429 */
430 static int findDominantColorByHue(Bitmap bitmap, int samples) {
431 final int height = bitmap.getHeight();
432 final int width = bitmap.getWidth();
433 int sampleStride = (int) Math.sqrt((height * width) / samples);
434 if (sampleStride < 1) {
435 sampleStride = 1;
436 }
437
438 // This is an out-param, for getting the hsv values for an rgb
439 float[] hsv = new float[3];
440
441 // First get the best hue, by creating a histogram over 360 hue buckets,
442 // where each pixel contributes a score weighted by saturation, value, and alpha.
443 float[] hueScoreHistogram = new float[360];
444 float highScore = -1;
445 int bestHue = -1;
446
447 for (int y = 0; y < height; y += sampleStride) {
448 for (int x = 0; x < width; x += sampleStride) {
449 int argb = bitmap.getPixel(x, y);
450 int alpha = 0xFF & (argb >> 24);
451 if (alpha < 0x80) {
452 // Drop mostly-transparent pixels.
453 continue;
454 }
455 // Remove the alpha channel.
456 int rgb = argb | 0xFF000000;
457 Color.colorToHSV(rgb, hsv);
458 // Bucket colors by the 360 integer hues.
459 int hue = (int) hsv[0];
460 if (hue < 0 || hue >= hueScoreHistogram.length) {
461 // Defensively avoid array bounds violations.
462 continue;
463 }
464 float score = hsv[1] * hsv[2];
465 hueScoreHistogram[hue] += score;
466 if (hueScoreHistogram[hue] > highScore) {
467 highScore = hueScoreHistogram[hue];
468 bestHue = hue;
469 }
470 }
471 }
472
473 SparseArray<Float> rgbScores = new SparseArray<Float>();
474 int bestColor = 0xff000000;
475 highScore = -1;
476 // Go back over the RGB colors that match the winning hue,
477 // creating a histogram of weighted s*v scores, for up to 100*100 [s,v] buckets.
478 // The highest-scoring RGB color wins.
479 for (int y = 0; y < height; y += sampleStride) {
480 for (int x = 0; x < width; x += sampleStride) {
481 int rgb = bitmap.getPixel(x, y) | 0xff000000;
482 Color.colorToHSV(rgb, hsv);
483 int hue = (int) hsv[0];
484 if (hue == bestHue) {
485 float s = hsv[1];
486 float v = hsv[2];
487 int bucket = (int) (s * 100) + (int) (v * 10000);
488 // Score by cumulative saturation * value.
489 float score = s * v;
490 Float oldTotal = rgbScores.get(bucket);
491 float newTotal = oldTotal == null ? score : oldTotal + score;
492 rgbScores.put(bucket, newTotal);
493 if (newTotal > highScore) {
494 highScore = newTotal;
495 // All the colors in the winning bucket are very similar. Last in wins.
496 bestColor = rgb;
497 }
498 }
499 }
500 }
501 return bestColor;
502 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700503
504 /*
505 * Finds a system apk which had a broadcast receiver listening to a particular action.
506 * @param action intent action used to find the apk
507 * @return a pair of apk package name and the resources.
508 */
509 static Pair<String, Resources> findSystemApk(String action, PackageManager pm) {
510 final Intent intent = new Intent(action);
511 for (ResolveInfo info : pm.queryBroadcastReceivers(intent, 0)) {
512 if (info.activityInfo != null &&
513 (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
514 final String packageName = info.activityInfo.packageName;
515 try {
516 final Resources res = pm.getResourcesForApplication(packageName);
517 return Pair.create(packageName, res);
518 } catch (NameNotFoundException e) {
519 Log.w(TAG, "Failed to find resources for " + packageName);
520 }
521 }
522 }
523 return null;
524 }
Sunny Goyalfafca522014-11-03 11:30:01 -0800525
526 @TargetApi(Build.VERSION_CODES.KITKAT)
527 public static boolean isViewAttachedToWindow(View v) {
528 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
529 return v.isAttachedToWindow();
530 } else {
531 // A proxy call which returns null, if the view is not attached to the window.
532 return v.getKeyDispatcherState() != null;
533 }
534 }
Sunny Goyal594d76d2014-11-06 10:12:54 -0800535
536 /**
537 * Returns a widget with category {@link AppWidgetProviderInfo#WIDGET_CATEGORY_SEARCHBOX}
538 * provided by the same package which is set to be global search activity.
539 * If widgetCategory is not supported, or no such widget is found, returns the first widget
540 * provided by the package.
541 */
542 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
543 public static AppWidgetProviderInfo getSearchWidgetProvider(Context context) {
544 SearchManager searchManager =
545 (SearchManager) context.getSystemService(Context.SEARCH_SERVICE);
546 ComponentName searchComponent = searchManager.getGlobalSearchActivity();
547 if (searchComponent == null) return null;
548 String providerPkg = searchComponent.getPackageName();
549
550 AppWidgetProviderInfo defaultWidgetForSearchPackage = null;
551
552 AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
553 for (AppWidgetProviderInfo info : appWidgetManager.getInstalledProviders()) {
554 if (info.provider.getPackageName().equals(providerPkg)) {
555 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
556 if ((info.widgetCategory & AppWidgetProviderInfo.WIDGET_CATEGORY_SEARCHBOX) != 0) {
557 return info;
558 } else if (defaultWidgetForSearchPackage == null) {
559 defaultWidgetForSearchPackage = info;
560 }
561 } else {
562 return info;
563 }
564 }
565 }
566 return defaultWidgetForSearchPackage;
567 }
Sunny Goyal08f72612015-01-05 13:41:43 -0800568
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700569 /**
570 * Compresses the bitmap to a byte array for serialization.
571 */
572 public static byte[] flattenBitmap(Bitmap bitmap) {
573 // Try go guesstimate how much space the icon will take when serialized
574 // to avoid unnecessary allocations/copies during the write.
575 int size = bitmap.getWidth() * bitmap.getHeight() * 4;
576 ByteArrayOutputStream out = new ByteArrayOutputStream(size);
577 try {
578 bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
579 out.flush();
580 out.close();
581 return out.toByteArray();
582 } catch (IOException e) {
583 Log.w(TAG, "Could not write bitmap");
584 return null;
585 }
586 }
587
Sunny Goyal08f72612015-01-05 13:41:43 -0800588 public static final Comparator<ItemInfo> RANK_COMPARATOR = new Comparator<ItemInfo>() {
589
590 @Override
591 public int compare(ItemInfo lhs, ItemInfo rhs) {
592 return lhs.rank - rhs.rank;
593 }
594 };
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700595
596 /**
597 * Find the first vacant cell, if there is one.
598 *
599 * @param vacant Holds the x and y coordinate of the vacant cell
600 * @param spanX Horizontal cell span.
601 * @param spanY Vertical cell span.
602 *
603 * @return true if a vacant cell was found
604 */
605 public static boolean findVacantCell(int[] vacant, int spanX, int spanY,
606 int xCount, int yCount, boolean[][] occupied) {
607
608 for (int y = 0; (y + spanY) <= yCount; y++) {
609 for (int x = 0; (x + spanX) <= xCount; x++) {
610 boolean available = !occupied[x][y];
611 out: for (int i = x; i < x + spanX; i++) {
612 for (int j = y; j < y + spanY; j++) {
613 available = available && !occupied[i][j];
614 if (!available) break out;
615 }
616 }
617
618 if (available) {
619 vacant[0] = x;
620 vacant[1] = y;
621 return true;
622 }
623 }
624 }
625
626 return false;
627 }
Winson Chung82b016c2015-05-08 17:00:10 -0700628
629 /**
630 * Trims the string, removing all whitespace at the beginning and end of the string.
631 * Non-breaking whitespaces are also removed.
632 */
633 public static String trim(CharSequence s) {
Winson Chungafa77e92015-05-15 12:04:03 -0700634 if (s == null) {
635 return null;
636 }
637
Winson Chung82b016c2015-05-08 17:00:10 -0700638 // Just strip any sequence of whitespace or java space characters from the beginning and end
639 Matcher m = sTrimPattern.matcher(s);
640 return m.replaceAll("$1");
641 }
Sunny Goyal70660032015-05-14 00:07:08 -0700642
643 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
644 public static boolean isRtl(Resources res) {
645 return (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) &&
646 (res.getConfiguration().getLayoutDirection() == View.LAYOUT_DIRECTION_RTL);
647 }
Hyunyoung Song2bd3d7d2015-05-21 13:04:53 -0700648
649 public static void assertWorkerThread() {
650 if (LauncherAppState.isDogfoodBuild()) {
651 Assert.assertTrue(LauncherModel.sWorkerThread.getThreadId() == Process.myTid());
652 }
653 }
Sunny Goyal5c97f512015-05-19 16:03:28 -0700654
655 /**
656 * Returns true if the intent is a valid launch intent for a launcher activity of an app.
657 * This is used to identify shortcuts which are different from the ones exposed by the
658 * applications' manifest file.
659 *
660 * @param launchIntent The intent that will be launched when the shortcut is clicked.
661 */
662 public static boolean isLauncherAppTarget(Intent launchIntent) {
663 return launchIntent != null
664 && Intent.ACTION_MAIN.equals(launchIntent.getAction())
665 && launchIntent.getComponent() != null
666 && launchIntent.getCategories() != null
667 && launchIntent.getCategories().size() == 1
668 && launchIntent.hasCategory(Intent.CATEGORY_LAUNCHER)
669 && launchIntent.getExtras() == null
670 && TextUtils.isEmpty(launchIntent.getDataString());
671 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800672}