blob: 6521f15b2134b3790011b52cdb91aa191a0036ad [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;
Rahul Chaturvedi7fc77ca2015-05-19 18:02:16 -070028import android.content.SharedPreferences;
Sunny Goyalc5c60ad2014-07-14 12:02:01 -070029import android.content.pm.ApplicationInfo;
30import android.content.pm.PackageInfo;
31import android.content.pm.PackageManager;
32import android.content.pm.PackageManager.NameNotFoundException;
33import android.content.pm.ResolveInfo;
Winson Chungaafa03c2010-06-11 17:34:16 -070034import android.content.res.Resources;
Sunny Goyal4fbc3822015-02-18 16:46:50 -080035import android.database.Cursor;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080036import android.graphics.Bitmap;
Sunny Goyal4fbc3822015-02-18 16:46:50 -080037import android.graphics.BitmapFactory;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080038import android.graphics.Canvas;
Sunny Goyal95abbb32014-08-04 10:53:22 -070039import android.graphics.Color;
Winson Chungc763c4e2013-07-19 13:49:06 -070040import android.graphics.Matrix;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080041import android.graphics.Paint;
Joe Onoratobf15cb42009-08-07 14:33:40 -070042import android.graphics.PaintFlagsDrawFilter;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080043import android.graphics.Rect;
Winson Chungaafa03c2010-06-11 17:34:16 -070044import android.graphics.drawable.BitmapDrawable;
45import android.graphics.drawable.Drawable;
46import android.graphics.drawable.PaintDrawable;
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -070047import android.os.Build;
Sunny Goyal4e5cc642015-06-25 16:37:44 -070048import android.os.Bundle;
Hyunyoung Song2bd3d7d2015-05-21 13:04:53 -070049import android.os.Process;
Sunny Goyal5c97f512015-05-19 16:03:28 -070050import android.text.TextUtils;
Adam Cohen2e6da152015-05-06 11:42:25 -070051import android.util.DisplayMetrics;
Michael Jurkaa805e1a2013-08-22 15:00:33 +020052import android.util.Log;
Sunny Goyal0fe505b2014-08-06 09:55:36 -070053import android.util.Pair;
Sunny Goyal95abbb32014-08-04 10:53:22 -070054import android.util.SparseArray;
Adam Cohen2e6da152015-05-06 11:42:25 -070055import android.util.TypedValue;
Winson Chungc763c4e2013-07-19 13:49:06 -070056import android.view.View;
Michael Jurkaa805e1a2013-08-22 15:00:33 +020057import android.widget.Toast;
Sunny Goyalb1622cc2015-06-10 16:00:42 -070058
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 Goyalb1622cc2015-06-10 16:00:42 -070062import java.util.Locale;
Sunny Goyal4e5cc642015-06-25 16:37:44 -070063import java.util.Set;
Sunny Goyal8ac727b2015-09-23 15:38:09 -070064import java.util.concurrent.Executor;
65import java.util.concurrent.LinkedBlockingQueue;
66import java.util.concurrent.ThreadPoolExecutor;
67import java.util.concurrent.TimeUnit;
Winson Chung82b016c2015-05-08 17:00:10 -070068import java.util.regex.Matcher;
69import java.util.regex.Pattern;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080070
71/**
72 * Various utilities shared amongst the Launcher's classes.
73 */
Mathew Inwood72fbec12013-11-19 15:45:07 +000074public final class Utilities {
Rahul Chaturvedi7fc77ca2015-05-19 18:02:16 -070075
Joe Onorato1291a8c2009-09-15 15:07:25 -040076 private static final String TAG = "Launcher.Utilities";
77
The Android Open Source Project31dd5032009-03-03 19:32:27 -080078 private static final Rect sOldBounds = new Rect();
Romain Guy89911d22009-09-28 18:48:49 -070079 private static final Canvas sCanvas = new Canvas();
The Android Open Source Project31dd5032009-03-03 19:32:27 -080080
Winson Chung82b016c2015-05-08 17:00:10 -070081 private static final Pattern sTrimPattern =
82 Pattern.compile("^[\\s|\\p{javaSpaceChar}]*(.*)[\\s|\\p{javaSpaceChar}]*$");
83
The Android Open Source Project31dd5032009-03-03 19:32:27 -080084 static {
85 sCanvas.setDrawFilter(new PaintFlagsDrawFilter(Paint.DITHER_FLAG,
86 Paint.FILTER_BITMAP_FLAG));
87 }
Joe Onorato6665c0f2009-09-02 15:27:24 -070088 static int sColors[] = { 0xffff0000, 0xff00ff00, 0xff0000ff };
89 static int sColorIndex = 0;
90
Sunny Goyal53d7ee42015-05-22 12:25:45 -070091 private static final int[] sLoc0 = new int[2];
92 private static final int[] sLoc1 = new int[2];
Michael Jurka7ad868b2013-12-12 15:04:25 +010093
Sunny Goyal9fc953b2015-08-17 12:24:25 -070094 // TODO: use Build.VERSION_CODES when available
95 public static final boolean ATLEAST_MARSHMALLOW = Build.VERSION.SDK_INT >= 23;
96
97 public static final boolean ATLEAST_LOLLIPOP_MR1 =
98 Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1;
99
100 public static final boolean ATLEAST_LOLLIPOP =
101 Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
102
103 public static final boolean ATLEAST_KITKAT =
104 Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
105
106 public static final boolean ATLEAST_JB_MR1 =
107 Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1;
108
109 public static final boolean ATLEAST_JB_MR2 =
110 Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2;
111
Sunny Goyal8ac727b2015-09-23 15:38:09 -0700112 // These values are same as that in {@link AsyncTask}.
113 private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
114 private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
115 private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
116 private static final int KEEP_ALIVE = 1;
117 /**
118 * An {@link Executor} to be used with async task with no limit on the queue size.
119 */
120 public static final Executor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(
121 CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
122 TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
123
Michael Jurka7ad868b2013-12-12 15:04:25 +0100124 // To turn on these properties, type
125 // adb shell setprop log.tag.PROPERTY_NAME [VERBOSE | SUPPRESS]
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700126 private static final String FORCE_ENABLE_ROTATION_PROPERTY = "launcher_force_rotate";
127 private static boolean sForceEnableRotation = isPropertyEnabled(FORCE_ENABLE_ROTATION_PROPERTY);
Michael Jurka7ad868b2013-12-12 15:04:25 +0100128
Rahul Chaturvedi7fc77ca2015-05-19 18:02:16 -0700129 public static final String ALLOW_ROTATION_PREFERENCE_KEY = "pref_allowRotation";
130
Sunny Goyal4bbf4192014-11-11 12:23:59 -0800131 public static boolean isPropertyEnabled(String propertyName) {
Michael Jurka7ad868b2013-12-12 15:04:25 +0100132 return Log.isLoggable(propertyName, Log.VERBOSE);
133 }
134
Rahul Chaturvedie863fed2015-06-15 14:09:42 -0400135 public static boolean isAllowRotationPrefEnabled(Context context, boolean multiProcess) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700136 SharedPreferences sharedPrefs = context.getSharedPreferences(
Rahul Chaturvedie863fed2015-06-15 14:09:42 -0400137 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE | (multiProcess ?
138 Context.MODE_MULTI_PROCESS : 0));
Rahul Chaturvedi7fc77ca2015-05-19 18:02:16 -0700139 boolean allowRotationPref = sharedPrefs.getBoolean(ALLOW_ROTATION_PREFERENCE_KEY, false);
140 return sForceEnableRotation || allowRotationPref;
141 }
142
143 public static boolean isRotationAllowedForDevice(Context context) {
144 return sForceEnableRotation || context.getResources().getBoolean(R.bool.allow_rotation);
Michael Jurka7ad868b2013-12-12 15:04:25 +0100145 }
146
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700147 public static Bitmap createIconBitmap(Cursor c, int iconIndex, Context context) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -0800148 byte[] data = c.getBlob(iconIndex);
149 try {
150 return createIconBitmap(BitmapFactory.decodeByteArray(data, 0, data.length), context);
151 } catch (Exception e) {
152 return null;
153 }
154 }
155
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -0700156 /**
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700157 * Returns a bitmap suitable for the all apps view. If the package or the resource do not
158 * exist, it returns null.
159 */
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700160 public static Bitmap createIconBitmap(String packageName, String resourceName,
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700161 Context context) {
162 PackageManager packageManager = context.getPackageManager();
163 // the resource
164 try {
165 Resources resources = packageManager.getResourcesForApplication(packageName);
166 if (resources != null) {
167 final int id = resources.getIdentifier(resourceName, null, null);
168 return createIconBitmap(
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700169 resources.getDrawableForDensity(id, LauncherAppState.getInstance()
170 .getInvariantDeviceProfile().fillResIconDpi), context);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700171 }
172 } catch (Exception e) {
173 // Icon not found.
174 }
175 return null;
176 }
177
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700178 private static int getIconBitmapSize() {
179 return LauncherAppState.getInstance().getInvariantDeviceProfile().iconBitmapSize;
180 }
181
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700182 /**
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700183 * Returns a bitmap which is of the appropriate size to be displayed as an icon
Michael Jurka931dc972011-08-05 15:08:15 -0700184 */
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700185 public static Bitmap createIconBitmap(Bitmap icon, Context context) {
186 final int iconBitmapSize = getIconBitmapSize();
187 if (iconBitmapSize == icon.getWidth() && iconBitmapSize == icon.getHeight()) {
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700188 return icon;
189 }
190 return createIconBitmap(new BitmapDrawable(context.getResources(), icon), context);
Michael Jurka931dc972011-08-05 15:08:15 -0700191 }
192
193 /**
194 * Returns a bitmap suitable for the all apps view.
Joe Onorato6665c0f2009-09-02 15:27:24 -0700195 */
Mathew Inwood72fbec12013-11-19 15:45:07 +0000196 public static Bitmap createIconBitmap(Drawable icon, Context context) {
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700197 synchronized (sCanvas) {
198 final int iconBitmapSize = getIconBitmapSize();
Joe Onorato6665c0f2009-09-02 15:27:24 -0700199
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700200 int width = iconBitmapSize;
201 int height = iconBitmapSize;
Joe Onorato6665c0f2009-09-02 15:27:24 -0700202
Joe Onorato6665c0f2009-09-02 15:27:24 -0700203 if (icon instanceof PaintDrawable) {
204 PaintDrawable painter = (PaintDrawable) icon;
205 painter.setIntrinsicWidth(width);
206 painter.setIntrinsicHeight(height);
207 } else if (icon instanceof BitmapDrawable) {
208 // Ensure the bitmap has a density.
209 BitmapDrawable bitmapDrawable = (BitmapDrawable) icon;
210 Bitmap bitmap = bitmapDrawable.getBitmap();
Sunny Goyalde9590b2015-09-23 12:56:51 -0700211 if (bitmap != null && bitmap.getDensity() == Bitmap.DENSITY_NONE) {
Joe Onorato6665c0f2009-09-02 15:27:24 -0700212 bitmapDrawable.setTargetDensity(context.getResources().getDisplayMetrics());
213 }
214 }
215 int sourceWidth = icon.getIntrinsicWidth();
216 int sourceHeight = icon.getIntrinsicHeight();
Michael Jurka931dc972011-08-05 15:08:15 -0700217 if (sourceWidth > 0 && sourceHeight > 0) {
Winson Chung5f8afe62013-08-12 16:19:28 -0700218 // Scale the icon proportionally to the icon dimensions
219 final float ratio = (float) sourceWidth / sourceHeight;
220 if (sourceWidth > sourceHeight) {
221 height = (int) (width / ratio);
222 } else if (sourceHeight > sourceWidth) {
223 width = (int) (height * ratio);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700224 }
225 }
226
227 // no intrinsic size --> use default size
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700228 int textureWidth = iconBitmapSize;
229 int textureHeight = iconBitmapSize;
Joe Onorato6665c0f2009-09-02 15:27:24 -0700230
231 final Bitmap bitmap = Bitmap.createBitmap(textureWidth, textureHeight,
232 Bitmap.Config.ARGB_8888);
233 final Canvas canvas = sCanvas;
234 canvas.setBitmap(bitmap);
235
236 final int left = (textureWidth-width) / 2;
237 final int top = (textureHeight-height) / 2;
238
Michael Jurka3a9fced2012-04-13 14:44:29 -0700239 @SuppressWarnings("all") // suppress dead code warning
240 final boolean debug = false;
241 if (debug) {
Joe Onorato6665c0f2009-09-02 15:27:24 -0700242 // draw a big box for the icon for debugging
243 canvas.drawColor(sColors[sColorIndex]);
244 if (++sColorIndex >= sColors.length) sColorIndex = 0;
245 Paint debugPaint = new Paint();
246 debugPaint.setColor(0xffcccc00);
247 canvas.drawRect(left, top, left+width, top+height, debugPaint);
248 }
249
250 sOldBounds.set(icon.getBounds());
251 icon.setBounds(left, top, left+width, top+height);
252 icon.draw(canvas);
253 icon.setBounds(sOldBounds);
Adam Cohenaaf473c2011-08-03 12:02:47 -0700254 canvas.setBitmap(null);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700255
256 return bitmap;
257 }
258 }
259
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800260 /**
Winson Chungc763c4e2013-07-19 13:49:06 -0700261 * Given a coordinate relative to the descendant, find the coordinate in a parent view's
262 * coordinates.
263 *
264 * @param descendant The descendant to which the passed coordinate is relative.
265 * @param root The root view to make the coordinates relative to.
266 * @param coord The coordinate that we want mapped.
267 * @param includeRootScroll Whether or not to account for the scroll of the descendant:
268 * sometimes this is relevant as in a child's coordinates within the descendant.
269 * @return The factor by which this descendant is scaled relative to this DragLayer. Caution
270 * this scale factor is assumed to be equal in X and Y, and so if at any point this
271 * assumption fails, we will need to return a pair of scale factors.
272 */
273 public static float getDescendantCoordRelativeToParent(View descendant, View root,
274 int[] coord, boolean includeRootScroll) {
275 ArrayList<View> ancestorChain = new ArrayList<View>();
276
277 float[] pt = {coord[0], coord[1]};
278
279 View v = descendant;
280 while(v != root && v != null) {
281 ancestorChain.add(v);
282 v = (View) v.getParent();
283 }
284 ancestorChain.add(root);
285
286 float scale = 1.0f;
287 int count = ancestorChain.size();
288 for (int i = 0; i < count; i++) {
289 View v0 = ancestorChain.get(i);
Winson Chungc763c4e2013-07-19 13:49:06 -0700290 // For TextViews, scroll has a meaning which relates to the text position
291 // which is very strange... ignore the scroll.
292 if (v0 != descendant || includeRootScroll) {
293 pt[0] -= v0.getScrollX();
294 pt[1] -= v0.getScrollY();
295 }
296
297 v0.getMatrix().mapPoints(pt);
298 pt[0] += v0.getLeft();
299 pt[1] += v0.getTop();
300 scale *= v0.getScaleX();
301 }
302
303 coord[0] = (int) Math.round(pt[0]);
304 coord[1] = (int) Math.round(pt[1]);
305 return scale;
306 }
307
308 /**
309 * Inverse of {@link #getDescendantCoordRelativeToSelf(View, int[])}.
310 */
311 public static float mapCoordInSelfToDescendent(View descendant, View root,
312 int[] coord) {
313 ArrayList<View> ancestorChain = new ArrayList<View>();
314
315 float[] pt = {coord[0], coord[1]};
316
317 View v = descendant;
318 while(v != root) {
319 ancestorChain.add(v);
320 v = (View) v.getParent();
321 }
322 ancestorChain.add(root);
323
324 float scale = 1.0f;
325 Matrix inverse = new Matrix();
326 int count = ancestorChain.size();
327 for (int i = count - 1; i >= 0; i--) {
328 View ancestor = ancestorChain.get(i);
329 View next = i > 0 ? ancestorChain.get(i-1) : null;
330
331 pt[0] += ancestor.getScrollX();
332 pt[1] += ancestor.getScrollY();
333
334 if (next != null) {
335 pt[0] -= next.getLeft();
336 pt[1] -= next.getTop();
337 next.getMatrix().invert(inverse);
338 inverse.mapPoints(pt);
339 scale *= next.getScaleX();
340 }
341 }
342
343 coord[0] = (int) Math.round(pt[0]);
344 coord[1] = (int) Math.round(pt[1]);
345 return scale;
346 }
347
Jason Monk02dd7ae2014-04-15 15:23:31 -0400348 /**
349 * Utility method to determine whether the given point, in local coordinates,
350 * is inside the view, where the area of the view is expanded by the slop factor.
351 * This method is called while processing touch-move events to determine if the event
352 * is still within the view.
353 */
354 public static boolean pointInView(View v, float localX, float localY, float slop) {
355 return localX >= -slop && localY >= -slop && localX < (v.getWidth() + slop) &&
356 localY < (v.getHeight() + slop);
357 }
358
Winson Chung3a6e7f32013-10-09 15:50:52 -0700359 public static void scaleRect(Rect r, float scale) {
360 if (scale != 1.0f) {
361 r.left = (int) (r.left * scale + 0.5f);
362 r.top = (int) (r.top * scale + 0.5f);
363 r.right = (int) (r.right * scale + 0.5f);
364 r.bottom = (int) (r.bottom * scale + 0.5f);
365 }
366 }
367
Adam Cohen63f1ec02014-08-12 09:23:13 -0700368 public static int[] getCenterDeltaInScreenSpace(View v0, View v1, int[] delta) {
369 v0.getLocationInWindow(sLoc0);
370 v1.getLocationInWindow(sLoc1);
371
372 sLoc0[0] += (v0.getMeasuredWidth() * v0.getScaleX()) / 2;
373 sLoc0[1] += (v0.getMeasuredHeight() * v0.getScaleY()) / 2;
374 sLoc1[0] += (v1.getMeasuredWidth() * v1.getScaleX()) / 2;
375 sLoc1[1] += (v1.getMeasuredHeight() * v1.getScaleY()) / 2;
376
377 if (delta == null) {
378 delta = new int[2];
379 }
380
381 delta[0] = sLoc1[0] - sLoc0[0];
382 delta[1] = sLoc1[1] - sLoc0[1];
383
384 return delta;
385 }
386
Winson Chung3a6e7f32013-10-09 15:50:52 -0700387 public static void scaleRectAboutCenter(Rect r, float scale) {
388 int cx = r.centerX();
389 int cy = r.centerY();
390 r.offset(-cx, -cy);
391 Utilities.scaleRect(r, scale);
392 r.offset(cx, cy);
393 }
394
Michael Jurkaa805e1a2013-08-22 15:00:33 +0200395 public static void startActivityForResultSafely(
396 Activity activity, Intent intent, int requestCode) {
397 try {
398 activity.startActivityForResult(intent, requestCode);
399 } catch (ActivityNotFoundException e) {
400 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
401 } catch (SecurityException e) {
402 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
403 Log.e(TAG, "Launcher does not have the permission to launch " + intent +
404 ". Make sure to create a MAIN intent-filter for the corresponding activity " +
405 "or use the exported attribute for this activity.", e);
406 }
407 }
Sunny Goyalc5c60ad2014-07-14 12:02:01 -0700408
409 static boolean isSystemApp(Context context, Intent intent) {
410 PackageManager pm = context.getPackageManager();
411 ComponentName cn = intent.getComponent();
412 String packageName = null;
413 if (cn == null) {
414 ResolveInfo info = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
415 if ((info != null) && (info.activityInfo != null)) {
416 packageName = info.activityInfo.packageName;
417 }
418 } else {
419 packageName = cn.getPackageName();
420 }
421 if (packageName != null) {
422 try {
423 PackageInfo info = pm.getPackageInfo(packageName, 0);
424 return (info != null) && (info.applicationInfo != null) &&
425 ((info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
426 } catch (NameNotFoundException e) {
427 return false;
428 }
429 } else {
430 return false;
431 }
432 }
Sunny Goyal95abbb32014-08-04 10:53:22 -0700433
434 /**
435 * This picks a dominant color, looking for high-saturation, high-value, repeated hues.
436 * @param bitmap The bitmap to scan
437 * @param samples The approximate max number of samples to use.
438 */
439 static int findDominantColorByHue(Bitmap bitmap, int samples) {
440 final int height = bitmap.getHeight();
441 final int width = bitmap.getWidth();
442 int sampleStride = (int) Math.sqrt((height * width) / samples);
443 if (sampleStride < 1) {
444 sampleStride = 1;
445 }
446
447 // This is an out-param, for getting the hsv values for an rgb
448 float[] hsv = new float[3];
449
450 // First get the best hue, by creating a histogram over 360 hue buckets,
451 // where each pixel contributes a score weighted by saturation, value, and alpha.
452 float[] hueScoreHistogram = new float[360];
453 float highScore = -1;
454 int bestHue = -1;
455
456 for (int y = 0; y < height; y += sampleStride) {
457 for (int x = 0; x < width; x += sampleStride) {
458 int argb = bitmap.getPixel(x, y);
459 int alpha = 0xFF & (argb >> 24);
460 if (alpha < 0x80) {
461 // Drop mostly-transparent pixels.
462 continue;
463 }
464 // Remove the alpha channel.
465 int rgb = argb | 0xFF000000;
466 Color.colorToHSV(rgb, hsv);
467 // Bucket colors by the 360 integer hues.
468 int hue = (int) hsv[0];
469 if (hue < 0 || hue >= hueScoreHistogram.length) {
470 // Defensively avoid array bounds violations.
471 continue;
472 }
473 float score = hsv[1] * hsv[2];
474 hueScoreHistogram[hue] += score;
475 if (hueScoreHistogram[hue] > highScore) {
476 highScore = hueScoreHistogram[hue];
477 bestHue = hue;
478 }
479 }
480 }
481
482 SparseArray<Float> rgbScores = new SparseArray<Float>();
483 int bestColor = 0xff000000;
484 highScore = -1;
485 // Go back over the RGB colors that match the winning hue,
486 // creating a histogram of weighted s*v scores, for up to 100*100 [s,v] buckets.
487 // The highest-scoring RGB color wins.
488 for (int y = 0; y < height; y += sampleStride) {
489 for (int x = 0; x < width; x += sampleStride) {
490 int rgb = bitmap.getPixel(x, y) | 0xff000000;
491 Color.colorToHSV(rgb, hsv);
492 int hue = (int) hsv[0];
493 if (hue == bestHue) {
494 float s = hsv[1];
495 float v = hsv[2];
496 int bucket = (int) (s * 100) + (int) (v * 10000);
497 // Score by cumulative saturation * value.
498 float score = s * v;
499 Float oldTotal = rgbScores.get(bucket);
500 float newTotal = oldTotal == null ? score : oldTotal + score;
501 rgbScores.put(bucket, newTotal);
502 if (newTotal > highScore) {
503 highScore = newTotal;
504 // All the colors in the winning bucket are very similar. Last in wins.
505 bestColor = rgb;
506 }
507 }
508 }
509 }
510 return bestColor;
511 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700512
513 /*
514 * Finds a system apk which had a broadcast receiver listening to a particular action.
515 * @param action intent action used to find the apk
516 * @return a pair of apk package name and the resources.
517 */
518 static Pair<String, Resources> findSystemApk(String action, PackageManager pm) {
519 final Intent intent = new Intent(action);
520 for (ResolveInfo info : pm.queryBroadcastReceivers(intent, 0)) {
521 if (info.activityInfo != null &&
522 (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
523 final String packageName = info.activityInfo.packageName;
524 try {
525 final Resources res = pm.getResourcesForApplication(packageName);
526 return Pair.create(packageName, res);
527 } catch (NameNotFoundException e) {
528 Log.w(TAG, "Failed to find resources for " + packageName);
529 }
530 }
531 }
532 return null;
533 }
Sunny Goyalfafca522014-11-03 11:30:01 -0800534
535 @TargetApi(Build.VERSION_CODES.KITKAT)
536 public static boolean isViewAttachedToWindow(View v) {
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700537 if (ATLEAST_KITKAT) {
Sunny Goyalfafca522014-11-03 11:30:01 -0800538 return v.isAttachedToWindow();
539 } else {
540 // A proxy call which returns null, if the view is not attached to the window.
541 return v.getKeyDispatcherState() != null;
542 }
543 }
Sunny Goyal594d76d2014-11-06 10:12:54 -0800544
545 /**
546 * Returns a widget with category {@link AppWidgetProviderInfo#WIDGET_CATEGORY_SEARCHBOX}
547 * provided by the same package which is set to be global search activity.
548 * If widgetCategory is not supported, or no such widget is found, returns the first widget
549 * provided by the package.
550 */
551 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
552 public static AppWidgetProviderInfo getSearchWidgetProvider(Context context) {
553 SearchManager searchManager =
554 (SearchManager) context.getSystemService(Context.SEARCH_SERVICE);
555 ComponentName searchComponent = searchManager.getGlobalSearchActivity();
556 if (searchComponent == null) return null;
557 String providerPkg = searchComponent.getPackageName();
558
559 AppWidgetProviderInfo defaultWidgetForSearchPackage = null;
560
561 AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
562 for (AppWidgetProviderInfo info : appWidgetManager.getInstalledProviders()) {
563 if (info.provider.getPackageName().equals(providerPkg)) {
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700564 if (ATLEAST_JB_MR1) {
Sunny Goyal594d76d2014-11-06 10:12:54 -0800565 if ((info.widgetCategory & AppWidgetProviderInfo.WIDGET_CATEGORY_SEARCHBOX) != 0) {
566 return info;
567 } else if (defaultWidgetForSearchPackage == null) {
568 defaultWidgetForSearchPackage = info;
569 }
570 } else {
571 return info;
572 }
573 }
574 }
575 return defaultWidgetForSearchPackage;
576 }
Sunny Goyal08f72612015-01-05 13:41:43 -0800577
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700578 /**
579 * Compresses the bitmap to a byte array for serialization.
580 */
581 public static byte[] flattenBitmap(Bitmap bitmap) {
582 // Try go guesstimate how much space the icon will take when serialized
583 // to avoid unnecessary allocations/copies during the write.
584 int size = bitmap.getWidth() * bitmap.getHeight() * 4;
585 ByteArrayOutputStream out = new ByteArrayOutputStream(size);
586 try {
587 bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
588 out.flush();
589 out.close();
590 return out.toByteArray();
591 } catch (IOException e) {
592 Log.w(TAG, "Could not write bitmap");
593 return null;
594 }
595 }
596
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700597 /**
598 * Find the first vacant cell, if there is one.
599 *
600 * @param vacant Holds the x and y coordinate of the vacant cell
601 * @param spanX Horizontal cell span.
602 * @param spanY Vertical cell span.
603 *
604 * @return true if a vacant cell was found
605 */
606 public static boolean findVacantCell(int[] vacant, int spanX, int spanY,
607 int xCount, int yCount, boolean[][] occupied) {
608
609 for (int y = 0; (y + spanY) <= yCount; y++) {
610 for (int x = 0; (x + spanX) <= xCount; x++) {
611 boolean available = !occupied[x][y];
612 out: for (int i = x; i < x + spanX; i++) {
613 for (int j = y; j < y + spanY; j++) {
614 available = available && !occupied[i][j];
615 if (!available) break out;
616 }
617 }
618
619 if (available) {
620 vacant[0] = x;
621 vacant[1] = y;
622 return true;
623 }
624 }
625 }
626
627 return false;
628 }
Winson Chung82b016c2015-05-08 17:00:10 -0700629
630 /**
631 * Trims the string, removing all whitespace at the beginning and end of the string.
632 * Non-breaking whitespaces are also removed.
633 */
634 public static String trim(CharSequence s) {
Winson Chungafa77e92015-05-15 12:04:03 -0700635 if (s == null) {
636 return null;
637 }
638
Winson Chung82b016c2015-05-08 17:00:10 -0700639 // Just strip any sequence of whitespace or java space characters from the beginning and end
640 Matcher m = sTrimPattern.matcher(s);
641 return m.replaceAll("$1");
642 }
Sunny Goyal70660032015-05-14 00:07:08 -0700643
Winson Chung2c6e5cc2015-06-01 14:38:24 -0700644 /**
645 * Calculates the height of a given string at a specific text size.
646 */
647 public static float calculateTextHeight(float textSizePx) {
648 Paint p = new Paint();
649 p.setTextSize(textSizePx);
650 Paint.FontMetrics fm = p.getFontMetrics();
651 return -fm.top + fm.bottom;
652 }
653
Winson Chungb1777442015-06-16 13:35:04 -0700654 /**
655 * Convenience println with multiple args.
656 */
657 public static void println(String key, Object... args) {
658 StringBuilder b = new StringBuilder();
659 b.append(key);
660 b.append(": ");
661 boolean isFirstArgument = true;
662 for (Object arg : args) {
663 if (isFirstArgument) {
664 isFirstArgument = false;
665 } else {
666 b.append(", ");
667 }
668 b.append(arg);
669 }
670 System.out.println(b.toString());
671 }
672
Sunny Goyal70660032015-05-14 00:07:08 -0700673 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
674 public static boolean isRtl(Resources res) {
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700675 return ATLEAST_JB_MR1 &&
Sunny Goyal70660032015-05-14 00:07:08 -0700676 (res.getConfiguration().getLayoutDirection() == View.LAYOUT_DIRECTION_RTL);
677 }
Hyunyoung Song2bd3d7d2015-05-21 13:04:53 -0700678
679 public static void assertWorkerThread() {
Sunny Goyal11d49112015-06-26 14:00:57 -0700680 if (LauncherAppState.isDogfoodBuild() &&
681 (LauncherModel.sWorkerThread.getThreadId() != Process.myTid())) {
682 throw new IllegalStateException();
Hyunyoung Song2bd3d7d2015-05-21 13:04:53 -0700683 }
684 }
Sunny Goyal5c97f512015-05-19 16:03:28 -0700685
686 /**
687 * Returns true if the intent is a valid launch intent for a launcher activity of an app.
688 * This is used to identify shortcuts which are different from the ones exposed by the
689 * applications' manifest file.
690 *
691 * @param launchIntent The intent that will be launched when the shortcut is clicked.
692 */
693 public static boolean isLauncherAppTarget(Intent launchIntent) {
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700694 if (launchIntent != null
Sunny Goyal5c97f512015-05-19 16:03:28 -0700695 && Intent.ACTION_MAIN.equals(launchIntent.getAction())
696 && launchIntent.getComponent() != null
697 && launchIntent.getCategories() != null
698 && launchIntent.getCategories().size() == 1
699 && launchIntent.hasCategory(Intent.CATEGORY_LAUNCHER)
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700700 && TextUtils.isEmpty(launchIntent.getDataString())) {
701 // An app target can either have no extra or have ItemInfo.EXTRA_PROFILE.
702 Bundle extras = launchIntent.getExtras();
703 if (extras == null) {
704 return true;
705 } else {
706 Set<String> keys = extras.keySet();
707 return keys.size() == 1 && keys.contains(ItemInfo.EXTRA_PROFILE);
708 }
709 };
710 return false;
Sunny Goyal5c97f512015-05-19 16:03:28 -0700711 }
Adam Cohen2e6da152015-05-06 11:42:25 -0700712
713 public static float dpiFromPx(int size, DisplayMetrics metrics){
714 float densityRatio = (float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT;
715 return (size / densityRatio);
716 }
717 public static int pxFromDp(float size, DisplayMetrics metrics) {
718 return (int) Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
719 size, metrics));
720 }
721 public static int pxFromSp(float size, DisplayMetrics metrics) {
722 return (int) Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
723 size, metrics));
724 }
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700725
726 public static String createDbSelectionQuery(String columnName, Iterable<?> values) {
727 return String.format(Locale.ENGLISH, "%s IN (%s)", columnName, TextUtils.join(", ", values));
728 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800729}