blob: 1f8a6f2a568e47e334a24f92022196613382db58 [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;
Michael Jurkaa805e1a2013-08-22 15:00:33 +020048import android.util.Log;
Sunny Goyal0fe505b2014-08-06 09:55:36 -070049import android.util.Pair;
Sunny Goyal95abbb32014-08-04 10:53:22 -070050import android.util.SparseArray;
Winson Chungc763c4e2013-07-19 13:49:06 -070051import android.view.View;
Michael Jurkaa805e1a2013-08-22 15:00:33 +020052import android.widget.Toast;
Winson Chungc763c4e2013-07-19 13:49:06 -070053
Sunny Goyal5b0e6692015-03-19 14:31:19 -070054import java.io.ByteArrayOutputStream;
55import java.io.IOException;
Winson Chungc763c4e2013-07-19 13:49:06 -070056import java.util.ArrayList;
Sunny Goyal08f72612015-01-05 13:41:43 -080057import java.util.Comparator;
Winson Chung82b016c2015-05-08 17:00:10 -070058import java.util.regex.Matcher;
59import java.util.regex.Pattern;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080060
Hyunyoung Song2bd3d7d2015-05-21 13:04:53 -070061import junit.framework.Assert;
62
The Android Open Source Project31dd5032009-03-03 19:32:27 -080063/**
64 * Various utilities shared amongst the Launcher's classes.
65 */
Mathew Inwood72fbec12013-11-19 15:45:07 +000066public final class Utilities {
Joe Onorato1291a8c2009-09-15 15:07:25 -040067 private static final String TAG = "Launcher.Utilities";
68
The Android Open Source Project31dd5032009-03-03 19:32:27 -080069 private static int sIconWidth = -1;
70 private static int sIconHeight = -1;
71
The Android Open Source Project31dd5032009-03-03 19:32:27 -080072 private static final Rect sOldBounds = new Rect();
Romain Guy89911d22009-09-28 18:48:49 -070073 private static final Canvas sCanvas = new Canvas();
The Android Open Source Project31dd5032009-03-03 19:32:27 -080074
Winson Chung82b016c2015-05-08 17:00:10 -070075 private static final Pattern sTrimPattern =
76 Pattern.compile("^[\\s|\\p{javaSpaceChar}]*(.*)[\\s|\\p{javaSpaceChar}]*$");
77
The Android Open Source Project31dd5032009-03-03 19:32:27 -080078 static {
79 sCanvas.setDrawFilter(new PaintFlagsDrawFilter(Paint.DITHER_FLAG,
80 Paint.FILTER_BITMAP_FLAG));
81 }
Joe Onorato6665c0f2009-09-02 15:27:24 -070082 static int sColors[] = { 0xffff0000, 0xff00ff00, 0xff0000ff };
83 static int sColorIndex = 0;
84
Adam Cohen63f1ec02014-08-12 09:23:13 -070085 static int[] sLoc0 = new int[2];
86 static int[] sLoc1 = new int[2];
Michael Jurka7ad868b2013-12-12 15:04:25 +010087
88 // To turn on these properties, type
89 // adb shell setprop log.tag.PROPERTY_NAME [VERBOSE | SUPPRESS]
90 static final String FORCE_ENABLE_ROTATION_PROPERTY = "launcher_force_rotate";
91 public static boolean sForceEnableRotation = isPropertyEnabled(FORCE_ENABLE_ROTATION_PROPERTY);
92
Joe Onorato6665c0f2009-09-02 15:27:24 -070093 /**
Winson Chung0dbd7342013-10-13 22:46:20 -070094 * Returns a FastBitmapDrawable with the icon, accurately sized.
95 */
Sunny Goyalffe83f12014-08-14 17:39:34 -070096 public static FastBitmapDrawable createIconDrawable(Bitmap icon) {
Winson Chung0dbd7342013-10-13 22:46:20 -070097 FastBitmapDrawable d = new FastBitmapDrawable(icon);
Winson Chung54000492013-10-14 16:29:29 -070098 d.setFilterBitmap(true);
Winson Chung0dbd7342013-10-13 22:46:20 -070099 resizeIconDrawable(d);
100 return d;
101 }
102
103 /**
104 * Resizes an icon drawable to the correct icon size.
105 */
106 static void resizeIconDrawable(Drawable icon) {
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700107 icon.setBounds(0, 0, sIconWidth, sIconHeight);
Winson Chung0dbd7342013-10-13 22:46:20 -0700108 }
109
Sunny Goyal4bbf4192014-11-11 12:23:59 -0800110 public static boolean isPropertyEnabled(String propertyName) {
Michael Jurka7ad868b2013-12-12 15:04:25 +0100111 return Log.isLoggable(propertyName, Log.VERBOSE);
112 }
113
114 public static boolean isRotationEnabled(Context c) {
115 boolean enableRotation = sForceEnableRotation ||
116 c.getResources().getBoolean(R.bool.allow_rotation);
117 return enableRotation;
118 }
119
Winson Chung0dbd7342013-10-13 22:46:20 -0700120 /**
Kenny Guyd794a3f2014-09-16 15:17:58 +0100121 * Indicates if the device is running LMP or higher.
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -0700122 */
Kenny Guyd794a3f2014-09-16 15:17:58 +0100123 public static boolean isLmpOrAbove() {
Brian Parfett1bc1ae62014-12-12 12:30:00 -0800124 return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -0700125 }
126
Sunny Goyal4fbc3822015-02-18 16:46:50 -0800127 static Bitmap createIconBitmap(Cursor c, int iconIndex, Context context) {
128 byte[] data = c.getBlob(iconIndex);
129 try {
130 return createIconBitmap(BitmapFactory.decodeByteArray(data, 0, data.length), context);
131 } catch (Exception e) {
132 return null;
133 }
134 }
135
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -0700136 /**
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700137 * Returns a bitmap suitable for the all apps view. If the package or the resource do not
138 * exist, it returns null.
139 */
140 static Bitmap createIconBitmap(String packageName, String resourceName, IconCache cache,
141 Context context) {
142 PackageManager packageManager = context.getPackageManager();
143 // the resource
144 try {
145 Resources resources = packageManager.getResourcesForApplication(packageName);
146 if (resources != null) {
147 final int id = resources.getIdentifier(resourceName, null, null);
148 return createIconBitmap(
149 resources.getDrawableForDensity(id, cache.getFullResIconDpi()), context);
150 }
151 } catch (Exception e) {
152 // Icon not found.
153 }
154 return null;
155 }
156
157 /**
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700158 * Returns a bitmap which is of the appropriate size to be displayed as an icon
Michael Jurka931dc972011-08-05 15:08:15 -0700159 */
160 static Bitmap createIconBitmap(Bitmap icon, Context context) {
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700161 synchronized (sCanvas) { // we share the statics :-(
162 if (sIconWidth == -1) {
163 initStatics(context);
164 }
Michael Jurka931dc972011-08-05 15:08:15 -0700165 }
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700166 if (sIconWidth == icon.getWidth() && sIconHeight == icon.getHeight()) {
167 return icon;
168 }
169 return createIconBitmap(new BitmapDrawable(context.getResources(), icon), context);
Michael Jurka931dc972011-08-05 15:08:15 -0700170 }
171
172 /**
173 * Returns a bitmap suitable for the all apps view.
Joe Onorato6665c0f2009-09-02 15:27:24 -0700174 */
Mathew Inwood72fbec12013-11-19 15:45:07 +0000175 public static Bitmap createIconBitmap(Drawable icon, Context context) {
Joe Onorato6665c0f2009-09-02 15:27:24 -0700176 synchronized (sCanvas) { // we share the statics :-(
177 if (sIconWidth == -1) {
178 initStatics(context);
179 }
180
181 int width = sIconWidth;
182 int height = sIconHeight;
183
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 Goyal2fce90c2014-10-07 12:01:58 -0700209 int textureWidth = sIconWidth;
210 int textureHeight = sIconHeight;
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
Joe Onorato6665c0f2009-09-02 15:27:24 -0700340 private static void initStatics(Context context) {
341 final Resources resources = context.getResources();
Michael Jurkac9a96192010-11-01 11:52:08 -0700342 sIconWidth = sIconHeight = (int) resources.getDimension(R.dimen.app_icon_size);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700343 }
344
Winson Chung5f8afe62013-08-12 16:19:28 -0700345 public static void setIconSize(int widthPx) {
346 sIconWidth = sIconHeight = widthPx;
Winson Chung97d85d22011-04-13 11:27:36 -0700347 }
Michael Jurkaa805e1a2013-08-22 15:00:33 +0200348
Winson Chung3a6e7f32013-10-09 15:50:52 -0700349 public static void scaleRect(Rect r, float scale) {
350 if (scale != 1.0f) {
351 r.left = (int) (r.left * scale + 0.5f);
352 r.top = (int) (r.top * scale + 0.5f);
353 r.right = (int) (r.right * scale + 0.5f);
354 r.bottom = (int) (r.bottom * scale + 0.5f);
355 }
356 }
357
Adam Cohen63f1ec02014-08-12 09:23:13 -0700358 public static int[] getCenterDeltaInScreenSpace(View v0, View v1, int[] delta) {
359 v0.getLocationInWindow(sLoc0);
360 v1.getLocationInWindow(sLoc1);
361
362 sLoc0[0] += (v0.getMeasuredWidth() * v0.getScaleX()) / 2;
363 sLoc0[1] += (v0.getMeasuredHeight() * v0.getScaleY()) / 2;
364 sLoc1[0] += (v1.getMeasuredWidth() * v1.getScaleX()) / 2;
365 sLoc1[1] += (v1.getMeasuredHeight() * v1.getScaleY()) / 2;
366
367 if (delta == null) {
368 delta = new int[2];
369 }
370
371 delta[0] = sLoc1[0] - sLoc0[0];
372 delta[1] = sLoc1[1] - sLoc0[1];
373
374 return delta;
375 }
376
Winson Chung3a6e7f32013-10-09 15:50:52 -0700377 public static void scaleRectAboutCenter(Rect r, float scale) {
378 int cx = r.centerX();
379 int cy = r.centerY();
380 r.offset(-cx, -cy);
381 Utilities.scaleRect(r, scale);
382 r.offset(cx, cy);
383 }
384
Michael Jurkaa805e1a2013-08-22 15:00:33 +0200385 public static void startActivityForResultSafely(
386 Activity activity, Intent intent, int requestCode) {
387 try {
388 activity.startActivityForResult(intent, requestCode);
389 } catch (ActivityNotFoundException e) {
390 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
391 } catch (SecurityException e) {
392 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
393 Log.e(TAG, "Launcher does not have the permission to launch " + intent +
394 ". Make sure to create a MAIN intent-filter for the corresponding activity " +
395 "or use the exported attribute for this activity.", e);
396 }
397 }
Sunny Goyalc5c60ad2014-07-14 12:02:01 -0700398
399 static boolean isSystemApp(Context context, Intent intent) {
400 PackageManager pm = context.getPackageManager();
401 ComponentName cn = intent.getComponent();
402 String packageName = null;
403 if (cn == null) {
404 ResolveInfo info = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
405 if ((info != null) && (info.activityInfo != null)) {
406 packageName = info.activityInfo.packageName;
407 }
408 } else {
409 packageName = cn.getPackageName();
410 }
411 if (packageName != null) {
412 try {
413 PackageInfo info = pm.getPackageInfo(packageName, 0);
414 return (info != null) && (info.applicationInfo != null) &&
415 ((info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
416 } catch (NameNotFoundException e) {
417 return false;
418 }
419 } else {
420 return false;
421 }
422 }
Sunny Goyal95abbb32014-08-04 10:53:22 -0700423
424 /**
425 * This picks a dominant color, looking for high-saturation, high-value, repeated hues.
426 * @param bitmap The bitmap to scan
427 * @param samples The approximate max number of samples to use.
428 */
429 static int findDominantColorByHue(Bitmap bitmap, int samples) {
430 final int height = bitmap.getHeight();
431 final int width = bitmap.getWidth();
432 int sampleStride = (int) Math.sqrt((height * width) / samples);
433 if (sampleStride < 1) {
434 sampleStride = 1;
435 }
436
437 // This is an out-param, for getting the hsv values for an rgb
438 float[] hsv = new float[3];
439
440 // First get the best hue, by creating a histogram over 360 hue buckets,
441 // where each pixel contributes a score weighted by saturation, value, and alpha.
442 float[] hueScoreHistogram = new float[360];
443 float highScore = -1;
444 int bestHue = -1;
445
446 for (int y = 0; y < height; y += sampleStride) {
447 for (int x = 0; x < width; x += sampleStride) {
448 int argb = bitmap.getPixel(x, y);
449 int alpha = 0xFF & (argb >> 24);
450 if (alpha < 0x80) {
451 // Drop mostly-transparent pixels.
452 continue;
453 }
454 // Remove the alpha channel.
455 int rgb = argb | 0xFF000000;
456 Color.colorToHSV(rgb, hsv);
457 // Bucket colors by the 360 integer hues.
458 int hue = (int) hsv[0];
459 if (hue < 0 || hue >= hueScoreHistogram.length) {
460 // Defensively avoid array bounds violations.
461 continue;
462 }
463 float score = hsv[1] * hsv[2];
464 hueScoreHistogram[hue] += score;
465 if (hueScoreHistogram[hue] > highScore) {
466 highScore = hueScoreHistogram[hue];
467 bestHue = hue;
468 }
469 }
470 }
471
472 SparseArray<Float> rgbScores = new SparseArray<Float>();
473 int bestColor = 0xff000000;
474 highScore = -1;
475 // Go back over the RGB colors that match the winning hue,
476 // creating a histogram of weighted s*v scores, for up to 100*100 [s,v] buckets.
477 // The highest-scoring RGB color wins.
478 for (int y = 0; y < height; y += sampleStride) {
479 for (int x = 0; x < width; x += sampleStride) {
480 int rgb = bitmap.getPixel(x, y) | 0xff000000;
481 Color.colorToHSV(rgb, hsv);
482 int hue = (int) hsv[0];
483 if (hue == bestHue) {
484 float s = hsv[1];
485 float v = hsv[2];
486 int bucket = (int) (s * 100) + (int) (v * 10000);
487 // Score by cumulative saturation * value.
488 float score = s * v;
489 Float oldTotal = rgbScores.get(bucket);
490 float newTotal = oldTotal == null ? score : oldTotal + score;
491 rgbScores.put(bucket, newTotal);
492 if (newTotal > highScore) {
493 highScore = newTotal;
494 // All the colors in the winning bucket are very similar. Last in wins.
495 bestColor = rgb;
496 }
497 }
498 }
499 }
500 return bestColor;
501 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700502
503 /*
504 * Finds a system apk which had a broadcast receiver listening to a particular action.
505 * @param action intent action used to find the apk
506 * @return a pair of apk package name and the resources.
507 */
508 static Pair<String, Resources> findSystemApk(String action, PackageManager pm) {
509 final Intent intent = new Intent(action);
510 for (ResolveInfo info : pm.queryBroadcastReceivers(intent, 0)) {
511 if (info.activityInfo != null &&
512 (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
513 final String packageName = info.activityInfo.packageName;
514 try {
515 final Resources res = pm.getResourcesForApplication(packageName);
516 return Pair.create(packageName, res);
517 } catch (NameNotFoundException e) {
518 Log.w(TAG, "Failed to find resources for " + packageName);
519 }
520 }
521 }
522 return null;
523 }
Sunny Goyalfafca522014-11-03 11:30:01 -0800524
525 @TargetApi(Build.VERSION_CODES.KITKAT)
526 public static boolean isViewAttachedToWindow(View v) {
527 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
528 return v.isAttachedToWindow();
529 } else {
530 // A proxy call which returns null, if the view is not attached to the window.
531 return v.getKeyDispatcherState() != null;
532 }
533 }
Sunny Goyal594d76d2014-11-06 10:12:54 -0800534
535 /**
536 * Returns a widget with category {@link AppWidgetProviderInfo#WIDGET_CATEGORY_SEARCHBOX}
537 * provided by the same package which is set to be global search activity.
538 * If widgetCategory is not supported, or no such widget is found, returns the first widget
539 * provided by the package.
540 */
541 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
542 public static AppWidgetProviderInfo getSearchWidgetProvider(Context context) {
543 SearchManager searchManager =
544 (SearchManager) context.getSystemService(Context.SEARCH_SERVICE);
545 ComponentName searchComponent = searchManager.getGlobalSearchActivity();
546 if (searchComponent == null) return null;
547 String providerPkg = searchComponent.getPackageName();
548
549 AppWidgetProviderInfo defaultWidgetForSearchPackage = null;
550
551 AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
552 for (AppWidgetProviderInfo info : appWidgetManager.getInstalledProviders()) {
553 if (info.provider.getPackageName().equals(providerPkg)) {
554 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
555 if ((info.widgetCategory & AppWidgetProviderInfo.WIDGET_CATEGORY_SEARCHBOX) != 0) {
556 return info;
557 } else if (defaultWidgetForSearchPackage == null) {
558 defaultWidgetForSearchPackage = info;
559 }
560 } else {
561 return info;
562 }
563 }
564 }
565 return defaultWidgetForSearchPackage;
566 }
Sunny Goyal08f72612015-01-05 13:41:43 -0800567
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700568 /**
569 * Compresses the bitmap to a byte array for serialization.
570 */
571 public static byte[] flattenBitmap(Bitmap bitmap) {
572 // Try go guesstimate how much space the icon will take when serialized
573 // to avoid unnecessary allocations/copies during the write.
574 int size = bitmap.getWidth() * bitmap.getHeight() * 4;
575 ByteArrayOutputStream out = new ByteArrayOutputStream(size);
576 try {
577 bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
578 out.flush();
579 out.close();
580 return out.toByteArray();
581 } catch (IOException e) {
582 Log.w(TAG, "Could not write bitmap");
583 return null;
584 }
585 }
586
Sunny Goyal08f72612015-01-05 13:41:43 -0800587 public static final Comparator<ItemInfo> RANK_COMPARATOR = new Comparator<ItemInfo>() {
588
589 @Override
590 public int compare(ItemInfo lhs, ItemInfo rhs) {
591 return lhs.rank - rhs.rank;
592 }
593 };
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700594
595 /**
596 * Find the first vacant cell, if there is one.
597 *
598 * @param vacant Holds the x and y coordinate of the vacant cell
599 * @param spanX Horizontal cell span.
600 * @param spanY Vertical cell span.
601 *
602 * @return true if a vacant cell was found
603 */
604 public static boolean findVacantCell(int[] vacant, int spanX, int spanY,
605 int xCount, int yCount, boolean[][] occupied) {
606
607 for (int y = 0; (y + spanY) <= yCount; y++) {
608 for (int x = 0; (x + spanX) <= xCount; x++) {
609 boolean available = !occupied[x][y];
610 out: for (int i = x; i < x + spanX; i++) {
611 for (int j = y; j < y + spanY; j++) {
612 available = available && !occupied[i][j];
613 if (!available) break out;
614 }
615 }
616
617 if (available) {
618 vacant[0] = x;
619 vacant[1] = y;
620 return true;
621 }
622 }
623 }
624
625 return false;
626 }
Winson Chung82b016c2015-05-08 17:00:10 -0700627
628 /**
629 * Trims the string, removing all whitespace at the beginning and end of the string.
630 * Non-breaking whitespaces are also removed.
631 */
632 public static String trim(CharSequence s) {
Winson Chungafa77e92015-05-15 12:04:03 -0700633 if (s == null) {
634 return null;
635 }
636
Winson Chung82b016c2015-05-08 17:00:10 -0700637 // Just strip any sequence of whitespace or java space characters from the beginning and end
638 Matcher m = sTrimPattern.matcher(s);
639 return m.replaceAll("$1");
640 }
Sunny Goyal70660032015-05-14 00:07:08 -0700641
642 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
643 public static boolean isRtl(Resources res) {
644 return (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) &&
645 (res.getConfiguration().getLayoutDirection() == View.LAYOUT_DIRECTION_RTL);
646 }
Hyunyoung Song2bd3d7d2015-05-21 13:04:53 -0700647
648 public static void assertWorkerThread() {
649 if (LauncherAppState.isDogfoodBuild()) {
650 Assert.assertTrue(LauncherModel.sWorkerThread.getThreadId() == Process.myTid());
651 }
652 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800653}