blob: 31c141460177f489372682f7fc6f6ba1a4198e76 [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 Goyal6c56c682015-07-16 14:09:05 -070062import com.android.launcher3.config.ProviderConfig;
63
Sunny Goyal5b0e6692015-03-19 14:31:19 -070064import java.io.ByteArrayOutputStream;
65import java.io.IOException;
Sunny Goyal25aba0a2015-07-16 15:07:47 -070066import java.lang.reflect.Method;
Winson Chungc763c4e2013-07-19 13:49:06 -070067import java.util.ArrayList;
Sunny Goyalb1622cc2015-06-10 16:00:42 -070068import java.util.Locale;
Sunny Goyal4e5cc642015-06-25 16:37:44 -070069import java.util.Set;
Sunny Goyal8ac727b2015-09-23 15:38:09 -070070import java.util.concurrent.Executor;
71import java.util.concurrent.LinkedBlockingQueue;
72import java.util.concurrent.ThreadPoolExecutor;
73import java.util.concurrent.TimeUnit;
Winson Chung82b016c2015-05-08 17:00:10 -070074import java.util.regex.Matcher;
75import java.util.regex.Pattern;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080076
77/**
78 * Various utilities shared amongst the Launcher's classes.
79 */
Mathew Inwood72fbec12013-11-19 15:45:07 +000080public final class Utilities {
Rahul Chaturvedi7fc77ca2015-05-19 18:02:16 -070081
Joe Onorato1291a8c2009-09-15 15:07:25 -040082 private static final String TAG = "Launcher.Utilities";
83
The Android Open Source Project31dd5032009-03-03 19:32:27 -080084 private static final Rect sOldBounds = new Rect();
Romain Guy89911d22009-09-28 18:48:49 -070085 private static final Canvas sCanvas = new Canvas();
The Android Open Source Project31dd5032009-03-03 19:32:27 -080086
Winson Chung82b016c2015-05-08 17:00:10 -070087 private static final Pattern sTrimPattern =
88 Pattern.compile("^[\\s|\\p{javaSpaceChar}]*(.*)[\\s|\\p{javaSpaceChar}]*$");
89
The Android Open Source Project31dd5032009-03-03 19:32:27 -080090 static {
91 sCanvas.setDrawFilter(new PaintFlagsDrawFilter(Paint.DITHER_FLAG,
92 Paint.FILTER_BITMAP_FLAG));
93 }
Joe Onorato6665c0f2009-09-02 15:27:24 -070094 static int sColors[] = { 0xffff0000, 0xff00ff00, 0xff0000ff };
95 static int sColorIndex = 0;
96
Sunny Goyal53d7ee42015-05-22 12:25:45 -070097 private static final int[] sLoc0 = new int[2];
98 private static final int[] sLoc1 = new int[2];
Michael Jurka7ad868b2013-12-12 15:04:25 +010099
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700100 // TODO: use Build.VERSION_CODES when available
101 public static final boolean ATLEAST_MARSHMALLOW = Build.VERSION.SDK_INT >= 23;
102
103 public static final boolean ATLEAST_LOLLIPOP_MR1 =
104 Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1;
105
106 public static final boolean ATLEAST_LOLLIPOP =
107 Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
108
109 public static final boolean ATLEAST_KITKAT =
110 Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
111
112 public static final boolean ATLEAST_JB_MR1 =
113 Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1;
114
115 public static final boolean ATLEAST_JB_MR2 =
116 Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2;
117
Sunny Goyal8ac727b2015-09-23 15:38:09 -0700118 // These values are same as that in {@link AsyncTask}.
119 private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
120 private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
121 private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
122 private static final int KEEP_ALIVE = 1;
123 /**
124 * An {@link Executor} to be used with async task with no limit on the queue size.
125 */
126 public static final Executor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(
127 CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
128 TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
129
Michael Jurka7ad868b2013-12-12 15:04:25 +0100130 // To turn on these properties, type
131 // adb shell setprop log.tag.PROPERTY_NAME [VERBOSE | SUPPRESS]
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700132 private static final String FORCE_ENABLE_ROTATION_PROPERTY = "launcher_force_rotate";
133 private static boolean sForceEnableRotation = isPropertyEnabled(FORCE_ENABLE_ROTATION_PROPERTY);
Michael Jurka7ad868b2013-12-12 15:04:25 +0100134
Rahul Chaturvedi7fc77ca2015-05-19 18:02:16 -0700135 public static final String ALLOW_ROTATION_PREFERENCE_KEY = "pref_allowRotation";
136
Sunny Goyal4bbf4192014-11-11 12:23:59 -0800137 public static boolean isPropertyEnabled(String propertyName) {
Michael Jurka7ad868b2013-12-12 15:04:25 +0100138 return Log.isLoggable(propertyName, Log.VERBOSE);
139 }
140
Sunny Goyal21bf5312015-08-21 11:08:24 -0700141 public static boolean isAllowRotationPrefEnabled(Context context) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700142 SharedPreferences sharedPrefs = context.getSharedPreferences(
Sunny Goyal21bf5312015-08-21 11:08:24 -0700143 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
Rahul Chaturvedi7fc77ca2015-05-19 18:02:16 -0700144 boolean allowRotationPref = sharedPrefs.getBoolean(ALLOW_ROTATION_PREFERENCE_KEY, false);
145 return sForceEnableRotation || allowRotationPref;
146 }
147
148 public static boolean isRotationAllowedForDevice(Context context) {
149 return sForceEnableRotation || context.getResources().getBoolean(R.bool.allow_rotation);
Michael Jurka7ad868b2013-12-12 15:04:25 +0100150 }
151
Vadim Tryshev9de91272015-08-03 18:37:17 -0700152 public static boolean isNycOrAbove() {
153 // TODO(vadimt): Replace using reflection with looking at the API version once
154 // Build.VERSION.SDK_INT gets bumped to 24. b/22942492.
155 try {
156 View.class.getDeclaredField("DRAG_FLAG_OPAQUE");
157 // View.DRAG_FLAG_OPAQUE doesn't exist in M-release, so it's an indication of N+.
158 return true;
159 } catch (NoSuchFieldException e) {
160 return false;
161 }
162 }
163
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700164 public static Bitmap createIconBitmap(Cursor c, int iconIndex, Context context) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -0800165 byte[] data = c.getBlob(iconIndex);
166 try {
167 return createIconBitmap(BitmapFactory.decodeByteArray(data, 0, data.length), context);
168 } catch (Exception e) {
169 return null;
170 }
171 }
172
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -0700173 /**
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700174 * Returns a bitmap suitable for the all apps view. If the package or the resource do not
175 * exist, it returns null.
176 */
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700177 public static Bitmap createIconBitmap(String packageName, String resourceName,
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700178 Context context) {
179 PackageManager packageManager = context.getPackageManager();
180 // the resource
181 try {
182 Resources resources = packageManager.getResourcesForApplication(packageName);
183 if (resources != null) {
184 final int id = resources.getIdentifier(resourceName, null, null);
185 return createIconBitmap(
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700186 resources.getDrawableForDensity(id, LauncherAppState.getInstance()
187 .getInvariantDeviceProfile().fillResIconDpi), context);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700188 }
189 } catch (Exception e) {
190 // Icon not found.
191 }
192 return null;
193 }
194
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700195 private static int getIconBitmapSize() {
196 return LauncherAppState.getInstance().getInvariantDeviceProfile().iconBitmapSize;
197 }
198
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700199 /**
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700200 * Returns a bitmap which is of the appropriate size to be displayed as an icon
Michael Jurka931dc972011-08-05 15:08:15 -0700201 */
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700202 public static Bitmap createIconBitmap(Bitmap icon, Context context) {
203 final int iconBitmapSize = getIconBitmapSize();
204 if (iconBitmapSize == icon.getWidth() && iconBitmapSize == icon.getHeight()) {
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700205 return icon;
206 }
207 return createIconBitmap(new BitmapDrawable(context.getResources(), icon), context);
Michael Jurka931dc972011-08-05 15:08:15 -0700208 }
209
210 /**
211 * Returns a bitmap suitable for the all apps view.
Joe Onorato6665c0f2009-09-02 15:27:24 -0700212 */
Mathew Inwood72fbec12013-11-19 15:45:07 +0000213 public static Bitmap createIconBitmap(Drawable icon, Context context) {
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700214 synchronized (sCanvas) {
215 final int iconBitmapSize = getIconBitmapSize();
Joe Onorato6665c0f2009-09-02 15:27:24 -0700216
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700217 int width = iconBitmapSize;
218 int height = iconBitmapSize;
Joe Onorato6665c0f2009-09-02 15:27:24 -0700219
Joe Onorato6665c0f2009-09-02 15:27:24 -0700220 if (icon instanceof PaintDrawable) {
221 PaintDrawable painter = (PaintDrawable) icon;
222 painter.setIntrinsicWidth(width);
223 painter.setIntrinsicHeight(height);
224 } else if (icon instanceof BitmapDrawable) {
225 // Ensure the bitmap has a density.
226 BitmapDrawable bitmapDrawable = (BitmapDrawable) icon;
227 Bitmap bitmap = bitmapDrawable.getBitmap();
228 if (bitmap.getDensity() == Bitmap.DENSITY_NONE) {
229 bitmapDrawable.setTargetDensity(context.getResources().getDisplayMetrics());
230 }
231 }
232 int sourceWidth = icon.getIntrinsicWidth();
233 int sourceHeight = icon.getIntrinsicHeight();
Michael Jurka931dc972011-08-05 15:08:15 -0700234 if (sourceWidth > 0 && sourceHeight > 0) {
Winson Chung5f8afe62013-08-12 16:19:28 -0700235 // Scale the icon proportionally to the icon dimensions
236 final float ratio = (float) sourceWidth / sourceHeight;
237 if (sourceWidth > sourceHeight) {
238 height = (int) (width / ratio);
239 } else if (sourceHeight > sourceWidth) {
240 width = (int) (height * ratio);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700241 }
242 }
243
244 // no intrinsic size --> use default size
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700245 int textureWidth = iconBitmapSize;
246 int textureHeight = iconBitmapSize;
Joe Onorato6665c0f2009-09-02 15:27:24 -0700247
248 final Bitmap bitmap = Bitmap.createBitmap(textureWidth, textureHeight,
249 Bitmap.Config.ARGB_8888);
250 final Canvas canvas = sCanvas;
251 canvas.setBitmap(bitmap);
252
253 final int left = (textureWidth-width) / 2;
254 final int top = (textureHeight-height) / 2;
255
Michael Jurka3a9fced2012-04-13 14:44:29 -0700256 @SuppressWarnings("all") // suppress dead code warning
257 final boolean debug = false;
258 if (debug) {
Joe Onorato6665c0f2009-09-02 15:27:24 -0700259 // draw a big box for the icon for debugging
260 canvas.drawColor(sColors[sColorIndex]);
261 if (++sColorIndex >= sColors.length) sColorIndex = 0;
262 Paint debugPaint = new Paint();
263 debugPaint.setColor(0xffcccc00);
264 canvas.drawRect(left, top, left+width, top+height, debugPaint);
265 }
266
267 sOldBounds.set(icon.getBounds());
268 icon.setBounds(left, top, left+width, top+height);
269 icon.draw(canvas);
270 icon.setBounds(sOldBounds);
Adam Cohenaaf473c2011-08-03 12:02:47 -0700271 canvas.setBitmap(null);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700272
273 return bitmap;
274 }
275 }
276
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800277 /**
Winson Chungc763c4e2013-07-19 13:49:06 -0700278 * Given a coordinate relative to the descendant, find the coordinate in a parent view's
279 * coordinates.
280 *
281 * @param descendant The descendant to which the passed coordinate is relative.
282 * @param root The root view to make the coordinates relative to.
283 * @param coord The coordinate that we want mapped.
284 * @param includeRootScroll Whether or not to account for the scroll of the descendant:
285 * sometimes this is relevant as in a child's coordinates within the descendant.
286 * @return The factor by which this descendant is scaled relative to this DragLayer. Caution
287 * this scale factor is assumed to be equal in X and Y, and so if at any point this
288 * assumption fails, we will need to return a pair of scale factors.
289 */
290 public static float getDescendantCoordRelativeToParent(View descendant, View root,
291 int[] coord, boolean includeRootScroll) {
292 ArrayList<View> ancestorChain = new ArrayList<View>();
293
294 float[] pt = {coord[0], coord[1]};
295
296 View v = descendant;
297 while(v != root && v != null) {
298 ancestorChain.add(v);
299 v = (View) v.getParent();
300 }
301 ancestorChain.add(root);
302
303 float scale = 1.0f;
304 int count = ancestorChain.size();
305 for (int i = 0; i < count; i++) {
306 View v0 = ancestorChain.get(i);
Winson Chungc763c4e2013-07-19 13:49:06 -0700307 // For TextViews, scroll has a meaning which relates to the text position
308 // which is very strange... ignore the scroll.
309 if (v0 != descendant || includeRootScroll) {
310 pt[0] -= v0.getScrollX();
311 pt[1] -= v0.getScrollY();
312 }
313
314 v0.getMatrix().mapPoints(pt);
315 pt[0] += v0.getLeft();
316 pt[1] += v0.getTop();
317 scale *= v0.getScaleX();
318 }
319
320 coord[0] = (int) Math.round(pt[0]);
321 coord[1] = (int) Math.round(pt[1]);
322 return scale;
323 }
324
325 /**
326 * Inverse of {@link #getDescendantCoordRelativeToSelf(View, int[])}.
327 */
328 public static float mapCoordInSelfToDescendent(View descendant, View root,
329 int[] coord) {
330 ArrayList<View> ancestorChain = new ArrayList<View>();
331
332 float[] pt = {coord[0], coord[1]};
333
334 View v = descendant;
335 while(v != root) {
336 ancestorChain.add(v);
337 v = (View) v.getParent();
338 }
339 ancestorChain.add(root);
340
341 float scale = 1.0f;
342 Matrix inverse = new Matrix();
343 int count = ancestorChain.size();
344 for (int i = count - 1; i >= 0; i--) {
345 View ancestor = ancestorChain.get(i);
346 View next = i > 0 ? ancestorChain.get(i-1) : null;
347
348 pt[0] += ancestor.getScrollX();
349 pt[1] += ancestor.getScrollY();
350
351 if (next != null) {
352 pt[0] -= next.getLeft();
353 pt[1] -= next.getTop();
354 next.getMatrix().invert(inverse);
355 inverse.mapPoints(pt);
356 scale *= next.getScaleX();
357 }
358 }
359
360 coord[0] = (int) Math.round(pt[0]);
361 coord[1] = (int) Math.round(pt[1]);
362 return scale;
363 }
364
Jason Monk02dd7ae2014-04-15 15:23:31 -0400365 /**
366 * Utility method to determine whether the given point, in local coordinates,
367 * is inside the view, where the area of the view is expanded by the slop factor.
368 * This method is called while processing touch-move events to determine if the event
369 * is still within the view.
370 */
371 public static boolean pointInView(View v, float localX, float localY, float slop) {
372 return localX >= -slop && localY >= -slop && localX < (v.getWidth() + slop) &&
373 localY < (v.getHeight() + slop);
374 }
375
Adam Cohen63f1ec02014-08-12 09:23:13 -0700376 public static int[] getCenterDeltaInScreenSpace(View v0, View v1, int[] delta) {
377 v0.getLocationInWindow(sLoc0);
378 v1.getLocationInWindow(sLoc1);
379
380 sLoc0[0] += (v0.getMeasuredWidth() * v0.getScaleX()) / 2;
381 sLoc0[1] += (v0.getMeasuredHeight() * v0.getScaleY()) / 2;
382 sLoc1[0] += (v1.getMeasuredWidth() * v1.getScaleX()) / 2;
383 sLoc1[1] += (v1.getMeasuredHeight() * v1.getScaleY()) / 2;
384
385 if (delta == null) {
386 delta = new int[2];
387 }
388
389 delta[0] = sLoc1[0] - sLoc0[0];
390 delta[1] = sLoc1[1] - sLoc0[1];
391
392 return delta;
393 }
394
Winson Chung3a6e7f32013-10-09 15:50:52 -0700395 public static void scaleRectAboutCenter(Rect r, float scale) {
Sunny Goyal106bf642015-07-16 12:18:06 -0700396 if (scale != 1.0f) {
397 int cx = r.centerX();
398 int cy = r.centerY();
399 r.offset(-cx, -cy);
400
401 r.left = (int) (r.left * scale + 0.5f);
402 r.top = (int) (r.top * scale + 0.5f);
403 r.right = (int) (r.right * scale + 0.5f);
404 r.bottom = (int) (r.bottom * scale + 0.5f);
405
406 r.offset(cx, cy);
407 }
Winson Chung3a6e7f32013-10-09 15:50:52 -0700408 }
409
Michael Jurkaa805e1a2013-08-22 15:00:33 +0200410 public static void startActivityForResultSafely(
411 Activity activity, Intent intent, int requestCode) {
412 try {
413 activity.startActivityForResult(intent, requestCode);
414 } catch (ActivityNotFoundException e) {
415 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
416 } catch (SecurityException e) {
417 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
418 Log.e(TAG, "Launcher does not have the permission to launch " + intent +
419 ". Make sure to create a MAIN intent-filter for the corresponding activity " +
420 "or use the exported attribute for this activity.", e);
421 }
422 }
Sunny Goyalc5c60ad2014-07-14 12:02:01 -0700423
424 static boolean isSystemApp(Context context, Intent intent) {
425 PackageManager pm = context.getPackageManager();
426 ComponentName cn = intent.getComponent();
427 String packageName = null;
428 if (cn == null) {
429 ResolveInfo info = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
430 if ((info != null) && (info.activityInfo != null)) {
431 packageName = info.activityInfo.packageName;
432 }
433 } else {
434 packageName = cn.getPackageName();
435 }
436 if (packageName != null) {
437 try {
438 PackageInfo info = pm.getPackageInfo(packageName, 0);
439 return (info != null) && (info.applicationInfo != null) &&
440 ((info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
441 } catch (NameNotFoundException e) {
442 return false;
443 }
444 } else {
445 return false;
446 }
447 }
Sunny Goyal95abbb32014-08-04 10:53:22 -0700448
449 /**
450 * This picks a dominant color, looking for high-saturation, high-value, repeated hues.
451 * @param bitmap The bitmap to scan
452 * @param samples The approximate max number of samples to use.
453 */
454 static int findDominantColorByHue(Bitmap bitmap, int samples) {
455 final int height = bitmap.getHeight();
456 final int width = bitmap.getWidth();
457 int sampleStride = (int) Math.sqrt((height * width) / samples);
458 if (sampleStride < 1) {
459 sampleStride = 1;
460 }
461
462 // This is an out-param, for getting the hsv values for an rgb
463 float[] hsv = new float[3];
464
465 // First get the best hue, by creating a histogram over 360 hue buckets,
466 // where each pixel contributes a score weighted by saturation, value, and alpha.
467 float[] hueScoreHistogram = new float[360];
468 float highScore = -1;
469 int bestHue = -1;
470
471 for (int y = 0; y < height; y += sampleStride) {
472 for (int x = 0; x < width; x += sampleStride) {
473 int argb = bitmap.getPixel(x, y);
474 int alpha = 0xFF & (argb >> 24);
475 if (alpha < 0x80) {
476 // Drop mostly-transparent pixels.
477 continue;
478 }
479 // Remove the alpha channel.
480 int rgb = argb | 0xFF000000;
481 Color.colorToHSV(rgb, hsv);
482 // Bucket colors by the 360 integer hues.
483 int hue = (int) hsv[0];
484 if (hue < 0 || hue >= hueScoreHistogram.length) {
485 // Defensively avoid array bounds violations.
486 continue;
487 }
488 float score = hsv[1] * hsv[2];
489 hueScoreHistogram[hue] += score;
490 if (hueScoreHistogram[hue] > highScore) {
491 highScore = hueScoreHistogram[hue];
492 bestHue = hue;
493 }
494 }
495 }
496
497 SparseArray<Float> rgbScores = new SparseArray<Float>();
498 int bestColor = 0xff000000;
499 highScore = -1;
500 // Go back over the RGB colors that match the winning hue,
501 // creating a histogram of weighted s*v scores, for up to 100*100 [s,v] buckets.
502 // The highest-scoring RGB color wins.
503 for (int y = 0; y < height; y += sampleStride) {
504 for (int x = 0; x < width; x += sampleStride) {
505 int rgb = bitmap.getPixel(x, y) | 0xff000000;
506 Color.colorToHSV(rgb, hsv);
507 int hue = (int) hsv[0];
508 if (hue == bestHue) {
509 float s = hsv[1];
510 float v = hsv[2];
511 int bucket = (int) (s * 100) + (int) (v * 10000);
512 // Score by cumulative saturation * value.
513 float score = s * v;
514 Float oldTotal = rgbScores.get(bucket);
515 float newTotal = oldTotal == null ? score : oldTotal + score;
516 rgbScores.put(bucket, newTotal);
517 if (newTotal > highScore) {
518 highScore = newTotal;
519 // All the colors in the winning bucket are very similar. Last in wins.
520 bestColor = rgb;
521 }
522 }
523 }
524 }
525 return bestColor;
526 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700527
528 /*
529 * Finds a system apk which had a broadcast receiver listening to a particular action.
530 * @param action intent action used to find the apk
531 * @return a pair of apk package name and the resources.
532 */
533 static Pair<String, Resources> findSystemApk(String action, PackageManager pm) {
534 final Intent intent = new Intent(action);
535 for (ResolveInfo info : pm.queryBroadcastReceivers(intent, 0)) {
536 if (info.activityInfo != null &&
537 (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
538 final String packageName = info.activityInfo.packageName;
539 try {
540 final Resources res = pm.getResourcesForApplication(packageName);
541 return Pair.create(packageName, res);
542 } catch (NameNotFoundException e) {
543 Log.w(TAG, "Failed to find resources for " + packageName);
544 }
545 }
546 }
547 return null;
548 }
Sunny Goyalfafca522014-11-03 11:30:01 -0800549
Sunny Goyal594d76d2014-11-06 10:12:54 -0800550 /**
551 * Returns a widget with category {@link AppWidgetProviderInfo#WIDGET_CATEGORY_SEARCHBOX}
552 * provided by the same package which is set to be global search activity.
553 * If widgetCategory is not supported, or no such widget is found, returns the first widget
554 * provided by the package.
555 */
556 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
557 public static AppWidgetProviderInfo getSearchWidgetProvider(Context context) {
558 SearchManager searchManager =
559 (SearchManager) context.getSystemService(Context.SEARCH_SERVICE);
560 ComponentName searchComponent = searchManager.getGlobalSearchActivity();
561 if (searchComponent == null) return null;
562 String providerPkg = searchComponent.getPackageName();
563
564 AppWidgetProviderInfo defaultWidgetForSearchPackage = null;
565
566 AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
567 for (AppWidgetProviderInfo info : appWidgetManager.getInstalledProviders()) {
568 if (info.provider.getPackageName().equals(providerPkg)) {
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700569 if (ATLEAST_JB_MR1) {
Sunny Goyal594d76d2014-11-06 10:12:54 -0800570 if ((info.widgetCategory & AppWidgetProviderInfo.WIDGET_CATEGORY_SEARCHBOX) != 0) {
571 return info;
572 } else if (defaultWidgetForSearchPackage == null) {
573 defaultWidgetForSearchPackage = info;
574 }
575 } else {
576 return info;
577 }
578 }
579 }
580 return defaultWidgetForSearchPackage;
581 }
Sunny Goyal08f72612015-01-05 13:41:43 -0800582
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700583 /**
584 * Compresses the bitmap to a byte array for serialization.
585 */
586 public static byte[] flattenBitmap(Bitmap bitmap) {
587 // Try go guesstimate how much space the icon will take when serialized
588 // to avoid unnecessary allocations/copies during the write.
589 int size = bitmap.getWidth() * bitmap.getHeight() * 4;
590 ByteArrayOutputStream out = new ByteArrayOutputStream(size);
591 try {
592 bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
593 out.flush();
594 out.close();
595 return out.toByteArray();
596 } catch (IOException e) {
597 Log.w(TAG, "Could not write bitmap");
598 return null;
599 }
600 }
601
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700602 /**
603 * Find the first vacant cell, if there is one.
604 *
605 * @param vacant Holds the x and y coordinate of the vacant cell
606 * @param spanX Horizontal cell span.
607 * @param spanY Vertical cell span.
608 *
609 * @return true if a vacant cell was found
610 */
611 public static boolean findVacantCell(int[] vacant, int spanX, int spanY,
612 int xCount, int yCount, boolean[][] occupied) {
613
614 for (int y = 0; (y + spanY) <= yCount; y++) {
615 for (int x = 0; (x + spanX) <= xCount; x++) {
616 boolean available = !occupied[x][y];
617 out: for (int i = x; i < x + spanX; i++) {
618 for (int j = y; j < y + spanY; j++) {
619 available = available && !occupied[i][j];
620 if (!available) break out;
621 }
622 }
623
624 if (available) {
625 vacant[0] = x;
626 vacant[1] = y;
627 return true;
628 }
629 }
630 }
631
632 return false;
633 }
Winson Chung82b016c2015-05-08 17:00:10 -0700634
635 /**
636 * Trims the string, removing all whitespace at the beginning and end of the string.
637 * Non-breaking whitespaces are also removed.
638 */
639 public static String trim(CharSequence s) {
Winson Chungafa77e92015-05-15 12:04:03 -0700640 if (s == null) {
641 return null;
642 }
643
Winson Chung82b016c2015-05-08 17:00:10 -0700644 // Just strip any sequence of whitespace or java space characters from the beginning and end
645 Matcher m = sTrimPattern.matcher(s);
646 return m.replaceAll("$1");
647 }
Sunny Goyal70660032015-05-14 00:07:08 -0700648
Winson Chung2c6e5cc2015-06-01 14:38:24 -0700649 /**
650 * Calculates the height of a given string at a specific text size.
651 */
652 public static float calculateTextHeight(float textSizePx) {
653 Paint p = new Paint();
654 p.setTextSize(textSizePx);
655 Paint.FontMetrics fm = p.getFontMetrics();
656 return -fm.top + fm.bottom;
657 }
658
Winson Chungb1777442015-06-16 13:35:04 -0700659 /**
660 * Convenience println with multiple args.
661 */
662 public static void println(String key, Object... args) {
663 StringBuilder b = new StringBuilder();
664 b.append(key);
665 b.append(": ");
666 boolean isFirstArgument = true;
667 for (Object arg : args) {
668 if (isFirstArgument) {
669 isFirstArgument = false;
670 } else {
671 b.append(", ");
672 }
673 b.append(arg);
674 }
675 System.out.println(b.toString());
676 }
677
Sunny Goyal70660032015-05-14 00:07:08 -0700678 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
679 public static boolean isRtl(Resources res) {
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700680 return ATLEAST_JB_MR1 &&
Sunny Goyal70660032015-05-14 00:07:08 -0700681 (res.getConfiguration().getLayoutDirection() == View.LAYOUT_DIRECTION_RTL);
682 }
Hyunyoung Song2bd3d7d2015-05-21 13:04:53 -0700683
684 public static void assertWorkerThread() {
Sunny Goyal6c56c682015-07-16 14:09:05 -0700685 if (ProviderConfig.IS_DOGFOOD_BUILD &&
Sunny Goyal11d49112015-06-26 14:00:57 -0700686 (LauncherModel.sWorkerThread.getThreadId() != Process.myTid())) {
687 throw new IllegalStateException();
Hyunyoung Song2bd3d7d2015-05-21 13:04:53 -0700688 }
689 }
Sunny Goyal5c97f512015-05-19 16:03:28 -0700690
691 /**
692 * Returns true if the intent is a valid launch intent for a launcher activity of an app.
693 * This is used to identify shortcuts which are different from the ones exposed by the
694 * applications' manifest file.
695 *
696 * @param launchIntent The intent that will be launched when the shortcut is clicked.
697 */
698 public static boolean isLauncherAppTarget(Intent launchIntent) {
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700699 if (launchIntent != null
Sunny Goyal5c97f512015-05-19 16:03:28 -0700700 && Intent.ACTION_MAIN.equals(launchIntent.getAction())
701 && launchIntent.getComponent() != null
702 && launchIntent.getCategories() != null
703 && launchIntent.getCategories().size() == 1
704 && launchIntent.hasCategory(Intent.CATEGORY_LAUNCHER)
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700705 && TextUtils.isEmpty(launchIntent.getDataString())) {
706 // An app target can either have no extra or have ItemInfo.EXTRA_PROFILE.
707 Bundle extras = launchIntent.getExtras();
708 if (extras == null) {
709 return true;
710 } else {
711 Set<String> keys = extras.keySet();
712 return keys.size() == 1 && keys.contains(ItemInfo.EXTRA_PROFILE);
713 }
714 };
715 return false;
Sunny Goyal5c97f512015-05-19 16:03:28 -0700716 }
Adam Cohen2e6da152015-05-06 11:42:25 -0700717
718 public static float dpiFromPx(int size, DisplayMetrics metrics){
719 float densityRatio = (float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT;
720 return (size / densityRatio);
721 }
722 public static int pxFromDp(float size, DisplayMetrics metrics) {
723 return (int) Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
724 size, metrics));
725 }
726 public static int pxFromSp(float size, DisplayMetrics metrics) {
727 return (int) Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
728 size, metrics));
729 }
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700730
731 public static String createDbSelectionQuery(String columnName, Iterable<?> values) {
732 return String.format(Locale.ENGLISH, "%s IN (%s)", columnName, TextUtils.join(", ", values));
733 }
Sunny Goyal25aba0a2015-07-16 15:07:47 -0700734
Sunny Goyal25aba0a2015-07-16 15:07:47 -0700735 public static boolean isBootCompleted() {
736 try {
737 Class clazz = Class.forName("android.os.SystemProperties");
738 Method getter = clazz.getDeclaredMethod("get", String.class);
739 String value = (String) getter.invoke(null, "sys.boot_completed");
740 return "1".equals(value);
741 } catch (Exception e) {
742 Log.d(TAG, "Unable to read system properties");
743 // Assume that boot has completed
744 return true;
745 }
746 }
Tony Wickham29d853c2015-09-08 10:35:56 -0700747
748 /**
749 * Ensures that a value is within given bounds. Specifically:
750 * If value is less than lowerBound, return lowerBound; else if value is greater than upperBound,
751 * return upperBound; else return value unchanged.
752 */
753 public static int boundInRange(int value, int lowerBound, int upperBound) {
754 return Math.max(lowerBound, Math.min(value, upperBound));
755 }
Sunny Goyal9d438082015-09-25 11:50:16 -0700756
Sunny Goyale78e3d72015-09-24 11:23:31 -0700757 /**
758 * Wraps a message with a TTS span, so that a different message is spoken than
759 * what is getting displayed.
760 * @param msg original message
761 * @param ttsMsg message to be spoken
762 */
763 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
764 public static CharSequence wrapForTts(CharSequence msg, String ttsMsg) {
765 if (Utilities.ATLEAST_LOLLIPOP) {
766 SpannableString spanned = new SpannableString(msg);
767 spanned.setSpan(new TtsSpan.TextBuilder(ttsMsg).build(),
768 0, spanned.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
769 return spanned;
770 } else {
771 return msg;
772 }
773 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800774}