DrawableUtils.java revision 64dbe1d454f1190b3cd8426d09b9119949a10709
1/*
2 * Copyright (C) 2014 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.support.v7.widget;
18
19import android.graphics.PorterDuff;
20import android.graphics.Rect;
21import android.graphics.drawable.Drawable;
22import android.graphics.drawable.DrawableContainer;
23import android.graphics.drawable.GradientDrawable;
24import android.graphics.drawable.InsetDrawable;
25import android.graphics.drawable.LayerDrawable;
26import android.graphics.drawable.ScaleDrawable;
27import android.graphics.drawable.StateListDrawable;
28import android.os.Build;
29import android.support.annotation.NonNull;
30import android.support.v4.graphics.drawable.DrawableCompat;
31import android.util.Log;
32
33import java.lang.reflect.Field;
34import java.lang.reflect.Method;
35
36/** @hide */
37public class DrawableUtils {
38
39    private static final String TAG = "DrawableUtils";
40
41    public static final Rect INSETS_NONE = new Rect();
42    private static Class<?> sInsetsClazz;
43
44    private static final String VECTOR_DRAWABLE_CLAZZ_NAME
45            = "android.graphics.drawable.VectorDrawable";
46
47    static {
48        if (Build.VERSION.SDK_INT >= 18) {
49            try {
50                sInsetsClazz = Class.forName("android.graphics.Insets");
51            } catch (ClassNotFoundException e) {
52                // Oh well...
53            }
54        }
55    }
56
57    private DrawableUtils() {}
58
59    /**
60     * Allows us to get the optical insets for a {@link Drawable}. Since this is hidden we need to
61     * use reflection. Since the {@code Insets} class is hidden also, we return a Rect instead.
62     */
63    public static Rect getOpticalBounds(Drawable drawable) {
64        if (sInsetsClazz != null) {
65            try {
66                // If the Drawable is wrapped, we need to manually unwrap it and process
67                // the wrapped drawable.
68                drawable = DrawableCompat.unwrap(drawable);
69
70                final Method getOpticalInsetsMethod = drawable.getClass()
71                        .getMethod("getOpticalInsets");
72                final Object insets = getOpticalInsetsMethod.invoke(drawable);
73
74                if (insets != null) {
75                    // If the drawable has some optical insets, let's copy them into a Rect
76                    final Rect result = new Rect();
77
78                    for (Field field : sInsetsClazz.getFields()) {
79                        switch (field.getName()) {
80                            case "left":
81                               result.left = field.getInt(insets);
82                                break;
83                            case "top":
84                                result.top = field.getInt(insets);
85                                break;
86                            case "right":
87                                result.right = field.getInt(insets);
88                                break;
89                            case "bottom":
90                                result.bottom = field.getInt(insets);
91                                break;
92                        }
93                    }
94                    return result;
95                }
96            } catch (Exception e) {
97                // Eugh, we hit some kind of reflection issue...
98                Log.e(TAG, "Couldn't obtain the optical insets. Ignoring.");
99            }
100        }
101
102        // If we reach here, either we're running on a device pre-v18, the Drawable didn't have
103        // any optical insets, or a reflection issue, so we'll just return an empty rect
104        return INSETS_NONE;
105    }
106
107    /**
108     * Attempt the fix any issues in the given drawable, usually caused by platform bugs in the
109     * implementation. This method should be call after retrieval from
110     * {@link android.content.res.Resources} or a {@link android.content.res.TypedArray}.
111     */
112    static void fixDrawable(@NonNull final Drawable drawable) {
113        if (Build.VERSION.SDK_INT == 21
114                && VECTOR_DRAWABLE_CLAZZ_NAME.equals(drawable.getClass().getName())) {
115            fixVectorDrawableTinting(drawable);
116        }
117    }
118
119    /**
120     * Some drawable implementations have problems with mutation. This method returns false if
121     * there is a known issue in the given drawable's implementation.
122     */
123    public static boolean canSafelyMutateDrawable(@NonNull Drawable drawable) {
124        if (Build.VERSION.SDK_INT < 15 && drawable instanceof InsetDrawable) {
125            return false;
126        }  else if (Build.VERSION.SDK_INT < 15 && drawable instanceof GradientDrawable) {
127            // GradientDrawable has a bug pre-ICS which results in mutate() resulting
128            // in loss of color
129            return false;
130        } else if (Build.VERSION.SDK_INT < 17 && drawable instanceof LayerDrawable) {
131            return false;
132        }
133
134        if (drawable instanceof DrawableContainer) {
135            // If we have a DrawableContainer, let's traverse it's child array
136            final Drawable.ConstantState state = drawable.getConstantState();
137            if (state instanceof DrawableContainer.DrawableContainerState) {
138                final DrawableContainer.DrawableContainerState containerState =
139                        (DrawableContainer.DrawableContainerState) state;
140                for (final Drawable child : containerState.getChildren()) {
141                    if (!canSafelyMutateDrawable(child)) {
142                        return false;
143                    }
144                }
145            }
146        } else if (drawable instanceof android.support.v4.graphics.drawable.DrawableWrapper) {
147            return canSafelyMutateDrawable(
148                    ((android.support.v4.graphics.drawable.DrawableWrapper) drawable)
149                            .getWrappedDrawable());
150        } else if (drawable instanceof android.support.v7.graphics.drawable.DrawableWrapper) {
151            return canSafelyMutateDrawable(
152                    ((android.support.v7.graphics.drawable.DrawableWrapper) drawable)
153                            .getWrappedDrawable());
154        } else if (drawable instanceof ScaleDrawable) {
155            return canSafelyMutateDrawable(((ScaleDrawable) drawable).getDrawable());
156        }
157
158        return true;
159    }
160
161    /**
162     * VectorDrawable has an issue on API 21 where it sometimes doesn't create its tint filter.
163     * Fixed by toggling it's state to force a filter creation.
164     */
165    private static void fixVectorDrawableTinting(final Drawable drawable) {
166        final int[] originalState = drawable.getState();
167        if (originalState == null || originalState.length == 0) {
168            // The drawable doesn't have a state, so set it to be checked
169            drawable.setState(ThemeUtils.CHECKED_STATE_SET);
170        } else {
171            // Else the drawable does have a state, so clear it
172            drawable.setState(ThemeUtils.EMPTY_STATE_SET);
173        }
174        // Now set the original state
175        drawable.setState(originalState);
176    }
177
178    static PorterDuff.Mode parseTintMode(int value, PorterDuff.Mode defaultMode) {
179        switch (value) {
180            case 3: return PorterDuff.Mode.SRC_OVER;
181            case 5: return PorterDuff.Mode.SRC_IN;
182            case 9: return PorterDuff.Mode.SRC_ATOP;
183            case 14: return PorterDuff.Mode.MULTIPLY;
184            case 15: return PorterDuff.Mode.SCREEN;
185            case 16: return Build.VERSION.SDK_INT >= 11
186                    ? PorterDuff.Mode.valueOf("ADD")
187                    : defaultMode;
188            default: return defaultMode;
189        }
190    }
191
192}
193