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