blob: 0a7028603693a57bd4323a3b95d68c1d8f620a1d [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 Goyal0b621152015-10-19 14:03:30 -070063import com.android.launcher3.compat.UserHandleCompat;
Sunny Goyalfc218302015-09-17 14:59:10 -070064import com.android.launcher3.util.IconNormalizer;
Sunny Goyal0b621152015-10-19 14:03:30 -070065
Sunny Goyal5b0e6692015-03-19 14:31:19 -070066import java.io.ByteArrayOutputStream;
67import java.io.IOException;
Winson Chungc763c4e2013-07-19 13:49:06 -070068import java.util.ArrayList;
Sunny Goyalb1622cc2015-06-10 16:00:42 -070069import java.util.Locale;
Sunny Goyal4e5cc642015-06-25 16:37:44 -070070import java.util.Set;
Sunny Goyal8ac727b2015-09-23 15:38:09 -070071import java.util.concurrent.Executor;
72import java.util.concurrent.LinkedBlockingQueue;
73import java.util.concurrent.ThreadPoolExecutor;
74import java.util.concurrent.TimeUnit;
Winson Chung82b016c2015-05-08 17:00:10 -070075import java.util.regex.Matcher;
76import java.util.regex.Pattern;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080077
78/**
79 * Various utilities shared amongst the Launcher's classes.
80 */
Mathew Inwood72fbec12013-11-19 15:45:07 +000081public final class Utilities {
Rahul Chaturvedi7fc77ca2015-05-19 18:02:16 -070082
Joe Onorato1291a8c2009-09-15 15:07:25 -040083 private static final String TAG = "Launcher.Utilities";
84
The Android Open Source Project31dd5032009-03-03 19:32:27 -080085 private static final Rect sOldBounds = new Rect();
Romain Guy89911d22009-09-28 18:48:49 -070086 private static final Canvas sCanvas = new Canvas();
The Android Open Source Project31dd5032009-03-03 19:32:27 -080087
Winson Chung82b016c2015-05-08 17:00:10 -070088 private static final Pattern sTrimPattern =
89 Pattern.compile("^[\\s|\\p{javaSpaceChar}]*(.*)[\\s|\\p{javaSpaceChar}]*$");
90
The Android Open Source Project31dd5032009-03-03 19:32:27 -080091 static {
92 sCanvas.setDrawFilter(new PaintFlagsDrawFilter(Paint.DITHER_FLAG,
93 Paint.FILTER_BITMAP_FLAG));
94 }
Joe Onorato6665c0f2009-09-02 15:27:24 -070095 static int sColors[] = { 0xffff0000, 0xff00ff00, 0xff0000ff };
96 static int sColorIndex = 0;
97
Sunny Goyal53d7ee42015-05-22 12:25:45 -070098 private static final int[] sLoc0 = new int[2];
99 private static final int[] sLoc1 = new int[2];
Michael Jurka7ad868b2013-12-12 15:04:25 +0100100
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700101 // TODO: use Build.VERSION_CODES when available
102 public static final boolean ATLEAST_MARSHMALLOW = Build.VERSION.SDK_INT >= 23;
103
104 public static final boolean ATLEAST_LOLLIPOP_MR1 =
105 Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1;
106
107 public static final boolean ATLEAST_LOLLIPOP =
108 Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
109
110 public static final boolean ATLEAST_KITKAT =
111 Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
112
113 public static final boolean ATLEAST_JB_MR1 =
114 Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1;
115
116 public static final boolean ATLEAST_JB_MR2 =
117 Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2;
118
Sunny Goyal8ac727b2015-09-23 15:38:09 -0700119 // These values are same as that in {@link AsyncTask}.
120 private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
121 private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
122 private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
123 private static final int KEEP_ALIVE = 1;
124 /**
125 * An {@link Executor} to be used with async task with no limit on the queue size.
126 */
127 public static final Executor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(
128 CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
129 TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
130
Michael Jurka7ad868b2013-12-12 15:04:25 +0100131 // To turn on these properties, type
132 // adb shell setprop log.tag.PROPERTY_NAME [VERBOSE | SUPPRESS]
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700133 private static final String FORCE_ENABLE_ROTATION_PROPERTY = "launcher_force_rotate";
134 private static boolean sForceEnableRotation = isPropertyEnabled(FORCE_ENABLE_ROTATION_PROPERTY);
Michael Jurka7ad868b2013-12-12 15:04:25 +0100135
Rahul Chaturvedi7fc77ca2015-05-19 18:02:16 -0700136 public static final String ALLOW_ROTATION_PREFERENCE_KEY = "pref_allowRotation";
137
Sunny Goyal4bbf4192014-11-11 12:23:59 -0800138 public static boolean isPropertyEnabled(String propertyName) {
Michael Jurka7ad868b2013-12-12 15:04:25 +0100139 return Log.isLoggable(propertyName, Log.VERBOSE);
140 }
141
Rahul Chaturvedie863fed2015-06-15 14:09:42 -0400142 public static boolean isAllowRotationPrefEnabled(Context context, boolean multiProcess) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700143 SharedPreferences sharedPrefs = context.getSharedPreferences(
Sunny Goyalf7258242015-10-19 16:59:07 -0700144 LauncherFiles.SHARED_PREFERENCES_KEY, Context.MODE_PRIVATE | (multiProcess ?
Rahul Chaturvedie863fed2015-06-15 14:09:42 -0400145 Context.MODE_MULTI_PROCESS : 0));
Rahul Chaturvedi7fc77ca2015-05-19 18:02:16 -0700146 boolean allowRotationPref = sharedPrefs.getBoolean(ALLOW_ROTATION_PREFERENCE_KEY, false);
147 return sForceEnableRotation || allowRotationPref;
148 }
149
150 public static boolean isRotationAllowedForDevice(Context context) {
151 return sForceEnableRotation || context.getResources().getBoolean(R.bool.allow_rotation);
Michael Jurka7ad868b2013-12-12 15:04:25 +0100152 }
153
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700154 public static Bitmap createIconBitmap(Cursor c, int iconIndex, Context context) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -0800155 byte[] data = c.getBlob(iconIndex);
156 try {
157 return createIconBitmap(BitmapFactory.decodeByteArray(data, 0, data.length), context);
158 } catch (Exception e) {
159 return null;
160 }
161 }
162
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -0700163 /**
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700164 * Returns a bitmap suitable for the all apps view. If the package or the resource do not
165 * exist, it returns null.
166 */
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700167 public static Bitmap createIconBitmap(String packageName, String resourceName,
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700168 Context context) {
169 PackageManager packageManager = context.getPackageManager();
170 // the resource
171 try {
172 Resources resources = packageManager.getResourcesForApplication(packageName);
173 if (resources != null) {
174 final int id = resources.getIdentifier(resourceName, null, null);
175 return createIconBitmap(
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700176 resources.getDrawableForDensity(id, LauncherAppState.getInstance()
177 .getInvariantDeviceProfile().fillResIconDpi), context);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700178 }
179 } catch (Exception e) {
180 // Icon not found.
181 }
182 return null;
183 }
184
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700185 private static int getIconBitmapSize() {
186 return LauncherAppState.getInstance().getInvariantDeviceProfile().iconBitmapSize;
187 }
188
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700189 /**
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700190 * Returns a bitmap which is of the appropriate size to be displayed as an icon
Michael Jurka931dc972011-08-05 15:08:15 -0700191 */
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700192 public static Bitmap createIconBitmap(Bitmap icon, Context context) {
193 final int iconBitmapSize = getIconBitmapSize();
194 if (iconBitmapSize == icon.getWidth() && iconBitmapSize == icon.getHeight()) {
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700195 return icon;
196 }
197 return createIconBitmap(new BitmapDrawable(context.getResources(), icon), context);
Michael Jurka931dc972011-08-05 15:08:15 -0700198 }
199
200 /**
Sunny Goyalfc218302015-09-17 14:59:10 -0700201 * Returns a bitmap suitable for the all apps view. The icon is badged for {@param user}.
202 * The bitmap is also visually normalized with other icons.
Sunny Goyal0b621152015-10-19 14:03:30 -0700203 */
204 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
205 public static Bitmap createBadgedIconBitmap(
206 Drawable icon, UserHandleCompat user, Context context) {
Sunny Goyalfc218302015-09-17 14:59:10 -0700207 float scale = LauncherAppState.isDogfoodBuild() ?
208 IconNormalizer.getInstance().getScale(icon) : 1;
209 Bitmap bitmap = createIconBitmap(icon, context, scale);
Sunny Goyal0b621152015-10-19 14:03:30 -0700210 if (Utilities.ATLEAST_LOLLIPOP && user != null
211 && !UserHandleCompat.myUserHandle().equals(user)) {
212 BitmapDrawable drawable = new BitmapDrawable(context.getResources(), bitmap);
213 Drawable badged = context.getPackageManager().getUserBadgedIcon(
214 drawable, user.getUser());
215 if (badged instanceof BitmapDrawable) {
216 return ((BitmapDrawable) badged).getBitmap();
217 } else {
218 return createIconBitmap(badged, context);
219 }
220 } else {
221 return bitmap;
222 }
223 }
224
225 /**
Michael Jurka931dc972011-08-05 15:08:15 -0700226 * Returns a bitmap suitable for the all apps view.
Joe Onorato6665c0f2009-09-02 15:27:24 -0700227 */
Mathew Inwood72fbec12013-11-19 15:45:07 +0000228 public static Bitmap createIconBitmap(Drawable icon, Context context) {
Sunny Goyalfc218302015-09-17 14:59:10 -0700229 return createIconBitmap(icon, context, 1.0f /* scale */);
230 }
231
232 /**
233 * @param scale the scale to apply before drawing {@param icon} on the canvas
234 */
235 public static Bitmap createIconBitmap(Drawable icon, Context context, float scale) {
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700236 synchronized (sCanvas) {
237 final int iconBitmapSize = getIconBitmapSize();
Joe Onorato6665c0f2009-09-02 15:27:24 -0700238
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700239 int width = iconBitmapSize;
240 int height = iconBitmapSize;
Joe Onorato6665c0f2009-09-02 15:27:24 -0700241
Joe Onorato6665c0f2009-09-02 15:27:24 -0700242 if (icon instanceof PaintDrawable) {
243 PaintDrawable painter = (PaintDrawable) icon;
244 painter.setIntrinsicWidth(width);
245 painter.setIntrinsicHeight(height);
246 } else if (icon instanceof BitmapDrawable) {
247 // Ensure the bitmap has a density.
248 BitmapDrawable bitmapDrawable = (BitmapDrawable) icon;
249 Bitmap bitmap = bitmapDrawable.getBitmap();
Sunny Goyalde9590b2015-09-23 12:56:51 -0700250 if (bitmap != null && bitmap.getDensity() == Bitmap.DENSITY_NONE) {
Joe Onorato6665c0f2009-09-02 15:27:24 -0700251 bitmapDrawable.setTargetDensity(context.getResources().getDisplayMetrics());
252 }
253 }
254 int sourceWidth = icon.getIntrinsicWidth();
255 int sourceHeight = icon.getIntrinsicHeight();
Michael Jurka931dc972011-08-05 15:08:15 -0700256 if (sourceWidth > 0 && sourceHeight > 0) {
Winson Chung5f8afe62013-08-12 16:19:28 -0700257 // Scale the icon proportionally to the icon dimensions
258 final float ratio = (float) sourceWidth / sourceHeight;
259 if (sourceWidth > sourceHeight) {
260 height = (int) (width / ratio);
261 } else if (sourceHeight > sourceWidth) {
262 width = (int) (height * ratio);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700263 }
264 }
265
266 // no intrinsic size --> use default size
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700267 int textureWidth = iconBitmapSize;
268 int textureHeight = iconBitmapSize;
Joe Onorato6665c0f2009-09-02 15:27:24 -0700269
270 final Bitmap bitmap = Bitmap.createBitmap(textureWidth, textureHeight,
271 Bitmap.Config.ARGB_8888);
272 final Canvas canvas = sCanvas;
273 canvas.setBitmap(bitmap);
274
275 final int left = (textureWidth-width) / 2;
276 final int top = (textureHeight-height) / 2;
277
Michael Jurka3a9fced2012-04-13 14:44:29 -0700278 @SuppressWarnings("all") // suppress dead code warning
279 final boolean debug = false;
280 if (debug) {
Joe Onorato6665c0f2009-09-02 15:27:24 -0700281 // draw a big box for the icon for debugging
282 canvas.drawColor(sColors[sColorIndex]);
283 if (++sColorIndex >= sColors.length) sColorIndex = 0;
284 Paint debugPaint = new Paint();
285 debugPaint.setColor(0xffcccc00);
286 canvas.drawRect(left, top, left+width, top+height, debugPaint);
287 }
288
289 sOldBounds.set(icon.getBounds());
290 icon.setBounds(left, top, left+width, top+height);
Sunny Goyalfc218302015-09-17 14:59:10 -0700291 canvas.save(Canvas.MATRIX_SAVE_FLAG);
292 canvas.scale(scale, scale, textureWidth / 2, textureHeight / 2);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700293 icon.draw(canvas);
Sunny Goyalfc218302015-09-17 14:59:10 -0700294 canvas.restore();
Joe Onorato6665c0f2009-09-02 15:27:24 -0700295 icon.setBounds(sOldBounds);
Adam Cohenaaf473c2011-08-03 12:02:47 -0700296 canvas.setBitmap(null);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700297
298 return bitmap;
299 }
300 }
301
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800302 /**
Winson Chungc763c4e2013-07-19 13:49:06 -0700303 * Given a coordinate relative to the descendant, find the coordinate in a parent view's
304 * coordinates.
305 *
306 * @param descendant The descendant to which the passed coordinate is relative.
307 * @param root The root view to make the coordinates relative to.
308 * @param coord The coordinate that we want mapped.
309 * @param includeRootScroll Whether or not to account for the scroll of the descendant:
310 * sometimes this is relevant as in a child's coordinates within the descendant.
311 * @return The factor by which this descendant is scaled relative to this DragLayer. Caution
312 * this scale factor is assumed to be equal in X and Y, and so if at any point this
313 * assumption fails, we will need to return a pair of scale factors.
314 */
315 public static float getDescendantCoordRelativeToParent(View descendant, View root,
316 int[] coord, boolean includeRootScroll) {
317 ArrayList<View> ancestorChain = new ArrayList<View>();
318
319 float[] pt = {coord[0], coord[1]};
320
321 View v = descendant;
322 while(v != root && v != null) {
323 ancestorChain.add(v);
324 v = (View) v.getParent();
325 }
326 ancestorChain.add(root);
327
328 float scale = 1.0f;
329 int count = ancestorChain.size();
330 for (int i = 0; i < count; i++) {
331 View v0 = ancestorChain.get(i);
Winson Chungc763c4e2013-07-19 13:49:06 -0700332 // For TextViews, scroll has a meaning which relates to the text position
333 // which is very strange... ignore the scroll.
334 if (v0 != descendant || includeRootScroll) {
335 pt[0] -= v0.getScrollX();
336 pt[1] -= v0.getScrollY();
337 }
338
339 v0.getMatrix().mapPoints(pt);
340 pt[0] += v0.getLeft();
341 pt[1] += v0.getTop();
342 scale *= v0.getScaleX();
343 }
344
345 coord[0] = (int) Math.round(pt[0]);
346 coord[1] = (int) Math.round(pt[1]);
347 return scale;
348 }
349
350 /**
Sunny Goyalfc218302015-09-17 14:59:10 -0700351 * Inverse of {@link #getDescendantCoordRelativeToParent(View, View, int[], boolean)}.
Winson Chungc763c4e2013-07-19 13:49:06 -0700352 */
353 public static float mapCoordInSelfToDescendent(View descendant, View root,
354 int[] coord) {
355 ArrayList<View> ancestorChain = new ArrayList<View>();
356
357 float[] pt = {coord[0], coord[1]};
358
359 View v = descendant;
360 while(v != root) {
361 ancestorChain.add(v);
362 v = (View) v.getParent();
363 }
364 ancestorChain.add(root);
365
366 float scale = 1.0f;
367 Matrix inverse = new Matrix();
368 int count = ancestorChain.size();
369 for (int i = count - 1; i >= 0; i--) {
370 View ancestor = ancestorChain.get(i);
371 View next = i > 0 ? ancestorChain.get(i-1) : null;
372
373 pt[0] += ancestor.getScrollX();
374 pt[1] += ancestor.getScrollY();
375
376 if (next != null) {
377 pt[0] -= next.getLeft();
378 pt[1] -= next.getTop();
379 next.getMatrix().invert(inverse);
380 inverse.mapPoints(pt);
381 scale *= next.getScaleX();
382 }
383 }
384
385 coord[0] = (int) Math.round(pt[0]);
386 coord[1] = (int) Math.round(pt[1]);
387 return scale;
388 }
389
Jason Monk02dd7ae2014-04-15 15:23:31 -0400390 /**
391 * Utility method to determine whether the given point, in local coordinates,
392 * is inside the view, where the area of the view is expanded by the slop factor.
393 * This method is called while processing touch-move events to determine if the event
394 * is still within the view.
395 */
396 public static boolean pointInView(View v, float localX, float localY, float slop) {
397 return localX >= -slop && localY >= -slop && localX < (v.getWidth() + slop) &&
398 localY < (v.getHeight() + slop);
399 }
400
Winson Chung3a6e7f32013-10-09 15:50:52 -0700401 public static void scaleRect(Rect r, float scale) {
402 if (scale != 1.0f) {
403 r.left = (int) (r.left * scale + 0.5f);
404 r.top = (int) (r.top * scale + 0.5f);
405 r.right = (int) (r.right * scale + 0.5f);
406 r.bottom = (int) (r.bottom * scale + 0.5f);
407 }
408 }
409
Adam Cohen63f1ec02014-08-12 09:23:13 -0700410 public static int[] getCenterDeltaInScreenSpace(View v0, View v1, int[] delta) {
411 v0.getLocationInWindow(sLoc0);
412 v1.getLocationInWindow(sLoc1);
413
414 sLoc0[0] += (v0.getMeasuredWidth() * v0.getScaleX()) / 2;
415 sLoc0[1] += (v0.getMeasuredHeight() * v0.getScaleY()) / 2;
416 sLoc1[0] += (v1.getMeasuredWidth() * v1.getScaleX()) / 2;
417 sLoc1[1] += (v1.getMeasuredHeight() * v1.getScaleY()) / 2;
418
419 if (delta == null) {
420 delta = new int[2];
421 }
422
423 delta[0] = sLoc1[0] - sLoc0[0];
424 delta[1] = sLoc1[1] - sLoc0[1];
425
426 return delta;
427 }
428
Winson Chung3a6e7f32013-10-09 15:50:52 -0700429 public static void scaleRectAboutCenter(Rect r, float scale) {
430 int cx = r.centerX();
431 int cy = r.centerY();
432 r.offset(-cx, -cy);
433 Utilities.scaleRect(r, scale);
434 r.offset(cx, cy);
435 }
436
Michael Jurkaa805e1a2013-08-22 15:00:33 +0200437 public static void startActivityForResultSafely(
438 Activity activity, Intent intent, int requestCode) {
439 try {
440 activity.startActivityForResult(intent, requestCode);
441 } catch (ActivityNotFoundException e) {
442 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
443 } catch (SecurityException e) {
444 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
445 Log.e(TAG, "Launcher does not have the permission to launch " + intent +
446 ". Make sure to create a MAIN intent-filter for the corresponding activity " +
447 "or use the exported attribute for this activity.", e);
448 }
449 }
Sunny Goyalc5c60ad2014-07-14 12:02:01 -0700450
451 static boolean isSystemApp(Context context, Intent intent) {
452 PackageManager pm = context.getPackageManager();
453 ComponentName cn = intent.getComponent();
454 String packageName = null;
455 if (cn == null) {
456 ResolveInfo info = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
457 if ((info != null) && (info.activityInfo != null)) {
458 packageName = info.activityInfo.packageName;
459 }
460 } else {
461 packageName = cn.getPackageName();
462 }
463 if (packageName != null) {
464 try {
465 PackageInfo info = pm.getPackageInfo(packageName, 0);
466 return (info != null) && (info.applicationInfo != null) &&
467 ((info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
468 } catch (NameNotFoundException e) {
469 return false;
470 }
471 } else {
472 return false;
473 }
474 }
Sunny Goyal95abbb32014-08-04 10:53:22 -0700475
476 /**
477 * This picks a dominant color, looking for high-saturation, high-value, repeated hues.
478 * @param bitmap The bitmap to scan
479 * @param samples The approximate max number of samples to use.
480 */
481 static int findDominantColorByHue(Bitmap bitmap, int samples) {
482 final int height = bitmap.getHeight();
483 final int width = bitmap.getWidth();
484 int sampleStride = (int) Math.sqrt((height * width) / samples);
485 if (sampleStride < 1) {
486 sampleStride = 1;
487 }
488
489 // This is an out-param, for getting the hsv values for an rgb
490 float[] hsv = new float[3];
491
492 // First get the best hue, by creating a histogram over 360 hue buckets,
493 // where each pixel contributes a score weighted by saturation, value, and alpha.
494 float[] hueScoreHistogram = new float[360];
495 float highScore = -1;
496 int bestHue = -1;
497
498 for (int y = 0; y < height; y += sampleStride) {
499 for (int x = 0; x < width; x += sampleStride) {
500 int argb = bitmap.getPixel(x, y);
501 int alpha = 0xFF & (argb >> 24);
502 if (alpha < 0x80) {
503 // Drop mostly-transparent pixels.
504 continue;
505 }
506 // Remove the alpha channel.
507 int rgb = argb | 0xFF000000;
508 Color.colorToHSV(rgb, hsv);
509 // Bucket colors by the 360 integer hues.
510 int hue = (int) hsv[0];
511 if (hue < 0 || hue >= hueScoreHistogram.length) {
512 // Defensively avoid array bounds violations.
513 continue;
514 }
515 float score = hsv[1] * hsv[2];
516 hueScoreHistogram[hue] += score;
517 if (hueScoreHistogram[hue] > highScore) {
518 highScore = hueScoreHistogram[hue];
519 bestHue = hue;
520 }
521 }
522 }
523
524 SparseArray<Float> rgbScores = new SparseArray<Float>();
525 int bestColor = 0xff000000;
526 highScore = -1;
527 // Go back over the RGB colors that match the winning hue,
528 // creating a histogram of weighted s*v scores, for up to 100*100 [s,v] buckets.
529 // The highest-scoring RGB color wins.
530 for (int y = 0; y < height; y += sampleStride) {
531 for (int x = 0; x < width; x += sampleStride) {
532 int rgb = bitmap.getPixel(x, y) | 0xff000000;
533 Color.colorToHSV(rgb, hsv);
534 int hue = (int) hsv[0];
535 if (hue == bestHue) {
536 float s = hsv[1];
537 float v = hsv[2];
538 int bucket = (int) (s * 100) + (int) (v * 10000);
539 // Score by cumulative saturation * value.
540 float score = s * v;
541 Float oldTotal = rgbScores.get(bucket);
542 float newTotal = oldTotal == null ? score : oldTotal + score;
543 rgbScores.put(bucket, newTotal);
544 if (newTotal > highScore) {
545 highScore = newTotal;
546 // All the colors in the winning bucket are very similar. Last in wins.
547 bestColor = rgb;
548 }
549 }
550 }
551 }
552 return bestColor;
553 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700554
555 /*
556 * Finds a system apk which had a broadcast receiver listening to a particular action.
557 * @param action intent action used to find the apk
558 * @return a pair of apk package name and the resources.
559 */
560 static Pair<String, Resources> findSystemApk(String action, PackageManager pm) {
561 final Intent intent = new Intent(action);
562 for (ResolveInfo info : pm.queryBroadcastReceivers(intent, 0)) {
563 if (info.activityInfo != null &&
564 (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
565 final String packageName = info.activityInfo.packageName;
566 try {
567 final Resources res = pm.getResourcesForApplication(packageName);
568 return Pair.create(packageName, res);
569 } catch (NameNotFoundException e) {
570 Log.w(TAG, "Failed to find resources for " + packageName);
571 }
572 }
573 }
574 return null;
575 }
Sunny Goyalfafca522014-11-03 11:30:01 -0800576
577 @TargetApi(Build.VERSION_CODES.KITKAT)
578 public static boolean isViewAttachedToWindow(View v) {
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700579 if (ATLEAST_KITKAT) {
Sunny Goyalfafca522014-11-03 11:30:01 -0800580 return v.isAttachedToWindow();
581 } else {
582 // A proxy call which returns null, if the view is not attached to the window.
583 return v.getKeyDispatcherState() != null;
584 }
585 }
Sunny Goyal594d76d2014-11-06 10:12:54 -0800586
587 /**
588 * Returns a widget with category {@link AppWidgetProviderInfo#WIDGET_CATEGORY_SEARCHBOX}
589 * provided by the same package which is set to be global search activity.
590 * If widgetCategory is not supported, or no such widget is found, returns the first widget
591 * provided by the package.
592 */
593 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
594 public static AppWidgetProviderInfo getSearchWidgetProvider(Context context) {
595 SearchManager searchManager =
596 (SearchManager) context.getSystemService(Context.SEARCH_SERVICE);
597 ComponentName searchComponent = searchManager.getGlobalSearchActivity();
598 if (searchComponent == null) return null;
599 String providerPkg = searchComponent.getPackageName();
600
601 AppWidgetProviderInfo defaultWidgetForSearchPackage = null;
602
603 AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
604 for (AppWidgetProviderInfo info : appWidgetManager.getInstalledProviders()) {
605 if (info.provider.getPackageName().equals(providerPkg)) {
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700606 if (ATLEAST_JB_MR1) {
Sunny Goyal594d76d2014-11-06 10:12:54 -0800607 if ((info.widgetCategory & AppWidgetProviderInfo.WIDGET_CATEGORY_SEARCHBOX) != 0) {
608 return info;
609 } else if (defaultWidgetForSearchPackage == null) {
610 defaultWidgetForSearchPackage = info;
611 }
612 } else {
613 return info;
614 }
615 }
616 }
617 return defaultWidgetForSearchPackage;
618 }
Sunny Goyal08f72612015-01-05 13:41:43 -0800619
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700620 /**
621 * Compresses the bitmap to a byte array for serialization.
622 */
623 public static byte[] flattenBitmap(Bitmap bitmap) {
624 // Try go guesstimate how much space the icon will take when serialized
625 // to avoid unnecessary allocations/copies during the write.
626 int size = bitmap.getWidth() * bitmap.getHeight() * 4;
627 ByteArrayOutputStream out = new ByteArrayOutputStream(size);
628 try {
629 bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
630 out.flush();
631 out.close();
632 return out.toByteArray();
633 } catch (IOException e) {
634 Log.w(TAG, "Could not write bitmap");
635 return null;
636 }
637 }
638
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700639 /**
640 * Find the first vacant cell, if there is one.
641 *
642 * @param vacant Holds the x and y coordinate of the vacant cell
643 * @param spanX Horizontal cell span.
644 * @param spanY Vertical cell span.
645 *
646 * @return true if a vacant cell was found
647 */
648 public static boolean findVacantCell(int[] vacant, int spanX, int spanY,
649 int xCount, int yCount, boolean[][] occupied) {
650
651 for (int y = 0; (y + spanY) <= yCount; y++) {
652 for (int x = 0; (x + spanX) <= xCount; x++) {
653 boolean available = !occupied[x][y];
654 out: for (int i = x; i < x + spanX; i++) {
655 for (int j = y; j < y + spanY; j++) {
656 available = available && !occupied[i][j];
657 if (!available) break out;
658 }
659 }
660
661 if (available) {
662 vacant[0] = x;
663 vacant[1] = y;
664 return true;
665 }
666 }
667 }
668
669 return false;
670 }
Winson Chung82b016c2015-05-08 17:00:10 -0700671
672 /**
673 * Trims the string, removing all whitespace at the beginning and end of the string.
674 * Non-breaking whitespaces are also removed.
675 */
676 public static String trim(CharSequence s) {
Winson Chungafa77e92015-05-15 12:04:03 -0700677 if (s == null) {
678 return null;
679 }
680
Winson Chung82b016c2015-05-08 17:00:10 -0700681 // Just strip any sequence of whitespace or java space characters from the beginning and end
682 Matcher m = sTrimPattern.matcher(s);
683 return m.replaceAll("$1");
684 }
Sunny Goyal70660032015-05-14 00:07:08 -0700685
Winson Chung2c6e5cc2015-06-01 14:38:24 -0700686 /**
687 * Calculates the height of a given string at a specific text size.
688 */
689 public static float calculateTextHeight(float textSizePx) {
690 Paint p = new Paint();
691 p.setTextSize(textSizePx);
692 Paint.FontMetrics fm = p.getFontMetrics();
693 return -fm.top + fm.bottom;
694 }
695
Winson Chungb1777442015-06-16 13:35:04 -0700696 /**
697 * Convenience println with multiple args.
698 */
699 public static void println(String key, Object... args) {
700 StringBuilder b = new StringBuilder();
701 b.append(key);
702 b.append(": ");
703 boolean isFirstArgument = true;
704 for (Object arg : args) {
705 if (isFirstArgument) {
706 isFirstArgument = false;
707 } else {
708 b.append(", ");
709 }
710 b.append(arg);
711 }
712 System.out.println(b.toString());
713 }
714
Sunny Goyal70660032015-05-14 00:07:08 -0700715 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
716 public static boolean isRtl(Resources res) {
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700717 return ATLEAST_JB_MR1 &&
Sunny Goyal70660032015-05-14 00:07:08 -0700718 (res.getConfiguration().getLayoutDirection() == View.LAYOUT_DIRECTION_RTL);
719 }
Hyunyoung Song2bd3d7d2015-05-21 13:04:53 -0700720
721 public static void assertWorkerThread() {
Sunny Goyal11d49112015-06-26 14:00:57 -0700722 if (LauncherAppState.isDogfoodBuild() &&
723 (LauncherModel.sWorkerThread.getThreadId() != Process.myTid())) {
724 throw new IllegalStateException();
Hyunyoung Song2bd3d7d2015-05-21 13:04:53 -0700725 }
726 }
Sunny Goyal5c97f512015-05-19 16:03:28 -0700727
728 /**
729 * Returns true if the intent is a valid launch intent for a launcher activity of an app.
730 * This is used to identify shortcuts which are different from the ones exposed by the
731 * applications' manifest file.
732 *
733 * @param launchIntent The intent that will be launched when the shortcut is clicked.
734 */
735 public static boolean isLauncherAppTarget(Intent launchIntent) {
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700736 if (launchIntent != null
Sunny Goyal5c97f512015-05-19 16:03:28 -0700737 && Intent.ACTION_MAIN.equals(launchIntent.getAction())
738 && launchIntent.getComponent() != null
739 && launchIntent.getCategories() != null
740 && launchIntent.getCategories().size() == 1
741 && launchIntent.hasCategory(Intent.CATEGORY_LAUNCHER)
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700742 && TextUtils.isEmpty(launchIntent.getDataString())) {
743 // An app target can either have no extra or have ItemInfo.EXTRA_PROFILE.
744 Bundle extras = launchIntent.getExtras();
745 if (extras == null) {
746 return true;
747 } else {
748 Set<String> keys = extras.keySet();
749 return keys.size() == 1 && keys.contains(ItemInfo.EXTRA_PROFILE);
750 }
751 };
752 return false;
Sunny Goyal5c97f512015-05-19 16:03:28 -0700753 }
Adam Cohen2e6da152015-05-06 11:42:25 -0700754
755 public static float dpiFromPx(int size, DisplayMetrics metrics){
756 float densityRatio = (float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT;
757 return (size / densityRatio);
758 }
759 public static int pxFromDp(float size, DisplayMetrics metrics) {
760 return (int) Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
761 size, metrics));
762 }
763 public static int pxFromSp(float size, DisplayMetrics metrics) {
764 return (int) Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
765 size, metrics));
766 }
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700767
768 public static String createDbSelectionQuery(String columnName, Iterable<?> values) {
769 return String.format(Locale.ENGLISH, "%s IN (%s)", columnName, TextUtils.join(", ", values));
770 }
Sunny Goyale78e3d72015-09-24 11:23:31 -0700771
772 /**
773 * Wraps a message with a TTS span, so that a different message is spoken than
774 * what is getting displayed.
775 * @param msg original message
776 * @param ttsMsg message to be spoken
777 */
778 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
779 public static CharSequence wrapForTts(CharSequence msg, String ttsMsg) {
780 if (Utilities.ATLEAST_LOLLIPOP) {
781 SpannableString spanned = new SpannableString(msg);
782 spanned.setSpan(new TtsSpan.TextBuilder(ttsMsg).build(),
783 0, spanned.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
784 return spanned;
785 } else {
786 return msg;
787 }
788 }
Winson12fb9fc2015-10-01 15:34:08 -0700789
790 /**
791 * Replacement for Long.compare() which was added in API level 19.
792 */
793 public static int longCompare(long lhs, long rhs) {
794 return lhs < rhs ? -1 : (lhs == rhs ? 0 : 1);
795 }
Sunny Goyalf7258242015-10-19 16:59:07 -0700796
797 public static SharedPreferences getPrefs(Context context) {
798 return context.getSharedPreferences(
799 LauncherFiles.SHARED_PREFERENCES_KEY, Context.MODE_PRIVATE);
800 }
Tony Wickham112ac952015-11-12 12:31:50 -0800801
802 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
803 public static boolean isPowerSaverOn(Context context) {
804 PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
805 return ATLEAST_LOLLIPOP && powerManager.isPowerSaveMode();
806 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800807}