Home | History | Annotate | Download | only in view
      1 /*
      2  * Copyright (C) 2011 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 android.view;
     18 
     19 import android.annotation.NonNull;
     20 import android.annotation.XmlRes;
     21 import android.content.Context;
     22 import android.content.res.Resources;
     23 import android.content.res.TypedArray;
     24 import android.content.res.XmlResourceParser;
     25 import android.graphics.Bitmap;
     26 import android.graphics.Canvas;
     27 import android.graphics.Paint;
     28 import android.graphics.Rect;
     29 import android.graphics.RectF;
     30 import android.graphics.drawable.AnimationDrawable;
     31 import android.graphics.drawable.BitmapDrawable;
     32 import android.graphics.drawable.Drawable;
     33 import android.os.Parcel;
     34 import android.os.Parcelable;
     35 import android.util.Log;
     36 import android.util.SparseArray;
     37 
     38 import com.android.internal.util.XmlUtils;
     39 
     40 /**
     41  * Represents an icon that can be used as a mouse pointer.
     42  * <p>
     43  * Pointer icons can be provided either by the system using system types,
     44  * or by applications using bitmaps or application resources.
     45  * </p>
     46  */
     47 public final class PointerIcon implements Parcelable {
     48     private static final String TAG = "PointerIcon";
     49 
     50     /** {@hide} Type constant: Custom icon with a user-supplied bitmap. */
     51     public static final int TYPE_CUSTOM = -1;
     52 
     53     /** Type constant: Null icon.  It has no bitmap. */
     54     public static final int TYPE_NULL = 0;
     55 
     56     /** Type constant: no icons are specified. If all views uses this, then falls back
     57      * to the default type, but this is helpful to distinguish a view explicitly want
     58      * to have the default icon.
     59      * @hide
     60      */
     61     public static final int TYPE_NOT_SPECIFIED = 1;
     62 
     63     /** Type constant: Arrow icon.  (Default mouse pointer) */
     64     public static final int TYPE_ARROW = 1000;
     65 
     66     /** {@hide} Type constant: Spot hover icon for touchpads. */
     67     public static final int TYPE_SPOT_HOVER = 2000;
     68 
     69     /** {@hide} Type constant: Spot touch icon for touchpads. */
     70     public static final int TYPE_SPOT_TOUCH = 2001;
     71 
     72     /** {@hide} Type constant: Spot anchor icon for touchpads. */
     73     public static final int TYPE_SPOT_ANCHOR = 2002;
     74 
     75     // Type constants for additional predefined icons for mice.
     76     /** Type constant: context-menu. */
     77     public static final int TYPE_CONTEXT_MENU = 1001;
     78 
     79     /** Type constant: hand. */
     80     public static final int TYPE_HAND = 1002;
     81 
     82     /** Type constant: help. */
     83     public static final int TYPE_HELP = 1003;
     84 
     85     /** Type constant: wait. */
     86     public static final int TYPE_WAIT = 1004;
     87 
     88     /** Type constant: cell. */
     89     public static final int TYPE_CELL = 1006;
     90 
     91     /** Type constant: crosshair. */
     92     public static final int TYPE_CROSSHAIR = 1007;
     93 
     94     /** Type constant: text. */
     95     public static final int TYPE_TEXT = 1008;
     96 
     97     /** Type constant: vertical-text. */
     98     public static final int TYPE_VERTICAL_TEXT = 1009;
     99 
    100     /** Type constant: alias (indicating an alias of/shortcut to something is
    101       * to be created. */
    102     public static final int TYPE_ALIAS = 1010;
    103 
    104     /** Type constant: copy. */
    105     public static final int TYPE_COPY = 1011;
    106 
    107     /** Type constant: no-drop. */
    108     public static final int TYPE_NO_DROP = 1012;
    109 
    110     /** Type constant: all-scroll. */
    111     public static final int TYPE_ALL_SCROLL = 1013;
    112 
    113     /** Type constant: horizontal double arrow mainly for resizing. */
    114     public static final int TYPE_HORIZONTAL_DOUBLE_ARROW = 1014;
    115 
    116     /** Type constant: vertical double arrow mainly for resizing. */
    117     public static final int TYPE_VERTICAL_DOUBLE_ARROW = 1015;
    118 
    119     /** Type constant: diagonal double arrow -- top-right to bottom-left. */
    120     public static final int TYPE_TOP_RIGHT_DIAGONAL_DOUBLE_ARROW = 1016;
    121 
    122     /** Type constant: diagonal double arrow -- top-left to bottom-right. */
    123     public static final int TYPE_TOP_LEFT_DIAGONAL_DOUBLE_ARROW = 1017;
    124 
    125     /** Type constant: zoom-in. */
    126     public static final int TYPE_ZOOM_IN = 1018;
    127 
    128     /** Type constant: zoom-out. */
    129     public static final int TYPE_ZOOM_OUT = 1019;
    130 
    131     /** Type constant: grab. */
    132     public static final int TYPE_GRAB = 1020;
    133 
    134     /** Type constant: grabbing. */
    135     public static final int TYPE_GRABBING = 1021;
    136 
    137     // OEM private types should be defined starting at this range to avoid
    138     // conflicts with any system types that may be defined in the future.
    139     private static final int TYPE_OEM_FIRST = 10000;
    140 
    141     /** The default pointer icon. */
    142     public static final int TYPE_DEFAULT = TYPE_ARROW;
    143 
    144     private static final PointerIcon gNullIcon = new PointerIcon(TYPE_NULL);
    145     private static final SparseArray<PointerIcon> gSystemIcons = new SparseArray<PointerIcon>();
    146     private static boolean sUseLargeIcons = false;
    147 
    148     private final int mType;
    149     private int mSystemIconResourceId;
    150     private Bitmap mBitmap;
    151     private float mHotSpotX;
    152     private float mHotSpotY;
    153     // The bitmaps for the additional frame of animated pointer icon. Note that the first frame
    154     // will be stored in mBitmap.
    155     private Bitmap mBitmapFrames[];
    156     private int mDurationPerFrame;
    157 
    158     private PointerIcon(int type) {
    159         mType = type;
    160     }
    161 
    162     /**
    163      * Gets a special pointer icon that has no bitmap.
    164      *
    165      * @return The null pointer icon.
    166      *
    167      * @see #TYPE_NULL
    168      * @hide
    169      */
    170     public static PointerIcon getNullIcon() {
    171         return gNullIcon;
    172     }
    173 
    174     /**
    175      * Gets the default pointer icon.
    176      *
    177      * @param context The context.
    178      * @return The default pointer icon.
    179      *
    180      * @throws IllegalArgumentException if context is null.
    181      * @hide
    182      */
    183     public static PointerIcon getDefaultIcon(@NonNull Context context) {
    184         return getSystemIcon(context, TYPE_DEFAULT);
    185     }
    186 
    187     /**
    188      * Gets a system pointer icon for the given type.
    189      * If typeis not recognized, returns the default pointer icon.
    190      *
    191      * @param context The context.
    192      * @param type The pointer icon type.
    193      * @return The pointer icon.
    194      *
    195      * @throws IllegalArgumentException if context is null.
    196      */
    197     public static PointerIcon getSystemIcon(@NonNull Context context, int type) {
    198         if (context == null) {
    199             throw new IllegalArgumentException("context must not be null");
    200         }
    201 
    202         if (type == TYPE_NULL) {
    203             return gNullIcon;
    204         }
    205 
    206         PointerIcon icon = gSystemIcons.get(type);
    207         if (icon != null) {
    208             return icon;
    209         }
    210 
    211         int typeIndex = getSystemIconTypeIndex(type);
    212         if (typeIndex == 0) {
    213             typeIndex = getSystemIconTypeIndex(TYPE_DEFAULT);
    214         }
    215 
    216         int defStyle = sUseLargeIcons ?
    217                 com.android.internal.R.style.LargePointer : com.android.internal.R.style.Pointer;
    218         TypedArray a = context.obtainStyledAttributes(null,
    219                 com.android.internal.R.styleable.Pointer,
    220                 0, defStyle);
    221         int resourceId = a.getResourceId(typeIndex, -1);
    222         a.recycle();
    223 
    224         if (resourceId == -1) {
    225             Log.w(TAG, "Missing theme resources for pointer icon type " + type);
    226             return type == TYPE_DEFAULT ? gNullIcon : getSystemIcon(context, TYPE_DEFAULT);
    227         }
    228 
    229         icon = new PointerIcon(type);
    230         if ((resourceId & 0xff000000) == 0x01000000) {
    231             icon.mSystemIconResourceId = resourceId;
    232         } else {
    233             icon.loadResource(context, context.getResources(), resourceId);
    234         }
    235         gSystemIcons.append(type, icon);
    236         return icon;
    237     }
    238 
    239     /**
    240      * Updates wheter accessibility large icons are used or not.
    241      * @hide
    242      */
    243     public static void setUseLargeIcons(boolean use) {
    244         sUseLargeIcons = use;
    245         gSystemIcons.clear();
    246     }
    247 
    248     /**
    249      * Creates a custom pointer icon from the given bitmap and hotspot information.
    250      *
    251      * @param bitmap The bitmap for the icon.
    252      * @param hotSpotX The X offset of the pointer icon hotspot in the bitmap.
    253      *        Must be within the [0, bitmap.getWidth()) range.
    254      * @param hotSpotY The Y offset of the pointer icon hotspot in the bitmap.
    255      *        Must be within the [0, bitmap.getHeight()) range.
    256      * @return A pointer icon for this bitmap.
    257      *
    258      * @throws IllegalArgumentException if bitmap is null, or if the x/y hotspot
    259      *         parameters are invalid.
    260      */
    261     public static PointerIcon create(@NonNull Bitmap bitmap, float hotSpotX, float hotSpotY) {
    262         if (bitmap == null) {
    263             throw new IllegalArgumentException("bitmap must not be null");
    264         }
    265         validateHotSpot(bitmap, hotSpotX, hotSpotY);
    266 
    267         PointerIcon icon = new PointerIcon(TYPE_CUSTOM);
    268         icon.mBitmap = bitmap;
    269         icon.mHotSpotX = hotSpotX;
    270         icon.mHotSpotY = hotSpotY;
    271         return icon;
    272     }
    273 
    274     /**
    275      * Loads a custom pointer icon from an XML resource.
    276      * <p>
    277      * The XML resource should have the following form:
    278      * <code>
    279      * &lt;?xml version="1.0" encoding="utf-8"?&gt;
    280      * &lt;pointer-icon xmlns:android="http://schemas.android.com/apk/res/android"
    281      *   android:bitmap="@drawable/my_pointer_bitmap"
    282      *   android:hotSpotX="24"
    283      *   android:hotSpotY="24" /&gt;
    284      * </code>
    285      * </p>
    286      *
    287      * @param resources The resources object.
    288      * @param resourceId The resource id.
    289      * @return The pointer icon.
    290      *
    291      * @throws IllegalArgumentException if resources is null.
    292      * @throws Resources.NotFoundException if the resource was not found or the drawable
    293      * linked in the resource was not found.
    294      */
    295     public static PointerIcon load(@NonNull Resources resources, @XmlRes int resourceId) {
    296         if (resources == null) {
    297             throw new IllegalArgumentException("resources must not be null");
    298         }
    299 
    300         PointerIcon icon = new PointerIcon(TYPE_CUSTOM);
    301         icon.loadResource(null, resources, resourceId);
    302         return icon;
    303     }
    304 
    305     /**
    306      * Loads the bitmap and hotspot information for a pointer icon, if it is not already loaded.
    307      * Returns a pointer icon (not necessarily the same instance) with the information filled in.
    308      *
    309      * @param context The context.
    310      * @return The loaded pointer icon.
    311      *
    312      * @throws IllegalArgumentException if context is null.
    313      * @hide
    314      */
    315     public PointerIcon load(@NonNull Context context) {
    316         if (context == null) {
    317             throw new IllegalArgumentException("context must not be null");
    318         }
    319 
    320         if (mSystemIconResourceId == 0 || mBitmap != null) {
    321             return this;
    322         }
    323 
    324         PointerIcon result = new PointerIcon(mType);
    325         result.mSystemIconResourceId = mSystemIconResourceId;
    326         result.loadResource(context, context.getResources(), mSystemIconResourceId);
    327         return result;
    328     }
    329 
    330     /** @hide */
    331     public int getType() {
    332         return mType;
    333     }
    334 
    335     public static final Parcelable.Creator<PointerIcon> CREATOR
    336             = new Parcelable.Creator<PointerIcon>() {
    337         public PointerIcon createFromParcel(Parcel in) {
    338             int type = in.readInt();
    339             if (type == TYPE_NULL) {
    340                 return getNullIcon();
    341             }
    342 
    343             int systemIconResourceId = in.readInt();
    344             if (systemIconResourceId != 0) {
    345                 PointerIcon icon = new PointerIcon(type);
    346                 icon.mSystemIconResourceId = systemIconResourceId;
    347                 return icon;
    348             }
    349 
    350             Bitmap bitmap = Bitmap.CREATOR.createFromParcel(in);
    351             float hotSpotX = in.readFloat();
    352             float hotSpotY = in.readFloat();
    353             return PointerIcon.create(bitmap, hotSpotX, hotSpotY);
    354         }
    355 
    356         public PointerIcon[] newArray(int size) {
    357             return new PointerIcon[size];
    358         }
    359     };
    360 
    361     public int describeContents() {
    362         return 0;
    363     }
    364 
    365     public void writeToParcel(Parcel out, int flags) {
    366         out.writeInt(mType);
    367 
    368         if (mType != TYPE_NULL) {
    369             out.writeInt(mSystemIconResourceId);
    370             if (mSystemIconResourceId == 0) {
    371                 mBitmap.writeToParcel(out, flags);
    372                 out.writeFloat(mHotSpotX);
    373                 out.writeFloat(mHotSpotY);
    374             }
    375         }
    376     }
    377 
    378     @Override
    379     public boolean equals(Object other) {
    380         if (this == other) {
    381             return true;
    382         }
    383 
    384         if (other == null || !(other instanceof PointerIcon)) {
    385             return false;
    386         }
    387 
    388         PointerIcon otherIcon = (PointerIcon) other;
    389         if (mType != otherIcon.mType
    390                 || mSystemIconResourceId != otherIcon.mSystemIconResourceId) {
    391             return false;
    392         }
    393 
    394         if (mSystemIconResourceId == 0 && (mBitmap != otherIcon.mBitmap
    395                 || mHotSpotX != otherIcon.mHotSpotX
    396                 || mHotSpotY != otherIcon.mHotSpotY)) {
    397             return false;
    398         }
    399 
    400         return true;
    401     }
    402 
    403     /**
    404      *  Get the Bitmap from the Drawable.
    405      *
    406      *  If the Bitmap needed to be scaled up to account for density, BitmapDrawable
    407      *  handles this at draw time. But this class doesn't actually draw the Bitmap;
    408      *  it is just a holder for native code to access its SkBitmap. So this needs to
    409      *  get a version that is scaled to account for density.
    410      */
    411     private Bitmap getBitmapFromDrawable(BitmapDrawable bitmapDrawable) {
    412         Bitmap bitmap = bitmapDrawable.getBitmap();
    413         final int scaledWidth  = bitmapDrawable.getIntrinsicWidth();
    414         final int scaledHeight = bitmapDrawable.getIntrinsicHeight();
    415         if (scaledWidth == bitmap.getWidth() && scaledHeight == bitmap.getHeight()) {
    416             return bitmap;
    417         }
    418 
    419         Rect src = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
    420         RectF dst = new RectF(0, 0, scaledWidth, scaledHeight);
    421 
    422         Bitmap scaled = Bitmap.createBitmap(scaledWidth, scaledHeight, bitmap.getConfig());
    423         Canvas canvas = new Canvas(scaled);
    424         Paint paint = new Paint();
    425         paint.setFilterBitmap(true);
    426         canvas.drawBitmap(bitmap, src, dst, paint);
    427         return scaled;
    428     }
    429 
    430     private void loadResource(Context context, Resources resources, @XmlRes int resourceId) {
    431         final XmlResourceParser parser = resources.getXml(resourceId);
    432         final int bitmapRes;
    433         final float hotSpotX;
    434         final float hotSpotY;
    435         try {
    436             XmlUtils.beginDocument(parser, "pointer-icon");
    437 
    438             final TypedArray a = resources.obtainAttributes(
    439                     parser, com.android.internal.R.styleable.PointerIcon);
    440             bitmapRes = a.getResourceId(com.android.internal.R.styleable.PointerIcon_bitmap, 0);
    441             hotSpotX = a.getDimension(com.android.internal.R.styleable.PointerIcon_hotSpotX, 0);
    442             hotSpotY = a.getDimension(com.android.internal.R.styleable.PointerIcon_hotSpotY, 0);
    443             a.recycle();
    444         } catch (Exception ex) {
    445             throw new IllegalArgumentException("Exception parsing pointer icon resource.", ex);
    446         } finally {
    447             parser.close();
    448         }
    449 
    450         if (bitmapRes == 0) {
    451             throw new IllegalArgumentException("<pointer-icon> is missing bitmap attribute.");
    452         }
    453 
    454         Drawable drawable;
    455         if (context == null) {
    456             drawable = resources.getDrawable(bitmapRes);
    457         } else {
    458             drawable = context.getDrawable(bitmapRes);
    459         }
    460         if (drawable instanceof AnimationDrawable) {
    461             // Extract animation frame bitmaps.
    462             final AnimationDrawable animationDrawable = (AnimationDrawable) drawable;
    463             final int frames = animationDrawable.getNumberOfFrames();
    464             drawable = animationDrawable.getFrame(0);
    465             if (frames == 1) {
    466                 Log.w(TAG, "Animation icon with single frame -- simply treating the first "
    467                         + "frame as a normal bitmap icon.");
    468             } else {
    469                 // Assumes they have the exact duration.
    470                 mDurationPerFrame = animationDrawable.getDuration(0);
    471                 mBitmapFrames = new Bitmap[frames - 1];
    472                 final int width = drawable.getIntrinsicWidth();
    473                 final int height = drawable.getIntrinsicHeight();
    474                 for (int i = 1; i < frames; ++i) {
    475                     Drawable drawableFrame = animationDrawable.getFrame(i);
    476                     if (!(drawableFrame instanceof BitmapDrawable)) {
    477                         throw new IllegalArgumentException("Frame of an animated pointer icon "
    478                                 + "must refer to a bitmap drawable.");
    479                     }
    480                     if (drawableFrame.getIntrinsicWidth() != width ||
    481                         drawableFrame.getIntrinsicHeight() != height) {
    482                         throw new IllegalArgumentException("The bitmap size of " + i + "-th frame "
    483                                 + "is different. All frames should have the exact same size and "
    484                                 + "share the same hotspot.");
    485                     }
    486                     BitmapDrawable bitmapDrawableFrame = (BitmapDrawable) drawableFrame;
    487                     mBitmapFrames[i - 1] = getBitmapFromDrawable(bitmapDrawableFrame);
    488                 }
    489             }
    490         }
    491         if (!(drawable instanceof BitmapDrawable)) {
    492             throw new IllegalArgumentException("<pointer-icon> bitmap attribute must "
    493                     + "refer to a bitmap drawable.");
    494         }
    495 
    496         BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
    497         final Bitmap bitmap = getBitmapFromDrawable(bitmapDrawable);
    498         validateHotSpot(bitmap, hotSpotX, hotSpotY);
    499         // Set the properties now that we have successfully loaded the icon.
    500         mBitmap = bitmap;
    501         mHotSpotX = hotSpotX;
    502         mHotSpotY = hotSpotY;
    503     }
    504 
    505     private static void validateHotSpot(Bitmap bitmap, float hotSpotX, float hotSpotY) {
    506         if (hotSpotX < 0 || hotSpotX >= bitmap.getWidth()) {
    507             throw new IllegalArgumentException("x hotspot lies outside of the bitmap area");
    508         }
    509         if (hotSpotY < 0 || hotSpotY >= bitmap.getHeight()) {
    510             throw new IllegalArgumentException("y hotspot lies outside of the bitmap area");
    511         }
    512     }
    513 
    514     private static int getSystemIconTypeIndex(int type) {
    515         switch (type) {
    516             case TYPE_ARROW:
    517                 return com.android.internal.R.styleable.Pointer_pointerIconArrow;
    518             case TYPE_SPOT_HOVER:
    519                 return com.android.internal.R.styleable.Pointer_pointerIconSpotHover;
    520             case TYPE_SPOT_TOUCH:
    521                 return com.android.internal.R.styleable.Pointer_pointerIconSpotTouch;
    522             case TYPE_SPOT_ANCHOR:
    523                 return com.android.internal.R.styleable.Pointer_pointerIconSpotAnchor;
    524             case TYPE_HAND:
    525                 return com.android.internal.R.styleable.Pointer_pointerIconHand;
    526             case TYPE_CONTEXT_MENU:
    527                 return com.android.internal.R.styleable.Pointer_pointerIconContextMenu;
    528             case TYPE_HELP:
    529                 return com.android.internal.R.styleable.Pointer_pointerIconHelp;
    530             case TYPE_WAIT:
    531                 return com.android.internal.R.styleable.Pointer_pointerIconWait;
    532             case TYPE_CELL:
    533                 return com.android.internal.R.styleable.Pointer_pointerIconCell;
    534             case TYPE_CROSSHAIR:
    535                 return com.android.internal.R.styleable.Pointer_pointerIconCrosshair;
    536             case TYPE_TEXT:
    537                 return com.android.internal.R.styleable.Pointer_pointerIconText;
    538             case TYPE_VERTICAL_TEXT:
    539                 return com.android.internal.R.styleable.Pointer_pointerIconVerticalText;
    540             case TYPE_ALIAS:
    541                 return com.android.internal.R.styleable.Pointer_pointerIconAlias;
    542             case TYPE_COPY:
    543                 return com.android.internal.R.styleable.Pointer_pointerIconCopy;
    544             case TYPE_ALL_SCROLL:
    545                 return com.android.internal.R.styleable.Pointer_pointerIconAllScroll;
    546             case TYPE_NO_DROP:
    547                 return com.android.internal.R.styleable.Pointer_pointerIconNodrop;
    548             case TYPE_HORIZONTAL_DOUBLE_ARROW:
    549                 return com.android.internal.R.styleable.Pointer_pointerIconHorizontalDoubleArrow;
    550             case TYPE_VERTICAL_DOUBLE_ARROW:
    551                 return com.android.internal.R.styleable.Pointer_pointerIconVerticalDoubleArrow;
    552             case TYPE_TOP_RIGHT_DIAGONAL_DOUBLE_ARROW:
    553                 return com.android.internal.R.styleable.
    554                         Pointer_pointerIconTopRightDiagonalDoubleArrow;
    555             case TYPE_TOP_LEFT_DIAGONAL_DOUBLE_ARROW:
    556                 return com.android.internal.R.styleable.
    557                         Pointer_pointerIconTopLeftDiagonalDoubleArrow;
    558             case TYPE_ZOOM_IN:
    559                 return com.android.internal.R.styleable.Pointer_pointerIconZoomIn;
    560             case TYPE_ZOOM_OUT:
    561                 return com.android.internal.R.styleable.Pointer_pointerIconZoomOut;
    562             case TYPE_GRAB:
    563                 return com.android.internal.R.styleable.Pointer_pointerIconGrab;
    564             case TYPE_GRABBING:
    565                 return com.android.internal.R.styleable.Pointer_pointerIconGrabbing;
    566             default:
    567                 return 0;
    568         }
    569     }
    570 }
    571