blob: cedbe74c74bb0288b2e74fc4b462c4da8293398c [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 Goyal1ed6c4a2016-04-21 15:16:11 -070021import android.app.WallpaperManager;
Michael Jurkaa805e1a2013-08-22 15:00:33 +020022import android.content.ActivityNotFoundException;
Sunny Goyalc5c60ad2014-07-14 12:02:01 -070023import android.content.ComponentName;
Winson Chungaafa03c2010-06-11 17:34:16 -070024import android.content.Context;
Michael Jurkaa805e1a2013-08-22 15:00:33 +020025import android.content.Intent;
Rahul Chaturvedi7fc77ca2015-05-19 18:02:16 -070026import android.content.SharedPreferences;
Sunny Goyalc5c60ad2014-07-14 12:02:01 -070027import android.content.pm.ApplicationInfo;
28import android.content.pm.PackageInfo;
29import android.content.pm.PackageManager;
30import android.content.pm.PackageManager.NameNotFoundException;
31import android.content.pm.ResolveInfo;
Winson Chungaafa03c2010-06-11 17:34:16 -070032import android.content.res.Resources;
Andrew Sappersteinabef55a2016-06-19 12:49:00 -070033import android.content.res.TypedArray;
Sunny Goyal4fbc3822015-02-18 16:46:50 -080034import android.database.Cursor;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080035import android.graphics.Bitmap;
Sunny Goyal4fbc3822015-02-18 16:46:50 -080036import android.graphics.BitmapFactory;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080037import android.graphics.Canvas;
Sunny Goyal95abbb32014-08-04 10:53:22 -070038import android.graphics.Color;
Winson Chungc763c4e2013-07-19 13:49:06 -070039import android.graphics.Matrix;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080040import android.graphics.Paint;
Joe Onoratobf15cb42009-08-07 14:33:40 -070041import android.graphics.PaintFlagsDrawFilter;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080042import android.graphics.Rect;
Winson Chungaafa03c2010-06-11 17:34:16 -070043import android.graphics.drawable.BitmapDrawable;
44import android.graphics.drawable.Drawable;
45import android.graphics.drawable.PaintDrawable;
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -070046import android.os.Build;
Sunny Goyal9994b2b2016-06-23 14:17:24 -070047import android.os.Build.VERSION;
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;
Tony Wickham1bce7fd2016-04-28 17:39:03 -070059import android.view.MotionEvent;
Winson Chungc763c4e2013-07-19 13:49:06 -070060import android.view.View;
Tony Wickham1bce7fd2016-04-28 17:39:03 -070061import android.view.ViewParent;
Michael Jurkaa805e1a2013-08-22 15:00:33 +020062import android.widget.Toast;
Sunny Goyalb1622cc2015-06-10 16:00:42 -070063
Sunny Goyalb84046d2015-10-19 14:03:30 -070064import com.android.launcher3.compat.UserHandleCompat;
Sunny Goyald896ee42015-12-17 11:24:31 -080065import com.android.launcher3.config.FeatureFlags;
Sunny Goyal713edfc2016-05-06 09:58:34 -070066import com.android.launcher3.config.ProviderConfig;
Sunny Goyalfc218302015-09-17 14:59:10 -070067import com.android.launcher3.util.IconNormalizer;
Sunny Goyal6c56c682015-07-16 14:09:05 -070068
Sunny Goyal5b0e6692015-03-19 14:31:19 -070069import java.io.ByteArrayOutputStream;
Sunny Goyal713edfc2016-05-06 09:58:34 -070070import java.io.Closeable;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070071import java.io.IOException;
Tony Wickham1bce7fd2016-04-28 17:39:03 -070072import java.lang.reflect.InvocationTargetException;
Sunny Goyal25aba0a2015-07-16 15:07:47 -070073import java.lang.reflect.Method;
Winson Chungc763c4e2013-07-19 13:49:06 -070074import java.util.ArrayList;
Tony Wickham1bce7fd2016-04-28 17:39:03 -070075import java.util.Collection;
Sunny Goyalb1622cc2015-06-10 16:00:42 -070076import java.util.Locale;
Sunny Goyal4e5cc642015-06-25 16:37:44 -070077import java.util.Set;
Sunny Goyal8ac727b2015-09-23 15:38:09 -070078import java.util.concurrent.Executor;
79import java.util.concurrent.LinkedBlockingQueue;
80import java.util.concurrent.ThreadPoolExecutor;
81import java.util.concurrent.TimeUnit;
Winson Chung82b016c2015-05-08 17:00:10 -070082import java.util.regex.Matcher;
83import java.util.regex.Pattern;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080084
85/**
86 * Various utilities shared amongst the Launcher's classes.
87 */
Mathew Inwood72fbec12013-11-19 15:45:07 +000088public final class Utilities {
Rahul Chaturvedi7fc77ca2015-05-19 18:02:16 -070089
Joe Onorato1291a8c2009-09-15 15:07:25 -040090 private static final String TAG = "Launcher.Utilities";
91
The Android Open Source Project31dd5032009-03-03 19:32:27 -080092 private static final Rect sOldBounds = new Rect();
Romain Guy89911d22009-09-28 18:48:49 -070093 private static final Canvas sCanvas = new Canvas();
The Android Open Source Project31dd5032009-03-03 19:32:27 -080094
Winson Chung82b016c2015-05-08 17:00:10 -070095 private static final Pattern sTrimPattern =
96 Pattern.compile("^[\\s|\\p{javaSpaceChar}]*(.*)[\\s|\\p{javaSpaceChar}]*$");
97
The Android Open Source Project31dd5032009-03-03 19:32:27 -080098 static {
99 sCanvas.setDrawFilter(new PaintFlagsDrawFilter(Paint.DITHER_FLAG,
100 Paint.FILTER_BITMAP_FLAG));
101 }
Joe Onorato6665c0f2009-09-02 15:27:24 -0700102 static int sColors[] = { 0xffff0000, 0xff00ff00, 0xff0000ff };
103 static int sColorIndex = 0;
104
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700105 private static final int[] sLoc0 = new int[2];
106 private static final int[] sLoc1 = new int[2];
Michael Jurka7ad868b2013-12-12 15:04:25 +0100107
Sunny Goyal9994b2b2016-06-23 14:17:24 -0700108 public static boolean isNycMR1OrAbove() {
109 // TODO: Use the check from support lib
110 return !"REL".equals(VERSION.CODENAME)
111 && "NMR1".compareTo(VERSION.CODENAME) <= 0;
112 }
113
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700114 // TODO: use Build.VERSION_CODES when available
115 public static final boolean ATLEAST_MARSHMALLOW = Build.VERSION.SDK_INT >= 23;
116
117 public static final boolean ATLEAST_LOLLIPOP_MR1 =
118 Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1;
119
120 public static final boolean ATLEAST_LOLLIPOP =
121 Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
122
123 public static final boolean ATLEAST_KITKAT =
124 Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
125
126 public static final boolean ATLEAST_JB_MR1 =
127 Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1;
128
129 public static final boolean ATLEAST_JB_MR2 =
130 Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2;
131
Sunny Goyal6f866092016-03-17 17:04:15 -0700132 // An intent extra to indicate the horizontal scroll of the wallpaper.
133 public static final String EXTRA_WALLPAPER_OFFSET = "com.android.launcher3.WALLPAPER_OFFSET";
134
Sunny Goyal8ac727b2015-09-23 15:38:09 -0700135 // These values are same as that in {@link AsyncTask}.
136 private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
137 private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
138 private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
139 private static final int KEEP_ALIVE = 1;
140 /**
141 * An {@link Executor} to be used with async task with no limit on the queue size.
142 */
143 public static final Executor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(
144 CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
145 TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
146
Rahul Chaturvedi7fc77ca2015-05-19 18:02:16 -0700147 public static final String ALLOW_ROTATION_PREFERENCE_KEY = "pref_allowRotation";
148
Sunny Goyal4bbf4192014-11-11 12:23:59 -0800149 public static boolean isPropertyEnabled(String propertyName) {
Michael Jurka7ad868b2013-12-12 15:04:25 +0100150 return Log.isLoggable(propertyName, Log.VERBOSE);
151 }
152
Sunny Goyal21bf5312015-08-21 11:08:24 -0700153 public static boolean isAllowRotationPrefEnabled(Context context) {
Sunny Goyalf48e5922016-05-12 15:36:20 -0700154 return getPrefs(context).getBoolean(ALLOW_ROTATION_PREFERENCE_KEY,
155 getAllowRotationDefaultValue(context));
156 }
157
158 public static boolean getAllowRotationDefaultValue(Context context) {
Sunny Goyal8f3819b2016-02-23 14:49:22 -0800159 if (isNycOrAbove()) {
160 // If the device was scaled, used the original dimensions to determine if rotation
161 // is allowed of not.
162 try {
163 // TODO: Use the actual field when the API is finalized.
164 int originalDensity =
165 DisplayMetrics.class.getField("DENSITY_DEVICE_STABLE").getInt(null);
166 Resources res = context.getResources();
167 int originalSmallestWidth = res.getConfiguration().smallestScreenWidthDp
168 * res.getDisplayMetrics().densityDpi / originalDensity;
Sunny Goyalf48e5922016-05-12 15:36:20 -0700169 return originalSmallestWidth >= 600;
Sunny Goyal8f3819b2016-02-23 14:49:22 -0800170 } catch (Exception e) {
171 // Ignore
172 }
173 }
Sunny Goyalf48e5922016-05-12 15:36:20 -0700174 return false;
Michael Jurka7ad868b2013-12-12 15:04:25 +0100175 }
176
Vadim Tryshev9de91272015-08-03 18:37:17 -0700177 public static boolean isNycOrAbove() {
178 // TODO(vadimt): Replace using reflection with looking at the API version once
179 // Build.VERSION.SDK_INT gets bumped to 24. b/22942492.
180 try {
181 View.class.getDeclaredField("DRAG_FLAG_OPAQUE");
182 // View.DRAG_FLAG_OPAQUE doesn't exist in M-release, so it's an indication of N+.
183 return true;
184 } catch (NoSuchFieldException e) {
185 return false;
186 }
187 }
188
Sunny Goyal745bad92016-05-02 10:54:12 -0700189 // TODO: Use Intent.ACTION_APPLICATION_PREFERENCES when N SDK is available.
190 public static final String ACTION_APPLICATION_PREFERENCES
191 = "android.intent.action.APPLICATION_PREFERENCES";
192
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700193 public static Bitmap createIconBitmap(Cursor c, int iconIndex, Context context) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -0800194 byte[] data = c.getBlob(iconIndex);
195 try {
196 return createIconBitmap(BitmapFactory.decodeByteArray(data, 0, data.length), context);
197 } catch (Exception e) {
198 return null;
199 }
200 }
201
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -0700202 /**
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700203 * Returns a bitmap suitable for the all apps view. If the package or the resource do not
204 * exist, it returns null.
205 */
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700206 public static Bitmap createIconBitmap(String packageName, String resourceName,
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700207 Context context) {
208 PackageManager packageManager = context.getPackageManager();
209 // the resource
210 try {
211 Resources resources = packageManager.getResourcesForApplication(packageName);
212 if (resources != null) {
213 final int id = resources.getIdentifier(resourceName, null, null);
214 return createIconBitmap(
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700215 resources.getDrawableForDensity(id, LauncherAppState.getInstance()
216 .getInvariantDeviceProfile().fillResIconDpi), context);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700217 }
218 } catch (Exception e) {
219 // Icon not found.
220 }
221 return null;
222 }
223
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700224 private static int getIconBitmapSize() {
225 return LauncherAppState.getInstance().getInvariantDeviceProfile().iconBitmapSize;
226 }
227
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700228 /**
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700229 * Returns a bitmap which is of the appropriate size to be displayed as an icon
Michael Jurka931dc972011-08-05 15:08:15 -0700230 */
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700231 public static Bitmap createIconBitmap(Bitmap icon, Context context) {
232 final int iconBitmapSize = getIconBitmapSize();
233 if (iconBitmapSize == icon.getWidth() && iconBitmapSize == icon.getHeight()) {
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700234 return icon;
235 }
236 return createIconBitmap(new BitmapDrawable(context.getResources(), icon), context);
Michael Jurka931dc972011-08-05 15:08:15 -0700237 }
238
239 /**
Sunny Goyalfc218302015-09-17 14:59:10 -0700240 * Returns a bitmap suitable for the all apps view. The icon is badged for {@param user}.
241 * The bitmap is also visually normalized with other icons.
Sunny Goyalb84046d2015-10-19 14:03:30 -0700242 */
243 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
244 public static Bitmap createBadgedIconBitmap(
245 Drawable icon, UserHandleCompat user, Context context) {
Sunny Goyal531cda62016-03-03 13:19:24 -0800246 float scale = FeatureFlags.LAUNCHER3_DISABLE_ICON_NORMALIZATION ?
247 1 : IconNormalizer.getInstance().getScale(icon);
Sunny Goyalfc218302015-09-17 14:59:10 -0700248 Bitmap bitmap = createIconBitmap(icon, context, scale);
Sunny Goyalb84046d2015-10-19 14:03:30 -0700249 if (Utilities.ATLEAST_LOLLIPOP && user != null
250 && !UserHandleCompat.myUserHandle().equals(user)) {
Sunny Goyale1483fb2016-01-08 12:16:15 -0800251 BitmapDrawable drawable = new FixedSizeBitmapDrawable(bitmap);
Sunny Goyalb84046d2015-10-19 14:03:30 -0700252 Drawable badged = context.getPackageManager().getUserBadgedIcon(
253 drawable, user.getUser());
254 if (badged instanceof BitmapDrawable) {
255 return ((BitmapDrawable) badged).getBitmap();
256 } else {
257 return createIconBitmap(badged, context);
258 }
259 } else {
260 return bitmap;
261 }
262 }
263
264 /**
Michael Jurka931dc972011-08-05 15:08:15 -0700265 * Returns a bitmap suitable for the all apps view.
Joe Onorato6665c0f2009-09-02 15:27:24 -0700266 */
Mathew Inwood72fbec12013-11-19 15:45:07 +0000267 public static Bitmap createIconBitmap(Drawable icon, Context context) {
Sunny Goyalfc218302015-09-17 14:59:10 -0700268 return createIconBitmap(icon, context, 1.0f /* scale */);
269 }
270
271 /**
272 * @param scale the scale to apply before drawing {@param icon} on the canvas
273 */
274 public static Bitmap createIconBitmap(Drawable icon, Context context, float scale) {
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700275 synchronized (sCanvas) {
276 final int iconBitmapSize = getIconBitmapSize();
Joe Onorato6665c0f2009-09-02 15:27:24 -0700277
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700278 int width = iconBitmapSize;
279 int height = iconBitmapSize;
Joe Onorato6665c0f2009-09-02 15:27:24 -0700280
Joe Onorato6665c0f2009-09-02 15:27:24 -0700281 if (icon instanceof PaintDrawable) {
282 PaintDrawable painter = (PaintDrawable) icon;
283 painter.setIntrinsicWidth(width);
284 painter.setIntrinsicHeight(height);
285 } else if (icon instanceof BitmapDrawable) {
286 // Ensure the bitmap has a density.
287 BitmapDrawable bitmapDrawable = (BitmapDrawable) icon;
288 Bitmap bitmap = bitmapDrawable.getBitmap();
Sunny Goyalde9590b2015-09-23 12:56:51 -0700289 if (bitmap != null && bitmap.getDensity() == Bitmap.DENSITY_NONE) {
Joe Onorato6665c0f2009-09-02 15:27:24 -0700290 bitmapDrawable.setTargetDensity(context.getResources().getDisplayMetrics());
291 }
292 }
293 int sourceWidth = icon.getIntrinsicWidth();
294 int sourceHeight = icon.getIntrinsicHeight();
Michael Jurka931dc972011-08-05 15:08:15 -0700295 if (sourceWidth > 0 && sourceHeight > 0) {
Winson Chung5f8afe62013-08-12 16:19:28 -0700296 // Scale the icon proportionally to the icon dimensions
297 final float ratio = (float) sourceWidth / sourceHeight;
298 if (sourceWidth > sourceHeight) {
299 height = (int) (width / ratio);
300 } else if (sourceHeight > sourceWidth) {
301 width = (int) (height * ratio);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700302 }
303 }
304
305 // no intrinsic size --> use default size
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700306 int textureWidth = iconBitmapSize;
307 int textureHeight = iconBitmapSize;
Joe Onorato6665c0f2009-09-02 15:27:24 -0700308
309 final Bitmap bitmap = Bitmap.createBitmap(textureWidth, textureHeight,
310 Bitmap.Config.ARGB_8888);
311 final Canvas canvas = sCanvas;
312 canvas.setBitmap(bitmap);
313
314 final int left = (textureWidth-width) / 2;
315 final int top = (textureHeight-height) / 2;
316
Michael Jurka3a9fced2012-04-13 14:44:29 -0700317 @SuppressWarnings("all") // suppress dead code warning
318 final boolean debug = false;
319 if (debug) {
Joe Onorato6665c0f2009-09-02 15:27:24 -0700320 // draw a big box for the icon for debugging
321 canvas.drawColor(sColors[sColorIndex]);
322 if (++sColorIndex >= sColors.length) sColorIndex = 0;
323 Paint debugPaint = new Paint();
324 debugPaint.setColor(0xffcccc00);
325 canvas.drawRect(left, top, left+width, top+height, debugPaint);
326 }
327
328 sOldBounds.set(icon.getBounds());
329 icon.setBounds(left, top, left+width, top+height);
Sunny Goyalfc218302015-09-17 14:59:10 -0700330 canvas.save(Canvas.MATRIX_SAVE_FLAG);
331 canvas.scale(scale, scale, textureWidth / 2, textureHeight / 2);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700332 icon.draw(canvas);
Sunny Goyalfc218302015-09-17 14:59:10 -0700333 canvas.restore();
Joe Onorato6665c0f2009-09-02 15:27:24 -0700334 icon.setBounds(sOldBounds);
Adam Cohenaaf473c2011-08-03 12:02:47 -0700335 canvas.setBitmap(null);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700336
337 return bitmap;
338 }
339 }
340
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800341 /**
Winson Chungc763c4e2013-07-19 13:49:06 -0700342 * Given a coordinate relative to the descendant, find the coordinate in a parent view's
343 * coordinates.
344 *
345 * @param descendant The descendant to which the passed coordinate is relative.
Sunny Goyale8b5d202016-06-13 16:36:59 -0700346 * @param ancestor The root view to make the coordinates relative to.
Winson Chungc763c4e2013-07-19 13:49:06 -0700347 * @param coord The coordinate that we want mapped.
348 * @param includeRootScroll Whether or not to account for the scroll of the descendant:
349 * sometimes this is relevant as in a child's coordinates within the descendant.
350 * @return The factor by which this descendant is scaled relative to this DragLayer. Caution
351 * this scale factor is assumed to be equal in X and Y, and so if at any point this
352 * assumption fails, we will need to return a pair of scale factors.
353 */
Sunny Goyale8b5d202016-06-13 16:36:59 -0700354 public static float getDescendantCoordRelativeToAncestor(
355 View descendant, View ancestor, int[] coord, boolean includeRootScroll) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700356 float[] pt = {coord[0], coord[1]};
Sunny Goyal8cf47a52016-06-15 10:11:30 -0700357 float scale = 1.0f;
Winson Chungc763c4e2013-07-19 13:49:06 -0700358 View v = descendant;
Sunny Goyale8b5d202016-06-13 16:36:59 -0700359 while(v != ancestor && v != null) {
Sunny Goyal8cf47a52016-06-15 10:11:30 -0700360 // For TextViews, scroll has a meaning which relates to the text position
361 // which is very strange... ignore the scroll.
362 if (v != descendant || includeRootScroll) {
363 pt[0] -= v.getScrollX();
364 pt[1] -= v.getScrollY();
365 }
366
367 v.getMatrix().mapPoints(pt);
368 pt[0] += v.getLeft();
369 pt[1] += v.getTop();
370 scale *= v.getScaleX();
371
Winson Chungc763c4e2013-07-19 13:49:06 -0700372 v = (View) v.getParent();
373 }
Winson Chungc763c4e2013-07-19 13:49:06 -0700374
Sunny Goyal8cf47a52016-06-15 10:11:30 -0700375 coord[0] = Math.round(pt[0]);
376 coord[1] = Math.round(pt[1]);
Winson Chungc763c4e2013-07-19 13:49:06 -0700377 return scale;
378 }
379
380 /**
Sunny Goyale8b5d202016-06-13 16:36:59 -0700381 * Inverse of {@link #getDescendantCoordRelativeToAncestor(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
Tony Wickham1bce7fd2016-04-28 17:39:03 -0700431 /** Translates MotionEvents from src's coordinate system to dst's. */
432 public static void translateEventCoordinates(View src, View dst, MotionEvent dstEvent) {
433 toGlobalMotionEvent(src, dstEvent);
434 toLocalMotionEvent(dst, dstEvent);
435 }
436
437 /**
438 * Emulates View.toGlobalMotionEvent(). This implementation does not handle transformations
439 * (scaleX, scaleY, etc).
440 */
441 private static void toGlobalMotionEvent(View view, MotionEvent event) {
442 view.getLocationOnScreen(sLoc0);
443 event.offsetLocation(sLoc0[0], sLoc0[1]);
444 }
445
446 /**
447 * Emulates View.toLocalMotionEvent(). This implementation does not handle transformations
448 * (scaleX, scaleY, etc).
449 */
450 private static void toLocalMotionEvent(View view, MotionEvent event) {
451 view.getLocationOnScreen(sLoc0);
452 event.offsetLocation(-sLoc0[0], -sLoc0[1]);
453 }
454
Adam Cohen63f1ec02014-08-12 09:23:13 -0700455 public static int[] getCenterDeltaInScreenSpace(View v0, View v1, int[] delta) {
456 v0.getLocationInWindow(sLoc0);
457 v1.getLocationInWindow(sLoc1);
458
459 sLoc0[0] += (v0.getMeasuredWidth() * v0.getScaleX()) / 2;
460 sLoc0[1] += (v0.getMeasuredHeight() * v0.getScaleY()) / 2;
461 sLoc1[0] += (v1.getMeasuredWidth() * v1.getScaleX()) / 2;
462 sLoc1[1] += (v1.getMeasuredHeight() * v1.getScaleY()) / 2;
463
464 if (delta == null) {
465 delta = new int[2];
466 }
467
468 delta[0] = sLoc1[0] - sLoc0[0];
469 delta[1] = sLoc1[1] - sLoc0[1];
470
471 return delta;
472 }
473
Winson Chung3a6e7f32013-10-09 15:50:52 -0700474 public static void scaleRectAboutCenter(Rect r, float scale) {
Sunny Goyal106bf642015-07-16 12:18:06 -0700475 if (scale != 1.0f) {
476 int cx = r.centerX();
477 int cy = r.centerY();
478 r.offset(-cx, -cy);
479
480 r.left = (int) (r.left * scale + 0.5f);
481 r.top = (int) (r.top * scale + 0.5f);
482 r.right = (int) (r.right * scale + 0.5f);
483 r.bottom = (int) (r.bottom * scale + 0.5f);
484
485 r.offset(cx, cy);
486 }
Winson Chung3a6e7f32013-10-09 15:50:52 -0700487 }
488
Michael Jurkaa805e1a2013-08-22 15:00:33 +0200489 public static void startActivityForResultSafely(
490 Activity activity, Intent intent, int requestCode) {
491 try {
492 activity.startActivityForResult(intent, requestCode);
493 } catch (ActivityNotFoundException e) {
494 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
495 } catch (SecurityException e) {
496 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
497 Log.e(TAG, "Launcher does not have the permission to launch " + intent +
498 ". Make sure to create a MAIN intent-filter for the corresponding activity " +
499 "or use the exported attribute for this activity.", e);
500 }
501 }
Sunny Goyalc5c60ad2014-07-14 12:02:01 -0700502
503 static boolean isSystemApp(Context context, Intent intent) {
504 PackageManager pm = context.getPackageManager();
505 ComponentName cn = intent.getComponent();
506 String packageName = null;
507 if (cn == null) {
508 ResolveInfo info = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
509 if ((info != null) && (info.activityInfo != null)) {
510 packageName = info.activityInfo.packageName;
511 }
512 } else {
513 packageName = cn.getPackageName();
514 }
515 if (packageName != null) {
516 try {
517 PackageInfo info = pm.getPackageInfo(packageName, 0);
518 return (info != null) && (info.applicationInfo != null) &&
519 ((info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
520 } catch (NameNotFoundException e) {
521 return false;
522 }
523 } else {
524 return false;
525 }
526 }
Sunny Goyal95abbb32014-08-04 10:53:22 -0700527
528 /**
529 * This picks a dominant color, looking for high-saturation, high-value, repeated hues.
530 * @param bitmap The bitmap to scan
531 * @param samples The approximate max number of samples to use.
532 */
533 static int findDominantColorByHue(Bitmap bitmap, int samples) {
534 final int height = bitmap.getHeight();
535 final int width = bitmap.getWidth();
536 int sampleStride = (int) Math.sqrt((height * width) / samples);
537 if (sampleStride < 1) {
538 sampleStride = 1;
539 }
540
541 // This is an out-param, for getting the hsv values for an rgb
542 float[] hsv = new float[3];
543
544 // First get the best hue, by creating a histogram over 360 hue buckets,
545 // where each pixel contributes a score weighted by saturation, value, and alpha.
546 float[] hueScoreHistogram = new float[360];
547 float highScore = -1;
548 int bestHue = -1;
549
550 for (int y = 0; y < height; y += sampleStride) {
551 for (int x = 0; x < width; x += sampleStride) {
552 int argb = bitmap.getPixel(x, y);
553 int alpha = 0xFF & (argb >> 24);
554 if (alpha < 0x80) {
555 // Drop mostly-transparent pixels.
556 continue;
557 }
558 // Remove the alpha channel.
559 int rgb = argb | 0xFF000000;
560 Color.colorToHSV(rgb, hsv);
561 // Bucket colors by the 360 integer hues.
562 int hue = (int) hsv[0];
563 if (hue < 0 || hue >= hueScoreHistogram.length) {
564 // Defensively avoid array bounds violations.
565 continue;
566 }
567 float score = hsv[1] * hsv[2];
568 hueScoreHistogram[hue] += score;
569 if (hueScoreHistogram[hue] > highScore) {
570 highScore = hueScoreHistogram[hue];
571 bestHue = hue;
572 }
573 }
574 }
575
576 SparseArray<Float> rgbScores = new SparseArray<Float>();
577 int bestColor = 0xff000000;
578 highScore = -1;
579 // Go back over the RGB colors that match the winning hue,
580 // creating a histogram of weighted s*v scores, for up to 100*100 [s,v] buckets.
581 // The highest-scoring RGB color wins.
582 for (int y = 0; y < height; y += sampleStride) {
583 for (int x = 0; x < width; x += sampleStride) {
584 int rgb = bitmap.getPixel(x, y) | 0xff000000;
585 Color.colorToHSV(rgb, hsv);
586 int hue = (int) hsv[0];
587 if (hue == bestHue) {
588 float s = hsv[1];
589 float v = hsv[2];
590 int bucket = (int) (s * 100) + (int) (v * 10000);
591 // Score by cumulative saturation * value.
592 float score = s * v;
593 Float oldTotal = rgbScores.get(bucket);
594 float newTotal = oldTotal == null ? score : oldTotal + score;
595 rgbScores.put(bucket, newTotal);
596 if (newTotal > highScore) {
597 highScore = newTotal;
598 // All the colors in the winning bucket are very similar. Last in wins.
599 bestColor = rgb;
600 }
601 }
602 }
603 }
604 return bestColor;
605 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700606
607 /*
608 * Finds a system apk which had a broadcast receiver listening to a particular action.
609 * @param action intent action used to find the apk
610 * @return a pair of apk package name and the resources.
611 */
612 static Pair<String, Resources> findSystemApk(String action, PackageManager pm) {
613 final Intent intent = new Intent(action);
614 for (ResolveInfo info : pm.queryBroadcastReceivers(intent, 0)) {
615 if (info.activityInfo != null &&
616 (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
617 final String packageName = info.activityInfo.packageName;
618 try {
619 final Resources res = pm.getResourcesForApplication(packageName);
620 return Pair.create(packageName, res);
621 } catch (NameNotFoundException e) {
622 Log.w(TAG, "Failed to find resources for " + packageName);
623 }
624 }
625 }
626 return null;
627 }
Sunny Goyalfafca522014-11-03 11:30:01 -0800628
Sunny Goyal594d76d2014-11-06 10:12:54 -0800629 /**
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700630 * Compresses the bitmap to a byte array for serialization.
631 */
632 public static byte[] flattenBitmap(Bitmap bitmap) {
633 // Try go guesstimate how much space the icon will take when serialized
634 // to avoid unnecessary allocations/copies during the write.
635 int size = bitmap.getWidth() * bitmap.getHeight() * 4;
636 ByteArrayOutputStream out = new ByteArrayOutputStream(size);
637 try {
638 bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
639 out.flush();
640 out.close();
641 return out.toByteArray();
642 } catch (IOException e) {
643 Log.w(TAG, "Could not write bitmap");
644 return null;
645 }
646 }
647
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700648 /**
Winson Chung82b016c2015-05-08 17:00:10 -0700649 * Trims the string, removing all whitespace at the beginning and end of the string.
650 * Non-breaking whitespaces are also removed.
651 */
652 public static String trim(CharSequence s) {
Winson Chungafa77e92015-05-15 12:04:03 -0700653 if (s == null) {
654 return null;
655 }
656
Winson Chung82b016c2015-05-08 17:00:10 -0700657 // Just strip any sequence of whitespace or java space characters from the beginning and end
658 Matcher m = sTrimPattern.matcher(s);
659 return m.replaceAll("$1");
660 }
Sunny Goyal70660032015-05-14 00:07:08 -0700661
Winson Chung2c6e5cc2015-06-01 14:38:24 -0700662 /**
663 * Calculates the height of a given string at a specific text size.
664 */
665 public static float calculateTextHeight(float textSizePx) {
666 Paint p = new Paint();
667 p.setTextSize(textSizePx);
668 Paint.FontMetrics fm = p.getFontMetrics();
669 return -fm.top + fm.bottom;
670 }
671
Winson Chungb1777442015-06-16 13:35:04 -0700672 /**
673 * Convenience println with multiple args.
674 */
675 public static void println(String key, Object... args) {
676 StringBuilder b = new StringBuilder();
677 b.append(key);
678 b.append(": ");
679 boolean isFirstArgument = true;
680 for (Object arg : args) {
681 if (isFirstArgument) {
682 isFirstArgument = false;
683 } else {
684 b.append(", ");
685 }
686 b.append(arg);
687 }
688 System.out.println(b.toString());
689 }
690
Sunny Goyal70660032015-05-14 00:07:08 -0700691 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
692 public static boolean isRtl(Resources res) {
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700693 return ATLEAST_JB_MR1 &&
Sunny Goyal70660032015-05-14 00:07:08 -0700694 (res.getConfiguration().getLayoutDirection() == View.LAYOUT_DIRECTION_RTL);
695 }
Hyunyoung Song2bd3d7d2015-05-21 13:04:53 -0700696
Sunny Goyal5c97f512015-05-19 16:03:28 -0700697 /**
698 * Returns true if the intent is a valid launch intent for a launcher activity of an app.
699 * This is used to identify shortcuts which are different from the ones exposed by the
700 * applications' manifest file.
701 *
702 * @param launchIntent The intent that will be launched when the shortcut is clicked.
703 */
704 public static boolean isLauncherAppTarget(Intent launchIntent) {
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700705 if (launchIntent != null
Sunny Goyal5c97f512015-05-19 16:03:28 -0700706 && Intent.ACTION_MAIN.equals(launchIntent.getAction())
707 && launchIntent.getComponent() != null
708 && launchIntent.getCategories() != null
709 && launchIntent.getCategories().size() == 1
710 && launchIntent.hasCategory(Intent.CATEGORY_LAUNCHER)
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700711 && TextUtils.isEmpty(launchIntent.getDataString())) {
712 // An app target can either have no extra or have ItemInfo.EXTRA_PROFILE.
713 Bundle extras = launchIntent.getExtras();
714 if (extras == null) {
715 return true;
716 } else {
717 Set<String> keys = extras.keySet();
718 return keys.size() == 1 && keys.contains(ItemInfo.EXTRA_PROFILE);
719 }
720 };
721 return false;
Sunny Goyal5c97f512015-05-19 16:03:28 -0700722 }
Adam Cohen2e6da152015-05-06 11:42:25 -0700723
724 public static float dpiFromPx(int size, DisplayMetrics metrics){
725 float densityRatio = (float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT;
726 return (size / densityRatio);
727 }
728 public static int pxFromDp(float size, DisplayMetrics metrics) {
729 return (int) Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
730 size, metrics));
731 }
732 public static int pxFromSp(float size, DisplayMetrics metrics) {
733 return (int) Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
734 size, metrics));
735 }
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700736
737 public static String createDbSelectionQuery(String columnName, Iterable<?> values) {
738 return String.format(Locale.ENGLISH, "%s IN (%s)", columnName, TextUtils.join(", ", values));
739 }
Sunny Goyal25aba0a2015-07-16 15:07:47 -0700740
Sunny Goyal25aba0a2015-07-16 15:07:47 -0700741 public static boolean isBootCompleted() {
742 try {
743 Class clazz = Class.forName("android.os.SystemProperties");
744 Method getter = clazz.getDeclaredMethod("get", String.class);
745 String value = (String) getter.invoke(null, "sys.boot_completed");
746 return "1".equals(value);
747 } catch (Exception e) {
748 Log.d(TAG, "Unable to read system properties");
749 // Assume that boot has completed
750 return true;
751 }
752 }
Tony Wickham29d853c2015-09-08 10:35:56 -0700753
754 /**
755 * Ensures that a value is within given bounds. Specifically:
756 * If value is less than lowerBound, return lowerBound; else if value is greater than upperBound,
757 * return upperBound; else return value unchanged.
758 */
Tony Wickhamf549dab2016-05-16 09:54:06 -0700759 public static int boundToRange(int value, int lowerBound, int upperBound) {
760 return Math.max(lowerBound, Math.min(value, upperBound));
761 }
762
763 /**
764 * @see #boundToRange(int, int, int).
765 */
766 public static float boundToRange(float value, float lowerBound, float upperBound) {
Tony Wickham29d853c2015-09-08 10:35:56 -0700767 return Math.max(lowerBound, Math.min(value, upperBound));
768 }
Sunny Goyal9d438082015-09-25 11:50:16 -0700769
Sunny Goyale78e3d72015-09-24 11:23:31 -0700770 /**
771 * Wraps a message with a TTS span, so that a different message is spoken than
772 * what is getting displayed.
773 * @param msg original message
774 * @param ttsMsg message to be spoken
775 */
776 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
777 public static CharSequence wrapForTts(CharSequence msg, String ttsMsg) {
778 if (Utilities.ATLEAST_LOLLIPOP) {
779 SpannableString spanned = new SpannableString(msg);
780 spanned.setSpan(new TtsSpan.TextBuilder(ttsMsg).build(),
781 0, spanned.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
782 return spanned;
783 } else {
784 return msg;
785 }
786 }
Winson12fb9fc2015-10-01 15:34:08 -0700787
788 /**
789 * Replacement for Long.compare() which was added in API level 19.
790 */
791 public static int longCompare(long lhs, long rhs) {
792 return lhs < rhs ? -1 : (lhs == rhs ? 0 : 1);
793 }
Sunny Goyalf7258242015-10-19 16:59:07 -0700794
795 public static SharedPreferences getPrefs(Context context) {
796 return context.getSharedPreferences(
797 LauncherFiles.SHARED_PREFERENCES_KEY, Context.MODE_PRIVATE);
798 }
Tony Wickham112ac952015-11-12 12:31:50 -0800799
800 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
801 public static boolean isPowerSaverOn(Context context) {
802 PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
803 return ATLEAST_LOLLIPOP && powerManager.isPowerSaveMode();
804 }
Sunny Goyale1483fb2016-01-08 12:16:15 -0800805
Sunny Goyal1ed6c4a2016-04-21 15:16:11 -0700806 public static boolean isWallapaperAllowed(Context context) {
807 if (isNycOrAbove()) {
808 try {
809 WallpaperManager wm = context.getSystemService(WallpaperManager.class);
Kenny Guy367da9f2016-05-25 19:22:14 +0100810 return (Boolean) wm.getClass().getDeclaredMethod("isSetWallpaperAllowed")
Sunny Goyal1ed6c4a2016-04-21 15:16:11 -0700811 .invoke(wm);
812 } catch (Exception e) { }
813 }
814 return true;
815 }
816
Sunny Goyal713edfc2016-05-06 09:58:34 -0700817 public static void closeSilently(Closeable c) {
818 if (c != null) {
819 try {
820 c.close();
821 } catch (IOException e) {
822 if (ProviderConfig.IS_DOGFOOD_BUILD) {
823 Log.d(TAG, "Error closing", e);
824 }
825 }
826 }
827 }
828
Sunny Goyale1483fb2016-01-08 12:16:15 -0800829 /**
Sunny Goyal3f732192016-05-13 13:48:44 -0700830 * Returns true if {@param original} contains all entries defined in {@param updates} and
831 * have the same value.
832 * The comparison uses {@link Object#equals(Object)} to compare the values.
833 */
834 public static boolean containsAll(Bundle original, Bundle updates) {
835 for (String key : updates.keySet()) {
836 Object value1 = updates.get(key);
837 Object value2 = original.get(key);
838 if (value1 == null) {
839 if (value2 != null) {
840 return false;
841 }
842 } else if (!value1.equals(value2)) {
843 return false;
844 }
845 }
846 return true;
847 }
848
Tony Wickham1bce7fd2016-04-28 17:39:03 -0700849 /** Returns whether the collection is null or empty. */
850 public static boolean isEmpty(Collection c) {
851 return c == null || c.isEmpty();
852 }
853
Sunny Goyal3f732192016-05-13 13:48:44 -0700854 /**
Sunny Goyale1483fb2016-01-08 12:16:15 -0800855 * An extension of {@link BitmapDrawable} which returns the bitmap pixel size as intrinsic size.
856 * This allows the badging to be done based on the action bitmap size rather than
857 * the scaled bitmap size.
858 */
859 private static class FixedSizeBitmapDrawable extends BitmapDrawable {
860
861 public FixedSizeBitmapDrawable(Bitmap bitmap) {
862 super(null, bitmap);
863 }
864
865 @Override
866 public int getIntrinsicHeight() {
867 return getBitmap().getWidth();
868 }
869
870 @Override
871 public int getIntrinsicWidth() {
872 return getBitmap().getWidth();
873 }
874 }
Andrew Sappersteinabef55a2016-06-19 12:49:00 -0700875
876 public static int getColorAccent(Context context) {
877 TypedArray ta = context.obtainStyledAttributes(new int[]{android.R.attr.colorAccent});
878 int colorAccent = ta.getColor(0, 0);
879 ta.recycle();
880 return colorAccent;
881 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800882}