blob: 6c4b7207bc3396eceb7a423c8a096ed4403570f3 [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;
Adam Cohen2e6da152015-05-06 11:42:25 -070049import android.util.DisplayMetrics;
Michael Jurkaa805e1a2013-08-22 15:00:33 +020050import android.util.Log;
Sunny Goyal0fe505b2014-08-06 09:55:36 -070051import android.util.Pair;
Sunny Goyal95abbb32014-08-04 10:53:22 -070052import android.util.SparseArray;
Adam Cohen2e6da152015-05-06 11:42:25 -070053import android.util.TypedValue;
Winson Chungc763c4e2013-07-19 13:49:06 -070054import android.view.View;
Michael Jurkaa805e1a2013-08-22 15:00:33 +020055import android.widget.Toast;
Winson Chungc763c4e2013-07-19 13:49:06 -070056
Sunny Goyal5c97f512015-05-19 16:03:28 -070057import junit.framework.Assert;
58
Sunny Goyal5b0e6692015-03-19 14:31:19 -070059import java.io.ByteArrayOutputStream;
60import java.io.IOException;
Winson Chungc763c4e2013-07-19 13:49:06 -070061import java.util.ArrayList;
Sunny Goyal08f72612015-01-05 13:41:43 -080062import java.util.Comparator;
Winson Chung82b016c2015-05-08 17:00:10 -070063import java.util.regex.Matcher;
64import java.util.regex.Pattern;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080065
66/**
67 * Various utilities shared amongst the Launcher's classes.
68 */
Mathew Inwood72fbec12013-11-19 15:45:07 +000069public final class Utilities {
Joe Onorato1291a8c2009-09-15 15:07:25 -040070 private static final String TAG = "Launcher.Utilities";
71
The Android Open Source Project31dd5032009-03-03 19:32:27 -080072 private static int sIconWidth = -1;
73 private static int sIconHeight = -1;
74
The Android Open Source Project31dd5032009-03-03 19:32:27 -080075 private static final Rect sOldBounds = new Rect();
Romain Guy89911d22009-09-28 18:48:49 -070076 private static final Canvas sCanvas = new Canvas();
The Android Open Source Project31dd5032009-03-03 19:32:27 -080077
Winson Chung82b016c2015-05-08 17:00:10 -070078 private static final Pattern sTrimPattern =
79 Pattern.compile("^[\\s|\\p{javaSpaceChar}]*(.*)[\\s|\\p{javaSpaceChar}]*$");
80
The Android Open Source Project31dd5032009-03-03 19:32:27 -080081 static {
82 sCanvas.setDrawFilter(new PaintFlagsDrawFilter(Paint.DITHER_FLAG,
83 Paint.FILTER_BITMAP_FLAG));
84 }
Joe Onorato6665c0f2009-09-02 15:27:24 -070085 static int sColors[] = { 0xffff0000, 0xff00ff00, 0xff0000ff };
86 static int sColorIndex = 0;
87
Adam Cohen63f1ec02014-08-12 09:23:13 -070088 static int[] sLoc0 = new int[2];
89 static int[] sLoc1 = new int[2];
Michael Jurka7ad868b2013-12-12 15:04:25 +010090
91 // To turn on these properties, type
92 // adb shell setprop log.tag.PROPERTY_NAME [VERBOSE | SUPPRESS]
93 static final String FORCE_ENABLE_ROTATION_PROPERTY = "launcher_force_rotate";
94 public static boolean sForceEnableRotation = isPropertyEnabled(FORCE_ENABLE_ROTATION_PROPERTY);
95
Joe Onorato6665c0f2009-09-02 15:27:24 -070096 /**
Winson Chung0dbd7342013-10-13 22:46:20 -070097 * Returns a FastBitmapDrawable with the icon, accurately sized.
98 */
Sunny Goyalffe83f12014-08-14 17:39:34 -070099 public static FastBitmapDrawable createIconDrawable(Bitmap icon) {
Winson Chung0dbd7342013-10-13 22:46:20 -0700100 FastBitmapDrawable d = new FastBitmapDrawable(icon);
Winson Chung54000492013-10-14 16:29:29 -0700101 d.setFilterBitmap(true);
Winson Chung0dbd7342013-10-13 22:46:20 -0700102 resizeIconDrawable(d);
103 return d;
104 }
105
106 /**
107 * Resizes an icon drawable to the correct icon size.
108 */
109 static void resizeIconDrawable(Drawable icon) {
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700110 icon.setBounds(0, 0, sIconWidth, sIconHeight);
Winson Chung0dbd7342013-10-13 22:46:20 -0700111 }
112
Sunny Goyal4bbf4192014-11-11 12:23:59 -0800113 public static boolean isPropertyEnabled(String propertyName) {
Michael Jurka7ad868b2013-12-12 15:04:25 +0100114 return Log.isLoggable(propertyName, Log.VERBOSE);
115 }
116
117 public static boolean isRotationEnabled(Context c) {
118 boolean enableRotation = sForceEnableRotation ||
119 c.getResources().getBoolean(R.bool.allow_rotation);
120 return enableRotation;
121 }
122
Winson Chung0dbd7342013-10-13 22:46:20 -0700123 /**
Kenny Guyd794a3f2014-09-16 15:17:58 +0100124 * Indicates if the device is running LMP or higher.
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -0700125 */
Kenny Guyd794a3f2014-09-16 15:17:58 +0100126 public static boolean isLmpOrAbove() {
Brian Parfett1bc1ae62014-12-12 12:30:00 -0800127 return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -0700128 }
129
Sunny Goyal4fbc3822015-02-18 16:46:50 -0800130 static Bitmap createIconBitmap(Cursor c, int iconIndex, Context context) {
131 byte[] data = c.getBlob(iconIndex);
132 try {
133 return createIconBitmap(BitmapFactory.decodeByteArray(data, 0, data.length), context);
134 } catch (Exception e) {
135 return null;
136 }
137 }
138
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -0700139 /**
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700140 * Returns a bitmap suitable for the all apps view. If the package or the resource do not
141 * exist, it returns null.
142 */
143 static Bitmap createIconBitmap(String packageName, String resourceName, IconCache cache,
144 Context context) {
145 PackageManager packageManager = context.getPackageManager();
146 // the resource
147 try {
148 Resources resources = packageManager.getResourcesForApplication(packageName);
149 if (resources != null) {
150 final int id = resources.getIdentifier(resourceName, null, null);
151 return createIconBitmap(
152 resources.getDrawableForDensity(id, cache.getFullResIconDpi()), context);
153 }
154 } catch (Exception e) {
155 // Icon not found.
156 }
157 return null;
158 }
159
160 /**
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700161 * Returns a bitmap which is of the appropriate size to be displayed as an icon
Michael Jurka931dc972011-08-05 15:08:15 -0700162 */
163 static Bitmap createIconBitmap(Bitmap icon, Context context) {
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700164 synchronized (sCanvas) { // we share the statics :-(
165 if (sIconWidth == -1) {
166 initStatics(context);
167 }
Michael Jurka931dc972011-08-05 15:08:15 -0700168 }
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700169 if (sIconWidth == icon.getWidth() && sIconHeight == icon.getHeight()) {
170 return icon;
171 }
172 return createIconBitmap(new BitmapDrawable(context.getResources(), icon), context);
Michael Jurka931dc972011-08-05 15:08:15 -0700173 }
174
175 /**
176 * Returns a bitmap suitable for the all apps view.
Joe Onorato6665c0f2009-09-02 15:27:24 -0700177 */
Mathew Inwood72fbec12013-11-19 15:45:07 +0000178 public static Bitmap createIconBitmap(Drawable icon, Context context) {
Joe Onorato6665c0f2009-09-02 15:27:24 -0700179 synchronized (sCanvas) { // we share the statics :-(
180 if (sIconWidth == -1) {
181 initStatics(context);
182 }
183
184 int width = sIconWidth;
185 int height = sIconHeight;
186
Joe Onorato6665c0f2009-09-02 15:27:24 -0700187 if (icon instanceof PaintDrawable) {
188 PaintDrawable painter = (PaintDrawable) icon;
189 painter.setIntrinsicWidth(width);
190 painter.setIntrinsicHeight(height);
191 } else if (icon instanceof BitmapDrawable) {
192 // Ensure the bitmap has a density.
193 BitmapDrawable bitmapDrawable = (BitmapDrawable) icon;
194 Bitmap bitmap = bitmapDrawable.getBitmap();
195 if (bitmap.getDensity() == Bitmap.DENSITY_NONE) {
196 bitmapDrawable.setTargetDensity(context.getResources().getDisplayMetrics());
197 }
198 }
199 int sourceWidth = icon.getIntrinsicWidth();
200 int sourceHeight = icon.getIntrinsicHeight();
Michael Jurka931dc972011-08-05 15:08:15 -0700201 if (sourceWidth > 0 && sourceHeight > 0) {
Winson Chung5f8afe62013-08-12 16:19:28 -0700202 // Scale the icon proportionally to the icon dimensions
203 final float ratio = (float) sourceWidth / sourceHeight;
204 if (sourceWidth > sourceHeight) {
205 height = (int) (width / ratio);
206 } else if (sourceHeight > sourceWidth) {
207 width = (int) (height * ratio);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700208 }
209 }
210
211 // no intrinsic size --> use default size
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700212 int textureWidth = sIconWidth;
213 int textureHeight = sIconHeight;
Joe Onorato6665c0f2009-09-02 15:27:24 -0700214
215 final Bitmap bitmap = Bitmap.createBitmap(textureWidth, textureHeight,
216 Bitmap.Config.ARGB_8888);
217 final Canvas canvas = sCanvas;
218 canvas.setBitmap(bitmap);
219
220 final int left = (textureWidth-width) / 2;
221 final int top = (textureHeight-height) / 2;
222
Michael Jurka3a9fced2012-04-13 14:44:29 -0700223 @SuppressWarnings("all") // suppress dead code warning
224 final boolean debug = false;
225 if (debug) {
Joe Onorato6665c0f2009-09-02 15:27:24 -0700226 // draw a big box for the icon for debugging
227 canvas.drawColor(sColors[sColorIndex]);
228 if (++sColorIndex >= sColors.length) sColorIndex = 0;
229 Paint debugPaint = new Paint();
230 debugPaint.setColor(0xffcccc00);
231 canvas.drawRect(left, top, left+width, top+height, debugPaint);
232 }
233
234 sOldBounds.set(icon.getBounds());
235 icon.setBounds(left, top, left+width, top+height);
236 icon.draw(canvas);
237 icon.setBounds(sOldBounds);
Adam Cohenaaf473c2011-08-03 12:02:47 -0700238 canvas.setBitmap(null);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700239
240 return bitmap;
241 }
242 }
243
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800244 /**
Winson Chungc763c4e2013-07-19 13:49:06 -0700245 * Given a coordinate relative to the descendant, find the coordinate in a parent view's
246 * coordinates.
247 *
248 * @param descendant The descendant to which the passed coordinate is relative.
249 * @param root The root view to make the coordinates relative to.
250 * @param coord The coordinate that we want mapped.
251 * @param includeRootScroll Whether or not to account for the scroll of the descendant:
252 * sometimes this is relevant as in a child's coordinates within the descendant.
253 * @return The factor by which this descendant is scaled relative to this DragLayer. Caution
254 * this scale factor is assumed to be equal in X and Y, and so if at any point this
255 * assumption fails, we will need to return a pair of scale factors.
256 */
257 public static float getDescendantCoordRelativeToParent(View descendant, View root,
258 int[] coord, boolean includeRootScroll) {
259 ArrayList<View> ancestorChain = new ArrayList<View>();
260
261 float[] pt = {coord[0], coord[1]};
262
263 View v = descendant;
264 while(v != root && v != null) {
265 ancestorChain.add(v);
266 v = (View) v.getParent();
267 }
268 ancestorChain.add(root);
269
270 float scale = 1.0f;
271 int count = ancestorChain.size();
272 for (int i = 0; i < count; i++) {
273 View v0 = ancestorChain.get(i);
Winson Chungc763c4e2013-07-19 13:49:06 -0700274 // For TextViews, scroll has a meaning which relates to the text position
275 // which is very strange... ignore the scroll.
276 if (v0 != descendant || includeRootScroll) {
277 pt[0] -= v0.getScrollX();
278 pt[1] -= v0.getScrollY();
279 }
280
281 v0.getMatrix().mapPoints(pt);
282 pt[0] += v0.getLeft();
283 pt[1] += v0.getTop();
284 scale *= v0.getScaleX();
285 }
286
287 coord[0] = (int) Math.round(pt[0]);
288 coord[1] = (int) Math.round(pt[1]);
289 return scale;
290 }
291
292 /**
293 * Inverse of {@link #getDescendantCoordRelativeToSelf(View, int[])}.
294 */
295 public static float mapCoordInSelfToDescendent(View descendant, View root,
296 int[] coord) {
297 ArrayList<View> ancestorChain = new ArrayList<View>();
298
299 float[] pt = {coord[0], coord[1]};
300
301 View v = descendant;
302 while(v != root) {
303 ancestorChain.add(v);
304 v = (View) v.getParent();
305 }
306 ancestorChain.add(root);
307
308 float scale = 1.0f;
309 Matrix inverse = new Matrix();
310 int count = ancestorChain.size();
311 for (int i = count - 1; i >= 0; i--) {
312 View ancestor = ancestorChain.get(i);
313 View next = i > 0 ? ancestorChain.get(i-1) : null;
314
315 pt[0] += ancestor.getScrollX();
316 pt[1] += ancestor.getScrollY();
317
318 if (next != null) {
319 pt[0] -= next.getLeft();
320 pt[1] -= next.getTop();
321 next.getMatrix().invert(inverse);
322 inverse.mapPoints(pt);
323 scale *= next.getScaleX();
324 }
325 }
326
327 coord[0] = (int) Math.round(pt[0]);
328 coord[1] = (int) Math.round(pt[1]);
329 return scale;
330 }
331
Jason Monk02dd7ae2014-04-15 15:23:31 -0400332 /**
333 * Utility method to determine whether the given point, in local coordinates,
334 * is inside the view, where the area of the view is expanded by the slop factor.
335 * This method is called while processing touch-move events to determine if the event
336 * is still within the view.
337 */
338 public static boolean pointInView(View v, float localX, float localY, float slop) {
339 return localX >= -slop && localY >= -slop && localX < (v.getWidth() + slop) &&
340 localY < (v.getHeight() + slop);
341 }
342
Joe Onorato6665c0f2009-09-02 15:27:24 -0700343 private static void initStatics(Context context) {
344 final Resources resources = context.getResources();
Michael Jurkac9a96192010-11-01 11:52:08 -0700345 sIconWidth = sIconHeight = (int) resources.getDimension(R.dimen.app_icon_size);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700346 }
347
Winson Chung5f8afe62013-08-12 16:19:28 -0700348 public static void setIconSize(int widthPx) {
349 sIconWidth = sIconHeight = widthPx;
Winson Chung97d85d22011-04-13 11:27:36 -0700350 }
Michael Jurkaa805e1a2013-08-22 15:00:33 +0200351
Winson Chung3a6e7f32013-10-09 15:50:52 -0700352 public static void scaleRect(Rect r, float scale) {
353 if (scale != 1.0f) {
354 r.left = (int) (r.left * scale + 0.5f);
355 r.top = (int) (r.top * scale + 0.5f);
356 r.right = (int) (r.right * scale + 0.5f);
357 r.bottom = (int) (r.bottom * scale + 0.5f);
358 }
359 }
360
Adam Cohen63f1ec02014-08-12 09:23:13 -0700361 public static int[] getCenterDeltaInScreenSpace(View v0, View v1, int[] delta) {
362 v0.getLocationInWindow(sLoc0);
363 v1.getLocationInWindow(sLoc1);
364
365 sLoc0[0] += (v0.getMeasuredWidth() * v0.getScaleX()) / 2;
366 sLoc0[1] += (v0.getMeasuredHeight() * v0.getScaleY()) / 2;
367 sLoc1[0] += (v1.getMeasuredWidth() * v1.getScaleX()) / 2;
368 sLoc1[1] += (v1.getMeasuredHeight() * v1.getScaleY()) / 2;
369
370 if (delta == null) {
371 delta = new int[2];
372 }
373
374 delta[0] = sLoc1[0] - sLoc0[0];
375 delta[1] = sLoc1[1] - sLoc0[1];
376
377 return delta;
378 }
379
Winson Chung3a6e7f32013-10-09 15:50:52 -0700380 public static void scaleRectAboutCenter(Rect r, float scale) {
381 int cx = r.centerX();
382 int cy = r.centerY();
383 r.offset(-cx, -cy);
384 Utilities.scaleRect(r, scale);
385 r.offset(cx, cy);
386 }
387
Michael Jurkaa805e1a2013-08-22 15:00:33 +0200388 public static void startActivityForResultSafely(
389 Activity activity, Intent intent, int requestCode) {
390 try {
391 activity.startActivityForResult(intent, requestCode);
392 } catch (ActivityNotFoundException e) {
393 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
394 } catch (SecurityException e) {
395 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
396 Log.e(TAG, "Launcher does not have the permission to launch " + intent +
397 ". Make sure to create a MAIN intent-filter for the corresponding activity " +
398 "or use the exported attribute for this activity.", e);
399 }
400 }
Sunny Goyalc5c60ad2014-07-14 12:02:01 -0700401
402 static boolean isSystemApp(Context context, Intent intent) {
403 PackageManager pm = context.getPackageManager();
404 ComponentName cn = intent.getComponent();
405 String packageName = null;
406 if (cn == null) {
407 ResolveInfo info = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
408 if ((info != null) && (info.activityInfo != null)) {
409 packageName = info.activityInfo.packageName;
410 }
411 } else {
412 packageName = cn.getPackageName();
413 }
414 if (packageName != null) {
415 try {
416 PackageInfo info = pm.getPackageInfo(packageName, 0);
417 return (info != null) && (info.applicationInfo != null) &&
418 ((info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
419 } catch (NameNotFoundException e) {
420 return false;
421 }
422 } else {
423 return false;
424 }
425 }
Sunny Goyal95abbb32014-08-04 10:53:22 -0700426
427 /**
428 * This picks a dominant color, looking for high-saturation, high-value, repeated hues.
429 * @param bitmap The bitmap to scan
430 * @param samples The approximate max number of samples to use.
431 */
432 static int findDominantColorByHue(Bitmap bitmap, int samples) {
433 final int height = bitmap.getHeight();
434 final int width = bitmap.getWidth();
435 int sampleStride = (int) Math.sqrt((height * width) / samples);
436 if (sampleStride < 1) {
437 sampleStride = 1;
438 }
439
440 // This is an out-param, for getting the hsv values for an rgb
441 float[] hsv = new float[3];
442
443 // First get the best hue, by creating a histogram over 360 hue buckets,
444 // where each pixel contributes a score weighted by saturation, value, and alpha.
445 float[] hueScoreHistogram = new float[360];
446 float highScore = -1;
447 int bestHue = -1;
448
449 for (int y = 0; y < height; y += sampleStride) {
450 for (int x = 0; x < width; x += sampleStride) {
451 int argb = bitmap.getPixel(x, y);
452 int alpha = 0xFF & (argb >> 24);
453 if (alpha < 0x80) {
454 // Drop mostly-transparent pixels.
455 continue;
456 }
457 // Remove the alpha channel.
458 int rgb = argb | 0xFF000000;
459 Color.colorToHSV(rgb, hsv);
460 // Bucket colors by the 360 integer hues.
461 int hue = (int) hsv[0];
462 if (hue < 0 || hue >= hueScoreHistogram.length) {
463 // Defensively avoid array bounds violations.
464 continue;
465 }
466 float score = hsv[1] * hsv[2];
467 hueScoreHistogram[hue] += score;
468 if (hueScoreHistogram[hue] > highScore) {
469 highScore = hueScoreHistogram[hue];
470 bestHue = hue;
471 }
472 }
473 }
474
475 SparseArray<Float> rgbScores = new SparseArray<Float>();
476 int bestColor = 0xff000000;
477 highScore = -1;
478 // Go back over the RGB colors that match the winning hue,
479 // creating a histogram of weighted s*v scores, for up to 100*100 [s,v] buckets.
480 // The highest-scoring RGB color wins.
481 for (int y = 0; y < height; y += sampleStride) {
482 for (int x = 0; x < width; x += sampleStride) {
483 int rgb = bitmap.getPixel(x, y) | 0xff000000;
484 Color.colorToHSV(rgb, hsv);
485 int hue = (int) hsv[0];
486 if (hue == bestHue) {
487 float s = hsv[1];
488 float v = hsv[2];
489 int bucket = (int) (s * 100) + (int) (v * 10000);
490 // Score by cumulative saturation * value.
491 float score = s * v;
492 Float oldTotal = rgbScores.get(bucket);
493 float newTotal = oldTotal == null ? score : oldTotal + score;
494 rgbScores.put(bucket, newTotal);
495 if (newTotal > highScore) {
496 highScore = newTotal;
497 // All the colors in the winning bucket are very similar. Last in wins.
498 bestColor = rgb;
499 }
500 }
501 }
502 }
503 return bestColor;
504 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700505
506 /*
507 * Finds a system apk which had a broadcast receiver listening to a particular action.
508 * @param action intent action used to find the apk
509 * @return a pair of apk package name and the resources.
510 */
511 static Pair<String, Resources> findSystemApk(String action, PackageManager pm) {
512 final Intent intent = new Intent(action);
513 for (ResolveInfo info : pm.queryBroadcastReceivers(intent, 0)) {
514 if (info.activityInfo != null &&
515 (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
516 final String packageName = info.activityInfo.packageName;
517 try {
518 final Resources res = pm.getResourcesForApplication(packageName);
519 return Pair.create(packageName, res);
520 } catch (NameNotFoundException e) {
521 Log.w(TAG, "Failed to find resources for " + packageName);
522 }
523 }
524 }
525 return null;
526 }
Sunny Goyalfafca522014-11-03 11:30:01 -0800527
528 @TargetApi(Build.VERSION_CODES.KITKAT)
529 public static boolean isViewAttachedToWindow(View v) {
530 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
531 return v.isAttachedToWindow();
532 } else {
533 // A proxy call which returns null, if the view is not attached to the window.
534 return v.getKeyDispatcherState() != null;
535 }
536 }
Sunny Goyal594d76d2014-11-06 10:12:54 -0800537
538 /**
539 * Returns a widget with category {@link AppWidgetProviderInfo#WIDGET_CATEGORY_SEARCHBOX}
540 * provided by the same package which is set to be global search activity.
541 * If widgetCategory is not supported, or no such widget is found, returns the first widget
542 * provided by the package.
543 */
544 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
545 public static AppWidgetProviderInfo getSearchWidgetProvider(Context context) {
546 SearchManager searchManager =
547 (SearchManager) context.getSystemService(Context.SEARCH_SERVICE);
548 ComponentName searchComponent = searchManager.getGlobalSearchActivity();
549 if (searchComponent == null) return null;
550 String providerPkg = searchComponent.getPackageName();
551
552 AppWidgetProviderInfo defaultWidgetForSearchPackage = null;
553
554 AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
555 for (AppWidgetProviderInfo info : appWidgetManager.getInstalledProviders()) {
556 if (info.provider.getPackageName().equals(providerPkg)) {
557 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
558 if ((info.widgetCategory & AppWidgetProviderInfo.WIDGET_CATEGORY_SEARCHBOX) != 0) {
559 return info;
560 } else if (defaultWidgetForSearchPackage == null) {
561 defaultWidgetForSearchPackage = info;
562 }
563 } else {
564 return info;
565 }
566 }
567 }
568 return defaultWidgetForSearchPackage;
569 }
Sunny Goyal08f72612015-01-05 13:41:43 -0800570
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700571 /**
572 * Compresses the bitmap to a byte array for serialization.
573 */
574 public static byte[] flattenBitmap(Bitmap bitmap) {
575 // Try go guesstimate how much space the icon will take when serialized
576 // to avoid unnecessary allocations/copies during the write.
577 int size = bitmap.getWidth() * bitmap.getHeight() * 4;
578 ByteArrayOutputStream out = new ByteArrayOutputStream(size);
579 try {
580 bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
581 out.flush();
582 out.close();
583 return out.toByteArray();
584 } catch (IOException e) {
585 Log.w(TAG, "Could not write bitmap");
586 return null;
587 }
588 }
589
Sunny Goyal08f72612015-01-05 13:41:43 -0800590 public static final Comparator<ItemInfo> RANK_COMPARATOR = new Comparator<ItemInfo>() {
591
592 @Override
593 public int compare(ItemInfo lhs, ItemInfo rhs) {
594 return lhs.rank - rhs.rank;
595 }
596 };
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700597
598 /**
599 * Find the first vacant cell, if there is one.
600 *
601 * @param vacant Holds the x and y coordinate of the vacant cell
602 * @param spanX Horizontal cell span.
603 * @param spanY Vertical cell span.
604 *
605 * @return true if a vacant cell was found
606 */
607 public static boolean findVacantCell(int[] vacant, int spanX, int spanY,
608 int xCount, int yCount, boolean[][] occupied) {
609
610 for (int y = 0; (y + spanY) <= yCount; y++) {
611 for (int x = 0; (x + spanX) <= xCount; x++) {
612 boolean available = !occupied[x][y];
613 out: for (int i = x; i < x + spanX; i++) {
614 for (int j = y; j < y + spanY; j++) {
615 available = available && !occupied[i][j];
616 if (!available) break out;
617 }
618 }
619
620 if (available) {
621 vacant[0] = x;
622 vacant[1] = y;
623 return true;
624 }
625 }
626 }
627
628 return false;
629 }
Winson Chung82b016c2015-05-08 17:00:10 -0700630
631 /**
632 * Trims the string, removing all whitespace at the beginning and end of the string.
633 * Non-breaking whitespaces are also removed.
634 */
635 public static String trim(CharSequence s) {
Winson Chungafa77e92015-05-15 12:04:03 -0700636 if (s == null) {
637 return null;
638 }
639
Winson Chung82b016c2015-05-08 17:00:10 -0700640 // Just strip any sequence of whitespace or java space characters from the beginning and end
641 Matcher m = sTrimPattern.matcher(s);
642 return m.replaceAll("$1");
643 }
Sunny Goyal70660032015-05-14 00:07:08 -0700644
645 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
646 public static boolean isRtl(Resources res) {
647 return (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) &&
648 (res.getConfiguration().getLayoutDirection() == View.LAYOUT_DIRECTION_RTL);
649 }
Hyunyoung Song2bd3d7d2015-05-21 13:04:53 -0700650
651 public static void assertWorkerThread() {
652 if (LauncherAppState.isDogfoodBuild()) {
653 Assert.assertTrue(LauncherModel.sWorkerThread.getThreadId() == Process.myTid());
654 }
655 }
Sunny Goyal5c97f512015-05-19 16:03:28 -0700656
657 /**
658 * Returns true if the intent is a valid launch intent for a launcher activity of an app.
659 * This is used to identify shortcuts which are different from the ones exposed by the
660 * applications' manifest file.
661 *
662 * @param launchIntent The intent that will be launched when the shortcut is clicked.
663 */
664 public static boolean isLauncherAppTarget(Intent launchIntent) {
665 return launchIntent != null
666 && Intent.ACTION_MAIN.equals(launchIntent.getAction())
667 && launchIntent.getComponent() != null
668 && launchIntent.getCategories() != null
669 && launchIntent.getCategories().size() == 1
670 && launchIntent.hasCategory(Intent.CATEGORY_LAUNCHER)
671 && launchIntent.getExtras() == null
672 && TextUtils.isEmpty(launchIntent.getDataString());
673 }
Adam Cohen2e6da152015-05-06 11:42:25 -0700674
675 public static float dpiFromPx(int size, DisplayMetrics metrics){
676 float densityRatio = (float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT;
677 return (size / densityRatio);
678 }
679 public static int pxFromDp(float size, DisplayMetrics metrics) {
680 return (int) Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
681 size, metrics));
682 }
683 public static int pxFromSp(float size, DisplayMetrics metrics) {
684 return (int) Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
685 size, metrics));
686 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800687}