blob: dd9b5fc40dc85f6556284e928235859cb6520912 [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;
Tony Wickham112ac952015-11-12 12:31:50 -080049import android.os.PowerManager;
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 Goyalb84046d2015-10-19 14:03:30 -070062import com.android.launcher3.compat.UserHandleCompat;
Sunny Goyald896ee42015-12-17 11:24:31 -080063import com.android.launcher3.config.FeatureFlags;
Sunny Goyalfc218302015-09-17 14:59:10 -070064import com.android.launcher3.util.IconNormalizer;
Sunny Goyal6c56c682015-07-16 14:09:05 -070065
Sunny Goyal5b0e6692015-03-19 14:31:19 -070066import java.io.ByteArrayOutputStream;
67import java.io.IOException;
Sunny Goyal25aba0a2015-07-16 15:07:47 -070068import java.lang.reflect.Method;
Winson Chungc763c4e2013-07-19 13:49:06 -070069import java.util.ArrayList;
Sunny Goyalb1622cc2015-06-10 16:00:42 -070070import java.util.Locale;
Sunny Goyal4e5cc642015-06-25 16:37:44 -070071import java.util.Set;
Sunny Goyal8ac727b2015-09-23 15:38:09 -070072import java.util.concurrent.Executor;
73import java.util.concurrent.LinkedBlockingQueue;
74import java.util.concurrent.ThreadPoolExecutor;
75import java.util.concurrent.TimeUnit;
Winson Chung82b016c2015-05-08 17:00:10 -070076import java.util.regex.Matcher;
77import java.util.regex.Pattern;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080078
79/**
80 * Various utilities shared amongst the Launcher's classes.
81 */
Mathew Inwood72fbec12013-11-19 15:45:07 +000082public final class Utilities {
Rahul Chaturvedi7fc77ca2015-05-19 18:02:16 -070083
Joe Onorato1291a8c2009-09-15 15:07:25 -040084 private static final String TAG = "Launcher.Utilities";
85
The Android Open Source Project31dd5032009-03-03 19:32:27 -080086 private static final Rect sOldBounds = new Rect();
Romain Guy89911d22009-09-28 18:48:49 -070087 private static final Canvas sCanvas = new Canvas();
The Android Open Source Project31dd5032009-03-03 19:32:27 -080088
Winson Chung82b016c2015-05-08 17:00:10 -070089 private static final Pattern sTrimPattern =
90 Pattern.compile("^[\\s|\\p{javaSpaceChar}]*(.*)[\\s|\\p{javaSpaceChar}]*$");
91
The Android Open Source Project31dd5032009-03-03 19:32:27 -080092 static {
93 sCanvas.setDrawFilter(new PaintFlagsDrawFilter(Paint.DITHER_FLAG,
94 Paint.FILTER_BITMAP_FLAG));
95 }
Joe Onorato6665c0f2009-09-02 15:27:24 -070096 static int sColors[] = { 0xffff0000, 0xff00ff00, 0xff0000ff };
97 static int sColorIndex = 0;
98
Sunny Goyal53d7ee42015-05-22 12:25:45 -070099 private static final int[] sLoc0 = new int[2];
100 private static final int[] sLoc1 = new int[2];
Michael Jurka7ad868b2013-12-12 15:04:25 +0100101
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700102 // TODO: use Build.VERSION_CODES when available
103 public static final boolean ATLEAST_MARSHMALLOW = Build.VERSION.SDK_INT >= 23;
104
105 public static final boolean ATLEAST_LOLLIPOP_MR1 =
106 Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1;
107
108 public static final boolean ATLEAST_LOLLIPOP =
109 Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
110
111 public static final boolean ATLEAST_KITKAT =
112 Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
113
114 public static final boolean ATLEAST_JB_MR1 =
115 Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1;
116
117 public static final boolean ATLEAST_JB_MR2 =
118 Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2;
119
Sunny Goyal6f866092016-03-17 17:04:15 -0700120 // An intent extra to indicate the horizontal scroll of the wallpaper.
121 public static final String EXTRA_WALLPAPER_OFFSET = "com.android.launcher3.WALLPAPER_OFFSET";
122
Sunny Goyal8ac727b2015-09-23 15:38:09 -0700123 // These values are same as that in {@link AsyncTask}.
124 private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
125 private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
126 private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
127 private static final int KEEP_ALIVE = 1;
128 /**
129 * An {@link Executor} to be used with async task with no limit on the queue size.
130 */
131 public static final Executor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(
132 CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
133 TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
134
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 Goyal8f3819b2016-02-23 14:49:22 -0800142 boolean allowRotationPref = false;
143 if (isNycOrAbove()) {
144 // If the device was scaled, used the original dimensions to determine if rotation
145 // is allowed of not.
146 try {
147 // TODO: Use the actual field when the API is finalized.
148 int originalDensity =
149 DisplayMetrics.class.getField("DENSITY_DEVICE_STABLE").getInt(null);
150 Resources res = context.getResources();
151 int originalSmallestWidth = res.getConfiguration().smallestScreenWidthDp
152 * res.getDisplayMetrics().densityDpi / originalDensity;
153 allowRotationPref = originalSmallestWidth >= 600;
154 } catch (Exception e) {
155 // Ignore
156 }
157 }
Rahul Chaturvedi7fc77ca2015-05-19 18:02:16 -0700158
Sunny Goyal8f3819b2016-02-23 14:49:22 -0800159 return getPrefs(context).getBoolean(ALLOW_ROTATION_PREFERENCE_KEY, allowRotationPref);
Michael Jurka7ad868b2013-12-12 15:04:25 +0100160 }
161
Vadim Tryshev9de91272015-08-03 18:37:17 -0700162 public static boolean isNycOrAbove() {
163 // TODO(vadimt): Replace using reflection with looking at the API version once
164 // Build.VERSION.SDK_INT gets bumped to 24. b/22942492.
165 try {
166 View.class.getDeclaredField("DRAG_FLAG_OPAQUE");
167 // View.DRAG_FLAG_OPAQUE doesn't exist in M-release, so it's an indication of N+.
168 return true;
169 } catch (NoSuchFieldException e) {
170 return false;
171 }
172 }
173
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700174 public static Bitmap createIconBitmap(Cursor c, int iconIndex, Context context) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -0800175 byte[] data = c.getBlob(iconIndex);
176 try {
177 return createIconBitmap(BitmapFactory.decodeByteArray(data, 0, data.length), context);
178 } catch (Exception e) {
179 return null;
180 }
181 }
182
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -0700183 /**
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700184 * Returns a bitmap suitable for the all apps view. If the package or the resource do not
185 * exist, it returns null.
186 */
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700187 public static Bitmap createIconBitmap(String packageName, String resourceName,
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700188 Context context) {
189 PackageManager packageManager = context.getPackageManager();
190 // the resource
191 try {
192 Resources resources = packageManager.getResourcesForApplication(packageName);
193 if (resources != null) {
194 final int id = resources.getIdentifier(resourceName, null, null);
195 return createIconBitmap(
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700196 resources.getDrawableForDensity(id, LauncherAppState.getInstance()
197 .getInvariantDeviceProfile().fillResIconDpi), context);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700198 }
199 } catch (Exception e) {
200 // Icon not found.
201 }
202 return null;
203 }
204
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700205 private static int getIconBitmapSize() {
206 return LauncherAppState.getInstance().getInvariantDeviceProfile().iconBitmapSize;
207 }
208
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700209 /**
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700210 * Returns a bitmap which is of the appropriate size to be displayed as an icon
Michael Jurka931dc972011-08-05 15:08:15 -0700211 */
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700212 public static Bitmap createIconBitmap(Bitmap icon, Context context) {
213 final int iconBitmapSize = getIconBitmapSize();
214 if (iconBitmapSize == icon.getWidth() && iconBitmapSize == icon.getHeight()) {
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700215 return icon;
216 }
217 return createIconBitmap(new BitmapDrawable(context.getResources(), icon), context);
Michael Jurka931dc972011-08-05 15:08:15 -0700218 }
219
220 /**
Sunny Goyalfc218302015-09-17 14:59:10 -0700221 * Returns a bitmap suitable for the all apps view. The icon is badged for {@param user}.
222 * The bitmap is also visually normalized with other icons.
Sunny Goyalb84046d2015-10-19 14:03:30 -0700223 */
224 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
225 public static Bitmap createBadgedIconBitmap(
226 Drawable icon, UserHandleCompat user, Context context) {
Sunny Goyal531cda62016-03-03 13:19:24 -0800227 float scale = FeatureFlags.LAUNCHER3_DISABLE_ICON_NORMALIZATION ?
228 1 : IconNormalizer.getInstance().getScale(icon);
Sunny Goyalfc218302015-09-17 14:59:10 -0700229 Bitmap bitmap = createIconBitmap(icon, context, scale);
Sunny Goyalb84046d2015-10-19 14:03:30 -0700230 if (Utilities.ATLEAST_LOLLIPOP && user != null
231 && !UserHandleCompat.myUserHandle().equals(user)) {
Sunny Goyale1483fb2016-01-08 12:16:15 -0800232 BitmapDrawable drawable = new FixedSizeBitmapDrawable(bitmap);
Sunny Goyalb84046d2015-10-19 14:03:30 -0700233 Drawable badged = context.getPackageManager().getUserBadgedIcon(
234 drawable, user.getUser());
235 if (badged instanceof BitmapDrawable) {
236 return ((BitmapDrawable) badged).getBitmap();
237 } else {
238 return createIconBitmap(badged, context);
239 }
240 } else {
241 return bitmap;
242 }
243 }
244
245 /**
Michael Jurka931dc972011-08-05 15:08:15 -0700246 * Returns a bitmap suitable for the all apps view.
Joe Onorato6665c0f2009-09-02 15:27:24 -0700247 */
Mathew Inwood72fbec12013-11-19 15:45:07 +0000248 public static Bitmap createIconBitmap(Drawable icon, Context context) {
Sunny Goyalfc218302015-09-17 14:59:10 -0700249 return createIconBitmap(icon, context, 1.0f /* scale */);
250 }
251
252 /**
253 * @param scale the scale to apply before drawing {@param icon} on the canvas
254 */
255 public static Bitmap createIconBitmap(Drawable icon, Context context, float scale) {
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700256 synchronized (sCanvas) {
257 final int iconBitmapSize = getIconBitmapSize();
Joe Onorato6665c0f2009-09-02 15:27:24 -0700258
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700259 int width = iconBitmapSize;
260 int height = iconBitmapSize;
Joe Onorato6665c0f2009-09-02 15:27:24 -0700261
Joe Onorato6665c0f2009-09-02 15:27:24 -0700262 if (icon instanceof PaintDrawable) {
263 PaintDrawable painter = (PaintDrawable) icon;
264 painter.setIntrinsicWidth(width);
265 painter.setIntrinsicHeight(height);
266 } else if (icon instanceof BitmapDrawable) {
267 // Ensure the bitmap has a density.
268 BitmapDrawable bitmapDrawable = (BitmapDrawable) icon;
269 Bitmap bitmap = bitmapDrawable.getBitmap();
Sunny Goyalde9590b2015-09-23 12:56:51 -0700270 if (bitmap != null && bitmap.getDensity() == Bitmap.DENSITY_NONE) {
Joe Onorato6665c0f2009-09-02 15:27:24 -0700271 bitmapDrawable.setTargetDensity(context.getResources().getDisplayMetrics());
272 }
273 }
274 int sourceWidth = icon.getIntrinsicWidth();
275 int sourceHeight = icon.getIntrinsicHeight();
Michael Jurka931dc972011-08-05 15:08:15 -0700276 if (sourceWidth > 0 && sourceHeight > 0) {
Winson Chung5f8afe62013-08-12 16:19:28 -0700277 // Scale the icon proportionally to the icon dimensions
278 final float ratio = (float) sourceWidth / sourceHeight;
279 if (sourceWidth > sourceHeight) {
280 height = (int) (width / ratio);
281 } else if (sourceHeight > sourceWidth) {
282 width = (int) (height * ratio);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700283 }
284 }
285
286 // no intrinsic size --> use default size
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700287 int textureWidth = iconBitmapSize;
288 int textureHeight = iconBitmapSize;
Joe Onorato6665c0f2009-09-02 15:27:24 -0700289
290 final Bitmap bitmap = Bitmap.createBitmap(textureWidth, textureHeight,
291 Bitmap.Config.ARGB_8888);
292 final Canvas canvas = sCanvas;
293 canvas.setBitmap(bitmap);
294
295 final int left = (textureWidth-width) / 2;
296 final int top = (textureHeight-height) / 2;
297
Michael Jurka3a9fced2012-04-13 14:44:29 -0700298 @SuppressWarnings("all") // suppress dead code warning
299 final boolean debug = false;
300 if (debug) {
Joe Onorato6665c0f2009-09-02 15:27:24 -0700301 // draw a big box for the icon for debugging
302 canvas.drawColor(sColors[sColorIndex]);
303 if (++sColorIndex >= sColors.length) sColorIndex = 0;
304 Paint debugPaint = new Paint();
305 debugPaint.setColor(0xffcccc00);
306 canvas.drawRect(left, top, left+width, top+height, debugPaint);
307 }
308
309 sOldBounds.set(icon.getBounds());
310 icon.setBounds(left, top, left+width, top+height);
Sunny Goyalfc218302015-09-17 14:59:10 -0700311 canvas.save(Canvas.MATRIX_SAVE_FLAG);
312 canvas.scale(scale, scale, textureWidth / 2, textureHeight / 2);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700313 icon.draw(canvas);
Sunny Goyalfc218302015-09-17 14:59:10 -0700314 canvas.restore();
Joe Onorato6665c0f2009-09-02 15:27:24 -0700315 icon.setBounds(sOldBounds);
Adam Cohenaaf473c2011-08-03 12:02:47 -0700316 canvas.setBitmap(null);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700317
318 return bitmap;
319 }
320 }
321
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800322 /**
Winson Chungc763c4e2013-07-19 13:49:06 -0700323 * Given a coordinate relative to the descendant, find the coordinate in a parent view's
324 * coordinates.
325 *
326 * @param descendant The descendant to which the passed coordinate is relative.
327 * @param root The root view to make the coordinates relative to.
328 * @param coord The coordinate that we want mapped.
329 * @param includeRootScroll Whether or not to account for the scroll of the descendant:
330 * sometimes this is relevant as in a child's coordinates within the descendant.
331 * @return The factor by which this descendant is scaled relative to this DragLayer. Caution
332 * this scale factor is assumed to be equal in X and Y, and so if at any point this
333 * assumption fails, we will need to return a pair of scale factors.
334 */
335 public static float getDescendantCoordRelativeToParent(View descendant, View root,
336 int[] coord, boolean includeRootScroll) {
337 ArrayList<View> ancestorChain = new ArrayList<View>();
338
339 float[] pt = {coord[0], coord[1]};
340
341 View v = descendant;
342 while(v != root && v != null) {
343 ancestorChain.add(v);
344 v = (View) v.getParent();
345 }
346 ancestorChain.add(root);
347
348 float scale = 1.0f;
349 int count = ancestorChain.size();
350 for (int i = 0; i < count; i++) {
351 View v0 = ancestorChain.get(i);
Winson Chungc763c4e2013-07-19 13:49:06 -0700352 // For TextViews, scroll has a meaning which relates to the text position
353 // which is very strange... ignore the scroll.
354 if (v0 != descendant || includeRootScroll) {
355 pt[0] -= v0.getScrollX();
356 pt[1] -= v0.getScrollY();
357 }
358
359 v0.getMatrix().mapPoints(pt);
360 pt[0] += v0.getLeft();
361 pt[1] += v0.getTop();
362 scale *= v0.getScaleX();
363 }
364
365 coord[0] = (int) Math.round(pt[0]);
366 coord[1] = (int) Math.round(pt[1]);
367 return scale;
368 }
369
370 /**
Sunny Goyalfc218302015-09-17 14:59:10 -0700371 * Inverse of {@link #getDescendantCoordRelativeToParent(View, View, int[], boolean)}.
Winson Chungc763c4e2013-07-19 13:49:06 -0700372 */
373 public static float mapCoordInSelfToDescendent(View descendant, View root,
374 int[] coord) {
375 ArrayList<View> ancestorChain = new ArrayList<View>();
376
377 float[] pt = {coord[0], coord[1]};
378
379 View v = descendant;
380 while(v != root) {
381 ancestorChain.add(v);
382 v = (View) v.getParent();
383 }
384 ancestorChain.add(root);
385
386 float scale = 1.0f;
387 Matrix inverse = new Matrix();
388 int count = ancestorChain.size();
389 for (int i = count - 1; i >= 0; i--) {
390 View ancestor = ancestorChain.get(i);
391 View next = i > 0 ? ancestorChain.get(i-1) : null;
392
393 pt[0] += ancestor.getScrollX();
394 pt[1] += ancestor.getScrollY();
395
396 if (next != null) {
397 pt[0] -= next.getLeft();
398 pt[1] -= next.getTop();
399 next.getMatrix().invert(inverse);
400 inverse.mapPoints(pt);
401 scale *= next.getScaleX();
402 }
403 }
404
405 coord[0] = (int) Math.round(pt[0]);
406 coord[1] = (int) Math.round(pt[1]);
407 return scale;
408 }
409
Jason Monk02dd7ae2014-04-15 15:23:31 -0400410 /**
411 * Utility method to determine whether the given point, in local coordinates,
412 * is inside the view, where the area of the view is expanded by the slop factor.
413 * This method is called while processing touch-move events to determine if the event
414 * is still within the view.
415 */
416 public static boolean pointInView(View v, float localX, float localY, float slop) {
417 return localX >= -slop && localY >= -slop && localX < (v.getWidth() + slop) &&
418 localY < (v.getHeight() + slop);
419 }
420
Adam Cohen63f1ec02014-08-12 09:23:13 -0700421 public static int[] getCenterDeltaInScreenSpace(View v0, View v1, int[] delta) {
422 v0.getLocationInWindow(sLoc0);
423 v1.getLocationInWindow(sLoc1);
424
425 sLoc0[0] += (v0.getMeasuredWidth() * v0.getScaleX()) / 2;
426 sLoc0[1] += (v0.getMeasuredHeight() * v0.getScaleY()) / 2;
427 sLoc1[0] += (v1.getMeasuredWidth() * v1.getScaleX()) / 2;
428 sLoc1[1] += (v1.getMeasuredHeight() * v1.getScaleY()) / 2;
429
430 if (delta == null) {
431 delta = new int[2];
432 }
433
434 delta[0] = sLoc1[0] - sLoc0[0];
435 delta[1] = sLoc1[1] - sLoc0[1];
436
437 return delta;
438 }
439
Winson Chung3a6e7f32013-10-09 15:50:52 -0700440 public static void scaleRectAboutCenter(Rect r, float scale) {
Sunny Goyal106bf642015-07-16 12:18:06 -0700441 if (scale != 1.0f) {
442 int cx = r.centerX();
443 int cy = r.centerY();
444 r.offset(-cx, -cy);
445
446 r.left = (int) (r.left * scale + 0.5f);
447 r.top = (int) (r.top * scale + 0.5f);
448 r.right = (int) (r.right * scale + 0.5f);
449 r.bottom = (int) (r.bottom * scale + 0.5f);
450
451 r.offset(cx, cy);
452 }
Winson Chung3a6e7f32013-10-09 15:50:52 -0700453 }
454
Michael Jurkaa805e1a2013-08-22 15:00:33 +0200455 public static void startActivityForResultSafely(
456 Activity activity, Intent intent, int requestCode) {
457 try {
458 activity.startActivityForResult(intent, requestCode);
459 } catch (ActivityNotFoundException e) {
460 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
461 } catch (SecurityException e) {
462 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
463 Log.e(TAG, "Launcher does not have the permission to launch " + intent +
464 ". Make sure to create a MAIN intent-filter for the corresponding activity " +
465 "or use the exported attribute for this activity.", e);
466 }
467 }
Sunny Goyalc5c60ad2014-07-14 12:02:01 -0700468
469 static boolean isSystemApp(Context context, Intent intent) {
470 PackageManager pm = context.getPackageManager();
471 ComponentName cn = intent.getComponent();
472 String packageName = null;
473 if (cn == null) {
474 ResolveInfo info = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
475 if ((info != null) && (info.activityInfo != null)) {
476 packageName = info.activityInfo.packageName;
477 }
478 } else {
479 packageName = cn.getPackageName();
480 }
481 if (packageName != null) {
482 try {
483 PackageInfo info = pm.getPackageInfo(packageName, 0);
484 return (info != null) && (info.applicationInfo != null) &&
485 ((info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
486 } catch (NameNotFoundException e) {
487 return false;
488 }
489 } else {
490 return false;
491 }
492 }
Sunny Goyal95abbb32014-08-04 10:53:22 -0700493
494 /**
495 * This picks a dominant color, looking for high-saturation, high-value, repeated hues.
496 * @param bitmap The bitmap to scan
497 * @param samples The approximate max number of samples to use.
498 */
499 static int findDominantColorByHue(Bitmap bitmap, int samples) {
500 final int height = bitmap.getHeight();
501 final int width = bitmap.getWidth();
502 int sampleStride = (int) Math.sqrt((height * width) / samples);
503 if (sampleStride < 1) {
504 sampleStride = 1;
505 }
506
507 // This is an out-param, for getting the hsv values for an rgb
508 float[] hsv = new float[3];
509
510 // First get the best hue, by creating a histogram over 360 hue buckets,
511 // where each pixel contributes a score weighted by saturation, value, and alpha.
512 float[] hueScoreHistogram = new float[360];
513 float highScore = -1;
514 int bestHue = -1;
515
516 for (int y = 0; y < height; y += sampleStride) {
517 for (int x = 0; x < width; x += sampleStride) {
518 int argb = bitmap.getPixel(x, y);
519 int alpha = 0xFF & (argb >> 24);
520 if (alpha < 0x80) {
521 // Drop mostly-transparent pixels.
522 continue;
523 }
524 // Remove the alpha channel.
525 int rgb = argb | 0xFF000000;
526 Color.colorToHSV(rgb, hsv);
527 // Bucket colors by the 360 integer hues.
528 int hue = (int) hsv[0];
529 if (hue < 0 || hue >= hueScoreHistogram.length) {
530 // Defensively avoid array bounds violations.
531 continue;
532 }
533 float score = hsv[1] * hsv[2];
534 hueScoreHistogram[hue] += score;
535 if (hueScoreHistogram[hue] > highScore) {
536 highScore = hueScoreHistogram[hue];
537 bestHue = hue;
538 }
539 }
540 }
541
542 SparseArray<Float> rgbScores = new SparseArray<Float>();
543 int bestColor = 0xff000000;
544 highScore = -1;
545 // Go back over the RGB colors that match the winning hue,
546 // creating a histogram of weighted s*v scores, for up to 100*100 [s,v] buckets.
547 // The highest-scoring RGB color wins.
548 for (int y = 0; y < height; y += sampleStride) {
549 for (int x = 0; x < width; x += sampleStride) {
550 int rgb = bitmap.getPixel(x, y) | 0xff000000;
551 Color.colorToHSV(rgb, hsv);
552 int hue = (int) hsv[0];
553 if (hue == bestHue) {
554 float s = hsv[1];
555 float v = hsv[2];
556 int bucket = (int) (s * 100) + (int) (v * 10000);
557 // Score by cumulative saturation * value.
558 float score = s * v;
559 Float oldTotal = rgbScores.get(bucket);
560 float newTotal = oldTotal == null ? score : oldTotal + score;
561 rgbScores.put(bucket, newTotal);
562 if (newTotal > highScore) {
563 highScore = newTotal;
564 // All the colors in the winning bucket are very similar. Last in wins.
565 bestColor = rgb;
566 }
567 }
568 }
569 }
570 return bestColor;
571 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700572
573 /*
574 * Finds a system apk which had a broadcast receiver listening to a particular action.
575 * @param action intent action used to find the apk
576 * @return a pair of apk package name and the resources.
577 */
578 static Pair<String, Resources> findSystemApk(String action, PackageManager pm) {
579 final Intent intent = new Intent(action);
580 for (ResolveInfo info : pm.queryBroadcastReceivers(intent, 0)) {
581 if (info.activityInfo != null &&
582 (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
583 final String packageName = info.activityInfo.packageName;
584 try {
585 final Resources res = pm.getResourcesForApplication(packageName);
586 return Pair.create(packageName, res);
587 } catch (NameNotFoundException e) {
588 Log.w(TAG, "Failed to find resources for " + packageName);
589 }
590 }
591 }
592 return null;
593 }
Sunny Goyalfafca522014-11-03 11:30:01 -0800594
Sunny Goyal594d76d2014-11-06 10:12:54 -0800595 /**
596 * Returns a widget with category {@link AppWidgetProviderInfo#WIDGET_CATEGORY_SEARCHBOX}
597 * provided by the same package which is set to be global search activity.
598 * If widgetCategory is not supported, or no such widget is found, returns the first widget
599 * provided by the package.
600 */
601 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
602 public static AppWidgetProviderInfo getSearchWidgetProvider(Context context) {
603 SearchManager searchManager =
604 (SearchManager) context.getSystemService(Context.SEARCH_SERVICE);
605 ComponentName searchComponent = searchManager.getGlobalSearchActivity();
606 if (searchComponent == null) return null;
607 String providerPkg = searchComponent.getPackageName();
608
609 AppWidgetProviderInfo defaultWidgetForSearchPackage = null;
610
611 AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
612 for (AppWidgetProviderInfo info : appWidgetManager.getInstalledProviders()) {
613 if (info.provider.getPackageName().equals(providerPkg)) {
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700614 if (ATLEAST_JB_MR1) {
Sunny Goyal594d76d2014-11-06 10:12:54 -0800615 if ((info.widgetCategory & AppWidgetProviderInfo.WIDGET_CATEGORY_SEARCHBOX) != 0) {
616 return info;
617 } else if (defaultWidgetForSearchPackage == null) {
618 defaultWidgetForSearchPackage = info;
619 }
620 } else {
621 return info;
622 }
623 }
624 }
625 return defaultWidgetForSearchPackage;
626 }
Sunny Goyal08f72612015-01-05 13:41:43 -0800627
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700628 /**
629 * Compresses the bitmap to a byte array for serialization.
630 */
631 public static byte[] flattenBitmap(Bitmap bitmap) {
632 // Try go guesstimate how much space the icon will take when serialized
633 // to avoid unnecessary allocations/copies during the write.
634 int size = bitmap.getWidth() * bitmap.getHeight() * 4;
635 ByteArrayOutputStream out = new ByteArrayOutputStream(size);
636 try {
637 bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
638 out.flush();
639 out.close();
640 return out.toByteArray();
641 } catch (IOException e) {
642 Log.w(TAG, "Could not write bitmap");
643 return null;
644 }
645 }
646
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700647 /**
648 * Find the first vacant cell, if there is one.
649 *
650 * @param vacant Holds the x and y coordinate of the vacant cell
651 * @param spanX Horizontal cell span.
652 * @param spanY Vertical cell span.
653 *
654 * @return true if a vacant cell was found
655 */
656 public static boolean findVacantCell(int[] vacant, int spanX, int spanY,
657 int xCount, int yCount, boolean[][] occupied) {
658
659 for (int y = 0; (y + spanY) <= yCount; y++) {
660 for (int x = 0; (x + spanX) <= xCount; x++) {
661 boolean available = !occupied[x][y];
662 out: for (int i = x; i < x + spanX; i++) {
663 for (int j = y; j < y + spanY; j++) {
664 available = available && !occupied[i][j];
665 if (!available) break out;
666 }
667 }
668
669 if (available) {
670 vacant[0] = x;
671 vacant[1] = y;
672 return true;
673 }
674 }
675 }
676
677 return false;
678 }
Winson Chung82b016c2015-05-08 17:00:10 -0700679
680 /**
681 * Trims the string, removing all whitespace at the beginning and end of the string.
682 * Non-breaking whitespaces are also removed.
683 */
684 public static String trim(CharSequence s) {
Winson Chungafa77e92015-05-15 12:04:03 -0700685 if (s == null) {
686 return null;
687 }
688
Winson Chung82b016c2015-05-08 17:00:10 -0700689 // Just strip any sequence of whitespace or java space characters from the beginning and end
690 Matcher m = sTrimPattern.matcher(s);
691 return m.replaceAll("$1");
692 }
Sunny Goyal70660032015-05-14 00:07:08 -0700693
Winson Chung2c6e5cc2015-06-01 14:38:24 -0700694 /**
695 * Calculates the height of a given string at a specific text size.
696 */
697 public static float calculateTextHeight(float textSizePx) {
698 Paint p = new Paint();
699 p.setTextSize(textSizePx);
700 Paint.FontMetrics fm = p.getFontMetrics();
701 return -fm.top + fm.bottom;
702 }
703
Winson Chungb1777442015-06-16 13:35:04 -0700704 /**
705 * Convenience println with multiple args.
706 */
707 public static void println(String key, Object... args) {
708 StringBuilder b = new StringBuilder();
709 b.append(key);
710 b.append(": ");
711 boolean isFirstArgument = true;
712 for (Object arg : args) {
713 if (isFirstArgument) {
714 isFirstArgument = false;
715 } else {
716 b.append(", ");
717 }
718 b.append(arg);
719 }
720 System.out.println(b.toString());
721 }
722
Sunny Goyal70660032015-05-14 00:07:08 -0700723 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
724 public static boolean isRtl(Resources res) {
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700725 return ATLEAST_JB_MR1 &&
Sunny Goyal70660032015-05-14 00:07:08 -0700726 (res.getConfiguration().getLayoutDirection() == View.LAYOUT_DIRECTION_RTL);
727 }
Hyunyoung Song2bd3d7d2015-05-21 13:04:53 -0700728
Sunny Goyal5c97f512015-05-19 16:03:28 -0700729 /**
730 * Returns true if the intent is a valid launch intent for a launcher activity of an app.
731 * This is used to identify shortcuts which are different from the ones exposed by the
732 * applications' manifest file.
733 *
734 * @param launchIntent The intent that will be launched when the shortcut is clicked.
735 */
736 public static boolean isLauncherAppTarget(Intent launchIntent) {
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700737 if (launchIntent != null
Sunny Goyal5c97f512015-05-19 16:03:28 -0700738 && Intent.ACTION_MAIN.equals(launchIntent.getAction())
739 && launchIntent.getComponent() != null
740 && launchIntent.getCategories() != null
741 && launchIntent.getCategories().size() == 1
742 && launchIntent.hasCategory(Intent.CATEGORY_LAUNCHER)
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700743 && TextUtils.isEmpty(launchIntent.getDataString())) {
744 // An app target can either have no extra or have ItemInfo.EXTRA_PROFILE.
745 Bundle extras = launchIntent.getExtras();
746 if (extras == null) {
747 return true;
748 } else {
749 Set<String> keys = extras.keySet();
750 return keys.size() == 1 && keys.contains(ItemInfo.EXTRA_PROFILE);
751 }
752 };
753 return false;
Sunny Goyal5c97f512015-05-19 16:03:28 -0700754 }
Adam Cohen2e6da152015-05-06 11:42:25 -0700755
756 public static float dpiFromPx(int size, DisplayMetrics metrics){
757 float densityRatio = (float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT;
758 return (size / densityRatio);
759 }
760 public static int pxFromDp(float size, DisplayMetrics metrics) {
761 return (int) Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
762 size, metrics));
763 }
764 public static int pxFromSp(float size, DisplayMetrics metrics) {
765 return (int) Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
766 size, metrics));
767 }
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700768
769 public static String createDbSelectionQuery(String columnName, Iterable<?> values) {
770 return String.format(Locale.ENGLISH, "%s IN (%s)", columnName, TextUtils.join(", ", values));
771 }
Sunny Goyal25aba0a2015-07-16 15:07:47 -0700772
Sunny Goyal25aba0a2015-07-16 15:07:47 -0700773 public static boolean isBootCompleted() {
774 try {
775 Class clazz = Class.forName("android.os.SystemProperties");
776 Method getter = clazz.getDeclaredMethod("get", String.class);
777 String value = (String) getter.invoke(null, "sys.boot_completed");
778 return "1".equals(value);
779 } catch (Exception e) {
780 Log.d(TAG, "Unable to read system properties");
781 // Assume that boot has completed
782 return true;
783 }
784 }
Tony Wickham29d853c2015-09-08 10:35:56 -0700785
786 /**
787 * Ensures that a value is within given bounds. Specifically:
788 * If value is less than lowerBound, return lowerBound; else if value is greater than upperBound,
789 * return upperBound; else return value unchanged.
790 */
791 public static int boundInRange(int value, int lowerBound, int upperBound) {
792 return Math.max(lowerBound, Math.min(value, upperBound));
793 }
Sunny Goyal9d438082015-09-25 11:50:16 -0700794
Sunny Goyale78e3d72015-09-24 11:23:31 -0700795 /**
796 * Wraps a message with a TTS span, so that a different message is spoken than
797 * what is getting displayed.
798 * @param msg original message
799 * @param ttsMsg message to be spoken
800 */
801 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
802 public static CharSequence wrapForTts(CharSequence msg, String ttsMsg) {
803 if (Utilities.ATLEAST_LOLLIPOP) {
804 SpannableString spanned = new SpannableString(msg);
805 spanned.setSpan(new TtsSpan.TextBuilder(ttsMsg).build(),
806 0, spanned.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
807 return spanned;
808 } else {
809 return msg;
810 }
811 }
Winson12fb9fc2015-10-01 15:34:08 -0700812
813 /**
814 * Replacement for Long.compare() which was added in API level 19.
815 */
816 public static int longCompare(long lhs, long rhs) {
817 return lhs < rhs ? -1 : (lhs == rhs ? 0 : 1);
818 }
Sunny Goyalf7258242015-10-19 16:59:07 -0700819
820 public static SharedPreferences getPrefs(Context context) {
821 return context.getSharedPreferences(
822 LauncherFiles.SHARED_PREFERENCES_KEY, Context.MODE_PRIVATE);
823 }
Tony Wickham112ac952015-11-12 12:31:50 -0800824
825 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
826 public static boolean isPowerSaverOn(Context context) {
827 PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
828 return ATLEAST_LOLLIPOP && powerManager.isPowerSaveMode();
829 }
Sunny Goyale1483fb2016-01-08 12:16:15 -0800830
831 /**
832 * An extension of {@link BitmapDrawable} which returns the bitmap pixel size as intrinsic size.
833 * This allows the badging to be done based on the action bitmap size rather than
834 * the scaled bitmap size.
835 */
836 private static class FixedSizeBitmapDrawable extends BitmapDrawable {
837
838 public FixedSizeBitmapDrawable(Bitmap bitmap) {
839 super(null, bitmap);
840 }
841
842 @Override
843 public int getIntrinsicHeight() {
844 return getBitmap().getWidth();
845 }
846
847 @Override
848 public int getIntrinsicWidth() {
849 return getBitmap().getWidth();
850 }
851 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800852}