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