blob: 2cbad53dce2857555e073c125ca4bd31475eda1b [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 Goyal1ed6c4a2016-04-21 15:16:11 -070021import android.app.WallpaperManager;
Michael Jurkaa805e1a2013-08-22 15:00:33 +020022import android.content.ActivityNotFoundException;
Sunny Goyalc5c60ad2014-07-14 12:02:01 -070023import android.content.ComponentName;
Winson Chungaafa03c2010-06-11 17:34:16 -070024import android.content.Context;
Michael Jurkaa805e1a2013-08-22 15:00:33 +020025import android.content.Intent;
Rahul Chaturvedi7fc77ca2015-05-19 18:02:16 -070026import android.content.SharedPreferences;
Sunny Goyalc5c60ad2014-07-14 12:02:01 -070027import android.content.pm.ApplicationInfo;
28import android.content.pm.PackageInfo;
29import android.content.pm.PackageManager;
30import android.content.pm.PackageManager.NameNotFoundException;
31import android.content.pm.ResolveInfo;
Winson Chungaafa03c2010-06-11 17:34:16 -070032import android.content.res.Resources;
Andrew Sappersteinabef55a2016-06-19 12:49:00 -070033import android.content.res.TypedArray;
Sunny Goyal4fbc3822015-02-18 16:46:50 -080034import android.database.Cursor;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080035import android.graphics.Bitmap;
Sunny Goyal4fbc3822015-02-18 16:46:50 -080036import android.graphics.BitmapFactory;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080037import android.graphics.Canvas;
Sunny Goyal95abbb32014-08-04 10:53:22 -070038import android.graphics.Color;
Winson Chungc763c4e2013-07-19 13:49:06 -070039import android.graphics.Matrix;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080040import android.graphics.Paint;
Joe Onoratobf15cb42009-08-07 14:33:40 -070041import android.graphics.PaintFlagsDrawFilter;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080042import android.graphics.Rect;
Sunny Goyal4a464792016-07-19 14:19:53 -070043import android.graphics.RectF;
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 Goyal9994b2b2016-06-23 14:17:24 -070048import android.os.Build.VERSION;
Sunny Goyal4e5cc642015-06-25 16:37:44 -070049import android.os.Bundle;
Tony Wickham112ac952015-11-12 12:31:50 -080050import android.os.PowerManager;
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;
Tony Wickham1bce7fd2016-04-28 17:39:03 -070060import android.view.MotionEvent;
Winson Chungc763c4e2013-07-19 13:49:06 -070061import android.view.View;
Tony Wickham1bce7fd2016-04-28 17:39:03 -070062import android.view.ViewParent;
Michael Jurkaa805e1a2013-08-22 15:00:33 +020063import android.widget.Toast;
Sunny Goyalb1622cc2015-06-10 16:00:42 -070064
Sunny Goyalb84046d2015-10-19 14:03:30 -070065import com.android.launcher3.compat.UserHandleCompat;
Sunny Goyald896ee42015-12-17 11:24:31 -080066import com.android.launcher3.config.FeatureFlags;
Sunny Goyal713edfc2016-05-06 09:58:34 -070067import com.android.launcher3.config.ProviderConfig;
Sunny Goyal4a464792016-07-19 14:19:53 -070068import com.android.launcher3.graphics.ShadowGenerator;
Sunny Goyalfc218302015-09-17 14:59:10 -070069import com.android.launcher3.util.IconNormalizer;
Sunny Goyal6c56c682015-07-16 14:09:05 -070070
Sunny Goyal5b0e6692015-03-19 14:31:19 -070071import java.io.ByteArrayOutputStream;
Sunny Goyal713edfc2016-05-06 09:58:34 -070072import java.io.Closeable;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070073import java.io.IOException;
Tony Wickham1bce7fd2016-04-28 17:39:03 -070074import java.lang.reflect.InvocationTargetException;
Sunny Goyal25aba0a2015-07-16 15:07:47 -070075import java.lang.reflect.Method;
Winson Chungc763c4e2013-07-19 13:49:06 -070076import java.util.ArrayList;
Tony Wickham1bce7fd2016-04-28 17:39:03 -070077import java.util.Collection;
Sunny Goyalb1622cc2015-06-10 16:00:42 -070078import java.util.Locale;
Sunny Goyal4e5cc642015-06-25 16:37:44 -070079import java.util.Set;
Sunny Goyal8ac727b2015-09-23 15:38:09 -070080import java.util.concurrent.Executor;
81import java.util.concurrent.LinkedBlockingQueue;
82import java.util.concurrent.ThreadPoolExecutor;
83import java.util.concurrent.TimeUnit;
Winson Chung82b016c2015-05-08 17:00:10 -070084import java.util.regex.Matcher;
85import java.util.regex.Pattern;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080086
87/**
88 * Various utilities shared amongst the Launcher's classes.
89 */
Mathew Inwood72fbec12013-11-19 15:45:07 +000090public final class Utilities {
Rahul Chaturvedi7fc77ca2015-05-19 18:02:16 -070091
Joe Onorato1291a8c2009-09-15 15:07:25 -040092 private static final String TAG = "Launcher.Utilities";
93
The Android Open Source Project31dd5032009-03-03 19:32:27 -080094 private static final Rect sOldBounds = new Rect();
Romain Guy89911d22009-09-28 18:48:49 -070095 private static final Canvas sCanvas = new Canvas();
The Android Open Source Project31dd5032009-03-03 19:32:27 -080096
Winson Chung82b016c2015-05-08 17:00:10 -070097 private static final Pattern sTrimPattern =
98 Pattern.compile("^[\\s|\\p{javaSpaceChar}]*(.*)[\\s|\\p{javaSpaceChar}]*$");
99
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800100 static {
101 sCanvas.setDrawFilter(new PaintFlagsDrawFilter(Paint.DITHER_FLAG,
102 Paint.FILTER_BITMAP_FLAG));
103 }
Joe Onorato6665c0f2009-09-02 15:27:24 -0700104 static int sColors[] = { 0xffff0000, 0xff00ff00, 0xff0000ff };
105 static int sColorIndex = 0;
106
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700107 private static final int[] sLoc0 = new int[2];
108 private static final int[] sLoc1 = new int[2];
Michael Jurka7ad868b2013-12-12 15:04:25 +0100109
Sunny Goyal9994b2b2016-06-23 14:17:24 -0700110 public static boolean isNycMR1OrAbove() {
111 // TODO: Use the check from support lib
112 return !"REL".equals(VERSION.CODENAME)
113 && "NMR1".compareTo(VERSION.CODENAME) <= 0;
114 }
115
Winsonbe9798b2016-07-20 12:55:49 -0700116 public static final boolean ATLEAST_MARSHMALLOW =
117 Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700118
119 public static final boolean ATLEAST_LOLLIPOP_MR1 =
120 Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1;
121
122 public static final boolean ATLEAST_LOLLIPOP =
123 Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
124
125 public static final boolean ATLEAST_KITKAT =
126 Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
127
128 public static final boolean ATLEAST_JB_MR1 =
129 Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1;
130
131 public static final boolean ATLEAST_JB_MR2 =
132 Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2;
133
Sunny Goyal6f866092016-03-17 17:04:15 -0700134 // An intent extra to indicate the horizontal scroll of the wallpaper.
135 public static final String EXTRA_WALLPAPER_OFFSET = "com.android.launcher3.WALLPAPER_OFFSET";
136
Sunny Goyal8ac727b2015-09-23 15:38:09 -0700137 // These values are same as that in {@link AsyncTask}.
138 private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
139 private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
140 private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
141 private static final int KEEP_ALIVE = 1;
142 /**
143 * An {@link Executor} to be used with async task with no limit on the queue size.
144 */
145 public static final Executor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(
146 CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
147 TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
148
Rahul Chaturvedi7fc77ca2015-05-19 18:02:16 -0700149 public static final String ALLOW_ROTATION_PREFERENCE_KEY = "pref_allowRotation";
150
Sunny Goyal4bbf4192014-11-11 12:23:59 -0800151 public static boolean isPropertyEnabled(String propertyName) {
Michael Jurka7ad868b2013-12-12 15:04:25 +0100152 return Log.isLoggable(propertyName, Log.VERBOSE);
153 }
154
Sunny Goyal21bf5312015-08-21 11:08:24 -0700155 public static boolean isAllowRotationPrefEnabled(Context context) {
Sunny Goyalf48e5922016-05-12 15:36:20 -0700156 return getPrefs(context).getBoolean(ALLOW_ROTATION_PREFERENCE_KEY,
157 getAllowRotationDefaultValue(context));
158 }
159
160 public static boolean getAllowRotationDefaultValue(Context context) {
Sunny Goyal8f3819b2016-02-23 14:49:22 -0800161 if (isNycOrAbove()) {
162 // If the device was scaled, used the original dimensions to determine if rotation
163 // is allowed of not.
164 try {
165 // TODO: Use the actual field when the API is finalized.
166 int originalDensity =
167 DisplayMetrics.class.getField("DENSITY_DEVICE_STABLE").getInt(null);
168 Resources res = context.getResources();
169 int originalSmallestWidth = res.getConfiguration().smallestScreenWidthDp
170 * res.getDisplayMetrics().densityDpi / originalDensity;
Sunny Goyalf48e5922016-05-12 15:36:20 -0700171 return originalSmallestWidth >= 600;
Sunny Goyal8f3819b2016-02-23 14:49:22 -0800172 } catch (Exception e) {
173 // Ignore
174 }
175 }
Sunny Goyalf48e5922016-05-12 15:36:20 -0700176 return false;
Michael Jurka7ad868b2013-12-12 15:04:25 +0100177 }
178
Vadim Tryshev9de91272015-08-03 18:37:17 -0700179 public static boolean isNycOrAbove() {
180 // TODO(vadimt): Replace using reflection with looking at the API version once
181 // Build.VERSION.SDK_INT gets bumped to 24. b/22942492.
182 try {
183 View.class.getDeclaredField("DRAG_FLAG_OPAQUE");
184 // View.DRAG_FLAG_OPAQUE doesn't exist in M-release, so it's an indication of N+.
185 return true;
186 } catch (NoSuchFieldException e) {
187 return false;
188 }
189 }
190
Sunny Goyal745bad92016-05-02 10:54:12 -0700191 // TODO: Use Intent.ACTION_APPLICATION_PREFERENCES when N SDK is available.
192 public static final String ACTION_APPLICATION_PREFERENCES
193 = "android.intent.action.APPLICATION_PREFERENCES";
194
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700195 public static Bitmap createIconBitmap(Cursor c, int iconIndex, Context context) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -0800196 byte[] data = c.getBlob(iconIndex);
197 try {
198 return createIconBitmap(BitmapFactory.decodeByteArray(data, 0, data.length), context);
199 } catch (Exception e) {
200 return null;
201 }
202 }
203
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -0700204 /**
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700205 * Returns a bitmap suitable for the all apps view. If the package or the resource do not
206 * exist, it returns null.
207 */
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700208 public static Bitmap createIconBitmap(String packageName, String resourceName,
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700209 Context context) {
210 PackageManager packageManager = context.getPackageManager();
211 // the resource
212 try {
213 Resources resources = packageManager.getResourcesForApplication(packageName);
214 if (resources != null) {
215 final int id = resources.getIdentifier(resourceName, null, null);
216 return createIconBitmap(
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700217 resources.getDrawableForDensity(id, LauncherAppState.getInstance()
218 .getInvariantDeviceProfile().fillResIconDpi), context);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700219 }
220 } catch (Exception e) {
221 // Icon not found.
222 }
223 return null;
224 }
225
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700226 private static int getIconBitmapSize() {
227 return LauncherAppState.getInstance().getInvariantDeviceProfile().iconBitmapSize;
228 }
229
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700230 /**
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700231 * Returns a bitmap which is of the appropriate size to be displayed as an icon
Michael Jurka931dc972011-08-05 15:08:15 -0700232 */
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700233 public static Bitmap createIconBitmap(Bitmap icon, Context context) {
234 final int iconBitmapSize = getIconBitmapSize();
235 if (iconBitmapSize == icon.getWidth() && iconBitmapSize == icon.getHeight()) {
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700236 return icon;
237 }
238 return createIconBitmap(new BitmapDrawable(context.getResources(), icon), context);
Michael Jurka931dc972011-08-05 15:08:15 -0700239 }
240
241 /**
Sunny Goyalfc218302015-09-17 14:59:10 -0700242 * Returns a bitmap suitable for the all apps view. The icon is badged for {@param user}.
243 * The bitmap is also visually normalized with other icons.
Sunny Goyalb84046d2015-10-19 14:03:30 -0700244 */
245 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
246 public static Bitmap createBadgedIconBitmap(
247 Drawable icon, UserHandleCompat user, Context context) {
Sunny Goyal531cda62016-03-03 13:19:24 -0800248 float scale = FeatureFlags.LAUNCHER3_DISABLE_ICON_NORMALIZATION ?
Sunny Goyal4a464792016-07-19 14:19:53 -0700249 1 : IconNormalizer.getInstance().getScale(icon, null);
Sunny Goyalfc218302015-09-17 14:59:10 -0700250 Bitmap bitmap = createIconBitmap(icon, context, scale);
Sunny Goyal79cf7182016-07-27 17:32:34 -0700251 return badgeIconForUser(bitmap, user, context);
252 }
253
254 /**
255 * Badges the provided icon with the user badge if required.
256 */
257 public static Bitmap badgeIconForUser(Bitmap icon, UserHandleCompat user, Context context) {
Sunny Goyalb84046d2015-10-19 14:03:30 -0700258 if (Utilities.ATLEAST_LOLLIPOP && user != null
259 && !UserHandleCompat.myUserHandle().equals(user)) {
Sunny Goyal79cf7182016-07-27 17:32:34 -0700260 BitmapDrawable drawable = new FixedSizeBitmapDrawable(icon);
Sunny Goyalb84046d2015-10-19 14:03:30 -0700261 Drawable badged = context.getPackageManager().getUserBadgedIcon(
262 drawable, user.getUser());
263 if (badged instanceof BitmapDrawable) {
264 return ((BitmapDrawable) badged).getBitmap();
265 } else {
266 return createIconBitmap(badged, context);
267 }
268 } else {
Sunny Goyal79cf7182016-07-27 17:32:34 -0700269 return icon;
Sunny Goyalb84046d2015-10-19 14:03:30 -0700270 }
271 }
272
273 /**
Sunny Goyal10923b32016-07-20 15:42:44 -0700274 * Creates a normalized bitmap suitable for the all apps view. The bitmap is also visually
275 * normalized with other icons and has enough spacing to add shadow.
276 */
277 public static Bitmap createScaledBitmapWithoutShadow(Drawable icon, Context context) {
278 RectF iconBounds = new RectF();
279 float scale = FeatureFlags.LAUNCHER3_DISABLE_ICON_NORMALIZATION ?
280 1 : IconNormalizer.getInstance().getScale(icon, iconBounds);
281 scale = Math.min(scale, ShadowGenerator.getScaleForBounds(iconBounds));
282 return createIconBitmap(icon, context, scale);
283 }
284
285 /**
Sunny Goyal79cf7182016-07-27 17:32:34 -0700286 * Adds a shadow to the provided icon. It assumes that the icon has already been scaled using
287 * {@link #createScaledBitmapWithoutShadow(Drawable, Context)}
288 */
289 public static Bitmap addShadowToIcon(Bitmap icon) {
290 return ShadowGenerator.getInstance().recreateIcon(icon);
291 }
292
293 /**
294 * Adds the {@param badge} on top of {@param srcTgt} using the badge dimensions.
Sunny Goyal4a464792016-07-19 14:19:53 -0700295 */
296 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
Sunny Goyal79cf7182016-07-27 17:32:34 -0700297 public static Bitmap badgeWithBitmap(Bitmap srcTgt, Bitmap badge, Context context) {
298 int badgeSize = context.getResources().getDimensionPixelSize(R.dimen.profile_badge_size);
299 synchronized (sCanvas) {
300 sCanvas.setBitmap(srcTgt);
301 sCanvas.drawBitmap(badge, new Rect(0, 0, badge.getWidth(), badge.getHeight()),
302 new Rect(srcTgt.getWidth() - badgeSize,
303 srcTgt.getHeight() - badgeSize, srcTgt.getWidth(), srcTgt.getHeight()),
304 new Paint(Paint.FILTER_BITMAP_FLAG));
305 sCanvas.setBitmap(null);
Sunny Goyal4a464792016-07-19 14:19:53 -0700306 }
Sunny Goyal79cf7182016-07-27 17:32:34 -0700307 return srcTgt;
Sunny Goyal4a464792016-07-19 14:19:53 -0700308 }
309
310 /**
Michael Jurka931dc972011-08-05 15:08:15 -0700311 * Returns a bitmap suitable for the all apps view.
Joe Onorato6665c0f2009-09-02 15:27:24 -0700312 */
Mathew Inwood72fbec12013-11-19 15:45:07 +0000313 public static Bitmap createIconBitmap(Drawable icon, Context context) {
Sunny Goyalfc218302015-09-17 14:59:10 -0700314 return createIconBitmap(icon, context, 1.0f /* scale */);
315 }
316
317 /**
318 * @param scale the scale to apply before drawing {@param icon} on the canvas
319 */
320 public static Bitmap createIconBitmap(Drawable icon, Context context, float scale) {
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700321 synchronized (sCanvas) {
322 final int iconBitmapSize = getIconBitmapSize();
Joe Onorato6665c0f2009-09-02 15:27:24 -0700323
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700324 int width = iconBitmapSize;
325 int height = iconBitmapSize;
Joe Onorato6665c0f2009-09-02 15:27:24 -0700326
Joe Onorato6665c0f2009-09-02 15:27:24 -0700327 if (icon instanceof PaintDrawable) {
328 PaintDrawable painter = (PaintDrawable) icon;
329 painter.setIntrinsicWidth(width);
330 painter.setIntrinsicHeight(height);
331 } else if (icon instanceof BitmapDrawable) {
332 // Ensure the bitmap has a density.
333 BitmapDrawable bitmapDrawable = (BitmapDrawable) icon;
334 Bitmap bitmap = bitmapDrawable.getBitmap();
Sunny Goyalde9590b2015-09-23 12:56:51 -0700335 if (bitmap != null && bitmap.getDensity() == Bitmap.DENSITY_NONE) {
Joe Onorato6665c0f2009-09-02 15:27:24 -0700336 bitmapDrawable.setTargetDensity(context.getResources().getDisplayMetrics());
337 }
338 }
339 int sourceWidth = icon.getIntrinsicWidth();
340 int sourceHeight = icon.getIntrinsicHeight();
Michael Jurka931dc972011-08-05 15:08:15 -0700341 if (sourceWidth > 0 && sourceHeight > 0) {
Winson Chung5f8afe62013-08-12 16:19:28 -0700342 // Scale the icon proportionally to the icon dimensions
343 final float ratio = (float) sourceWidth / sourceHeight;
344 if (sourceWidth > sourceHeight) {
345 height = (int) (width / ratio);
346 } else if (sourceHeight > sourceWidth) {
347 width = (int) (height * ratio);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700348 }
349 }
350
351 // no intrinsic size --> use default size
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700352 int textureWidth = iconBitmapSize;
353 int textureHeight = iconBitmapSize;
Joe Onorato6665c0f2009-09-02 15:27:24 -0700354
355 final Bitmap bitmap = Bitmap.createBitmap(textureWidth, textureHeight,
356 Bitmap.Config.ARGB_8888);
357 final Canvas canvas = sCanvas;
358 canvas.setBitmap(bitmap);
359
360 final int left = (textureWidth-width) / 2;
361 final int top = (textureHeight-height) / 2;
362
Michael Jurka3a9fced2012-04-13 14:44:29 -0700363 @SuppressWarnings("all") // suppress dead code warning
364 final boolean debug = false;
365 if (debug) {
Joe Onorato6665c0f2009-09-02 15:27:24 -0700366 // draw a big box for the icon for debugging
367 canvas.drawColor(sColors[sColorIndex]);
368 if (++sColorIndex >= sColors.length) sColorIndex = 0;
369 Paint debugPaint = new Paint();
370 debugPaint.setColor(0xffcccc00);
371 canvas.drawRect(left, top, left+width, top+height, debugPaint);
372 }
373
374 sOldBounds.set(icon.getBounds());
375 icon.setBounds(left, top, left+width, top+height);
Sunny Goyalfc218302015-09-17 14:59:10 -0700376 canvas.save(Canvas.MATRIX_SAVE_FLAG);
377 canvas.scale(scale, scale, textureWidth / 2, textureHeight / 2);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700378 icon.draw(canvas);
Sunny Goyalfc218302015-09-17 14:59:10 -0700379 canvas.restore();
Joe Onorato6665c0f2009-09-02 15:27:24 -0700380 icon.setBounds(sOldBounds);
Adam Cohenaaf473c2011-08-03 12:02:47 -0700381 canvas.setBitmap(null);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700382
383 return bitmap;
384 }
385 }
386
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800387 /**
Winson Chungc763c4e2013-07-19 13:49:06 -0700388 * Given a coordinate relative to the descendant, find the coordinate in a parent view's
389 * coordinates.
390 *
391 * @param descendant The descendant to which the passed coordinate is relative.
Sunny Goyale8b5d202016-06-13 16:36:59 -0700392 * @param ancestor The root view to make the coordinates relative to.
Winson Chungc763c4e2013-07-19 13:49:06 -0700393 * @param coord The coordinate that we want mapped.
394 * @param includeRootScroll Whether or not to account for the scroll of the descendant:
395 * sometimes this is relevant as in a child's coordinates within the descendant.
396 * @return The factor by which this descendant is scaled relative to this DragLayer. Caution
397 * this scale factor is assumed to be equal in X and Y, and so if at any point this
398 * assumption fails, we will need to return a pair of scale factors.
399 */
Sunny Goyale8b5d202016-06-13 16:36:59 -0700400 public static float getDescendantCoordRelativeToAncestor(
401 View descendant, View ancestor, int[] coord, boolean includeRootScroll) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700402 float[] pt = {coord[0], coord[1]};
Sunny Goyal8cf47a52016-06-15 10:11:30 -0700403 float scale = 1.0f;
Winson Chungc763c4e2013-07-19 13:49:06 -0700404 View v = descendant;
Sunny Goyale8b5d202016-06-13 16:36:59 -0700405 while(v != ancestor && v != null) {
Sunny Goyal8cf47a52016-06-15 10:11:30 -0700406 // For TextViews, scroll has a meaning which relates to the text position
407 // which is very strange... ignore the scroll.
408 if (v != descendant || includeRootScroll) {
409 pt[0] -= v.getScrollX();
410 pt[1] -= v.getScrollY();
411 }
412
413 v.getMatrix().mapPoints(pt);
414 pt[0] += v.getLeft();
415 pt[1] += v.getTop();
416 scale *= v.getScaleX();
417
Winson Chungc763c4e2013-07-19 13:49:06 -0700418 v = (View) v.getParent();
419 }
Winson Chungc763c4e2013-07-19 13:49:06 -0700420
Sunny Goyal8cf47a52016-06-15 10:11:30 -0700421 coord[0] = Math.round(pt[0]);
422 coord[1] = Math.round(pt[1]);
Winson Chungc763c4e2013-07-19 13:49:06 -0700423 return scale;
424 }
425
426 /**
Sunny Goyale8b5d202016-06-13 16:36:59 -0700427 * Inverse of {@link #getDescendantCoordRelativeToAncestor(View, View, int[], boolean)}.
Winson Chungc763c4e2013-07-19 13:49:06 -0700428 */
429 public static float mapCoordInSelfToDescendent(View descendant, View root,
430 int[] coord) {
431 ArrayList<View> ancestorChain = new ArrayList<View>();
432
433 float[] pt = {coord[0], coord[1]};
434
435 View v = descendant;
436 while(v != root) {
437 ancestorChain.add(v);
438 v = (View) v.getParent();
439 }
440 ancestorChain.add(root);
441
442 float scale = 1.0f;
443 Matrix inverse = new Matrix();
444 int count = ancestorChain.size();
445 for (int i = count - 1; i >= 0; i--) {
446 View ancestor = ancestorChain.get(i);
447 View next = i > 0 ? ancestorChain.get(i-1) : null;
448
449 pt[0] += ancestor.getScrollX();
450 pt[1] += ancestor.getScrollY();
451
452 if (next != null) {
453 pt[0] -= next.getLeft();
454 pt[1] -= next.getTop();
455 next.getMatrix().invert(inverse);
456 inverse.mapPoints(pt);
457 scale *= next.getScaleX();
458 }
459 }
460
461 coord[0] = (int) Math.round(pt[0]);
462 coord[1] = (int) Math.round(pt[1]);
463 return scale;
464 }
465
Jason Monk02dd7ae2014-04-15 15:23:31 -0400466 /**
467 * Utility method to determine whether the given point, in local coordinates,
468 * is inside the view, where the area of the view is expanded by the slop factor.
469 * This method is called while processing touch-move events to determine if the event
470 * is still within the view.
471 */
472 public static boolean pointInView(View v, float localX, float localY, float slop) {
473 return localX >= -slop && localY >= -slop && localX < (v.getWidth() + slop) &&
474 localY < (v.getHeight() + slop);
475 }
476
Tony Wickham1bce7fd2016-04-28 17:39:03 -0700477 /** Translates MotionEvents from src's coordinate system to dst's. */
478 public static void translateEventCoordinates(View src, View dst, MotionEvent dstEvent) {
479 toGlobalMotionEvent(src, dstEvent);
480 toLocalMotionEvent(dst, dstEvent);
481 }
482
483 /**
484 * Emulates View.toGlobalMotionEvent(). This implementation does not handle transformations
485 * (scaleX, scaleY, etc).
486 */
487 private static void toGlobalMotionEvent(View view, MotionEvent event) {
488 view.getLocationOnScreen(sLoc0);
489 event.offsetLocation(sLoc0[0], sLoc0[1]);
490 }
491
492 /**
493 * Emulates View.toLocalMotionEvent(). This implementation does not handle transformations
494 * (scaleX, scaleY, etc).
495 */
496 private static void toLocalMotionEvent(View view, MotionEvent event) {
497 view.getLocationOnScreen(sLoc0);
498 event.offsetLocation(-sLoc0[0], -sLoc0[1]);
499 }
500
Adam Cohen63f1ec02014-08-12 09:23:13 -0700501 public static int[] getCenterDeltaInScreenSpace(View v0, View v1, int[] delta) {
502 v0.getLocationInWindow(sLoc0);
503 v1.getLocationInWindow(sLoc1);
504
505 sLoc0[0] += (v0.getMeasuredWidth() * v0.getScaleX()) / 2;
506 sLoc0[1] += (v0.getMeasuredHeight() * v0.getScaleY()) / 2;
507 sLoc1[0] += (v1.getMeasuredWidth() * v1.getScaleX()) / 2;
508 sLoc1[1] += (v1.getMeasuredHeight() * v1.getScaleY()) / 2;
509
510 if (delta == null) {
511 delta = new int[2];
512 }
513
514 delta[0] = sLoc1[0] - sLoc0[0];
515 delta[1] = sLoc1[1] - sLoc0[1];
516
517 return delta;
518 }
519
Winson Chung3a6e7f32013-10-09 15:50:52 -0700520 public static void scaleRectAboutCenter(Rect r, float scale) {
Sunny Goyal106bf642015-07-16 12:18:06 -0700521 if (scale != 1.0f) {
522 int cx = r.centerX();
523 int cy = r.centerY();
524 r.offset(-cx, -cy);
525
526 r.left = (int) (r.left * scale + 0.5f);
527 r.top = (int) (r.top * scale + 0.5f);
528 r.right = (int) (r.right * scale + 0.5f);
529 r.bottom = (int) (r.bottom * scale + 0.5f);
530
531 r.offset(cx, cy);
532 }
Winson Chung3a6e7f32013-10-09 15:50:52 -0700533 }
534
Michael Jurkaa805e1a2013-08-22 15:00:33 +0200535 public static void startActivityForResultSafely(
536 Activity activity, Intent intent, int requestCode) {
537 try {
538 activity.startActivityForResult(intent, requestCode);
539 } catch (ActivityNotFoundException e) {
540 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
541 } catch (SecurityException e) {
542 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
543 Log.e(TAG, "Launcher does not have the permission to launch " + intent +
544 ". Make sure to create a MAIN intent-filter for the corresponding activity " +
545 "or use the exported attribute for this activity.", e);
546 }
547 }
Sunny Goyalc5c60ad2014-07-14 12:02:01 -0700548
549 static boolean isSystemApp(Context context, Intent intent) {
550 PackageManager pm = context.getPackageManager();
551 ComponentName cn = intent.getComponent();
552 String packageName = null;
553 if (cn == null) {
554 ResolveInfo info = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
555 if ((info != null) && (info.activityInfo != null)) {
556 packageName = info.activityInfo.packageName;
557 }
558 } else {
559 packageName = cn.getPackageName();
560 }
561 if (packageName != null) {
562 try {
563 PackageInfo info = pm.getPackageInfo(packageName, 0);
564 return (info != null) && (info.applicationInfo != null) &&
565 ((info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
566 } catch (NameNotFoundException e) {
567 return false;
568 }
569 } else {
570 return false;
571 }
572 }
Sunny Goyal95abbb32014-08-04 10:53:22 -0700573
574 /**
575 * This picks a dominant color, looking for high-saturation, high-value, repeated hues.
576 * @param bitmap The bitmap to scan
577 * @param samples The approximate max number of samples to use.
578 */
579 static int findDominantColorByHue(Bitmap bitmap, int samples) {
580 final int height = bitmap.getHeight();
581 final int width = bitmap.getWidth();
582 int sampleStride = (int) Math.sqrt((height * width) / samples);
583 if (sampleStride < 1) {
584 sampleStride = 1;
585 }
586
587 // This is an out-param, for getting the hsv values for an rgb
588 float[] hsv = new float[3];
589
590 // First get the best hue, by creating a histogram over 360 hue buckets,
591 // where each pixel contributes a score weighted by saturation, value, and alpha.
592 float[] hueScoreHistogram = new float[360];
593 float highScore = -1;
594 int bestHue = -1;
595
596 for (int y = 0; y < height; y += sampleStride) {
597 for (int x = 0; x < width; x += sampleStride) {
598 int argb = bitmap.getPixel(x, y);
599 int alpha = 0xFF & (argb >> 24);
600 if (alpha < 0x80) {
601 // Drop mostly-transparent pixels.
602 continue;
603 }
604 // Remove the alpha channel.
605 int rgb = argb | 0xFF000000;
606 Color.colorToHSV(rgb, hsv);
607 // Bucket colors by the 360 integer hues.
608 int hue = (int) hsv[0];
609 if (hue < 0 || hue >= hueScoreHistogram.length) {
610 // Defensively avoid array bounds violations.
611 continue;
612 }
613 float score = hsv[1] * hsv[2];
614 hueScoreHistogram[hue] += score;
615 if (hueScoreHistogram[hue] > highScore) {
616 highScore = hueScoreHistogram[hue];
617 bestHue = hue;
618 }
619 }
620 }
621
622 SparseArray<Float> rgbScores = new SparseArray<Float>();
623 int bestColor = 0xff000000;
624 highScore = -1;
625 // Go back over the RGB colors that match the winning hue,
626 // creating a histogram of weighted s*v scores, for up to 100*100 [s,v] buckets.
627 // The highest-scoring RGB color wins.
628 for (int y = 0; y < height; y += sampleStride) {
629 for (int x = 0; x < width; x += sampleStride) {
630 int rgb = bitmap.getPixel(x, y) | 0xff000000;
631 Color.colorToHSV(rgb, hsv);
632 int hue = (int) hsv[0];
633 if (hue == bestHue) {
634 float s = hsv[1];
635 float v = hsv[2];
636 int bucket = (int) (s * 100) + (int) (v * 10000);
637 // Score by cumulative saturation * value.
638 float score = s * v;
639 Float oldTotal = rgbScores.get(bucket);
640 float newTotal = oldTotal == null ? score : oldTotal + score;
641 rgbScores.put(bucket, newTotal);
642 if (newTotal > highScore) {
643 highScore = newTotal;
644 // All the colors in the winning bucket are very similar. Last in wins.
645 bestColor = rgb;
646 }
647 }
648 }
649 }
650 return bestColor;
651 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700652
653 /*
654 * Finds a system apk which had a broadcast receiver listening to a particular action.
655 * @param action intent action used to find the apk
656 * @return a pair of apk package name and the resources.
657 */
658 static Pair<String, Resources> findSystemApk(String action, PackageManager pm) {
659 final Intent intent = new Intent(action);
660 for (ResolveInfo info : pm.queryBroadcastReceivers(intent, 0)) {
661 if (info.activityInfo != null &&
662 (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
663 final String packageName = info.activityInfo.packageName;
664 try {
665 final Resources res = pm.getResourcesForApplication(packageName);
666 return Pair.create(packageName, res);
667 } catch (NameNotFoundException e) {
668 Log.w(TAG, "Failed to find resources for " + packageName);
669 }
670 }
671 }
672 return null;
673 }
Sunny Goyalfafca522014-11-03 11:30:01 -0800674
Sunny Goyal594d76d2014-11-06 10:12:54 -0800675 /**
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700676 * Compresses the bitmap to a byte array for serialization.
677 */
678 public static byte[] flattenBitmap(Bitmap bitmap) {
679 // Try go guesstimate how much space the icon will take when serialized
680 // to avoid unnecessary allocations/copies during the write.
681 int size = bitmap.getWidth() * bitmap.getHeight() * 4;
682 ByteArrayOutputStream out = new ByteArrayOutputStream(size);
683 try {
684 bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
685 out.flush();
686 out.close();
687 return out.toByteArray();
688 } catch (IOException e) {
689 Log.w(TAG, "Could not write bitmap");
690 return null;
691 }
692 }
693
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700694 /**
Winson Chung82b016c2015-05-08 17:00:10 -0700695 * Trims the string, removing all whitespace at the beginning and end of the string.
696 * Non-breaking whitespaces are also removed.
697 */
698 public static String trim(CharSequence s) {
Winson Chungafa77e92015-05-15 12:04:03 -0700699 if (s == null) {
700 return null;
701 }
702
Winson Chung82b016c2015-05-08 17:00:10 -0700703 // Just strip any sequence of whitespace or java space characters from the beginning and end
704 Matcher m = sTrimPattern.matcher(s);
705 return m.replaceAll("$1");
706 }
Sunny Goyal70660032015-05-14 00:07:08 -0700707
Winson Chung2c6e5cc2015-06-01 14:38:24 -0700708 /**
709 * Calculates the height of a given string at a specific text size.
710 */
711 public static float calculateTextHeight(float textSizePx) {
712 Paint p = new Paint();
713 p.setTextSize(textSizePx);
714 Paint.FontMetrics fm = p.getFontMetrics();
715 return -fm.top + fm.bottom;
716 }
717
Winson Chungb1777442015-06-16 13:35:04 -0700718 /**
719 * Convenience println with multiple args.
720 */
721 public static void println(String key, Object... args) {
722 StringBuilder b = new StringBuilder();
723 b.append(key);
724 b.append(": ");
725 boolean isFirstArgument = true;
726 for (Object arg : args) {
727 if (isFirstArgument) {
728 isFirstArgument = false;
729 } else {
730 b.append(", ");
731 }
732 b.append(arg);
733 }
734 System.out.println(b.toString());
735 }
736
Sunny Goyal70660032015-05-14 00:07:08 -0700737 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
738 public static boolean isRtl(Resources res) {
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700739 return ATLEAST_JB_MR1 &&
Sunny Goyal70660032015-05-14 00:07:08 -0700740 (res.getConfiguration().getLayoutDirection() == View.LAYOUT_DIRECTION_RTL);
741 }
Hyunyoung Song2bd3d7d2015-05-21 13:04:53 -0700742
Sunny Goyal5c97f512015-05-19 16:03:28 -0700743 /**
744 * Returns true if the intent is a valid launch intent for a launcher activity of an app.
745 * This is used to identify shortcuts which are different from the ones exposed by the
746 * applications' manifest file.
747 *
748 * @param launchIntent The intent that will be launched when the shortcut is clicked.
749 */
750 public static boolean isLauncherAppTarget(Intent launchIntent) {
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700751 if (launchIntent != null
Sunny Goyal5c97f512015-05-19 16:03:28 -0700752 && Intent.ACTION_MAIN.equals(launchIntent.getAction())
753 && launchIntent.getComponent() != null
754 && launchIntent.getCategories() != null
755 && launchIntent.getCategories().size() == 1
756 && launchIntent.hasCategory(Intent.CATEGORY_LAUNCHER)
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700757 && TextUtils.isEmpty(launchIntent.getDataString())) {
758 // An app target can either have no extra or have ItemInfo.EXTRA_PROFILE.
759 Bundle extras = launchIntent.getExtras();
760 if (extras == null) {
761 return true;
762 } else {
763 Set<String> keys = extras.keySet();
764 return keys.size() == 1 && keys.contains(ItemInfo.EXTRA_PROFILE);
765 }
766 };
767 return false;
Sunny Goyal5c97f512015-05-19 16:03:28 -0700768 }
Adam Cohen2e6da152015-05-06 11:42:25 -0700769
770 public static float dpiFromPx(int size, DisplayMetrics metrics){
771 float densityRatio = (float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT;
772 return (size / densityRatio);
773 }
774 public static int pxFromDp(float size, DisplayMetrics metrics) {
775 return (int) Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
776 size, metrics));
777 }
778 public static int pxFromSp(float size, DisplayMetrics metrics) {
779 return (int) Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
780 size, metrics));
781 }
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700782
783 public static String createDbSelectionQuery(String columnName, Iterable<?> values) {
784 return String.format(Locale.ENGLISH, "%s IN (%s)", columnName, TextUtils.join(", ", values));
785 }
Sunny Goyal25aba0a2015-07-16 15:07:47 -0700786
Sunny Goyal25aba0a2015-07-16 15:07:47 -0700787 public static boolean isBootCompleted() {
788 try {
789 Class clazz = Class.forName("android.os.SystemProperties");
790 Method getter = clazz.getDeclaredMethod("get", String.class);
791 String value = (String) getter.invoke(null, "sys.boot_completed");
792 return "1".equals(value);
793 } catch (Exception e) {
794 Log.d(TAG, "Unable to read system properties");
795 // Assume that boot has completed
796 return true;
797 }
798 }
Tony Wickham29d853c2015-09-08 10:35:56 -0700799
800 /**
801 * Ensures that a value is within given bounds. Specifically:
802 * If value is less than lowerBound, return lowerBound; else if value is greater than upperBound,
803 * return upperBound; else return value unchanged.
804 */
Tony Wickhamf549dab2016-05-16 09:54:06 -0700805 public static int boundToRange(int value, int lowerBound, int upperBound) {
806 return Math.max(lowerBound, Math.min(value, upperBound));
807 }
808
809 /**
810 * @see #boundToRange(int, int, int).
811 */
812 public static float boundToRange(float value, float lowerBound, float upperBound) {
Tony Wickham29d853c2015-09-08 10:35:56 -0700813 return Math.max(lowerBound, Math.min(value, upperBound));
814 }
Sunny Goyal9d438082015-09-25 11:50:16 -0700815
Sunny Goyale78e3d72015-09-24 11:23:31 -0700816 /**
817 * Wraps a message with a TTS span, so that a different message is spoken than
818 * what is getting displayed.
819 * @param msg original message
820 * @param ttsMsg message to be spoken
821 */
822 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
823 public static CharSequence wrapForTts(CharSequence msg, String ttsMsg) {
824 if (Utilities.ATLEAST_LOLLIPOP) {
825 SpannableString spanned = new SpannableString(msg);
826 spanned.setSpan(new TtsSpan.TextBuilder(ttsMsg).build(),
827 0, spanned.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
828 return spanned;
829 } else {
830 return msg;
831 }
832 }
Winson12fb9fc2015-10-01 15:34:08 -0700833
834 /**
835 * Replacement for Long.compare() which was added in API level 19.
836 */
837 public static int longCompare(long lhs, long rhs) {
838 return lhs < rhs ? -1 : (lhs == rhs ? 0 : 1);
839 }
Sunny Goyalf7258242015-10-19 16:59:07 -0700840
841 public static SharedPreferences getPrefs(Context context) {
842 return context.getSharedPreferences(
843 LauncherFiles.SHARED_PREFERENCES_KEY, Context.MODE_PRIVATE);
844 }
Tony Wickham112ac952015-11-12 12:31:50 -0800845
846 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
847 public static boolean isPowerSaverOn(Context context) {
848 PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
849 return ATLEAST_LOLLIPOP && powerManager.isPowerSaveMode();
850 }
Sunny Goyale1483fb2016-01-08 12:16:15 -0800851
Sunny Goyal1ed6c4a2016-04-21 15:16:11 -0700852 public static boolean isWallapaperAllowed(Context context) {
853 if (isNycOrAbove()) {
854 try {
855 WallpaperManager wm = context.getSystemService(WallpaperManager.class);
Kenny Guy367da9f2016-05-25 19:22:14 +0100856 return (Boolean) wm.getClass().getDeclaredMethod("isSetWallpaperAllowed")
Sunny Goyal1ed6c4a2016-04-21 15:16:11 -0700857 .invoke(wm);
858 } catch (Exception e) { }
859 }
860 return true;
861 }
862
Sunny Goyal713edfc2016-05-06 09:58:34 -0700863 public static void closeSilently(Closeable c) {
864 if (c != null) {
865 try {
866 c.close();
867 } catch (IOException e) {
868 if (ProviderConfig.IS_DOGFOOD_BUILD) {
869 Log.d(TAG, "Error closing", e);
870 }
871 }
872 }
873 }
874
Sunny Goyale1483fb2016-01-08 12:16:15 -0800875 /**
Sunny Goyal3f732192016-05-13 13:48:44 -0700876 * Returns true if {@param original} contains all entries defined in {@param updates} and
877 * have the same value.
878 * The comparison uses {@link Object#equals(Object)} to compare the values.
879 */
880 public static boolean containsAll(Bundle original, Bundle updates) {
881 for (String key : updates.keySet()) {
882 Object value1 = updates.get(key);
883 Object value2 = original.get(key);
884 if (value1 == null) {
885 if (value2 != null) {
886 return false;
887 }
888 } else if (!value1.equals(value2)) {
889 return false;
890 }
891 }
892 return true;
893 }
894
Tony Wickham1bce7fd2016-04-28 17:39:03 -0700895 /** Returns whether the collection is null or empty. */
896 public static boolean isEmpty(Collection c) {
897 return c == null || c.isEmpty();
898 }
899
Sunny Goyal3f732192016-05-13 13:48:44 -0700900 /**
Sunny Goyale1483fb2016-01-08 12:16:15 -0800901 * An extension of {@link BitmapDrawable} which returns the bitmap pixel size as intrinsic size.
902 * This allows the badging to be done based on the action bitmap size rather than
903 * the scaled bitmap size.
904 */
905 private static class FixedSizeBitmapDrawable extends BitmapDrawable {
906
907 public FixedSizeBitmapDrawable(Bitmap bitmap) {
908 super(null, bitmap);
909 }
910
911 @Override
912 public int getIntrinsicHeight() {
913 return getBitmap().getWidth();
914 }
915
916 @Override
917 public int getIntrinsicWidth() {
918 return getBitmap().getWidth();
919 }
920 }
Andrew Sappersteinabef55a2016-06-19 12:49:00 -0700921
922 public static int getColorAccent(Context context) {
923 TypedArray ta = context.obtainStyledAttributes(new int[]{android.R.attr.colorAccent});
924 int colorAccent = ta.getColor(0, 0);
925 ta.recycle();
926 return colorAccent;
927 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800928}