blob: 2ed9a25ada7fa5c34d0d683a4e1eb38d5e877f33 [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 Goyale78e3d72015-09-24 11:23:31 -070050import android.text.Spannable;
51import android.text.SpannableString;
Sunny Goyal5c97f512015-05-19 16:03:28 -070052import android.text.TextUtils;
Sunny Goyale78e3d72015-09-24 11:23:31 -070053import android.text.style.TtsSpan;
Adam Cohen2e6da152015-05-06 11:42:25 -070054import android.util.DisplayMetrics;
Michael Jurkaa805e1a2013-08-22 15:00:33 +020055import android.util.Log;
Sunny Goyal0fe505b2014-08-06 09:55:36 -070056import android.util.Pair;
Sunny Goyal95abbb32014-08-04 10:53:22 -070057import android.util.SparseArray;
Adam Cohen2e6da152015-05-06 11:42:25 -070058import android.util.TypedValue;
Winson Chungc763c4e2013-07-19 13:49:06 -070059import android.view.View;
Michael Jurkaa805e1a2013-08-22 15:00:33 +020060import android.widget.Toast;
Sunny Goyalb1622cc2015-06-10 16:00:42 -070061
Sunny Goyal5b0e6692015-03-19 14:31:19 -070062import java.io.ByteArrayOutputStream;
63import java.io.IOException;
Winson Chungc763c4e2013-07-19 13:49:06 -070064import java.util.ArrayList;
Sunny Goyalb1622cc2015-06-10 16:00:42 -070065import java.util.Locale;
Sunny Goyal4e5cc642015-06-25 16:37:44 -070066import java.util.Set;
Sunny Goyal8ac727b2015-09-23 15:38:09 -070067import java.util.concurrent.Executor;
68import java.util.concurrent.LinkedBlockingQueue;
69import java.util.concurrent.ThreadPoolExecutor;
70import java.util.concurrent.TimeUnit;
Winson Chung82b016c2015-05-08 17:00:10 -070071import java.util.regex.Matcher;
72import java.util.regex.Pattern;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080073
74/**
75 * Various utilities shared amongst the Launcher's classes.
76 */
Mathew Inwood72fbec12013-11-19 15:45:07 +000077public final class Utilities {
Rahul Chaturvedi7fc77ca2015-05-19 18:02:16 -070078
Joe Onorato1291a8c2009-09-15 15:07:25 -040079 private static final String TAG = "Launcher.Utilities";
80
The Android Open Source Project31dd5032009-03-03 19:32:27 -080081 private static final Rect sOldBounds = new Rect();
Romain Guy89911d22009-09-28 18:48:49 -070082 private static final Canvas sCanvas = new Canvas();
The Android Open Source Project31dd5032009-03-03 19:32:27 -080083
Winson Chung82b016c2015-05-08 17:00:10 -070084 private static final Pattern sTrimPattern =
85 Pattern.compile("^[\\s|\\p{javaSpaceChar}]*(.*)[\\s|\\p{javaSpaceChar}]*$");
86
The Android Open Source Project31dd5032009-03-03 19:32:27 -080087 static {
88 sCanvas.setDrawFilter(new PaintFlagsDrawFilter(Paint.DITHER_FLAG,
89 Paint.FILTER_BITMAP_FLAG));
90 }
Joe Onorato6665c0f2009-09-02 15:27:24 -070091 static int sColors[] = { 0xffff0000, 0xff00ff00, 0xff0000ff };
92 static int sColorIndex = 0;
93
Sunny Goyal53d7ee42015-05-22 12:25:45 -070094 private static final int[] sLoc0 = new int[2];
95 private static final int[] sLoc1 = new int[2];
Michael Jurka7ad868b2013-12-12 15:04:25 +010096
Sunny Goyal9fc953b2015-08-17 12:24:25 -070097 // TODO: use Build.VERSION_CODES when available
98 public static final boolean ATLEAST_MARSHMALLOW = Build.VERSION.SDK_INT >= 23;
99
100 public static final boolean ATLEAST_LOLLIPOP_MR1 =
101 Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1;
102
103 public static final boolean ATLEAST_LOLLIPOP =
104 Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
105
106 public static final boolean ATLEAST_KITKAT =
107 Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
108
109 public static final boolean ATLEAST_JB_MR1 =
110 Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1;
111
112 public static final boolean ATLEAST_JB_MR2 =
113 Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2;
114
Sunny Goyal8ac727b2015-09-23 15:38:09 -0700115 // These values are same as that in {@link AsyncTask}.
116 private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
117 private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
118 private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
119 private static final int KEEP_ALIVE = 1;
120 /**
121 * An {@link Executor} to be used with async task with no limit on the queue size.
122 */
123 public static final Executor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(
124 CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
125 TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
126
Michael Jurka7ad868b2013-12-12 15:04:25 +0100127 // To turn on these properties, type
128 // adb shell setprop log.tag.PROPERTY_NAME [VERBOSE | SUPPRESS]
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700129 private static final String FORCE_ENABLE_ROTATION_PROPERTY = "launcher_force_rotate";
130 private static boolean sForceEnableRotation = isPropertyEnabled(FORCE_ENABLE_ROTATION_PROPERTY);
Michael Jurka7ad868b2013-12-12 15:04:25 +0100131
Rahul Chaturvedi7fc77ca2015-05-19 18:02:16 -0700132 public static final String ALLOW_ROTATION_PREFERENCE_KEY = "pref_allowRotation";
133
Sunny Goyal4bbf4192014-11-11 12:23:59 -0800134 public static boolean isPropertyEnabled(String propertyName) {
Michael Jurka7ad868b2013-12-12 15:04:25 +0100135 return Log.isLoggable(propertyName, Log.VERBOSE);
136 }
137
Rahul Chaturvedie863fed2015-06-15 14:09:42 -0400138 public static boolean isAllowRotationPrefEnabled(Context context, boolean multiProcess) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700139 SharedPreferences sharedPrefs = context.getSharedPreferences(
Rahul Chaturvedie863fed2015-06-15 14:09:42 -0400140 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE | (multiProcess ?
141 Context.MODE_MULTI_PROCESS : 0));
Rahul Chaturvedi7fc77ca2015-05-19 18:02:16 -0700142 boolean allowRotationPref = sharedPrefs.getBoolean(ALLOW_ROTATION_PREFERENCE_KEY, false);
143 return sForceEnableRotation || allowRotationPref;
144 }
145
146 public static boolean isRotationAllowedForDevice(Context context) {
147 return sForceEnableRotation || context.getResources().getBoolean(R.bool.allow_rotation);
Michael Jurka7ad868b2013-12-12 15:04:25 +0100148 }
149
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700150 public static Bitmap createIconBitmap(Cursor c, int iconIndex, Context context) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -0800151 byte[] data = c.getBlob(iconIndex);
152 try {
153 return createIconBitmap(BitmapFactory.decodeByteArray(data, 0, data.length), context);
154 } catch (Exception e) {
155 return null;
156 }
157 }
158
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -0700159 /**
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700160 * Returns a bitmap suitable for the all apps view. If the package or the resource do not
161 * exist, it returns null.
162 */
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700163 public static Bitmap createIconBitmap(String packageName, String resourceName,
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700164 Context context) {
165 PackageManager packageManager = context.getPackageManager();
166 // the resource
167 try {
168 Resources resources = packageManager.getResourcesForApplication(packageName);
169 if (resources != null) {
170 final int id = resources.getIdentifier(resourceName, null, null);
171 return createIconBitmap(
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700172 resources.getDrawableForDensity(id, LauncherAppState.getInstance()
173 .getInvariantDeviceProfile().fillResIconDpi), context);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700174 }
175 } catch (Exception e) {
176 // Icon not found.
177 }
178 return null;
179 }
180
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700181 private static int getIconBitmapSize() {
182 return LauncherAppState.getInstance().getInvariantDeviceProfile().iconBitmapSize;
183 }
184
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700185 /**
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700186 * Returns a bitmap which is of the appropriate size to be displayed as an icon
Michael Jurka931dc972011-08-05 15:08:15 -0700187 */
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700188 public static Bitmap createIconBitmap(Bitmap icon, Context context) {
189 final int iconBitmapSize = getIconBitmapSize();
190 if (iconBitmapSize == icon.getWidth() && iconBitmapSize == icon.getHeight()) {
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700191 return icon;
192 }
193 return createIconBitmap(new BitmapDrawable(context.getResources(), icon), context);
Michael Jurka931dc972011-08-05 15:08:15 -0700194 }
195
196 /**
197 * Returns a bitmap suitable for the all apps view.
Joe Onorato6665c0f2009-09-02 15:27:24 -0700198 */
Mathew Inwood72fbec12013-11-19 15:45:07 +0000199 public static Bitmap createIconBitmap(Drawable icon, Context context) {
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700200 synchronized (sCanvas) {
201 final int iconBitmapSize = getIconBitmapSize();
Joe Onorato6665c0f2009-09-02 15:27:24 -0700202
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700203 int width = iconBitmapSize;
204 int height = iconBitmapSize;
Joe Onorato6665c0f2009-09-02 15:27:24 -0700205
Joe Onorato6665c0f2009-09-02 15:27:24 -0700206 if (icon instanceof PaintDrawable) {
207 PaintDrawable painter = (PaintDrawable) icon;
208 painter.setIntrinsicWidth(width);
209 painter.setIntrinsicHeight(height);
210 } else if (icon instanceof BitmapDrawable) {
211 // Ensure the bitmap has a density.
212 BitmapDrawable bitmapDrawable = (BitmapDrawable) icon;
213 Bitmap bitmap = bitmapDrawable.getBitmap();
Sunny Goyalde9590b2015-09-23 12:56:51 -0700214 if (bitmap != null && bitmap.getDensity() == Bitmap.DENSITY_NONE) {
Joe Onorato6665c0f2009-09-02 15:27:24 -0700215 bitmapDrawable.setTargetDensity(context.getResources().getDisplayMetrics());
216 }
217 }
218 int sourceWidth = icon.getIntrinsicWidth();
219 int sourceHeight = icon.getIntrinsicHeight();
Michael Jurka931dc972011-08-05 15:08:15 -0700220 if (sourceWidth > 0 && sourceHeight > 0) {
Winson Chung5f8afe62013-08-12 16:19:28 -0700221 // Scale the icon proportionally to the icon dimensions
222 final float ratio = (float) sourceWidth / sourceHeight;
223 if (sourceWidth > sourceHeight) {
224 height = (int) (width / ratio);
225 } else if (sourceHeight > sourceWidth) {
226 width = (int) (height * ratio);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700227 }
228 }
229
230 // no intrinsic size --> use default size
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700231 int textureWidth = iconBitmapSize;
232 int textureHeight = iconBitmapSize;
Joe Onorato6665c0f2009-09-02 15:27:24 -0700233
234 final Bitmap bitmap = Bitmap.createBitmap(textureWidth, textureHeight,
235 Bitmap.Config.ARGB_8888);
236 final Canvas canvas = sCanvas;
237 canvas.setBitmap(bitmap);
238
239 final int left = (textureWidth-width) / 2;
240 final int top = (textureHeight-height) / 2;
241
Michael Jurka3a9fced2012-04-13 14:44:29 -0700242 @SuppressWarnings("all") // suppress dead code warning
243 final boolean debug = false;
244 if (debug) {
Joe Onorato6665c0f2009-09-02 15:27:24 -0700245 // draw a big box for the icon for debugging
246 canvas.drawColor(sColors[sColorIndex]);
247 if (++sColorIndex >= sColors.length) sColorIndex = 0;
248 Paint debugPaint = new Paint();
249 debugPaint.setColor(0xffcccc00);
250 canvas.drawRect(left, top, left+width, top+height, debugPaint);
251 }
252
253 sOldBounds.set(icon.getBounds());
254 icon.setBounds(left, top, left+width, top+height);
255 icon.draw(canvas);
256 icon.setBounds(sOldBounds);
Adam Cohenaaf473c2011-08-03 12:02:47 -0700257 canvas.setBitmap(null);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700258
259 return bitmap;
260 }
261 }
262
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800263 /**
Winson Chungc763c4e2013-07-19 13:49:06 -0700264 * Given a coordinate relative to the descendant, find the coordinate in a parent view's
265 * coordinates.
266 *
267 * @param descendant The descendant to which the passed coordinate is relative.
268 * @param root The root view to make the coordinates relative to.
269 * @param coord The coordinate that we want mapped.
270 * @param includeRootScroll Whether or not to account for the scroll of the descendant:
271 * sometimes this is relevant as in a child's coordinates within the descendant.
272 * @return The factor by which this descendant is scaled relative to this DragLayer. Caution
273 * this scale factor is assumed to be equal in X and Y, and so if at any point this
274 * assumption fails, we will need to return a pair of scale factors.
275 */
276 public static float getDescendantCoordRelativeToParent(View descendant, View root,
277 int[] coord, boolean includeRootScroll) {
278 ArrayList<View> ancestorChain = new ArrayList<View>();
279
280 float[] pt = {coord[0], coord[1]};
281
282 View v = descendant;
283 while(v != root && v != null) {
284 ancestorChain.add(v);
285 v = (View) v.getParent();
286 }
287 ancestorChain.add(root);
288
289 float scale = 1.0f;
290 int count = ancestorChain.size();
291 for (int i = 0; i < count; i++) {
292 View v0 = ancestorChain.get(i);
Winson Chungc763c4e2013-07-19 13:49:06 -0700293 // For TextViews, scroll has a meaning which relates to the text position
294 // which is very strange... ignore the scroll.
295 if (v0 != descendant || includeRootScroll) {
296 pt[0] -= v0.getScrollX();
297 pt[1] -= v0.getScrollY();
298 }
299
300 v0.getMatrix().mapPoints(pt);
301 pt[0] += v0.getLeft();
302 pt[1] += v0.getTop();
303 scale *= v0.getScaleX();
304 }
305
306 coord[0] = (int) Math.round(pt[0]);
307 coord[1] = (int) Math.round(pt[1]);
308 return scale;
309 }
310
311 /**
312 * Inverse of {@link #getDescendantCoordRelativeToSelf(View, int[])}.
313 */
314 public static float mapCoordInSelfToDescendent(View descendant, View root,
315 int[] coord) {
316 ArrayList<View> ancestorChain = new ArrayList<View>();
317
318 float[] pt = {coord[0], coord[1]};
319
320 View v = descendant;
321 while(v != root) {
322 ancestorChain.add(v);
323 v = (View) v.getParent();
324 }
325 ancestorChain.add(root);
326
327 float scale = 1.0f;
328 Matrix inverse = new Matrix();
329 int count = ancestorChain.size();
330 for (int i = count - 1; i >= 0; i--) {
331 View ancestor = ancestorChain.get(i);
332 View next = i > 0 ? ancestorChain.get(i-1) : null;
333
334 pt[0] += ancestor.getScrollX();
335 pt[1] += ancestor.getScrollY();
336
337 if (next != null) {
338 pt[0] -= next.getLeft();
339 pt[1] -= next.getTop();
340 next.getMatrix().invert(inverse);
341 inverse.mapPoints(pt);
342 scale *= next.getScaleX();
343 }
344 }
345
346 coord[0] = (int) Math.round(pt[0]);
347 coord[1] = (int) Math.round(pt[1]);
348 return scale;
349 }
350
Jason Monk02dd7ae2014-04-15 15:23:31 -0400351 /**
352 * Utility method to determine whether the given point, in local coordinates,
353 * is inside the view, where the area of the view is expanded by the slop factor.
354 * This method is called while processing touch-move events to determine if the event
355 * is still within the view.
356 */
357 public static boolean pointInView(View v, float localX, float localY, float slop) {
358 return localX >= -slop && localY >= -slop && localX < (v.getWidth() + slop) &&
359 localY < (v.getHeight() + slop);
360 }
361
Winson Chung3a6e7f32013-10-09 15:50:52 -0700362 public static void scaleRect(Rect r, float scale) {
363 if (scale != 1.0f) {
364 r.left = (int) (r.left * scale + 0.5f);
365 r.top = (int) (r.top * scale + 0.5f);
366 r.right = (int) (r.right * scale + 0.5f);
367 r.bottom = (int) (r.bottom * scale + 0.5f);
368 }
369 }
370
Adam Cohen63f1ec02014-08-12 09:23:13 -0700371 public static int[] getCenterDeltaInScreenSpace(View v0, View v1, int[] delta) {
372 v0.getLocationInWindow(sLoc0);
373 v1.getLocationInWindow(sLoc1);
374
375 sLoc0[0] += (v0.getMeasuredWidth() * v0.getScaleX()) / 2;
376 sLoc0[1] += (v0.getMeasuredHeight() * v0.getScaleY()) / 2;
377 sLoc1[0] += (v1.getMeasuredWidth() * v1.getScaleX()) / 2;
378 sLoc1[1] += (v1.getMeasuredHeight() * v1.getScaleY()) / 2;
379
380 if (delta == null) {
381 delta = new int[2];
382 }
383
384 delta[0] = sLoc1[0] - sLoc0[0];
385 delta[1] = sLoc1[1] - sLoc0[1];
386
387 return delta;
388 }
389
Winson Chung3a6e7f32013-10-09 15:50:52 -0700390 public static void scaleRectAboutCenter(Rect r, float scale) {
391 int cx = r.centerX();
392 int cy = r.centerY();
393 r.offset(-cx, -cy);
394 Utilities.scaleRect(r, scale);
395 r.offset(cx, cy);
396 }
397
Michael Jurkaa805e1a2013-08-22 15:00:33 +0200398 public static void startActivityForResultSafely(
399 Activity activity, Intent intent, int requestCode) {
400 try {
401 activity.startActivityForResult(intent, requestCode);
402 } catch (ActivityNotFoundException e) {
403 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
404 } catch (SecurityException e) {
405 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
406 Log.e(TAG, "Launcher does not have the permission to launch " + intent +
407 ". Make sure to create a MAIN intent-filter for the corresponding activity " +
408 "or use the exported attribute for this activity.", e);
409 }
410 }
Sunny Goyalc5c60ad2014-07-14 12:02:01 -0700411
412 static boolean isSystemApp(Context context, Intent intent) {
413 PackageManager pm = context.getPackageManager();
414 ComponentName cn = intent.getComponent();
415 String packageName = null;
416 if (cn == null) {
417 ResolveInfo info = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
418 if ((info != null) && (info.activityInfo != null)) {
419 packageName = info.activityInfo.packageName;
420 }
421 } else {
422 packageName = cn.getPackageName();
423 }
424 if (packageName != null) {
425 try {
426 PackageInfo info = pm.getPackageInfo(packageName, 0);
427 return (info != null) && (info.applicationInfo != null) &&
428 ((info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
429 } catch (NameNotFoundException e) {
430 return false;
431 }
432 } else {
433 return false;
434 }
435 }
Sunny Goyal95abbb32014-08-04 10:53:22 -0700436
437 /**
438 * This picks a dominant color, looking for high-saturation, high-value, repeated hues.
439 * @param bitmap The bitmap to scan
440 * @param samples The approximate max number of samples to use.
441 */
442 static int findDominantColorByHue(Bitmap bitmap, int samples) {
443 final int height = bitmap.getHeight();
444 final int width = bitmap.getWidth();
445 int sampleStride = (int) Math.sqrt((height * width) / samples);
446 if (sampleStride < 1) {
447 sampleStride = 1;
448 }
449
450 // This is an out-param, for getting the hsv values for an rgb
451 float[] hsv = new float[3];
452
453 // First get the best hue, by creating a histogram over 360 hue buckets,
454 // where each pixel contributes a score weighted by saturation, value, and alpha.
455 float[] hueScoreHistogram = new float[360];
456 float highScore = -1;
457 int bestHue = -1;
458
459 for (int y = 0; y < height; y += sampleStride) {
460 for (int x = 0; x < width; x += sampleStride) {
461 int argb = bitmap.getPixel(x, y);
462 int alpha = 0xFF & (argb >> 24);
463 if (alpha < 0x80) {
464 // Drop mostly-transparent pixels.
465 continue;
466 }
467 // Remove the alpha channel.
468 int rgb = argb | 0xFF000000;
469 Color.colorToHSV(rgb, hsv);
470 // Bucket colors by the 360 integer hues.
471 int hue = (int) hsv[0];
472 if (hue < 0 || hue >= hueScoreHistogram.length) {
473 // Defensively avoid array bounds violations.
474 continue;
475 }
476 float score = hsv[1] * hsv[2];
477 hueScoreHistogram[hue] += score;
478 if (hueScoreHistogram[hue] > highScore) {
479 highScore = hueScoreHistogram[hue];
480 bestHue = hue;
481 }
482 }
483 }
484
485 SparseArray<Float> rgbScores = new SparseArray<Float>();
486 int bestColor = 0xff000000;
487 highScore = -1;
488 // Go back over the RGB colors that match the winning hue,
489 // creating a histogram of weighted s*v scores, for up to 100*100 [s,v] buckets.
490 // The highest-scoring RGB color wins.
491 for (int y = 0; y < height; y += sampleStride) {
492 for (int x = 0; x < width; x += sampleStride) {
493 int rgb = bitmap.getPixel(x, y) | 0xff000000;
494 Color.colorToHSV(rgb, hsv);
495 int hue = (int) hsv[0];
496 if (hue == bestHue) {
497 float s = hsv[1];
498 float v = hsv[2];
499 int bucket = (int) (s * 100) + (int) (v * 10000);
500 // Score by cumulative saturation * value.
501 float score = s * v;
502 Float oldTotal = rgbScores.get(bucket);
503 float newTotal = oldTotal == null ? score : oldTotal + score;
504 rgbScores.put(bucket, newTotal);
505 if (newTotal > highScore) {
506 highScore = newTotal;
507 // All the colors in the winning bucket are very similar. Last in wins.
508 bestColor = rgb;
509 }
510 }
511 }
512 }
513 return bestColor;
514 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700515
516 /*
517 * Finds a system apk which had a broadcast receiver listening to a particular action.
518 * @param action intent action used to find the apk
519 * @return a pair of apk package name and the resources.
520 */
521 static Pair<String, Resources> findSystemApk(String action, PackageManager pm) {
522 final Intent intent = new Intent(action);
523 for (ResolveInfo info : pm.queryBroadcastReceivers(intent, 0)) {
524 if (info.activityInfo != null &&
525 (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
526 final String packageName = info.activityInfo.packageName;
527 try {
528 final Resources res = pm.getResourcesForApplication(packageName);
529 return Pair.create(packageName, res);
530 } catch (NameNotFoundException e) {
531 Log.w(TAG, "Failed to find resources for " + packageName);
532 }
533 }
534 }
535 return null;
536 }
Sunny Goyalfafca522014-11-03 11:30:01 -0800537
538 @TargetApi(Build.VERSION_CODES.KITKAT)
539 public static boolean isViewAttachedToWindow(View v) {
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700540 if (ATLEAST_KITKAT) {
Sunny Goyalfafca522014-11-03 11:30:01 -0800541 return v.isAttachedToWindow();
542 } else {
543 // A proxy call which returns null, if the view is not attached to the window.
544 return v.getKeyDispatcherState() != null;
545 }
546 }
Sunny Goyal594d76d2014-11-06 10:12:54 -0800547
548 /**
549 * Returns a widget with category {@link AppWidgetProviderInfo#WIDGET_CATEGORY_SEARCHBOX}
550 * provided by the same package which is set to be global search activity.
551 * If widgetCategory is not supported, or no such widget is found, returns the first widget
552 * provided by the package.
553 */
554 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
555 public static AppWidgetProviderInfo getSearchWidgetProvider(Context context) {
556 SearchManager searchManager =
557 (SearchManager) context.getSystemService(Context.SEARCH_SERVICE);
558 ComponentName searchComponent = searchManager.getGlobalSearchActivity();
559 if (searchComponent == null) return null;
560 String providerPkg = searchComponent.getPackageName();
561
562 AppWidgetProviderInfo defaultWidgetForSearchPackage = null;
563
564 AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
565 for (AppWidgetProviderInfo info : appWidgetManager.getInstalledProviders()) {
566 if (info.provider.getPackageName().equals(providerPkg)) {
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700567 if (ATLEAST_JB_MR1) {
Sunny Goyal594d76d2014-11-06 10:12:54 -0800568 if ((info.widgetCategory & AppWidgetProviderInfo.WIDGET_CATEGORY_SEARCHBOX) != 0) {
569 return info;
570 } else if (defaultWidgetForSearchPackage == null) {
571 defaultWidgetForSearchPackage = info;
572 }
573 } else {
574 return info;
575 }
576 }
577 }
578 return defaultWidgetForSearchPackage;
579 }
Sunny Goyal08f72612015-01-05 13:41:43 -0800580
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700581 /**
582 * Compresses the bitmap to a byte array for serialization.
583 */
584 public static byte[] flattenBitmap(Bitmap bitmap) {
585 // Try go guesstimate how much space the icon will take when serialized
586 // to avoid unnecessary allocations/copies during the write.
587 int size = bitmap.getWidth() * bitmap.getHeight() * 4;
588 ByteArrayOutputStream out = new ByteArrayOutputStream(size);
589 try {
590 bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
591 out.flush();
592 out.close();
593 return out.toByteArray();
594 } catch (IOException e) {
595 Log.w(TAG, "Could not write bitmap");
596 return null;
597 }
598 }
599
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700600 /**
601 * Find the first vacant cell, if there is one.
602 *
603 * @param vacant Holds the x and y coordinate of the vacant cell
604 * @param spanX Horizontal cell span.
605 * @param spanY Vertical cell span.
606 *
607 * @return true if a vacant cell was found
608 */
609 public static boolean findVacantCell(int[] vacant, int spanX, int spanY,
610 int xCount, int yCount, boolean[][] occupied) {
611
612 for (int y = 0; (y + spanY) <= yCount; y++) {
613 for (int x = 0; (x + spanX) <= xCount; x++) {
614 boolean available = !occupied[x][y];
615 out: for (int i = x; i < x + spanX; i++) {
616 for (int j = y; j < y + spanY; j++) {
617 available = available && !occupied[i][j];
618 if (!available) break out;
619 }
620 }
621
622 if (available) {
623 vacant[0] = x;
624 vacant[1] = y;
625 return true;
626 }
627 }
628 }
629
630 return false;
631 }
Winson Chung82b016c2015-05-08 17:00:10 -0700632
633 /**
634 * Trims the string, removing all whitespace at the beginning and end of the string.
635 * Non-breaking whitespaces are also removed.
636 */
637 public static String trim(CharSequence s) {
Winson Chungafa77e92015-05-15 12:04:03 -0700638 if (s == null) {
639 return null;
640 }
641
Winson Chung82b016c2015-05-08 17:00:10 -0700642 // Just strip any sequence of whitespace or java space characters from the beginning and end
643 Matcher m = sTrimPattern.matcher(s);
644 return m.replaceAll("$1");
645 }
Sunny Goyal70660032015-05-14 00:07:08 -0700646
Winson Chung2c6e5cc2015-06-01 14:38:24 -0700647 /**
648 * Calculates the height of a given string at a specific text size.
649 */
650 public static float calculateTextHeight(float textSizePx) {
651 Paint p = new Paint();
652 p.setTextSize(textSizePx);
653 Paint.FontMetrics fm = p.getFontMetrics();
654 return -fm.top + fm.bottom;
655 }
656
Winson Chungb1777442015-06-16 13:35:04 -0700657 /**
658 * Convenience println with multiple args.
659 */
660 public static void println(String key, Object... args) {
661 StringBuilder b = new StringBuilder();
662 b.append(key);
663 b.append(": ");
664 boolean isFirstArgument = true;
665 for (Object arg : args) {
666 if (isFirstArgument) {
667 isFirstArgument = false;
668 } else {
669 b.append(", ");
670 }
671 b.append(arg);
672 }
673 System.out.println(b.toString());
674 }
675
Sunny Goyal70660032015-05-14 00:07:08 -0700676 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
677 public static boolean isRtl(Resources res) {
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700678 return ATLEAST_JB_MR1 &&
Sunny Goyal70660032015-05-14 00:07:08 -0700679 (res.getConfiguration().getLayoutDirection() == View.LAYOUT_DIRECTION_RTL);
680 }
Hyunyoung Song2bd3d7d2015-05-21 13:04:53 -0700681
682 public static void assertWorkerThread() {
Sunny Goyal11d49112015-06-26 14:00:57 -0700683 if (LauncherAppState.isDogfoodBuild() &&
684 (LauncherModel.sWorkerThread.getThreadId() != Process.myTid())) {
685 throw new IllegalStateException();
Hyunyoung Song2bd3d7d2015-05-21 13:04:53 -0700686 }
687 }
Sunny Goyal5c97f512015-05-19 16:03:28 -0700688
689 /**
690 * Returns true if the intent is a valid launch intent for a launcher activity of an app.
691 * This is used to identify shortcuts which are different from the ones exposed by the
692 * applications' manifest file.
693 *
694 * @param launchIntent The intent that will be launched when the shortcut is clicked.
695 */
696 public static boolean isLauncherAppTarget(Intent launchIntent) {
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700697 if (launchIntent != null
Sunny Goyal5c97f512015-05-19 16:03:28 -0700698 && Intent.ACTION_MAIN.equals(launchIntent.getAction())
699 && launchIntent.getComponent() != null
700 && launchIntent.getCategories() != null
701 && launchIntent.getCategories().size() == 1
702 && launchIntent.hasCategory(Intent.CATEGORY_LAUNCHER)
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700703 && TextUtils.isEmpty(launchIntent.getDataString())) {
704 // An app target can either have no extra or have ItemInfo.EXTRA_PROFILE.
705 Bundle extras = launchIntent.getExtras();
706 if (extras == null) {
707 return true;
708 } else {
709 Set<String> keys = extras.keySet();
710 return keys.size() == 1 && keys.contains(ItemInfo.EXTRA_PROFILE);
711 }
712 };
713 return false;
Sunny Goyal5c97f512015-05-19 16:03:28 -0700714 }
Adam Cohen2e6da152015-05-06 11:42:25 -0700715
716 public static float dpiFromPx(int size, DisplayMetrics metrics){
717 float densityRatio = (float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT;
718 return (size / densityRatio);
719 }
720 public static int pxFromDp(float size, DisplayMetrics metrics) {
721 return (int) Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
722 size, metrics));
723 }
724 public static int pxFromSp(float size, DisplayMetrics metrics) {
725 return (int) Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
726 size, metrics));
727 }
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700728
729 public static String createDbSelectionQuery(String columnName, Iterable<?> values) {
730 return String.format(Locale.ENGLISH, "%s IN (%s)", columnName, TextUtils.join(", ", values));
731 }
Sunny Goyale78e3d72015-09-24 11:23:31 -0700732
733 /**
734 * Wraps a message with a TTS span, so that a different message is spoken than
735 * what is getting displayed.
736 * @param msg original message
737 * @param ttsMsg message to be spoken
738 */
739 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
740 public static CharSequence wrapForTts(CharSequence msg, String ttsMsg) {
741 if (Utilities.ATLEAST_LOLLIPOP) {
742 SpannableString spanned = new SpannableString(msg);
743 spanned.setSpan(new TtsSpan.TextBuilder(ttsMsg).build(),
744 0, spanned.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
745 return spanned;
746 } else {
747 return msg;
748 }
749 }
Winson12fb9fc2015-10-01 15:34:08 -0700750
751 /**
752 * Replacement for Long.compare() which was added in API level 19.
753 */
754 public static int longCompare(long lhs, long rhs) {
755 return lhs < rhs ? -1 : (lhs == rhs ? 0 : 1);
756 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800757}