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