Drawable.java revision e5e92602a41a4ddc7b42cd1c171a0edfbd09b8da
1/*
2 * Copyright (C) 2006 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.graphics.drawable;
18
19import android.annotation.NonNull;
20import android.graphics.Insets;
21import android.graphics.Xfermode;
22import android.os.Trace;
23
24import org.xmlpull.v1.XmlPullParser;
25import org.xmlpull.v1.XmlPullParserException;
26
27import android.content.res.ColorStateList;
28import android.content.res.Resources;
29import android.content.res.Resources.Theme;
30import android.content.res.TypedArray;
31import android.graphics.Bitmap;
32import android.graphics.BitmapFactory;
33import android.graphics.Canvas;
34import android.graphics.ColorFilter;
35import android.graphics.NinePatch;
36import android.graphics.Outline;
37import android.graphics.PixelFormat;
38import android.graphics.PorterDuff;
39import android.graphics.PorterDuffColorFilter;
40import android.graphics.Rect;
41import android.graphics.Region;
42import android.graphics.PorterDuff.Mode;
43import android.util.AttributeSet;
44import android.util.DisplayMetrics;
45import android.util.StateSet;
46import android.util.TypedValue;
47import android.util.Xml;
48import android.view.View;
49
50import java.io.IOException;
51import java.io.InputStream;
52import java.lang.ref.WeakReference;
53import java.util.Arrays;
54
55/**
56 * A Drawable is a general abstraction for "something that can be drawn."  Most
57 * often you will deal with Drawable as the type of resource retrieved for
58 * drawing things to the screen; the Drawable class provides a generic API for
59 * dealing with an underlying visual resource that may take a variety of forms.
60 * Unlike a {@link android.view.View}, a Drawable does not have any facility to
61 * receive events or otherwise interact with the user.
62 *
63 * <p>In addition to simple drawing, Drawable provides a number of generic
64 * mechanisms for its client to interact with what is being drawn:
65 *
66 * <ul>
67 *     <li> The {@link #setBounds} method <var>must</var> be called to tell the
68 *     Drawable where it is drawn and how large it should be.  All Drawables
69 *     should respect the requested size, often simply by scaling their
70 *     imagery.  A client can find the preferred size for some Drawables with
71 *     the {@link #getIntrinsicHeight} and {@link #getIntrinsicWidth} methods.
72 *
73 *     <li> The {@link #getPadding} method can return from some Drawables
74 *     information about how to frame content that is placed inside of them.
75 *     For example, a Drawable that is intended to be the frame for a button
76 *     widget would need to return padding that correctly places the label
77 *     inside of itself.
78 *
79 *     <li> The {@link #setState} method allows the client to tell the Drawable
80 *     in which state it is to be drawn, such as "focused", "selected", etc.
81 *     Some drawables may modify their imagery based on the selected state.
82 *
83 *     <li> The {@link #setLevel} method allows the client to supply a single
84 *     continuous controller that can modify the Drawable is displayed, such as
85 *     a battery level or progress level.  Some drawables may modify their
86 *     imagery based on the current level.
87 *
88 *     <li> A Drawable can perform animations by calling back to its client
89 *     through the {@link Callback} interface.  All clients should support this
90 *     interface (via {@link #setCallback}) so that animations will work.  A
91 *     simple way to do this is through the system facilities such as
92 *     {@link android.view.View#setBackground(Drawable)} and
93 *     {@link android.widget.ImageView}.
94 * </ul>
95 *
96 * Though usually not visible to the application, Drawables may take a variety
97 * of forms:
98 *
99 * <ul>
100 *     <li> <b>Bitmap</b>: the simplest Drawable, a PNG or JPEG image.
101 *     <li> <b>Nine Patch</b>: an extension to the PNG format allows it to
102 *     specify information about how to stretch it and place things inside of
103 *     it.
104 *     <li> <b>Shape</b>: contains simple drawing commands instead of a raw
105 *     bitmap, allowing it to resize better in some cases.
106 *     <li> <b>Layers</b>: a compound drawable, which draws multiple underlying
107 *     drawables on top of each other.
108 *     <li> <b>States</b>: a compound drawable that selects one of a set of
109 *     drawables based on its state.
110 *     <li> <b>Levels</b>: a compound drawable that selects one of a set of
111 *     drawables based on its level.
112 *     <li> <b>Scale</b>: a compound drawable with a single child drawable,
113 *     whose overall size is modified based on the current level.
114 * </ul>
115 *
116 * <div class="special reference">
117 * <h3>Developer Guides</h3>
118 * <p>For more information about how to use drawables, read the
119 * <a href="{@docRoot}guide/topics/graphics/2d-graphics.html">Canvas and Drawables</a> developer
120 * guide. For information and examples of creating drawable resources (XML or bitmap files that
121 * can be loaded in code), read the
122 * <a href="{@docRoot}guide/topics/resources/drawable-resource.html">Drawable Resources</a>
123 * document.</p></div>
124 */
125public abstract class Drawable {
126    private static final Rect ZERO_BOUNDS_RECT = new Rect();
127
128    private int[] mStateSet = StateSet.WILD_CARD;
129    private int mLevel = 0;
130    private int mChangingConfigurations = 0;
131    private Rect mBounds = ZERO_BOUNDS_RECT;  // lazily becomes a new Rect()
132    private WeakReference<Callback> mCallback = null;
133    private boolean mVisible = true;
134
135    private int mLayoutDirection;
136
137    /**
138     * Draw in its bounds (set via setBounds) respecting optional effects such
139     * as alpha (set via setAlpha) and color filter (set via setColorFilter).
140     *
141     * @param canvas The canvas to draw into
142     */
143    public abstract void draw(Canvas canvas);
144
145    /**
146     * Specify a bounding rectangle for the Drawable. This is where the drawable
147     * will draw when its draw() method is called.
148     */
149    public void setBounds(int left, int top, int right, int bottom) {
150        Rect oldBounds = mBounds;
151
152        if (oldBounds == ZERO_BOUNDS_RECT) {
153            oldBounds = mBounds = new Rect();
154        }
155
156        if (oldBounds.left != left || oldBounds.top != top ||
157                oldBounds.right != right || oldBounds.bottom != bottom) {
158            if (!oldBounds.isEmpty()) {
159                // first invalidate the previous bounds
160                invalidateSelf();
161            }
162            mBounds.set(left, top, right, bottom);
163            onBoundsChange(mBounds);
164        }
165    }
166
167    /**
168     * Specify a bounding rectangle for the Drawable. This is where the drawable
169     * will draw when its draw() method is called.
170     */
171    public void setBounds(Rect bounds) {
172        setBounds(bounds.left, bounds.top, bounds.right, bounds.bottom);
173    }
174
175    /**
176     * Return a copy of the drawable's bounds in the specified Rect (allocated
177     * by the caller). The bounds specify where this will draw when its draw()
178     * method is called.
179     *
180     * @param bounds Rect to receive the drawable's bounds (allocated by the
181     *               caller).
182     */
183    public final void copyBounds(Rect bounds) {
184        bounds.set(mBounds);
185    }
186
187    /**
188     * Return a copy of the drawable's bounds in a new Rect. This returns the
189     * same values as getBounds(), but the returned object is guaranteed to not
190     * be changed later by the drawable (i.e. it retains no reference to this
191     * rect). If the caller already has a Rect allocated, call copyBounds(rect).
192     *
193     * @return A copy of the drawable's bounds
194     */
195    public final Rect copyBounds() {
196        return new Rect(mBounds);
197    }
198
199    /**
200     * Return the drawable's bounds Rect. Note: for efficiency, the returned
201     * object may be the same object stored in the drawable (though this is not
202     * guaranteed), so if a persistent copy of the bounds is needed, call
203     * copyBounds(rect) instead.
204     * You should also not change the object returned by this method as it may
205     * be the same object stored in the drawable.
206     *
207     * @return The bounds of the drawable (which may change later, so caller
208     *         beware). DO NOT ALTER the returned object as it may change the
209     *         stored bounds of this drawable.
210     *
211     * @see #copyBounds()
212     * @see #copyBounds(android.graphics.Rect)
213     */
214    public final Rect getBounds() {
215        if (mBounds == ZERO_BOUNDS_RECT) {
216            mBounds = new Rect();
217        }
218
219        return mBounds;
220    }
221
222    /**
223     * Return the drawable's dirty bounds Rect. Note: for efficiency, the
224     * returned object may be the same object stored in the drawable (though
225     * this is not guaranteed).
226     * <p>
227     * By default, this returns the full drawable bounds. Custom drawables may
228     * override this method to perform more precise invalidation.
229     *
230     * @return The dirty bounds of this drawable
231     */
232    public Rect getDirtyBounds() {
233        return getBounds();
234    }
235
236    /**
237     * Set a mask of the configuration parameters for which this drawable
238     * may change, requiring that it be re-created.
239     *
240     * @param configs A mask of the changing configuration parameters, as
241     * defined by {@link android.content.res.Configuration}.
242     *
243     * @see android.content.res.Configuration
244     */
245    public void setChangingConfigurations(int configs) {
246        mChangingConfigurations = configs;
247    }
248
249    /**
250     * Return a mask of the configuration parameters for which this drawable
251     * may change, requiring that it be re-created.  The default implementation
252     * returns whatever was provided through
253     * {@link #setChangingConfigurations(int)} or 0 by default.  Subclasses
254     * may extend this to or in the changing configurations of any other
255     * drawables they hold.
256     *
257     * @return Returns a mask of the changing configuration parameters, as
258     * defined by {@link android.content.res.Configuration}.
259     *
260     * @see android.content.res.Configuration
261     */
262    public int getChangingConfigurations() {
263        return mChangingConfigurations;
264    }
265
266    /**
267     * Set to true to have the drawable dither its colors when drawn to a device
268     * with fewer than 8-bits per color component. This can improve the look on
269     * those devices, but can also slow down the drawing a little.
270     */
271    public void setDither(boolean dither) {}
272
273    /**
274     * Set to true to have the drawable filter its bitmap when scaled or rotated
275     * (for drawables that use bitmaps). If the drawable does not use bitmaps,
276     * this call is ignored. This can improve the look when scaled or rotated,
277     * but also slows down the drawing.
278     */
279    public void setFilterBitmap(boolean filter) {}
280
281    /**
282     * Implement this interface if you want to create an animated drawable that
283     * extends {@link android.graphics.drawable.Drawable Drawable}.
284     * Upon retrieving a drawable, use
285     * {@link Drawable#setCallback(android.graphics.drawable.Drawable.Callback)}
286     * to supply your implementation of the interface to the drawable; it uses
287     * this interface to schedule and execute animation changes.
288     */
289    public static interface Callback {
290        /**
291         * Called when the drawable needs to be redrawn.  A view at this point
292         * should invalidate itself (or at least the part of itself where the
293         * drawable appears).
294         *
295         * @param who The drawable that is requesting the update.
296         */
297        public void invalidateDrawable(Drawable who);
298
299        /**
300         * A Drawable can call this to schedule the next frame of its
301         * animation.  An implementation can generally simply call
302         * {@link android.os.Handler#postAtTime(Runnable, Object, long)} with
303         * the parameters <var>(what, who, when)</var> to perform the
304         * scheduling.
305         *
306         * @param who The drawable being scheduled.
307         * @param what The action to execute.
308         * @param when The time (in milliseconds) to run.  The timebase is
309         *             {@link android.os.SystemClock#uptimeMillis}
310         */
311        public void scheduleDrawable(Drawable who, Runnable what, long when);
312
313        /**
314         * A Drawable can call this to unschedule an action previously
315         * scheduled with {@link #scheduleDrawable}.  An implementation can
316         * generally simply call
317         * {@link android.os.Handler#removeCallbacks(Runnable, Object)} with
318         * the parameters <var>(what, who)</var> to unschedule the drawable.
319         *
320         * @param who The drawable being unscheduled.
321         * @param what The action being unscheduled.
322         */
323        public void unscheduleDrawable(Drawable who, Runnable what);
324    }
325
326    /**
327     * Bind a {@link Callback} object to this Drawable.  Required for clients
328     * that want to support animated drawables.
329     *
330     * @param cb The client's Callback implementation.
331     *
332     * @see #getCallback()
333     */
334    public final void setCallback(Callback cb) {
335        mCallback = new WeakReference<Callback>(cb);
336    }
337
338    /**
339     * Return the current {@link Callback} implementation attached to this
340     * Drawable.
341     *
342     * @return A {@link Callback} instance or null if no callback was set.
343     *
344     * @see #setCallback(android.graphics.drawable.Drawable.Callback)
345     */
346    public Callback getCallback() {
347        if (mCallback != null) {
348            return mCallback.get();
349        }
350        return null;
351    }
352
353    /**
354     * Use the current {@link Callback} implementation to have this Drawable
355     * redrawn.  Does nothing if there is no Callback attached to the
356     * Drawable.
357     *
358     * @see Callback#invalidateDrawable
359     * @see #getCallback()
360     * @see #setCallback(android.graphics.drawable.Drawable.Callback)
361     */
362    public void invalidateSelf() {
363        final Callback callback = getCallback();
364        if (callback != null) {
365            callback.invalidateDrawable(this);
366        }
367    }
368
369    /**
370     * Use the current {@link Callback} implementation to have this Drawable
371     * scheduled.  Does nothing if there is no Callback attached to the
372     * Drawable.
373     *
374     * @param what The action being scheduled.
375     * @param when The time (in milliseconds) to run.
376     *
377     * @see Callback#scheduleDrawable
378     */
379    public void scheduleSelf(Runnable what, long when) {
380        final Callback callback = getCallback();
381        if (callback != null) {
382            callback.scheduleDrawable(this, what, when);
383        }
384    }
385
386    /**
387     * Use the current {@link Callback} implementation to have this Drawable
388     * unscheduled.  Does nothing if there is no Callback attached to the
389     * Drawable.
390     *
391     * @param what The runnable that you no longer want called.
392     *
393     * @see Callback#unscheduleDrawable
394     */
395    public void unscheduleSelf(Runnable what) {
396        final Callback callback = getCallback();
397        if (callback != null) {
398            callback.unscheduleDrawable(this, what);
399        }
400    }
401
402    /**
403     * Returns the resolved layout direction for this Drawable.
404     *
405     * @return One of {@link android.view.View#LAYOUT_DIRECTION_LTR},
406     *   {@link android.view.View#LAYOUT_DIRECTION_RTL}
407     *
408     * @hide
409     */
410    public int getLayoutDirection() {
411        return mLayoutDirection;
412    }
413
414    /**
415     * Set the layout direction for this drawable. Should be a resolved direction as the
416     * Drawable as no capacity to do the resolution on his own.
417     *
418     * @param layoutDirection One of {@link android.view.View#LAYOUT_DIRECTION_LTR},
419     *   {@link android.view.View#LAYOUT_DIRECTION_RTL}
420     *
421     * @hide
422     */
423    public void setLayoutDirection(@View.ResolvedLayoutDir int layoutDirection) {
424        if (getLayoutDirection() != layoutDirection) {
425            mLayoutDirection = layoutDirection;
426        }
427    }
428
429    /**
430     * Specify an alpha value for the drawable. 0 means fully transparent, and
431     * 255 means fully opaque.
432     */
433    public abstract void setAlpha(int alpha);
434
435    /**
436     * Gets the current alpha value for the drawable. 0 means fully transparent,
437     * 255 means fully opaque. This method is implemented by
438     * Drawable subclasses and the value returned is specific to how that class treats alpha.
439     * The default return value is 255 if the class does not override this method to return a value
440     * specific to its use of alpha.
441     */
442    public int getAlpha() {
443        return 0xFF;
444    }
445
446    /**
447     * @hide Consider for future API inclusion
448     */
449    public void setXfermode(Xfermode mode) {
450        // Base implementation drops it on the floor for compatibility. Whee!
451        // TODO: For this to be included in the API proper, all framework drawables need impls.
452        // For right now only BitmapDrawable has it.
453    }
454
455    /**
456     * Specify an optional color filter for the drawable. Pass {@code null} to
457     * remove any existing color filter.
458     *
459     * @param cf the color filter to apply, or {@code null} to remove the
460     *            existing color filter
461     */
462    public abstract void setColorFilter(ColorFilter cf);
463
464    /**
465     * Specify a color and Porter-Duff mode to be the color filter for this
466     * drawable.
467     */
468    public void setColorFilter(int color, PorterDuff.Mode mode) {
469        setColorFilter(new PorterDuffColorFilter(color, mode));
470    }
471
472    /**
473     * Specifies a tint and blending mode for this drawable.
474     * <p>
475     * Setting a color filter via {@link #setColorFilter(ColorFilter)} overrides
476     * tint.
477     *
478     * @param tint Color state list to use for tinting this drawable, or null to
479     *            clear the tint
480     * @param tintMode A Porter-Duff blending mode
481     */
482    public void setTint(ColorStateList tint, PorterDuff.Mode tintMode) {}
483
484    /**
485     * Returns the current color filter, or {@code null} if none set.
486     *
487     * @return the current color filter, or {@code null} if none set
488     */
489    public ColorFilter getColorFilter() {
490        return null;
491    }
492
493    /**
494     * Removes the color filter for this drawable.
495     */
496    public void clearColorFilter() {
497        setColorFilter(null);
498    }
499
500    /**
501     * Specifies the hotspot's location within the drawable.
502     *
503     * @param x The X coordinate of the center of the hotspot
504     * @param y The Y coordinate of the center of the hotspot
505     */
506    public void setHotspot(float x, float y) {}
507
508    /**
509     * Sets the bounds to which the hotspot is constrained, if they should be
510     * different from the drawable bounds.
511     *
512     * @param left
513     * @param top
514     * @param right
515     * @param bottom
516     */
517    public void setHotspotBounds(int left, int top, int right, int bottom) {}
518
519    /**
520     * Whether this drawable requests projection.
521     *
522     * @hide magic!
523     */
524    public boolean isProjected() {
525        return false;
526    }
527
528    /**
529     * Indicates whether this drawable will change its appearance based on
530     * state. Clients can use this to determine whether it is necessary to
531     * calculate their state and call setState.
532     *
533     * @return True if this drawable changes its appearance based on state,
534     *         false otherwise.
535     * @see #setState(int[])
536     */
537    public boolean isStateful() {
538        return false;
539    }
540
541    /**
542     * Specify a set of states for the drawable. These are use-case specific,
543     * so see the relevant documentation. As an example, the background for
544     * widgets like Button understand the following states:
545     * [{@link android.R.attr#state_focused},
546     *  {@link android.R.attr#state_pressed}].
547     *
548     * <p>If the new state you are supplying causes the appearance of the
549     * Drawable to change, then it is responsible for calling
550     * {@link #invalidateSelf} in order to have itself redrawn, <em>and</em>
551     * true will be returned from this function.
552     *
553     * <p>Note: The Drawable holds a reference on to <var>stateSet</var>
554     * until a new state array is given to it, so you must not modify this
555     * array during that time.</p>
556     *
557     * @param stateSet The new set of states to be displayed.
558     *
559     * @return Returns true if this change in state has caused the appearance
560     * of the Drawable to change (hence requiring an invalidate), otherwise
561     * returns false.
562     */
563    public boolean setState(final int[] stateSet) {
564        if (!Arrays.equals(mStateSet, stateSet)) {
565            mStateSet = stateSet;
566            return onStateChange(stateSet);
567        }
568        return false;
569    }
570
571    /**
572     * Describes the current state, as a union of primitve states, such as
573     * {@link android.R.attr#state_focused},
574     * {@link android.R.attr#state_selected}, etc.
575     * Some drawables may modify their imagery based on the selected state.
576     * @return An array of resource Ids describing the current state.
577     */
578    public int[] getState() {
579        return mStateSet;
580    }
581
582    /**
583     * If this Drawable does transition animations between states, ask that
584     * it immediately jump to the current state and skip any active animations.
585     */
586    public void jumpToCurrentState() {
587    }
588
589    /**
590     * @return The current drawable that will be used by this drawable. For simple drawables, this
591     *         is just the drawable itself. For drawables that change state like
592     *         {@link StateListDrawable} and {@link LevelListDrawable} this will be the child drawable
593     *         currently in use.
594     */
595    public Drawable getCurrent() {
596        return this;
597    }
598
599    /**
600     * Specify the level for the drawable.  This allows a drawable to vary its
601     * imagery based on a continuous controller, for example to show progress
602     * or volume level.
603     *
604     * <p>If the new level you are supplying causes the appearance of the
605     * Drawable to change, then it is responsible for calling
606     * {@link #invalidateSelf} in order to have itself redrawn, <em>and</em>
607     * true will be returned from this function.
608     *
609     * @param level The new level, from 0 (minimum) to 10000 (maximum).
610     *
611     * @return Returns true if this change in level has caused the appearance
612     * of the Drawable to change (hence requiring an invalidate), otherwise
613     * returns false.
614     */
615    public final boolean setLevel(int level) {
616        if (mLevel != level) {
617            mLevel = level;
618            return onLevelChange(level);
619        }
620        return false;
621    }
622
623    /**
624     * Retrieve the current level.
625     *
626     * @return int Current level, from 0 (minimum) to 10000 (maximum).
627     */
628    public final int getLevel() {
629        return mLevel;
630    }
631
632    /**
633     * Set whether this Drawable is visible.  This generally does not impact
634     * the Drawable's behavior, but is a hint that can be used by some
635     * Drawables, for example, to decide whether run animations.
636     *
637     * @param visible Set to true if visible, false if not.
638     * @param restart You can supply true here to force the drawable to behave
639     *                as if it has just become visible, even if it had last
640     *                been set visible.  Used for example to force animations
641     *                to restart.
642     *
643     * @return boolean Returns true if the new visibility is different than
644     *         its previous state.
645     */
646    public boolean setVisible(boolean visible, boolean restart) {
647        boolean changed = mVisible != visible;
648        if (changed) {
649            mVisible = visible;
650            invalidateSelf();
651        }
652        return changed;
653    }
654
655    public final boolean isVisible() {
656        return mVisible;
657    }
658
659    /**
660     * Set whether this Drawable is automatically mirrored when its layout direction is RTL
661     * (right-to left). See {@link android.util.LayoutDirection}.
662     *
663     * @param mirrored Set to true if the Drawable should be mirrored, false if not.
664     */
665    public void setAutoMirrored(boolean mirrored) {
666    }
667
668    /**
669     * Tells if this Drawable will be automatically mirrored  when its layout direction is RTL
670     * right-to-left. See {@link android.util.LayoutDirection}.
671     *
672     * @return boolean Returns true if this Drawable will be automatically mirrored.
673     */
674    public boolean isAutoMirrored() {
675        return false;
676    }
677
678    /**
679     * Applies the specified theme to this Drawable and its children.
680     */
681    public void applyTheme(@SuppressWarnings("unused") Theme t) {
682    }
683
684    public boolean canApplyTheme() {
685        return false;
686    }
687
688    /**
689     * Return the opacity/transparency of this Drawable.  The returned value is
690     * one of the abstract format constants in
691     * {@link android.graphics.PixelFormat}:
692     * {@link android.graphics.PixelFormat#UNKNOWN},
693     * {@link android.graphics.PixelFormat#TRANSLUCENT},
694     * {@link android.graphics.PixelFormat#TRANSPARENT}, or
695     * {@link android.graphics.PixelFormat#OPAQUE}.
696     *
697     * <p>Generally a Drawable should be as conservative as possible with the
698     * value it returns.  For example, if it contains multiple child drawables
699     * and only shows one of them at a time, if only one of the children is
700     * TRANSLUCENT and the others are OPAQUE then TRANSLUCENT should be
701     * returned.  You can use the method {@link #resolveOpacity} to perform a
702     * standard reduction of two opacities to the appropriate single output.
703     *
704     * <p>Note that the returned value does <em>not</em> take into account a
705     * custom alpha or color filter that has been applied by the client through
706     * the {@link #setAlpha} or {@link #setColorFilter} methods.
707     *
708     * @return int The opacity class of the Drawable.
709     *
710     * @see android.graphics.PixelFormat
711     */
712    public abstract int getOpacity();
713
714    /**
715     * Return the appropriate opacity value for two source opacities.  If
716     * either is UNKNOWN, that is returned; else, if either is TRANSLUCENT,
717     * that is returned; else, if either is TRANSPARENT, that is returned;
718     * else, OPAQUE is returned.
719     *
720     * <p>This is to help in implementing {@link #getOpacity}.
721     *
722     * @param op1 One opacity value.
723     * @param op2 Another opacity value.
724     *
725     * @return int The combined opacity value.
726     *
727     * @see #getOpacity
728     */
729    public static int resolveOpacity(int op1, int op2) {
730        if (op1 == op2) {
731            return op1;
732        }
733        if (op1 == PixelFormat.UNKNOWN || op2 == PixelFormat.UNKNOWN) {
734            return PixelFormat.UNKNOWN;
735        }
736        if (op1 == PixelFormat.TRANSLUCENT || op2 == PixelFormat.TRANSLUCENT) {
737            return PixelFormat.TRANSLUCENT;
738        }
739        if (op1 == PixelFormat.TRANSPARENT || op2 == PixelFormat.TRANSPARENT) {
740            return PixelFormat.TRANSPARENT;
741        }
742        return PixelFormat.OPAQUE;
743    }
744
745    /**
746     * Returns a Region representing the part of the Drawable that is completely
747     * transparent.  This can be used to perform drawing operations, identifying
748     * which parts of the target will not change when rendering the Drawable.
749     * The default implementation returns null, indicating no transparent
750     * region; subclasses can optionally override this to return an actual
751     * Region if they want to supply this optimization information, but it is
752     * not required that they do so.
753     *
754     * @return Returns null if the Drawables has no transparent region to
755     * report, else a Region holding the parts of the Drawable's bounds that
756     * are transparent.
757     */
758    public Region getTransparentRegion() {
759        return null;
760    }
761
762    /**
763     * Override this in your subclass to change appearance if you recognize the
764     * specified state.
765     *
766     * @return Returns true if the state change has caused the appearance of
767     * the Drawable to change (that is, it needs to be drawn), else false
768     * if it looks the same and there is no need to redraw it since its
769     * last state.
770     */
771    protected boolean onStateChange(int[] state) { return false; }
772    /** Override this in your subclass to change appearance if you vary based
773     *  on level.
774     * @return Returns true if the level change has caused the appearance of
775     * the Drawable to change (that is, it needs to be drawn), else false
776     * if it looks the same and there is no need to redraw it since its
777     * last level.
778     */
779    protected boolean onLevelChange(int level) { return false; }
780    /**
781     * Override this in your subclass to change appearance if you vary based on
782     * the bounds.
783     */
784    protected void onBoundsChange(Rect bounds) {}
785
786    /**
787     * Return the intrinsic width of the underlying drawable object.  Returns
788     * -1 if it has no intrinsic width, such as with a solid color.
789     */
790    public int getIntrinsicWidth() {
791        return -1;
792    }
793
794    /**
795     * Return the intrinsic height of the underlying drawable object. Returns
796     * -1 if it has no intrinsic height, such as with a solid color.
797     */
798    public int getIntrinsicHeight() {
799        return -1;
800    }
801
802    /**
803     * Returns the minimum width suggested by this Drawable. If a View uses this
804     * Drawable as a background, it is suggested that the View use at least this
805     * value for its width. (There will be some scenarios where this will not be
806     * possible.) This value should INCLUDE any padding.
807     *
808     * @return The minimum width suggested by this Drawable. If this Drawable
809     *         doesn't have a suggested minimum width, 0 is returned.
810     */
811    public int getMinimumWidth() {
812        final int intrinsicWidth = getIntrinsicWidth();
813        return intrinsicWidth > 0 ? intrinsicWidth : 0;
814    }
815
816    /**
817     * Returns the minimum height suggested by this Drawable. If a View uses this
818     * Drawable as a background, it is suggested that the View use at least this
819     * value for its height. (There will be some scenarios where this will not be
820     * possible.) This value should INCLUDE any padding.
821     *
822     * @return The minimum height suggested by this Drawable. If this Drawable
823     *         doesn't have a suggested minimum height, 0 is returned.
824     */
825    public int getMinimumHeight() {
826        final int intrinsicHeight = getIntrinsicHeight();
827        return intrinsicHeight > 0 ? intrinsicHeight : 0;
828    }
829
830    /**
831     * Return in padding the insets suggested by this Drawable for placing
832     * content inside the drawable's bounds. Positive values move toward the
833     * center of the Drawable (set Rect.inset).
834     *
835     * @return true if this drawable actually has a padding, else false. When false is returned,
836     * the padding is always set to 0.
837     */
838    public boolean getPadding(@NonNull Rect padding) {
839        padding.set(0, 0, 0, 0);
840        return false;
841    }
842
843    /**
844     * Return in insets the layout insets suggested by this Drawable for use with alignment
845     * operations during layout.
846     *
847     * @hide
848     */
849    public Insets getOpticalInsets() {
850        return Insets.NONE;
851    }
852
853    /**
854     * Called to get the drawable to populate the Outline.
855     * <p>
856     * This method will be called by a View on its background Drawable after bounds change, or its
857     * Drawable is invalidated, if the View's Outline isn't set explicitly. This allows the
858     * background Drawable to define the shape of the shadow cast by the View.
859     * <p>
860     * The default behavior defines the outline to be the bounding rectangle. Subclasses that wish
861     * to convey a different shape must override this method.
862     *
863     * @return true if this drawable actually has an outline, else false. The outline must be
864     *         populated by the drawable if true is returned.
865     *
866     * @see View#setOutline(android.graphics.Outline)
867     */
868    public boolean getOutline(@NonNull Outline outline) {
869        outline.setRect(getBounds());
870        return true;
871    }
872
873    /**
874     * Make this drawable mutable. This operation cannot be reversed. A mutable
875     * drawable is guaranteed to not share its state with any other drawable.
876     * This is especially useful when you need to modify properties of drawables
877     * loaded from resources. By default, all drawables instances loaded from
878     * the same resource share a common state; if you modify the state of one
879     * instance, all the other instances will receive the same modification.
880     *
881     * Calling this method on a mutable Drawable will have no effect.
882     *
883     * @return This drawable.
884     * @see ConstantState
885     * @see #getConstantState()
886     */
887    public Drawable mutate() {
888        return this;
889    }
890
891    /**
892     * Create a drawable from an inputstream
893     */
894    public static Drawable createFromStream(InputStream is, String srcName) {
895        Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, srcName != null ? srcName : "Unknown drawable");
896        try {
897            return createFromResourceStream(null, null, is, srcName);
898        } finally {
899            Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
900        }
901    }
902
903    /**
904     * Create a drawable from an inputstream, using the given resources and
905     * value to determine density information.
906     */
907    public static Drawable createFromResourceStream(Resources res, TypedValue value,
908            InputStream is, String srcName) {
909        Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, srcName != null ? srcName : "Unknown drawable");
910        try {
911            return createFromResourceStream(res, value, is, srcName, null);
912        } finally {
913            Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
914        }
915    }
916
917    /**
918     * Create a drawable from an inputstream, using the given resources and
919     * value to determine density information.
920     */
921    public static Drawable createFromResourceStream(Resources res, TypedValue value,
922            InputStream is, String srcName, BitmapFactory.Options opts) {
923        if (is == null) {
924            return null;
925        }
926
927        /*  ugh. The decodeStream contract is that we have already allocated
928            the pad rect, but if the bitmap does not had a ninepatch chunk,
929            then the pad will be ignored. If we could change this to lazily
930            alloc/assign the rect, we could avoid the GC churn of making new
931            Rects only to drop them on the floor.
932        */
933        Rect pad = new Rect();
934
935        // Special stuff for compatibility mode: if the target density is not
936        // the same as the display density, but the resource -is- the same as
937        // the display density, then don't scale it down to the target density.
938        // This allows us to load the system's density-correct resources into
939        // an application in compatibility mode, without scaling those down
940        // to the compatibility density only to have them scaled back up when
941        // drawn to the screen.
942        if (opts == null) opts = new BitmapFactory.Options();
943        opts.inScreenDensity = res != null
944                ? res.getDisplayMetrics().noncompatDensityDpi : DisplayMetrics.DENSITY_DEVICE;
945        Bitmap  bm = BitmapFactory.decodeResourceStream(res, value, is, pad, opts);
946        if (bm != null) {
947            byte[] np = bm.getNinePatchChunk();
948            if (np == null || !NinePatch.isNinePatchChunk(np)) {
949                np = null;
950                pad = null;
951            }
952            int[] layoutBounds = bm.getLayoutBounds();
953            Rect layoutBoundsRect = null;
954            if (layoutBounds != null) {
955                layoutBoundsRect = new Rect(layoutBounds[0], layoutBounds[1],
956                                             layoutBounds[2], layoutBounds[3]);
957            }
958            return drawableFromBitmap(res, bm, np, pad, layoutBoundsRect, srcName);
959        }
960        return null;
961    }
962
963    /**
964     * Create a drawable from an XML document. For more information on how to
965     * create resources in XML, see
966     * <a href="{@docRoot}guide/topics/resources/drawable-resource.html">Drawable Resources</a>.
967     */
968    public static Drawable createFromXml(Resources r, XmlPullParser parser)
969            throws XmlPullParserException, IOException {
970        return createFromXml(r, parser, null);
971    }
972
973    /**
974     * Create a drawable from an XML document using an optional {@link Theme}.
975     * For more information on how to create resources in XML, see
976     * <a href="{@docRoot}guide/topics/resources/drawable-resource.html">Drawable Resources</a>.
977     */
978    public static Drawable createFromXml(Resources r, XmlPullParser parser, Theme theme)
979            throws XmlPullParserException, IOException {
980        AttributeSet attrs = Xml.asAttributeSet(parser);
981
982        int type;
983        while ((type=parser.next()) != XmlPullParser.START_TAG &&
984                type != XmlPullParser.END_DOCUMENT) {
985            // Empty loop
986        }
987
988        if (type != XmlPullParser.START_TAG) {
989            throw new XmlPullParserException("No start tag found");
990        }
991
992        Drawable drawable = createFromXmlInner(r, parser, attrs, theme);
993
994        if (drawable == null) {
995            throw new RuntimeException("Unknown initial tag: " + parser.getName());
996        }
997
998        return drawable;
999    }
1000
1001    /**
1002     * Create from inside an XML document.  Called on a parser positioned at
1003     * a tag in an XML document, tries to create a Drawable from that tag.
1004     * Returns null if the tag is not a valid drawable.
1005     */
1006    public static Drawable createFromXmlInner(Resources r, XmlPullParser parser, AttributeSet attrs)
1007            throws XmlPullParserException, IOException {
1008        return createFromXmlInner(r, parser, attrs, null);
1009    }
1010
1011    /**
1012     * Create a drawable from inside an XML document using an optional
1013     * {@link Theme}. Called on a parser positioned at a tag in an XML
1014     * document, tries to create a Drawable from that tag. Returns {@code null}
1015     * if the tag is not a valid drawable.
1016     */
1017    public static Drawable createFromXmlInner(Resources r, XmlPullParser parser, AttributeSet attrs,
1018            Theme theme) throws XmlPullParserException, IOException {
1019        final Drawable drawable;
1020
1021        final String name = parser.getName();
1022        if (name.equals("selector")) {
1023            drawable = new StateListDrawable();
1024        } else if (name.equals("animated-selector")) {
1025            drawable = new AnimatedStateListDrawable();
1026        } else if (name.equals("material-progress")) {
1027            // TODO: Replace this with something less ridiculous.
1028            drawable = new MaterialProgressDrawable();
1029        } else if (name.equals("level-list")) {
1030            drawable = new LevelListDrawable();
1031        } else if (name.equals("layer-list")) {
1032            drawable = new LayerDrawable();
1033        } else if (name.equals("transition")) {
1034            drawable = new TransitionDrawable();
1035        } else if (name.equals("ripple")) {
1036            drawable = new RippleDrawable();
1037        } else if (name.equals("color")) {
1038            drawable = new ColorDrawable();
1039        } else if (name.equals("shape")) {
1040            drawable = new GradientDrawable();
1041        } else if (name.equals("vector")) {
1042            drawable = new VectorDrawable();
1043        } else if (name.equals("animated-vector")) {
1044            drawable = new AnimatedVectorDrawable();
1045        } else if (name.equals("scale")) {
1046            drawable = new ScaleDrawable();
1047        } else if (name.equals("clip")) {
1048            drawable = new ClipDrawable();
1049        } else if (name.equals("rotate")) {
1050            drawable = new RotateDrawable();
1051        } else if (name.equals("animated-rotate")) {
1052            drawable = new AnimatedRotateDrawable();
1053        } else if (name.equals("animation-list")) {
1054            drawable = new AnimationDrawable();
1055        } else if (name.equals("inset")) {
1056            drawable = new InsetDrawable();
1057        } else if (name.equals("bitmap")) {
1058            //noinspection deprecation
1059            drawable = new BitmapDrawable(r);
1060            if (r != null) {
1061               ((BitmapDrawable) drawable).setTargetDensity(r.getDisplayMetrics());
1062            }
1063        } else if (name.equals("nine-patch")) {
1064            drawable = new NinePatchDrawable();
1065            if (r != null) {
1066                ((NinePatchDrawable) drawable).setTargetDensity(r.getDisplayMetrics());
1067             }
1068        } else {
1069            throw new XmlPullParserException(parser.getPositionDescription() +
1070                    ": invalid drawable tag " + name);
1071        }
1072
1073        drawable.inflate(r, parser, attrs, theme);
1074        return drawable;
1075    }
1076
1077
1078    /**
1079     * Create a drawable from file path name.
1080     */
1081    public static Drawable createFromPath(String pathName) {
1082        if (pathName == null) {
1083            return null;
1084        }
1085
1086        Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, pathName);
1087        try {
1088            Bitmap bm = BitmapFactory.decodeFile(pathName);
1089            if (bm != null) {
1090                return drawableFromBitmap(null, bm, null, null, null, pathName);
1091            }
1092        } finally {
1093            Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
1094        }
1095
1096        return null;
1097    }
1098
1099    /**
1100     * Inflate this Drawable from an XML resource. Does not apply a theme.
1101     *
1102     * @see #inflate(Resources, XmlPullParser, AttributeSet, Theme)
1103     */
1104    public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs)
1105            throws XmlPullParserException, IOException {
1106        inflate(r, parser, attrs, null);
1107    }
1108
1109    /**
1110     * Inflate this Drawable from an XML resource optionally styled by a theme.
1111     *
1112     * @param r Resources used to resolve attribute values
1113     * @param parser XML parser from which to inflate this Drawable
1114     * @param attrs Base set of attribute values
1115     * @param theme Theme to apply, may be null
1116     * @throws XmlPullParserException
1117     * @throws IOException
1118     */
1119    public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs, Theme theme)
1120            throws XmlPullParserException, IOException {
1121        final TypedArray a;
1122        if (theme != null) {
1123            a = theme.obtainStyledAttributes(
1124                    attrs, com.android.internal.R.styleable.Drawable, 0, 0);
1125        } else {
1126            a = r.obtainAttributes(attrs, com.android.internal.R.styleable.Drawable);
1127        }
1128
1129        inflateWithAttributes(r, parser, a, com.android.internal.R.styleable.Drawable_visible);
1130        a.recycle();
1131    }
1132
1133    /**
1134     * Inflate a Drawable from an XML resource.
1135     *
1136     * @throws XmlPullParserException
1137     * @throws IOException
1138     */
1139    void inflateWithAttributes(Resources r, XmlPullParser parser, TypedArray attrs, int visibleAttr)
1140            throws XmlPullParserException, IOException {
1141        mVisible = attrs.getBoolean(visibleAttr, mVisible);
1142    }
1143
1144    /**
1145     * This abstract class is used by {@link Drawable}s to store shared constant state and data
1146     * between Drawables. {@link BitmapDrawable}s created from the same resource will for instance
1147     * share a unique bitmap stored in their ConstantState.
1148     *
1149     * <p>
1150     * {@link #newDrawable(Resources)} can be used as a factory to create new Drawable instances
1151     * from this ConstantState.
1152     * </p>
1153     *
1154     * Use {@link Drawable#getConstantState()} to retrieve the ConstantState of a Drawable. Calling
1155     * {@link Drawable#mutate()} on a Drawable should typically create a new ConstantState for that
1156     * Drawable.
1157     */
1158    public static abstract class ConstantState {
1159        /**
1160         * Create a new drawable without supplying resources the caller
1161         * is running in.  Note that using this means the density-dependent
1162         * drawables (like bitmaps) will not be able to update their target
1163         * density correctly. One should use {@link #newDrawable(Resources)}
1164         * instead to provide a resource.
1165         */
1166        public abstract Drawable newDrawable();
1167
1168        /**
1169         * Create a new Drawable instance from its constant state.  This
1170         * must be implemented for drawables that change based on the target
1171         * density of their caller (that is depending on whether it is
1172         * in compatibility mode).
1173         */
1174        public Drawable newDrawable(Resources res) {
1175            return newDrawable();
1176        }
1177
1178        /**
1179         * Create a new Drawable instance from its constant state. This must be
1180         * implemented for drawables that can have a theme applied.
1181         */
1182        public Drawable newDrawable(Resources res, Theme theme) {
1183            return newDrawable();
1184        }
1185
1186        /**
1187         * Return a bit mask of configuration changes that will impact
1188         * this drawable (and thus require completely reloading it).
1189         */
1190        public abstract int getChangingConfigurations();
1191
1192        /**
1193         * @hide
1194         */
1195        public Bitmap getBitmap() {
1196            return null;
1197        }
1198
1199        /**
1200         * Return whether this constant state can have a theme applied.
1201         */
1202        public boolean canApplyTheme() {
1203            return false;
1204        }
1205    }
1206
1207    /**
1208     * Return a {@link ConstantState} instance that holds the shared state of this Drawable.
1209     *
1210     * @return The ConstantState associated to that Drawable.
1211     * @see ConstantState
1212     * @see Drawable#mutate()
1213     */
1214    public ConstantState getConstantState() {
1215        return null;
1216    }
1217
1218    private static Drawable drawableFromBitmap(Resources res, Bitmap bm, byte[] np,
1219            Rect pad, Rect layoutBounds, String srcName) {
1220
1221        if (np != null) {
1222            return new NinePatchDrawable(res, bm, np, pad, layoutBounds, srcName);
1223        }
1224
1225        return new BitmapDrawable(res, bm);
1226    }
1227
1228    /**
1229     * Obtains styled attributes from the theme, if available, or unstyled
1230     * resources if the theme is null.
1231     */
1232    static TypedArray obtainAttributes(
1233            Resources res, Theme theme, AttributeSet set, int[] attrs) {
1234        if (theme == null) {
1235            return res.obtainAttributes(set, attrs);
1236        }
1237        return theme.obtainStyledAttributes(set, attrs, 0, 0);
1238    }
1239
1240    /**
1241     * Parses a {@link android.graphics.PorterDuff.Mode} from a tintMode
1242     * attribute's enum value.
1243     */
1244    static PorterDuff.Mode parseTintMode(int value, Mode defaultMode) {
1245        switch (value) {
1246            case 3: return Mode.SRC_OVER;
1247            case 5: return Mode.SRC_IN;
1248            case 9: return Mode.SRC_ATOP;
1249            case 14: return Mode.MULTIPLY;
1250            case 15: return Mode.SCREEN;
1251            case 16: return Mode.ADD;
1252            default: return defaultMode;
1253        }
1254    }
1255}
1256
1257