blob: 2f460bcecee9868350f71d446428333d0afcd565 [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;
Sunny Goyal1ed6c4a2016-04-21 15:16:11 -070022import android.app.WallpaperManager;
Sunny Goyal594d76d2014-11-06 10:12:54 -080023import android.appwidget.AppWidgetManager;
24import android.appwidget.AppWidgetProviderInfo;
Michael Jurkaa805e1a2013-08-22 15:00:33 +020025import android.content.ActivityNotFoundException;
Sunny Goyalc5c60ad2014-07-14 12:02:01 -070026import android.content.ComponentName;
Winson Chungaafa03c2010-06-11 17:34:16 -070027import android.content.Context;
Michael Jurkaa805e1a2013-08-22 15:00:33 +020028import android.content.Intent;
Rahul Chaturvedi7fc77ca2015-05-19 18:02:16 -070029import android.content.SharedPreferences;
Sunny Goyalc5c60ad2014-07-14 12:02:01 -070030import android.content.pm.ApplicationInfo;
31import android.content.pm.PackageInfo;
32import android.content.pm.PackageManager;
33import android.content.pm.PackageManager.NameNotFoundException;
34import android.content.pm.ResolveInfo;
Winson Chungaafa03c2010-06-11 17:34:16 -070035import android.content.res.Resources;
Sunny Goyal4fbc3822015-02-18 16:46:50 -080036import android.database.Cursor;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080037import android.graphics.Bitmap;
Sunny Goyal4fbc3822015-02-18 16:46:50 -080038import android.graphics.BitmapFactory;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080039import android.graphics.Canvas;
Sunny Goyal95abbb32014-08-04 10:53:22 -070040import android.graphics.Color;
Winson Chungc763c4e2013-07-19 13:49:06 -070041import android.graphics.Matrix;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080042import android.graphics.Paint;
Joe Onoratobf15cb42009-08-07 14:33:40 -070043import android.graphics.PaintFlagsDrawFilter;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080044import android.graphics.Rect;
Winson Chungaafa03c2010-06-11 17:34:16 -070045import android.graphics.drawable.BitmapDrawable;
46import android.graphics.drawable.Drawable;
47import android.graphics.drawable.PaintDrawable;
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -070048import android.os.Build;
Sunny Goyal4e5cc642015-06-25 16:37:44 -070049import android.os.Bundle;
Tony Wickham112ac952015-11-12 12:31:50 -080050import android.os.PowerManager;
Sunny Goyale78e3d72015-09-24 11:23:31 -070051import android.text.Spannable;
52import android.text.SpannableString;
Sunny Goyal5c97f512015-05-19 16:03:28 -070053import android.text.TextUtils;
Sunny Goyale78e3d72015-09-24 11:23:31 -070054import android.text.style.TtsSpan;
Adam Cohen2e6da152015-05-06 11:42:25 -070055import android.util.DisplayMetrics;
Michael Jurkaa805e1a2013-08-22 15:00:33 +020056import android.util.Log;
Sunny Goyal0fe505b2014-08-06 09:55:36 -070057import android.util.Pair;
Sunny Goyal95abbb32014-08-04 10:53:22 -070058import android.util.SparseArray;
Adam Cohen2e6da152015-05-06 11:42:25 -070059import android.util.TypedValue;
Winson Chungc763c4e2013-07-19 13:49:06 -070060import android.view.View;
Michael Jurkaa805e1a2013-08-22 15:00:33 +020061import android.widget.Toast;
Sunny Goyalb1622cc2015-06-10 16:00:42 -070062
Sunny Goyalb84046d2015-10-19 14:03:30 -070063import com.android.launcher3.compat.UserHandleCompat;
Sunny Goyald896ee42015-12-17 11:24:31 -080064import com.android.launcher3.config.FeatureFlags;
Sunny Goyal713edfc2016-05-06 09:58:34 -070065import com.android.launcher3.config.ProviderConfig;
Sunny Goyalfc218302015-09-17 14:59:10 -070066import com.android.launcher3.util.IconNormalizer;
Sunny Goyal6c56c682015-07-16 14:09:05 -070067
Sunny Goyal5b0e6692015-03-19 14:31:19 -070068import java.io.ByteArrayOutputStream;
Sunny Goyal713edfc2016-05-06 09:58:34 -070069import java.io.Closeable;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070070import java.io.IOException;
Sunny Goyal25aba0a2015-07-16 15:07:47 -070071import java.lang.reflect.Method;
Winson Chungc763c4e2013-07-19 13:49:06 -070072import java.util.ArrayList;
Sunny Goyalb1622cc2015-06-10 16:00:42 -070073import java.util.Locale;
Sunny Goyal4e5cc642015-06-25 16:37:44 -070074import java.util.Set;
Sunny Goyal8ac727b2015-09-23 15:38:09 -070075import java.util.concurrent.Executor;
76import java.util.concurrent.LinkedBlockingQueue;
77import java.util.concurrent.ThreadPoolExecutor;
78import java.util.concurrent.TimeUnit;
Winson Chung82b016c2015-05-08 17:00:10 -070079import java.util.regex.Matcher;
80import java.util.regex.Pattern;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080081
82/**
83 * Various utilities shared amongst the Launcher's classes.
84 */
Mathew Inwood72fbec12013-11-19 15:45:07 +000085public final class Utilities {
Rahul Chaturvedi7fc77ca2015-05-19 18:02:16 -070086
Joe Onorato1291a8c2009-09-15 15:07:25 -040087 private static final String TAG = "Launcher.Utilities";
88
The Android Open Source Project31dd5032009-03-03 19:32:27 -080089 private static final Rect sOldBounds = new Rect();
Romain Guy89911d22009-09-28 18:48:49 -070090 private static final Canvas sCanvas = new Canvas();
The Android Open Source Project31dd5032009-03-03 19:32:27 -080091
Winson Chung82b016c2015-05-08 17:00:10 -070092 private static final Pattern sTrimPattern =
93 Pattern.compile("^[\\s|\\p{javaSpaceChar}]*(.*)[\\s|\\p{javaSpaceChar}]*$");
94
The Android Open Source Project31dd5032009-03-03 19:32:27 -080095 static {
96 sCanvas.setDrawFilter(new PaintFlagsDrawFilter(Paint.DITHER_FLAG,
97 Paint.FILTER_BITMAP_FLAG));
98 }
Joe Onorato6665c0f2009-09-02 15:27:24 -070099 static int sColors[] = { 0xffff0000, 0xff00ff00, 0xff0000ff };
100 static int sColorIndex = 0;
101
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700102 private static final int[] sLoc0 = new int[2];
103 private static final int[] sLoc1 = new int[2];
Michael Jurka7ad868b2013-12-12 15:04:25 +0100104
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700105 // TODO: use Build.VERSION_CODES when available
106 public static final boolean ATLEAST_MARSHMALLOW = Build.VERSION.SDK_INT >= 23;
107
108 public static final boolean ATLEAST_LOLLIPOP_MR1 =
109 Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1;
110
111 public static final boolean ATLEAST_LOLLIPOP =
112 Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
113
114 public static final boolean ATLEAST_KITKAT =
115 Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
116
117 public static final boolean ATLEAST_JB_MR1 =
118 Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1;
119
120 public static final boolean ATLEAST_JB_MR2 =
121 Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2;
122
Sunny Goyal6f866092016-03-17 17:04:15 -0700123 // An intent extra to indicate the horizontal scroll of the wallpaper.
124 public static final String EXTRA_WALLPAPER_OFFSET = "com.android.launcher3.WALLPAPER_OFFSET";
125
Sunny Goyal8ac727b2015-09-23 15:38:09 -0700126 // These values are same as that in {@link AsyncTask}.
127 private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
128 private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
129 private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
130 private static final int KEEP_ALIVE = 1;
131 /**
132 * An {@link Executor} to be used with async task with no limit on the queue size.
133 */
134 public static final Executor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(
135 CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
136 TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
137
Rahul Chaturvedi7fc77ca2015-05-19 18:02:16 -0700138 public static final String ALLOW_ROTATION_PREFERENCE_KEY = "pref_allowRotation";
139
Sunny Goyal4bbf4192014-11-11 12:23:59 -0800140 public static boolean isPropertyEnabled(String propertyName) {
Michael Jurka7ad868b2013-12-12 15:04:25 +0100141 return Log.isLoggable(propertyName, Log.VERBOSE);
142 }
143
Sunny Goyal21bf5312015-08-21 11:08:24 -0700144 public static boolean isAllowRotationPrefEnabled(Context context) {
Sunny Goyalf48e5922016-05-12 15:36:20 -0700145 return getPrefs(context).getBoolean(ALLOW_ROTATION_PREFERENCE_KEY,
146 getAllowRotationDefaultValue(context));
147 }
148
149 public static boolean getAllowRotationDefaultValue(Context context) {
Sunny Goyal8f3819b2016-02-23 14:49:22 -0800150 if (isNycOrAbove()) {
151 // If the device was scaled, used the original dimensions to determine if rotation
152 // is allowed of not.
153 try {
154 // TODO: Use the actual field when the API is finalized.
155 int originalDensity =
156 DisplayMetrics.class.getField("DENSITY_DEVICE_STABLE").getInt(null);
157 Resources res = context.getResources();
158 int originalSmallestWidth = res.getConfiguration().smallestScreenWidthDp
159 * res.getDisplayMetrics().densityDpi / originalDensity;
Sunny Goyalf48e5922016-05-12 15:36:20 -0700160 return originalSmallestWidth >= 600;
Sunny Goyal8f3819b2016-02-23 14:49:22 -0800161 } catch (Exception e) {
162 // Ignore
163 }
164 }
Sunny Goyalf48e5922016-05-12 15:36:20 -0700165 return false;
Michael Jurka7ad868b2013-12-12 15:04:25 +0100166 }
167
Vadim Tryshev9de91272015-08-03 18:37:17 -0700168 public static boolean isNycOrAbove() {
169 // TODO(vadimt): Replace using reflection with looking at the API version once
170 // Build.VERSION.SDK_INT gets bumped to 24. b/22942492.
171 try {
172 View.class.getDeclaredField("DRAG_FLAG_OPAQUE");
173 // View.DRAG_FLAG_OPAQUE doesn't exist in M-release, so it's an indication of N+.
174 return true;
175 } catch (NoSuchFieldException e) {
176 return false;
177 }
178 }
179
Sunny Goyal745bad92016-05-02 10:54:12 -0700180 // TODO: Use Intent.ACTION_APPLICATION_PREFERENCES when N SDK is available.
181 public static final String ACTION_APPLICATION_PREFERENCES
182 = "android.intent.action.APPLICATION_PREFERENCES";
183
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700184 public static Bitmap createIconBitmap(Cursor c, int iconIndex, Context context) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -0800185 byte[] data = c.getBlob(iconIndex);
186 try {
187 return createIconBitmap(BitmapFactory.decodeByteArray(data, 0, data.length), context);
188 } catch (Exception e) {
189 return null;
190 }
191 }
192
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -0700193 /**
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700194 * Returns a bitmap suitable for the all apps view. If the package or the resource do not
195 * exist, it returns null.
196 */
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700197 public static Bitmap createIconBitmap(String packageName, String resourceName,
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700198 Context context) {
199 PackageManager packageManager = context.getPackageManager();
200 // the resource
201 try {
202 Resources resources = packageManager.getResourcesForApplication(packageName);
203 if (resources != null) {
204 final int id = resources.getIdentifier(resourceName, null, null);
205 return createIconBitmap(
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700206 resources.getDrawableForDensity(id, LauncherAppState.getInstance()
207 .getInvariantDeviceProfile().fillResIconDpi), context);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700208 }
209 } catch (Exception e) {
210 // Icon not found.
211 }
212 return null;
213 }
214
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700215 private static int getIconBitmapSize() {
216 return LauncherAppState.getInstance().getInvariantDeviceProfile().iconBitmapSize;
217 }
218
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700219 /**
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700220 * Returns a bitmap which is of the appropriate size to be displayed as an icon
Michael Jurka931dc972011-08-05 15:08:15 -0700221 */
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700222 public static Bitmap createIconBitmap(Bitmap icon, Context context) {
223 final int iconBitmapSize = getIconBitmapSize();
224 if (iconBitmapSize == icon.getWidth() && iconBitmapSize == icon.getHeight()) {
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700225 return icon;
226 }
227 return createIconBitmap(new BitmapDrawable(context.getResources(), icon), context);
Michael Jurka931dc972011-08-05 15:08:15 -0700228 }
229
230 /**
Sunny Goyalfc218302015-09-17 14:59:10 -0700231 * Returns a bitmap suitable for the all apps view. The icon is badged for {@param user}.
232 * The bitmap is also visually normalized with other icons.
Sunny Goyalb84046d2015-10-19 14:03:30 -0700233 */
234 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
235 public static Bitmap createBadgedIconBitmap(
236 Drawable icon, UserHandleCompat user, Context context) {
Sunny Goyal531cda62016-03-03 13:19:24 -0800237 float scale = FeatureFlags.LAUNCHER3_DISABLE_ICON_NORMALIZATION ?
238 1 : IconNormalizer.getInstance().getScale(icon);
Sunny Goyalfc218302015-09-17 14:59:10 -0700239 Bitmap bitmap = createIconBitmap(icon, context, scale);
Sunny Goyalb84046d2015-10-19 14:03:30 -0700240 if (Utilities.ATLEAST_LOLLIPOP && user != null
241 && !UserHandleCompat.myUserHandle().equals(user)) {
Sunny Goyale1483fb2016-01-08 12:16:15 -0800242 BitmapDrawable drawable = new FixedSizeBitmapDrawable(bitmap);
Sunny Goyalb84046d2015-10-19 14:03:30 -0700243 Drawable badged = context.getPackageManager().getUserBadgedIcon(
244 drawable, user.getUser());
245 if (badged instanceof BitmapDrawable) {
246 return ((BitmapDrawable) badged).getBitmap();
247 } else {
248 return createIconBitmap(badged, context);
249 }
250 } else {
251 return bitmap;
252 }
253 }
254
255 /**
Michael Jurka931dc972011-08-05 15:08:15 -0700256 * Returns a bitmap suitable for the all apps view.
Joe Onorato6665c0f2009-09-02 15:27:24 -0700257 */
Mathew Inwood72fbec12013-11-19 15:45:07 +0000258 public static Bitmap createIconBitmap(Drawable icon, Context context) {
Sunny Goyalfc218302015-09-17 14:59:10 -0700259 return createIconBitmap(icon, context, 1.0f /* scale */);
260 }
261
262 /**
263 * @param scale the scale to apply before drawing {@param icon} on the canvas
264 */
265 public static Bitmap createIconBitmap(Drawable icon, Context context, float scale) {
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700266 synchronized (sCanvas) {
267 final int iconBitmapSize = getIconBitmapSize();
Joe Onorato6665c0f2009-09-02 15:27:24 -0700268
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700269 int width = iconBitmapSize;
270 int height = iconBitmapSize;
Joe Onorato6665c0f2009-09-02 15:27:24 -0700271
Joe Onorato6665c0f2009-09-02 15:27:24 -0700272 if (icon instanceof PaintDrawable) {
273 PaintDrawable painter = (PaintDrawable) icon;
274 painter.setIntrinsicWidth(width);
275 painter.setIntrinsicHeight(height);
276 } else if (icon instanceof BitmapDrawable) {
277 // Ensure the bitmap has a density.
278 BitmapDrawable bitmapDrawable = (BitmapDrawable) icon;
279 Bitmap bitmap = bitmapDrawable.getBitmap();
Sunny Goyalde9590b2015-09-23 12:56:51 -0700280 if (bitmap != null && bitmap.getDensity() == Bitmap.DENSITY_NONE) {
Joe Onorato6665c0f2009-09-02 15:27:24 -0700281 bitmapDrawable.setTargetDensity(context.getResources().getDisplayMetrics());
282 }
283 }
284 int sourceWidth = icon.getIntrinsicWidth();
285 int sourceHeight = icon.getIntrinsicHeight();
Michael Jurka931dc972011-08-05 15:08:15 -0700286 if (sourceWidth > 0 && sourceHeight > 0) {
Winson Chung5f8afe62013-08-12 16:19:28 -0700287 // Scale the icon proportionally to the icon dimensions
288 final float ratio = (float) sourceWidth / sourceHeight;
289 if (sourceWidth > sourceHeight) {
290 height = (int) (width / ratio);
291 } else if (sourceHeight > sourceWidth) {
292 width = (int) (height * ratio);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700293 }
294 }
295
296 // no intrinsic size --> use default size
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700297 int textureWidth = iconBitmapSize;
298 int textureHeight = iconBitmapSize;
Joe Onorato6665c0f2009-09-02 15:27:24 -0700299
300 final Bitmap bitmap = Bitmap.createBitmap(textureWidth, textureHeight,
301 Bitmap.Config.ARGB_8888);
302 final Canvas canvas = sCanvas;
303 canvas.setBitmap(bitmap);
304
305 final int left = (textureWidth-width) / 2;
306 final int top = (textureHeight-height) / 2;
307
Michael Jurka3a9fced2012-04-13 14:44:29 -0700308 @SuppressWarnings("all") // suppress dead code warning
309 final boolean debug = false;
310 if (debug) {
Joe Onorato6665c0f2009-09-02 15:27:24 -0700311 // draw a big box for the icon for debugging
312 canvas.drawColor(sColors[sColorIndex]);
313 if (++sColorIndex >= sColors.length) sColorIndex = 0;
314 Paint debugPaint = new Paint();
315 debugPaint.setColor(0xffcccc00);
316 canvas.drawRect(left, top, left+width, top+height, debugPaint);
317 }
318
319 sOldBounds.set(icon.getBounds());
320 icon.setBounds(left, top, left+width, top+height);
Sunny Goyalfc218302015-09-17 14:59:10 -0700321 canvas.save(Canvas.MATRIX_SAVE_FLAG);
322 canvas.scale(scale, scale, textureWidth / 2, textureHeight / 2);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700323 icon.draw(canvas);
Sunny Goyalfc218302015-09-17 14:59:10 -0700324 canvas.restore();
Joe Onorato6665c0f2009-09-02 15:27:24 -0700325 icon.setBounds(sOldBounds);
Adam Cohenaaf473c2011-08-03 12:02:47 -0700326 canvas.setBitmap(null);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700327
328 return bitmap;
329 }
330 }
331
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800332 /**
Winson Chungc763c4e2013-07-19 13:49:06 -0700333 * Given a coordinate relative to the descendant, find the coordinate in a parent view's
334 * coordinates.
335 *
336 * @param descendant The descendant to which the passed coordinate is relative.
337 * @param root The root view to make the coordinates relative to.
338 * @param coord The coordinate that we want mapped.
339 * @param includeRootScroll Whether or not to account for the scroll of the descendant:
340 * sometimes this is relevant as in a child's coordinates within the descendant.
341 * @return The factor by which this descendant is scaled relative to this DragLayer. Caution
342 * this scale factor is assumed to be equal in X and Y, and so if at any point this
343 * assumption fails, we will need to return a pair of scale factors.
344 */
345 public static float getDescendantCoordRelativeToParent(View descendant, View root,
346 int[] coord, boolean includeRootScroll) {
347 ArrayList<View> ancestorChain = new ArrayList<View>();
348
349 float[] pt = {coord[0], coord[1]};
350
351 View v = descendant;
352 while(v != root && v != null) {
353 ancestorChain.add(v);
354 v = (View) v.getParent();
355 }
356 ancestorChain.add(root);
357
358 float scale = 1.0f;
359 int count = ancestorChain.size();
360 for (int i = 0; i < count; i++) {
361 View v0 = ancestorChain.get(i);
Winson Chungc763c4e2013-07-19 13:49:06 -0700362 // For TextViews, scroll has a meaning which relates to the text position
363 // which is very strange... ignore the scroll.
364 if (v0 != descendant || includeRootScroll) {
365 pt[0] -= v0.getScrollX();
366 pt[1] -= v0.getScrollY();
367 }
368
369 v0.getMatrix().mapPoints(pt);
370 pt[0] += v0.getLeft();
371 pt[1] += v0.getTop();
372 scale *= v0.getScaleX();
373 }
374
375 coord[0] = (int) Math.round(pt[0]);
376 coord[1] = (int) Math.round(pt[1]);
377 return scale;
378 }
379
380 /**
Sunny Goyalfc218302015-09-17 14:59:10 -0700381 * Inverse of {@link #getDescendantCoordRelativeToParent(View, View, int[], boolean)}.
Winson Chungc763c4e2013-07-19 13:49:06 -0700382 */
383 public static float mapCoordInSelfToDescendent(View descendant, View root,
384 int[] coord) {
385 ArrayList<View> ancestorChain = new ArrayList<View>();
386
387 float[] pt = {coord[0], coord[1]};
388
389 View v = descendant;
390 while(v != root) {
391 ancestorChain.add(v);
392 v = (View) v.getParent();
393 }
394 ancestorChain.add(root);
395
396 float scale = 1.0f;
397 Matrix inverse = new Matrix();
398 int count = ancestorChain.size();
399 for (int i = count - 1; i >= 0; i--) {
400 View ancestor = ancestorChain.get(i);
401 View next = i > 0 ? ancestorChain.get(i-1) : null;
402
403 pt[0] += ancestor.getScrollX();
404 pt[1] += ancestor.getScrollY();
405
406 if (next != null) {
407 pt[0] -= next.getLeft();
408 pt[1] -= next.getTop();
409 next.getMatrix().invert(inverse);
410 inverse.mapPoints(pt);
411 scale *= next.getScaleX();
412 }
413 }
414
415 coord[0] = (int) Math.round(pt[0]);
416 coord[1] = (int) Math.round(pt[1]);
417 return scale;
418 }
419
Jason Monk02dd7ae2014-04-15 15:23:31 -0400420 /**
421 * Utility method to determine whether the given point, in local coordinates,
422 * is inside the view, where the area of the view is expanded by the slop factor.
423 * This method is called while processing touch-move events to determine if the event
424 * is still within the view.
425 */
426 public static boolean pointInView(View v, float localX, float localY, float slop) {
427 return localX >= -slop && localY >= -slop && localX < (v.getWidth() + slop) &&
428 localY < (v.getHeight() + slop);
429 }
430
Adam Cohen63f1ec02014-08-12 09:23:13 -0700431 public static int[] getCenterDeltaInScreenSpace(View v0, View v1, int[] delta) {
432 v0.getLocationInWindow(sLoc0);
433 v1.getLocationInWindow(sLoc1);
434
435 sLoc0[0] += (v0.getMeasuredWidth() * v0.getScaleX()) / 2;
436 sLoc0[1] += (v0.getMeasuredHeight() * v0.getScaleY()) / 2;
437 sLoc1[0] += (v1.getMeasuredWidth() * v1.getScaleX()) / 2;
438 sLoc1[1] += (v1.getMeasuredHeight() * v1.getScaleY()) / 2;
439
440 if (delta == null) {
441 delta = new int[2];
442 }
443
444 delta[0] = sLoc1[0] - sLoc0[0];
445 delta[1] = sLoc1[1] - sLoc0[1];
446
447 return delta;
448 }
449
Winson Chung3a6e7f32013-10-09 15:50:52 -0700450 public static void scaleRectAboutCenter(Rect r, float scale) {
Sunny Goyal106bf642015-07-16 12:18:06 -0700451 if (scale != 1.0f) {
452 int cx = r.centerX();
453 int cy = r.centerY();
454 r.offset(-cx, -cy);
455
456 r.left = (int) (r.left * scale + 0.5f);
457 r.top = (int) (r.top * scale + 0.5f);
458 r.right = (int) (r.right * scale + 0.5f);
459 r.bottom = (int) (r.bottom * scale + 0.5f);
460
461 r.offset(cx, cy);
462 }
Winson Chung3a6e7f32013-10-09 15:50:52 -0700463 }
464
Michael Jurkaa805e1a2013-08-22 15:00:33 +0200465 public static void startActivityForResultSafely(
466 Activity activity, Intent intent, int requestCode) {
467 try {
468 activity.startActivityForResult(intent, requestCode);
469 } catch (ActivityNotFoundException e) {
470 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
471 } catch (SecurityException e) {
472 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
473 Log.e(TAG, "Launcher does not have the permission to launch " + intent +
474 ". Make sure to create a MAIN intent-filter for the corresponding activity " +
475 "or use the exported attribute for this activity.", e);
476 }
477 }
Sunny Goyalc5c60ad2014-07-14 12:02:01 -0700478
479 static boolean isSystemApp(Context context, Intent intent) {
480 PackageManager pm = context.getPackageManager();
481 ComponentName cn = intent.getComponent();
482 String packageName = null;
483 if (cn == null) {
484 ResolveInfo info = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
485 if ((info != null) && (info.activityInfo != null)) {
486 packageName = info.activityInfo.packageName;
487 }
488 } else {
489 packageName = cn.getPackageName();
490 }
491 if (packageName != null) {
492 try {
493 PackageInfo info = pm.getPackageInfo(packageName, 0);
494 return (info != null) && (info.applicationInfo != null) &&
495 ((info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
496 } catch (NameNotFoundException e) {
497 return false;
498 }
499 } else {
500 return false;
501 }
502 }
Sunny Goyal95abbb32014-08-04 10:53:22 -0700503
504 /**
505 * This picks a dominant color, looking for high-saturation, high-value, repeated hues.
506 * @param bitmap The bitmap to scan
507 * @param samples The approximate max number of samples to use.
508 */
509 static int findDominantColorByHue(Bitmap bitmap, int samples) {
510 final int height = bitmap.getHeight();
511 final int width = bitmap.getWidth();
512 int sampleStride = (int) Math.sqrt((height * width) / samples);
513 if (sampleStride < 1) {
514 sampleStride = 1;
515 }
516
517 // This is an out-param, for getting the hsv values for an rgb
518 float[] hsv = new float[3];
519
520 // First get the best hue, by creating a histogram over 360 hue buckets,
521 // where each pixel contributes a score weighted by saturation, value, and alpha.
522 float[] hueScoreHistogram = new float[360];
523 float highScore = -1;
524 int bestHue = -1;
525
526 for (int y = 0; y < height; y += sampleStride) {
527 for (int x = 0; x < width; x += sampleStride) {
528 int argb = bitmap.getPixel(x, y);
529 int alpha = 0xFF & (argb >> 24);
530 if (alpha < 0x80) {
531 // Drop mostly-transparent pixels.
532 continue;
533 }
534 // Remove the alpha channel.
535 int rgb = argb | 0xFF000000;
536 Color.colorToHSV(rgb, hsv);
537 // Bucket colors by the 360 integer hues.
538 int hue = (int) hsv[0];
539 if (hue < 0 || hue >= hueScoreHistogram.length) {
540 // Defensively avoid array bounds violations.
541 continue;
542 }
543 float score = hsv[1] * hsv[2];
544 hueScoreHistogram[hue] += score;
545 if (hueScoreHistogram[hue] > highScore) {
546 highScore = hueScoreHistogram[hue];
547 bestHue = hue;
548 }
549 }
550 }
551
552 SparseArray<Float> rgbScores = new SparseArray<Float>();
553 int bestColor = 0xff000000;
554 highScore = -1;
555 // Go back over the RGB colors that match the winning hue,
556 // creating a histogram of weighted s*v scores, for up to 100*100 [s,v] buckets.
557 // The highest-scoring RGB color wins.
558 for (int y = 0; y < height; y += sampleStride) {
559 for (int x = 0; x < width; x += sampleStride) {
560 int rgb = bitmap.getPixel(x, y) | 0xff000000;
561 Color.colorToHSV(rgb, hsv);
562 int hue = (int) hsv[0];
563 if (hue == bestHue) {
564 float s = hsv[1];
565 float v = hsv[2];
566 int bucket = (int) (s * 100) + (int) (v * 10000);
567 // Score by cumulative saturation * value.
568 float score = s * v;
569 Float oldTotal = rgbScores.get(bucket);
570 float newTotal = oldTotal == null ? score : oldTotal + score;
571 rgbScores.put(bucket, newTotal);
572 if (newTotal > highScore) {
573 highScore = newTotal;
574 // All the colors in the winning bucket are very similar. Last in wins.
575 bestColor = rgb;
576 }
577 }
578 }
579 }
580 return bestColor;
581 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700582
583 /*
584 * Finds a system apk which had a broadcast receiver listening to a particular action.
585 * @param action intent action used to find the apk
586 * @return a pair of apk package name and the resources.
587 */
588 static Pair<String, Resources> findSystemApk(String action, PackageManager pm) {
589 final Intent intent = new Intent(action);
590 for (ResolveInfo info : pm.queryBroadcastReceivers(intent, 0)) {
591 if (info.activityInfo != null &&
592 (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
593 final String packageName = info.activityInfo.packageName;
594 try {
595 final Resources res = pm.getResourcesForApplication(packageName);
596 return Pair.create(packageName, res);
597 } catch (NameNotFoundException e) {
598 Log.w(TAG, "Failed to find resources for " + packageName);
599 }
600 }
601 }
602 return null;
603 }
Sunny Goyalfafca522014-11-03 11:30:01 -0800604
Sunny Goyal594d76d2014-11-06 10:12:54 -0800605 /**
606 * Returns a widget with category {@link AppWidgetProviderInfo#WIDGET_CATEGORY_SEARCHBOX}
607 * provided by the same package which is set to be global search activity.
608 * If widgetCategory is not supported, or no such widget is found, returns the first widget
609 * provided by the package.
610 */
611 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
612 public static AppWidgetProviderInfo getSearchWidgetProvider(Context context) {
613 SearchManager searchManager =
614 (SearchManager) context.getSystemService(Context.SEARCH_SERVICE);
615 ComponentName searchComponent = searchManager.getGlobalSearchActivity();
616 if (searchComponent == null) return null;
617 String providerPkg = searchComponent.getPackageName();
618
619 AppWidgetProviderInfo defaultWidgetForSearchPackage = null;
620
621 AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
622 for (AppWidgetProviderInfo info : appWidgetManager.getInstalledProviders()) {
623 if (info.provider.getPackageName().equals(providerPkg)) {
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700624 if (ATLEAST_JB_MR1) {
Sunny Goyal594d76d2014-11-06 10:12:54 -0800625 if ((info.widgetCategory & AppWidgetProviderInfo.WIDGET_CATEGORY_SEARCHBOX) != 0) {
626 return info;
627 } else if (defaultWidgetForSearchPackage == null) {
628 defaultWidgetForSearchPackage = info;
629 }
630 } else {
631 return info;
632 }
633 }
634 }
635 return defaultWidgetForSearchPackage;
636 }
Sunny Goyal08f72612015-01-05 13:41:43 -0800637
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700638 /**
639 * Compresses the bitmap to a byte array for serialization.
640 */
641 public static byte[] flattenBitmap(Bitmap bitmap) {
642 // Try go guesstimate how much space the icon will take when serialized
643 // to avoid unnecessary allocations/copies during the write.
644 int size = bitmap.getWidth() * bitmap.getHeight() * 4;
645 ByteArrayOutputStream out = new ByteArrayOutputStream(size);
646 try {
647 bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
648 out.flush();
649 out.close();
650 return out.toByteArray();
651 } catch (IOException e) {
652 Log.w(TAG, "Could not write bitmap");
653 return null;
654 }
655 }
656
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700657 /**
658 * Find the first vacant cell, if there is one.
659 *
660 * @param vacant Holds the x and y coordinate of the vacant cell
661 * @param spanX Horizontal cell span.
662 * @param spanY Vertical cell span.
663 *
664 * @return true if a vacant cell was found
665 */
666 public static boolean findVacantCell(int[] vacant, int spanX, int spanY,
667 int xCount, int yCount, boolean[][] occupied) {
668
669 for (int y = 0; (y + spanY) <= yCount; y++) {
670 for (int x = 0; (x + spanX) <= xCount; x++) {
671 boolean available = !occupied[x][y];
672 out: for (int i = x; i < x + spanX; i++) {
673 for (int j = y; j < y + spanY; j++) {
674 available = available && !occupied[i][j];
675 if (!available) break out;
676 }
677 }
678
679 if (available) {
680 vacant[0] = x;
681 vacant[1] = y;
682 return true;
683 }
684 }
685 }
686
687 return false;
688 }
Winson Chung82b016c2015-05-08 17:00:10 -0700689
690 /**
691 * Trims the string, removing all whitespace at the beginning and end of the string.
692 * Non-breaking whitespaces are also removed.
693 */
694 public static String trim(CharSequence s) {
Winson Chungafa77e92015-05-15 12:04:03 -0700695 if (s == null) {
696 return null;
697 }
698
Winson Chung82b016c2015-05-08 17:00:10 -0700699 // Just strip any sequence of whitespace or java space characters from the beginning and end
700 Matcher m = sTrimPattern.matcher(s);
701 return m.replaceAll("$1");
702 }
Sunny Goyal70660032015-05-14 00:07:08 -0700703
Winson Chung2c6e5cc2015-06-01 14:38:24 -0700704 /**
705 * Calculates the height of a given string at a specific text size.
706 */
707 public static float calculateTextHeight(float textSizePx) {
708 Paint p = new Paint();
709 p.setTextSize(textSizePx);
710 Paint.FontMetrics fm = p.getFontMetrics();
711 return -fm.top + fm.bottom;
712 }
713
Winson Chungb1777442015-06-16 13:35:04 -0700714 /**
715 * Convenience println with multiple args.
716 */
717 public static void println(String key, Object... args) {
718 StringBuilder b = new StringBuilder();
719 b.append(key);
720 b.append(": ");
721 boolean isFirstArgument = true;
722 for (Object arg : args) {
723 if (isFirstArgument) {
724 isFirstArgument = false;
725 } else {
726 b.append(", ");
727 }
728 b.append(arg);
729 }
730 System.out.println(b.toString());
731 }
732
Sunny Goyal70660032015-05-14 00:07:08 -0700733 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
734 public static boolean isRtl(Resources res) {
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700735 return ATLEAST_JB_MR1 &&
Sunny Goyal70660032015-05-14 00:07:08 -0700736 (res.getConfiguration().getLayoutDirection() == View.LAYOUT_DIRECTION_RTL);
737 }
Hyunyoung Song2bd3d7d2015-05-21 13:04:53 -0700738
Sunny Goyal5c97f512015-05-19 16:03:28 -0700739 /**
740 * Returns true if the intent is a valid launch intent for a launcher activity of an app.
741 * This is used to identify shortcuts which are different from the ones exposed by the
742 * applications' manifest file.
743 *
744 * @param launchIntent The intent that will be launched when the shortcut is clicked.
745 */
746 public static boolean isLauncherAppTarget(Intent launchIntent) {
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700747 if (launchIntent != null
Sunny Goyal5c97f512015-05-19 16:03:28 -0700748 && Intent.ACTION_MAIN.equals(launchIntent.getAction())
749 && launchIntent.getComponent() != null
750 && launchIntent.getCategories() != null
751 && launchIntent.getCategories().size() == 1
752 && launchIntent.hasCategory(Intent.CATEGORY_LAUNCHER)
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700753 && TextUtils.isEmpty(launchIntent.getDataString())) {
754 // An app target can either have no extra or have ItemInfo.EXTRA_PROFILE.
755 Bundle extras = launchIntent.getExtras();
756 if (extras == null) {
757 return true;
758 } else {
759 Set<String> keys = extras.keySet();
760 return keys.size() == 1 && keys.contains(ItemInfo.EXTRA_PROFILE);
761 }
762 };
763 return false;
Sunny Goyal5c97f512015-05-19 16:03:28 -0700764 }
Adam Cohen2e6da152015-05-06 11:42:25 -0700765
766 public static float dpiFromPx(int size, DisplayMetrics metrics){
767 float densityRatio = (float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT;
768 return (size / densityRatio);
769 }
770 public static int pxFromDp(float size, DisplayMetrics metrics) {
771 return (int) Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
772 size, metrics));
773 }
774 public static int pxFromSp(float size, DisplayMetrics metrics) {
775 return (int) Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
776 size, metrics));
777 }
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700778
779 public static String createDbSelectionQuery(String columnName, Iterable<?> values) {
780 return String.format(Locale.ENGLISH, "%s IN (%s)", columnName, TextUtils.join(", ", values));
781 }
Sunny Goyal25aba0a2015-07-16 15:07:47 -0700782
Sunny Goyal25aba0a2015-07-16 15:07:47 -0700783 public static boolean isBootCompleted() {
784 try {
785 Class clazz = Class.forName("android.os.SystemProperties");
786 Method getter = clazz.getDeclaredMethod("get", String.class);
787 String value = (String) getter.invoke(null, "sys.boot_completed");
788 return "1".equals(value);
789 } catch (Exception e) {
790 Log.d(TAG, "Unable to read system properties");
791 // Assume that boot has completed
792 return true;
793 }
794 }
Tony Wickham29d853c2015-09-08 10:35:56 -0700795
796 /**
797 * Ensures that a value is within given bounds. Specifically:
798 * If value is less than lowerBound, return lowerBound; else if value is greater than upperBound,
799 * return upperBound; else return value unchanged.
800 */
Tony Wickhamf549dab2016-05-16 09:54:06 -0700801 public static int boundToRange(int value, int lowerBound, int upperBound) {
802 return Math.max(lowerBound, Math.min(value, upperBound));
803 }
804
805 /**
806 * @see #boundToRange(int, int, int).
807 */
808 public static float boundToRange(float value, float lowerBound, float upperBound) {
Tony Wickham29d853c2015-09-08 10:35:56 -0700809 return Math.max(lowerBound, Math.min(value, upperBound));
810 }
Sunny Goyal9d438082015-09-25 11:50:16 -0700811
Sunny Goyale78e3d72015-09-24 11:23:31 -0700812 /**
813 * Wraps a message with a TTS span, so that a different message is spoken than
814 * what is getting displayed.
815 * @param msg original message
816 * @param ttsMsg message to be spoken
817 */
818 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
819 public static CharSequence wrapForTts(CharSequence msg, String ttsMsg) {
820 if (Utilities.ATLEAST_LOLLIPOP) {
821 SpannableString spanned = new SpannableString(msg);
822 spanned.setSpan(new TtsSpan.TextBuilder(ttsMsg).build(),
823 0, spanned.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
824 return spanned;
825 } else {
826 return msg;
827 }
828 }
Winson12fb9fc2015-10-01 15:34:08 -0700829
830 /**
831 * Replacement for Long.compare() which was added in API level 19.
832 */
833 public static int longCompare(long lhs, long rhs) {
834 return lhs < rhs ? -1 : (lhs == rhs ? 0 : 1);
835 }
Sunny Goyalf7258242015-10-19 16:59:07 -0700836
837 public static SharedPreferences getPrefs(Context context) {
838 return context.getSharedPreferences(
839 LauncherFiles.SHARED_PREFERENCES_KEY, Context.MODE_PRIVATE);
840 }
Tony Wickham112ac952015-11-12 12:31:50 -0800841
842 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
843 public static boolean isPowerSaverOn(Context context) {
844 PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
845 return ATLEAST_LOLLIPOP && powerManager.isPowerSaveMode();
846 }
Sunny Goyale1483fb2016-01-08 12:16:15 -0800847
Sunny Goyal1ed6c4a2016-04-21 15:16:11 -0700848 public static boolean isWallapaperAllowed(Context context) {
849 if (isNycOrAbove()) {
850 try {
851 WallpaperManager wm = context.getSystemService(WallpaperManager.class);
Kenny Guy367da9f2016-05-25 19:22:14 +0100852 return (Boolean) wm.getClass().getDeclaredMethod("isSetWallpaperAllowed")
Sunny Goyal1ed6c4a2016-04-21 15:16:11 -0700853 .invoke(wm);
854 } catch (Exception e) { }
855 }
856 return true;
857 }
858
Sunny Goyal713edfc2016-05-06 09:58:34 -0700859 public static void closeSilently(Closeable c) {
860 if (c != null) {
861 try {
862 c.close();
863 } catch (IOException e) {
864 if (ProviderConfig.IS_DOGFOOD_BUILD) {
865 Log.d(TAG, "Error closing", e);
866 }
867 }
868 }
869 }
870
Sunny Goyale1483fb2016-01-08 12:16:15 -0800871 /**
Sunny Goyal3f732192016-05-13 13:48:44 -0700872 * Returns true if {@param original} contains all entries defined in {@param updates} and
873 * have the same value.
874 * The comparison uses {@link Object#equals(Object)} to compare the values.
875 */
876 public static boolean containsAll(Bundle original, Bundle updates) {
877 for (String key : updates.keySet()) {
878 Object value1 = updates.get(key);
879 Object value2 = original.get(key);
880 if (value1 == null) {
881 if (value2 != null) {
882 return false;
883 }
884 } else if (!value1.equals(value2)) {
885 return false;
886 }
887 }
888 return true;
889 }
890
891 /**
Sunny Goyale1483fb2016-01-08 12:16:15 -0800892 * An extension of {@link BitmapDrawable} which returns the bitmap pixel size as intrinsic size.
893 * This allows the badging to be done based on the action bitmap size rather than
894 * the scaled bitmap size.
895 */
896 private static class FixedSizeBitmapDrawable extends BitmapDrawable {
897
898 public FixedSizeBitmapDrawable(Bitmap bitmap) {
899 super(null, bitmap);
900 }
901
902 @Override
903 public int getIntrinsicHeight() {
904 return getBitmap().getWidth();
905 }
906
907 @Override
908 public int getIntrinsicWidth() {
909 return getBitmap().getWidth();
910 }
911 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800912}