blob: 00d4c8d83c30357daae88c5d06c510865643fc7f [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;
Hyunyoung Song2bd3d7d2015-05-21 13:04:53 -070049import android.os.Process;
Sunny Goyal5c97f512015-05-19 16:03:28 -070050import android.text.TextUtils;
Adam Cohen2e6da152015-05-06 11:42:25 -070051import android.util.DisplayMetrics;
Michael Jurkaa805e1a2013-08-22 15:00:33 +020052import android.util.Log;
Sunny Goyal0fe505b2014-08-06 09:55:36 -070053import android.util.Pair;
Sunny Goyal95abbb32014-08-04 10:53:22 -070054import android.util.SparseArray;
Adam Cohen2e6da152015-05-06 11:42:25 -070055import android.util.TypedValue;
Winson Chungc763c4e2013-07-19 13:49:06 -070056import android.view.View;
Michael Jurkaa805e1a2013-08-22 15:00:33 +020057import android.widget.Toast;
Sunny Goyalb1622cc2015-06-10 16:00:42 -070058
Sunny Goyal6c56c682015-07-16 14:09:05 -070059import com.android.launcher3.config.ProviderConfig;
60
Sunny Goyal5b0e6692015-03-19 14:31:19 -070061import java.io.ByteArrayOutputStream;
62import java.io.IOException;
Sunny Goyal25aba0a2015-07-16 15:07:47 -070063import java.lang.reflect.Method;
Winson Chungc763c4e2013-07-19 13:49:06 -070064import java.util.ArrayList;
Sunny Goyalb1622cc2015-06-10 16:00:42 -070065import java.util.Locale;
Sunny Goyal4e5cc642015-06-25 16:37:44 -070066import java.util.Set;
Winson Chung82b016c2015-05-08 17:00:10 -070067import java.util.regex.Matcher;
68import java.util.regex.Pattern;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080069
70/**
71 * Various utilities shared amongst the Launcher's classes.
72 */
Mathew Inwood72fbec12013-11-19 15:45:07 +000073public final class Utilities {
Rahul Chaturvedi7fc77ca2015-05-19 18:02:16 -070074
Joe Onorato1291a8c2009-09-15 15:07:25 -040075 private static final String TAG = "Launcher.Utilities";
76
The Android Open Source Project31dd5032009-03-03 19:32:27 -080077 private static final Rect sOldBounds = new Rect();
Romain Guy89911d22009-09-28 18:48:49 -070078 private static final Canvas sCanvas = new Canvas();
The Android Open Source Project31dd5032009-03-03 19:32:27 -080079
Winson Chung82b016c2015-05-08 17:00:10 -070080 private static final Pattern sTrimPattern =
81 Pattern.compile("^[\\s|\\p{javaSpaceChar}]*(.*)[\\s|\\p{javaSpaceChar}]*$");
82
The Android Open Source Project31dd5032009-03-03 19:32:27 -080083 static {
84 sCanvas.setDrawFilter(new PaintFlagsDrawFilter(Paint.DITHER_FLAG,
85 Paint.FILTER_BITMAP_FLAG));
86 }
Joe Onorato6665c0f2009-09-02 15:27:24 -070087 static int sColors[] = { 0xffff0000, 0xff00ff00, 0xff0000ff };
88 static int sColorIndex = 0;
89
Sunny Goyal53d7ee42015-05-22 12:25:45 -070090 private static final int[] sLoc0 = new int[2];
91 private static final int[] sLoc1 = new int[2];
Michael Jurka7ad868b2013-12-12 15:04:25 +010092
93 // To turn on these properties, type
94 // adb shell setprop log.tag.PROPERTY_NAME [VERBOSE | SUPPRESS]
Sunny Goyal53d7ee42015-05-22 12:25:45 -070095 private static final String FORCE_ENABLE_ROTATION_PROPERTY = "launcher_force_rotate";
96 private static boolean sForceEnableRotation = isPropertyEnabled(FORCE_ENABLE_ROTATION_PROPERTY);
Michael Jurka7ad868b2013-12-12 15:04:25 +010097
Rahul Chaturvedi7fc77ca2015-05-19 18:02:16 -070098 public static final String ALLOW_ROTATION_PREFERENCE_KEY = "pref_allowRotation";
99
Sunny Goyal4bbf4192014-11-11 12:23:59 -0800100 public static boolean isPropertyEnabled(String propertyName) {
Michael Jurka7ad868b2013-12-12 15:04:25 +0100101 return Log.isLoggable(propertyName, Log.VERBOSE);
102 }
103
Rahul Chaturvedie863fed2015-06-15 14:09:42 -0400104 public static boolean isAllowRotationPrefEnabled(Context context, boolean multiProcess) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700105 SharedPreferences sharedPrefs = context.getSharedPreferences(
Rahul Chaturvedie863fed2015-06-15 14:09:42 -0400106 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE | (multiProcess ?
107 Context.MODE_MULTI_PROCESS : 0));
Rahul Chaturvedi7fc77ca2015-05-19 18:02:16 -0700108 boolean allowRotationPref = sharedPrefs.getBoolean(ALLOW_ROTATION_PREFERENCE_KEY, false);
109 return sForceEnableRotation || allowRotationPref;
110 }
111
112 public static boolean isRotationAllowedForDevice(Context context) {
113 return sForceEnableRotation || context.getResources().getBoolean(R.bool.allow_rotation);
Michael Jurka7ad868b2013-12-12 15:04:25 +0100114 }
115
Winson Chung0dbd7342013-10-13 22:46:20 -0700116 /**
Kenny Guyd794a3f2014-09-16 15:17:58 +0100117 * Indicates if the device is running LMP or higher.
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -0700118 */
Kenny Guyd794a3f2014-09-16 15:17:58 +0100119 public static boolean isLmpOrAbove() {
Brian Parfett1bc1ae62014-12-12 12:30:00 -0800120 return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -0700121 }
122
Adam Cohen15588932015-05-26 23:03:31 -0700123 public static boolean isLmpMR1OrAbove() {
124 // TODO(adamcohen): update to Build.VERSION_CODES.LOLLIPOP_MR1 once building against 22;
125 return Build.VERSION.SDK_INT >= 22;
126 }
127
Adam Cohen947e02b2015-05-22 19:23:34 -0700128 public static boolean isLmpMR1() {
129 // TODO(adamcohen): update to Build.VERSION_CODES.LOLLIPOP_MR1 once building against 22;
130 return Build.VERSION.SDK_INT == 22;
131 }
132
Vadim Tryshev9de91272015-08-03 18:37:17 -0700133 public static boolean isNycOrAbove() {
134 // TODO(vadimt): Replace using reflection with looking at the API version once
135 // Build.VERSION.SDK_INT gets bumped to 24. b/22942492.
136 try {
137 View.class.getDeclaredField("DRAG_FLAG_OPAQUE");
138 // View.DRAG_FLAG_OPAQUE doesn't exist in M-release, so it's an indication of N+.
139 return true;
140 } catch (NoSuchFieldException e) {
141 return false;
142 }
143 }
144
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700145 public static Bitmap createIconBitmap(Cursor c, int iconIndex, Context context) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -0800146 byte[] data = c.getBlob(iconIndex);
147 try {
148 return createIconBitmap(BitmapFactory.decodeByteArray(data, 0, data.length), context);
149 } catch (Exception e) {
150 return null;
151 }
152 }
153
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -0700154 /**
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700155 * Returns a bitmap suitable for the all apps view. If the package or the resource do not
156 * exist, it returns null.
157 */
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700158 public static Bitmap createIconBitmap(String packageName, String resourceName,
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700159 Context context) {
160 PackageManager packageManager = context.getPackageManager();
161 // the resource
162 try {
163 Resources resources = packageManager.getResourcesForApplication(packageName);
164 if (resources != null) {
165 final int id = resources.getIdentifier(resourceName, null, null);
166 return createIconBitmap(
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700167 resources.getDrawableForDensity(id, LauncherAppState.getInstance()
168 .getInvariantDeviceProfile().fillResIconDpi), context);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700169 }
170 } catch (Exception e) {
171 // Icon not found.
172 }
173 return null;
174 }
175
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700176 private static int getIconBitmapSize() {
177 return LauncherAppState.getInstance().getInvariantDeviceProfile().iconBitmapSize;
178 }
179
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700180 /**
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700181 * Returns a bitmap which is of the appropriate size to be displayed as an icon
Michael Jurka931dc972011-08-05 15:08:15 -0700182 */
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700183 public static Bitmap createIconBitmap(Bitmap icon, Context context) {
184 final int iconBitmapSize = getIconBitmapSize();
185 if (iconBitmapSize == icon.getWidth() && iconBitmapSize == icon.getHeight()) {
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700186 return icon;
187 }
188 return createIconBitmap(new BitmapDrawable(context.getResources(), icon), context);
Michael Jurka931dc972011-08-05 15:08:15 -0700189 }
190
191 /**
192 * Returns a bitmap suitable for the all apps view.
Joe Onorato6665c0f2009-09-02 15:27:24 -0700193 */
Mathew Inwood72fbec12013-11-19 15:45:07 +0000194 public static Bitmap createIconBitmap(Drawable icon, Context context) {
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700195 synchronized (sCanvas) {
196 final int iconBitmapSize = getIconBitmapSize();
Joe Onorato6665c0f2009-09-02 15:27:24 -0700197
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700198 int width = iconBitmapSize;
199 int height = iconBitmapSize;
Joe Onorato6665c0f2009-09-02 15:27:24 -0700200
Joe Onorato6665c0f2009-09-02 15:27:24 -0700201 if (icon instanceof PaintDrawable) {
202 PaintDrawable painter = (PaintDrawable) icon;
203 painter.setIntrinsicWidth(width);
204 painter.setIntrinsicHeight(height);
205 } else if (icon instanceof BitmapDrawable) {
206 // Ensure the bitmap has a density.
207 BitmapDrawable bitmapDrawable = (BitmapDrawable) icon;
208 Bitmap bitmap = bitmapDrawable.getBitmap();
209 if (bitmap.getDensity() == Bitmap.DENSITY_NONE) {
210 bitmapDrawable.setTargetDensity(context.getResources().getDisplayMetrics());
211 }
212 }
213 int sourceWidth = icon.getIntrinsicWidth();
214 int sourceHeight = icon.getIntrinsicHeight();
Michael Jurka931dc972011-08-05 15:08:15 -0700215 if (sourceWidth > 0 && sourceHeight > 0) {
Winson Chung5f8afe62013-08-12 16:19:28 -0700216 // Scale the icon proportionally to the icon dimensions
217 final float ratio = (float) sourceWidth / sourceHeight;
218 if (sourceWidth > sourceHeight) {
219 height = (int) (width / ratio);
220 } else if (sourceHeight > sourceWidth) {
221 width = (int) (height * ratio);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700222 }
223 }
224
225 // no intrinsic size --> use default size
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700226 int textureWidth = iconBitmapSize;
227 int textureHeight = iconBitmapSize;
Joe Onorato6665c0f2009-09-02 15:27:24 -0700228
229 final Bitmap bitmap = Bitmap.createBitmap(textureWidth, textureHeight,
230 Bitmap.Config.ARGB_8888);
231 final Canvas canvas = sCanvas;
232 canvas.setBitmap(bitmap);
233
234 final int left = (textureWidth-width) / 2;
235 final int top = (textureHeight-height) / 2;
236
Michael Jurka3a9fced2012-04-13 14:44:29 -0700237 @SuppressWarnings("all") // suppress dead code warning
238 final boolean debug = false;
239 if (debug) {
Joe Onorato6665c0f2009-09-02 15:27:24 -0700240 // draw a big box for the icon for debugging
241 canvas.drawColor(sColors[sColorIndex]);
242 if (++sColorIndex >= sColors.length) sColorIndex = 0;
243 Paint debugPaint = new Paint();
244 debugPaint.setColor(0xffcccc00);
245 canvas.drawRect(left, top, left+width, top+height, debugPaint);
246 }
247
248 sOldBounds.set(icon.getBounds());
249 icon.setBounds(left, top, left+width, top+height);
250 icon.draw(canvas);
251 icon.setBounds(sOldBounds);
Adam Cohenaaf473c2011-08-03 12:02:47 -0700252 canvas.setBitmap(null);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700253
254 return bitmap;
255 }
256 }
257
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800258 /**
Winson Chungc763c4e2013-07-19 13:49:06 -0700259 * Given a coordinate relative to the descendant, find the coordinate in a parent view's
260 * coordinates.
261 *
262 * @param descendant The descendant to which the passed coordinate is relative.
263 * @param root The root view to make the coordinates relative to.
264 * @param coord The coordinate that we want mapped.
265 * @param includeRootScroll Whether or not to account for the scroll of the descendant:
266 * sometimes this is relevant as in a child's coordinates within the descendant.
267 * @return The factor by which this descendant is scaled relative to this DragLayer. Caution
268 * this scale factor is assumed to be equal in X and Y, and so if at any point this
269 * assumption fails, we will need to return a pair of scale factors.
270 */
271 public static float getDescendantCoordRelativeToParent(View descendant, View root,
272 int[] coord, boolean includeRootScroll) {
273 ArrayList<View> ancestorChain = new ArrayList<View>();
274
275 float[] pt = {coord[0], coord[1]};
276
277 View v = descendant;
278 while(v != root && v != null) {
279 ancestorChain.add(v);
280 v = (View) v.getParent();
281 }
282 ancestorChain.add(root);
283
284 float scale = 1.0f;
285 int count = ancestorChain.size();
286 for (int i = 0; i < count; i++) {
287 View v0 = ancestorChain.get(i);
Winson Chungc763c4e2013-07-19 13:49:06 -0700288 // For TextViews, scroll has a meaning which relates to the text position
289 // which is very strange... ignore the scroll.
290 if (v0 != descendant || includeRootScroll) {
291 pt[0] -= v0.getScrollX();
292 pt[1] -= v0.getScrollY();
293 }
294
295 v0.getMatrix().mapPoints(pt);
296 pt[0] += v0.getLeft();
297 pt[1] += v0.getTop();
298 scale *= v0.getScaleX();
299 }
300
301 coord[0] = (int) Math.round(pt[0]);
302 coord[1] = (int) Math.round(pt[1]);
303 return scale;
304 }
305
306 /**
307 * Inverse of {@link #getDescendantCoordRelativeToSelf(View, int[])}.
308 */
309 public static float mapCoordInSelfToDescendent(View descendant, View root,
310 int[] coord) {
311 ArrayList<View> ancestorChain = new ArrayList<View>();
312
313 float[] pt = {coord[0], coord[1]};
314
315 View v = descendant;
316 while(v != root) {
317 ancestorChain.add(v);
318 v = (View) v.getParent();
319 }
320 ancestorChain.add(root);
321
322 float scale = 1.0f;
323 Matrix inverse = new Matrix();
324 int count = ancestorChain.size();
325 for (int i = count - 1; i >= 0; i--) {
326 View ancestor = ancestorChain.get(i);
327 View next = i > 0 ? ancestorChain.get(i-1) : null;
328
329 pt[0] += ancestor.getScrollX();
330 pt[1] += ancestor.getScrollY();
331
332 if (next != null) {
333 pt[0] -= next.getLeft();
334 pt[1] -= next.getTop();
335 next.getMatrix().invert(inverse);
336 inverse.mapPoints(pt);
337 scale *= next.getScaleX();
338 }
339 }
340
341 coord[0] = (int) Math.round(pt[0]);
342 coord[1] = (int) Math.round(pt[1]);
343 return scale;
344 }
345
Jason Monk02dd7ae2014-04-15 15:23:31 -0400346 /**
347 * Utility method to determine whether the given point, in local coordinates,
348 * is inside the view, where the area of the view is expanded by the slop factor.
349 * This method is called while processing touch-move events to determine if the event
350 * is still within the view.
351 */
352 public static boolean pointInView(View v, float localX, float localY, float slop) {
353 return localX >= -slop && localY >= -slop && localX < (v.getWidth() + slop) &&
354 localY < (v.getHeight() + slop);
355 }
356
Winson Chung3a6e7f32013-10-09 15:50:52 -0700357 public static void scaleRect(Rect r, float scale) {
358 if (scale != 1.0f) {
359 r.left = (int) (r.left * scale + 0.5f);
360 r.top = (int) (r.top * scale + 0.5f);
361 r.right = (int) (r.right * scale + 0.5f);
362 r.bottom = (int) (r.bottom * scale + 0.5f);
363 }
364 }
365
Adam Cohen63f1ec02014-08-12 09:23:13 -0700366 public static int[] getCenterDeltaInScreenSpace(View v0, View v1, int[] delta) {
367 v0.getLocationInWindow(sLoc0);
368 v1.getLocationInWindow(sLoc1);
369
370 sLoc0[0] += (v0.getMeasuredWidth() * v0.getScaleX()) / 2;
371 sLoc0[1] += (v0.getMeasuredHeight() * v0.getScaleY()) / 2;
372 sLoc1[0] += (v1.getMeasuredWidth() * v1.getScaleX()) / 2;
373 sLoc1[1] += (v1.getMeasuredHeight() * v1.getScaleY()) / 2;
374
375 if (delta == null) {
376 delta = new int[2];
377 }
378
379 delta[0] = sLoc1[0] - sLoc0[0];
380 delta[1] = sLoc1[1] - sLoc0[1];
381
382 return delta;
383 }
384
Winson Chung3a6e7f32013-10-09 15:50:52 -0700385 public static void scaleRectAboutCenter(Rect r, float scale) {
386 int cx = r.centerX();
387 int cy = r.centerY();
388 r.offset(-cx, -cy);
389 Utilities.scaleRect(r, scale);
390 r.offset(cx, cy);
391 }
392
Michael Jurkaa805e1a2013-08-22 15:00:33 +0200393 public static void startActivityForResultSafely(
394 Activity activity, Intent intent, int requestCode) {
395 try {
396 activity.startActivityForResult(intent, requestCode);
397 } catch (ActivityNotFoundException e) {
398 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
399 } catch (SecurityException e) {
400 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
401 Log.e(TAG, "Launcher does not have the permission to launch " + intent +
402 ". Make sure to create a MAIN intent-filter for the corresponding activity " +
403 "or use the exported attribute for this activity.", e);
404 }
405 }
Sunny Goyalc5c60ad2014-07-14 12:02:01 -0700406
407 static boolean isSystemApp(Context context, Intent intent) {
408 PackageManager pm = context.getPackageManager();
409 ComponentName cn = intent.getComponent();
410 String packageName = null;
411 if (cn == null) {
412 ResolveInfo info = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
413 if ((info != null) && (info.activityInfo != null)) {
414 packageName = info.activityInfo.packageName;
415 }
416 } else {
417 packageName = cn.getPackageName();
418 }
419 if (packageName != null) {
420 try {
421 PackageInfo info = pm.getPackageInfo(packageName, 0);
422 return (info != null) && (info.applicationInfo != null) &&
423 ((info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
424 } catch (NameNotFoundException e) {
425 return false;
426 }
427 } else {
428 return false;
429 }
430 }
Sunny Goyal95abbb32014-08-04 10:53:22 -0700431
432 /**
433 * This picks a dominant color, looking for high-saturation, high-value, repeated hues.
434 * @param bitmap The bitmap to scan
435 * @param samples The approximate max number of samples to use.
436 */
437 static int findDominantColorByHue(Bitmap bitmap, int samples) {
438 final int height = bitmap.getHeight();
439 final int width = bitmap.getWidth();
440 int sampleStride = (int) Math.sqrt((height * width) / samples);
441 if (sampleStride < 1) {
442 sampleStride = 1;
443 }
444
445 // This is an out-param, for getting the hsv values for an rgb
446 float[] hsv = new float[3];
447
448 // First get the best hue, by creating a histogram over 360 hue buckets,
449 // where each pixel contributes a score weighted by saturation, value, and alpha.
450 float[] hueScoreHistogram = new float[360];
451 float highScore = -1;
452 int bestHue = -1;
453
454 for (int y = 0; y < height; y += sampleStride) {
455 for (int x = 0; x < width; x += sampleStride) {
456 int argb = bitmap.getPixel(x, y);
457 int alpha = 0xFF & (argb >> 24);
458 if (alpha < 0x80) {
459 // Drop mostly-transparent pixels.
460 continue;
461 }
462 // Remove the alpha channel.
463 int rgb = argb | 0xFF000000;
464 Color.colorToHSV(rgb, hsv);
465 // Bucket colors by the 360 integer hues.
466 int hue = (int) hsv[0];
467 if (hue < 0 || hue >= hueScoreHistogram.length) {
468 // Defensively avoid array bounds violations.
469 continue;
470 }
471 float score = hsv[1] * hsv[2];
472 hueScoreHistogram[hue] += score;
473 if (hueScoreHistogram[hue] > highScore) {
474 highScore = hueScoreHistogram[hue];
475 bestHue = hue;
476 }
477 }
478 }
479
480 SparseArray<Float> rgbScores = new SparseArray<Float>();
481 int bestColor = 0xff000000;
482 highScore = -1;
483 // Go back over the RGB colors that match the winning hue,
484 // creating a histogram of weighted s*v scores, for up to 100*100 [s,v] buckets.
485 // The highest-scoring RGB color wins.
486 for (int y = 0; y < height; y += sampleStride) {
487 for (int x = 0; x < width; x += sampleStride) {
488 int rgb = bitmap.getPixel(x, y) | 0xff000000;
489 Color.colorToHSV(rgb, hsv);
490 int hue = (int) hsv[0];
491 if (hue == bestHue) {
492 float s = hsv[1];
493 float v = hsv[2];
494 int bucket = (int) (s * 100) + (int) (v * 10000);
495 // Score by cumulative saturation * value.
496 float score = s * v;
497 Float oldTotal = rgbScores.get(bucket);
498 float newTotal = oldTotal == null ? score : oldTotal + score;
499 rgbScores.put(bucket, newTotal);
500 if (newTotal > highScore) {
501 highScore = newTotal;
502 // All the colors in the winning bucket are very similar. Last in wins.
503 bestColor = rgb;
504 }
505 }
506 }
507 }
508 return bestColor;
509 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700510
511 /*
512 * Finds a system apk which had a broadcast receiver listening to a particular action.
513 * @param action intent action used to find the apk
514 * @return a pair of apk package name and the resources.
515 */
516 static Pair<String, Resources> findSystemApk(String action, PackageManager pm) {
517 final Intent intent = new Intent(action);
518 for (ResolveInfo info : pm.queryBroadcastReceivers(intent, 0)) {
519 if (info.activityInfo != null &&
520 (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
521 final String packageName = info.activityInfo.packageName;
522 try {
523 final Resources res = pm.getResourcesForApplication(packageName);
524 return Pair.create(packageName, res);
525 } catch (NameNotFoundException e) {
526 Log.w(TAG, "Failed to find resources for " + packageName);
527 }
528 }
529 }
530 return null;
531 }
Sunny Goyalfafca522014-11-03 11:30:01 -0800532
533 @TargetApi(Build.VERSION_CODES.KITKAT)
534 public static boolean isViewAttachedToWindow(View v) {
535 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
536 return v.isAttachedToWindow();
537 } else {
538 // A proxy call which returns null, if the view is not attached to the window.
539 return v.getKeyDispatcherState() != null;
540 }
541 }
Sunny Goyal594d76d2014-11-06 10:12:54 -0800542
543 /**
544 * Returns a widget with category {@link AppWidgetProviderInfo#WIDGET_CATEGORY_SEARCHBOX}
545 * provided by the same package which is set to be global search activity.
546 * If widgetCategory is not supported, or no such widget is found, returns the first widget
547 * provided by the package.
548 */
549 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
550 public static AppWidgetProviderInfo getSearchWidgetProvider(Context context) {
551 SearchManager searchManager =
552 (SearchManager) context.getSystemService(Context.SEARCH_SERVICE);
553 ComponentName searchComponent = searchManager.getGlobalSearchActivity();
554 if (searchComponent == null) return null;
555 String providerPkg = searchComponent.getPackageName();
556
557 AppWidgetProviderInfo defaultWidgetForSearchPackage = null;
558
559 AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
560 for (AppWidgetProviderInfo info : appWidgetManager.getInstalledProviders()) {
561 if (info.provider.getPackageName().equals(providerPkg)) {
562 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
563 if ((info.widgetCategory & AppWidgetProviderInfo.WIDGET_CATEGORY_SEARCHBOX) != 0) {
564 return info;
565 } else if (defaultWidgetForSearchPackage == null) {
566 defaultWidgetForSearchPackage = info;
567 }
568 } else {
569 return info;
570 }
571 }
572 }
573 return defaultWidgetForSearchPackage;
574 }
Sunny Goyal08f72612015-01-05 13:41:43 -0800575
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700576 /**
577 * Compresses the bitmap to a byte array for serialization.
578 */
579 public static byte[] flattenBitmap(Bitmap bitmap) {
580 // Try go guesstimate how much space the icon will take when serialized
581 // to avoid unnecessary allocations/copies during the write.
582 int size = bitmap.getWidth() * bitmap.getHeight() * 4;
583 ByteArrayOutputStream out = new ByteArrayOutputStream(size);
584 try {
585 bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
586 out.flush();
587 out.close();
588 return out.toByteArray();
589 } catch (IOException e) {
590 Log.w(TAG, "Could not write bitmap");
591 return null;
592 }
593 }
594
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700595 /**
596 * Find the first vacant cell, if there is one.
597 *
598 * @param vacant Holds the x and y coordinate of the vacant cell
599 * @param spanX Horizontal cell span.
600 * @param spanY Vertical cell span.
601 *
602 * @return true if a vacant cell was found
603 */
604 public static boolean findVacantCell(int[] vacant, int spanX, int spanY,
605 int xCount, int yCount, boolean[][] occupied) {
606
607 for (int y = 0; (y + spanY) <= yCount; y++) {
608 for (int x = 0; (x + spanX) <= xCount; x++) {
609 boolean available = !occupied[x][y];
610 out: for (int i = x; i < x + spanX; i++) {
611 for (int j = y; j < y + spanY; j++) {
612 available = available && !occupied[i][j];
613 if (!available) break out;
614 }
615 }
616
617 if (available) {
618 vacant[0] = x;
619 vacant[1] = y;
620 return true;
621 }
622 }
623 }
624
625 return false;
626 }
Winson Chung82b016c2015-05-08 17:00:10 -0700627
628 /**
629 * Trims the string, removing all whitespace at the beginning and end of the string.
630 * Non-breaking whitespaces are also removed.
631 */
632 public static String trim(CharSequence s) {
Winson Chungafa77e92015-05-15 12:04:03 -0700633 if (s == null) {
634 return null;
635 }
636
Winson Chung82b016c2015-05-08 17:00:10 -0700637 // Just strip any sequence of whitespace or java space characters from the beginning and end
638 Matcher m = sTrimPattern.matcher(s);
639 return m.replaceAll("$1");
640 }
Sunny Goyal70660032015-05-14 00:07:08 -0700641
Winson Chung2c6e5cc2015-06-01 14:38:24 -0700642 /**
643 * Calculates the height of a given string at a specific text size.
644 */
645 public static float calculateTextHeight(float textSizePx) {
646 Paint p = new Paint();
647 p.setTextSize(textSizePx);
648 Paint.FontMetrics fm = p.getFontMetrics();
649 return -fm.top + fm.bottom;
650 }
651
Winson Chungb1777442015-06-16 13:35:04 -0700652 /**
653 * Convenience println with multiple args.
654 */
655 public static void println(String key, Object... args) {
656 StringBuilder b = new StringBuilder();
657 b.append(key);
658 b.append(": ");
659 boolean isFirstArgument = true;
660 for (Object arg : args) {
661 if (isFirstArgument) {
662 isFirstArgument = false;
663 } else {
664 b.append(", ");
665 }
666 b.append(arg);
667 }
668 System.out.println(b.toString());
669 }
670
Sunny Goyal70660032015-05-14 00:07:08 -0700671 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
672 public static boolean isRtl(Resources res) {
673 return (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) &&
674 (res.getConfiguration().getLayoutDirection() == View.LAYOUT_DIRECTION_RTL);
675 }
Hyunyoung Song2bd3d7d2015-05-21 13:04:53 -0700676
677 public static void assertWorkerThread() {
Sunny Goyal6c56c682015-07-16 14:09:05 -0700678 if (ProviderConfig.IS_DOGFOOD_BUILD &&
Sunny Goyal11d49112015-06-26 14:00:57 -0700679 (LauncherModel.sWorkerThread.getThreadId() != Process.myTid())) {
680 throw new IllegalStateException();
Hyunyoung Song2bd3d7d2015-05-21 13:04:53 -0700681 }
682 }
Sunny Goyal5c97f512015-05-19 16:03:28 -0700683
684 /**
685 * Returns true if the intent is a valid launch intent for a launcher activity of an app.
686 * This is used to identify shortcuts which are different from the ones exposed by the
687 * applications' manifest file.
688 *
689 * @param launchIntent The intent that will be launched when the shortcut is clicked.
690 */
691 public static boolean isLauncherAppTarget(Intent launchIntent) {
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700692 if (launchIntent != null
Sunny Goyal5c97f512015-05-19 16:03:28 -0700693 && Intent.ACTION_MAIN.equals(launchIntent.getAction())
694 && launchIntent.getComponent() != null
695 && launchIntent.getCategories() != null
696 && launchIntent.getCategories().size() == 1
697 && launchIntent.hasCategory(Intent.CATEGORY_LAUNCHER)
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700698 && TextUtils.isEmpty(launchIntent.getDataString())) {
699 // An app target can either have no extra or have ItemInfo.EXTRA_PROFILE.
700 Bundle extras = launchIntent.getExtras();
701 if (extras == null) {
702 return true;
703 } else {
704 Set<String> keys = extras.keySet();
705 return keys.size() == 1 && keys.contains(ItemInfo.EXTRA_PROFILE);
706 }
707 };
708 return false;
Sunny Goyal5c97f512015-05-19 16:03:28 -0700709 }
Adam Cohen2e6da152015-05-06 11:42:25 -0700710
711 public static float dpiFromPx(int size, DisplayMetrics metrics){
712 float densityRatio = (float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT;
713 return (size / densityRatio);
714 }
715 public static int pxFromDp(float size, DisplayMetrics metrics) {
716 return (int) Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
717 size, metrics));
718 }
719 public static int pxFromSp(float size, DisplayMetrics metrics) {
720 return (int) Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
721 size, metrics));
722 }
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700723
724 public static String createDbSelectionQuery(String columnName, Iterable<?> values) {
725 return String.format(Locale.ENGLISH, "%s IN (%s)", columnName, TextUtils.join(", ", values));
726 }
Sunny Goyal25aba0a2015-07-16 15:07:47 -0700727
728 @SuppressWarnings({"unchecked", "rawtypes"})
729 public static boolean isBootCompleted() {
730 try {
731 Class clazz = Class.forName("android.os.SystemProperties");
732 Method getter = clazz.getDeclaredMethod("get", String.class);
733 String value = (String) getter.invoke(null, "sys.boot_completed");
734 return "1".equals(value);
735 } catch (Exception e) {
736 Log.d(TAG, "Unable to read system properties");
737 // Assume that boot has completed
738 return true;
739 }
740 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800741}