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