blob: 096edc54622629a0928877fcaae40fc65ba89ee0 [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;
Winson Chungc763c4e2013-07-19 13:49:06 -070063import java.util.ArrayList;
Sunny Goyalb1622cc2015-06-10 16:00:42 -070064import java.util.Locale;
Sunny Goyal4e5cc642015-06-25 16:37:44 -070065import java.util.Set;
Winson Chung82b016c2015-05-08 17:00:10 -070066import java.util.regex.Matcher;
67import java.util.regex.Pattern;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080068
69/**
70 * Various utilities shared amongst the Launcher's classes.
71 */
Mathew Inwood72fbec12013-11-19 15:45:07 +000072public final class Utilities {
Rahul Chaturvedi7fc77ca2015-05-19 18:02:16 -070073
Joe Onorato1291a8c2009-09-15 15:07:25 -040074 private static final String TAG = "Launcher.Utilities";
75
The Android Open Source Project31dd5032009-03-03 19:32:27 -080076 private static final Rect sOldBounds = new Rect();
Romain Guy89911d22009-09-28 18:48:49 -070077 private static final Canvas sCanvas = new Canvas();
The Android Open Source Project31dd5032009-03-03 19:32:27 -080078
Winson Chung82b016c2015-05-08 17:00:10 -070079 private static final Pattern sTrimPattern =
80 Pattern.compile("^[\\s|\\p{javaSpaceChar}]*(.*)[\\s|\\p{javaSpaceChar}]*$");
81
The Android Open Source Project31dd5032009-03-03 19:32:27 -080082 static {
83 sCanvas.setDrawFilter(new PaintFlagsDrawFilter(Paint.DITHER_FLAG,
84 Paint.FILTER_BITMAP_FLAG));
85 }
Joe Onorato6665c0f2009-09-02 15:27:24 -070086 static int sColors[] = { 0xffff0000, 0xff00ff00, 0xff0000ff };
87 static int sColorIndex = 0;
88
Sunny Goyal53d7ee42015-05-22 12:25:45 -070089 private static final int[] sLoc0 = new int[2];
90 private static final int[] sLoc1 = new int[2];
Michael Jurka7ad868b2013-12-12 15:04:25 +010091
92 // To turn on these properties, type
93 // adb shell setprop log.tag.PROPERTY_NAME [VERBOSE | SUPPRESS]
Sunny Goyal53d7ee42015-05-22 12:25:45 -070094 private static final String FORCE_ENABLE_ROTATION_PROPERTY = "launcher_force_rotate";
95 private static boolean sForceEnableRotation = isPropertyEnabled(FORCE_ENABLE_ROTATION_PROPERTY);
Michael Jurka7ad868b2013-12-12 15:04:25 +010096
Rahul Chaturvedi7fc77ca2015-05-19 18:02:16 -070097 public static final String ALLOW_ROTATION_PREFERENCE_KEY = "pref_allowRotation";
98
Sunny Goyal4bbf4192014-11-11 12:23:59 -080099 public static boolean isPropertyEnabled(String propertyName) {
Michael Jurka7ad868b2013-12-12 15:04:25 +0100100 return Log.isLoggable(propertyName, Log.VERBOSE);
101 }
102
Rahul Chaturvedie863fed2015-06-15 14:09:42 -0400103 public static boolean isAllowRotationPrefEnabled(Context context, boolean multiProcess) {
Sunny Goyal7779d622015-06-11 16:18:39 -0700104 SharedPreferences sharedPrefs = context.getSharedPreferences(
Rahul Chaturvedie863fed2015-06-15 14:09:42 -0400105 LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE | (multiProcess ?
106 Context.MODE_MULTI_PROCESS : 0));
Rahul Chaturvedi7fc77ca2015-05-19 18:02:16 -0700107 boolean allowRotationPref = sharedPrefs.getBoolean(ALLOW_ROTATION_PREFERENCE_KEY, false);
108 return sForceEnableRotation || allowRotationPref;
109 }
110
111 public static boolean isRotationAllowedForDevice(Context context) {
112 return sForceEnableRotation || context.getResources().getBoolean(R.bool.allow_rotation);
Michael Jurka7ad868b2013-12-12 15:04:25 +0100113 }
114
Winson Chung0dbd7342013-10-13 22:46:20 -0700115 /**
Kenny Guyd794a3f2014-09-16 15:17:58 +0100116 * Indicates if the device is running LMP or higher.
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -0700117 */
Kenny Guyd794a3f2014-09-16 15:17:58 +0100118 public static boolean isLmpOrAbove() {
Brian Parfett1bc1ae62014-12-12 12:30:00 -0800119 return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -0700120 }
121
Adam Cohen15588932015-05-26 23:03:31 -0700122 public static boolean isLmpMR1OrAbove() {
123 // TODO(adamcohen): update to Build.VERSION_CODES.LOLLIPOP_MR1 once building against 22;
124 return Build.VERSION.SDK_INT >= 22;
125 }
126
Adam Cohen947e02b2015-05-22 19:23:34 -0700127 public static boolean isLmpMR1() {
128 // TODO(adamcohen): update to Build.VERSION_CODES.LOLLIPOP_MR1 once building against 22;
129 return Build.VERSION.SDK_INT == 22;
130 }
131
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700132 public static Bitmap createIconBitmap(Cursor c, int iconIndex, Context context) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -0800133 byte[] data = c.getBlob(iconIndex);
134 try {
135 return createIconBitmap(BitmapFactory.decodeByteArray(data, 0, data.length), context);
136 } catch (Exception e) {
137 return null;
138 }
139 }
140
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -0700141 /**
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700142 * Returns a bitmap suitable for the all apps view. If the package or the resource do not
143 * exist, it returns null.
144 */
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700145 public static Bitmap createIconBitmap(String packageName, String resourceName,
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700146 Context context) {
147 PackageManager packageManager = context.getPackageManager();
148 // the resource
149 try {
150 Resources resources = packageManager.getResourcesForApplication(packageName);
151 if (resources != null) {
152 final int id = resources.getIdentifier(resourceName, null, null);
153 return createIconBitmap(
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700154 resources.getDrawableForDensity(id, LauncherAppState.getInstance()
155 .getInvariantDeviceProfile().fillResIconDpi), context);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700156 }
157 } catch (Exception e) {
158 // Icon not found.
159 }
160 return null;
161 }
162
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700163 private static int getIconBitmapSize() {
164 return LauncherAppState.getInstance().getInvariantDeviceProfile().iconBitmapSize;
165 }
166
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700167 /**
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700168 * Returns a bitmap which is of the appropriate size to be displayed as an icon
Michael Jurka931dc972011-08-05 15:08:15 -0700169 */
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700170 public static Bitmap createIconBitmap(Bitmap icon, Context context) {
171 final int iconBitmapSize = getIconBitmapSize();
172 if (iconBitmapSize == icon.getWidth() && iconBitmapSize == icon.getHeight()) {
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700173 return icon;
174 }
175 return createIconBitmap(new BitmapDrawable(context.getResources(), icon), context);
Michael Jurka931dc972011-08-05 15:08:15 -0700176 }
177
178 /**
179 * Returns a bitmap suitable for the all apps view.
Joe Onorato6665c0f2009-09-02 15:27:24 -0700180 */
Mathew Inwood72fbec12013-11-19 15:45:07 +0000181 public static Bitmap createIconBitmap(Drawable icon, Context context) {
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700182 synchronized (sCanvas) {
183 final int iconBitmapSize = getIconBitmapSize();
Joe Onorato6665c0f2009-09-02 15:27:24 -0700184
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700185 int width = iconBitmapSize;
186 int height = iconBitmapSize;
Joe Onorato6665c0f2009-09-02 15:27:24 -0700187
Joe Onorato6665c0f2009-09-02 15:27:24 -0700188 if (icon instanceof PaintDrawable) {
189 PaintDrawable painter = (PaintDrawable) icon;
190 painter.setIntrinsicWidth(width);
191 painter.setIntrinsicHeight(height);
192 } else if (icon instanceof BitmapDrawable) {
193 // Ensure the bitmap has a density.
194 BitmapDrawable bitmapDrawable = (BitmapDrawable) icon;
195 Bitmap bitmap = bitmapDrawable.getBitmap();
196 if (bitmap.getDensity() == Bitmap.DENSITY_NONE) {
197 bitmapDrawable.setTargetDensity(context.getResources().getDisplayMetrics());
198 }
199 }
200 int sourceWidth = icon.getIntrinsicWidth();
201 int sourceHeight = icon.getIntrinsicHeight();
Michael Jurka931dc972011-08-05 15:08:15 -0700202 if (sourceWidth > 0 && sourceHeight > 0) {
Winson Chung5f8afe62013-08-12 16:19:28 -0700203 // Scale the icon proportionally to the icon dimensions
204 final float ratio = (float) sourceWidth / sourceHeight;
205 if (sourceWidth > sourceHeight) {
206 height = (int) (width / ratio);
207 } else if (sourceHeight > sourceWidth) {
208 width = (int) (height * ratio);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700209 }
210 }
211
212 // no intrinsic size --> use default size
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700213 int textureWidth = iconBitmapSize;
214 int textureHeight = iconBitmapSize;
Joe Onorato6665c0f2009-09-02 15:27:24 -0700215
216 final Bitmap bitmap = Bitmap.createBitmap(textureWidth, textureHeight,
217 Bitmap.Config.ARGB_8888);
218 final Canvas canvas = sCanvas;
219 canvas.setBitmap(bitmap);
220
221 final int left = (textureWidth-width) / 2;
222 final int top = (textureHeight-height) / 2;
223
Michael Jurka3a9fced2012-04-13 14:44:29 -0700224 @SuppressWarnings("all") // suppress dead code warning
225 final boolean debug = false;
226 if (debug) {
Joe Onorato6665c0f2009-09-02 15:27:24 -0700227 // draw a big box for the icon for debugging
228 canvas.drawColor(sColors[sColorIndex]);
229 if (++sColorIndex >= sColors.length) sColorIndex = 0;
230 Paint debugPaint = new Paint();
231 debugPaint.setColor(0xffcccc00);
232 canvas.drawRect(left, top, left+width, top+height, debugPaint);
233 }
234
235 sOldBounds.set(icon.getBounds());
236 icon.setBounds(left, top, left+width, top+height);
237 icon.draw(canvas);
238 icon.setBounds(sOldBounds);
Adam Cohenaaf473c2011-08-03 12:02:47 -0700239 canvas.setBitmap(null);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700240
241 return bitmap;
242 }
243 }
244
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800245 /**
Winson Chungc763c4e2013-07-19 13:49:06 -0700246 * Given a coordinate relative to the descendant, find the coordinate in a parent view's
247 * coordinates.
248 *
249 * @param descendant The descendant to which the passed coordinate is relative.
250 * @param root The root view to make the coordinates relative to.
251 * @param coord The coordinate that we want mapped.
252 * @param includeRootScroll Whether or not to account for the scroll of the descendant:
253 * sometimes this is relevant as in a child's coordinates within the descendant.
254 * @return The factor by which this descendant is scaled relative to this DragLayer. Caution
255 * this scale factor is assumed to be equal in X and Y, and so if at any point this
256 * assumption fails, we will need to return a pair of scale factors.
257 */
258 public static float getDescendantCoordRelativeToParent(View descendant, View root,
259 int[] coord, boolean includeRootScroll) {
260 ArrayList<View> ancestorChain = new ArrayList<View>();
261
262 float[] pt = {coord[0], coord[1]};
263
264 View v = descendant;
265 while(v != root && v != null) {
266 ancestorChain.add(v);
267 v = (View) v.getParent();
268 }
269 ancestorChain.add(root);
270
271 float scale = 1.0f;
272 int count = ancestorChain.size();
273 for (int i = 0; i < count; i++) {
274 View v0 = ancestorChain.get(i);
Winson Chungc763c4e2013-07-19 13:49:06 -0700275 // For TextViews, scroll has a meaning which relates to the text position
276 // which is very strange... ignore the scroll.
277 if (v0 != descendant || includeRootScroll) {
278 pt[0] -= v0.getScrollX();
279 pt[1] -= v0.getScrollY();
280 }
281
282 v0.getMatrix().mapPoints(pt);
283 pt[0] += v0.getLeft();
284 pt[1] += v0.getTop();
285 scale *= v0.getScaleX();
286 }
287
288 coord[0] = (int) Math.round(pt[0]);
289 coord[1] = (int) Math.round(pt[1]);
290 return scale;
291 }
292
293 /**
294 * Inverse of {@link #getDescendantCoordRelativeToSelf(View, int[])}.
295 */
296 public static float mapCoordInSelfToDescendent(View descendant, View root,
297 int[] coord) {
298 ArrayList<View> ancestorChain = new ArrayList<View>();
299
300 float[] pt = {coord[0], coord[1]};
301
302 View v = descendant;
303 while(v != root) {
304 ancestorChain.add(v);
305 v = (View) v.getParent();
306 }
307 ancestorChain.add(root);
308
309 float scale = 1.0f;
310 Matrix inverse = new Matrix();
311 int count = ancestorChain.size();
312 for (int i = count - 1; i >= 0; i--) {
313 View ancestor = ancestorChain.get(i);
314 View next = i > 0 ? ancestorChain.get(i-1) : null;
315
316 pt[0] += ancestor.getScrollX();
317 pt[1] += ancestor.getScrollY();
318
319 if (next != null) {
320 pt[0] -= next.getLeft();
321 pt[1] -= next.getTop();
322 next.getMatrix().invert(inverse);
323 inverse.mapPoints(pt);
324 scale *= next.getScaleX();
325 }
326 }
327
328 coord[0] = (int) Math.round(pt[0]);
329 coord[1] = (int) Math.round(pt[1]);
330 return scale;
331 }
332
Jason Monk02dd7ae2014-04-15 15:23:31 -0400333 /**
334 * Utility method to determine whether the given point, in local coordinates,
335 * is inside the view, where the area of the view is expanded by the slop factor.
336 * This method is called while processing touch-move events to determine if the event
337 * is still within the view.
338 */
339 public static boolean pointInView(View v, float localX, float localY, float slop) {
340 return localX >= -slop && localY >= -slop && localX < (v.getWidth() + slop) &&
341 localY < (v.getHeight() + slop);
342 }
343
Winson Chung3a6e7f32013-10-09 15:50:52 -0700344 public static void scaleRect(Rect r, float scale) {
345 if (scale != 1.0f) {
346 r.left = (int) (r.left * scale + 0.5f);
347 r.top = (int) (r.top * scale + 0.5f);
348 r.right = (int) (r.right * scale + 0.5f);
349 r.bottom = (int) (r.bottom * scale + 0.5f);
350 }
351 }
352
Adam Cohen63f1ec02014-08-12 09:23:13 -0700353 public static int[] getCenterDeltaInScreenSpace(View v0, View v1, int[] delta) {
354 v0.getLocationInWindow(sLoc0);
355 v1.getLocationInWindow(sLoc1);
356
357 sLoc0[0] += (v0.getMeasuredWidth() * v0.getScaleX()) / 2;
358 sLoc0[1] += (v0.getMeasuredHeight() * v0.getScaleY()) / 2;
359 sLoc1[0] += (v1.getMeasuredWidth() * v1.getScaleX()) / 2;
360 sLoc1[1] += (v1.getMeasuredHeight() * v1.getScaleY()) / 2;
361
362 if (delta == null) {
363 delta = new int[2];
364 }
365
366 delta[0] = sLoc1[0] - sLoc0[0];
367 delta[1] = sLoc1[1] - sLoc0[1];
368
369 return delta;
370 }
371
Winson Chung3a6e7f32013-10-09 15:50:52 -0700372 public static void scaleRectAboutCenter(Rect r, float scale) {
373 int cx = r.centerX();
374 int cy = r.centerY();
375 r.offset(-cx, -cy);
376 Utilities.scaleRect(r, scale);
377 r.offset(cx, cy);
378 }
379
Michael Jurkaa805e1a2013-08-22 15:00:33 +0200380 public static void startActivityForResultSafely(
381 Activity activity, Intent intent, int requestCode) {
382 try {
383 activity.startActivityForResult(intent, requestCode);
384 } catch (ActivityNotFoundException e) {
385 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
386 } catch (SecurityException e) {
387 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
388 Log.e(TAG, "Launcher does not have the permission to launch " + intent +
389 ". Make sure to create a MAIN intent-filter for the corresponding activity " +
390 "or use the exported attribute for this activity.", e);
391 }
392 }
Sunny Goyalc5c60ad2014-07-14 12:02:01 -0700393
394 static boolean isSystemApp(Context context, Intent intent) {
395 PackageManager pm = context.getPackageManager();
396 ComponentName cn = intent.getComponent();
397 String packageName = null;
398 if (cn == null) {
399 ResolveInfo info = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
400 if ((info != null) && (info.activityInfo != null)) {
401 packageName = info.activityInfo.packageName;
402 }
403 } else {
404 packageName = cn.getPackageName();
405 }
406 if (packageName != null) {
407 try {
408 PackageInfo info = pm.getPackageInfo(packageName, 0);
409 return (info != null) && (info.applicationInfo != null) &&
410 ((info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
411 } catch (NameNotFoundException e) {
412 return false;
413 }
414 } else {
415 return false;
416 }
417 }
Sunny Goyal95abbb32014-08-04 10:53:22 -0700418
419 /**
420 * This picks a dominant color, looking for high-saturation, high-value, repeated hues.
421 * @param bitmap The bitmap to scan
422 * @param samples The approximate max number of samples to use.
423 */
424 static int findDominantColorByHue(Bitmap bitmap, int samples) {
425 final int height = bitmap.getHeight();
426 final int width = bitmap.getWidth();
427 int sampleStride = (int) Math.sqrt((height * width) / samples);
428 if (sampleStride < 1) {
429 sampleStride = 1;
430 }
431
432 // This is an out-param, for getting the hsv values for an rgb
433 float[] hsv = new float[3];
434
435 // First get the best hue, by creating a histogram over 360 hue buckets,
436 // where each pixel contributes a score weighted by saturation, value, and alpha.
437 float[] hueScoreHistogram = new float[360];
438 float highScore = -1;
439 int bestHue = -1;
440
441 for (int y = 0; y < height; y += sampleStride) {
442 for (int x = 0; x < width; x += sampleStride) {
443 int argb = bitmap.getPixel(x, y);
444 int alpha = 0xFF & (argb >> 24);
445 if (alpha < 0x80) {
446 // Drop mostly-transparent pixels.
447 continue;
448 }
449 // Remove the alpha channel.
450 int rgb = argb | 0xFF000000;
451 Color.colorToHSV(rgb, hsv);
452 // Bucket colors by the 360 integer hues.
453 int hue = (int) hsv[0];
454 if (hue < 0 || hue >= hueScoreHistogram.length) {
455 // Defensively avoid array bounds violations.
456 continue;
457 }
458 float score = hsv[1] * hsv[2];
459 hueScoreHistogram[hue] += score;
460 if (hueScoreHistogram[hue] > highScore) {
461 highScore = hueScoreHistogram[hue];
462 bestHue = hue;
463 }
464 }
465 }
466
467 SparseArray<Float> rgbScores = new SparseArray<Float>();
468 int bestColor = 0xff000000;
469 highScore = -1;
470 // Go back over the RGB colors that match the winning hue,
471 // creating a histogram of weighted s*v scores, for up to 100*100 [s,v] buckets.
472 // The highest-scoring RGB color wins.
473 for (int y = 0; y < height; y += sampleStride) {
474 for (int x = 0; x < width; x += sampleStride) {
475 int rgb = bitmap.getPixel(x, y) | 0xff000000;
476 Color.colorToHSV(rgb, hsv);
477 int hue = (int) hsv[0];
478 if (hue == bestHue) {
479 float s = hsv[1];
480 float v = hsv[2];
481 int bucket = (int) (s * 100) + (int) (v * 10000);
482 // Score by cumulative saturation * value.
483 float score = s * v;
484 Float oldTotal = rgbScores.get(bucket);
485 float newTotal = oldTotal == null ? score : oldTotal + score;
486 rgbScores.put(bucket, newTotal);
487 if (newTotal > highScore) {
488 highScore = newTotal;
489 // All the colors in the winning bucket are very similar. Last in wins.
490 bestColor = rgb;
491 }
492 }
493 }
494 }
495 return bestColor;
496 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700497
498 /*
499 * Finds a system apk which had a broadcast receiver listening to a particular action.
500 * @param action intent action used to find the apk
501 * @return a pair of apk package name and the resources.
502 */
503 static Pair<String, Resources> findSystemApk(String action, PackageManager pm) {
504 final Intent intent = new Intent(action);
505 for (ResolveInfo info : pm.queryBroadcastReceivers(intent, 0)) {
506 if (info.activityInfo != null &&
507 (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
508 final String packageName = info.activityInfo.packageName;
509 try {
510 final Resources res = pm.getResourcesForApplication(packageName);
511 return Pair.create(packageName, res);
512 } catch (NameNotFoundException e) {
513 Log.w(TAG, "Failed to find resources for " + packageName);
514 }
515 }
516 }
517 return null;
518 }
Sunny Goyalfafca522014-11-03 11:30:01 -0800519
520 @TargetApi(Build.VERSION_CODES.KITKAT)
521 public static boolean isViewAttachedToWindow(View v) {
522 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
523 return v.isAttachedToWindow();
524 } else {
525 // A proxy call which returns null, if the view is not attached to the window.
526 return v.getKeyDispatcherState() != null;
527 }
528 }
Sunny Goyal594d76d2014-11-06 10:12:54 -0800529
530 /**
531 * Returns a widget with category {@link AppWidgetProviderInfo#WIDGET_CATEGORY_SEARCHBOX}
532 * provided by the same package which is set to be global search activity.
533 * If widgetCategory is not supported, or no such widget is found, returns the first widget
534 * provided by the package.
535 */
536 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
537 public static AppWidgetProviderInfo getSearchWidgetProvider(Context context) {
538 SearchManager searchManager =
539 (SearchManager) context.getSystemService(Context.SEARCH_SERVICE);
540 ComponentName searchComponent = searchManager.getGlobalSearchActivity();
541 if (searchComponent == null) return null;
542 String providerPkg = searchComponent.getPackageName();
543
544 AppWidgetProviderInfo defaultWidgetForSearchPackage = null;
545
546 AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
547 for (AppWidgetProviderInfo info : appWidgetManager.getInstalledProviders()) {
548 if (info.provider.getPackageName().equals(providerPkg)) {
549 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
550 if ((info.widgetCategory & AppWidgetProviderInfo.WIDGET_CATEGORY_SEARCHBOX) != 0) {
551 return info;
552 } else if (defaultWidgetForSearchPackage == null) {
553 defaultWidgetForSearchPackage = info;
554 }
555 } else {
556 return info;
557 }
558 }
559 }
560 return defaultWidgetForSearchPackage;
561 }
Sunny Goyal08f72612015-01-05 13:41:43 -0800562
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700563 /**
564 * Compresses the bitmap to a byte array for serialization.
565 */
566 public static byte[] flattenBitmap(Bitmap bitmap) {
567 // Try go guesstimate how much space the icon will take when serialized
568 // to avoid unnecessary allocations/copies during the write.
569 int size = bitmap.getWidth() * bitmap.getHeight() * 4;
570 ByteArrayOutputStream out = new ByteArrayOutputStream(size);
571 try {
572 bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
573 out.flush();
574 out.close();
575 return out.toByteArray();
576 } catch (IOException e) {
577 Log.w(TAG, "Could not write bitmap");
578 return null;
579 }
580 }
581
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700582 /**
583 * Find the first vacant cell, if there is one.
584 *
585 * @param vacant Holds the x and y coordinate of the vacant cell
586 * @param spanX Horizontal cell span.
587 * @param spanY Vertical cell span.
588 *
589 * @return true if a vacant cell was found
590 */
591 public static boolean findVacantCell(int[] vacant, int spanX, int spanY,
592 int xCount, int yCount, boolean[][] occupied) {
593
594 for (int y = 0; (y + spanY) <= yCount; y++) {
595 for (int x = 0; (x + spanX) <= xCount; x++) {
596 boolean available = !occupied[x][y];
597 out: for (int i = x; i < x + spanX; i++) {
598 for (int j = y; j < y + spanY; j++) {
599 available = available && !occupied[i][j];
600 if (!available) break out;
601 }
602 }
603
604 if (available) {
605 vacant[0] = x;
606 vacant[1] = y;
607 return true;
608 }
609 }
610 }
611
612 return false;
613 }
Winson Chung82b016c2015-05-08 17:00:10 -0700614
615 /**
616 * Trims the string, removing all whitespace at the beginning and end of the string.
617 * Non-breaking whitespaces are also removed.
618 */
619 public static String trim(CharSequence s) {
Winson Chungafa77e92015-05-15 12:04:03 -0700620 if (s == null) {
621 return null;
622 }
623
Winson Chung82b016c2015-05-08 17:00:10 -0700624 // Just strip any sequence of whitespace or java space characters from the beginning and end
625 Matcher m = sTrimPattern.matcher(s);
626 return m.replaceAll("$1");
627 }
Sunny Goyal70660032015-05-14 00:07:08 -0700628
Winson Chung2c6e5cc2015-06-01 14:38:24 -0700629 /**
630 * Calculates the height of a given string at a specific text size.
631 */
632 public static float calculateTextHeight(float textSizePx) {
633 Paint p = new Paint();
634 p.setTextSize(textSizePx);
635 Paint.FontMetrics fm = p.getFontMetrics();
636 return -fm.top + fm.bottom;
637 }
638
Winson Chungb1777442015-06-16 13:35:04 -0700639 /**
640 * Convenience println with multiple args.
641 */
642 public static void println(String key, Object... args) {
643 StringBuilder b = new StringBuilder();
644 b.append(key);
645 b.append(": ");
646 boolean isFirstArgument = true;
647 for (Object arg : args) {
648 if (isFirstArgument) {
649 isFirstArgument = false;
650 } else {
651 b.append(", ");
652 }
653 b.append(arg);
654 }
655 System.out.println(b.toString());
656 }
657
Sunny Goyal70660032015-05-14 00:07:08 -0700658 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
659 public static boolean isRtl(Resources res) {
660 return (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) &&
661 (res.getConfiguration().getLayoutDirection() == View.LAYOUT_DIRECTION_RTL);
662 }
Hyunyoung Song2bd3d7d2015-05-21 13:04:53 -0700663
664 public static void assertWorkerThread() {
Sunny Goyal6c56c682015-07-16 14:09:05 -0700665 if (ProviderConfig.IS_DOGFOOD_BUILD &&
Sunny Goyal11d49112015-06-26 14:00:57 -0700666 (LauncherModel.sWorkerThread.getThreadId() != Process.myTid())) {
667 throw new IllegalStateException();
Hyunyoung Song2bd3d7d2015-05-21 13:04:53 -0700668 }
669 }
Sunny Goyal5c97f512015-05-19 16:03:28 -0700670
671 /**
672 * Returns true if the intent is a valid launch intent for a launcher activity of an app.
673 * This is used to identify shortcuts which are different from the ones exposed by the
674 * applications' manifest file.
675 *
676 * @param launchIntent The intent that will be launched when the shortcut is clicked.
677 */
678 public static boolean isLauncherAppTarget(Intent launchIntent) {
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700679 if (launchIntent != null
Sunny Goyal5c97f512015-05-19 16:03:28 -0700680 && Intent.ACTION_MAIN.equals(launchIntent.getAction())
681 && launchIntent.getComponent() != null
682 && launchIntent.getCategories() != null
683 && launchIntent.getCategories().size() == 1
684 && launchIntent.hasCategory(Intent.CATEGORY_LAUNCHER)
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700685 && TextUtils.isEmpty(launchIntent.getDataString())) {
686 // An app target can either have no extra or have ItemInfo.EXTRA_PROFILE.
687 Bundle extras = launchIntent.getExtras();
688 if (extras == null) {
689 return true;
690 } else {
691 Set<String> keys = extras.keySet();
692 return keys.size() == 1 && keys.contains(ItemInfo.EXTRA_PROFILE);
693 }
694 };
695 return false;
Sunny Goyal5c97f512015-05-19 16:03:28 -0700696 }
Adam Cohen2e6da152015-05-06 11:42:25 -0700697
698 public static float dpiFromPx(int size, DisplayMetrics metrics){
699 float densityRatio = (float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT;
700 return (size / densityRatio);
701 }
702 public static int pxFromDp(float size, DisplayMetrics metrics) {
703 return (int) Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
704 size, metrics));
705 }
706 public static int pxFromSp(float size, DisplayMetrics metrics) {
707 return (int) Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
708 size, metrics));
709 }
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700710
711 public static String createDbSelectionQuery(String columnName, Iterable<?> values) {
712 return String.format(Locale.ENGLISH, "%s IN (%s)", columnName, TextUtils.join(", ", values));
713 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800714}