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