Drawable.java revision 78e561ce541e5c72780c68b5b14eb50c08bb97ac
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.ColorInt;
20import android.annotation.NonNull;
21import android.annotation.Nullable;
22import android.content.pm.ActivityInfo.Config;
23import android.content.res.ColorStateList;
24import android.content.res.Resources;
25import android.content.res.Resources.Theme;
26import android.content.res.TypedArray;
27import android.graphics.Bitmap;
28import android.graphics.BitmapFactory;
29import android.graphics.Canvas;
30import android.graphics.Color;
31import android.graphics.ColorFilter;
32import android.graphics.Insets;
33import android.graphics.NinePatch;
34import android.graphics.Outline;
35import android.graphics.PixelFormat;
36import android.graphics.PorterDuff;
37import android.graphics.PorterDuff.Mode;
38import android.graphics.PorterDuffColorFilter;
39import android.graphics.Rect;
40import android.graphics.Region;
41import android.graphics.Xfermode;
42import android.os.Trace;
43import android.util.AttributeSet;
44import android.util.DisplayMetrics;
45import android.util.StateSet;
46import android.util.TypedValue;
47import android.util.Xml;
48import android.view.View;
49
50import org.xmlpull.v1.XmlPullParser;
51import org.xmlpull.v1.XmlPullParserException;
52
53import java.io.IOException;
54import java.io.InputStream;
55import java.lang.ref.WeakReference;
56import java.util.Arrays;
57import java.util.Collection;
58
59import com.android.internal.R;
60
61/**
62 * A Drawable is a general abstraction for "something that can be drawn."  Most
63 * often you will deal with Drawable as the type of resource retrieved for
64 * drawing things to the screen; the Drawable class provides a generic API for
65 * dealing with an underlying visual resource that may take a variety of forms.
66 * Unlike a {@link android.view.View}, a Drawable does not have any facility to
67 * receive events or otherwise interact with the user.
68 *
69 * <p>In addition to simple drawing, Drawable provides a number of generic
70 * mechanisms for its client to interact with what is being drawn:
71 *
72 * <ul>
73 *     <li> The {@link #setBounds} method <var>must</var> be called to tell the
74 *     Drawable where it is drawn and how large it should be.  All Drawables
75 *     should respect the requested size, often simply by scaling their
76 *     imagery.  A client can find the preferred size for some Drawables with
77 *     the {@link #getIntrinsicHeight} and {@link #getIntrinsicWidth} methods.
78 *
79 *     <li> The {@link #getPadding} method can return from some Drawables
80 *     information about how to frame content that is placed inside of them.
81 *     For example, a Drawable that is intended to be the frame for a button
82 *     widget would need to return padding that correctly places the label
83 *     inside of itself.
84 *
85 *     <li> The {@link #setState} method allows the client to tell the Drawable
86 *     in which state it is to be drawn, such as "focused", "selected", etc.
87 *     Some drawables may modify their imagery based on the selected state.
88 *
89 *     <li> The {@link #setLevel} method allows the client to supply a single
90 *     continuous controller that can modify the Drawable is displayed, such as
91 *     a battery level or progress level.  Some drawables may modify their
92 *     imagery based on the current level.
93 *
94 *     <li> A Drawable can perform animations by calling back to its client
95 *     through the {@link Callback} interface.  All clients should support this
96 *     interface (via {@link #setCallback}) so that animations will work.  A
97 *     simple way to do this is through the system facilities such as
98 *     {@link android.view.View#setBackground(Drawable)} and
99 *     {@link android.widget.ImageView}.
100 * </ul>
101 *
102 * Though usually not visible to the application, Drawables may take a variety
103 * of forms:
104 *
105 * <ul>
106 *     <li> <b>Bitmap</b>: the simplest Drawable, a PNG or JPEG image.
107 *     <li> <b>Nine Patch</b>: an extension to the PNG format allows it to
108 *     specify information about how to stretch it and place things inside of
109 *     it.
110 *     <li> <b>Shape</b>: contains simple drawing commands instead of a raw
111 *     bitmap, allowing it to resize better in some cases.
112 *     <li> <b>Layers</b>: a compound drawable, which draws multiple underlying
113 *     drawables on top of each other.
114 *     <li> <b>States</b>: a compound drawable that selects one of a set of
115 *     drawables based on its state.
116 *     <li> <b>Levels</b>: a compound drawable that selects one of a set of
117 *     drawables based on its level.
118 *     <li> <b>Scale</b>: a compound drawable with a single child drawable,
119 *     whose overall size is modified based on the current level.
120 * </ul>
121 *
122 * <div class="special reference">
123 * <h3>Developer Guides</h3>
124 * <p>For more information about how to use drawables, read the
125 * <a href="{@docRoot}guide/topics/graphics/2d-graphics.html">Canvas and Drawables</a> developer
126 * guide. For information and examples of creating drawable resources (XML or bitmap files that
127 * can be loaded in code), read the
128 * <a href="{@docRoot}guide/topics/resources/drawable-resource.html">Drawable Resources</a>
129 * document.</p></div>
130 */
131public abstract class Drawable {
132    private static final Rect ZERO_BOUNDS_RECT = new Rect();
133
134    static final PorterDuff.Mode DEFAULT_TINT_MODE = PorterDuff.Mode.SRC_IN;
135
136    private int[] mStateSet = StateSet.WILD_CARD;
137    private int mLevel = 0;
138    private @Config int mChangingConfigurations = 0;
139    private Rect mBounds = ZERO_BOUNDS_RECT;  // lazily becomes a new Rect()
140    private WeakReference<Callback> mCallback = null;
141    private boolean mVisible = true;
142
143    private int mLayoutDirection;
144
145    /**
146     * Draw in its bounds (set via setBounds) respecting optional effects such
147     * as alpha (set via setAlpha) and color filter (set via setColorFilter).
148     *
149     * @param canvas The canvas to draw into
150     */
151    public abstract void draw(Canvas canvas);
152
153    /**
154     * Specify a bounding rectangle for the Drawable. This is where the drawable
155     * will draw when its draw() method is called.
156     */
157    public void setBounds(int left, int top, int right, int bottom) {
158        Rect oldBounds = mBounds;
159
160        if (oldBounds == ZERO_BOUNDS_RECT) {
161            oldBounds = mBounds = new Rect();
162        }
163
164        if (oldBounds.left != left || oldBounds.top != top ||
165                oldBounds.right != right || oldBounds.bottom != bottom) {
166            if (!oldBounds.isEmpty()) {
167                // first invalidate the previous bounds
168                invalidateSelf();
169            }
170            mBounds.set(left, top, right, bottom);
171            onBoundsChange(mBounds);
172        }
173    }
174
175    /**
176     * Specify a bounding rectangle for the Drawable. This is where the drawable
177     * will draw when its draw() method is called.
178     */
179    public void setBounds(Rect bounds) {
180        setBounds(bounds.left, bounds.top, bounds.right, bounds.bottom);
181    }
182
183    /**
184     * Return a copy of the drawable's bounds in the specified Rect (allocated
185     * by the caller). The bounds specify where this will draw when its draw()
186     * method is called.
187     *
188     * @param bounds Rect to receive the drawable's bounds (allocated by the
189     *               caller).
190     */
191    public final void copyBounds(Rect bounds) {
192        bounds.set(mBounds);
193    }
194
195    /**
196     * Return a copy of the drawable's bounds in a new Rect. This returns the
197     * same values as getBounds(), but the returned object is guaranteed to not
198     * be changed later by the drawable (i.e. it retains no reference to this
199     * rect). If the caller already has a Rect allocated, call copyBounds(rect).
200     *
201     * @return A copy of the drawable's bounds
202     */
203    public final Rect copyBounds() {
204        return new Rect(mBounds);
205    }
206
207    /**
208     * Return the drawable's bounds Rect. Note: for efficiency, the returned
209     * object may be the same object stored in the drawable (though this is not
210     * guaranteed), so if a persistent copy of the bounds is needed, call
211     * copyBounds(rect) instead.
212     * You should also not change the object returned by this method as it may
213     * be the same object stored in the drawable.
214     *
215     * @return The bounds of the drawable (which may change later, so caller
216     *         beware). DO NOT ALTER the returned object as it may change the
217     *         stored bounds of this drawable.
218     *
219     * @see #copyBounds()
220     * @see #copyBounds(android.graphics.Rect)
221     */
222    public final Rect getBounds() {
223        if (mBounds == ZERO_BOUNDS_RECT) {
224            mBounds = new Rect();
225        }
226
227        return mBounds;
228    }
229
230    /**
231     * Return the drawable's dirty bounds Rect. Note: for efficiency, the
232     * returned object may be the same object stored in the drawable (though
233     * this is not guaranteed).
234     * <p>
235     * By default, this returns the full drawable bounds. Custom drawables may
236     * override this method to perform more precise invalidation.
237     *
238     * @return The dirty bounds of this drawable
239     */
240    public Rect getDirtyBounds() {
241        return getBounds();
242    }
243
244    /**
245     * Set a mask of the configuration parameters for which this drawable
246     * may change, requiring that it be re-created.
247     *
248     * @param configs A mask of the changing configuration parameters, as
249     * defined by {@link android.content.pm.ActivityInfo}.
250     *
251     * @see android.content.pm.ActivityInfo
252     */
253    public void setChangingConfigurations(@Config int configs) {
254        mChangingConfigurations = configs;
255    }
256
257    /**
258     * Return a mask of the configuration parameters for which this drawable
259     * may change, requiring that it be re-created.  The default implementation
260     * returns whatever was provided through
261     * {@link #setChangingConfigurations(int)} or 0 by default.  Subclasses
262     * may extend this to or in the changing configurations of any other
263     * drawables they hold.
264     *
265     * @return Returns a mask of the changing configuration parameters, as
266     * defined by {@link android.content.pm.ActivityInfo}.
267     *
268     * @see android.content.pm.ActivityInfo
269     */
270    public @Config int getChangingConfigurations() {
271        return mChangingConfigurations;
272    }
273
274    /**
275     * Set to true to have the drawable dither its colors when drawn to a
276     * device with fewer than 8-bits per color component.
277     *
278     * @see android.graphics.Paint#setDither(boolean);
279     * @deprecated This property is ignored.
280     */
281    @Deprecated
282    public void setDither(boolean dither) {}
283
284    /**
285     * Set to true to have the drawable filter its bitmaps with bilinear
286     * sampling when they are scaled or rotated.
287     *
288     * <p>This can improve appearance when bitmaps are rotated. If the drawable
289     * does not use bitmaps, this call is ignored.</p>
290     *
291     * @see #isFilterBitmap()
292     * @see android.graphics.Paint#setFilterBitmap(boolean);
293     */
294    public void setFilterBitmap(boolean filter) {}
295
296    /**
297     * @return whether this drawable filters its bitmaps
298     * @see #setFilterBitmap(boolean)
299     */
300    public boolean isFilterBitmap() {
301        return false;
302    }
303
304    /**
305     * Implement this interface if you want to create an animated drawable that
306     * extends {@link android.graphics.drawable.Drawable Drawable}.
307     * Upon retrieving a drawable, use
308     * {@link Drawable#setCallback(android.graphics.drawable.Drawable.Callback)}
309     * to supply your implementation of the interface to the drawable; it uses
310     * this interface to schedule and execute animation changes.
311     */
312    public interface Callback {
313        /**
314         * Called when the drawable needs to be redrawn.  A view at this point
315         * should invalidate itself (or at least the part of itself where the
316         * drawable appears).
317         *
318         * @param who The drawable that is requesting the update.
319         */
320        void invalidateDrawable(@NonNull Drawable who);
321
322        /**
323         * A Drawable can call this to schedule the next frame of its
324         * animation.  An implementation can generally simply call
325         * {@link android.os.Handler#postAtTime(Runnable, Object, long)} with
326         * the parameters <var>(what, who, when)</var> to perform the
327         * scheduling.
328         *
329         * @param who The drawable being scheduled.
330         * @param what The action to execute.
331         * @param when The time (in milliseconds) to run.  The timebase is
332         *             {@link android.os.SystemClock#uptimeMillis}
333         */
334        void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when);
335
336        /**
337         * A Drawable can call this to unschedule an action previously
338         * scheduled with {@link #scheduleDrawable}.  An implementation can
339         * generally simply call
340         * {@link android.os.Handler#removeCallbacks(Runnable, Object)} with
341         * the parameters <var>(what, who)</var> to unschedule the drawable.
342         *
343         * @param who The drawable being unscheduled.
344         * @param what The action being unscheduled.
345         */
346        void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what);
347    }
348
349    /**
350     * Bind a {@link Callback} object to this Drawable.  Required for clients
351     * that want to support animated drawables.
352     *
353     * @param cb The client's Callback implementation.
354     *
355     * @see #getCallback()
356     */
357    public final void setCallback(Callback cb) {
358        mCallback = new WeakReference<Callback>(cb);
359    }
360
361    /**
362     * Return the current {@link Callback} implementation attached to this
363     * Drawable.
364     *
365     * @return A {@link Callback} instance or null if no callback was set.
366     *
367     * @see #setCallback(android.graphics.drawable.Drawable.Callback)
368     */
369    public Callback getCallback() {
370        if (mCallback != null) {
371            return mCallback.get();
372        }
373        return null;
374    }
375
376    /**
377     * Use the current {@link Callback} implementation to have this Drawable
378     * redrawn.  Does nothing if there is no Callback attached to the
379     * Drawable.
380     *
381     * @see Callback#invalidateDrawable
382     * @see #getCallback()
383     * @see #setCallback(android.graphics.drawable.Drawable.Callback)
384     */
385    public void invalidateSelf() {
386        final Callback callback = getCallback();
387        if (callback != null) {
388            callback.invalidateDrawable(this);
389        }
390    }
391
392    /**
393     * Use the current {@link Callback} implementation to have this Drawable
394     * scheduled.  Does nothing if there is no Callback attached to the
395     * Drawable.
396     *
397     * @param what The action being scheduled.
398     * @param when The time (in milliseconds) to run.
399     *
400     * @see Callback#scheduleDrawable
401     */
402    public void scheduleSelf(Runnable what, long when) {
403        final Callback callback = getCallback();
404        if (callback != null) {
405            callback.scheduleDrawable(this, what, when);
406        }
407    }
408
409    /**
410     * Use the current {@link Callback} implementation to have this Drawable
411     * unscheduled.  Does nothing if there is no Callback attached to the
412     * Drawable.
413     *
414     * @param what The runnable that you no longer want called.
415     *
416     * @see Callback#unscheduleDrawable
417     */
418    public void unscheduleSelf(Runnable what) {
419        final Callback callback = getCallback();
420        if (callback != null) {
421            callback.unscheduleDrawable(this, what);
422        }
423    }
424
425    /**
426     * Returns the resolved layout direction for this Drawable.
427     *
428     * @return One of {@link android.view.View#LAYOUT_DIRECTION_LTR},
429     *         {@link android.view.View#LAYOUT_DIRECTION_RTL}
430     * @see #setLayoutDirection(int)
431     */
432    public int getLayoutDirection() {
433        return mLayoutDirection;
434    }
435
436    /**
437     * Set the layout direction for this drawable. Should be a resolved
438     * layout direction, as the Drawable has no capacity to do the resolution on
439     * its own.
440     *
441     * @param layoutDirection the resolved layout direction for the drawable,
442     *                        either {@link android.view.View#LAYOUT_DIRECTION_LTR}
443     *                        or {@link android.view.View#LAYOUT_DIRECTION_RTL}
444     * @return {@code true} if the layout direction change has caused the
445     *         appearance of the drawable to change such that it needs to be
446     *         re-drawn, {@code false} otherwise
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 {@code true} if the layout direction change has caused the
462     *         appearance of the drawable to change such that it needs to be
463     *         re-drawn, {@code false} otherwise
464     * @see #setLayoutDirection(int)
465     */
466    public boolean onLayoutDirectionChanged(@View.ResolvedLayoutDir int layoutDirection) {
467        return false;
468    }
469
470    /**
471     * Specify an alpha value for the drawable. 0 means fully transparent, and
472     * 255 means fully opaque.
473     */
474    public abstract void setAlpha(int alpha);
475
476    /**
477     * Gets the current alpha value for the drawable. 0 means fully transparent,
478     * 255 means fully opaque. This method is implemented by
479     * Drawable subclasses and the value returned is specific to how that class treats alpha.
480     * The default return value is 255 if the class does not override this method to return a value
481     * specific to its use of alpha.
482     */
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(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 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(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(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 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 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(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 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 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 int resolveOpacity(int op1, int op2) {
864        if (op1 == op2) {
865            return op1;
866        }
867        if (op1 == PixelFormat.UNKNOWN || op2 == PixelFormat.UNKNOWN) {
868            return PixelFormat.UNKNOWN;
869        }
870        if (op1 == PixelFormat.TRANSLUCENT || op2 == PixelFormat.TRANSLUCENT) {
871            return PixelFormat.TRANSLUCENT;
872        }
873        if (op1 == PixelFormat.TRANSPARENT || op2 == PixelFormat.TRANSPARENT) {
874            return PixelFormat.TRANSPARENT;
875        }
876        return PixelFormat.OPAQUE;
877    }
878
879    /**
880     * Returns a Region representing the part of the Drawable that is completely
881     * transparent.  This can be used to perform drawing operations, identifying
882     * which parts of the target will not change when rendering the Drawable.
883     * The default implementation returns null, indicating no transparent
884     * region; subclasses can optionally override this to return an actual
885     * Region if they want to supply this optimization information, but it is
886     * not required that they do so.
887     *
888     * @return Returns null if the Drawables has no transparent region to
889     * report, else a Region holding the parts of the Drawable's bounds that
890     * are transparent.
891     */
892    public Region getTransparentRegion() {
893        return null;
894    }
895
896    /**
897     * Override this in your subclass to change appearance if you recognize the
898     * specified state.
899     *
900     * @return Returns true if the state change has caused the appearance of
901     * the Drawable to change (that is, it needs to be drawn), else false
902     * if it looks the same and there is no need to redraw it since its
903     * last state.
904     */
905    protected boolean onStateChange(int[] state) { return false; }
906    /** Override this in your subclass to change appearance if you vary based
907     *  on level.
908     * @return Returns true if the level change has caused the appearance of
909     * the Drawable to change (that is, it needs to be drawn), else false
910     * if it looks the same and there is no need to redraw it since its
911     * last level.
912     */
913    protected boolean onLevelChange(int level) { return false; }
914    /**
915     * Override this in your subclass to change appearance if you vary based on
916     * the bounds.
917     */
918    protected void onBoundsChange(Rect bounds) {}
919
920    /**
921     * Returns the drawable's intrinsic width.
922     * <p>
923     * Intrinsic width is the width at which the drawable would like to be laid
924     * out, including any inherent padding. If the drawable has no intrinsic
925     * width, such as a solid color, this method returns -1.
926     *
927     * @return the intrinsic width, or -1 if no intrinsic width
928     */
929    public int getIntrinsicWidth() {
930        return -1;
931    }
932
933    /**
934     * Returns the drawable's intrinsic height.
935     * <p>
936     * Intrinsic height is the height at which the drawable would like to be
937     * laid out, including any inherent padding. If the drawable has no
938     * intrinsic height, such as a solid color, this method returns -1.
939     *
940     * @return the intrinsic height, or -1 if no intrinsic height
941     */
942    public int getIntrinsicHeight() {
943        return -1;
944    }
945
946    /**
947     * Returns the minimum width suggested by this Drawable. If a View uses this
948     * Drawable as a background, it is suggested that the View use at least this
949     * value for its width. (There will be some scenarios where this will not be
950     * possible.) This value should INCLUDE any padding.
951     *
952     * @return The minimum width suggested by this Drawable. If this Drawable
953     *         doesn't have a suggested minimum width, 0 is returned.
954     */
955    public int getMinimumWidth() {
956        final int intrinsicWidth = getIntrinsicWidth();
957        return intrinsicWidth > 0 ? intrinsicWidth : 0;
958    }
959
960    /**
961     * Returns the minimum height suggested by this Drawable. If a View uses this
962     * Drawable as a background, it is suggested that the View use at least this
963     * value for its height. (There will be some scenarios where this will not be
964     * possible.) This value should INCLUDE any padding.
965     *
966     * @return The minimum height suggested by this Drawable. If this Drawable
967     *         doesn't have a suggested minimum height, 0 is returned.
968     */
969    public int getMinimumHeight() {
970        final int intrinsicHeight = getIntrinsicHeight();
971        return intrinsicHeight > 0 ? intrinsicHeight : 0;
972    }
973
974    /**
975     * Return in padding the insets suggested by this Drawable for placing
976     * content inside the drawable's bounds. Positive values move toward the
977     * center of the Drawable (set Rect.inset).
978     *
979     * @return true if this drawable actually has a padding, else false. When false is returned,
980     * the padding is always set to 0.
981     */
982    public boolean getPadding(@NonNull Rect padding) {
983        padding.set(0, 0, 0, 0);
984        return false;
985    }
986
987    /**
988     * Return in insets the layout insets suggested by this Drawable for use with alignment
989     * operations during layout.
990     *
991     * @hide
992     */
993    public Insets getOpticalInsets() {
994        return Insets.NONE;
995    }
996
997    /**
998     * Called to get the drawable to populate the Outline that defines its drawing area.
999     * <p>
1000     * This method is called by the default {@link android.view.ViewOutlineProvider} to define
1001     * the outline of the View.
1002     * <p>
1003     * The default behavior defines the outline to be the bounding rectangle of 0 alpha.
1004     * Subclasses that wish to convey a different shape or alpha value must override this method.
1005     *
1006     * @see android.view.View#setOutlineProvider(android.view.ViewOutlineProvider)
1007     */
1008    public void getOutline(@NonNull Outline outline) {
1009        outline.setRect(getBounds());
1010        outline.setAlpha(0);
1011    }
1012
1013    /**
1014     * Make this drawable mutable. This operation cannot be reversed. A mutable
1015     * drawable is guaranteed to not share its state with any other drawable.
1016     * This is especially useful when you need to modify properties of drawables
1017     * loaded from resources. By default, all drawables instances loaded from
1018     * the same resource share a common state; if you modify the state of one
1019     * instance, all the other instances will receive the same modification.
1020     *
1021     * Calling this method on a mutable Drawable will have no effect.
1022     *
1023     * @return This drawable.
1024     * @see ConstantState
1025     * @see #getConstantState()
1026     */
1027    public Drawable mutate() {
1028        return this;
1029    }
1030
1031    /**
1032     * Clears the mutated state, allowing this drawable to be cached and
1033     * mutated again.
1034     * <p>
1035     * This is hidden because only framework drawables can be cached, so
1036     * custom drawables don't need to support constant state, mutate(), or
1037     * clearMutated().
1038     *
1039     * @hide
1040     */
1041    public void clearMutated() {
1042        // Default implementation is no-op.
1043    }
1044
1045    /**
1046     * Create a drawable from an inputstream
1047     */
1048    public static Drawable createFromStream(InputStream is, String srcName) {
1049        Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, srcName != null ? srcName : "Unknown drawable");
1050        try {
1051            return createFromResourceStream(null, null, is, srcName);
1052        } finally {
1053            Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
1054        }
1055    }
1056
1057    /**
1058     * Create a drawable from an inputstream, using the given resources and
1059     * value to determine density information.
1060     */
1061    public static Drawable createFromResourceStream(Resources res, TypedValue value,
1062            InputStream is, String srcName) {
1063        Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, srcName != null ? srcName : "Unknown drawable");
1064        try {
1065            return createFromResourceStream(res, value, is, srcName, null);
1066        } finally {
1067            Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
1068        }
1069    }
1070
1071    /**
1072     * Create a drawable from an inputstream, using the given resources and
1073     * value to determine density information.
1074     */
1075    public static Drawable createFromResourceStream(Resources res, TypedValue value,
1076            InputStream is, String srcName, BitmapFactory.Options opts) {
1077        if (is == null) {
1078            return null;
1079        }
1080
1081        /*  ugh. The decodeStream contract is that we have already allocated
1082            the pad rect, but if the bitmap does not had a ninepatch chunk,
1083            then the pad will be ignored. If we could change this to lazily
1084            alloc/assign the rect, we could avoid the GC churn of making new
1085            Rects only to drop them on the floor.
1086        */
1087        Rect pad = new Rect();
1088
1089        // Special stuff for compatibility mode: if the target density is not
1090        // the same as the display density, but the resource -is- the same as
1091        // the display density, then don't scale it down to the target density.
1092        // This allows us to load the system's density-correct resources into
1093        // an application in compatibility mode, without scaling those down
1094        // to the compatibility density only to have them scaled back up when
1095        // drawn to the screen.
1096        if (opts == null) opts = new BitmapFactory.Options();
1097        opts.inScreenDensity = Drawable.resolveDensity(res, 0);
1098        Bitmap  bm = BitmapFactory.decodeResourceStream(res, value, is, pad, opts);
1099        if (bm != null) {
1100            byte[] np = bm.getNinePatchChunk();
1101            if (np == null || !NinePatch.isNinePatchChunk(np)) {
1102                np = null;
1103                pad = null;
1104            }
1105
1106            final Rect opticalInsets = new Rect();
1107            bm.getOpticalInsets(opticalInsets);
1108            return drawableFromBitmap(res, bm, np, pad, opticalInsets, srcName);
1109        }
1110        return null;
1111    }
1112
1113    /**
1114     * Create a drawable from an XML document. For more information on how to
1115     * create resources in XML, see
1116     * <a href="{@docRoot}guide/topics/resources/drawable-resource.html">Drawable Resources</a>.
1117     */
1118    public static Drawable createFromXml(Resources r, XmlPullParser parser)
1119            throws XmlPullParserException, IOException {
1120        return createFromXml(r, parser, null);
1121    }
1122
1123    /**
1124     * Create a drawable from an XML document using an optional {@link Theme}.
1125     * For more information on how to create resources in XML, see
1126     * <a href="{@docRoot}guide/topics/resources/drawable-resource.html">Drawable Resources</a>.
1127     */
1128    public static Drawable createFromXml(Resources r, XmlPullParser parser, Theme theme)
1129            throws XmlPullParserException, IOException {
1130        AttributeSet attrs = Xml.asAttributeSet(parser);
1131
1132        int type;
1133        while ((type=parser.next()) != XmlPullParser.START_TAG &&
1134                type != XmlPullParser.END_DOCUMENT) {
1135            // Empty loop
1136        }
1137
1138        if (type != XmlPullParser.START_TAG) {
1139            throw new XmlPullParserException("No start tag found");
1140        }
1141
1142        Drawable drawable = createFromXmlInner(r, parser, attrs, theme);
1143
1144        if (drawable == null) {
1145            throw new RuntimeException("Unknown initial tag: " + parser.getName());
1146        }
1147
1148        return drawable;
1149    }
1150
1151    /**
1152     * Create from inside an XML document.  Called on a parser positioned at
1153     * a tag in an XML document, tries to create a Drawable from that tag.
1154     * Returns null if the tag is not a valid drawable.
1155     */
1156    public static Drawable createFromXmlInner(Resources r, XmlPullParser parser, AttributeSet attrs)
1157            throws XmlPullParserException, IOException {
1158        return createFromXmlInner(r, parser, attrs, null);
1159    }
1160
1161    /**
1162     * Create a drawable from inside an XML document using an optional
1163     * {@link Theme}. Called on a parser positioned at a tag in an XML
1164     * document, tries to create a Drawable from that tag. Returns {@code null}
1165     * if the tag is not a valid drawable.
1166     */
1167    public static Drawable createFromXmlInner(Resources r, XmlPullParser parser, AttributeSet attrs,
1168            Theme theme) throws XmlPullParserException, IOException {
1169        return r.getDrawableInflater().inflateFromXml(parser.getName(), parser, attrs, theme);
1170    }
1171
1172    /**
1173     * Create a drawable from file path name.
1174     */
1175    public static Drawable createFromPath(String pathName) {
1176        if (pathName == null) {
1177            return null;
1178        }
1179
1180        Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, pathName);
1181        try {
1182            Bitmap bm = BitmapFactory.decodeFile(pathName);
1183            if (bm != null) {
1184                return drawableFromBitmap(null, bm, null, null, null, pathName);
1185            }
1186        } finally {
1187            Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
1188        }
1189
1190        return null;
1191    }
1192
1193    /**
1194     * Inflate this Drawable from an XML resource. Does not apply a theme.
1195     *
1196     * @see #inflate(Resources, XmlPullParser, AttributeSet, Theme)
1197     */
1198    public void inflate(@NonNull Resources r, @NonNull XmlPullParser parser,
1199            @NonNull AttributeSet attrs) throws XmlPullParserException, IOException {
1200        inflate(r, parser, attrs, null);
1201    }
1202
1203    /**
1204     * Inflate this Drawable from an XML resource optionally styled by a theme.
1205     * This can't be called more than once for each Drawable. Note that framework may have called
1206     * this once to create the Drawable instance from XML resource.
1207     *
1208     * @param r Resources used to resolve attribute values
1209     * @param parser XML parser from which to inflate this Drawable
1210     * @param attrs Base set of attribute values
1211     * @param theme Theme to apply, may be null
1212     * @throws XmlPullParserException
1213     * @throws IOException
1214     */
1215    public void inflate(@NonNull Resources r, @NonNull XmlPullParser parser,
1216            @NonNull AttributeSet attrs, @Nullable Theme theme)
1217            throws XmlPullParserException, IOException {
1218        final TypedArray a = obtainAttributes(r, theme, attrs, R.styleable.Drawable);
1219        mVisible = a.getBoolean(R.styleable.Drawable_visible, mVisible);
1220        a.recycle();
1221    }
1222
1223    /**
1224     * Inflate a Drawable from an XML resource.
1225     *
1226     * @throws XmlPullParserException
1227     * @throws IOException
1228     */
1229    void inflateWithAttributes(@NonNull Resources r, @NonNull XmlPullParser parser,
1230            @NonNull TypedArray attrs, int visibleAttr) throws XmlPullParserException, IOException {
1231        mVisible = attrs.getBoolean(visibleAttr, mVisible);
1232    }
1233
1234    /**
1235     * This abstract class is used by {@link Drawable}s to store shared constant state and data
1236     * between Drawables. {@link BitmapDrawable}s created from the same resource will for instance
1237     * share a unique bitmap stored in their ConstantState.
1238     *
1239     * <p>
1240     * {@link #newDrawable(Resources)} can be used as a factory to create new Drawable instances
1241     * from this ConstantState.
1242     * </p>
1243     *
1244     * Use {@link Drawable#getConstantState()} to retrieve the ConstantState of a Drawable. Calling
1245     * {@link Drawable#mutate()} on a Drawable should typically create a new ConstantState for that
1246     * Drawable.
1247     */
1248    public static abstract class ConstantState {
1249        /**
1250         * Creates a new Drawable instance from its constant state.
1251         * <p>
1252         * <strong>Note:</strong> Using this method means density-dependent
1253         * properties, such as pixel dimensions or bitmap images, will not be
1254         * updated to match the density of the target display. To ensure
1255         * correct scaling, use {@link #newDrawable(Resources)} instead to
1256         * provide an appropriate Resources object.
1257         *
1258         * @return a new drawable object based on this constant state
1259         * @see {@link #newDrawable(Resources)}
1260         */
1261        @NonNull
1262        public abstract Drawable newDrawable();
1263
1264        /**
1265         * Creates a new Drawable instance from its constant state using the
1266         * specified resources. This method should be implemented for drawables
1267         * that have density-dependent properties.
1268         * <p>
1269         * The default implementation for this method calls through to
1270         * {@link #newDrawable()}.
1271         *
1272         * @param res the resources of the context in which the drawable will
1273         *            be displayed
1274         * @return a new drawable object based on this constant state
1275         */
1276        @NonNull
1277        public Drawable newDrawable(@Nullable Resources res) {
1278            return newDrawable();
1279        }
1280
1281        /**
1282         * Creates a new Drawable instance from its constant state using the
1283         * specified resources and theme. This method should be implemented for
1284         * drawables that have theme-dependent properties.
1285         * <p>
1286         * The default implementation for this method calls through to
1287         * {@link #newDrawable(Resources)}.
1288         *
1289         * @param res the resources of the context in which the drawable will
1290         *            be displayed
1291         * @param theme the theme of the context in which the drawable will be
1292         *              displayed
1293         * @return a new drawable object based on this constant state
1294         */
1295        @NonNull
1296        public Drawable newDrawable(@Nullable Resources res, @Nullable Theme theme) {
1297            return newDrawable(res);
1298        }
1299
1300        /**
1301         * Return a bit mask of configuration changes that will impact
1302         * this drawable (and thus require completely reloading it).
1303         */
1304        public abstract @Config int getChangingConfigurations();
1305
1306        /**
1307         * @return Total pixel count
1308         * @hide
1309         */
1310        public int addAtlasableBitmaps(Collection<Bitmap> atlasList) {
1311            return 0;
1312        }
1313
1314        /** @hide */
1315        protected final boolean isAtlasable(Bitmap bitmap) {
1316            return bitmap != null && bitmap.getConfig() == Bitmap.Config.ARGB_8888;
1317        }
1318
1319        /**
1320         * Return whether this constant state can have a theme applied.
1321         */
1322        public boolean canApplyTheme() {
1323            return false;
1324        }
1325    }
1326
1327    /**
1328     * Return a {@link ConstantState} instance that holds the shared state of this Drawable.
1329     *
1330     * @return The ConstantState associated to that Drawable.
1331     * @see ConstantState
1332     * @see Drawable#mutate()
1333     */
1334    public ConstantState getConstantState() {
1335        return null;
1336    }
1337
1338    private static Drawable drawableFromBitmap(Resources res, Bitmap bm, byte[] np,
1339            Rect pad, Rect layoutBounds, String srcName) {
1340
1341        if (np != null) {
1342            return new NinePatchDrawable(res, bm, np, pad, layoutBounds, srcName);
1343        }
1344
1345        return new BitmapDrawable(res, bm);
1346    }
1347
1348    /**
1349     * Ensures the tint filter is consistent with the current tint color and
1350     * mode.
1351     */
1352    PorterDuffColorFilter updateTintFilter(PorterDuffColorFilter tintFilter, ColorStateList tint,
1353            PorterDuff.Mode tintMode) {
1354        if (tint == null || tintMode == null) {
1355            return null;
1356        }
1357
1358        final int color = tint.getColorForState(getState(), Color.TRANSPARENT);
1359        if (tintFilter == null) {
1360            return new PorterDuffColorFilter(color, tintMode);
1361        }
1362
1363        tintFilter.setColor(color);
1364        tintFilter.setMode(tintMode);
1365        return tintFilter;
1366    }
1367
1368    /**
1369     * Obtains styled attributes from the theme, if available, or unstyled
1370     * resources if the theme is null.
1371     */
1372    static TypedArray obtainAttributes(
1373            Resources res, Theme theme, AttributeSet set, int[] attrs) {
1374        if (theme == null) {
1375            return res.obtainAttributes(set, attrs);
1376        }
1377        return theme.obtainStyledAttributes(set, attrs, 0, 0);
1378    }
1379
1380    /**
1381     * Scales a floating-point pixel value from the source density to the
1382     * target density.
1383     *
1384     * @param pixels the pixel value for use in source density
1385     * @param sourceDensity the source density
1386     * @param targetDensity the target density
1387     * @return the scaled pixel value for use in target density
1388     */
1389    static float scaleFromDensity(float pixels, int sourceDensity, int targetDensity) {
1390        return pixels * targetDensity / sourceDensity;
1391    }
1392
1393    /**
1394     * Scales a pixel value from the source density to the target density,
1395     * optionally handling the resulting pixel value as a size rather than an
1396     * offset.
1397     * <p>
1398     * A size conversion involves rounding the base value and ensuring that
1399     * a non-zero base value is at least one pixel in size.
1400     * <p>
1401     * An offset conversion involves simply truncating the base value to an
1402     * integer.
1403     *
1404     * @param pixels the pixel value for use in source density
1405     * @param sourceDensity the source density
1406     * @param targetDensity the target density
1407     * @param isSize {@code true} to handle the resulting scaled value as a
1408     *               size, or {@code false} to handle it as an offset
1409     * @return the scaled pixel value for use in target density
1410     */
1411    static int scaleFromDensity(
1412            int pixels, int sourceDensity, int targetDensity, boolean isSize) {
1413        if (pixels == 0 || sourceDensity == targetDensity) {
1414            return pixels;
1415        }
1416
1417        final float result = pixels * targetDensity / (float) sourceDensity;
1418        if (!isSize) {
1419            return (int) result;
1420        }
1421
1422        final int rounded = Math.round(result);
1423        if (rounded != 0) {
1424            return rounded;
1425        } else if (pixels == 0) {
1426            return 0;
1427        } else if (pixels > 0) {
1428            return 1;
1429        } else {
1430            return -1;
1431        }
1432    }
1433
1434    static int resolveDensity(@Nullable Resources r, int parentDensity) {
1435        final int densityDpi = r == null ? parentDensity : r.getDisplayMetrics().densityDpi;
1436        return densityDpi == 0 ? DisplayMetrics.DENSITY_DEFAULT : densityDpi;
1437    }
1438
1439    /**
1440     * Re-throws an exception as a {@link RuntimeException} with an empty stack
1441     * trace to avoid cluttering the log. The original exception's stack trace
1442     * will still be included.
1443     *
1444     * @param cause the exception to re-throw
1445     * @throws RuntimeException
1446     */
1447    static void rethrowAsRuntimeException(Exception cause) throws RuntimeException {
1448        final RuntimeException e = new RuntimeException(cause);
1449        e.setStackTrace(new StackTraceElement[0]);
1450        throw e;
1451    }
1452
1453    /**
1454     * Parses a {@link android.graphics.PorterDuff.Mode} from a tintMode
1455     * attribute's enum value.
1456     *
1457     * @hide
1458     */
1459    public static PorterDuff.Mode parseTintMode(int value, Mode defaultMode) {
1460        switch (value) {
1461            case 3: return Mode.SRC_OVER;
1462            case 5: return Mode.SRC_IN;
1463            case 9: return Mode.SRC_ATOP;
1464            case 14: return Mode.MULTIPLY;
1465            case 15: return Mode.SCREEN;
1466            case 16: return Mode.ADD;
1467            default: return defaultMode;
1468        }
1469    }
1470}
1471
1472