blob: 735cbebb732f269cde03d03d600c168427c7aa7b [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 Goyal5b0e6692015-03-19 14:31:19 -070063import java.io.ByteArrayOutputStream;
64import java.io.IOException;
Winson Chungc763c4e2013-07-19 13:49:06 -070065import java.util.ArrayList;
Sunny Goyalb1622cc2015-06-10 16:00:42 -070066import java.util.Locale;
Sunny Goyal4e5cc642015-06-25 16:37:44 -070067import java.util.Set;
Sunny Goyal8ac727b2015-09-23 15:38:09 -070068import java.util.concurrent.Executor;
69import java.util.concurrent.LinkedBlockingQueue;
70import java.util.concurrent.ThreadPoolExecutor;
71import java.util.concurrent.TimeUnit;
Winson Chung82b016c2015-05-08 17:00:10 -070072import java.util.regex.Matcher;
73import java.util.regex.Pattern;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080074
75/**
76 * Various utilities shared amongst the Launcher's classes.
77 */
Mathew Inwood72fbec12013-11-19 15:45:07 +000078public final class Utilities {
Rahul Chaturvedi7fc77ca2015-05-19 18:02:16 -070079
Joe Onorato1291a8c2009-09-15 15:07:25 -040080 private static final String TAG = "Launcher.Utilities";
81
The Android Open Source Project31dd5032009-03-03 19:32:27 -080082 private static final Rect sOldBounds = new Rect();
Romain Guy89911d22009-09-28 18:48:49 -070083 private static final Canvas sCanvas = new Canvas();
The Android Open Source Project31dd5032009-03-03 19:32:27 -080084
Winson Chung82b016c2015-05-08 17:00:10 -070085 private static final Pattern sTrimPattern =
86 Pattern.compile("^[\\s|\\p{javaSpaceChar}]*(.*)[\\s|\\p{javaSpaceChar}]*$");
87
The Android Open Source Project31dd5032009-03-03 19:32:27 -080088 static {
89 sCanvas.setDrawFilter(new PaintFlagsDrawFilter(Paint.DITHER_FLAG,
90 Paint.FILTER_BITMAP_FLAG));
91 }
Joe Onorato6665c0f2009-09-02 15:27:24 -070092 static int sColors[] = { 0xffff0000, 0xff00ff00, 0xff0000ff };
93 static int sColorIndex = 0;
94
Sunny Goyal53d7ee42015-05-22 12:25:45 -070095 private static final int[] sLoc0 = new int[2];
96 private static final int[] sLoc1 = new int[2];
Michael Jurka7ad868b2013-12-12 15:04:25 +010097
Sunny Goyal9fc953b2015-08-17 12:24:25 -070098 // TODO: use Build.VERSION_CODES when available
99 public static final boolean ATLEAST_MARSHMALLOW = Build.VERSION.SDK_INT >= 23;
100
101 public static final boolean ATLEAST_LOLLIPOP_MR1 =
102 Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1;
103
104 public static final boolean ATLEAST_LOLLIPOP =
105 Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
106
107 public static final boolean ATLEAST_KITKAT =
108 Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
109
110 public static final boolean ATLEAST_JB_MR1 =
111 Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1;
112
113 public static final boolean ATLEAST_JB_MR2 =
114 Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2;
115
Sunny Goyal8ac727b2015-09-23 15:38:09 -0700116 // These values are same as that in {@link AsyncTask}.
117 private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
118 private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
119 private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
120 private static final int KEEP_ALIVE = 1;
121 /**
122 * An {@link Executor} to be used with async task with no limit on the queue size.
123 */
124 public static final Executor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(
125 CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
126 TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
127
Michael Jurka7ad868b2013-12-12 15:04:25 +0100128 // To turn on these properties, type
129 // adb shell setprop log.tag.PROPERTY_NAME [VERBOSE | SUPPRESS]
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700130 private static final String FORCE_ENABLE_ROTATION_PROPERTY = "launcher_force_rotate";
131 private static boolean sForceEnableRotation = isPropertyEnabled(FORCE_ENABLE_ROTATION_PROPERTY);
Michael Jurka7ad868b2013-12-12 15:04:25 +0100132
Rahul Chaturvedi7fc77ca2015-05-19 18:02:16 -0700133 public static final String ALLOW_ROTATION_PREFERENCE_KEY = "pref_allowRotation";
134
Sunny Goyal4bbf4192014-11-11 12:23:59 -0800135 public static boolean isPropertyEnabled(String propertyName) {
Michael Jurka7ad868b2013-12-12 15:04:25 +0100136 return Log.isLoggable(propertyName, Log.VERBOSE);
137 }
138
Rahul Chaturvedie863fed2015-06-15 14:09:42 -0400139 public static boolean isAllowRotationPrefEnabled(Context context, boolean multiProcess) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700140 SharedPreferences sharedPrefs = context.getSharedPreferences(
Sunny Goyalf7258242015-10-19 16:59:07 -0700141 LauncherFiles.SHARED_PREFERENCES_KEY, Context.MODE_PRIVATE | (multiProcess ?
Rahul Chaturvedie863fed2015-06-15 14:09:42 -0400142 Context.MODE_MULTI_PROCESS : 0));
Rahul Chaturvedi7fc77ca2015-05-19 18:02:16 -0700143 boolean allowRotationPref = sharedPrefs.getBoolean(ALLOW_ROTATION_PREFERENCE_KEY, false);
144 return sForceEnableRotation || allowRotationPref;
145 }
146
147 public static boolean isRotationAllowedForDevice(Context context) {
148 return sForceEnableRotation || context.getResources().getBoolean(R.bool.allow_rotation);
Michael Jurka7ad868b2013-12-12 15:04:25 +0100149 }
150
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700151 public static Bitmap createIconBitmap(Cursor c, int iconIndex, Context context) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -0800152 byte[] data = c.getBlob(iconIndex);
153 try {
154 return createIconBitmap(BitmapFactory.decodeByteArray(data, 0, data.length), context);
155 } catch (Exception e) {
156 return null;
157 }
158 }
159
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -0700160 /**
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700161 * Returns a bitmap suitable for the all apps view. If the package or the resource do not
162 * exist, it returns null.
163 */
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700164 public static Bitmap createIconBitmap(String packageName, String resourceName,
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700165 Context context) {
166 PackageManager packageManager = context.getPackageManager();
167 // the resource
168 try {
169 Resources resources = packageManager.getResourcesForApplication(packageName);
170 if (resources != null) {
171 final int id = resources.getIdentifier(resourceName, null, null);
172 return createIconBitmap(
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700173 resources.getDrawableForDensity(id, LauncherAppState.getInstance()
174 .getInvariantDeviceProfile().fillResIconDpi), context);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700175 }
176 } catch (Exception e) {
177 // Icon not found.
178 }
179 return null;
180 }
181
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700182 private static int getIconBitmapSize() {
183 return LauncherAppState.getInstance().getInvariantDeviceProfile().iconBitmapSize;
184 }
185
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700186 /**
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700187 * Returns a bitmap which is of the appropriate size to be displayed as an icon
Michael Jurka931dc972011-08-05 15:08:15 -0700188 */
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700189 public static Bitmap createIconBitmap(Bitmap icon, Context context) {
190 final int iconBitmapSize = getIconBitmapSize();
191 if (iconBitmapSize == icon.getWidth() && iconBitmapSize == icon.getHeight()) {
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700192 return icon;
193 }
194 return createIconBitmap(new BitmapDrawable(context.getResources(), icon), context);
Michael Jurka931dc972011-08-05 15:08:15 -0700195 }
196
197 /**
198 * Returns a bitmap suitable for the all apps view.
Joe Onorato6665c0f2009-09-02 15:27:24 -0700199 */
Mathew Inwood72fbec12013-11-19 15:45:07 +0000200 public static Bitmap createIconBitmap(Drawable icon, Context context) {
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700201 synchronized (sCanvas) {
202 final int iconBitmapSize = getIconBitmapSize();
Joe Onorato6665c0f2009-09-02 15:27:24 -0700203
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700204 int width = iconBitmapSize;
205 int height = iconBitmapSize;
Joe Onorato6665c0f2009-09-02 15:27:24 -0700206
Joe Onorato6665c0f2009-09-02 15:27:24 -0700207 if (icon instanceof PaintDrawable) {
208 PaintDrawable painter = (PaintDrawable) icon;
209 painter.setIntrinsicWidth(width);
210 painter.setIntrinsicHeight(height);
211 } else if (icon instanceof BitmapDrawable) {
212 // Ensure the bitmap has a density.
213 BitmapDrawable bitmapDrawable = (BitmapDrawable) icon;
214 Bitmap bitmap = bitmapDrawable.getBitmap();
Sunny Goyalde9590b2015-09-23 12:56:51 -0700215 if (bitmap != null && bitmap.getDensity() == Bitmap.DENSITY_NONE) {
Joe Onorato6665c0f2009-09-02 15:27:24 -0700216 bitmapDrawable.setTargetDensity(context.getResources().getDisplayMetrics());
217 }
218 }
219 int sourceWidth = icon.getIntrinsicWidth();
220 int sourceHeight = icon.getIntrinsicHeight();
Michael Jurka931dc972011-08-05 15:08:15 -0700221 if (sourceWidth > 0 && sourceHeight > 0) {
Winson Chung5f8afe62013-08-12 16:19:28 -0700222 // Scale the icon proportionally to the icon dimensions
223 final float ratio = (float) sourceWidth / sourceHeight;
224 if (sourceWidth > sourceHeight) {
225 height = (int) (width / ratio);
226 } else if (sourceHeight > sourceWidth) {
227 width = (int) (height * ratio);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700228 }
229 }
230
231 // no intrinsic size --> use default size
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700232 int textureWidth = iconBitmapSize;
233 int textureHeight = iconBitmapSize;
Joe Onorato6665c0f2009-09-02 15:27:24 -0700234
235 final Bitmap bitmap = Bitmap.createBitmap(textureWidth, textureHeight,
236 Bitmap.Config.ARGB_8888);
237 final Canvas canvas = sCanvas;
238 canvas.setBitmap(bitmap);
239
240 final int left = (textureWidth-width) / 2;
241 final int top = (textureHeight-height) / 2;
242
Michael Jurka3a9fced2012-04-13 14:44:29 -0700243 @SuppressWarnings("all") // suppress dead code warning
244 final boolean debug = false;
245 if (debug) {
Joe Onorato6665c0f2009-09-02 15:27:24 -0700246 // draw a big box for the icon for debugging
247 canvas.drawColor(sColors[sColorIndex]);
248 if (++sColorIndex >= sColors.length) sColorIndex = 0;
249 Paint debugPaint = new Paint();
250 debugPaint.setColor(0xffcccc00);
251 canvas.drawRect(left, top, left+width, top+height, debugPaint);
252 }
253
254 sOldBounds.set(icon.getBounds());
255 icon.setBounds(left, top, left+width, top+height);
256 icon.draw(canvas);
257 icon.setBounds(sOldBounds);
Adam Cohenaaf473c2011-08-03 12:02:47 -0700258 canvas.setBitmap(null);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700259
260 return bitmap;
261 }
262 }
263
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800264 /**
Winson Chungc763c4e2013-07-19 13:49:06 -0700265 * Given a coordinate relative to the descendant, find the coordinate in a parent view's
266 * coordinates.
267 *
268 * @param descendant The descendant to which the passed coordinate is relative.
269 * @param root The root view to make the coordinates relative to.
270 * @param coord The coordinate that we want mapped.
271 * @param includeRootScroll Whether or not to account for the scroll of the descendant:
272 * sometimes this is relevant as in a child's coordinates within the descendant.
273 * @return The factor by which this descendant is scaled relative to this DragLayer. Caution
274 * this scale factor is assumed to be equal in X and Y, and so if at any point this
275 * assumption fails, we will need to return a pair of scale factors.
276 */
277 public static float getDescendantCoordRelativeToParent(View descendant, View root,
278 int[] coord, boolean includeRootScroll) {
279 ArrayList<View> ancestorChain = new ArrayList<View>();
280
281 float[] pt = {coord[0], coord[1]};
282
283 View v = descendant;
284 while(v != root && v != null) {
285 ancestorChain.add(v);
286 v = (View) v.getParent();
287 }
288 ancestorChain.add(root);
289
290 float scale = 1.0f;
291 int count = ancestorChain.size();
292 for (int i = 0; i < count; i++) {
293 View v0 = ancestorChain.get(i);
Winson Chungc763c4e2013-07-19 13:49:06 -0700294 // For TextViews, scroll has a meaning which relates to the text position
295 // which is very strange... ignore the scroll.
296 if (v0 != descendant || includeRootScroll) {
297 pt[0] -= v0.getScrollX();
298 pt[1] -= v0.getScrollY();
299 }
300
301 v0.getMatrix().mapPoints(pt);
302 pt[0] += v0.getLeft();
303 pt[1] += v0.getTop();
304 scale *= v0.getScaleX();
305 }
306
307 coord[0] = (int) Math.round(pt[0]);
308 coord[1] = (int) Math.round(pt[1]);
309 return scale;
310 }
311
312 /**
313 * Inverse of {@link #getDescendantCoordRelativeToSelf(View, int[])}.
314 */
315 public static float mapCoordInSelfToDescendent(View descendant, View root,
316 int[] coord) {
317 ArrayList<View> ancestorChain = new ArrayList<View>();
318
319 float[] pt = {coord[0], coord[1]};
320
321 View v = descendant;
322 while(v != root) {
323 ancestorChain.add(v);
324 v = (View) v.getParent();
325 }
326 ancestorChain.add(root);
327
328 float scale = 1.0f;
329 Matrix inverse = new Matrix();
330 int count = ancestorChain.size();
331 for (int i = count - 1; i >= 0; i--) {
332 View ancestor = ancestorChain.get(i);
333 View next = i > 0 ? ancestorChain.get(i-1) : null;
334
335 pt[0] += ancestor.getScrollX();
336 pt[1] += ancestor.getScrollY();
337
338 if (next != null) {
339 pt[0] -= next.getLeft();
340 pt[1] -= next.getTop();
341 next.getMatrix().invert(inverse);
342 inverse.mapPoints(pt);
343 scale *= next.getScaleX();
344 }
345 }
346
347 coord[0] = (int) Math.round(pt[0]);
348 coord[1] = (int) Math.round(pt[1]);
349 return scale;
350 }
351
Jason Monk02dd7ae2014-04-15 15:23:31 -0400352 /**
353 * Utility method to determine whether the given point, in local coordinates,
354 * is inside the view, where the area of the view is expanded by the slop factor.
355 * This method is called while processing touch-move events to determine if the event
356 * is still within the view.
357 */
358 public static boolean pointInView(View v, float localX, float localY, float slop) {
359 return localX >= -slop && localY >= -slop && localX < (v.getWidth() + slop) &&
360 localY < (v.getHeight() + slop);
361 }
362
Winson Chung3a6e7f32013-10-09 15:50:52 -0700363 public static void scaleRect(Rect r, float scale) {
364 if (scale != 1.0f) {
365 r.left = (int) (r.left * scale + 0.5f);
366 r.top = (int) (r.top * scale + 0.5f);
367 r.right = (int) (r.right * scale + 0.5f);
368 r.bottom = (int) (r.bottom * scale + 0.5f);
369 }
370 }
371
Adam Cohen63f1ec02014-08-12 09:23:13 -0700372 public static int[] getCenterDeltaInScreenSpace(View v0, View v1, int[] delta) {
373 v0.getLocationInWindow(sLoc0);
374 v1.getLocationInWindow(sLoc1);
375
376 sLoc0[0] += (v0.getMeasuredWidth() * v0.getScaleX()) / 2;
377 sLoc0[1] += (v0.getMeasuredHeight() * v0.getScaleY()) / 2;
378 sLoc1[0] += (v1.getMeasuredWidth() * v1.getScaleX()) / 2;
379 sLoc1[1] += (v1.getMeasuredHeight() * v1.getScaleY()) / 2;
380
381 if (delta == null) {
382 delta = new int[2];
383 }
384
385 delta[0] = sLoc1[0] - sLoc0[0];
386 delta[1] = sLoc1[1] - sLoc0[1];
387
388 return delta;
389 }
390
Winson Chung3a6e7f32013-10-09 15:50:52 -0700391 public static void scaleRectAboutCenter(Rect r, float scale) {
392 int cx = r.centerX();
393 int cy = r.centerY();
394 r.offset(-cx, -cy);
395 Utilities.scaleRect(r, scale);
396 r.offset(cx, cy);
397 }
398
Michael Jurkaa805e1a2013-08-22 15:00:33 +0200399 public static void startActivityForResultSafely(
400 Activity activity, Intent intent, int requestCode) {
401 try {
402 activity.startActivityForResult(intent, requestCode);
403 } catch (ActivityNotFoundException e) {
404 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
405 } catch (SecurityException e) {
406 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
407 Log.e(TAG, "Launcher does not have the permission to launch " + intent +
408 ". Make sure to create a MAIN intent-filter for the corresponding activity " +
409 "or use the exported attribute for this activity.", e);
410 }
411 }
Sunny Goyalc5c60ad2014-07-14 12:02:01 -0700412
413 static boolean isSystemApp(Context context, Intent intent) {
414 PackageManager pm = context.getPackageManager();
415 ComponentName cn = intent.getComponent();
416 String packageName = null;
417 if (cn == null) {
418 ResolveInfo info = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
419 if ((info != null) && (info.activityInfo != null)) {
420 packageName = info.activityInfo.packageName;
421 }
422 } else {
423 packageName = cn.getPackageName();
424 }
425 if (packageName != null) {
426 try {
427 PackageInfo info = pm.getPackageInfo(packageName, 0);
428 return (info != null) && (info.applicationInfo != null) &&
429 ((info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
430 } catch (NameNotFoundException e) {
431 return false;
432 }
433 } else {
434 return false;
435 }
436 }
Sunny Goyal95abbb32014-08-04 10:53:22 -0700437
438 /**
439 * This picks a dominant color, looking for high-saturation, high-value, repeated hues.
440 * @param bitmap The bitmap to scan
441 * @param samples The approximate max number of samples to use.
442 */
443 static int findDominantColorByHue(Bitmap bitmap, int samples) {
444 final int height = bitmap.getHeight();
445 final int width = bitmap.getWidth();
446 int sampleStride = (int) Math.sqrt((height * width) / samples);
447 if (sampleStride < 1) {
448 sampleStride = 1;
449 }
450
451 // This is an out-param, for getting the hsv values for an rgb
452 float[] hsv = new float[3];
453
454 // First get the best hue, by creating a histogram over 360 hue buckets,
455 // where each pixel contributes a score weighted by saturation, value, and alpha.
456 float[] hueScoreHistogram = new float[360];
457 float highScore = -1;
458 int bestHue = -1;
459
460 for (int y = 0; y < height; y += sampleStride) {
461 for (int x = 0; x < width; x += sampleStride) {
462 int argb = bitmap.getPixel(x, y);
463 int alpha = 0xFF & (argb >> 24);
464 if (alpha < 0x80) {
465 // Drop mostly-transparent pixels.
466 continue;
467 }
468 // Remove the alpha channel.
469 int rgb = argb | 0xFF000000;
470 Color.colorToHSV(rgb, hsv);
471 // Bucket colors by the 360 integer hues.
472 int hue = (int) hsv[0];
473 if (hue < 0 || hue >= hueScoreHistogram.length) {
474 // Defensively avoid array bounds violations.
475 continue;
476 }
477 float score = hsv[1] * hsv[2];
478 hueScoreHistogram[hue] += score;
479 if (hueScoreHistogram[hue] > highScore) {
480 highScore = hueScoreHistogram[hue];
481 bestHue = hue;
482 }
483 }
484 }
485
486 SparseArray<Float> rgbScores = new SparseArray<Float>();
487 int bestColor = 0xff000000;
488 highScore = -1;
489 // Go back over the RGB colors that match the winning hue,
490 // creating a histogram of weighted s*v scores, for up to 100*100 [s,v] buckets.
491 // The highest-scoring RGB color wins.
492 for (int y = 0; y < height; y += sampleStride) {
493 for (int x = 0; x < width; x += sampleStride) {
494 int rgb = bitmap.getPixel(x, y) | 0xff000000;
495 Color.colorToHSV(rgb, hsv);
496 int hue = (int) hsv[0];
497 if (hue == bestHue) {
498 float s = hsv[1];
499 float v = hsv[2];
500 int bucket = (int) (s * 100) + (int) (v * 10000);
501 // Score by cumulative saturation * value.
502 float score = s * v;
503 Float oldTotal = rgbScores.get(bucket);
504 float newTotal = oldTotal == null ? score : oldTotal + score;
505 rgbScores.put(bucket, newTotal);
506 if (newTotal > highScore) {
507 highScore = newTotal;
508 // All the colors in the winning bucket are very similar. Last in wins.
509 bestColor = rgb;
510 }
511 }
512 }
513 }
514 return bestColor;
515 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700516
517 /*
518 * Finds a system apk which had a broadcast receiver listening to a particular action.
519 * @param action intent action used to find the apk
520 * @return a pair of apk package name and the resources.
521 */
522 static Pair<String, Resources> findSystemApk(String action, PackageManager pm) {
523 final Intent intent = new Intent(action);
524 for (ResolveInfo info : pm.queryBroadcastReceivers(intent, 0)) {
525 if (info.activityInfo != null &&
526 (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
527 final String packageName = info.activityInfo.packageName;
528 try {
529 final Resources res = pm.getResourcesForApplication(packageName);
530 return Pair.create(packageName, res);
531 } catch (NameNotFoundException e) {
532 Log.w(TAG, "Failed to find resources for " + packageName);
533 }
534 }
535 }
536 return null;
537 }
Sunny Goyalfafca522014-11-03 11:30:01 -0800538
539 @TargetApi(Build.VERSION_CODES.KITKAT)
540 public static boolean isViewAttachedToWindow(View v) {
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700541 if (ATLEAST_KITKAT) {
Sunny Goyalfafca522014-11-03 11:30:01 -0800542 return v.isAttachedToWindow();
543 } else {
544 // A proxy call which returns null, if the view is not attached to the window.
545 return v.getKeyDispatcherState() != null;
546 }
547 }
Sunny Goyal594d76d2014-11-06 10:12:54 -0800548
549 /**
550 * Returns a widget with category {@link AppWidgetProviderInfo#WIDGET_CATEGORY_SEARCHBOX}
551 * provided by the same package which is set to be global search activity.
552 * If widgetCategory is not supported, or no such widget is found, returns the first widget
553 * provided by the package.
554 */
555 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
556 public static AppWidgetProviderInfo getSearchWidgetProvider(Context context) {
557 SearchManager searchManager =
558 (SearchManager) context.getSystemService(Context.SEARCH_SERVICE);
559 ComponentName searchComponent = searchManager.getGlobalSearchActivity();
560 if (searchComponent == null) return null;
561 String providerPkg = searchComponent.getPackageName();
562
563 AppWidgetProviderInfo defaultWidgetForSearchPackage = null;
564
565 AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
566 for (AppWidgetProviderInfo info : appWidgetManager.getInstalledProviders()) {
567 if (info.provider.getPackageName().equals(providerPkg)) {
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700568 if (ATLEAST_JB_MR1) {
Sunny Goyal594d76d2014-11-06 10:12:54 -0800569 if ((info.widgetCategory & AppWidgetProviderInfo.WIDGET_CATEGORY_SEARCHBOX) != 0) {
570 return info;
571 } else if (defaultWidgetForSearchPackage == null) {
572 defaultWidgetForSearchPackage = info;
573 }
574 } else {
575 return info;
576 }
577 }
578 }
579 return defaultWidgetForSearchPackage;
580 }
Sunny Goyal08f72612015-01-05 13:41:43 -0800581
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700582 /**
583 * Compresses the bitmap to a byte array for serialization.
584 */
585 public static byte[] flattenBitmap(Bitmap bitmap) {
586 // Try go guesstimate how much space the icon will take when serialized
587 // to avoid unnecessary allocations/copies during the write.
588 int size = bitmap.getWidth() * bitmap.getHeight() * 4;
589 ByteArrayOutputStream out = new ByteArrayOutputStream(size);
590 try {
591 bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
592 out.flush();
593 out.close();
594 return out.toByteArray();
595 } catch (IOException e) {
596 Log.w(TAG, "Could not write bitmap");
597 return null;
598 }
599 }
600
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700601 /**
602 * Find the first vacant cell, if there is one.
603 *
604 * @param vacant Holds the x and y coordinate of the vacant cell
605 * @param spanX Horizontal cell span.
606 * @param spanY Vertical cell span.
607 *
608 * @return true if a vacant cell was found
609 */
610 public static boolean findVacantCell(int[] vacant, int spanX, int spanY,
611 int xCount, int yCount, boolean[][] occupied) {
612
613 for (int y = 0; (y + spanY) <= yCount; y++) {
614 for (int x = 0; (x + spanX) <= xCount; x++) {
615 boolean available = !occupied[x][y];
616 out: for (int i = x; i < x + spanX; i++) {
617 for (int j = y; j < y + spanY; j++) {
618 available = available && !occupied[i][j];
619 if (!available) break out;
620 }
621 }
622
623 if (available) {
624 vacant[0] = x;
625 vacant[1] = y;
626 return true;
627 }
628 }
629 }
630
631 return false;
632 }
Winson Chung82b016c2015-05-08 17:00:10 -0700633
634 /**
635 * Trims the string, removing all whitespace at the beginning and end of the string.
636 * Non-breaking whitespaces are also removed.
637 */
638 public static String trim(CharSequence s) {
Winson Chungafa77e92015-05-15 12:04:03 -0700639 if (s == null) {
640 return null;
641 }
642
Winson Chung82b016c2015-05-08 17:00:10 -0700643 // Just strip any sequence of whitespace or java space characters from the beginning and end
644 Matcher m = sTrimPattern.matcher(s);
645 return m.replaceAll("$1");
646 }
Sunny Goyal70660032015-05-14 00:07:08 -0700647
Winson Chung2c6e5cc2015-06-01 14:38:24 -0700648 /**
649 * Calculates the height of a given string at a specific text size.
650 */
651 public static float calculateTextHeight(float textSizePx) {
652 Paint p = new Paint();
653 p.setTextSize(textSizePx);
654 Paint.FontMetrics fm = p.getFontMetrics();
655 return -fm.top + fm.bottom;
656 }
657
Winson Chungb1777442015-06-16 13:35:04 -0700658 /**
659 * Convenience println with multiple args.
660 */
661 public static void println(String key, Object... args) {
662 StringBuilder b = new StringBuilder();
663 b.append(key);
664 b.append(": ");
665 boolean isFirstArgument = true;
666 for (Object arg : args) {
667 if (isFirstArgument) {
668 isFirstArgument = false;
669 } else {
670 b.append(", ");
671 }
672 b.append(arg);
673 }
674 System.out.println(b.toString());
675 }
676
Sunny Goyal70660032015-05-14 00:07:08 -0700677 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
678 public static boolean isRtl(Resources res) {
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700679 return ATLEAST_JB_MR1 &&
Sunny Goyal70660032015-05-14 00:07:08 -0700680 (res.getConfiguration().getLayoutDirection() == View.LAYOUT_DIRECTION_RTL);
681 }
Hyunyoung Song2bd3d7d2015-05-21 13:04:53 -0700682
683 public static void assertWorkerThread() {
Sunny Goyal11d49112015-06-26 14:00:57 -0700684 if (LauncherAppState.isDogfoodBuild() &&
685 (LauncherModel.sWorkerThread.getThreadId() != Process.myTid())) {
686 throw new IllegalStateException();
Hyunyoung Song2bd3d7d2015-05-21 13:04:53 -0700687 }
688 }
Sunny Goyal5c97f512015-05-19 16:03:28 -0700689
690 /**
691 * Returns true if the intent is a valid launch intent for a launcher activity of an app.
692 * This is used to identify shortcuts which are different from the ones exposed by the
693 * applications' manifest file.
694 *
695 * @param launchIntent The intent that will be launched when the shortcut is clicked.
696 */
697 public static boolean isLauncherAppTarget(Intent launchIntent) {
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700698 if (launchIntent != null
Sunny Goyal5c97f512015-05-19 16:03:28 -0700699 && Intent.ACTION_MAIN.equals(launchIntent.getAction())
700 && launchIntent.getComponent() != null
701 && launchIntent.getCategories() != null
702 && launchIntent.getCategories().size() == 1
703 && launchIntent.hasCategory(Intent.CATEGORY_LAUNCHER)
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700704 && TextUtils.isEmpty(launchIntent.getDataString())) {
705 // An app target can either have no extra or have ItemInfo.EXTRA_PROFILE.
706 Bundle extras = launchIntent.getExtras();
707 if (extras == null) {
708 return true;
709 } else {
710 Set<String> keys = extras.keySet();
711 return keys.size() == 1 && keys.contains(ItemInfo.EXTRA_PROFILE);
712 }
713 };
714 return false;
Sunny Goyal5c97f512015-05-19 16:03:28 -0700715 }
Adam Cohen2e6da152015-05-06 11:42:25 -0700716
717 public static float dpiFromPx(int size, DisplayMetrics metrics){
718 float densityRatio = (float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT;
719 return (size / densityRatio);
720 }
721 public static int pxFromDp(float size, DisplayMetrics metrics) {
722 return (int) Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
723 size, metrics));
724 }
725 public static int pxFromSp(float size, DisplayMetrics metrics) {
726 return (int) Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
727 size, metrics));
728 }
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700729
730 public static String createDbSelectionQuery(String columnName, Iterable<?> values) {
731 return String.format(Locale.ENGLISH, "%s IN (%s)", columnName, TextUtils.join(", ", values));
732 }
Sunny Goyale78e3d72015-09-24 11:23:31 -0700733
734 /**
735 * Wraps a message with a TTS span, so that a different message is spoken than
736 * what is getting displayed.
737 * @param msg original message
738 * @param ttsMsg message to be spoken
739 */
740 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
741 public static CharSequence wrapForTts(CharSequence msg, String ttsMsg) {
742 if (Utilities.ATLEAST_LOLLIPOP) {
743 SpannableString spanned = new SpannableString(msg);
744 spanned.setSpan(new TtsSpan.TextBuilder(ttsMsg).build(),
745 0, spanned.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
746 return spanned;
747 } else {
748 return msg;
749 }
750 }
Winson12fb9fc2015-10-01 15:34:08 -0700751
752 /**
753 * Replacement for Long.compare() which was added in API level 19.
754 */
755 public static int longCompare(long lhs, long rhs) {
756 return lhs < rhs ? -1 : (lhs == rhs ? 0 : 1);
757 }
Sunny Goyalf7258242015-10-19 16:59:07 -0700758
759 public static SharedPreferences getPrefs(Context context) {
760 return context.getSharedPreferences(
761 LauncherFiles.SHARED_PREFERENCES_KEY, Context.MODE_PRIVATE);
762 }
Tony Wickham112ac952015-11-12 12:31:50 -0800763
764 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
765 public static boolean isPowerSaverOn(Context context) {
766 PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
767 return ATLEAST_LOLLIPOP && powerManager.isPowerSaveMode();
768 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800769}