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