blob: 6734fdc0d50b25630c0bfeeca9a7dcd91df4e9fc [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;
Michael Jurkaa805e1a2013-08-22 15:00:33 +020047import android.util.Log;
Sunny Goyal0fe505b2014-08-06 09:55:36 -070048import android.util.Pair;
Sunny Goyal95abbb32014-08-04 10:53:22 -070049import android.util.SparseArray;
Winson Chungc763c4e2013-07-19 13:49:06 -070050import android.view.View;
Michael Jurkaa805e1a2013-08-22 15:00:33 +020051import android.widget.Toast;
Winson Chungc763c4e2013-07-19 13:49:06 -070052
Sunny Goyal5b0e6692015-03-19 14:31:19 -070053import java.io.ByteArrayOutputStream;
54import java.io.IOException;
Winson Chungc763c4e2013-07-19 13:49:06 -070055import java.util.ArrayList;
Sunny Goyal08f72612015-01-05 13:41:43 -080056import java.util.Comparator;
Winson Chung82b016c2015-05-08 17:00:10 -070057import java.util.regex.Matcher;
58import java.util.regex.Pattern;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080059
60/**
61 * Various utilities shared amongst the Launcher's classes.
62 */
Mathew Inwood72fbec12013-11-19 15:45:07 +000063public final class Utilities {
Joe Onorato1291a8c2009-09-15 15:07:25 -040064 private static final String TAG = "Launcher.Utilities";
65
The Android Open Source Project31dd5032009-03-03 19:32:27 -080066 private static int sIconWidth = -1;
67 private static int sIconHeight = -1;
68
The Android Open Source Project31dd5032009-03-03 19:32:27 -080069 private static final Rect sOldBounds = new Rect();
Romain Guy89911d22009-09-28 18:48:49 -070070 private static final Canvas sCanvas = new Canvas();
The Android Open Source Project31dd5032009-03-03 19:32:27 -080071
Winson Chung82b016c2015-05-08 17:00:10 -070072 private static final Pattern sTrimPattern =
73 Pattern.compile("^[\\s|\\p{javaSpaceChar}]*(.*)[\\s|\\p{javaSpaceChar}]*$");
74
The Android Open Source Project31dd5032009-03-03 19:32:27 -080075 static {
76 sCanvas.setDrawFilter(new PaintFlagsDrawFilter(Paint.DITHER_FLAG,
77 Paint.FILTER_BITMAP_FLAG));
78 }
Joe Onorato6665c0f2009-09-02 15:27:24 -070079 static int sColors[] = { 0xffff0000, 0xff00ff00, 0xff0000ff };
80 static int sColorIndex = 0;
81
Adam Cohen63f1ec02014-08-12 09:23:13 -070082 static int[] sLoc0 = new int[2];
83 static int[] sLoc1 = new int[2];
Michael Jurka7ad868b2013-12-12 15:04:25 +010084
85 // To turn on these properties, type
86 // adb shell setprop log.tag.PROPERTY_NAME [VERBOSE | SUPPRESS]
87 static final String FORCE_ENABLE_ROTATION_PROPERTY = "launcher_force_rotate";
88 public static boolean sForceEnableRotation = isPropertyEnabled(FORCE_ENABLE_ROTATION_PROPERTY);
89
Joe Onorato6665c0f2009-09-02 15:27:24 -070090 /**
Winson Chung0dbd7342013-10-13 22:46:20 -070091 * Returns a FastBitmapDrawable with the icon, accurately sized.
92 */
Sunny Goyalffe83f12014-08-14 17:39:34 -070093 public static FastBitmapDrawable createIconDrawable(Bitmap icon) {
Winson Chung0dbd7342013-10-13 22:46:20 -070094 FastBitmapDrawable d = new FastBitmapDrawable(icon);
Winson Chung54000492013-10-14 16:29:29 -070095 d.setFilterBitmap(true);
Winson Chung0dbd7342013-10-13 22:46:20 -070096 resizeIconDrawable(d);
97 return d;
98 }
99
100 /**
101 * Resizes an icon drawable to the correct icon size.
102 */
103 static void resizeIconDrawable(Drawable icon) {
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700104 icon.setBounds(0, 0, sIconWidth, sIconHeight);
Winson Chung0dbd7342013-10-13 22:46:20 -0700105 }
106
Sunny Goyal4bbf4192014-11-11 12:23:59 -0800107 public static boolean isPropertyEnabled(String propertyName) {
Michael Jurka7ad868b2013-12-12 15:04:25 +0100108 return Log.isLoggable(propertyName, Log.VERBOSE);
109 }
110
111 public static boolean isRotationEnabled(Context c) {
112 boolean enableRotation = sForceEnableRotation ||
113 c.getResources().getBoolean(R.bool.allow_rotation);
114 return enableRotation;
115 }
116
Winson Chung0dbd7342013-10-13 22:46:20 -0700117 /**
Kenny Guyd794a3f2014-09-16 15:17:58 +0100118 * Indicates if the device is running LMP or higher.
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -0700119 */
Kenny Guyd794a3f2014-09-16 15:17:58 +0100120 public static boolean isLmpOrAbove() {
Brian Parfett1bc1ae62014-12-12 12:30:00 -0800121 return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -0700122 }
123
Sunny Goyal4fbc3822015-02-18 16:46:50 -0800124 static Bitmap createIconBitmap(Cursor c, int iconIndex, Context context) {
125 byte[] data = c.getBlob(iconIndex);
126 try {
127 return createIconBitmap(BitmapFactory.decodeByteArray(data, 0, data.length), context);
128 } catch (Exception e) {
129 return null;
130 }
131 }
132
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -0700133 /**
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700134 * Returns a bitmap suitable for the all apps view. If the package or the resource do not
135 * exist, it returns null.
136 */
137 static Bitmap createIconBitmap(String packageName, String resourceName, IconCache cache,
138 Context context) {
139 PackageManager packageManager = context.getPackageManager();
140 // the resource
141 try {
142 Resources resources = packageManager.getResourcesForApplication(packageName);
143 if (resources != null) {
144 final int id = resources.getIdentifier(resourceName, null, null);
145 return createIconBitmap(
146 resources.getDrawableForDensity(id, cache.getFullResIconDpi()), context);
147 }
148 } catch (Exception e) {
149 // Icon not found.
150 }
151 return null;
152 }
153
154 /**
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700155 * Returns a bitmap which is of the appropriate size to be displayed as an icon
Michael Jurka931dc972011-08-05 15:08:15 -0700156 */
157 static Bitmap createIconBitmap(Bitmap icon, Context context) {
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700158 synchronized (sCanvas) { // we share the statics :-(
159 if (sIconWidth == -1) {
160 initStatics(context);
161 }
Michael Jurka931dc972011-08-05 15:08:15 -0700162 }
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700163 if (sIconWidth == icon.getWidth() && sIconHeight == icon.getHeight()) {
164 return icon;
165 }
166 return createIconBitmap(new BitmapDrawable(context.getResources(), icon), context);
Michael Jurka931dc972011-08-05 15:08:15 -0700167 }
168
169 /**
170 * Returns a bitmap suitable for the all apps view.
Joe Onorato6665c0f2009-09-02 15:27:24 -0700171 */
Mathew Inwood72fbec12013-11-19 15:45:07 +0000172 public static Bitmap createIconBitmap(Drawable icon, Context context) {
Joe Onorato6665c0f2009-09-02 15:27:24 -0700173 synchronized (sCanvas) { // we share the statics :-(
174 if (sIconWidth == -1) {
175 initStatics(context);
176 }
177
178 int width = sIconWidth;
179 int height = sIconHeight;
180
Joe Onorato6665c0f2009-09-02 15:27:24 -0700181 if (icon instanceof PaintDrawable) {
182 PaintDrawable painter = (PaintDrawable) icon;
183 painter.setIntrinsicWidth(width);
184 painter.setIntrinsicHeight(height);
185 } else if (icon instanceof BitmapDrawable) {
186 // Ensure the bitmap has a density.
187 BitmapDrawable bitmapDrawable = (BitmapDrawable) icon;
188 Bitmap bitmap = bitmapDrawable.getBitmap();
189 if (bitmap.getDensity() == Bitmap.DENSITY_NONE) {
190 bitmapDrawable.setTargetDensity(context.getResources().getDisplayMetrics());
191 }
192 }
193 int sourceWidth = icon.getIntrinsicWidth();
194 int sourceHeight = icon.getIntrinsicHeight();
Michael Jurka931dc972011-08-05 15:08:15 -0700195 if (sourceWidth > 0 && sourceHeight > 0) {
Winson Chung5f8afe62013-08-12 16:19:28 -0700196 // Scale the icon proportionally to the icon dimensions
197 final float ratio = (float) sourceWidth / sourceHeight;
198 if (sourceWidth > sourceHeight) {
199 height = (int) (width / ratio);
200 } else if (sourceHeight > sourceWidth) {
201 width = (int) (height * ratio);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700202 }
203 }
204
205 // no intrinsic size --> use default size
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700206 int textureWidth = sIconWidth;
207 int textureHeight = sIconHeight;
Joe Onorato6665c0f2009-09-02 15:27:24 -0700208
209 final Bitmap bitmap = Bitmap.createBitmap(textureWidth, textureHeight,
210 Bitmap.Config.ARGB_8888);
211 final Canvas canvas = sCanvas;
212 canvas.setBitmap(bitmap);
213
214 final int left = (textureWidth-width) / 2;
215 final int top = (textureHeight-height) / 2;
216
Michael Jurka3a9fced2012-04-13 14:44:29 -0700217 @SuppressWarnings("all") // suppress dead code warning
218 final boolean debug = false;
219 if (debug) {
Joe Onorato6665c0f2009-09-02 15:27:24 -0700220 // draw a big box for the icon for debugging
221 canvas.drawColor(sColors[sColorIndex]);
222 if (++sColorIndex >= sColors.length) sColorIndex = 0;
223 Paint debugPaint = new Paint();
224 debugPaint.setColor(0xffcccc00);
225 canvas.drawRect(left, top, left+width, top+height, debugPaint);
226 }
227
228 sOldBounds.set(icon.getBounds());
229 icon.setBounds(left, top, left+width, top+height);
230 icon.draw(canvas);
231 icon.setBounds(sOldBounds);
Adam Cohenaaf473c2011-08-03 12:02:47 -0700232 canvas.setBitmap(null);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700233
234 return bitmap;
235 }
236 }
237
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800238 /**
Winson Chungc763c4e2013-07-19 13:49:06 -0700239 * Given a coordinate relative to the descendant, find the coordinate in a parent view's
240 * coordinates.
241 *
242 * @param descendant The descendant to which the passed coordinate is relative.
243 * @param root The root view to make the coordinates relative to.
244 * @param coord The coordinate that we want mapped.
245 * @param includeRootScroll Whether or not to account for the scroll of the descendant:
246 * sometimes this is relevant as in a child's coordinates within the descendant.
247 * @return The factor by which this descendant is scaled relative to this DragLayer. Caution
248 * this scale factor is assumed to be equal in X and Y, and so if at any point this
249 * assumption fails, we will need to return a pair of scale factors.
250 */
251 public static float getDescendantCoordRelativeToParent(View descendant, View root,
252 int[] coord, boolean includeRootScroll) {
253 ArrayList<View> ancestorChain = new ArrayList<View>();
254
255 float[] pt = {coord[0], coord[1]};
256
257 View v = descendant;
258 while(v != root && v != null) {
259 ancestorChain.add(v);
260 v = (View) v.getParent();
261 }
262 ancestorChain.add(root);
263
264 float scale = 1.0f;
265 int count = ancestorChain.size();
266 for (int i = 0; i < count; i++) {
267 View v0 = ancestorChain.get(i);
Winson Chungc763c4e2013-07-19 13:49:06 -0700268 // For TextViews, scroll has a meaning which relates to the text position
269 // which is very strange... ignore the scroll.
270 if (v0 != descendant || includeRootScroll) {
271 pt[0] -= v0.getScrollX();
272 pt[1] -= v0.getScrollY();
273 }
274
275 v0.getMatrix().mapPoints(pt);
276 pt[0] += v0.getLeft();
277 pt[1] += v0.getTop();
278 scale *= v0.getScaleX();
279 }
280
281 coord[0] = (int) Math.round(pt[0]);
282 coord[1] = (int) Math.round(pt[1]);
283 return scale;
284 }
285
286 /**
287 * Inverse of {@link #getDescendantCoordRelativeToSelf(View, int[])}.
288 */
289 public static float mapCoordInSelfToDescendent(View descendant, View root,
290 int[] coord) {
291 ArrayList<View> ancestorChain = new ArrayList<View>();
292
293 float[] pt = {coord[0], coord[1]};
294
295 View v = descendant;
296 while(v != root) {
297 ancestorChain.add(v);
298 v = (View) v.getParent();
299 }
300 ancestorChain.add(root);
301
302 float scale = 1.0f;
303 Matrix inverse = new Matrix();
304 int count = ancestorChain.size();
305 for (int i = count - 1; i >= 0; i--) {
306 View ancestor = ancestorChain.get(i);
307 View next = i > 0 ? ancestorChain.get(i-1) : null;
308
309 pt[0] += ancestor.getScrollX();
310 pt[1] += ancestor.getScrollY();
311
312 if (next != null) {
313 pt[0] -= next.getLeft();
314 pt[1] -= next.getTop();
315 next.getMatrix().invert(inverse);
316 inverse.mapPoints(pt);
317 scale *= next.getScaleX();
318 }
319 }
320
321 coord[0] = (int) Math.round(pt[0]);
322 coord[1] = (int) Math.round(pt[1]);
323 return scale;
324 }
325
Jason Monk02dd7ae2014-04-15 15:23:31 -0400326 /**
327 * Utility method to determine whether the given point, in local coordinates,
328 * is inside the view, where the area of the view is expanded by the slop factor.
329 * This method is called while processing touch-move events to determine if the event
330 * is still within the view.
331 */
332 public static boolean pointInView(View v, float localX, float localY, float slop) {
333 return localX >= -slop && localY >= -slop && localX < (v.getWidth() + slop) &&
334 localY < (v.getHeight() + slop);
335 }
336
Joe Onorato6665c0f2009-09-02 15:27:24 -0700337 private static void initStatics(Context context) {
338 final Resources resources = context.getResources();
Michael Jurkac9a96192010-11-01 11:52:08 -0700339 sIconWidth = sIconHeight = (int) resources.getDimension(R.dimen.app_icon_size);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700340 }
341
Winson Chung5f8afe62013-08-12 16:19:28 -0700342 public static void setIconSize(int widthPx) {
343 sIconWidth = sIconHeight = widthPx;
Winson Chung97d85d22011-04-13 11:27:36 -0700344 }
Michael Jurkaa805e1a2013-08-22 15:00:33 +0200345
Winson Chung3a6e7f32013-10-09 15:50:52 -0700346 public static void scaleRect(Rect r, float scale) {
347 if (scale != 1.0f) {
348 r.left = (int) (r.left * scale + 0.5f);
349 r.top = (int) (r.top * scale + 0.5f);
350 r.right = (int) (r.right * scale + 0.5f);
351 r.bottom = (int) (r.bottom * scale + 0.5f);
352 }
353 }
354
Adam Cohen63f1ec02014-08-12 09:23:13 -0700355 public static int[] getCenterDeltaInScreenSpace(View v0, View v1, int[] delta) {
356 v0.getLocationInWindow(sLoc0);
357 v1.getLocationInWindow(sLoc1);
358
359 sLoc0[0] += (v0.getMeasuredWidth() * v0.getScaleX()) / 2;
360 sLoc0[1] += (v0.getMeasuredHeight() * v0.getScaleY()) / 2;
361 sLoc1[0] += (v1.getMeasuredWidth() * v1.getScaleX()) / 2;
362 sLoc1[1] += (v1.getMeasuredHeight() * v1.getScaleY()) / 2;
363
364 if (delta == null) {
365 delta = new int[2];
366 }
367
368 delta[0] = sLoc1[0] - sLoc0[0];
369 delta[1] = sLoc1[1] - sLoc0[1];
370
371 return delta;
372 }
373
Winson Chung3a6e7f32013-10-09 15:50:52 -0700374 public static void scaleRectAboutCenter(Rect r, float scale) {
375 int cx = r.centerX();
376 int cy = r.centerY();
377 r.offset(-cx, -cy);
378 Utilities.scaleRect(r, scale);
379 r.offset(cx, cy);
380 }
381
Michael Jurkaa805e1a2013-08-22 15:00:33 +0200382 public static void startActivityForResultSafely(
383 Activity activity, Intent intent, int requestCode) {
384 try {
385 activity.startActivityForResult(intent, requestCode);
386 } catch (ActivityNotFoundException e) {
387 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
388 } catch (SecurityException e) {
389 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
390 Log.e(TAG, "Launcher does not have the permission to launch " + intent +
391 ". Make sure to create a MAIN intent-filter for the corresponding activity " +
392 "or use the exported attribute for this activity.", e);
393 }
394 }
Sunny Goyalc5c60ad2014-07-14 12:02:01 -0700395
396 static boolean isSystemApp(Context context, Intent intent) {
397 PackageManager pm = context.getPackageManager();
398 ComponentName cn = intent.getComponent();
399 String packageName = null;
400 if (cn == null) {
401 ResolveInfo info = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
402 if ((info != null) && (info.activityInfo != null)) {
403 packageName = info.activityInfo.packageName;
404 }
405 } else {
406 packageName = cn.getPackageName();
407 }
408 if (packageName != null) {
409 try {
410 PackageInfo info = pm.getPackageInfo(packageName, 0);
411 return (info != null) && (info.applicationInfo != null) &&
412 ((info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
413 } catch (NameNotFoundException e) {
414 return false;
415 }
416 } else {
417 return false;
418 }
419 }
Sunny Goyal95abbb32014-08-04 10:53:22 -0700420
421 /**
422 * This picks a dominant color, looking for high-saturation, high-value, repeated hues.
423 * @param bitmap The bitmap to scan
424 * @param samples The approximate max number of samples to use.
425 */
426 static int findDominantColorByHue(Bitmap bitmap, int samples) {
427 final int height = bitmap.getHeight();
428 final int width = bitmap.getWidth();
429 int sampleStride = (int) Math.sqrt((height * width) / samples);
430 if (sampleStride < 1) {
431 sampleStride = 1;
432 }
433
434 // This is an out-param, for getting the hsv values for an rgb
435 float[] hsv = new float[3];
436
437 // First get the best hue, by creating a histogram over 360 hue buckets,
438 // where each pixel contributes a score weighted by saturation, value, and alpha.
439 float[] hueScoreHistogram = new float[360];
440 float highScore = -1;
441 int bestHue = -1;
442
443 for (int y = 0; y < height; y += sampleStride) {
444 for (int x = 0; x < width; x += sampleStride) {
445 int argb = bitmap.getPixel(x, y);
446 int alpha = 0xFF & (argb >> 24);
447 if (alpha < 0x80) {
448 // Drop mostly-transparent pixels.
449 continue;
450 }
451 // Remove the alpha channel.
452 int rgb = argb | 0xFF000000;
453 Color.colorToHSV(rgb, hsv);
454 // Bucket colors by the 360 integer hues.
455 int hue = (int) hsv[0];
456 if (hue < 0 || hue >= hueScoreHistogram.length) {
457 // Defensively avoid array bounds violations.
458 continue;
459 }
460 float score = hsv[1] * hsv[2];
461 hueScoreHistogram[hue] += score;
462 if (hueScoreHistogram[hue] > highScore) {
463 highScore = hueScoreHistogram[hue];
464 bestHue = hue;
465 }
466 }
467 }
468
469 SparseArray<Float> rgbScores = new SparseArray<Float>();
470 int bestColor = 0xff000000;
471 highScore = -1;
472 // Go back over the RGB colors that match the winning hue,
473 // creating a histogram of weighted s*v scores, for up to 100*100 [s,v] buckets.
474 // The highest-scoring RGB color wins.
475 for (int y = 0; y < height; y += sampleStride) {
476 for (int x = 0; x < width; x += sampleStride) {
477 int rgb = bitmap.getPixel(x, y) | 0xff000000;
478 Color.colorToHSV(rgb, hsv);
479 int hue = (int) hsv[0];
480 if (hue == bestHue) {
481 float s = hsv[1];
482 float v = hsv[2];
483 int bucket = (int) (s * 100) + (int) (v * 10000);
484 // Score by cumulative saturation * value.
485 float score = s * v;
486 Float oldTotal = rgbScores.get(bucket);
487 float newTotal = oldTotal == null ? score : oldTotal + score;
488 rgbScores.put(bucket, newTotal);
489 if (newTotal > highScore) {
490 highScore = newTotal;
491 // All the colors in the winning bucket are very similar. Last in wins.
492 bestColor = rgb;
493 }
494 }
495 }
496 }
497 return bestColor;
498 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700499
500 /*
501 * Finds a system apk which had a broadcast receiver listening to a particular action.
502 * @param action intent action used to find the apk
503 * @return a pair of apk package name and the resources.
504 */
505 static Pair<String, Resources> findSystemApk(String action, PackageManager pm) {
506 final Intent intent = new Intent(action);
507 for (ResolveInfo info : pm.queryBroadcastReceivers(intent, 0)) {
508 if (info.activityInfo != null &&
509 (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
510 final String packageName = info.activityInfo.packageName;
511 try {
512 final Resources res = pm.getResourcesForApplication(packageName);
513 return Pair.create(packageName, res);
514 } catch (NameNotFoundException e) {
515 Log.w(TAG, "Failed to find resources for " + packageName);
516 }
517 }
518 }
519 return null;
520 }
Sunny Goyalfafca522014-11-03 11:30:01 -0800521
522 @TargetApi(Build.VERSION_CODES.KITKAT)
523 public static boolean isViewAttachedToWindow(View v) {
524 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
525 return v.isAttachedToWindow();
526 } else {
527 // A proxy call which returns null, if the view is not attached to the window.
528 return v.getKeyDispatcherState() != null;
529 }
530 }
Sunny Goyal594d76d2014-11-06 10:12:54 -0800531
532 /**
533 * Returns a widget with category {@link AppWidgetProviderInfo#WIDGET_CATEGORY_SEARCHBOX}
534 * provided by the same package which is set to be global search activity.
535 * If widgetCategory is not supported, or no such widget is found, returns the first widget
536 * provided by the package.
537 */
538 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
539 public static AppWidgetProviderInfo getSearchWidgetProvider(Context context) {
540 SearchManager searchManager =
541 (SearchManager) context.getSystemService(Context.SEARCH_SERVICE);
542 ComponentName searchComponent = searchManager.getGlobalSearchActivity();
543 if (searchComponent == null) return null;
544 String providerPkg = searchComponent.getPackageName();
545
546 AppWidgetProviderInfo defaultWidgetForSearchPackage = null;
547
548 AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
549 for (AppWidgetProviderInfo info : appWidgetManager.getInstalledProviders()) {
550 if (info.provider.getPackageName().equals(providerPkg)) {
551 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
552 if ((info.widgetCategory & AppWidgetProviderInfo.WIDGET_CATEGORY_SEARCHBOX) != 0) {
553 return info;
554 } else if (defaultWidgetForSearchPackage == null) {
555 defaultWidgetForSearchPackage = info;
556 }
557 } else {
558 return info;
559 }
560 }
561 }
562 return defaultWidgetForSearchPackage;
563 }
Sunny Goyal08f72612015-01-05 13:41:43 -0800564
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700565 /**
566 * Compresses the bitmap to a byte array for serialization.
567 */
568 public static byte[] flattenBitmap(Bitmap bitmap) {
569 // Try go guesstimate how much space the icon will take when serialized
570 // to avoid unnecessary allocations/copies during the write.
571 int size = bitmap.getWidth() * bitmap.getHeight() * 4;
572 ByteArrayOutputStream out = new ByteArrayOutputStream(size);
573 try {
574 bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
575 out.flush();
576 out.close();
577 return out.toByteArray();
578 } catch (IOException e) {
579 Log.w(TAG, "Could not write bitmap");
580 return null;
581 }
582 }
583
Sunny Goyal08f72612015-01-05 13:41:43 -0800584 public static final Comparator<ItemInfo> RANK_COMPARATOR = new Comparator<ItemInfo>() {
585
586 @Override
587 public int compare(ItemInfo lhs, ItemInfo rhs) {
588 return lhs.rank - rhs.rank;
589 }
590 };
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700591
592 /**
593 * Find the first vacant cell, if there is one.
594 *
595 * @param vacant Holds the x and y coordinate of the vacant cell
596 * @param spanX Horizontal cell span.
597 * @param spanY Vertical cell span.
598 *
599 * @return true if a vacant cell was found
600 */
601 public static boolean findVacantCell(int[] vacant, int spanX, int spanY,
602 int xCount, int yCount, boolean[][] occupied) {
603
604 for (int y = 0; (y + spanY) <= yCount; y++) {
605 for (int x = 0; (x + spanX) <= xCount; x++) {
606 boolean available = !occupied[x][y];
607 out: for (int i = x; i < x + spanX; i++) {
608 for (int j = y; j < y + spanY; j++) {
609 available = available && !occupied[i][j];
610 if (!available) break out;
611 }
612 }
613
614 if (available) {
615 vacant[0] = x;
616 vacant[1] = y;
617 return true;
618 }
619 }
620 }
621
622 return false;
623 }
Winson Chung82b016c2015-05-08 17:00:10 -0700624
625 /**
626 * Trims the string, removing all whitespace at the beginning and end of the string.
627 * Non-breaking whitespaces are also removed.
628 */
629 public static String trim(CharSequence s) {
Winson Chungafa77e92015-05-15 12:04:03 -0700630 if (s == null) {
631 return null;
632 }
633
Winson Chung82b016c2015-05-08 17:00:10 -0700634 // Just strip any sequence of whitespace or java space characters from the beginning and end
635 Matcher m = sTrimPattern.matcher(s);
636 return m.replaceAll("$1");
637 }
Sunny Goyal70660032015-05-14 00:07:08 -0700638
639 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
640 public static boolean isRtl(Resources res) {
641 return (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) &&
642 (res.getConfiguration().getLayoutDirection() == View.LAYOUT_DIRECTION_RTL);
643 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800644}