Home | History | Annotate | Download | only in launcher3
      1 /*
      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 
     17 package com.android.launcher3;
     18 
     19 import android.annotation.TargetApi;
     20 import android.app.Activity;
     21 import android.app.SearchManager;
     22 import android.app.WallpaperManager;
     23 import android.appwidget.AppWidgetManager;
     24 import android.appwidget.AppWidgetProviderInfo;
     25 import android.content.ActivityNotFoundException;
     26 import android.content.ComponentName;
     27 import android.content.Context;
     28 import android.content.Intent;
     29 import android.content.SharedPreferences;
     30 import android.content.pm.ApplicationInfo;
     31 import android.content.pm.PackageInfo;
     32 import android.content.pm.PackageManager;
     33 import android.content.pm.PackageManager.NameNotFoundException;
     34 import android.content.pm.ResolveInfo;
     35 import android.content.res.Resources;
     36 import android.database.Cursor;
     37 import android.graphics.Bitmap;
     38 import android.graphics.BitmapFactory;
     39 import android.graphics.Canvas;
     40 import android.graphics.Color;
     41 import android.graphics.Matrix;
     42 import android.graphics.Paint;
     43 import android.graphics.PaintFlagsDrawFilter;
     44 import android.graphics.Rect;
     45 import android.graphics.drawable.BitmapDrawable;
     46 import android.graphics.drawable.Drawable;
     47 import android.graphics.drawable.PaintDrawable;
     48 import android.os.Build;
     49 import android.os.Bundle;
     50 import android.os.PowerManager;
     51 import android.os.Process;
     52 import android.text.Spannable;
     53 import android.text.SpannableString;
     54 import android.text.TextUtils;
     55 import android.text.style.TtsSpan;
     56 import android.util.DisplayMetrics;
     57 import android.util.Log;
     58 import android.util.Pair;
     59 import android.util.SparseArray;
     60 import android.util.TypedValue;
     61 import android.view.View;
     62 import android.widget.Toast;
     63 
     64 import com.android.launcher3.compat.UserHandleCompat;
     65 import com.android.launcher3.config.FeatureFlags;
     66 import com.android.launcher3.util.IconNormalizer;
     67 
     68 import java.io.ByteArrayOutputStream;
     69 import java.io.IOException;
     70 import java.util.ArrayList;
     71 import java.util.Locale;
     72 import java.util.Set;
     73 import java.util.concurrent.Executor;
     74 import java.util.concurrent.LinkedBlockingQueue;
     75 import java.util.concurrent.ThreadPoolExecutor;
     76 import java.util.concurrent.TimeUnit;
     77 import java.util.regex.Matcher;
     78 import java.util.regex.Pattern;
     79 
     80 /**
     81  * Various utilities shared amongst the Launcher's classes.
     82  */
     83 public final class Utilities {
     84 
     85     private static final String TAG = "Launcher.Utilities";
     86 
     87     private static final Rect sOldBounds = new Rect();
     88     private static final Canvas sCanvas = new Canvas();
     89 
     90     private static final Pattern sTrimPattern =
     91             Pattern.compile("^[\\s|\\p{javaSpaceChar}]*(.*)[\\s|\\p{javaSpaceChar}]*$");
     92 
     93     static {
     94         sCanvas.setDrawFilter(new PaintFlagsDrawFilter(Paint.DITHER_FLAG,
     95                 Paint.FILTER_BITMAP_FLAG));
     96     }
     97     static int sColors[] = { 0xffff0000, 0xff00ff00, 0xff0000ff };
     98     static int sColorIndex = 0;
     99 
    100     private static final int[] sLoc0 = new int[2];
    101     private static final int[] sLoc1 = new int[2];
    102 
    103     // TODO: use the full N name (e.g. ATLEAST_N*****) when available
    104     public static final boolean ATLEAST_N = Build.VERSION.SDK_INT >= Build.VERSION_CODES.N;
    105 
    106     public static final boolean ATLEAST_MARSHMALLOW =
    107             Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
    108 
    109     public static final boolean ATLEAST_LOLLIPOP_MR1 =
    110             Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1;
    111 
    112     public static final boolean ATLEAST_LOLLIPOP =
    113             Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
    114 
    115     public static final boolean ATLEAST_KITKAT =
    116             Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
    117 
    118     public static final boolean ATLEAST_JB_MR1 =
    119             Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1;
    120 
    121     public static final boolean ATLEAST_JB_MR2 =
    122             Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2;
    123 
    124     // These values are same as that in {@link AsyncTask}.
    125     private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
    126     private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
    127     private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
    128     private static final int KEEP_ALIVE = 1;
    129     /**
    130      * An {@link Executor} to be used with async task with no limit on the queue size.
    131      */
    132     public static final Executor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(
    133             CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
    134             TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
    135 
    136     public static final String ALLOW_ROTATION_PREFERENCE_KEY = "pref_allowRotation";
    137 
    138     public static boolean isPropertyEnabled(String propertyName) {
    139         return Log.isLoggable(propertyName, Log.VERBOSE);
    140     }
    141 
    142     public static boolean isAllowRotationPrefEnabled(Context context) {
    143         boolean allowRotationPref = false;
    144         if (ATLEAST_N) {
    145             // If the device was scaled, used the original dimensions to determine if rotation
    146             // is allowed of not.
    147             int originalDensity = DisplayMetrics.DENSITY_DEVICE_STABLE;
    148             Resources res = context.getResources();
    149             int originalSmallestWidth = res.getConfiguration().smallestScreenWidthDp
    150                     * res.getDisplayMetrics().densityDpi / originalDensity;
    151             allowRotationPref = originalSmallestWidth >= 600;
    152         }
    153         return getPrefs(context).getBoolean(ALLOW_ROTATION_PREFERENCE_KEY, allowRotationPref);
    154     }
    155 
    156     public static Bitmap createIconBitmap(Cursor c, int iconIndex, Context context) {
    157         byte[] data = c.getBlob(iconIndex);
    158         try {
    159             return createIconBitmap(BitmapFactory.decodeByteArray(data, 0, data.length), context);
    160         } catch (Exception e) {
    161             return null;
    162         }
    163     }
    164 
    165     /**
    166      * Returns a bitmap suitable for the all apps view. If the package or the resource do not
    167      * exist, it returns null.
    168      */
    169     public static Bitmap createIconBitmap(String packageName, String resourceName,
    170             Context context) {
    171         PackageManager packageManager = context.getPackageManager();
    172         // the resource
    173         try {
    174             Resources resources = packageManager.getResourcesForApplication(packageName);
    175             if (resources != null) {
    176                 final int id = resources.getIdentifier(resourceName, null, null);
    177                 return createIconBitmap(
    178                         resources.getDrawableForDensity(id, LauncherAppState.getInstance()
    179                                 .getInvariantDeviceProfile().fillResIconDpi), context);
    180             }
    181         } catch (Exception e) {
    182             // Icon not found.
    183         }
    184         return null;
    185     }
    186 
    187     private static int getIconBitmapSize() {
    188         return LauncherAppState.getInstance().getInvariantDeviceProfile().iconBitmapSize;
    189     }
    190 
    191     /**
    192      * Returns a bitmap which is of the appropriate size to be displayed as an icon
    193      */
    194     public static Bitmap createIconBitmap(Bitmap icon, Context context) {
    195         final int iconBitmapSize = getIconBitmapSize();
    196         if (iconBitmapSize == icon.getWidth() && iconBitmapSize == icon.getHeight()) {
    197             return icon;
    198         }
    199         return createIconBitmap(new BitmapDrawable(context.getResources(), icon), context);
    200     }
    201 
    202     /**
    203      * Returns a bitmap suitable for the all apps view. The icon is badged for {@param user}.
    204      * The bitmap is also visually normalized with other icons.
    205      */
    206     @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    207     public static Bitmap createBadgedIconBitmap(
    208             Drawable icon, UserHandleCompat user, Context context) {
    209         float scale = FeatureFlags.LAUNCHER3_ICON_NORMALIZATION ?
    210                 IconNormalizer.getInstance().getScale(icon) : 1;
    211         Bitmap bitmap = createIconBitmap(icon, context, scale);
    212         if (Utilities.ATLEAST_LOLLIPOP && user != null
    213                 && !UserHandleCompat.myUserHandle().equals(user)) {
    214             BitmapDrawable drawable = new FixedSizeBitmapDrawable(bitmap);
    215             Drawable badged = context.getPackageManager().getUserBadgedIcon(
    216                     drawable, user.getUser());
    217             if (badged instanceof BitmapDrawable) {
    218                 return ((BitmapDrawable) badged).getBitmap();
    219             } else {
    220                 return createIconBitmap(badged, context);
    221             }
    222         } else {
    223             return bitmap;
    224         }
    225     }
    226 
    227     /**
    228      * Returns a bitmap suitable for the all apps view.
    229      */
    230     public static Bitmap createIconBitmap(Drawable icon, Context context) {
    231         return createIconBitmap(icon, context, 1.0f /* scale */);
    232     }
    233 
    234     /**
    235      * @param scale the scale to apply before drawing {@param icon} on the canvas
    236      */
    237     public static Bitmap createIconBitmap(Drawable icon, Context context, float scale) {
    238         synchronized (sCanvas) {
    239             final int iconBitmapSize = getIconBitmapSize();
    240 
    241             int width = iconBitmapSize;
    242             int height = iconBitmapSize;
    243 
    244             if (icon instanceof PaintDrawable) {
    245                 PaintDrawable painter = (PaintDrawable) icon;
    246                 painter.setIntrinsicWidth(width);
    247                 painter.setIntrinsicHeight(height);
    248             } else if (icon instanceof BitmapDrawable) {
    249                 // Ensure the bitmap has a density.
    250                 BitmapDrawable bitmapDrawable = (BitmapDrawable) icon;
    251                 Bitmap bitmap = bitmapDrawable.getBitmap();
    252                 if (bitmap != null && bitmap.getDensity() == Bitmap.DENSITY_NONE) {
    253                     bitmapDrawable.setTargetDensity(context.getResources().getDisplayMetrics());
    254                 }
    255             }
    256             int sourceWidth = icon.getIntrinsicWidth();
    257             int sourceHeight = icon.getIntrinsicHeight();
    258             if (sourceWidth > 0 && sourceHeight > 0) {
    259                 // Scale the icon proportionally to the icon dimensions
    260                 final float ratio = (float) sourceWidth / sourceHeight;
    261                 if (sourceWidth > sourceHeight) {
    262                     height = (int) (width / ratio);
    263                 } else if (sourceHeight > sourceWidth) {
    264                     width = (int) (height * ratio);
    265                 }
    266             }
    267 
    268             // no intrinsic size --> use default size
    269             int textureWidth = iconBitmapSize;
    270             int textureHeight = iconBitmapSize;
    271 
    272             final Bitmap bitmap = Bitmap.createBitmap(textureWidth, textureHeight,
    273                     Bitmap.Config.ARGB_8888);
    274             final Canvas canvas = sCanvas;
    275             canvas.setBitmap(bitmap);
    276 
    277             final int left = (textureWidth-width) / 2;
    278             final int top = (textureHeight-height) / 2;
    279 
    280             @SuppressWarnings("all") // suppress dead code warning
    281             final boolean debug = false;
    282             if (debug) {
    283                 // draw a big box for the icon for debugging
    284                 canvas.drawColor(sColors[sColorIndex]);
    285                 if (++sColorIndex >= sColors.length) sColorIndex = 0;
    286                 Paint debugPaint = new Paint();
    287                 debugPaint.setColor(0xffcccc00);
    288                 canvas.drawRect(left, top, left+width, top+height, debugPaint);
    289             }
    290 
    291             sOldBounds.set(icon.getBounds());
    292             icon.setBounds(left, top, left+width, top+height);
    293             canvas.save(Canvas.MATRIX_SAVE_FLAG);
    294             canvas.scale(scale, scale, textureWidth / 2, textureHeight / 2);
    295             icon.draw(canvas);
    296             canvas.restore();
    297             icon.setBounds(sOldBounds);
    298             canvas.setBitmap(null);
    299 
    300             return bitmap;
    301         }
    302     }
    303 
    304     /**
    305      * Given a coordinate relative to the descendant, find the coordinate in a parent view's
    306      * coordinates.
    307      *
    308      * @param descendant The descendant to which the passed coordinate is relative.
    309      * @param root The root view to make the coordinates relative to.
    310      * @param coord The coordinate that we want mapped.
    311      * @param includeRootScroll Whether or not to account for the scroll of the descendant:
    312      *          sometimes this is relevant as in a child's coordinates within the descendant.
    313      * @return The factor by which this descendant is scaled relative to this DragLayer. Caution
    314      *         this scale factor is assumed to be equal in X and Y, and so if at any point this
    315      *         assumption fails, we will need to return a pair of scale factors.
    316      */
    317     public static float getDescendantCoordRelativeToParent(View descendant, View root,
    318                                                            int[] coord, boolean includeRootScroll) {
    319         ArrayList<View> ancestorChain = new ArrayList<View>();
    320 
    321         float[] pt = {coord[0], coord[1]};
    322 
    323         View v = descendant;
    324         while(v != root && v != null) {
    325             ancestorChain.add(v);
    326             v = (View) v.getParent();
    327         }
    328         ancestorChain.add(root);
    329 
    330         float scale = 1.0f;
    331         int count = ancestorChain.size();
    332         for (int i = 0; i < count; i++) {
    333             View v0 = ancestorChain.get(i);
    334             // For TextViews, scroll has a meaning which relates to the text position
    335             // which is very strange... ignore the scroll.
    336             if (v0 != descendant || includeRootScroll) {
    337                 pt[0] -= v0.getScrollX();
    338                 pt[1] -= v0.getScrollY();
    339             }
    340 
    341             v0.getMatrix().mapPoints(pt);
    342             pt[0] += v0.getLeft();
    343             pt[1] += v0.getTop();
    344             scale *= v0.getScaleX();
    345         }
    346 
    347         coord[0] = (int) Math.round(pt[0]);
    348         coord[1] = (int) Math.round(pt[1]);
    349         return scale;
    350     }
    351 
    352     /**
    353      * Inverse of {@link #getDescendantCoordRelativeToParent(View, View, int[], boolean)}.
    354      */
    355     public static float mapCoordInSelfToDescendent(View descendant, View root,
    356                                                    int[] coord) {
    357         ArrayList<View> ancestorChain = new ArrayList<View>();
    358 
    359         float[] pt = {coord[0], coord[1]};
    360 
    361         View v = descendant;
    362         while(v != root) {
    363             ancestorChain.add(v);
    364             v = (View) v.getParent();
    365         }
    366         ancestorChain.add(root);
    367 
    368         float scale = 1.0f;
    369         Matrix inverse = new Matrix();
    370         int count = ancestorChain.size();
    371         for (int i = count - 1; i >= 0; i--) {
    372             View ancestor = ancestorChain.get(i);
    373             View next = i > 0 ? ancestorChain.get(i-1) : null;
    374 
    375             pt[0] += ancestor.getScrollX();
    376             pt[1] += ancestor.getScrollY();
    377 
    378             if (next != null) {
    379                 pt[0] -= next.getLeft();
    380                 pt[1] -= next.getTop();
    381                 next.getMatrix().invert(inverse);
    382                 inverse.mapPoints(pt);
    383                 scale *= next.getScaleX();
    384             }
    385         }
    386 
    387         coord[0] = (int) Math.round(pt[0]);
    388         coord[1] = (int) Math.round(pt[1]);
    389         return scale;
    390     }
    391 
    392     /**
    393      * Utility method to determine whether the given point, in local coordinates,
    394      * is inside the view, where the area of the view is expanded by the slop factor.
    395      * This method is called while processing touch-move events to determine if the event
    396      * is still within the view.
    397      */
    398     public static boolean pointInView(View v, float localX, float localY, float slop) {
    399         return localX >= -slop && localY >= -slop && localX < (v.getWidth() + slop) &&
    400                 localY < (v.getHeight() + slop);
    401     }
    402 
    403     public static void scaleRect(Rect r, float scale) {
    404         if (scale != 1.0f) {
    405             r.left = (int) (r.left * scale + 0.5f);
    406             r.top = (int) (r.top * scale + 0.5f);
    407             r.right = (int) (r.right * scale + 0.5f);
    408             r.bottom = (int) (r.bottom * scale + 0.5f);
    409         }
    410     }
    411 
    412     public static int[] getCenterDeltaInScreenSpace(View v0, View v1, int[] delta) {
    413         v0.getLocationInWindow(sLoc0);
    414         v1.getLocationInWindow(sLoc1);
    415 
    416         sLoc0[0] += (v0.getMeasuredWidth() * v0.getScaleX()) / 2;
    417         sLoc0[1] += (v0.getMeasuredHeight() * v0.getScaleY()) / 2;
    418         sLoc1[0] += (v1.getMeasuredWidth() * v1.getScaleX()) / 2;
    419         sLoc1[1] += (v1.getMeasuredHeight() * v1.getScaleY()) / 2;
    420 
    421         if (delta == null) {
    422             delta = new int[2];
    423         }
    424 
    425         delta[0] = sLoc1[0] - sLoc0[0];
    426         delta[1] = sLoc1[1] - sLoc0[1];
    427 
    428         return delta;
    429     }
    430 
    431     public static void scaleRectAboutCenter(Rect r, float scale) {
    432         int cx = r.centerX();
    433         int cy = r.centerY();
    434         r.offset(-cx, -cy);
    435         Utilities.scaleRect(r, scale);
    436         r.offset(cx, cy);
    437     }
    438 
    439     public static void startActivityForResultSafely(
    440             Activity activity, Intent intent, int requestCode) {
    441         try {
    442             activity.startActivityForResult(intent, requestCode);
    443         } catch (ActivityNotFoundException e) {
    444             Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
    445         } catch (SecurityException e) {
    446             Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
    447             Log.e(TAG, "Launcher does not have the permission to launch " + intent +
    448                     ". Make sure to create a MAIN intent-filter for the corresponding activity " +
    449                     "or use the exported attribute for this activity.", e);
    450         }
    451     }
    452 
    453     static boolean isSystemApp(Context context, Intent intent) {
    454         PackageManager pm = context.getPackageManager();
    455         ComponentName cn = intent.getComponent();
    456         String packageName = null;
    457         if (cn == null) {
    458             ResolveInfo info = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
    459             if ((info != null) && (info.activityInfo != null)) {
    460                 packageName = info.activityInfo.packageName;
    461             }
    462         } else {
    463             packageName = cn.getPackageName();
    464         }
    465         if (packageName != null) {
    466             try {
    467                 PackageInfo info = pm.getPackageInfo(packageName, 0);
    468                 return (info != null) && (info.applicationInfo != null) &&
    469                         ((info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
    470             } catch (NameNotFoundException e) {
    471                 return false;
    472             }
    473         } else {
    474             return false;
    475         }
    476     }
    477 
    478     /**
    479      * This picks a dominant color, looking for high-saturation, high-value, repeated hues.
    480      * @param bitmap The bitmap to scan
    481      * @param samples The approximate max number of samples to use.
    482      */
    483     static int findDominantColorByHue(Bitmap bitmap, int samples) {
    484         final int height = bitmap.getHeight();
    485         final int width = bitmap.getWidth();
    486         int sampleStride = (int) Math.sqrt((height * width) / samples);
    487         if (sampleStride < 1) {
    488             sampleStride = 1;
    489         }
    490 
    491         // This is an out-param, for getting the hsv values for an rgb
    492         float[] hsv = new float[3];
    493 
    494         // First get the best hue, by creating a histogram over 360 hue buckets,
    495         // where each pixel contributes a score weighted by saturation, value, and alpha.
    496         float[] hueScoreHistogram = new float[360];
    497         float highScore = -1;
    498         int bestHue = -1;
    499 
    500         for (int y = 0; y < height; y += sampleStride) {
    501             for (int x = 0; x < width; x += sampleStride) {
    502                 int argb = bitmap.getPixel(x, y);
    503                 int alpha = 0xFF & (argb >> 24);
    504                 if (alpha < 0x80) {
    505                     // Drop mostly-transparent pixels.
    506                     continue;
    507                 }
    508                 // Remove the alpha channel.
    509                 int rgb = argb | 0xFF000000;
    510                 Color.colorToHSV(rgb, hsv);
    511                 // Bucket colors by the 360 integer hues.
    512                 int hue = (int) hsv[0];
    513                 if (hue < 0 || hue >= hueScoreHistogram.length) {
    514                     // Defensively avoid array bounds violations.
    515                     continue;
    516                 }
    517                 float score = hsv[1] * hsv[2];
    518                 hueScoreHistogram[hue] += score;
    519                 if (hueScoreHistogram[hue] > highScore) {
    520                     highScore = hueScoreHistogram[hue];
    521                     bestHue = hue;
    522                 }
    523             }
    524         }
    525 
    526         SparseArray<Float> rgbScores = new SparseArray<Float>();
    527         int bestColor = 0xff000000;
    528         highScore = -1;
    529         // Go back over the RGB colors that match the winning hue,
    530         // creating a histogram of weighted s*v scores, for up to 100*100 [s,v] buckets.
    531         // The highest-scoring RGB color wins.
    532         for (int y = 0; y < height; y += sampleStride) {
    533             for (int x = 0; x < width; x += sampleStride) {
    534                 int rgb = bitmap.getPixel(x, y) | 0xff000000;
    535                 Color.colorToHSV(rgb, hsv);
    536                 int hue = (int) hsv[0];
    537                 if (hue == bestHue) {
    538                     float s = hsv[1];
    539                     float v = hsv[2];
    540                     int bucket = (int) (s * 100) + (int) (v * 10000);
    541                     // Score by cumulative saturation * value.
    542                     float score = s * v;
    543                     Float oldTotal = rgbScores.get(bucket);
    544                     float newTotal = oldTotal == null ? score : oldTotal + score;
    545                     rgbScores.put(bucket, newTotal);
    546                     if (newTotal > highScore) {
    547                         highScore = newTotal;
    548                         // All the colors in the winning bucket are very similar. Last in wins.
    549                         bestColor = rgb;
    550                     }
    551                 }
    552             }
    553         }
    554         return bestColor;
    555     }
    556 
    557     /*
    558      * Finds a system apk which had a broadcast receiver listening to a particular action.
    559      * @param action intent action used to find the apk
    560      * @return a pair of apk package name and the resources.
    561      */
    562     static Pair<String, Resources> findSystemApk(String action, PackageManager pm) {
    563         final Intent intent = new Intent(action);
    564         for (ResolveInfo info : pm.queryBroadcastReceivers(intent, 0)) {
    565             if (info.activityInfo != null &&
    566                     (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
    567                 final String packageName = info.activityInfo.packageName;
    568                 try {
    569                     final Resources res = pm.getResourcesForApplication(packageName);
    570                     return Pair.create(packageName, res);
    571                 } catch (NameNotFoundException e) {
    572                     Log.w(TAG, "Failed to find resources for " + packageName);
    573                 }
    574             }
    575         }
    576         return null;
    577     }
    578 
    579     @TargetApi(Build.VERSION_CODES.KITKAT)
    580     public static boolean isViewAttachedToWindow(View v) {
    581         if (ATLEAST_KITKAT) {
    582             return v.isAttachedToWindow();
    583         } else {
    584             // A proxy call which returns null, if the view is not attached to the window.
    585             return v.getKeyDispatcherState() != null;
    586         }
    587     }
    588 
    589     /**
    590      * Returns a widget with category {@link AppWidgetProviderInfo#WIDGET_CATEGORY_SEARCHBOX}
    591      * provided by the same package which is set to be global search activity.
    592      * If widgetCategory is not supported, or no such widget is found, returns the first widget
    593      * provided by the package.
    594      */
    595     @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    596     public static AppWidgetProviderInfo getSearchWidgetProvider(Context context) {
    597         SearchManager searchManager =
    598                 (SearchManager) context.getSystemService(Context.SEARCH_SERVICE);
    599         ComponentName searchComponent = searchManager.getGlobalSearchActivity();
    600         if (searchComponent == null) return null;
    601         String providerPkg = searchComponent.getPackageName();
    602 
    603         AppWidgetProviderInfo defaultWidgetForSearchPackage = null;
    604 
    605         AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
    606         for (AppWidgetProviderInfo info : appWidgetManager.getInstalledProviders()) {
    607             if (info.provider.getPackageName().equals(providerPkg)) {
    608                 if (ATLEAST_JB_MR1) {
    609                     if ((info.widgetCategory & AppWidgetProviderInfo.WIDGET_CATEGORY_SEARCHBOX) != 0) {
    610                         return info;
    611                     } else if (defaultWidgetForSearchPackage == null) {
    612                         defaultWidgetForSearchPackage = info;
    613                     }
    614                 } else {
    615                     return info;
    616                 }
    617             }
    618         }
    619         return defaultWidgetForSearchPackage;
    620     }
    621 
    622     /**
    623      * Compresses the bitmap to a byte array for serialization.
    624      */
    625     public static byte[] flattenBitmap(Bitmap bitmap) {
    626         // Try go guesstimate how much space the icon will take when serialized
    627         // to avoid unnecessary allocations/copies during the write.
    628         int size = bitmap.getWidth() * bitmap.getHeight() * 4;
    629         ByteArrayOutputStream out = new ByteArrayOutputStream(size);
    630         try {
    631             bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
    632             out.flush();
    633             out.close();
    634             return out.toByteArray();
    635         } catch (IOException e) {
    636             Log.w(TAG, "Could not write bitmap");
    637             return null;
    638         }
    639     }
    640 
    641     /**
    642      * Find the first vacant cell, if there is one.
    643      *
    644      * @param vacant Holds the x and y coordinate of the vacant cell
    645      * @param spanX Horizontal cell span.
    646      * @param spanY Vertical cell span.
    647      *
    648      * @return true if a vacant cell was found
    649      */
    650     public static boolean findVacantCell(int[] vacant, int spanX, int spanY,
    651             int xCount, int yCount, boolean[][] occupied) {
    652 
    653         for (int y = 0; (y + spanY) <= yCount; y++) {
    654             for (int x = 0; (x + spanX) <= xCount; x++) {
    655                 boolean available = !occupied[x][y];
    656                 out:            for (int i = x; i < x + spanX; i++) {
    657                     for (int j = y; j < y + spanY; j++) {
    658                         available = available && !occupied[i][j];
    659                         if (!available) break out;
    660                     }
    661                 }
    662 
    663                 if (available) {
    664                     vacant[0] = x;
    665                     vacant[1] = y;
    666                     return true;
    667                 }
    668             }
    669         }
    670 
    671         return false;
    672     }
    673 
    674     /**
    675      * Trims the string, removing all whitespace at the beginning and end of the string.
    676      * Non-breaking whitespaces are also removed.
    677      */
    678     public static String trim(CharSequence s) {
    679         if (s == null) {
    680             return null;
    681         }
    682 
    683         // Just strip any sequence of whitespace or java space characters from the beginning and end
    684         Matcher m = sTrimPattern.matcher(s);
    685         return m.replaceAll("$1");
    686     }
    687 
    688     /**
    689      * Calculates the height of a given string at a specific text size.
    690      */
    691     public static float calculateTextHeight(float textSizePx) {
    692         Paint p = new Paint();
    693         p.setTextSize(textSizePx);
    694         Paint.FontMetrics fm = p.getFontMetrics();
    695         return -fm.top + fm.bottom;
    696     }
    697 
    698     /**
    699      * Convenience println with multiple args.
    700      */
    701     public static void println(String key, Object... args) {
    702         StringBuilder b = new StringBuilder();
    703         b.append(key);
    704         b.append(": ");
    705         boolean isFirstArgument = true;
    706         for (Object arg : args) {
    707             if (isFirstArgument) {
    708                 isFirstArgument = false;
    709             } else {
    710                 b.append(", ");
    711             }
    712             b.append(arg);
    713         }
    714         System.out.println(b.toString());
    715     }
    716 
    717     @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    718     public static boolean isRtl(Resources res) {
    719         return ATLEAST_JB_MR1 &&
    720                 (res.getConfiguration().getLayoutDirection() == View.LAYOUT_DIRECTION_RTL);
    721     }
    722 
    723     public static void assertWorkerThread() {
    724         if (LauncherAppState.isDogfoodBuild() &&
    725                 (LauncherModel.sWorkerThread.getThreadId() != Process.myTid())) {
    726             throw new IllegalStateException();
    727         }
    728     }
    729 
    730     /**
    731      * Returns true if the intent is a valid launch intent for a launcher activity of an app.
    732      * This is used to identify shortcuts which are different from the ones exposed by the
    733      * applications' manifest file.
    734      *
    735      * @param launchIntent The intent that will be launched when the shortcut is clicked.
    736      */
    737     public static boolean isLauncherAppTarget(Intent launchIntent) {
    738         if (launchIntent != null
    739                 && Intent.ACTION_MAIN.equals(launchIntent.getAction())
    740                 && launchIntent.getComponent() != null
    741                 && launchIntent.getCategories() != null
    742                 && launchIntent.getCategories().size() == 1
    743                 && launchIntent.hasCategory(Intent.CATEGORY_LAUNCHER)
    744                 && TextUtils.isEmpty(launchIntent.getDataString())) {
    745             // An app target can either have no extra or have ItemInfo.EXTRA_PROFILE.
    746             Bundle extras = launchIntent.getExtras();
    747             if (extras == null) {
    748                 return true;
    749             } else {
    750                 Set<String> keys = extras.keySet();
    751                 return keys.size() == 1 && keys.contains(ItemInfo.EXTRA_PROFILE);
    752             }
    753         };
    754         return false;
    755     }
    756 
    757     public static float dpiFromPx(int size, DisplayMetrics metrics){
    758         float densityRatio = (float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT;
    759         return (size / densityRatio);
    760     }
    761     public static int pxFromDp(float size, DisplayMetrics metrics) {
    762         return (int) Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
    763                 size, metrics));
    764     }
    765     public static int pxFromSp(float size, DisplayMetrics metrics) {
    766         return (int) Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
    767                 size, metrics));
    768     }
    769 
    770     public static String createDbSelectionQuery(String columnName, Iterable<?> values) {
    771         return String.format(Locale.ENGLISH, "%s IN (%s)", columnName, TextUtils.join(", ", values));
    772     }
    773 
    774     /**
    775      * Wraps a message with a TTS span, so that a different message is spoken than
    776      * what is getting displayed.
    777      * @param msg original message
    778      * @param ttsMsg message to be spoken
    779      */
    780     @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    781     public static CharSequence wrapForTts(CharSequence msg, String ttsMsg) {
    782         if (Utilities.ATLEAST_LOLLIPOP) {
    783             SpannableString spanned = new SpannableString(msg);
    784             spanned.setSpan(new TtsSpan.TextBuilder(ttsMsg).build(),
    785                     0, spanned.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
    786             return spanned;
    787         } else {
    788             return msg;
    789         }
    790     }
    791 
    792     /**
    793      * Replacement for Long.compare() which was added in API level 19.
    794      */
    795     public static int longCompare(long lhs, long rhs) {
    796         return lhs < rhs ? -1 : (lhs == rhs ? 0 : 1);
    797     }
    798 
    799     public static SharedPreferences getPrefs(Context context) {
    800         return context.getSharedPreferences(
    801                 LauncherFiles.SHARED_PREFERENCES_KEY, Context.MODE_PRIVATE);
    802     }
    803 
    804     @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    805     public static boolean isPowerSaverOn(Context context) {
    806         PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    807         return ATLEAST_LOLLIPOP && powerManager.isPowerSaveMode();
    808     }
    809 
    810     public static boolean isWallapaperAllowed(Context context) {
    811         if (ATLEAST_N) {
    812             return context.getSystemService(WallpaperManager.class).isSetWallpaperAllowed();
    813         }
    814         return true;
    815     }
    816 
    817     /**
    818      * An extension of {@link BitmapDrawable} which returns the bitmap pixel size as intrinsic size.
    819      * This allows the badging to be done based on the action bitmap size rather than
    820      * the scaled bitmap size.
    821      */
    822     private static class FixedSizeBitmapDrawable extends BitmapDrawable {
    823 
    824         public FixedSizeBitmapDrawable(Bitmap bitmap) {
    825             super(null, bitmap);
    826         }
    827 
    828         @Override
    829         public int getIntrinsicHeight() {
    830             return getBitmap().getWidth();
    831         }
    832 
    833         @Override
    834         public int getIntrinsicWidth() {
    835             return getBitmap().getWidth();
    836         }
    837     }
    838 }
    839