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