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.appwidget.AppWidgetManager;
     23 import android.appwidget.AppWidgetProviderInfo;
     24 import android.content.ActivityNotFoundException;
     25 import android.content.ComponentName;
     26 import android.content.Context;
     27 import android.content.Intent;
     28 import android.content.pm.ApplicationInfo;
     29 import android.content.pm.PackageInfo;
     30 import android.content.pm.PackageManager;
     31 import android.content.pm.PackageManager.NameNotFoundException;
     32 import android.content.pm.ResolveInfo;
     33 import android.content.res.Resources;
     34 import android.graphics.Bitmap;
     35 import android.graphics.Canvas;
     36 import android.graphics.Color;
     37 import android.graphics.Matrix;
     38 import android.graphics.Paint;
     39 import android.graphics.PaintFlagsDrawFilter;
     40 import android.graphics.Rect;
     41 import android.graphics.drawable.BitmapDrawable;
     42 import android.graphics.drawable.Drawable;
     43 import android.graphics.drawable.PaintDrawable;
     44 import android.os.Build;
     45 import android.util.Log;
     46 import android.util.Pair;
     47 import android.util.SparseArray;
     48 import android.view.View;
     49 import android.widget.Toast;
     50 
     51 import java.util.ArrayList;
     52 
     53 /**
     54  * Various utilities shared amongst the Launcher's classes.
     55  */
     56 public final class Utilities {
     57     private static final String TAG = "Launcher.Utilities";
     58 
     59     private static int sIconWidth = -1;
     60     private static int sIconHeight = -1;
     61 
     62     private static final Rect sOldBounds = new Rect();
     63     private static final Canvas sCanvas = new Canvas();
     64 
     65     static {
     66         sCanvas.setDrawFilter(new PaintFlagsDrawFilter(Paint.DITHER_FLAG,
     67                 Paint.FILTER_BITMAP_FLAG));
     68     }
     69     static int sColors[] = { 0xffff0000, 0xff00ff00, 0xff0000ff };
     70     static int sColorIndex = 0;
     71 
     72     static int[] sLoc0 = new int[2];
     73     static int[] sLoc1 = new int[2];
     74 
     75     // To turn on these properties, type
     76     // adb shell setprop log.tag.PROPERTY_NAME [VERBOSE | SUPPRESS]
     77     static final String FORCE_ENABLE_ROTATION_PROPERTY = "launcher_force_rotate";
     78     public static boolean sForceEnableRotation = isPropertyEnabled(FORCE_ENABLE_ROTATION_PROPERTY);
     79 
     80     /**
     81      * Returns a FastBitmapDrawable with the icon, accurately sized.
     82      */
     83     public static FastBitmapDrawable createIconDrawable(Bitmap icon) {
     84         FastBitmapDrawable d = new FastBitmapDrawable(icon);
     85         d.setFilterBitmap(true);
     86         resizeIconDrawable(d);
     87         return d;
     88     }
     89 
     90     /**
     91      * Resizes an icon drawable to the correct icon size.
     92      */
     93     static void resizeIconDrawable(Drawable icon) {
     94         icon.setBounds(0, 0, sIconWidth, sIconHeight);
     95     }
     96 
     97     public static boolean isPropertyEnabled(String propertyName) {
     98         return Log.isLoggable(propertyName, Log.VERBOSE);
     99     }
    100 
    101     public static boolean isRotationEnabled(Context c) {
    102         boolean enableRotation = sForceEnableRotation ||
    103                 c.getResources().getBoolean(R.bool.allow_rotation);
    104         return enableRotation;
    105     }
    106 
    107     /**
    108      * Indicates if the device is running LMP or higher.
    109      */
    110     public static boolean isLmpOrAbove() {
    111         return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
    112     }
    113 
    114     /**
    115      * Returns a bitmap suitable for the all apps view. If the package or the resource do not
    116      * exist, it returns null.
    117      */
    118     static Bitmap createIconBitmap(String packageName, String resourceName, IconCache cache,
    119             Context context) {
    120         PackageManager packageManager = context.getPackageManager();
    121         // the resource
    122         try {
    123             Resources resources = packageManager.getResourcesForApplication(packageName);
    124             if (resources != null) {
    125                 final int id = resources.getIdentifier(resourceName, null, null);
    126                 return createIconBitmap(
    127                         resources.getDrawableForDensity(id, cache.getFullResIconDpi()), context);
    128             }
    129         } catch (Exception e) {
    130             // Icon not found.
    131         }
    132         return null;
    133     }
    134 
    135     /**
    136      * Returns a bitmap which is of the appropriate size to be displayed as an icon
    137      */
    138     static Bitmap createIconBitmap(Bitmap icon, Context context) {
    139         synchronized (sCanvas) { // we share the statics :-(
    140             if (sIconWidth == -1) {
    141                 initStatics(context);
    142             }
    143         }
    144         if (sIconWidth == icon.getWidth() && sIconHeight == icon.getHeight()) {
    145             return icon;
    146         }
    147         return createIconBitmap(new BitmapDrawable(context.getResources(), icon), context);
    148     }
    149 
    150     /**
    151      * Returns a bitmap suitable for the all apps view.
    152      */
    153     public static Bitmap createIconBitmap(Drawable icon, Context context) {
    154         synchronized (sCanvas) { // we share the statics :-(
    155             if (sIconWidth == -1) {
    156                 initStatics(context);
    157             }
    158 
    159             int width = sIconWidth;
    160             int height = sIconHeight;
    161 
    162             if (icon instanceof PaintDrawable) {
    163                 PaintDrawable painter = (PaintDrawable) icon;
    164                 painter.setIntrinsicWidth(width);
    165                 painter.setIntrinsicHeight(height);
    166             } else if (icon instanceof BitmapDrawable) {
    167                 // Ensure the bitmap has a density.
    168                 BitmapDrawable bitmapDrawable = (BitmapDrawable) icon;
    169                 Bitmap bitmap = bitmapDrawable.getBitmap();
    170                 if (bitmap.getDensity() == Bitmap.DENSITY_NONE) {
    171                     bitmapDrawable.setTargetDensity(context.getResources().getDisplayMetrics());
    172                 }
    173             }
    174             int sourceWidth = icon.getIntrinsicWidth();
    175             int sourceHeight = icon.getIntrinsicHeight();
    176             if (sourceWidth > 0 && sourceHeight > 0) {
    177                 // Scale the icon proportionally to the icon dimensions
    178                 final float ratio = (float) sourceWidth / sourceHeight;
    179                 if (sourceWidth > sourceHeight) {
    180                     height = (int) (width / ratio);
    181                 } else if (sourceHeight > sourceWidth) {
    182                     width = (int) (height * ratio);
    183                 }
    184             }
    185 
    186             // no intrinsic size --> use default size
    187             int textureWidth = sIconWidth;
    188             int textureHeight = sIconHeight;
    189 
    190             final Bitmap bitmap = Bitmap.createBitmap(textureWidth, textureHeight,
    191                     Bitmap.Config.ARGB_8888);
    192             final Canvas canvas = sCanvas;
    193             canvas.setBitmap(bitmap);
    194 
    195             final int left = (textureWidth-width) / 2;
    196             final int top = (textureHeight-height) / 2;
    197 
    198             @SuppressWarnings("all") // suppress dead code warning
    199             final boolean debug = false;
    200             if (debug) {
    201                 // draw a big box for the icon for debugging
    202                 canvas.drawColor(sColors[sColorIndex]);
    203                 if (++sColorIndex >= sColors.length) sColorIndex = 0;
    204                 Paint debugPaint = new Paint();
    205                 debugPaint.setColor(0xffcccc00);
    206                 canvas.drawRect(left, top, left+width, top+height, debugPaint);
    207             }
    208 
    209             sOldBounds.set(icon.getBounds());
    210             icon.setBounds(left, top, left+width, top+height);
    211             icon.draw(canvas);
    212             icon.setBounds(sOldBounds);
    213             canvas.setBitmap(null);
    214 
    215             return bitmap;
    216         }
    217     }
    218 
    219     /**
    220      * Given a coordinate relative to the descendant, find the coordinate in a parent view's
    221      * coordinates.
    222      *
    223      * @param descendant The descendant to which the passed coordinate is relative.
    224      * @param root The root view to make the coordinates relative to.
    225      * @param coord The coordinate that we want mapped.
    226      * @param includeRootScroll Whether or not to account for the scroll of the descendant:
    227      *          sometimes this is relevant as in a child's coordinates within the descendant.
    228      * @return The factor by which this descendant is scaled relative to this DragLayer. Caution
    229      *         this scale factor is assumed to be equal in X and Y, and so if at any point this
    230      *         assumption fails, we will need to return a pair of scale factors.
    231      */
    232     public static float getDescendantCoordRelativeToParent(View descendant, View root,
    233                                                            int[] coord, boolean includeRootScroll) {
    234         ArrayList<View> ancestorChain = new ArrayList<View>();
    235 
    236         float[] pt = {coord[0], coord[1]};
    237 
    238         View v = descendant;
    239         while(v != root && v != null) {
    240             ancestorChain.add(v);
    241             v = (View) v.getParent();
    242         }
    243         ancestorChain.add(root);
    244 
    245         float scale = 1.0f;
    246         int count = ancestorChain.size();
    247         for (int i = 0; i < count; i++) {
    248             View v0 = ancestorChain.get(i);
    249             // For TextViews, scroll has a meaning which relates to the text position
    250             // which is very strange... ignore the scroll.
    251             if (v0 != descendant || includeRootScroll) {
    252                 pt[0] -= v0.getScrollX();
    253                 pt[1] -= v0.getScrollY();
    254             }
    255 
    256             v0.getMatrix().mapPoints(pt);
    257             pt[0] += v0.getLeft();
    258             pt[1] += v0.getTop();
    259             scale *= v0.getScaleX();
    260         }
    261 
    262         coord[0] = (int) Math.round(pt[0]);
    263         coord[1] = (int) Math.round(pt[1]);
    264         return scale;
    265     }
    266 
    267     /**
    268      * Inverse of {@link #getDescendantCoordRelativeToSelf(View, int[])}.
    269      */
    270     public static float mapCoordInSelfToDescendent(View descendant, View root,
    271                                                    int[] coord) {
    272         ArrayList<View> ancestorChain = new ArrayList<View>();
    273 
    274         float[] pt = {coord[0], coord[1]};
    275 
    276         View v = descendant;
    277         while(v != root) {
    278             ancestorChain.add(v);
    279             v = (View) v.getParent();
    280         }
    281         ancestorChain.add(root);
    282 
    283         float scale = 1.0f;
    284         Matrix inverse = new Matrix();
    285         int count = ancestorChain.size();
    286         for (int i = count - 1; i >= 0; i--) {
    287             View ancestor = ancestorChain.get(i);
    288             View next = i > 0 ? ancestorChain.get(i-1) : null;
    289 
    290             pt[0] += ancestor.getScrollX();
    291             pt[1] += ancestor.getScrollY();
    292 
    293             if (next != null) {
    294                 pt[0] -= next.getLeft();
    295                 pt[1] -= next.getTop();
    296                 next.getMatrix().invert(inverse);
    297                 inverse.mapPoints(pt);
    298                 scale *= next.getScaleX();
    299             }
    300         }
    301 
    302         coord[0] = (int) Math.round(pt[0]);
    303         coord[1] = (int) Math.round(pt[1]);
    304         return scale;
    305     }
    306 
    307     /**
    308      * Utility method to determine whether the given point, in local coordinates,
    309      * is inside the view, where the area of the view is expanded by the slop factor.
    310      * This method is called while processing touch-move events to determine if the event
    311      * is still within the view.
    312      */
    313     public static boolean pointInView(View v, float localX, float localY, float slop) {
    314         return localX >= -slop && localY >= -slop && localX < (v.getWidth() + slop) &&
    315                 localY < (v.getHeight() + slop);
    316     }
    317 
    318     private static void initStatics(Context context) {
    319         final Resources resources = context.getResources();
    320         sIconWidth = sIconHeight = (int) resources.getDimension(R.dimen.app_icon_size);
    321     }
    322 
    323     public static void setIconSize(int widthPx) {
    324         sIconWidth = sIconHeight = widthPx;
    325     }
    326 
    327     public static void scaleRect(Rect r, float scale) {
    328         if (scale != 1.0f) {
    329             r.left = (int) (r.left * scale + 0.5f);
    330             r.top = (int) (r.top * scale + 0.5f);
    331             r.right = (int) (r.right * scale + 0.5f);
    332             r.bottom = (int) (r.bottom * scale + 0.5f);
    333         }
    334     }
    335 
    336     public static int[] getCenterDeltaInScreenSpace(View v0, View v1, int[] delta) {
    337         v0.getLocationInWindow(sLoc0);
    338         v1.getLocationInWindow(sLoc1);
    339 
    340         sLoc0[0] += (v0.getMeasuredWidth() * v0.getScaleX()) / 2;
    341         sLoc0[1] += (v0.getMeasuredHeight() * v0.getScaleY()) / 2;
    342         sLoc1[0] += (v1.getMeasuredWidth() * v1.getScaleX()) / 2;
    343         sLoc1[1] += (v1.getMeasuredHeight() * v1.getScaleY()) / 2;
    344 
    345         if (delta == null) {
    346             delta = new int[2];
    347         }
    348 
    349         delta[0] = sLoc1[0] - sLoc0[0];
    350         delta[1] = sLoc1[1] - sLoc0[1];
    351 
    352         return delta;
    353     }
    354 
    355     public static void scaleRectAboutCenter(Rect r, float scale) {
    356         int cx = r.centerX();
    357         int cy = r.centerY();
    358         r.offset(-cx, -cy);
    359         Utilities.scaleRect(r, scale);
    360         r.offset(cx, cy);
    361     }
    362 
    363     public static void startActivityForResultSafely(
    364             Activity activity, Intent intent, int requestCode) {
    365         try {
    366             activity.startActivityForResult(intent, requestCode);
    367         } catch (ActivityNotFoundException e) {
    368             Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
    369         } catch (SecurityException e) {
    370             Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
    371             Log.e(TAG, "Launcher does not have the permission to launch " + intent +
    372                     ". Make sure to create a MAIN intent-filter for the corresponding activity " +
    373                     "or use the exported attribute for this activity.", e);
    374         }
    375     }
    376 
    377     static boolean isSystemApp(Context context, Intent intent) {
    378         PackageManager pm = context.getPackageManager();
    379         ComponentName cn = intent.getComponent();
    380         String packageName = null;
    381         if (cn == null) {
    382             ResolveInfo info = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
    383             if ((info != null) && (info.activityInfo != null)) {
    384                 packageName = info.activityInfo.packageName;
    385             }
    386         } else {
    387             packageName = cn.getPackageName();
    388         }
    389         if (packageName != null) {
    390             try {
    391                 PackageInfo info = pm.getPackageInfo(packageName, 0);
    392                 return (info != null) && (info.applicationInfo != null) &&
    393                         ((info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
    394             } catch (NameNotFoundException e) {
    395                 return false;
    396             }
    397         } else {
    398             return false;
    399         }
    400     }
    401 
    402     /**
    403      * This picks a dominant color, looking for high-saturation, high-value, repeated hues.
    404      * @param bitmap The bitmap to scan
    405      * @param samples The approximate max number of samples to use.
    406      */
    407     static int findDominantColorByHue(Bitmap bitmap, int samples) {
    408         final int height = bitmap.getHeight();
    409         final int width = bitmap.getWidth();
    410         int sampleStride = (int) Math.sqrt((height * width) / samples);
    411         if (sampleStride < 1) {
    412             sampleStride = 1;
    413         }
    414 
    415         // This is an out-param, for getting the hsv values for an rgb
    416         float[] hsv = new float[3];
    417 
    418         // First get the best hue, by creating a histogram over 360 hue buckets,
    419         // where each pixel contributes a score weighted by saturation, value, and alpha.
    420         float[] hueScoreHistogram = new float[360];
    421         float highScore = -1;
    422         int bestHue = -1;
    423 
    424         for (int y = 0; y < height; y += sampleStride) {
    425             for (int x = 0; x < width; x += sampleStride) {
    426                 int argb = bitmap.getPixel(x, y);
    427                 int alpha = 0xFF & (argb >> 24);
    428                 if (alpha < 0x80) {
    429                     // Drop mostly-transparent pixels.
    430                     continue;
    431                 }
    432                 // Remove the alpha channel.
    433                 int rgb = argb | 0xFF000000;
    434                 Color.colorToHSV(rgb, hsv);
    435                 // Bucket colors by the 360 integer hues.
    436                 int hue = (int) hsv[0];
    437                 if (hue < 0 || hue >= hueScoreHistogram.length) {
    438                     // Defensively avoid array bounds violations.
    439                     continue;
    440                 }
    441                 float score = hsv[1] * hsv[2];
    442                 hueScoreHistogram[hue] += score;
    443                 if (hueScoreHistogram[hue] > highScore) {
    444                     highScore = hueScoreHistogram[hue];
    445                     bestHue = hue;
    446                 }
    447             }
    448         }
    449 
    450         SparseArray<Float> rgbScores = new SparseArray<Float>();
    451         int bestColor = 0xff000000;
    452         highScore = -1;
    453         // Go back over the RGB colors that match the winning hue,
    454         // creating a histogram of weighted s*v scores, for up to 100*100 [s,v] buckets.
    455         // The highest-scoring RGB color wins.
    456         for (int y = 0; y < height; y += sampleStride) {
    457             for (int x = 0; x < width; x += sampleStride) {
    458                 int rgb = bitmap.getPixel(x, y) | 0xff000000;
    459                 Color.colorToHSV(rgb, hsv);
    460                 int hue = (int) hsv[0];
    461                 if (hue == bestHue) {
    462                     float s = hsv[1];
    463                     float v = hsv[2];
    464                     int bucket = (int) (s * 100) + (int) (v * 10000);
    465                     // Score by cumulative saturation * value.
    466                     float score = s * v;
    467                     Float oldTotal = rgbScores.get(bucket);
    468                     float newTotal = oldTotal == null ? score : oldTotal + score;
    469                     rgbScores.put(bucket, newTotal);
    470                     if (newTotal > highScore) {
    471                         highScore = newTotal;
    472                         // All the colors in the winning bucket are very similar. Last in wins.
    473                         bestColor = rgb;
    474                     }
    475                 }
    476             }
    477         }
    478         return bestColor;
    479     }
    480 
    481     /*
    482      * Finds a system apk which had a broadcast receiver listening to a particular action.
    483      * @param action intent action used to find the apk
    484      * @return a pair of apk package name and the resources.
    485      */
    486     static Pair<String, Resources> findSystemApk(String action, PackageManager pm) {
    487         final Intent intent = new Intent(action);
    488         for (ResolveInfo info : pm.queryBroadcastReceivers(intent, 0)) {
    489             if (info.activityInfo != null &&
    490                     (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
    491                 final String packageName = info.activityInfo.packageName;
    492                 try {
    493                     final Resources res = pm.getResourcesForApplication(packageName);
    494                     return Pair.create(packageName, res);
    495                 } catch (NameNotFoundException e) {
    496                     Log.w(TAG, "Failed to find resources for " + packageName);
    497                 }
    498             }
    499         }
    500         return null;
    501     }
    502 
    503     @TargetApi(Build.VERSION_CODES.KITKAT)
    504     public static boolean isViewAttachedToWindow(View v) {
    505         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    506             return v.isAttachedToWindow();
    507         } else {
    508             // A proxy call which returns null, if the view is not attached to the window.
    509             return v.getKeyDispatcherState() != null;
    510         }
    511     }
    512 
    513     /**
    514      * Returns a widget with category {@link AppWidgetProviderInfo#WIDGET_CATEGORY_SEARCHBOX}
    515      * provided by the same package which is set to be global search activity.
    516      * If widgetCategory is not supported, or no such widget is found, returns the first widget
    517      * provided by the package.
    518      */
    519     @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    520     public static AppWidgetProviderInfo getSearchWidgetProvider(Context context) {
    521         SearchManager searchManager =
    522                 (SearchManager) context.getSystemService(Context.SEARCH_SERVICE);
    523         ComponentName searchComponent = searchManager.getGlobalSearchActivity();
    524         if (searchComponent == null) return null;
    525         String providerPkg = searchComponent.getPackageName();
    526 
    527         AppWidgetProviderInfo defaultWidgetForSearchPackage = null;
    528 
    529         AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
    530         for (AppWidgetProviderInfo info : appWidgetManager.getInstalledProviders()) {
    531             if (info.provider.getPackageName().equals(providerPkg)) {
    532                 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
    533                     if ((info.widgetCategory & AppWidgetProviderInfo.WIDGET_CATEGORY_SEARCHBOX) != 0) {
    534                         return info;
    535                     } else if (defaultWidgetForSearchPackage == null) {
    536                         defaultWidgetForSearchPackage = info;
    537                     }
    538                 } else {
    539                     return info;
    540                 }
    541             }
    542         }
    543         return defaultWidgetForSearchPackage;
    544     }
    545 }
    546