blob: 50f715634e30df592080196d632a31bc7592f51f [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 Goyal4e5cc642015-06-25 16:37:44 -070048import android.os.Bundle;
Tony Wickham112ac952015-11-12 12:31:50 -080049import android.os.PowerManager;
Sunny Goyale78e3d72015-09-24 11:23:31 -070050import android.text.Spannable;
51import android.text.SpannableString;
Sunny Goyal5c97f512015-05-19 16:03:28 -070052import android.text.TextUtils;
Sunny Goyale78e3d72015-09-24 11:23:31 -070053import android.text.style.TtsSpan;
Adam Cohen2e6da152015-05-06 11:42:25 -070054import android.util.DisplayMetrics;
Michael Jurkaa805e1a2013-08-22 15:00:33 +020055import android.util.Log;
Sunny Goyal0fe505b2014-08-06 09:55:36 -070056import android.util.Pair;
Sunny Goyal95abbb32014-08-04 10:53:22 -070057import android.util.SparseArray;
Adam Cohen2e6da152015-05-06 11:42:25 -070058import android.util.TypedValue;
Tony Wickham1bce7fd2016-04-28 17:39:03 -070059import android.view.MotionEvent;
Winson Chungc763c4e2013-07-19 13:49:06 -070060import android.view.View;
Michael Jurkaa805e1a2013-08-22 15:00:33 +020061import android.widget.Toast;
Sunny Goyalb1622cc2015-06-10 16:00:42 -070062
Sunny Goyalb84046d2015-10-19 14:03:30 -070063import com.android.launcher3.compat.UserHandleCompat;
Sunny Goyald896ee42015-12-17 11:24:31 -080064import com.android.launcher3.config.FeatureFlags;
Sunny Goyal713edfc2016-05-06 09:58:34 -070065import com.android.launcher3.config.ProviderConfig;
Sunny Goyal4a464792016-07-19 14:19:53 -070066import com.android.launcher3.graphics.ShadowGenerator;
Sunny Goyalfc218302015-09-17 14:59:10 -070067import com.android.launcher3.util.IconNormalizer;
Sunny Goyal6c56c682015-07-16 14:09:05 -070068
Sunny Goyal5b0e6692015-03-19 14:31:19 -070069import java.io.ByteArrayOutputStream;
Sunny Goyal713edfc2016-05-06 09:58:34 -070070import java.io.Closeable;
Sunny Goyal5b0e6692015-03-19 14:31:19 -070071import java.io.IOException;
Sunny Goyal25aba0a2015-07-16 15:07:47 -070072import java.lang.reflect.Method;
Winson Chungc763c4e2013-07-19 13:49:06 -070073import java.util.ArrayList;
Tony Wickham1bce7fd2016-04-28 17:39:03 -070074import java.util.Collection;
Sunny Goyalb1622cc2015-06-10 16:00:42 -070075import java.util.Locale;
Sunny Goyal4e5cc642015-06-25 16:37:44 -070076import java.util.Set;
Sunny Goyal8ac727b2015-09-23 15:38:09 -070077import java.util.concurrent.Executor;
78import java.util.concurrent.LinkedBlockingQueue;
79import java.util.concurrent.ThreadPoolExecutor;
80import java.util.concurrent.TimeUnit;
Winson Chung82b016c2015-05-08 17:00:10 -070081import java.util.regex.Matcher;
82import java.util.regex.Pattern;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080083
84/**
85 * Various utilities shared amongst the Launcher's classes.
86 */
Mathew Inwood72fbec12013-11-19 15:45:07 +000087public final class Utilities {
Rahul Chaturvedi7fc77ca2015-05-19 18:02:16 -070088
Joe Onorato1291a8c2009-09-15 15:07:25 -040089 private static final String TAG = "Launcher.Utilities";
90
The Android Open Source Project31dd5032009-03-03 19:32:27 -080091 private static final Rect sOldBounds = new Rect();
Romain Guy89911d22009-09-28 18:48:49 -070092 private static final Canvas sCanvas = new Canvas();
The Android Open Source Project31dd5032009-03-03 19:32:27 -080093
Winson Chung82b016c2015-05-08 17:00:10 -070094 private static final Pattern sTrimPattern =
95 Pattern.compile("^[\\s|\\p{javaSpaceChar}]*(.*)[\\s|\\p{javaSpaceChar}]*$");
96
The Android Open Source Project31dd5032009-03-03 19:32:27 -080097 static {
98 sCanvas.setDrawFilter(new PaintFlagsDrawFilter(Paint.DITHER_FLAG,
99 Paint.FILTER_BITMAP_FLAG));
100 }
Joe Onorato6665c0f2009-09-02 15:27:24 -0700101 static int sColors[] = { 0xffff0000, 0xff00ff00, 0xff0000ff };
102 static int sColorIndex = 0;
103
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700104 private static final int[] sLoc0 = new int[2];
105 private static final int[] sLoc1 = new int[2];
Michael Jurka7ad868b2013-12-12 15:04:25 +0100106
Sunny Goyal9994b2b2016-06-23 14:17:24 -0700107 public static boolean isNycMR1OrAbove() {
Sunny Goyala9206122016-08-15 19:34:37 -0700108 return Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1;
Sunny Goyal9994b2b2016-06-23 14:17:24 -0700109 }
110
Winsonbe9798b2016-07-20 12:55:49 -0700111 public static final boolean ATLEAST_MARSHMALLOW =
112 Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700113
114 public static final boolean ATLEAST_LOLLIPOP_MR1 =
115 Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1;
116
117 public static final boolean ATLEAST_LOLLIPOP =
118 Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
119
120 public static final boolean ATLEAST_KITKAT =
121 Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
122
123 public static final boolean ATLEAST_JB_MR1 =
124 Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1;
125
126 public static final boolean ATLEAST_JB_MR2 =
127 Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2;
128
Sunny Goyal6f866092016-03-17 17:04:15 -0700129 // An intent extra to indicate the horizontal scroll of the wallpaper.
130 public static final String EXTRA_WALLPAPER_OFFSET = "com.android.launcher3.WALLPAPER_OFFSET";
131
Sunny Goyal8ac727b2015-09-23 15:38:09 -0700132 // These values are same as that in {@link AsyncTask}.
133 private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
134 private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
135 private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
136 private static final int KEEP_ALIVE = 1;
137 /**
138 * An {@link Executor} to be used with async task with no limit on the queue size.
139 */
140 public static final Executor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(
141 CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
142 TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
143
Rahul Chaturvedi7fc77ca2015-05-19 18:02:16 -0700144 public static final String ALLOW_ROTATION_PREFERENCE_KEY = "pref_allowRotation";
145
Sunny Goyal4bbf4192014-11-11 12:23:59 -0800146 public static boolean isPropertyEnabled(String propertyName) {
Michael Jurka7ad868b2013-12-12 15:04:25 +0100147 return Log.isLoggable(propertyName, Log.VERBOSE);
148 }
149
Sunny Goyal21bf5312015-08-21 11:08:24 -0700150 public static boolean isAllowRotationPrefEnabled(Context context) {
Sunny Goyalf48e5922016-05-12 15:36:20 -0700151 return getPrefs(context).getBoolean(ALLOW_ROTATION_PREFERENCE_KEY,
152 getAllowRotationDefaultValue(context));
153 }
154
155 public static boolean getAllowRotationDefaultValue(Context context) {
Sunny Goyal8f3819b2016-02-23 14:49:22 -0800156 if (isNycOrAbove()) {
157 // If the device was scaled, used the original dimensions to determine if rotation
158 // is allowed of not.
159 try {
160 // TODO: Use the actual field when the API is finalized.
161 int originalDensity =
162 DisplayMetrics.class.getField("DENSITY_DEVICE_STABLE").getInt(null);
163 Resources res = context.getResources();
164 int originalSmallestWidth = res.getConfiguration().smallestScreenWidthDp
165 * res.getDisplayMetrics().densityDpi / originalDensity;
Sunny Goyalf48e5922016-05-12 15:36:20 -0700166 return originalSmallestWidth >= 600;
Sunny Goyal8f3819b2016-02-23 14:49:22 -0800167 } catch (Exception e) {
168 // Ignore
169 }
170 }
Sunny Goyalf48e5922016-05-12 15:36:20 -0700171 return false;
Michael Jurka7ad868b2013-12-12 15:04:25 +0100172 }
173
Vadim Tryshev9de91272015-08-03 18:37:17 -0700174 public static boolean isNycOrAbove() {
175 // TODO(vadimt): Replace using reflection with looking at the API version once
176 // Build.VERSION.SDK_INT gets bumped to 24. b/22942492.
177 try {
178 View.class.getDeclaredField("DRAG_FLAG_OPAQUE");
179 // View.DRAG_FLAG_OPAQUE doesn't exist in M-release, so it's an indication of N+.
180 return true;
181 } catch (NoSuchFieldException e) {
182 return false;
183 }
184 }
185
Sunny Goyal745bad92016-05-02 10:54:12 -0700186 // TODO: Use Intent.ACTION_APPLICATION_PREFERENCES when N SDK is available.
187 public static final String ACTION_APPLICATION_PREFERENCES
188 = "android.intent.action.APPLICATION_PREFERENCES";
189
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700190 public static Bitmap createIconBitmap(Cursor c, int iconIndex, Context context) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -0800191 byte[] data = c.getBlob(iconIndex);
192 try {
193 return createIconBitmap(BitmapFactory.decodeByteArray(data, 0, data.length), context);
194 } catch (Exception e) {
195 return null;
196 }
197 }
198
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -0700199 /**
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700200 * Returns a bitmap suitable for the all apps view. If the package or the resource do not
201 * exist, it returns null.
202 */
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700203 public static Bitmap createIconBitmap(String packageName, String resourceName,
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700204 Context context) {
205 PackageManager packageManager = context.getPackageManager();
206 // the resource
207 try {
208 Resources resources = packageManager.getResourcesForApplication(packageName);
209 if (resources != null) {
210 final int id = resources.getIdentifier(resourceName, null, null);
211 return createIconBitmap(
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700212 resources.getDrawableForDensity(id, LauncherAppState.getInstance()
213 .getInvariantDeviceProfile().fillResIconDpi), context);
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700214 }
215 } catch (Exception e) {
216 // Icon not found.
217 }
218 return null;
219 }
220
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700221 private static int getIconBitmapSize() {
222 return LauncherAppState.getInstance().getInvariantDeviceProfile().iconBitmapSize;
223 }
224
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700225 /**
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700226 * Returns a bitmap which is of the appropriate size to be displayed as an icon
Michael Jurka931dc972011-08-05 15:08:15 -0700227 */
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700228 public static Bitmap createIconBitmap(Bitmap icon, Context context) {
229 final int iconBitmapSize = getIconBitmapSize();
230 if (iconBitmapSize == icon.getWidth() && iconBitmapSize == icon.getHeight()) {
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700231 return icon;
232 }
233 return createIconBitmap(new BitmapDrawable(context.getResources(), icon), context);
Michael Jurka931dc972011-08-05 15:08:15 -0700234 }
235
236 /**
Sunny Goyalfc218302015-09-17 14:59:10 -0700237 * Returns a bitmap suitable for the all apps view. The icon is badged for {@param user}.
238 * The bitmap is also visually normalized with other icons.
Sunny Goyalb84046d2015-10-19 14:03:30 -0700239 */
240 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
241 public static Bitmap createBadgedIconBitmap(
242 Drawable icon, UserHandleCompat user, Context context) {
Sunny Goyal531cda62016-03-03 13:19:24 -0800243 float scale = FeatureFlags.LAUNCHER3_DISABLE_ICON_NORMALIZATION ?
Sunny Goyal4a464792016-07-19 14:19:53 -0700244 1 : IconNormalizer.getInstance().getScale(icon, null);
Sunny Goyalfc218302015-09-17 14:59:10 -0700245 Bitmap bitmap = createIconBitmap(icon, context, scale);
Sunny Goyal79cf7182016-07-27 17:32:34 -0700246 return badgeIconForUser(bitmap, user, context);
247 }
248
249 /**
250 * Badges the provided icon with the user badge if required.
251 */
252 public static Bitmap badgeIconForUser(Bitmap icon, UserHandleCompat user, Context context) {
Sunny Goyalb84046d2015-10-19 14:03:30 -0700253 if (Utilities.ATLEAST_LOLLIPOP && user != null
254 && !UserHandleCompat.myUserHandle().equals(user)) {
Sunny Goyal79cf7182016-07-27 17:32:34 -0700255 BitmapDrawable drawable = new FixedSizeBitmapDrawable(icon);
Sunny Goyalb84046d2015-10-19 14:03:30 -0700256 Drawable badged = context.getPackageManager().getUserBadgedIcon(
257 drawable, user.getUser());
258 if (badged instanceof BitmapDrawable) {
259 return ((BitmapDrawable) badged).getBitmap();
260 } else {
261 return createIconBitmap(badged, context);
262 }
263 } else {
Sunny Goyal79cf7182016-07-27 17:32:34 -0700264 return icon;
Sunny Goyalb84046d2015-10-19 14:03:30 -0700265 }
266 }
267
268 /**
Sunny Goyal10923b32016-07-20 15:42:44 -0700269 * Creates a normalized bitmap suitable for the all apps view. The bitmap is also visually
270 * normalized with other icons and has enough spacing to add shadow.
271 */
272 public static Bitmap createScaledBitmapWithoutShadow(Drawable icon, Context context) {
273 RectF iconBounds = new RectF();
274 float scale = FeatureFlags.LAUNCHER3_DISABLE_ICON_NORMALIZATION ?
275 1 : IconNormalizer.getInstance().getScale(icon, iconBounds);
276 scale = Math.min(scale, ShadowGenerator.getScaleForBounds(iconBounds));
277 return createIconBitmap(icon, context, scale);
278 }
279
280 /**
Sunny Goyal79cf7182016-07-27 17:32:34 -0700281 * Adds a shadow to the provided icon. It assumes that the icon has already been scaled using
282 * {@link #createScaledBitmapWithoutShadow(Drawable, Context)}
283 */
284 public static Bitmap addShadowToIcon(Bitmap icon) {
285 return ShadowGenerator.getInstance().recreateIcon(icon);
286 }
287
288 /**
289 * Adds the {@param badge} on top of {@param srcTgt} using the badge dimensions.
Sunny Goyal4a464792016-07-19 14:19:53 -0700290 */
291 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
Sunny Goyal79cf7182016-07-27 17:32:34 -0700292 public static Bitmap badgeWithBitmap(Bitmap srcTgt, Bitmap badge, Context context) {
293 int badgeSize = context.getResources().getDimensionPixelSize(R.dimen.profile_badge_size);
294 synchronized (sCanvas) {
295 sCanvas.setBitmap(srcTgt);
296 sCanvas.drawBitmap(badge, new Rect(0, 0, badge.getWidth(), badge.getHeight()),
297 new Rect(srcTgt.getWidth() - badgeSize,
298 srcTgt.getHeight() - badgeSize, srcTgt.getWidth(), srcTgt.getHeight()),
299 new Paint(Paint.FILTER_BITMAP_FLAG));
300 sCanvas.setBitmap(null);
Sunny Goyal4a464792016-07-19 14:19:53 -0700301 }
Sunny Goyal79cf7182016-07-27 17:32:34 -0700302 return srcTgt;
Sunny Goyal4a464792016-07-19 14:19:53 -0700303 }
304
305 /**
Michael Jurka931dc972011-08-05 15:08:15 -0700306 * Returns a bitmap suitable for the all apps view.
Joe Onorato6665c0f2009-09-02 15:27:24 -0700307 */
Mathew Inwood72fbec12013-11-19 15:45:07 +0000308 public static Bitmap createIconBitmap(Drawable icon, Context context) {
Sunny Goyalfc218302015-09-17 14:59:10 -0700309 return createIconBitmap(icon, context, 1.0f /* scale */);
310 }
311
312 /**
313 * @param scale the scale to apply before drawing {@param icon} on the canvas
314 */
315 public static Bitmap createIconBitmap(Drawable icon, Context context, float scale) {
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700316 synchronized (sCanvas) {
317 final int iconBitmapSize = getIconBitmapSize();
Joe Onorato6665c0f2009-09-02 15:27:24 -0700318
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700319 int width = iconBitmapSize;
320 int height = iconBitmapSize;
Joe Onorato6665c0f2009-09-02 15:27:24 -0700321
Joe Onorato6665c0f2009-09-02 15:27:24 -0700322 if (icon instanceof PaintDrawable) {
323 PaintDrawable painter = (PaintDrawable) icon;
324 painter.setIntrinsicWidth(width);
325 painter.setIntrinsicHeight(height);
326 } else if (icon instanceof BitmapDrawable) {
327 // Ensure the bitmap has a density.
328 BitmapDrawable bitmapDrawable = (BitmapDrawable) icon;
329 Bitmap bitmap = bitmapDrawable.getBitmap();
Sunny Goyalde9590b2015-09-23 12:56:51 -0700330 if (bitmap != null && bitmap.getDensity() == Bitmap.DENSITY_NONE) {
Joe Onorato6665c0f2009-09-02 15:27:24 -0700331 bitmapDrawable.setTargetDensity(context.getResources().getDisplayMetrics());
332 }
333 }
334 int sourceWidth = icon.getIntrinsicWidth();
335 int sourceHeight = icon.getIntrinsicHeight();
Michael Jurka931dc972011-08-05 15:08:15 -0700336 if (sourceWidth > 0 && sourceHeight > 0) {
Winson Chung5f8afe62013-08-12 16:19:28 -0700337 // Scale the icon proportionally to the icon dimensions
338 final float ratio = (float) sourceWidth / sourceHeight;
339 if (sourceWidth > sourceHeight) {
340 height = (int) (width / ratio);
341 } else if (sourceHeight > sourceWidth) {
342 width = (int) (height * ratio);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700343 }
344 }
345
346 // no intrinsic size --> use default size
Sunny Goyal53d7ee42015-05-22 12:25:45 -0700347 int textureWidth = iconBitmapSize;
348 int textureHeight = iconBitmapSize;
Joe Onorato6665c0f2009-09-02 15:27:24 -0700349
350 final Bitmap bitmap = Bitmap.createBitmap(textureWidth, textureHeight,
351 Bitmap.Config.ARGB_8888);
352 final Canvas canvas = sCanvas;
353 canvas.setBitmap(bitmap);
354
355 final int left = (textureWidth-width) / 2;
356 final int top = (textureHeight-height) / 2;
357
Michael Jurka3a9fced2012-04-13 14:44:29 -0700358 @SuppressWarnings("all") // suppress dead code warning
359 final boolean debug = false;
360 if (debug) {
Joe Onorato6665c0f2009-09-02 15:27:24 -0700361 // draw a big box for the icon for debugging
362 canvas.drawColor(sColors[sColorIndex]);
363 if (++sColorIndex >= sColors.length) sColorIndex = 0;
364 Paint debugPaint = new Paint();
365 debugPaint.setColor(0xffcccc00);
366 canvas.drawRect(left, top, left+width, top+height, debugPaint);
367 }
368
369 sOldBounds.set(icon.getBounds());
370 icon.setBounds(left, top, left+width, top+height);
Sunny Goyalfc218302015-09-17 14:59:10 -0700371 canvas.save(Canvas.MATRIX_SAVE_FLAG);
372 canvas.scale(scale, scale, textureWidth / 2, textureHeight / 2);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700373 icon.draw(canvas);
Sunny Goyalfc218302015-09-17 14:59:10 -0700374 canvas.restore();
Joe Onorato6665c0f2009-09-02 15:27:24 -0700375 icon.setBounds(sOldBounds);
Adam Cohenaaf473c2011-08-03 12:02:47 -0700376 canvas.setBitmap(null);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700377
378 return bitmap;
379 }
380 }
381
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800382 /**
Winson Chungc763c4e2013-07-19 13:49:06 -0700383 * Given a coordinate relative to the descendant, find the coordinate in a parent view's
384 * coordinates.
385 *
386 * @param descendant The descendant to which the passed coordinate is relative.
Sunny Goyale8b5d202016-06-13 16:36:59 -0700387 * @param ancestor The root view to make the coordinates relative to.
Winson Chungc763c4e2013-07-19 13:49:06 -0700388 * @param coord The coordinate that we want mapped.
389 * @param includeRootScroll Whether or not to account for the scroll of the descendant:
390 * sometimes this is relevant as in a child's coordinates within the descendant.
391 * @return The factor by which this descendant is scaled relative to this DragLayer. Caution
392 * this scale factor is assumed to be equal in X and Y, and so if at any point this
393 * assumption fails, we will need to return a pair of scale factors.
394 */
Sunny Goyale8b5d202016-06-13 16:36:59 -0700395 public static float getDescendantCoordRelativeToAncestor(
396 View descendant, View ancestor, int[] coord, boolean includeRootScroll) {
Winson Chungc763c4e2013-07-19 13:49:06 -0700397 float[] pt = {coord[0], coord[1]};
Sunny Goyal8cf47a52016-06-15 10:11:30 -0700398 float scale = 1.0f;
Winson Chungc763c4e2013-07-19 13:49:06 -0700399 View v = descendant;
Sunny Goyale8b5d202016-06-13 16:36:59 -0700400 while(v != ancestor && v != null) {
Sunny Goyal8cf47a52016-06-15 10:11:30 -0700401 // For TextViews, scroll has a meaning which relates to the text position
402 // which is very strange... ignore the scroll.
403 if (v != descendant || includeRootScroll) {
404 pt[0] -= v.getScrollX();
405 pt[1] -= v.getScrollY();
406 }
407
408 v.getMatrix().mapPoints(pt);
409 pt[0] += v.getLeft();
410 pt[1] += v.getTop();
411 scale *= v.getScaleX();
412
Winson Chungc763c4e2013-07-19 13:49:06 -0700413 v = (View) v.getParent();
414 }
Winson Chungc763c4e2013-07-19 13:49:06 -0700415
Sunny Goyal8cf47a52016-06-15 10:11:30 -0700416 coord[0] = Math.round(pt[0]);
417 coord[1] = Math.round(pt[1]);
Winson Chungc763c4e2013-07-19 13:49:06 -0700418 return scale;
419 }
420
421 /**
Sunny Goyale8b5d202016-06-13 16:36:59 -0700422 * Inverse of {@link #getDescendantCoordRelativeToAncestor(View, View, int[], boolean)}.
Winson Chungc763c4e2013-07-19 13:49:06 -0700423 */
424 public static float mapCoordInSelfToDescendent(View descendant, View root,
425 int[] coord) {
426 ArrayList<View> ancestorChain = new ArrayList<View>();
427
428 float[] pt = {coord[0], coord[1]};
429
430 View v = descendant;
431 while(v != root) {
432 ancestorChain.add(v);
433 v = (View) v.getParent();
434 }
435 ancestorChain.add(root);
436
437 float scale = 1.0f;
438 Matrix inverse = new Matrix();
439 int count = ancestorChain.size();
440 for (int i = count - 1; i >= 0; i--) {
441 View ancestor = ancestorChain.get(i);
442 View next = i > 0 ? ancestorChain.get(i-1) : null;
443
444 pt[0] += ancestor.getScrollX();
445 pt[1] += ancestor.getScrollY();
446
447 if (next != null) {
448 pt[0] -= next.getLeft();
449 pt[1] -= next.getTop();
450 next.getMatrix().invert(inverse);
451 inverse.mapPoints(pt);
452 scale *= next.getScaleX();
453 }
454 }
455
456 coord[0] = (int) Math.round(pt[0]);
457 coord[1] = (int) Math.round(pt[1]);
458 return scale;
459 }
460
Jason Monk02dd7ae2014-04-15 15:23:31 -0400461 /**
462 * Utility method to determine whether the given point, in local coordinates,
463 * is inside the view, where the area of the view is expanded by the slop factor.
464 * This method is called while processing touch-move events to determine if the event
465 * is still within the view.
466 */
467 public static boolean pointInView(View v, float localX, float localY, float slop) {
468 return localX >= -slop && localY >= -slop && localX < (v.getWidth() + slop) &&
469 localY < (v.getHeight() + slop);
470 }
471
Tony Wickham1bce7fd2016-04-28 17:39:03 -0700472 /** Translates MotionEvents from src's coordinate system to dst's. */
473 public static void translateEventCoordinates(View src, View dst, MotionEvent dstEvent) {
474 toGlobalMotionEvent(src, dstEvent);
475 toLocalMotionEvent(dst, dstEvent);
476 }
477
478 /**
479 * Emulates View.toGlobalMotionEvent(). This implementation does not handle transformations
480 * (scaleX, scaleY, etc).
481 */
482 private static void toGlobalMotionEvent(View view, MotionEvent event) {
483 view.getLocationOnScreen(sLoc0);
484 event.offsetLocation(sLoc0[0], sLoc0[1]);
485 }
486
487 /**
488 * Emulates View.toLocalMotionEvent(). This implementation does not handle transformations
489 * (scaleX, scaleY, etc).
490 */
491 private static void toLocalMotionEvent(View view, MotionEvent event) {
492 view.getLocationOnScreen(sLoc0);
493 event.offsetLocation(-sLoc0[0], -sLoc0[1]);
494 }
495
Adam Cohen63f1ec02014-08-12 09:23:13 -0700496 public static int[] getCenterDeltaInScreenSpace(View v0, View v1, int[] delta) {
497 v0.getLocationInWindow(sLoc0);
498 v1.getLocationInWindow(sLoc1);
499
500 sLoc0[0] += (v0.getMeasuredWidth() * v0.getScaleX()) / 2;
501 sLoc0[1] += (v0.getMeasuredHeight() * v0.getScaleY()) / 2;
502 sLoc1[0] += (v1.getMeasuredWidth() * v1.getScaleX()) / 2;
503 sLoc1[1] += (v1.getMeasuredHeight() * v1.getScaleY()) / 2;
504
505 if (delta == null) {
506 delta = new int[2];
507 }
508
509 delta[0] = sLoc1[0] - sLoc0[0];
510 delta[1] = sLoc1[1] - sLoc0[1];
511
512 return delta;
513 }
514
Winson Chung3a6e7f32013-10-09 15:50:52 -0700515 public static void scaleRectAboutCenter(Rect r, float scale) {
Sunny Goyal106bf642015-07-16 12:18:06 -0700516 if (scale != 1.0f) {
517 int cx = r.centerX();
518 int cy = r.centerY();
519 r.offset(-cx, -cy);
520
521 r.left = (int) (r.left * scale + 0.5f);
522 r.top = (int) (r.top * scale + 0.5f);
523 r.right = (int) (r.right * scale + 0.5f);
524 r.bottom = (int) (r.bottom * scale + 0.5f);
525
526 r.offset(cx, cy);
527 }
Winson Chung3a6e7f32013-10-09 15:50:52 -0700528 }
529
Michael Jurkaa805e1a2013-08-22 15:00:33 +0200530 public static void startActivityForResultSafely(
531 Activity activity, Intent intent, int requestCode) {
532 try {
533 activity.startActivityForResult(intent, requestCode);
534 } catch (ActivityNotFoundException e) {
535 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
536 } catch (SecurityException e) {
537 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
538 Log.e(TAG, "Launcher does not have the permission to launch " + intent +
539 ". Make sure to create a MAIN intent-filter for the corresponding activity " +
540 "or use the exported attribute for this activity.", e);
541 }
542 }
Sunny Goyalc5c60ad2014-07-14 12:02:01 -0700543
544 static boolean isSystemApp(Context context, Intent intent) {
545 PackageManager pm = context.getPackageManager();
546 ComponentName cn = intent.getComponent();
547 String packageName = null;
548 if (cn == null) {
549 ResolveInfo info = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
550 if ((info != null) && (info.activityInfo != null)) {
551 packageName = info.activityInfo.packageName;
552 }
553 } else {
554 packageName = cn.getPackageName();
555 }
556 if (packageName != null) {
557 try {
558 PackageInfo info = pm.getPackageInfo(packageName, 0);
559 return (info != null) && (info.applicationInfo != null) &&
560 ((info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
561 } catch (NameNotFoundException e) {
562 return false;
563 }
564 } else {
565 return false;
566 }
567 }
Sunny Goyal95abbb32014-08-04 10:53:22 -0700568
569 /**
570 * This picks a dominant color, looking for high-saturation, high-value, repeated hues.
571 * @param bitmap The bitmap to scan
572 * @param samples The approximate max number of samples to use.
573 */
574 static int findDominantColorByHue(Bitmap bitmap, int samples) {
575 final int height = bitmap.getHeight();
576 final int width = bitmap.getWidth();
577 int sampleStride = (int) Math.sqrt((height * width) / samples);
578 if (sampleStride < 1) {
579 sampleStride = 1;
580 }
581
582 // This is an out-param, for getting the hsv values for an rgb
583 float[] hsv = new float[3];
584
585 // First get the best hue, by creating a histogram over 360 hue buckets,
586 // where each pixel contributes a score weighted by saturation, value, and alpha.
587 float[] hueScoreHistogram = new float[360];
588 float highScore = -1;
589 int bestHue = -1;
590
591 for (int y = 0; y < height; y += sampleStride) {
592 for (int x = 0; x < width; x += sampleStride) {
593 int argb = bitmap.getPixel(x, y);
594 int alpha = 0xFF & (argb >> 24);
595 if (alpha < 0x80) {
596 // Drop mostly-transparent pixels.
597 continue;
598 }
599 // Remove the alpha channel.
600 int rgb = argb | 0xFF000000;
601 Color.colorToHSV(rgb, hsv);
602 // Bucket colors by the 360 integer hues.
603 int hue = (int) hsv[0];
604 if (hue < 0 || hue >= hueScoreHistogram.length) {
605 // Defensively avoid array bounds violations.
606 continue;
607 }
608 float score = hsv[1] * hsv[2];
609 hueScoreHistogram[hue] += score;
610 if (hueScoreHistogram[hue] > highScore) {
611 highScore = hueScoreHistogram[hue];
612 bestHue = hue;
613 }
614 }
615 }
616
617 SparseArray<Float> rgbScores = new SparseArray<Float>();
618 int bestColor = 0xff000000;
619 highScore = -1;
620 // Go back over the RGB colors that match the winning hue,
621 // creating a histogram of weighted s*v scores, for up to 100*100 [s,v] buckets.
622 // The highest-scoring RGB color wins.
623 for (int y = 0; y < height; y += sampleStride) {
624 for (int x = 0; x < width; x += sampleStride) {
625 int rgb = bitmap.getPixel(x, y) | 0xff000000;
626 Color.colorToHSV(rgb, hsv);
627 int hue = (int) hsv[0];
628 if (hue == bestHue) {
629 float s = hsv[1];
630 float v = hsv[2];
631 int bucket = (int) (s * 100) + (int) (v * 10000);
632 // Score by cumulative saturation * value.
633 float score = s * v;
634 Float oldTotal = rgbScores.get(bucket);
635 float newTotal = oldTotal == null ? score : oldTotal + score;
636 rgbScores.put(bucket, newTotal);
637 if (newTotal > highScore) {
638 highScore = newTotal;
639 // All the colors in the winning bucket are very similar. Last in wins.
640 bestColor = rgb;
641 }
642 }
643 }
644 }
645 return bestColor;
646 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700647
648 /*
649 * Finds a system apk which had a broadcast receiver listening to a particular action.
650 * @param action intent action used to find the apk
651 * @return a pair of apk package name and the resources.
652 */
653 static Pair<String, Resources> findSystemApk(String action, PackageManager pm) {
654 final Intent intent = new Intent(action);
655 for (ResolveInfo info : pm.queryBroadcastReceivers(intent, 0)) {
656 if (info.activityInfo != null &&
657 (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
658 final String packageName = info.activityInfo.packageName;
659 try {
660 final Resources res = pm.getResourcesForApplication(packageName);
661 return Pair.create(packageName, res);
662 } catch (NameNotFoundException e) {
663 Log.w(TAG, "Failed to find resources for " + packageName);
664 }
665 }
666 }
667 return null;
668 }
Sunny Goyalfafca522014-11-03 11:30:01 -0800669
Sunny Goyal594d76d2014-11-06 10:12:54 -0800670 /**
Sunny Goyal5b0e6692015-03-19 14:31:19 -0700671 * Compresses the bitmap to a byte array for serialization.
672 */
673 public static byte[] flattenBitmap(Bitmap bitmap) {
674 // Try go guesstimate how much space the icon will take when serialized
675 // to avoid unnecessary allocations/copies during the write.
676 int size = bitmap.getWidth() * bitmap.getHeight() * 4;
677 ByteArrayOutputStream out = new ByteArrayOutputStream(size);
678 try {
679 bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
680 out.flush();
681 out.close();
682 return out.toByteArray();
683 } catch (IOException e) {
684 Log.w(TAG, "Could not write bitmap");
685 return null;
686 }
687 }
688
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700689 /**
Winson Chung82b016c2015-05-08 17:00:10 -0700690 * Trims the string, removing all whitespace at the beginning and end of the string.
691 * Non-breaking whitespaces are also removed.
692 */
693 public static String trim(CharSequence s) {
Winson Chungafa77e92015-05-15 12:04:03 -0700694 if (s == null) {
695 return null;
696 }
697
Winson Chung82b016c2015-05-08 17:00:10 -0700698 // Just strip any sequence of whitespace or java space characters from the beginning and end
699 Matcher m = sTrimPattern.matcher(s);
700 return m.replaceAll("$1");
701 }
Sunny Goyal70660032015-05-14 00:07:08 -0700702
Winson Chung2c6e5cc2015-06-01 14:38:24 -0700703 /**
704 * Calculates the height of a given string at a specific text size.
705 */
706 public static float calculateTextHeight(float textSizePx) {
707 Paint p = new Paint();
708 p.setTextSize(textSizePx);
709 Paint.FontMetrics fm = p.getFontMetrics();
710 return -fm.top + fm.bottom;
711 }
712
Winson Chungb1777442015-06-16 13:35:04 -0700713 /**
714 * Convenience println with multiple args.
715 */
716 public static void println(String key, Object... args) {
717 StringBuilder b = new StringBuilder();
718 b.append(key);
719 b.append(": ");
720 boolean isFirstArgument = true;
721 for (Object arg : args) {
722 if (isFirstArgument) {
723 isFirstArgument = false;
724 } else {
725 b.append(", ");
726 }
727 b.append(arg);
728 }
729 System.out.println(b.toString());
730 }
731
Sunny Goyal70660032015-05-14 00:07:08 -0700732 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
733 public static boolean isRtl(Resources res) {
Sunny Goyal9fc953b2015-08-17 12:24:25 -0700734 return ATLEAST_JB_MR1 &&
Sunny Goyal70660032015-05-14 00:07:08 -0700735 (res.getConfiguration().getLayoutDirection() == View.LAYOUT_DIRECTION_RTL);
736 }
Hyunyoung Song2bd3d7d2015-05-21 13:04:53 -0700737
Sunny Goyal5c97f512015-05-19 16:03:28 -0700738 /**
739 * Returns true if the intent is a valid launch intent for a launcher activity of an app.
740 * This is used to identify shortcuts which are different from the ones exposed by the
741 * applications' manifest file.
742 *
743 * @param launchIntent The intent that will be launched when the shortcut is clicked.
744 */
745 public static boolean isLauncherAppTarget(Intent launchIntent) {
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700746 if (launchIntent != null
Sunny Goyal5c97f512015-05-19 16:03:28 -0700747 && Intent.ACTION_MAIN.equals(launchIntent.getAction())
748 && launchIntent.getComponent() != null
749 && launchIntent.getCategories() != null
750 && launchIntent.getCategories().size() == 1
751 && launchIntent.hasCategory(Intent.CATEGORY_LAUNCHER)
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700752 && TextUtils.isEmpty(launchIntent.getDataString())) {
753 // An app target can either have no extra or have ItemInfo.EXTRA_PROFILE.
754 Bundle extras = launchIntent.getExtras();
755 if (extras == null) {
756 return true;
757 } else {
758 Set<String> keys = extras.keySet();
759 return keys.size() == 1 && keys.contains(ItemInfo.EXTRA_PROFILE);
760 }
761 };
762 return false;
Sunny Goyal5c97f512015-05-19 16:03:28 -0700763 }
Adam Cohen2e6da152015-05-06 11:42:25 -0700764
765 public static float dpiFromPx(int size, DisplayMetrics metrics){
766 float densityRatio = (float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT;
767 return (size / densityRatio);
768 }
769 public static int pxFromDp(float size, DisplayMetrics metrics) {
770 return (int) Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
771 size, metrics));
772 }
773 public static int pxFromSp(float size, DisplayMetrics metrics) {
774 return (int) Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
775 size, metrics));
776 }
Sunny Goyalb1622cc2015-06-10 16:00:42 -0700777
778 public static String createDbSelectionQuery(String columnName, Iterable<?> values) {
779 return String.format(Locale.ENGLISH, "%s IN (%s)", columnName, TextUtils.join(", ", values));
780 }
Sunny Goyal25aba0a2015-07-16 15:07:47 -0700781
Sunny Goyal25aba0a2015-07-16 15:07:47 -0700782 public static boolean isBootCompleted() {
783 try {
784 Class clazz = Class.forName("android.os.SystemProperties");
785 Method getter = clazz.getDeclaredMethod("get", String.class);
786 String value = (String) getter.invoke(null, "sys.boot_completed");
787 return "1".equals(value);
788 } catch (Exception e) {
789 Log.d(TAG, "Unable to read system properties");
790 // Assume that boot has completed
791 return true;
792 }
793 }
Tony Wickham29d853c2015-09-08 10:35:56 -0700794
795 /**
796 * Ensures that a value is within given bounds. Specifically:
797 * If value is less than lowerBound, return lowerBound; else if value is greater than upperBound,
798 * return upperBound; else return value unchanged.
799 */
Tony Wickhamf549dab2016-05-16 09:54:06 -0700800 public static int boundToRange(int value, int lowerBound, int upperBound) {
801 return Math.max(lowerBound, Math.min(value, upperBound));
802 }
803
804 /**
805 * @see #boundToRange(int, int, int).
806 */
807 public static float boundToRange(float value, float lowerBound, float upperBound) {
Tony Wickham29d853c2015-09-08 10:35:56 -0700808 return Math.max(lowerBound, Math.min(value, upperBound));
809 }
Sunny Goyal9d438082015-09-25 11:50:16 -0700810
Sunny Goyale78e3d72015-09-24 11:23:31 -0700811 /**
812 * Wraps a message with a TTS span, so that a different message is spoken than
813 * what is getting displayed.
814 * @param msg original message
815 * @param ttsMsg message to be spoken
816 */
817 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
818 public static CharSequence wrapForTts(CharSequence msg, String ttsMsg) {
819 if (Utilities.ATLEAST_LOLLIPOP) {
820 SpannableString spanned = new SpannableString(msg);
821 spanned.setSpan(new TtsSpan.TextBuilder(ttsMsg).build(),
822 0, spanned.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
823 return spanned;
824 } else {
825 return msg;
826 }
827 }
Winson12fb9fc2015-10-01 15:34:08 -0700828
829 /**
830 * Replacement for Long.compare() which was added in API level 19.
831 */
832 public static int longCompare(long lhs, long rhs) {
833 return lhs < rhs ? -1 : (lhs == rhs ? 0 : 1);
834 }
Sunny Goyalf7258242015-10-19 16:59:07 -0700835
836 public static SharedPreferences getPrefs(Context context) {
837 return context.getSharedPreferences(
838 LauncherFiles.SHARED_PREFERENCES_KEY, Context.MODE_PRIVATE);
839 }
Tony Wickham112ac952015-11-12 12:31:50 -0800840
841 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
842 public static boolean isPowerSaverOn(Context context) {
843 PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
844 return ATLEAST_LOLLIPOP && powerManager.isPowerSaveMode();
845 }
Sunny Goyale1483fb2016-01-08 12:16:15 -0800846
Sunny Goyal1ed6c4a2016-04-21 15:16:11 -0700847 public static boolean isWallapaperAllowed(Context context) {
848 if (isNycOrAbove()) {
849 try {
850 WallpaperManager wm = context.getSystemService(WallpaperManager.class);
Kenny Guy367da9f2016-05-25 19:22:14 +0100851 return (Boolean) wm.getClass().getDeclaredMethod("isSetWallpaperAllowed")
Sunny Goyal1ed6c4a2016-04-21 15:16:11 -0700852 .invoke(wm);
853 } catch (Exception e) { }
854 }
855 return true;
856 }
857
Sunny Goyal713edfc2016-05-06 09:58:34 -0700858 public static void closeSilently(Closeable c) {
859 if (c != null) {
860 try {
861 c.close();
862 } catch (IOException e) {
863 if (ProviderConfig.IS_DOGFOOD_BUILD) {
864 Log.d(TAG, "Error closing", e);
865 }
866 }
867 }
868 }
869
Sunny Goyale1483fb2016-01-08 12:16:15 -0800870 /**
Sunny Goyal3f732192016-05-13 13:48:44 -0700871 * Returns true if {@param original} contains all entries defined in {@param updates} and
872 * have the same value.
873 * The comparison uses {@link Object#equals(Object)} to compare the values.
874 */
875 public static boolean containsAll(Bundle original, Bundle updates) {
876 for (String key : updates.keySet()) {
877 Object value1 = updates.get(key);
878 Object value2 = original.get(key);
879 if (value1 == null) {
880 if (value2 != null) {
881 return false;
882 }
883 } else if (!value1.equals(value2)) {
884 return false;
885 }
886 }
887 return true;
888 }
889
Tony Wickham1bce7fd2016-04-28 17:39:03 -0700890 /** Returns whether the collection is null or empty. */
891 public static boolean isEmpty(Collection c) {
892 return c == null || c.isEmpty();
893 }
894
Sunny Goyal3f732192016-05-13 13:48:44 -0700895 /**
Sunny Goyale1483fb2016-01-08 12:16:15 -0800896 * An extension of {@link BitmapDrawable} which returns the bitmap pixel size as intrinsic size.
897 * This allows the badging to be done based on the action bitmap size rather than
898 * the scaled bitmap size.
899 */
900 private static class FixedSizeBitmapDrawable extends BitmapDrawable {
901
902 public FixedSizeBitmapDrawable(Bitmap bitmap) {
903 super(null, bitmap);
904 }
905
906 @Override
907 public int getIntrinsicHeight() {
908 return getBitmap().getWidth();
909 }
910
911 @Override
912 public int getIntrinsicWidth() {
913 return getBitmap().getWidth();
914 }
915 }
Andrew Sappersteinabef55a2016-06-19 12:49:00 -0700916
917 public static int getColorAccent(Context context) {
918 TypedArray ta = context.obtainStyledAttributes(new int[]{android.R.attr.colorAccent});
919 int colorAccent = ta.getColor(0, 0);
920 ta.recycle();
921 return colorAccent;
922 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800923}