blob: d7a8a4e6213444ce529f201aac7efad00e8063c0 [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;
Hyunyoung Song2bd3d7d2015-05-21 13:04:53 -070050import android.os.Process;
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 Goyal6c56c682015-07-16 14:09:05 -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;
69import java.io.IOException;
Sunny Goyal25aba0a2015-07-16 15:07:47 -070070import java.lang.reflect.Method;
Winson Chungc763c4e2013-07-19 13:49:06 -070071import java.util.ArrayList;
Sunny Goyalb1622cc2015-06-10 16:00:42 -070072import java.util.Locale;
Sunny Goyal4e5cc642015-06-25 16:37:44 -070073import java.util.Set;
Sunny Goyal8ac727b2015-09-23 15:38:09 -070074import java.util.concurrent.Executor;
75import java.util.concurrent.LinkedBlockingQueue;
76import java.util.concurrent.ThreadPoolExecutor;
77import java.util.concurrent.TimeUnit;
Winson Chung82b016c2015-05-08 17:00:10 -070078import java.util.regex.Matcher;
79import java.util.regex.Pattern;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080080
81/**
82 * Various utilities shared amongst the Launcher's classes.
83 */
Mathew Inwood72fbec12013-11-19 15:45:07 +000084public final class Utilities {
Rahul Chaturvedi7fc77ca2015-05-19 18:02:16 -070085
Joe Onorato1291a8c2009-09-15 15:07:25 -040086 private static final String TAG = "Launcher.Utilities";
87
The Android Open Source Project31dd5032009-03-03 19:32:27 -080088 private static final Rect sOldBounds = new Rect();
Romain Guy89911d22009-09-28 18:48:49 -070089 private static final Canvas sCanvas = new Canvas();
The Android Open Source Project31dd5032009-03-03 19:32:27 -080090
Winson Chung82b016c2015-05-08 17:00:10 -070091 private static final Pattern sTrimPattern =
92 Pattern.compile("^[\\s|\\p{javaSpaceChar}]*(.*)[\\s|\\p{javaSpaceChar}]*$");
93
The Android Open Source Project31dd5032009-03-03 19:32:27 -080094 static {
95 sCanvas.setDrawFilter(new PaintFlagsDrawFilter(Paint.DITHER_FLAG,
96 Paint.FILTER_BITMAP_FLAG));
97 }
Joe Onorato6665c0f2009-09-02 15:27:24 -070098 static int sColors[] = { 0xffff0000, 0xff00ff00, 0xff0000ff };
99 static int sColorIndex = 0;
100
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700101 private static final int[] sLoc0 = new int[2];
102 private static final int[] sLoc1 = new int[2];
Michael Jurka7ad868b2013-12-12 15:04:25 +0100103
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700104 // TODO: use Build.VERSION_CODES when available
105 public static final boolean ATLEAST_MARSHMALLOW = Build.VERSION.SDK_INT >= 23;
106
107 public static final boolean ATLEAST_LOLLIPOP_MR1 =
108 Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1;
109
110 public static final boolean ATLEAST_LOLLIPOP =
111 Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
112
113 public static final boolean ATLEAST_KITKAT =
114 Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
115
116 public static final boolean ATLEAST_JB_MR1 =
117 Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1;
118
119 public static final boolean ATLEAST_JB_MR2 =
120 Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2;
121
Sunny Goyal8ac727b2015-09-23 15:38:09 -0700122 // These values are same as that in {@link AsyncTask}.
123 private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
124 private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
125 private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
126 private static final int KEEP_ALIVE = 1;
127 /**
128 * An {@link Executor} to be used with async task with no limit on the queue size.
129 */
130 public static final Executor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(
131 CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
132 TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
133
Rahul Chaturvedi7fc77ca2015-05-19 18:02:16 -0700134 public static final String ALLOW_ROTATION_PREFERENCE_KEY = "pref_allowRotation";
135
Sunny Goyal4bbf4192014-11-11 12:23:59 -0800136 public static boolean isPropertyEnabled(String propertyName) {
Michael Jurka7ad868b2013-12-12 15:04:25 +0100137 return Log.isLoggable(propertyName, Log.VERBOSE);
138 }
139
Sunny Goyal21bf5312015-08-21 11:08:24 -0700140 public static boolean isAllowRotationPrefEnabled(Context context) {
Sunny Goyal8f3819b2016-02-23 14:49:22 -0800141 boolean allowRotationPref = false;
142 if (isNycOrAbove()) {
143 // If the device was scaled, used the original dimensions to determine if rotation
144 // is allowed of not.
145 try {
146 // TODO: Use the actual field when the API is finalized.
147 int originalDensity =
148 DisplayMetrics.class.getField("DENSITY_DEVICE_STABLE").getInt(null);
149 Resources res = context.getResources();
150 int originalSmallestWidth = res.getConfiguration().smallestScreenWidthDp
151 * res.getDisplayMetrics().densityDpi / originalDensity;
152 allowRotationPref = originalSmallestWidth >= 600;
153 } catch (Exception e) {
154 // Ignore
155 }
156 }
Rahul Chaturvedi7fc77ca2015-05-19 18:02:16 -0700157
Sunny Goyal8f3819b2016-02-23 14:49:22 -0800158 return getPrefs(context).getBoolean(ALLOW_ROTATION_PREFERENCE_KEY, allowRotationPref);
Michael Jurka7ad868b2013-12-12 15:04:25 +0100159 }
160
Vadim Tryshev9de91272015-08-03 18:37:17 -0700161 public static boolean isNycOrAbove() {
162 // TODO(vadimt): Replace using reflection with looking at the API version once
163 // Build.VERSION.SDK_INT gets bumped to 24. b/22942492.
164 try {
165 View.class.getDeclaredField("DRAG_FLAG_OPAQUE");
166 // View.DRAG_FLAG_OPAQUE doesn't exist in M-release, so it's an indication of N+.
167 return true;
168 } catch (NoSuchFieldException e) {
169 return false;
170 }
171 }
172
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700173 public static Bitmap createIconBitmap(Cursor c, int iconIndex, Context context) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -0800174 byte[] data = c.getBlob(iconIndex);
175 try {
176 return createIconBitmap(BitmapFactory.decodeByteArray(data, 0, data.length), context);
177 } catch (Exception e) {
178 return null;
179 }
180 }
181
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -0700182 /**
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700183 * Returns a bitmap suitable for the all apps view. If the package or the resource do not
184 * exist, it returns null.
185 */
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700186 public static Bitmap createIconBitmap(String packageName, String resourceName,
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700187 Context context) {
188 PackageManager packageManager = context.getPackageManager();
189 // the resource
190 try {
191 Resources resources = packageManager.getResourcesForApplication(packageName);
192 if (resources != null) {
193 final int id = resources.getIdentifier(resourceName, null, null);
194 return createIconBitmap(
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700195 resources.getDrawableForDensity(id, LauncherAppState.getInstance()
196 .getInvariantDeviceProfile().fillResIconDpi), context);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700197 }
198 } catch (Exception e) {
199 // Icon not found.
200 }
201 return null;
202 }
203
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700204 private static int getIconBitmapSize() {
205 return LauncherAppState.getInstance().getInvariantDeviceProfile().iconBitmapSize;
206 }
207
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700208 /**
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700209 * Returns a bitmap which is of the appropriate size to be displayed as an icon
Michael Jurka931dc972011-08-05 15:08:15 -0700210 */
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700211 public static Bitmap createIconBitmap(Bitmap icon, Context context) {
212 final int iconBitmapSize = getIconBitmapSize();
213 if (iconBitmapSize == icon.getWidth() && iconBitmapSize == icon.getHeight()) {
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700214 return icon;
215 }
216 return createIconBitmap(new BitmapDrawable(context.getResources(), icon), context);
Michael Jurka931dc972011-08-05 15:08:15 -0700217 }
218
219 /**
Sunny Goyalfc218302015-09-17 14:59:10 -0700220 * Returns a bitmap suitable for the all apps view. The icon is badged for {@param user}.
221 * The bitmap is also visually normalized with other icons.
Sunny Goyalb84046d2015-10-19 14:03:30 -0700222 */
223 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
224 public static Bitmap createBadgedIconBitmap(
225 Drawable icon, UserHandleCompat user, Context context) {
Sunny Goyald896ee42015-12-17 11:24:31 -0800226 float scale = FeatureFlags.LAUNCHER3_ICON_NORMALIZATION ?
Sunny Goyalfc218302015-09-17 14:59:10 -0700227 IconNormalizer.getInstance().getScale(icon) : 1;
228 Bitmap bitmap = createIconBitmap(icon, context, scale);
Sunny Goyalb84046d2015-10-19 14:03:30 -0700229 if (Utilities.ATLEAST_LOLLIPOP && user != null
230 && !UserHandleCompat.myUserHandle().equals(user)) {
Sunny Goyale1483fb2016-01-08 12:16:15 -0800231 BitmapDrawable drawable = new FixedSizeBitmapDrawable(bitmap);
Sunny Goyalb84046d2015-10-19 14:03:30 -0700232 Drawable badged = context.getPackageManager().getUserBadgedIcon(
233 drawable, user.getUser());
234 if (badged instanceof BitmapDrawable) {
235 return ((BitmapDrawable) badged).getBitmap();
236 } else {
237 return createIconBitmap(badged, context);
238 }
239 } else {
240 return bitmap;
241 }
242 }
243
244 /**
Michael Jurka931dc972011-08-05 15:08:15 -0700245 * Returns a bitmap suitable for the all apps view.
Joe Onorato6665c0f2009-09-02 15:27:24 -0700246 */
Mathew Inwood72fbec12013-11-19 15:45:07 +0000247 public static Bitmap createIconBitmap(Drawable icon, Context context) {
Sunny Goyalfc218302015-09-17 14:59:10 -0700248 return createIconBitmap(icon, context, 1.0f /* scale */);
249 }
250
251 /**
252 * @param scale the scale to apply before drawing {@param icon} on the canvas
253 */
254 public static Bitmap createIconBitmap(Drawable icon, Context context, float scale) {
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700255 synchronized (sCanvas) {
256 final int iconBitmapSize = getIconBitmapSize();
Joe Onorato6665c0f2009-09-02 15:27:24 -0700257
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700258 int width = iconBitmapSize;
259 int height = iconBitmapSize;
Joe Onorato6665c0f2009-09-02 15:27:24 -0700260
Joe Onorato6665c0f2009-09-02 15:27:24 -0700261 if (icon instanceof PaintDrawable) {
262 PaintDrawable painter = (PaintDrawable) icon;
263 painter.setIntrinsicWidth(width);
264 painter.setIntrinsicHeight(height);
265 } else if (icon instanceof BitmapDrawable) {
266 // Ensure the bitmap has a density.
267 BitmapDrawable bitmapDrawable = (BitmapDrawable) icon;
268 Bitmap bitmap = bitmapDrawable.getBitmap();
Sunny Goyalde9590b2015-09-23 12:56:51 -0700269 if (bitmap != null && bitmap.getDensity() == Bitmap.DENSITY_NONE) {
Joe Onorato6665c0f2009-09-02 15:27:24 -0700270 bitmapDrawable.setTargetDensity(context.getResources().getDisplayMetrics());
271 }
272 }
273 int sourceWidth = icon.getIntrinsicWidth();
274 int sourceHeight = icon.getIntrinsicHeight();
Michael Jurka931dc972011-08-05 15:08:15 -0700275 if (sourceWidth > 0 && sourceHeight > 0) {
Winson Chung5f8afe62013-08-12 16:19:28 -0700276 // Scale the icon proportionally to the icon dimensions
277 final float ratio = (float) sourceWidth / sourceHeight;
278 if (sourceWidth > sourceHeight) {
279 height = (int) (width / ratio);
280 } else if (sourceHeight > sourceWidth) {
281 width = (int) (height * ratio);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700282 }
283 }
284
285 // no intrinsic size --> use default size
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700286 int textureWidth = iconBitmapSize;
287 int textureHeight = iconBitmapSize;
Joe Onorato6665c0f2009-09-02 15:27:24 -0700288
289 final Bitmap bitmap = Bitmap.createBitmap(textureWidth, textureHeight,
290 Bitmap.Config.ARGB_8888);
291 final Canvas canvas = sCanvas;
292 canvas.setBitmap(bitmap);
293
294 final int left = (textureWidth-width) / 2;
295 final int top = (textureHeight-height) / 2;
296
Michael Jurka3a9fced2012-04-13 14:44:29 -0700297 @SuppressWarnings("all") // suppress dead code warning
298 final boolean debug = false;
299 if (debug) {
Joe Onorato6665c0f2009-09-02 15:27:24 -0700300 // draw a big box for the icon for debugging
301 canvas.drawColor(sColors[sColorIndex]);
302 if (++sColorIndex >= sColors.length) sColorIndex = 0;
303 Paint debugPaint = new Paint();
304 debugPaint.setColor(0xffcccc00);
305 canvas.drawRect(left, top, left+width, top+height, debugPaint);
306 }
307
308 sOldBounds.set(icon.getBounds());
309 icon.setBounds(left, top, left+width, top+height);
Sunny Goyalfc218302015-09-17 14:59:10 -0700310 canvas.save(Canvas.MATRIX_SAVE_FLAG);
311 canvas.scale(scale, scale, textureWidth / 2, textureHeight / 2);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700312 icon.draw(canvas);
Sunny Goyalfc218302015-09-17 14:59:10 -0700313 canvas.restore();
Joe Onorato6665c0f2009-09-02 15:27:24 -0700314 icon.setBounds(sOldBounds);
Adam Cohenaaf473c2011-08-03 12:02:47 -0700315 canvas.setBitmap(null);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700316
317 return bitmap;
318 }
319 }
320
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800321 /**
Winson Chungc763c4e2013-07-19 13:49:06 -0700322 * Given a coordinate relative to the descendant, find the coordinate in a parent view's
323 * coordinates.
324 *
325 * @param descendant The descendant to which the passed coordinate is relative.
326 * @param root The root view to make the coordinates relative to.
327 * @param coord The coordinate that we want mapped.
328 * @param includeRootScroll Whether or not to account for the scroll of the descendant:
329 * sometimes this is relevant as in a child's coordinates within the descendant.
330 * @return The factor by which this descendant is scaled relative to this DragLayer. Caution
331 * this scale factor is assumed to be equal in X and Y, and so if at any point this
332 * assumption fails, we will need to return a pair of scale factors.
333 */
334 public static float getDescendantCoordRelativeToParent(View descendant, View root,
335 int[] coord, boolean includeRootScroll) {
336 ArrayList<View> ancestorChain = new ArrayList<View>();
337
338 float[] pt = {coord[0], coord[1]};
339
340 View v = descendant;
341 while(v != root && v != null) {
342 ancestorChain.add(v);
343 v = (View) v.getParent();
344 }
345 ancestorChain.add(root);
346
347 float scale = 1.0f;
348 int count = ancestorChain.size();
349 for (int i = 0; i < count; i++) {
350 View v0 = ancestorChain.get(i);
Winson Chungc763c4e2013-07-19 13:49:06 -0700351 // For TextViews, scroll has a meaning which relates to the text position
352 // which is very strange... ignore the scroll.
353 if (v0 != descendant || includeRootScroll) {
354 pt[0] -= v0.getScrollX();
355 pt[1] -= v0.getScrollY();
356 }
357
358 v0.getMatrix().mapPoints(pt);
359 pt[0] += v0.getLeft();
360 pt[1] += v0.getTop();
361 scale *= v0.getScaleX();
362 }
363
364 coord[0] = (int) Math.round(pt[0]);
365 coord[1] = (int) Math.round(pt[1]);
366 return scale;
367 }
368
369 /**
Sunny Goyalfc218302015-09-17 14:59:10 -0700370 * Inverse of {@link #getDescendantCoordRelativeToParent(View, View, int[], boolean)}.
Winson Chungc763c4e2013-07-19 13:49:06 -0700371 */
372 public static float mapCoordInSelfToDescendent(View descendant, View root,
373 int[] coord) {
374 ArrayList<View> ancestorChain = new ArrayList<View>();
375
376 float[] pt = {coord[0], coord[1]};
377
378 View v = descendant;
379 while(v != root) {
380 ancestorChain.add(v);
381 v = (View) v.getParent();
382 }
383 ancestorChain.add(root);
384
385 float scale = 1.0f;
386 Matrix inverse = new Matrix();
387 int count = ancestorChain.size();
388 for (int i = count - 1; i >= 0; i--) {
389 View ancestor = ancestorChain.get(i);
390 View next = i > 0 ? ancestorChain.get(i-1) : null;
391
392 pt[0] += ancestor.getScrollX();
393 pt[1] += ancestor.getScrollY();
394
395 if (next != null) {
396 pt[0] -= next.getLeft();
397 pt[1] -= next.getTop();
398 next.getMatrix().invert(inverse);
399 inverse.mapPoints(pt);
400 scale *= next.getScaleX();
401 }
402 }
403
404 coord[0] = (int) Math.round(pt[0]);
405 coord[1] = (int) Math.round(pt[1]);
406 return scale;
407 }
408
Jason Monk02dd7ae2014-04-15 15:23:31 -0400409 /**
410 * Utility method to determine whether the given point, in local coordinates,
411 * is inside the view, where the area of the view is expanded by the slop factor.
412 * This method is called while processing touch-move events to determine if the event
413 * is still within the view.
414 */
415 public static boolean pointInView(View v, float localX, float localY, float slop) {
416 return localX >= -slop && localY >= -slop && localX < (v.getWidth() + slop) &&
417 localY < (v.getHeight() + slop);
418 }
419
Adam Cohen63f1ec02014-08-12 09:23:13 -0700420 public static int[] getCenterDeltaInScreenSpace(View v0, View v1, int[] delta) {
421 v0.getLocationInWindow(sLoc0);
422 v1.getLocationInWindow(sLoc1);
423
424 sLoc0[0] += (v0.getMeasuredWidth() * v0.getScaleX()) / 2;
425 sLoc0[1] += (v0.getMeasuredHeight() * v0.getScaleY()) / 2;
426 sLoc1[0] += (v1.getMeasuredWidth() * v1.getScaleX()) / 2;
427 sLoc1[1] += (v1.getMeasuredHeight() * v1.getScaleY()) / 2;
428
429 if (delta == null) {
430 delta = new int[2];
431 }
432
433 delta[0] = sLoc1[0] - sLoc0[0];
434 delta[1] = sLoc1[1] - sLoc0[1];
435
436 return delta;
437 }
438
Winson Chung3a6e7f32013-10-09 15:50:52 -0700439 public static void scaleRectAboutCenter(Rect r, float scale) {
Sunny Goyal106bf642015-07-16 12:18:06 -0700440 if (scale != 1.0f) {
441 int cx = r.centerX();
442 int cy = r.centerY();
443 r.offset(-cx, -cy);
444
445 r.left = (int) (r.left * scale + 0.5f);
446 r.top = (int) (r.top * scale + 0.5f);
447 r.right = (int) (r.right * scale + 0.5f);
448 r.bottom = (int) (r.bottom * scale + 0.5f);
449
450 r.offset(cx, cy);
451 }
Winson Chung3a6e7f32013-10-09 15:50:52 -0700452 }
453
Michael Jurkaa805e1a2013-08-22 15:00:33 +0200454 public static void startActivityForResultSafely(
455 Activity activity, Intent intent, int requestCode) {
456 try {
457 activity.startActivityForResult(intent, requestCode);
458 } catch (ActivityNotFoundException e) {
459 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
460 } catch (SecurityException e) {
461 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
462 Log.e(TAG, "Launcher does not have the permission to launch " + intent +
463 ". Make sure to create a MAIN intent-filter for the corresponding activity " +
464 "or use the exported attribute for this activity.", e);
465 }
466 }
Sunny Goyalc5c60ad2014-07-14 12:02:01 -0700467
468 static boolean isSystemApp(Context context, Intent intent) {
469 PackageManager pm = context.getPackageManager();
470 ComponentName cn = intent.getComponent();
471 String packageName = null;
472 if (cn == null) {
473 ResolveInfo info = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
474 if ((info != null) && (info.activityInfo != null)) {
475 packageName = info.activityInfo.packageName;
476 }
477 } else {
478 packageName = cn.getPackageName();
479 }
480 if (packageName != null) {
481 try {
482 PackageInfo info = pm.getPackageInfo(packageName, 0);
483 return (info != null) && (info.applicationInfo != null) &&
484 ((info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
485 } catch (NameNotFoundException e) {
486 return false;
487 }
488 } else {
489 return false;
490 }
491 }
Sunny Goyal95abbb32014-08-04 10:53:22 -0700492
493 /**
494 * This picks a dominant color, looking for high-saturation, high-value, repeated hues.
495 * @param bitmap The bitmap to scan
496 * @param samples The approximate max number of samples to use.
497 */
498 static int findDominantColorByHue(Bitmap bitmap, int samples) {
499 final int height = bitmap.getHeight();
500 final int width = bitmap.getWidth();
501 int sampleStride = (int) Math.sqrt((height * width) / samples);
502 if (sampleStride < 1) {
503 sampleStride = 1;
504 }
505
506 // This is an out-param, for getting the hsv values for an rgb
507 float[] hsv = new float[3];
508
509 // First get the best hue, by creating a histogram over 360 hue buckets,
510 // where each pixel contributes a score weighted by saturation, value, and alpha.
511 float[] hueScoreHistogram = new float[360];
512 float highScore = -1;
513 int bestHue = -1;
514
515 for (int y = 0; y < height; y += sampleStride) {
516 for (int x = 0; x < width; x += sampleStride) {
517 int argb = bitmap.getPixel(x, y);
518 int alpha = 0xFF & (argb >> 24);
519 if (alpha < 0x80) {
520 // Drop mostly-transparent pixels.
521 continue;
522 }
523 // Remove the alpha channel.
524 int rgb = argb | 0xFF000000;
525 Color.colorToHSV(rgb, hsv);
526 // Bucket colors by the 360 integer hues.
527 int hue = (int) hsv[0];
528 if (hue < 0 || hue >= hueScoreHistogram.length) {
529 // Defensively avoid array bounds violations.
530 continue;
531 }
532 float score = hsv[1] * hsv[2];
533 hueScoreHistogram[hue] += score;
534 if (hueScoreHistogram[hue] > highScore) {
535 highScore = hueScoreHistogram[hue];
536 bestHue = hue;
537 }
538 }
539 }
540
541 SparseArray<Float> rgbScores = new SparseArray<Float>();
542 int bestColor = 0xff000000;
543 highScore = -1;
544 // Go back over the RGB colors that match the winning hue,
545 // creating a histogram of weighted s*v scores, for up to 100*100 [s,v] buckets.
546 // The highest-scoring RGB color wins.
547 for (int y = 0; y < height; y += sampleStride) {
548 for (int x = 0; x < width; x += sampleStride) {
549 int rgb = bitmap.getPixel(x, y) | 0xff000000;
550 Color.colorToHSV(rgb, hsv);
551 int hue = (int) hsv[0];
552 if (hue == bestHue) {
553 float s = hsv[1];
554 float v = hsv[2];
555 int bucket = (int) (s * 100) + (int) (v * 10000);
556 // Score by cumulative saturation * value.
557 float score = s * v;
558 Float oldTotal = rgbScores.get(bucket);
559 float newTotal = oldTotal == null ? score : oldTotal + score;
560 rgbScores.put(bucket, newTotal);
561 if (newTotal > highScore) {
562 highScore = newTotal;
563 // All the colors in the winning bucket are very similar. Last in wins.
564 bestColor = rgb;
565 }
566 }
567 }
568 }
569 return bestColor;
570 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700571
572 /*
573 * Finds a system apk which had a broadcast receiver listening to a particular action.
574 * @param action intent action used to find the apk
575 * @return a pair of apk package name and the resources.
576 */
577 static Pair<String, Resources> findSystemApk(String action, PackageManager pm) {
578 final Intent intent = new Intent(action);
579 for (ResolveInfo info : pm.queryBroadcastReceivers(intent, 0)) {
580 if (info.activityInfo != null &&
581 (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
582 final String packageName = info.activityInfo.packageName;
583 try {
584 final Resources res = pm.getResourcesForApplication(packageName);
585 return Pair.create(packageName, res);
586 } catch (NameNotFoundException e) {
587 Log.w(TAG, "Failed to find resources for " + packageName);
588 }
589 }
590 }
591 return null;
592 }
Sunny Goyalfafca522014-11-03 11:30:01 -0800593
Sunny Goyal594d76d2014-11-06 10:12:54 -0800594 /**
595 * Returns a widget with category {@link AppWidgetProviderInfo#WIDGET_CATEGORY_SEARCHBOX}
596 * provided by the same package which is set to be global search activity.
597 * If widgetCategory is not supported, or no such widget is found, returns the first widget
598 * provided by the package.
599 */
600 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
601 public static AppWidgetProviderInfo getSearchWidgetProvider(Context context) {
602 SearchManager searchManager =
603 (SearchManager) context.getSystemService(Context.SEARCH_SERVICE);
604 ComponentName searchComponent = searchManager.getGlobalSearchActivity();
605 if (searchComponent == null) return null;
606 String providerPkg = searchComponent.getPackageName();
607
608 AppWidgetProviderInfo defaultWidgetForSearchPackage = null;
609
610 AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
611 for (AppWidgetProviderInfo info : appWidgetManager.getInstalledProviders()) {
612 if (info.provider.getPackageName().equals(providerPkg)) {
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700613 if (ATLEAST_JB_MR1) {
Sunny Goyal594d76d2014-11-06 10:12:54 -0800614 if ((info.widgetCategory & AppWidgetProviderInfo.WIDGET_CATEGORY_SEARCHBOX) != 0) {
615 return info;
616 } else if (defaultWidgetForSearchPackage == null) {
617 defaultWidgetForSearchPackage = info;
618 }
619 } else {
620 return info;
621 }
622 }
623 }
624 return defaultWidgetForSearchPackage;
625 }
Sunny Goyal08f72612015-01-05 13:41:43 -0800626
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700627 /**
628 * Compresses the bitmap to a byte array for serialization.
629 */
630 public static byte[] flattenBitmap(Bitmap bitmap) {
631 // Try go guesstimate how much space the icon will take when serialized
632 // to avoid unnecessary allocations/copies during the write.
633 int size = bitmap.getWidth() * bitmap.getHeight() * 4;
634 ByteArrayOutputStream out = new ByteArrayOutputStream(size);
635 try {
636 bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
637 out.flush();
638 out.close();
639 return out.toByteArray();
640 } catch (IOException e) {
641 Log.w(TAG, "Could not write bitmap");
642 return null;
643 }
644 }
645
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700646 /**
647 * Find the first vacant cell, if there is one.
648 *
649 * @param vacant Holds the x and y coordinate of the vacant cell
650 * @param spanX Horizontal cell span.
651 * @param spanY Vertical cell span.
652 *
653 * @return true if a vacant cell was found
654 */
655 public static boolean findVacantCell(int[] vacant, int spanX, int spanY,
656 int xCount, int yCount, boolean[][] occupied) {
657
658 for (int y = 0; (y + spanY) <= yCount; y++) {
659 for (int x = 0; (x + spanX) <= xCount; x++) {
660 boolean available = !occupied[x][y];
661 out: for (int i = x; i < x + spanX; i++) {
662 for (int j = y; j < y + spanY; j++) {
663 available = available && !occupied[i][j];
664 if (!available) break out;
665 }
666 }
667
668 if (available) {
669 vacant[0] = x;
670 vacant[1] = y;
671 return true;
672 }
673 }
674 }
675
676 return false;
677 }
Winson Chung82b016c2015-05-08 17:00:10 -0700678
679 /**
680 * Trims the string, removing all whitespace at the beginning and end of the string.
681 * Non-breaking whitespaces are also removed.
682 */
683 public static String trim(CharSequence s) {
Winson Chungafa77e92015-05-15 12:04:03 -0700684 if (s == null) {
685 return null;
686 }
687
Winson Chung82b016c2015-05-08 17:00:10 -0700688 // Just strip any sequence of whitespace or java space characters from the beginning and end
689 Matcher m = sTrimPattern.matcher(s);
690 return m.replaceAll("$1");
691 }
Sunny Goyal70660032015-05-14 00:07:08 -0700692
Winson Chung2c6e5cc2015-06-01 14:38:24 -0700693 /**
694 * Calculates the height of a given string at a specific text size.
695 */
696 public static float calculateTextHeight(float textSizePx) {
697 Paint p = new Paint();
698 p.setTextSize(textSizePx);
699 Paint.FontMetrics fm = p.getFontMetrics();
700 return -fm.top + fm.bottom;
701 }
702
Winson Chungb1777442015-06-16 13:35:04 -0700703 /**
704 * Convenience println with multiple args.
705 */
706 public static void println(String key, Object... args) {
707 StringBuilder b = new StringBuilder();
708 b.append(key);
709 b.append(": ");
710 boolean isFirstArgument = true;
711 for (Object arg : args) {
712 if (isFirstArgument) {
713 isFirstArgument = false;
714 } else {
715 b.append(", ");
716 }
717 b.append(arg);
718 }
719 System.out.println(b.toString());
720 }
721
Sunny Goyal70660032015-05-14 00:07:08 -0700722 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
723 public static boolean isRtl(Resources res) {
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700724 return ATLEAST_JB_MR1 &&
Sunny Goyal70660032015-05-14 00:07:08 -0700725 (res.getConfiguration().getLayoutDirection() == View.LAYOUT_DIRECTION_RTL);
726 }
Hyunyoung Song2bd3d7d2015-05-21 13:04:53 -0700727
728 public static void assertWorkerThread() {
Sunny Goyal6c56c682015-07-16 14:09:05 -0700729 if (ProviderConfig.IS_DOGFOOD_BUILD &&
Sunny Goyal11d49112015-06-26 14:00:57 -0700730 (LauncherModel.sWorkerThread.getThreadId() != Process.myTid())) {
731 throw new IllegalStateException();
Hyunyoung Song2bd3d7d2015-05-21 13:04:53 -0700732 }
733 }
Sunny Goyal5c97f512015-05-19 16:03:28 -0700734
735 /**
736 * Returns true if the intent is a valid launch intent for a launcher activity of an app.
737 * This is used to identify shortcuts which are different from the ones exposed by the
738 * applications' manifest file.
739 *
740 * @param launchIntent The intent that will be launched when the shortcut is clicked.
741 */
742 public static boolean isLauncherAppTarget(Intent launchIntent) {
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700743 if (launchIntent != null
Sunny Goyal5c97f512015-05-19 16:03:28 -0700744 && Intent.ACTION_MAIN.equals(launchIntent.getAction())
745 && launchIntent.getComponent() != null
746 && launchIntent.getCategories() != null
747 && launchIntent.getCategories().size() == 1
748 && launchIntent.hasCategory(Intent.CATEGORY_LAUNCHER)
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700749 && TextUtils.isEmpty(launchIntent.getDataString())) {
750 // An app target can either have no extra or have ItemInfo.EXTRA_PROFILE.
751 Bundle extras = launchIntent.getExtras();
752 if (extras == null) {
753 return true;
754 } else {
755 Set<String> keys = extras.keySet();
756 return keys.size() == 1 && keys.contains(ItemInfo.EXTRA_PROFILE);
757 }
758 };
759 return false;
Sunny Goyal5c97f512015-05-19 16:03:28 -0700760 }
Adam Cohen2e6da152015-05-06 11:42:25 -0700761
762 public static float dpiFromPx(int size, DisplayMetrics metrics){
763 float densityRatio = (float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT;
764 return (size / densityRatio);
765 }
766 public static int pxFromDp(float size, DisplayMetrics metrics) {
767 return (int) Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
768 size, metrics));
769 }
770 public static int pxFromSp(float size, DisplayMetrics metrics) {
771 return (int) Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
772 size, metrics));
773 }
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700774
775 public static String createDbSelectionQuery(String columnName, Iterable<?> values) {
776 return String.format(Locale.ENGLISH, "%s IN (%s)", columnName, TextUtils.join(", ", values));
777 }
Sunny Goyal25aba0a2015-07-16 15:07:47 -0700778
Sunny Goyal25aba0a2015-07-16 15:07:47 -0700779 public static boolean isBootCompleted() {
780 try {
781 Class clazz = Class.forName("android.os.SystemProperties");
782 Method getter = clazz.getDeclaredMethod("get", String.class);
783 String value = (String) getter.invoke(null, "sys.boot_completed");
784 return "1".equals(value);
785 } catch (Exception e) {
786 Log.d(TAG, "Unable to read system properties");
787 // Assume that boot has completed
788 return true;
789 }
790 }
Tony Wickham29d853c2015-09-08 10:35:56 -0700791
792 /**
793 * Ensures that a value is within given bounds. Specifically:
794 * If value is less than lowerBound, return lowerBound; else if value is greater than upperBound,
795 * return upperBound; else return value unchanged.
796 */
797 public static int boundInRange(int value, int lowerBound, int upperBound) {
798 return Math.max(lowerBound, Math.min(value, upperBound));
799 }
Sunny Goyal9d438082015-09-25 11:50:16 -0700800
Sunny Goyale78e3d72015-09-24 11:23:31 -0700801 /**
802 * Wraps a message with a TTS span, so that a different message is spoken than
803 * what is getting displayed.
804 * @param msg original message
805 * @param ttsMsg message to be spoken
806 */
807 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
808 public static CharSequence wrapForTts(CharSequence msg, String ttsMsg) {
809 if (Utilities.ATLEAST_LOLLIPOP) {
810 SpannableString spanned = new SpannableString(msg);
811 spanned.setSpan(new TtsSpan.TextBuilder(ttsMsg).build(),
812 0, spanned.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
813 return spanned;
814 } else {
815 return msg;
816 }
817 }
Winson12fb9fc2015-10-01 15:34:08 -0700818
819 /**
820 * Replacement for Long.compare() which was added in API level 19.
821 */
822 public static int longCompare(long lhs, long rhs) {
823 return lhs < rhs ? -1 : (lhs == rhs ? 0 : 1);
824 }
Sunny Goyalf7258242015-10-19 16:59:07 -0700825
826 public static SharedPreferences getPrefs(Context context) {
827 return context.getSharedPreferences(
828 LauncherFiles.SHARED_PREFERENCES_KEY, Context.MODE_PRIVATE);
829 }
Tony Wickham112ac952015-11-12 12:31:50 -0800830
831 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
832 public static boolean isPowerSaverOn(Context context) {
833 PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
834 return ATLEAST_LOLLIPOP && powerManager.isPowerSaveMode();
835 }
Sunny Goyale1483fb2016-01-08 12:16:15 -0800836
837 /**
838 * An extension of {@link BitmapDrawable} which returns the bitmap pixel size as intrinsic size.
839 * This allows the badging to be done based on the action bitmap size rather than
840 * the scaled bitmap size.
841 */
842 private static class FixedSizeBitmapDrawable extends BitmapDrawable {
843
844 public FixedSizeBitmapDrawable(Bitmap bitmap) {
845 super(null, bitmap);
846 }
847
848 @Override
849 public int getIntrinsicHeight() {
850 return getBitmap().getWidth();
851 }
852
853 @Override
854 public int getIntrinsicWidth() {
855 return getBitmap().getWidth();
856 }
857 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800858}