blob: 22677c8ea404fba82c5d8a13ead854c9e8f78036 [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;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080057
58/**
59 * Various utilities shared amongst the Launcher's classes.
60 */
Mathew Inwood72fbec12013-11-19 15:45:07 +000061public final class Utilities {
Joe Onorato1291a8c2009-09-15 15:07:25 -040062 private static final String TAG = "Launcher.Utilities";
63
The Android Open Source Project31dd5032009-03-03 19:32:27 -080064 private static int sIconWidth = -1;
65 private static int sIconHeight = -1;
66
The Android Open Source Project31dd5032009-03-03 19:32:27 -080067 private static final Rect sOldBounds = new Rect();
Romain Guy89911d22009-09-28 18:48:49 -070068 private static final Canvas sCanvas = new Canvas();
The Android Open Source Project31dd5032009-03-03 19:32:27 -080069
70 static {
71 sCanvas.setDrawFilter(new PaintFlagsDrawFilter(Paint.DITHER_FLAG,
72 Paint.FILTER_BITMAP_FLAG));
73 }
Joe Onorato6665c0f2009-09-02 15:27:24 -070074 static int sColors[] = { 0xffff0000, 0xff00ff00, 0xff0000ff };
75 static int sColorIndex = 0;
76
Adam Cohen63f1ec02014-08-12 09:23:13 -070077 static int[] sLoc0 = new int[2];
78 static int[] sLoc1 = new int[2];
Michael Jurka7ad868b2013-12-12 15:04:25 +010079
80 // To turn on these properties, type
81 // adb shell setprop log.tag.PROPERTY_NAME [VERBOSE | SUPPRESS]
82 static final String FORCE_ENABLE_ROTATION_PROPERTY = "launcher_force_rotate";
83 public static boolean sForceEnableRotation = isPropertyEnabled(FORCE_ENABLE_ROTATION_PROPERTY);
84
Joe Onorato6665c0f2009-09-02 15:27:24 -070085 /**
Winson Chung0dbd7342013-10-13 22:46:20 -070086 * Returns a FastBitmapDrawable with the icon, accurately sized.
87 */
Sunny Goyalffe83f12014-08-14 17:39:34 -070088 public static FastBitmapDrawable createIconDrawable(Bitmap icon) {
Winson Chung0dbd7342013-10-13 22:46:20 -070089 FastBitmapDrawable d = new FastBitmapDrawable(icon);
Winson Chung54000492013-10-14 16:29:29 -070090 d.setFilterBitmap(true);
Winson Chung0dbd7342013-10-13 22:46:20 -070091 resizeIconDrawable(d);
92 return d;
93 }
94
95 /**
96 * Resizes an icon drawable to the correct icon size.
97 */
98 static void resizeIconDrawable(Drawable icon) {
Sunny Goyal2fce90c2014-10-07 12:01:58 -070099 icon.setBounds(0, 0, sIconWidth, sIconHeight);
Winson Chung0dbd7342013-10-13 22:46:20 -0700100 }
101
Sunny Goyal4bbf4192014-11-11 12:23:59 -0800102 public static boolean isPropertyEnabled(String propertyName) {
Michael Jurka7ad868b2013-12-12 15:04:25 +0100103 return Log.isLoggable(propertyName, Log.VERBOSE);
104 }
105
106 public static boolean isRotationEnabled(Context c) {
107 boolean enableRotation = sForceEnableRotation ||
108 c.getResources().getBoolean(R.bool.allow_rotation);
109 return enableRotation;
110 }
111
Winson Chung0dbd7342013-10-13 22:46:20 -0700112 /**
Kenny Guyd794a3f2014-09-16 15:17:58 +0100113 * Indicates if the device is running LMP or higher.
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -0700114 */
Kenny Guyd794a3f2014-09-16 15:17:58 +0100115 public static boolean isLmpOrAbove() {
Brian Parfett1bc1ae62014-12-12 12:30:00 -0800116 return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -0700117 }
118
Sunny Goyal4fbc3822015-02-18 16:46:50 -0800119 static Bitmap createIconBitmap(Cursor c, int iconIndex, Context context) {
120 byte[] data = c.getBlob(iconIndex);
121 try {
122 return createIconBitmap(BitmapFactory.decodeByteArray(data, 0, data.length), context);
123 } catch (Exception e) {
124 return null;
125 }
126 }
127
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -0700128 /**
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700129 * Returns a bitmap suitable for the all apps view. If the package or the resource do not
130 * exist, it returns null.
131 */
132 static Bitmap createIconBitmap(String packageName, String resourceName, IconCache cache,
133 Context context) {
134 PackageManager packageManager = context.getPackageManager();
135 // the resource
136 try {
137 Resources resources = packageManager.getResourcesForApplication(packageName);
138 if (resources != null) {
139 final int id = resources.getIdentifier(resourceName, null, null);
140 return createIconBitmap(
141 resources.getDrawableForDensity(id, cache.getFullResIconDpi()), context);
142 }
143 } catch (Exception e) {
144 // Icon not found.
145 }
146 return null;
147 }
148
149 /**
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700150 * Returns a bitmap which is of the appropriate size to be displayed as an icon
Michael Jurka931dc972011-08-05 15:08:15 -0700151 */
152 static Bitmap createIconBitmap(Bitmap icon, Context context) {
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700153 synchronized (sCanvas) { // we share the statics :-(
154 if (sIconWidth == -1) {
155 initStatics(context);
156 }
Michael Jurka931dc972011-08-05 15:08:15 -0700157 }
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700158 if (sIconWidth == icon.getWidth() && sIconHeight == icon.getHeight()) {
159 return icon;
160 }
161 return createIconBitmap(new BitmapDrawable(context.getResources(), icon), context);
Michael Jurka931dc972011-08-05 15:08:15 -0700162 }
163
164 /**
165 * Returns a bitmap suitable for the all apps view.
Joe Onorato6665c0f2009-09-02 15:27:24 -0700166 */
Mathew Inwood72fbec12013-11-19 15:45:07 +0000167 public static Bitmap createIconBitmap(Drawable icon, Context context) {
Joe Onorato6665c0f2009-09-02 15:27:24 -0700168 synchronized (sCanvas) { // we share the statics :-(
169 if (sIconWidth == -1) {
170 initStatics(context);
171 }
172
173 int width = sIconWidth;
174 int height = sIconHeight;
175
Joe Onorato6665c0f2009-09-02 15:27:24 -0700176 if (icon instanceof PaintDrawable) {
177 PaintDrawable painter = (PaintDrawable) icon;
178 painter.setIntrinsicWidth(width);
179 painter.setIntrinsicHeight(height);
180 } else if (icon instanceof BitmapDrawable) {
181 // Ensure the bitmap has a density.
182 BitmapDrawable bitmapDrawable = (BitmapDrawable) icon;
183 Bitmap bitmap = bitmapDrawable.getBitmap();
184 if (bitmap.getDensity() == Bitmap.DENSITY_NONE) {
185 bitmapDrawable.setTargetDensity(context.getResources().getDisplayMetrics());
186 }
187 }
188 int sourceWidth = icon.getIntrinsicWidth();
189 int sourceHeight = icon.getIntrinsicHeight();
Michael Jurka931dc972011-08-05 15:08:15 -0700190 if (sourceWidth > 0 && sourceHeight > 0) {
Winson Chung5f8afe62013-08-12 16:19:28 -0700191 // Scale the icon proportionally to the icon dimensions
192 final float ratio = (float) sourceWidth / sourceHeight;
193 if (sourceWidth > sourceHeight) {
194 height = (int) (width / ratio);
195 } else if (sourceHeight > sourceWidth) {
196 width = (int) (height * ratio);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700197 }
198 }
199
200 // no intrinsic size --> use default size
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700201 int textureWidth = sIconWidth;
202 int textureHeight = sIconHeight;
Joe Onorato6665c0f2009-09-02 15:27:24 -0700203
204 final Bitmap bitmap = Bitmap.createBitmap(textureWidth, textureHeight,
205 Bitmap.Config.ARGB_8888);
206 final Canvas canvas = sCanvas;
207 canvas.setBitmap(bitmap);
208
209 final int left = (textureWidth-width) / 2;
210 final int top = (textureHeight-height) / 2;
211
Michael Jurka3a9fced2012-04-13 14:44:29 -0700212 @SuppressWarnings("all") // suppress dead code warning
213 final boolean debug = false;
214 if (debug) {
Joe Onorato6665c0f2009-09-02 15:27:24 -0700215 // draw a big box for the icon for debugging
216 canvas.drawColor(sColors[sColorIndex]);
217 if (++sColorIndex >= sColors.length) sColorIndex = 0;
218 Paint debugPaint = new Paint();
219 debugPaint.setColor(0xffcccc00);
220 canvas.drawRect(left, top, left+width, top+height, debugPaint);
221 }
222
223 sOldBounds.set(icon.getBounds());
224 icon.setBounds(left, top, left+width, top+height);
225 icon.draw(canvas);
226 icon.setBounds(sOldBounds);
Adam Cohenaaf473c2011-08-03 12:02:47 -0700227 canvas.setBitmap(null);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700228
229 return bitmap;
230 }
231 }
232
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800233 /**
Winson Chungc763c4e2013-07-19 13:49:06 -0700234 * Given a coordinate relative to the descendant, find the coordinate in a parent view's
235 * coordinates.
236 *
237 * @param descendant The descendant to which the passed coordinate is relative.
238 * @param root The root view to make the coordinates relative to.
239 * @param coord The coordinate that we want mapped.
240 * @param includeRootScroll Whether or not to account for the scroll of the descendant:
241 * sometimes this is relevant as in a child's coordinates within the descendant.
242 * @return The factor by which this descendant is scaled relative to this DragLayer. Caution
243 * this scale factor is assumed to be equal in X and Y, and so if at any point this
244 * assumption fails, we will need to return a pair of scale factors.
245 */
246 public static float getDescendantCoordRelativeToParent(View descendant, View root,
247 int[] coord, boolean includeRootScroll) {
248 ArrayList<View> ancestorChain = new ArrayList<View>();
249
250 float[] pt = {coord[0], coord[1]};
251
252 View v = descendant;
253 while(v != root && v != null) {
254 ancestorChain.add(v);
255 v = (View) v.getParent();
256 }
257 ancestorChain.add(root);
258
259 float scale = 1.0f;
260 int count = ancestorChain.size();
261 for (int i = 0; i < count; i++) {
262 View v0 = ancestorChain.get(i);
Winson Chungc763c4e2013-07-19 13:49:06 -0700263 // For TextViews, scroll has a meaning which relates to the text position
264 // which is very strange... ignore the scroll.
265 if (v0 != descendant || includeRootScroll) {
266 pt[0] -= v0.getScrollX();
267 pt[1] -= v0.getScrollY();
268 }
269
270 v0.getMatrix().mapPoints(pt);
271 pt[0] += v0.getLeft();
272 pt[1] += v0.getTop();
273 scale *= v0.getScaleX();
274 }
275
276 coord[0] = (int) Math.round(pt[0]);
277 coord[1] = (int) Math.round(pt[1]);
278 return scale;
279 }
280
281 /**
282 * Inverse of {@link #getDescendantCoordRelativeToSelf(View, int[])}.
283 */
284 public static float mapCoordInSelfToDescendent(View descendant, View root,
285 int[] coord) {
286 ArrayList<View> ancestorChain = new ArrayList<View>();
287
288 float[] pt = {coord[0], coord[1]};
289
290 View v = descendant;
291 while(v != root) {
292 ancestorChain.add(v);
293 v = (View) v.getParent();
294 }
295 ancestorChain.add(root);
296
297 float scale = 1.0f;
298 Matrix inverse = new Matrix();
299 int count = ancestorChain.size();
300 for (int i = count - 1; i >= 0; i--) {
301 View ancestor = ancestorChain.get(i);
302 View next = i > 0 ? ancestorChain.get(i-1) : null;
303
304 pt[0] += ancestor.getScrollX();
305 pt[1] += ancestor.getScrollY();
306
307 if (next != null) {
308 pt[0] -= next.getLeft();
309 pt[1] -= next.getTop();
310 next.getMatrix().invert(inverse);
311 inverse.mapPoints(pt);
312 scale *= next.getScaleX();
313 }
314 }
315
316 coord[0] = (int) Math.round(pt[0]);
317 coord[1] = (int) Math.round(pt[1]);
318 return scale;
319 }
320
Jason Monk02dd7ae2014-04-15 15:23:31 -0400321 /**
322 * Utility method to determine whether the given point, in local coordinates,
323 * is inside the view, where the area of the view is expanded by the slop factor.
324 * This method is called while processing touch-move events to determine if the event
325 * is still within the view.
326 */
327 public static boolean pointInView(View v, float localX, float localY, float slop) {
328 return localX >= -slop && localY >= -slop && localX < (v.getWidth() + slop) &&
329 localY < (v.getHeight() + slop);
330 }
331
Joe Onorato6665c0f2009-09-02 15:27:24 -0700332 private static void initStatics(Context context) {
333 final Resources resources = context.getResources();
Michael Jurkac9a96192010-11-01 11:52:08 -0700334 sIconWidth = sIconHeight = (int) resources.getDimension(R.dimen.app_icon_size);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700335 }
336
Winson Chung5f8afe62013-08-12 16:19:28 -0700337 public static void setIconSize(int widthPx) {
338 sIconWidth = sIconHeight = widthPx;
Winson Chung97d85d22011-04-13 11:27:36 -0700339 }
Michael Jurkaa805e1a2013-08-22 15:00:33 +0200340
Winson Chung3a6e7f32013-10-09 15:50:52 -0700341 public static void scaleRect(Rect r, float scale) {
342 if (scale != 1.0f) {
343 r.left = (int) (r.left * scale + 0.5f);
344 r.top = (int) (r.top * scale + 0.5f);
345 r.right = (int) (r.right * scale + 0.5f);
346 r.bottom = (int) (r.bottom * scale + 0.5f);
347 }
348 }
349
Adam Cohen63f1ec02014-08-12 09:23:13 -0700350 public static int[] getCenterDeltaInScreenSpace(View v0, View v1, int[] delta) {
351 v0.getLocationInWindow(sLoc0);
352 v1.getLocationInWindow(sLoc1);
353
354 sLoc0[0] += (v0.getMeasuredWidth() * v0.getScaleX()) / 2;
355 sLoc0[1] += (v0.getMeasuredHeight() * v0.getScaleY()) / 2;
356 sLoc1[0] += (v1.getMeasuredWidth() * v1.getScaleX()) / 2;
357 sLoc1[1] += (v1.getMeasuredHeight() * v1.getScaleY()) / 2;
358
359 if (delta == null) {
360 delta = new int[2];
361 }
362
363 delta[0] = sLoc1[0] - sLoc0[0];
364 delta[1] = sLoc1[1] - sLoc0[1];
365
366 return delta;
367 }
368
Winson Chung3a6e7f32013-10-09 15:50:52 -0700369 public static void scaleRectAboutCenter(Rect r, float scale) {
370 int cx = r.centerX();
371 int cy = r.centerY();
372 r.offset(-cx, -cy);
373 Utilities.scaleRect(r, scale);
374 r.offset(cx, cy);
375 }
376
Michael Jurkaa805e1a2013-08-22 15:00:33 +0200377 public static void startActivityForResultSafely(
378 Activity activity, Intent intent, int requestCode) {
379 try {
380 activity.startActivityForResult(intent, requestCode);
381 } catch (ActivityNotFoundException e) {
382 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
383 } catch (SecurityException e) {
384 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
385 Log.e(TAG, "Launcher does not have the permission to launch " + intent +
386 ". Make sure to create a MAIN intent-filter for the corresponding activity " +
387 "or use the exported attribute for this activity.", e);
388 }
389 }
Sunny Goyalc5c60ad2014-07-14 12:02:01 -0700390
391 static boolean isSystemApp(Context context, Intent intent) {
392 PackageManager pm = context.getPackageManager();
393 ComponentName cn = intent.getComponent();
394 String packageName = null;
395 if (cn == null) {
396 ResolveInfo info = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
397 if ((info != null) && (info.activityInfo != null)) {
398 packageName = info.activityInfo.packageName;
399 }
400 } else {
401 packageName = cn.getPackageName();
402 }
403 if (packageName != null) {
404 try {
405 PackageInfo info = pm.getPackageInfo(packageName, 0);
406 return (info != null) && (info.applicationInfo != null) &&
407 ((info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
408 } catch (NameNotFoundException e) {
409 return false;
410 }
411 } else {
412 return false;
413 }
414 }
Sunny Goyal95abbb32014-08-04 10:53:22 -0700415
416 /**
417 * This picks a dominant color, looking for high-saturation, high-value, repeated hues.
418 * @param bitmap The bitmap to scan
419 * @param samples The approximate max number of samples to use.
420 */
421 static int findDominantColorByHue(Bitmap bitmap, int samples) {
422 final int height = bitmap.getHeight();
423 final int width = bitmap.getWidth();
424 int sampleStride = (int) Math.sqrt((height * width) / samples);
425 if (sampleStride < 1) {
426 sampleStride = 1;
427 }
428
429 // This is an out-param, for getting the hsv values for an rgb
430 float[] hsv = new float[3];
431
432 // First get the best hue, by creating a histogram over 360 hue buckets,
433 // where each pixel contributes a score weighted by saturation, value, and alpha.
434 float[] hueScoreHistogram = new float[360];
435 float highScore = -1;
436 int bestHue = -1;
437
438 for (int y = 0; y < height; y += sampleStride) {
439 for (int x = 0; x < width; x += sampleStride) {
440 int argb = bitmap.getPixel(x, y);
441 int alpha = 0xFF & (argb >> 24);
442 if (alpha < 0x80) {
443 // Drop mostly-transparent pixels.
444 continue;
445 }
446 // Remove the alpha channel.
447 int rgb = argb | 0xFF000000;
448 Color.colorToHSV(rgb, hsv);
449 // Bucket colors by the 360 integer hues.
450 int hue = (int) hsv[0];
451 if (hue < 0 || hue >= hueScoreHistogram.length) {
452 // Defensively avoid array bounds violations.
453 continue;
454 }
455 float score = hsv[1] * hsv[2];
456 hueScoreHistogram[hue] += score;
457 if (hueScoreHistogram[hue] > highScore) {
458 highScore = hueScoreHistogram[hue];
459 bestHue = hue;
460 }
461 }
462 }
463
464 SparseArray<Float> rgbScores = new SparseArray<Float>();
465 int bestColor = 0xff000000;
466 highScore = -1;
467 // Go back over the RGB colors that match the winning hue,
468 // creating a histogram of weighted s*v scores, for up to 100*100 [s,v] buckets.
469 // The highest-scoring RGB color wins.
470 for (int y = 0; y < height; y += sampleStride) {
471 for (int x = 0; x < width; x += sampleStride) {
472 int rgb = bitmap.getPixel(x, y) | 0xff000000;
473 Color.colorToHSV(rgb, hsv);
474 int hue = (int) hsv[0];
475 if (hue == bestHue) {
476 float s = hsv[1];
477 float v = hsv[2];
478 int bucket = (int) (s * 100) + (int) (v * 10000);
479 // Score by cumulative saturation * value.
480 float score = s * v;
481 Float oldTotal = rgbScores.get(bucket);
482 float newTotal = oldTotal == null ? score : oldTotal + score;
483 rgbScores.put(bucket, newTotal);
484 if (newTotal > highScore) {
485 highScore = newTotal;
486 // All the colors in the winning bucket are very similar. Last in wins.
487 bestColor = rgb;
488 }
489 }
490 }
491 }
492 return bestColor;
493 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700494
495 /*
496 * Finds a system apk which had a broadcast receiver listening to a particular action.
497 * @param action intent action used to find the apk
498 * @return a pair of apk package name and the resources.
499 */
500 static Pair<String, Resources> findSystemApk(String action, PackageManager pm) {
501 final Intent intent = new Intent(action);
502 for (ResolveInfo info : pm.queryBroadcastReceivers(intent, 0)) {
503 if (info.activityInfo != null &&
504 (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
505 final String packageName = info.activityInfo.packageName;
506 try {
507 final Resources res = pm.getResourcesForApplication(packageName);
508 return Pair.create(packageName, res);
509 } catch (NameNotFoundException e) {
510 Log.w(TAG, "Failed to find resources for " + packageName);
511 }
512 }
513 }
514 return null;
515 }
Sunny Goyalfafca522014-11-03 11:30:01 -0800516
517 @TargetApi(Build.VERSION_CODES.KITKAT)
518 public static boolean isViewAttachedToWindow(View v) {
519 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
520 return v.isAttachedToWindow();
521 } else {
522 // A proxy call which returns null, if the view is not attached to the window.
523 return v.getKeyDispatcherState() != null;
524 }
525 }
Sunny Goyal594d76d2014-11-06 10:12:54 -0800526
527 /**
528 * Returns a widget with category {@link AppWidgetProviderInfo#WIDGET_CATEGORY_SEARCHBOX}
529 * provided by the same package which is set to be global search activity.
530 * If widgetCategory is not supported, or no such widget is found, returns the first widget
531 * provided by the package.
532 */
533 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
534 public static AppWidgetProviderInfo getSearchWidgetProvider(Context context) {
535 SearchManager searchManager =
536 (SearchManager) context.getSystemService(Context.SEARCH_SERVICE);
537 ComponentName searchComponent = searchManager.getGlobalSearchActivity();
538 if (searchComponent == null) return null;
539 String providerPkg = searchComponent.getPackageName();
540
541 AppWidgetProviderInfo defaultWidgetForSearchPackage = null;
542
543 AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
544 for (AppWidgetProviderInfo info : appWidgetManager.getInstalledProviders()) {
545 if (info.provider.getPackageName().equals(providerPkg)) {
546 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
547 if ((info.widgetCategory & AppWidgetProviderInfo.WIDGET_CATEGORY_SEARCHBOX) != 0) {
548 return info;
549 } else if (defaultWidgetForSearchPackage == null) {
550 defaultWidgetForSearchPackage = info;
551 }
552 } else {
553 return info;
554 }
555 }
556 }
557 return defaultWidgetForSearchPackage;
558 }
Sunny Goyal08f72612015-01-05 13:41:43 -0800559
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700560 /**
561 * Compresses the bitmap to a byte array for serialization.
562 */
563 public static byte[] flattenBitmap(Bitmap bitmap) {
564 // Try go guesstimate how much space the icon will take when serialized
565 // to avoid unnecessary allocations/copies during the write.
566 int size = bitmap.getWidth() * bitmap.getHeight() * 4;
567 ByteArrayOutputStream out = new ByteArrayOutputStream(size);
568 try {
569 bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
570 out.flush();
571 out.close();
572 return out.toByteArray();
573 } catch (IOException e) {
574 Log.w(TAG, "Could not write bitmap");
575 return null;
576 }
577 }
578
Sunny Goyal08f72612015-01-05 13:41:43 -0800579 public static final Comparator<ItemInfo> RANK_COMPARATOR = new Comparator<ItemInfo>() {
580
581 @Override
582 public int compare(ItemInfo lhs, ItemInfo rhs) {
583 return lhs.rank - rhs.rank;
584 }
585 };
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800586}