Resources.java revision 5c64b957dd710cce27134cd480e0b83563c50d7f
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.content.res;
18
19import android.animation.Animator;
20import android.animation.StateListAnimator;
21import android.annotation.AnimRes;
22import android.annotation.AnyRes;
23import android.annotation.ArrayRes;
24import android.annotation.AttrRes;
25import android.annotation.BoolRes;
26import android.annotation.ColorInt;
27import android.annotation.ColorRes;
28import android.annotation.DimenRes;
29import android.annotation.DrawableRes;
30import android.annotation.FractionRes;
31import android.annotation.IntegerRes;
32import android.annotation.LayoutRes;
33import android.annotation.NonNull;
34import android.annotation.Nullable;
35import android.annotation.PluralsRes;
36import android.annotation.RawRes;
37import android.annotation.StringRes;
38import android.annotation.StyleRes;
39import android.annotation.StyleableRes;
40import android.annotation.XmlRes;
41import android.content.pm.ActivityInfo;
42import android.graphics.Movie;
43import android.graphics.drawable.ColorDrawable;
44import android.graphics.drawable.Drawable;
45import android.graphics.drawable.Drawable.ConstantState;
46import android.graphics.drawable.DrawableInflater;
47import android.icu.text.PluralRules;
48import android.os.Build;
49import android.os.Bundle;
50import android.os.Trace;
51import android.util.AttributeSet;
52import android.util.DisplayMetrics;
53import android.util.LocaleList;
54import android.util.Log;
55import android.util.LongSparseArray;
56import android.util.Pools.SynchronizedPool;
57import android.util.Slog;
58import android.util.TypedValue;
59import android.util.Xml;
60import android.view.ViewDebug;
61import android.view.ViewHierarchyEncoder;
62
63import com.android.internal.util.GrowingArrayUtils;
64import com.android.internal.util.XmlUtils;
65
66import org.xmlpull.v1.XmlPullParser;
67import org.xmlpull.v1.XmlPullParserException;
68
69import java.io.IOException;
70import java.io.InputStream;
71import java.util.Arrays;
72import java.util.Locale;
73
74/**
75 * Class for accessing an application's resources.  This sits on top of the
76 * asset manager of the application (accessible through {@link #getAssets}) and
77 * provides a high-level API for getting typed data from the assets.
78 *
79 * <p>The Android resource system keeps track of all non-code assets associated with an
80 * application. You can use this class to access your application's resources. You can generally
81 * acquire the {@link android.content.res.Resources} instance associated with your application
82 * with {@link android.content.Context#getResources getResources()}.</p>
83 *
84 * <p>The Android SDK tools compile your application's resources into the application binary
85 * at build time.  To use a resource, you must install it correctly in the source tree (inside
86 * your project's {@code res/} directory) and build your application.  As part of the build
87 * process, the SDK tools generate symbols for each resource, which you can use in your application
88 * code to access the resources.</p>
89 *
90 * <p>Using application resources makes it easy to update various characteristics of your
91 * application without modifying code, and&mdash;by providing sets of alternative
92 * resources&mdash;enables you to optimize your application for a variety of device configurations
93 * (such as for different languages and screen sizes). This is an important aspect of developing
94 * Android applications that are compatible on different types of devices.</p>
95 *
96 * <p>For more information about using resources, see the documentation about <a
97 * href="{@docRoot}guide/topics/resources/index.html">Application Resources</a>.</p>
98 */
99public class Resources {
100    static final String TAG = "Resources";
101
102    private static final boolean DEBUG_LOAD = false;
103    private static final boolean DEBUG_CONFIG = false;
104    private static final boolean TRACE_FOR_PRELOAD = false;
105    private static final boolean TRACE_FOR_MISS_PRELOAD = false;
106
107    private static final int LAYOUT_DIR_CONFIG = ActivityInfo.activityInfoConfigToNative(
108            ActivityInfo.CONFIG_LAYOUT_DIRECTION);
109
110    private static final int ID_OTHER = 0x01000004;
111
112    private static final Object sSync = new Object();
113
114    // Information about preloaded resources.  Note that they are not
115    // protected by a lock, because while preloading in zygote we are all
116    // single-threaded, and after that these are immutable.
117    private static final LongSparseArray<ConstantState>[] sPreloadedDrawables;
118    private static final LongSparseArray<ConstantState> sPreloadedColorDrawables
119            = new LongSparseArray<>();
120    private static final LongSparseArray<android.content.res.ConstantState<ComplexColor>>
121            sPreloadedComplexColors = new LongSparseArray<>();
122
123    /** Size of the cyclical cache used to map XML files to blocks. */
124    private static final int XML_BLOCK_CACHE_SIZE = 4;
125
126    // Pool of TypedArrays targeted to this Resources object.
127    final SynchronizedPool<TypedArray> mTypedArrayPool = new SynchronizedPool<>(5);
128
129    // Used by BridgeResources in layoutlib
130    static Resources mSystem = null;
131
132    private static boolean sPreloaded;
133
134    /** Lock object used to protect access to caches and configuration. */
135    private final Object mAccessLock = new Object();
136
137    // These are protected by mAccessLock.
138    private final Configuration mTmpConfig = new Configuration();
139    private final DrawableCache mDrawableCache = new DrawableCache(this);
140    private final DrawableCache mColorDrawableCache = new DrawableCache(this);
141    private final ConfigurationBoundResourceCache<ComplexColor> mComplexColorCache =
142            new ConfigurationBoundResourceCache<>(this);
143    private final ConfigurationBoundResourceCache<Animator> mAnimatorCache =
144            new ConfigurationBoundResourceCache<>(this);
145    private final ConfigurationBoundResourceCache<StateListAnimator> mStateListAnimatorCache =
146            new ConfigurationBoundResourceCache<>(this);
147
148    /** Used to inflate drawable objects from XML. */
149    private DrawableInflater mDrawableInflater;
150
151    /** Lock object used to protect access to {@link #mTmpValue}. */
152    private final Object mTmpValueLock = new Object();
153
154    /** Single-item pool used to minimize TypedValue allocations. */
155    private TypedValue mTmpValue = new TypedValue();
156
157    private boolean mPreloading;
158
159    // Cyclical cache used for recently-accessed XML files.
160    private int mLastCachedXmlBlockIndex = -1;
161    private final int[] mCachedXmlBlockCookies = new int[XML_BLOCK_CACHE_SIZE];
162    private final String[] mCachedXmlBlockFiles = new String[XML_BLOCK_CACHE_SIZE];
163    private final XmlBlock[] mCachedXmlBlocks = new XmlBlock[XML_BLOCK_CACHE_SIZE];
164
165    final AssetManager mAssets;
166    final ClassLoader mClassLoader;
167    final DisplayMetrics mMetrics = new DisplayMetrics();
168
169    private final Configuration mConfiguration = new Configuration();
170
171    private PluralRules mPluralRule;
172
173    private CompatibilityInfo mCompatibilityInfo = CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO;
174
175    static {
176        sPreloadedDrawables = new LongSparseArray[2];
177        sPreloadedDrawables[0] = new LongSparseArray<>();
178        sPreloadedDrawables[1] = new LongSparseArray<>();
179    }
180
181    /**
182     * Returns the most appropriate default theme for the specified target SDK version.
183     * <ul>
184     * <li>Below API 11: Gingerbread
185     * <li>APIs 11 thru 14: Holo
186     * <li>APIs 14 thru XX: Device default dark
187     * <li>API XX and above: Device default light with dark action bar
188     * </ul>
189     *
190     * @param curTheme The current theme, or 0 if not specified.
191     * @param targetSdkVersion The target SDK version.
192     * @return A theme resource identifier
193     * @hide
194     */
195    public static int selectDefaultTheme(int curTheme, int targetSdkVersion) {
196        return selectSystemTheme(curTheme, targetSdkVersion,
197                com.android.internal.R.style.Theme,
198                com.android.internal.R.style.Theme_Holo,
199                com.android.internal.R.style.Theme_DeviceDefault,
200                com.android.internal.R.style.Theme_DeviceDefault_Light_DarkActionBar);
201    }
202
203    /** @hide */
204    public static int selectSystemTheme(int curTheme, int targetSdkVersion, int orig, int holo,
205            int dark, int deviceDefault) {
206        if (curTheme != 0) {
207            return curTheme;
208        }
209        if (targetSdkVersion < Build.VERSION_CODES.HONEYCOMB) {
210            return orig;
211        }
212        if (targetSdkVersion < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
213            return holo;
214        }
215        if (targetSdkVersion < Build.VERSION_CODES.CUR_DEVELOPMENT) {
216            return dark;
217        }
218        return deviceDefault;
219    }
220
221    /**
222     * @return the inflater used to create drawable objects
223     * @hide Pending API finalization.
224     */
225    public final DrawableInflater getDrawableInflater() {
226        if (mDrawableInflater == null) {
227            mDrawableInflater = new DrawableInflater(this, mClassLoader);
228        }
229        return mDrawableInflater;
230    }
231
232    /**
233     * Used by AnimatorInflater.
234     *
235     * @hide
236     */
237    public ConfigurationBoundResourceCache<Animator> getAnimatorCache() {
238        return mAnimatorCache;
239    }
240
241    /**
242     * Used by AnimatorInflater.
243     *
244     * @hide
245     */
246    public ConfigurationBoundResourceCache<StateListAnimator> getStateListAnimatorCache() {
247        return mStateListAnimatorCache;
248    }
249
250    /**
251     * This exception is thrown by the resource APIs when a requested resource
252     * can not be found.
253     */
254    public static class NotFoundException extends RuntimeException {
255        public NotFoundException() {
256        }
257
258        public NotFoundException(String name) {
259            super(name);
260        }
261
262        public NotFoundException(String name, Exception cause) {
263            super(name, cause);
264        }
265    }
266
267    /**
268     * Create a new Resources object on top of an existing set of assets in an
269     * AssetManager.
270     *
271     * @param assets Previously created AssetManager.
272     * @param metrics Current display metrics to consider when
273     *                selecting/computing resource values.
274     * @param config Desired device configuration to consider when
275     *               selecting/computing resource values (optional).
276     */
277    public Resources(AssetManager assets, DisplayMetrics metrics, Configuration config) {
278        this(assets, metrics, config, CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO, null);
279    }
280
281    /**
282     * Creates a new Resources object with CompatibilityInfo.
283     *
284     * @param assets Previously created AssetManager.
285     * @param metrics Current display metrics to consider when
286     *                selecting/computing resource values.
287     * @param config Desired device configuration to consider when
288     *               selecting/computing resource values (optional).
289     * @param compatInfo this resource's compatibility info. Must not be null.
290     * @param classLoader class loader for the package used to load custom
291     *                    resource classes, may be {@code null} to use system
292     *                    class loader
293     * @hide
294     */
295    public Resources(AssetManager assets, DisplayMetrics metrics, Configuration config,
296            CompatibilityInfo compatInfo, @Nullable ClassLoader classLoader) {
297        mAssets = assets;
298        mClassLoader = classLoader == null ? ClassLoader.getSystemClassLoader() : classLoader;
299        mMetrics.setToDefaults();
300        if (compatInfo != null) {
301            mCompatibilityInfo = compatInfo;
302        }
303        updateConfiguration(config, metrics);
304        assets.ensureStringBlocks();
305    }
306
307    /**
308     * Return a global shared Resources object that provides access to only
309     * system resources (no application resources), and is not configured for
310     * the current screen (can not use dimension units, does not change based
311     * on orientation, etc).
312     */
313    public static Resources getSystem() {
314        synchronized (sSync) {
315            Resources ret = mSystem;
316            if (ret == null) {
317                ret = new Resources();
318                mSystem = ret;
319            }
320
321            return ret;
322        }
323    }
324
325    /**
326     * Return the string value associated with a particular resource ID.  The
327     * returned object will be a String if this is a plain string; it will be
328     * some other type of CharSequence if it is styled.
329     * {@more}
330     *
331     * @param id The desired resource identifier, as generated by the aapt
332     *           tool. This integer encodes the package, type, and resource
333     *           entry. The value 0 is an invalid identifier.
334     *
335     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
336     *
337     * @return CharSequence The string data associated with the resource, plus
338     *         possibly styled text information.
339     */
340    public CharSequence getText(@StringRes int id) throws NotFoundException {
341        CharSequence res = mAssets.getResourceText(id);
342        if (res != null) {
343            return res;
344        }
345        throw new NotFoundException("String resource ID #0x"
346                                    + Integer.toHexString(id));
347    }
348
349    /**
350     * Returns the character sequence necessary for grammatically correct pluralization
351     * of the given resource ID for the given quantity.
352     * Note that the character sequence is selected based solely on grammatical necessity,
353     * and that such rules differ between languages. Do not assume you know which string
354     * will be returned for a given quantity. See
355     * <a href="{@docRoot}guide/topics/resources/string-resource.html#Plurals">String Resources</a>
356     * for more detail.
357     *
358     * @param id The desired resource identifier, as generated by the aapt
359     *           tool. This integer encodes the package, type, and resource
360     *           entry. The value 0 is an invalid identifier.
361     * @param quantity The number used to get the correct string for the current language's
362     *           plural rules.
363     *
364     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
365     *
366     * @return CharSequence The string data associated with the resource, plus
367     *         possibly styled text information.
368     */
369    public CharSequence getQuantityText(@PluralsRes int id, int quantity)
370            throws NotFoundException {
371        PluralRules rule = getPluralRule();
372        CharSequence res = mAssets.getResourceBagText(id,
373                attrForQuantityCode(rule.select(quantity)));
374        if (res != null) {
375            return res;
376        }
377        res = mAssets.getResourceBagText(id, ID_OTHER);
378        if (res != null) {
379            return res;
380        }
381        throw new NotFoundException("Plural resource ID #0x" + Integer.toHexString(id)
382                + " quantity=" + quantity
383                + " item=" + rule.select(quantity));
384    }
385
386    private PluralRules getPluralRule() {
387        synchronized (sSync) {
388            if (mPluralRule == null) {
389                mPluralRule = PluralRules.forLocale(mConfiguration.getLocales().get(0));
390            }
391            return mPluralRule;
392        }
393    }
394
395    private static int attrForQuantityCode(String quantityCode) {
396        switch (quantityCode) {
397            case PluralRules.KEYWORD_ZERO: return 0x01000005;
398            case PluralRules.KEYWORD_ONE:  return 0x01000006;
399            case PluralRules.KEYWORD_TWO:  return 0x01000007;
400            case PluralRules.KEYWORD_FEW:  return 0x01000008;
401            case PluralRules.KEYWORD_MANY: return 0x01000009;
402            default:                     return ID_OTHER;
403        }
404    }
405
406    /**
407     * Return the string value associated with a particular resource ID.  It
408     * will be stripped of any styled text information.
409     * {@more}
410     *
411     * @param id The desired resource identifier, as generated by the aapt
412     *           tool. This integer encodes the package, type, and resource
413     *           entry. The value 0 is an invalid identifier.
414     *
415     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
416     *
417     * @return String The string data associated with the resource,
418     *         stripped of styled text information.
419     */
420    @NonNull
421    public String getString(@StringRes int id) throws NotFoundException {
422        final CharSequence res = getText(id);
423        if (res != null) {
424            return res.toString();
425        }
426        throw new NotFoundException("String resource ID #0x"
427                                    + Integer.toHexString(id));
428    }
429
430
431    /**
432     * Return the string value associated with a particular resource ID,
433     * substituting the format arguments as defined in {@link java.util.Formatter}
434     * and {@link java.lang.String#format}. It will be stripped of any styled text
435     * information.
436     * {@more}
437     *
438     * @param id The desired resource identifier, as generated by the aapt
439     *           tool. This integer encodes the package, type, and resource
440     *           entry. The value 0 is an invalid identifier.
441     *
442     * @param formatArgs The format arguments that will be used for substitution.
443     *
444     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
445     *
446     * @return String The string data associated with the resource,
447     *         stripped of styled text information.
448     */
449    @NonNull
450    public String getString(@StringRes int id, Object... formatArgs) throws NotFoundException {
451        final String raw = getString(id);
452        return String.format(mConfiguration.getLocales().get(0), raw, formatArgs);
453    }
454
455    /**
456     * Formats the string necessary for grammatically correct pluralization
457     * of the given resource ID for the given quantity, using the given arguments.
458     * Note that the string is selected based solely on grammatical necessity,
459     * and that such rules differ between languages. Do not assume you know which string
460     * will be returned for a given quantity. See
461     * <a href="{@docRoot}guide/topics/resources/string-resource.html#Plurals">String Resources</a>
462     * for more detail.
463     *
464     * <p>Substitution of format arguments works as if using
465     * {@link java.util.Formatter} and {@link java.lang.String#format}.
466     * The resulting string will be stripped of any styled text information.
467     *
468     * @param id The desired resource identifier, as generated by the aapt
469     *           tool. This integer encodes the package, type, and resource
470     *           entry. The value 0 is an invalid identifier.
471     * @param quantity The number used to get the correct string for the current language's
472     *           plural rules.
473     * @param formatArgs The format arguments that will be used for substitution.
474     *
475     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
476     *
477     * @return String The string data associated with the resource,
478     * stripped of styled text information.
479     */
480    public String getQuantityString(@PluralsRes int id, int quantity, Object... formatArgs)
481            throws NotFoundException {
482        String raw = getQuantityText(id, quantity).toString();
483        return String.format(mConfiguration.getLocales().get(0), raw, formatArgs);
484    }
485
486    /**
487     * Returns the string necessary for grammatically correct pluralization
488     * of the given resource ID for the given quantity.
489     * Note that the string is selected based solely on grammatical necessity,
490     * and that such rules differ between languages. Do not assume you know which string
491     * will be returned for a given quantity. See
492     * <a href="{@docRoot}guide/topics/resources/string-resource.html#Plurals">String Resources</a>
493     * for more detail.
494     *
495     * @param id The desired resource identifier, as generated by the aapt
496     *           tool. This integer encodes the package, type, and resource
497     *           entry. The value 0 is an invalid identifier.
498     * @param quantity The number used to get the correct string for the current language's
499     *           plural rules.
500     *
501     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
502     *
503     * @return String The string data associated with the resource,
504     * stripped of styled text information.
505     */
506    public String getQuantityString(@PluralsRes int id, int quantity)
507            throws NotFoundException {
508        return getQuantityText(id, quantity).toString();
509    }
510
511    /**
512     * Return the string value associated with a particular resource ID.  The
513     * returned object will be a String if this is a plain string; it will be
514     * some other type of CharSequence if it is styled.
515     *
516     * @param id The desired resource identifier, as generated by the aapt
517     *           tool. This integer encodes the package, type, and resource
518     *           entry. The value 0 is an invalid identifier.
519     *
520     * @param def The default CharSequence to return.
521     *
522     * @return CharSequence The string data associated with the resource, plus
523     *         possibly styled text information, or def if id is 0 or not found.
524     */
525    public CharSequence getText(@StringRes int id, CharSequence def) {
526        CharSequence res = id != 0 ? mAssets.getResourceText(id) : null;
527        return res != null ? res : def;
528    }
529
530    /**
531     * Return the styled text array associated with a particular resource ID.
532     *
533     * @param id The desired resource identifier, as generated by the aapt
534     *           tool. This integer encodes the package, type, and resource
535     *           entry. The value 0 is an invalid identifier.
536     *
537     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
538     *
539     * @return The styled text array associated with the resource.
540     */
541    public CharSequence[] getTextArray(@ArrayRes int id) throws NotFoundException {
542        CharSequence[] res = mAssets.getResourceTextArray(id);
543        if (res != null) {
544            return res;
545        }
546        throw new NotFoundException("Text array resource ID #0x"
547                                    + Integer.toHexString(id));
548    }
549
550    /**
551     * Return the string array associated with a particular resource ID.
552     *
553     * @param id The desired resource identifier, as generated by the aapt
554     *           tool. This integer encodes the package, type, and resource
555     *           entry. The value 0 is an invalid identifier.
556     *
557     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
558     *
559     * @return The string array associated with the resource.
560     */
561    public String[] getStringArray(@ArrayRes int id)
562            throws NotFoundException {
563        String[] res = mAssets.getResourceStringArray(id);
564        if (res != null) {
565            return res;
566        }
567        throw new NotFoundException("String array resource ID #0x"
568                                    + Integer.toHexString(id));
569    }
570
571    /**
572     * Return the int array associated with a particular resource ID.
573     *
574     * @param id The desired resource identifier, as generated by the aapt
575     *           tool. This integer encodes the package, type, and resource
576     *           entry. The value 0 is an invalid identifier.
577     *
578     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
579     *
580     * @return The int array associated with the resource.
581     */
582    public int[] getIntArray(@ArrayRes int id) throws NotFoundException {
583        int[] res = mAssets.getArrayIntResource(id);
584        if (res != null) {
585            return res;
586        }
587        throw new NotFoundException("Int array resource ID #0x"
588                                    + Integer.toHexString(id));
589    }
590
591    /**
592     * Return an array of heterogeneous values.
593     *
594     * @param id The desired resource identifier, as generated by the aapt
595     *           tool. This integer encodes the package, type, and resource
596     *           entry. The value 0 is an invalid identifier.
597     *
598     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
599     *
600     * @return Returns a TypedArray holding an array of the array values.
601     * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()}
602     * when done with it.
603     */
604    public TypedArray obtainTypedArray(@ArrayRes int id)
605            throws NotFoundException {
606        int len = mAssets.getArraySize(id);
607        if (len < 0) {
608            throw new NotFoundException("Array resource ID #0x"
609                                        + Integer.toHexString(id));
610        }
611
612        TypedArray array = TypedArray.obtain(this, len);
613        array.mLength = mAssets.retrieveArray(id, array.mData);
614        array.mIndices[0] = 0;
615
616        return array;
617    }
618
619    /**
620     * Retrieve a dimensional for a particular resource ID.  Unit
621     * conversions are based on the current {@link DisplayMetrics} associated
622     * with the resources.
623     *
624     * @param id The desired resource identifier, as generated by the aapt
625     *           tool. This integer encodes the package, type, and resource
626     *           entry. The value 0 is an invalid identifier.
627     *
628     * @return Resource dimension value multiplied by the appropriate
629     * metric.
630     *
631     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
632     *
633     * @see #getDimensionPixelOffset
634     * @see #getDimensionPixelSize
635     */
636    public float getDimension(@DimenRes int id) throws NotFoundException {
637        final TypedValue value = obtainTempTypedValue(id);
638        try {
639            if (value.type == TypedValue.TYPE_DIMENSION) {
640                return TypedValue.complexToDimension(value.data, mMetrics);
641            }
642            throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id)
643                    + " type #0x" + Integer.toHexString(value.type) + " is not valid");
644        } finally {
645            releaseTempTypedValue(value);
646        }
647    }
648
649    /**
650     * Retrieve a dimensional for a particular resource ID for use
651     * as an offset in raw pixels.  This is the same as
652     * {@link #getDimension}, except the returned value is converted to
653     * integer pixels for you.  An offset conversion involves simply
654     * truncating the base value to an integer.
655     *
656     * @param id The desired resource identifier, as generated by the aapt
657     *           tool. This integer encodes the package, type, and resource
658     *           entry. The value 0 is an invalid identifier.
659     *
660     * @return Resource dimension value multiplied by the appropriate
661     * metric and truncated to integer pixels.
662     *
663     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
664     *
665     * @see #getDimension
666     * @see #getDimensionPixelSize
667     */
668    public int getDimensionPixelOffset(@DimenRes int id) throws NotFoundException {
669        final TypedValue value = obtainTempTypedValue(id);
670        try {
671            if (value.type == TypedValue.TYPE_DIMENSION) {
672                return TypedValue.complexToDimensionPixelOffset(value.data, mMetrics);
673            }
674            throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id)
675                    + " type #0x" + Integer.toHexString(value.type) + " is not valid");
676        } finally {
677            releaseTempTypedValue(value);
678        }
679    }
680
681    /**
682     * Retrieve a dimensional for a particular resource ID for use
683     * as a size in raw pixels.  This is the same as
684     * {@link #getDimension}, except the returned value is converted to
685     * integer pixels for use as a size.  A size conversion involves
686     * rounding the base value, and ensuring that a non-zero base value
687     * is at least one pixel in size.
688     *
689     * @param id The desired resource identifier, as generated by the aapt
690     *           tool. This integer encodes the package, type, and resource
691     *           entry. The value 0 is an invalid identifier.
692     *
693     * @return Resource dimension value multiplied by the appropriate
694     * metric and truncated to integer pixels.
695     *
696     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
697     *
698     * @see #getDimension
699     * @see #getDimensionPixelOffset
700     */
701    public int getDimensionPixelSize(@DimenRes int id) throws NotFoundException {
702        final TypedValue value = obtainTempTypedValue(id);
703        try {
704            if (value.type == TypedValue.TYPE_DIMENSION) {
705                return TypedValue.complexToDimensionPixelSize(value.data, mMetrics);
706            }
707            throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id)
708                    + " type #0x" + Integer.toHexString(value.type) + " is not valid");
709        } finally {
710            releaseTempTypedValue(value);
711        }
712    }
713
714    /**
715     * Retrieve a fractional unit for a particular resource ID.
716     *
717     * @param id The desired resource identifier, as generated by the aapt
718     *           tool. This integer encodes the package, type, and resource
719     *           entry. The value 0 is an invalid identifier.
720     * @param base The base value of this fraction.  In other words, a
721     *             standard fraction is multiplied by this value.
722     * @param pbase The parent base value of this fraction.  In other
723     *             words, a parent fraction (nn%p) is multiplied by this
724     *             value.
725     *
726     * @return Attribute fractional value multiplied by the appropriate
727     * base value.
728     *
729     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
730     */
731    public float getFraction(@FractionRes int id, int base, int pbase) {
732        final TypedValue value = obtainTempTypedValue(id);
733        try {
734            if (value.type == TypedValue.TYPE_FRACTION) {
735                return TypedValue.complexToFraction(value.data, base, pbase);
736            }
737            throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id)
738                    + " type #0x" + Integer.toHexString(value.type) + " is not valid");
739        } finally {
740            releaseTempTypedValue(value);
741        }
742    }
743
744    /**
745     * Return a drawable object associated with a particular resource ID.
746     * Various types of objects will be returned depending on the underlying
747     * resource -- for example, a solid color, PNG image, scalable image, etc.
748     * The Drawable API hides these implementation details.
749     *
750     * <p class="note"><strong>Note:</strong> Prior to
751     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN}, this function
752     * would not correctly retrieve the final configuration density when
753     * the resource ID passed here is an alias to another Drawable resource.
754     * This means that if the density configuration of the alias resource
755     * is different than the actual resource, the density of the returned
756     * Drawable would be incorrect, resulting in bad scaling.  To work
757     * around this, you can instead retrieve the Drawable through
758     * {@link TypedArray#getDrawable TypedArray.getDrawable}.  Use
759     * {@link android.content.Context#obtainStyledAttributes(int[])
760     * Context.obtainStyledAttributes} with
761     * an array containing the resource ID of interest to create the TypedArray.</p>
762     *
763     * <p class="note"><strong>Note:</strong> To obtain a themed drawable, use
764     * {@link android.content.Context#getDrawable(int) Context.getDrawable(int)}
765     * or {@link #getDrawable(int, Theme)} passing the desired theme.</p>
766     *
767     * @param id The desired resource identifier, as generated by the aapt
768     *           tool. This integer encodes the package, type, and resource
769     *           entry. The value 0 is an invalid identifier.
770     * @return Drawable An object that can be used to draw this resource.
771     * @throws NotFoundException Throws NotFoundException if the given ID does
772     *         not exist.
773     * @see #getDrawable(int, Theme)
774     * @deprecated Use {@link #getDrawable(int, Theme)} instead.
775     */
776    @Deprecated
777    public Drawable getDrawable(@DrawableRes int id) throws NotFoundException {
778        final Drawable d = getDrawable(id, null);
779        if (d != null && d.canApplyTheme()) {
780            Log.w(TAG, "Drawable " + getResourceName(id) + " has unresolved theme "
781                    + "attributes! Consider using Resources.getDrawable(int, Theme) or "
782                    + "Context.getDrawable(int).", new RuntimeException());
783        }
784        return d;
785    }
786
787    /**
788     * Return a drawable object associated with a particular resource ID and
789     * styled for the specified theme. Various types of objects will be
790     * returned depending on the underlying resource -- for example, a solid
791     * color, PNG image, scalable image, etc.
792     *
793     * @param id The desired resource identifier, as generated by the aapt
794     *           tool. This integer encodes the package, type, and resource
795     *           entry. The value 0 is an invalid identifier.
796     * @param theme The theme used to style the drawable attributes, may be {@code null}.
797     * @return Drawable An object that can be used to draw this resource.
798     * @throws NotFoundException Throws NotFoundException if the given ID does
799     *         not exist.
800     */
801    public Drawable getDrawable(@DrawableRes int id, @Nullable Theme theme)
802            throws NotFoundException {
803        final TypedValue value = obtainTempTypedValue(id);
804        try {
805            return loadDrawable(value, id, theme);
806        } finally {
807            releaseTempTypedValue(value);
808        }
809    }
810
811    /**
812     * Return a drawable object associated with a particular resource ID for the
813     * given screen density in DPI. This will set the drawable's density to be
814     * the device's density multiplied by the ratio of actual drawable density
815     * to requested density. This allows the drawable to be scaled up to the
816     * correct size if needed. Various types of objects will be returned
817     * depending on the underlying resource -- for example, a solid color, PNG
818     * image, scalable image, etc. The Drawable API hides these implementation
819     * details.
820     *
821     * <p class="note"><strong>Note:</strong> To obtain a themed drawable, use
822     * {@link android.content.Context#getDrawable(int) Context.getDrawable(int)}
823     * or {@link #getDrawableForDensity(int, int, Theme)} passing the desired
824     * theme.</p>
825     *
826     * @param id The desired resource identifier, as generated by the aapt tool.
827     *            This integer encodes the package, type, and resource entry.
828     *            The value 0 is an invalid identifier.
829     * @param density the desired screen density indicated by the resource as
830     *            found in {@link DisplayMetrics}.
831     * @return Drawable An object that can be used to draw this resource.
832     * @throws NotFoundException Throws NotFoundException if the given ID does
833     *             not exist.
834     * @see #getDrawableForDensity(int, int, Theme)
835     * @deprecated Use {@link #getDrawableForDensity(int, int, Theme)} instead.
836     */
837    @Deprecated
838    public Drawable getDrawableForDensity(@DrawableRes int id, int density)
839            throws NotFoundException {
840        return getDrawableForDensity(id, density, null);
841    }
842
843    /**
844     * Return a drawable object associated with a particular resource ID for the
845     * given screen density in DPI and styled for the specified theme.
846     *
847     * @param id The desired resource identifier, as generated by the aapt tool.
848     *            This integer encodes the package, type, and resource entry.
849     *            The value 0 is an invalid identifier.
850     * @param density The desired screen density indicated by the resource as
851     *            found in {@link DisplayMetrics}.
852     * @param theme The theme used to style the drawable attributes, may be {@code null}.
853     * @return Drawable An object that can be used to draw this resource.
854     * @throws NotFoundException Throws NotFoundException if the given ID does
855     *             not exist.
856     */
857    public Drawable getDrawableForDensity(@DrawableRes int id, int density, @Nullable Theme theme) {
858        final TypedValue value = obtainTempTypedValue(id);
859        try {
860            getValueForDensity(id, density, value, true);
861
862            // If the drawable's XML lives in our current density qualifier,
863            // it's okay to use a scaled version from the cache. Otherwise, we
864            // need to actually load the drawable from XML.
865            final boolean useCache = value.density == mMetrics.densityDpi;
866
867            /*
868             * Pretend the requested density is actually the display density. If
869             * the drawable returned is not the requested density, then force it
870             * to be scaled later by dividing its density by the ratio of
871             * requested density to actual device density. Drawables that have
872             * undefined density or no density don't need to be handled here.
873             */
874            if (value.density > 0 && value.density != TypedValue.DENSITY_NONE) {
875                if (value.density == density) {
876                    value.density = mMetrics.densityDpi;
877                } else {
878                    value.density = (value.density * mMetrics.densityDpi) / density;
879                }
880            }
881
882            return loadDrawable(value, id, theme, useCache);
883        } finally {
884            releaseTempTypedValue(value);
885        }
886    }
887
888    /**
889     * Return a movie object associated with the particular resource ID.
890     * @param id The desired resource identifier, as generated by the aapt
891     *           tool. This integer encodes the package, type, and resource
892     *           entry. The value 0 is an invalid identifier.
893     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
894     *
895     */
896    public Movie getMovie(@RawRes int id) throws NotFoundException {
897        InputStream is = openRawResource(id);
898        Movie movie = Movie.decodeStream(is);
899        try {
900            is.close();
901        }
902        catch (java.io.IOException e) {
903            // don't care, since the return value is valid
904        }
905        return movie;
906    }
907
908    /**
909     * Returns a color integer associated with a particular resource ID. If the
910     * resource holds a complex {@link ColorStateList}, then the default color
911     * from the set is returned.
912     *
913     * @param id The desired resource identifier, as generated by the aapt
914     *           tool. This integer encodes the package, type, and resource
915     *           entry. The value 0 is an invalid identifier.
916     *
917     * @throws NotFoundException Throws NotFoundException if the given ID does
918     *         not exist.
919     *
920     * @return A single color value in the form 0xAARRGGBB.
921     * @deprecated Use {@link #getColor(int, Theme)} instead.
922     */
923    @ColorInt
924    @Deprecated
925    public int getColor(@ColorRes int id) throws NotFoundException {
926        return getColor(id, null);
927    }
928
929    /**
930     * Returns a themed color integer associated with a particular resource ID.
931     * If the resource holds a complex {@link ColorStateList}, then the default
932     * color from the set is returned.
933     *
934     * @param id The desired resource identifier, as generated by the aapt
935     *           tool. This integer encodes the package, type, and resource
936     *           entry. The value 0 is an invalid identifier.
937     * @param theme The theme used to style the color attributes, may be
938     *              {@code null}.
939     *
940     * @throws NotFoundException Throws NotFoundException if the given ID does
941     *         not exist.
942     *
943     * @return A single color value in the form 0xAARRGGBB.
944     */
945    @ColorInt
946    public int getColor(@ColorRes int id, @Nullable Theme theme) throws NotFoundException {
947        final TypedValue value = obtainTempTypedValue(id);
948        try {
949            if (value.type >= TypedValue.TYPE_FIRST_INT
950                    && value.type <= TypedValue.TYPE_LAST_INT) {
951                return value.data;
952            } else if (value.type != TypedValue.TYPE_STRING) {
953                throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id)
954                        + " type #0x" + Integer.toHexString(value.type) + " is not valid");
955            }
956
957            final ColorStateList csl = loadColorStateList(value, id, theme);
958            return csl.getDefaultColor();
959        } finally {
960            releaseTempTypedValue(value);
961        }
962    }
963
964    /**
965     * Returns a color state list associated with a particular resource ID. The
966     * resource may contain either a single raw color value or a complex
967     * {@link ColorStateList} holding multiple possible colors.
968     *
969     * @param id The desired resource identifier of a {@link ColorStateList},
970     *           as generated by the aapt tool. This integer encodes the
971     *           package, type, and resource entry. The value 0 is an invalid
972     *           identifier.
973     *
974     * @throws NotFoundException Throws NotFoundException if the given ID does
975     *         not exist.
976     *
977     * @return A ColorStateList object containing either a single solid color
978     *         or multiple colors that can be selected based on a state.
979     * @deprecated Use {@link #getColorStateList(int, Theme)} instead.
980     */
981    @Nullable
982    @Deprecated
983    public ColorStateList getColorStateList(@ColorRes int id) throws NotFoundException {
984        final ColorStateList csl = getColorStateList(id, null);
985        if (csl != null && csl.canApplyTheme()) {
986            Log.w(TAG, "ColorStateList " + getResourceName(id) + " has "
987                    + "unresolved theme attributes! Consider using "
988                    + "Resources.getColorStateList(int, Theme) or "
989                    + "Context.getColorStateList(int).", new RuntimeException());
990        }
991        return csl;
992    }
993
994    /**
995     * Returns a themed color state list associated with a particular resource
996     * ID. The resource may contain either a single raw color value or a
997     * complex {@link ColorStateList} holding multiple possible colors.
998     *
999     * @param id The desired resource identifier of a {@link ColorStateList},
1000     *           as generated by the aapt tool. This integer encodes the
1001     *           package, type, and resource entry. The value 0 is an invalid
1002     *           identifier.
1003     * @param theme The theme used to style the color attributes, may be
1004     *              {@code null}.
1005     *
1006     * @throws NotFoundException Throws NotFoundException if the given ID does
1007     *         not exist.
1008     *
1009     * @return A themed ColorStateList object containing either a single solid
1010     *         color or multiple colors that can be selected based on a state.
1011     */
1012    @Nullable
1013    public ColorStateList getColorStateList(@ColorRes int id, @Nullable Theme theme)
1014            throws NotFoundException {
1015        final TypedValue value = obtainTempTypedValue(id);
1016        try {
1017            return loadColorStateList(value, id, theme);
1018        } finally {
1019            releaseTempTypedValue(value);
1020        }
1021    }
1022
1023    /**
1024     * Return a boolean associated with a particular resource ID.  This can be
1025     * used with any integral resource value, and will return true if it is
1026     * non-zero.
1027     *
1028     * @param id The desired resource identifier, as generated by the aapt
1029     *           tool. This integer encodes the package, type, and resource
1030     *           entry. The value 0 is an invalid identifier.
1031     *
1032     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1033     *
1034     * @return Returns the boolean value contained in the resource.
1035     */
1036    public boolean getBoolean(@BoolRes int id) throws NotFoundException {
1037        final TypedValue value = obtainTempTypedValue(id);
1038        try {
1039            if (value.type >= TypedValue.TYPE_FIRST_INT
1040                    && value.type <= TypedValue.TYPE_LAST_INT) {
1041                return value.data != 0;
1042            }
1043            throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id)
1044                    + " type #0x" + Integer.toHexString(value.type) + " is not valid");
1045        } finally {
1046            releaseTempTypedValue(value);
1047        }
1048    }
1049
1050    /**
1051     * Return an integer associated with a particular resource ID.
1052     *
1053     * @param id The desired resource identifier, as generated by the aapt
1054     *           tool. This integer encodes the package, type, and resource
1055     *           entry. The value 0 is an invalid identifier.
1056     *
1057     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1058     *
1059     * @return Returns the integer value contained in the resource.
1060     */
1061    public int getInteger(@IntegerRes int id) throws NotFoundException {
1062        final TypedValue value = obtainTempTypedValue(id);
1063        try {
1064            if (value.type >= TypedValue.TYPE_FIRST_INT
1065                    && value.type <= TypedValue.TYPE_LAST_INT) {
1066                return value.data;
1067            }
1068            throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id)
1069                    + " type #0x" + Integer.toHexString(value.type) + " is not valid");
1070        } finally {
1071            releaseTempTypedValue(value);
1072        }
1073    }
1074
1075    /**
1076     * Retrieve a floating-point value for a particular resource ID.
1077     *
1078     * @param id The desired resource identifier, as generated by the aapt
1079     *           tool. This integer encodes the package, type, and resource
1080     *           entry. The value 0 is an invalid identifier.
1081     *
1082     * @return Returns the floating-point value contained in the resource.
1083     *
1084     * @throws NotFoundException Throws NotFoundException if the given ID does
1085     *         not exist or is not a floating-point value.
1086     * @hide Pending API council approval.
1087     */
1088    public float getFloat(int id) {
1089        final TypedValue value = obtainTempTypedValue(id);
1090        try {
1091            if (value.type == TypedValue.TYPE_FLOAT) {
1092                return value.getFloat();
1093            }
1094            throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id)
1095                    + " type #0x" + Integer.toHexString(value.type) + " is not valid");
1096        } finally {
1097            releaseTempTypedValue(value);
1098        }
1099    }
1100
1101    /**
1102     * Return an XmlResourceParser through which you can read a view layout
1103     * description for the given resource ID.  This parser has limited
1104     * functionality -- in particular, you can't change its input, and only
1105     * the high-level events are available.
1106     *
1107     * <p>This function is really a simple wrapper for calling
1108     * {@link #getXml} with a layout resource.
1109     *
1110     * @param id The desired resource identifier, as generated by the aapt
1111     *           tool. This integer encodes the package, type, and resource
1112     *           entry. The value 0 is an invalid identifier.
1113     *
1114     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1115     *
1116     * @return A new parser object through which you can read
1117     *         the XML data.
1118     *
1119     * @see #getXml
1120     */
1121    public XmlResourceParser getLayout(@LayoutRes int id) throws NotFoundException {
1122        return loadXmlResourceParser(id, "layout");
1123    }
1124
1125    /**
1126     * Return an XmlResourceParser through which you can read an animation
1127     * description for the given resource ID.  This parser has limited
1128     * functionality -- in particular, you can't change its input, and only
1129     * the high-level events are available.
1130     *
1131     * <p>This function is really a simple wrapper for calling
1132     * {@link #getXml} with an animation resource.
1133     *
1134     * @param id The desired resource identifier, as generated by the aapt
1135     *           tool. This integer encodes the package, type, and resource
1136     *           entry. The value 0 is an invalid identifier.
1137     *
1138     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1139     *
1140     * @return A new parser object through which you can read
1141     *         the XML data.
1142     *
1143     * @see #getXml
1144     */
1145    public XmlResourceParser getAnimation(@AnimRes int id) throws NotFoundException {
1146        return loadXmlResourceParser(id, "anim");
1147    }
1148
1149    /**
1150     * Return an XmlResourceParser through which you can read a generic XML
1151     * resource for the given resource ID.
1152     *
1153     * <p>The XmlPullParser implementation returned here has some limited
1154     * functionality.  In particular, you can't change its input, and only
1155     * high-level parsing events are available (since the document was
1156     * pre-parsed for you at build time, which involved merging text and
1157     * stripping comments).
1158     *
1159     * @param id The desired resource identifier, as generated by the aapt
1160     *           tool. This integer encodes the package, type, and resource
1161     *           entry. The value 0 is an invalid identifier.
1162     *
1163     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1164     *
1165     * @return A new parser object through which you can read
1166     *         the XML data.
1167     *
1168     * @see android.util.AttributeSet
1169     */
1170    public XmlResourceParser getXml(@XmlRes int id) throws NotFoundException {
1171        return loadXmlResourceParser(id, "xml");
1172    }
1173
1174    /**
1175     * Open a data stream for reading a raw resource.  This can only be used
1176     * with resources whose value is the name of an asset files -- that is, it can be
1177     * used to open drawable, sound, and raw resources; it will fail on string
1178     * and color resources.
1179     *
1180     * @param id The resource identifier to open, as generated by the appt
1181     *           tool.
1182     *
1183     * @return InputStream Access to the resource data.
1184     *
1185     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1186     *
1187     */
1188    public InputStream openRawResource(@RawRes int id) throws NotFoundException {
1189        final TypedValue value = obtainTempTypedValue();
1190        try {
1191            return openRawResource(id, value);
1192        } finally {
1193            releaseTempTypedValue(value);
1194        }
1195    }
1196
1197    /**
1198     * Returns a TypedValue populated with data for the specified resource ID
1199     * that's suitable for temporary use. The obtained TypedValue should be
1200     * released using {@link #releaseTempTypedValue(TypedValue)}.
1201     *
1202     * @param id the resource ID for which data should be obtained
1203     * @return a populated typed value suitable for temporary use
1204     */
1205    private TypedValue obtainTempTypedValue(@AnyRes int id) {
1206        final TypedValue value = obtainTempTypedValue();
1207        getValue(id, value, true);
1208        return value;
1209    }
1210
1211    /**
1212     * Returns a TypedValue suitable for temporary use. The obtained TypedValue
1213     * should be released using {@link #releaseTempTypedValue(TypedValue)}.
1214     *
1215     * @return a typed value suitable for temporary use
1216     */
1217    private TypedValue obtainTempTypedValue() {
1218        TypedValue tmpValue = null;
1219        synchronized (mTmpValueLock) {
1220            if (mTmpValue != null) {
1221                tmpValue = mTmpValue;
1222                mTmpValue = null;
1223            }
1224        }
1225        if (tmpValue == null) {
1226            return new TypedValue();
1227        }
1228        return tmpValue;
1229    }
1230
1231    /**
1232     * Returns a TypedValue to the pool. After calling this method, the
1233     * specified TypedValue should no longer be accessed.
1234     *
1235     * @param value the typed value to return to the pool
1236     */
1237    private void releaseTempTypedValue(TypedValue value) {
1238        synchronized (mTmpValueLock) {
1239            if (mTmpValue == null) {
1240                mTmpValue = value;
1241            }
1242        }
1243    }
1244
1245    /**
1246     * Open a data stream for reading a raw resource.  This can only be used
1247     * with resources whose value is the name of an asset file -- that is, it can be
1248     * used to open drawable, sound, and raw resources; it will fail on string
1249     * and color resources.
1250     *
1251     * @param id The resource identifier to open, as generated by the appt tool.
1252     * @param value The TypedValue object to hold the resource information.
1253     *
1254     * @return InputStream Access to the resource data.
1255     *
1256     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1257     */
1258    public InputStream openRawResource(@RawRes int id, TypedValue value)
1259            throws NotFoundException {
1260        getValue(id, value, true);
1261
1262        try {
1263            return mAssets.openNonAsset(value.assetCookie, value.string.toString(),
1264                    AssetManager.ACCESS_STREAMING);
1265        } catch (Exception e) {
1266            NotFoundException rnf = new NotFoundException("File " + value.string.toString() +
1267                    " from drawable resource ID #0x" + Integer.toHexString(id));
1268            rnf.initCause(e);
1269            throw rnf;
1270        }
1271    }
1272
1273    /**
1274     * Open a file descriptor for reading a raw resource.  This can only be used
1275     * with resources whose value is the name of an asset files -- that is, it can be
1276     * used to open drawable, sound, and raw resources; it will fail on string
1277     * and color resources.
1278     *
1279     * <p>This function only works for resources that are stored in the package
1280     * as uncompressed data, which typically includes things like mp3 files
1281     * and png images.
1282     *
1283     * @param id The resource identifier to open, as generated by the appt
1284     *           tool.
1285     *
1286     * @return AssetFileDescriptor A new file descriptor you can use to read
1287     * the resource.  This includes the file descriptor itself, as well as the
1288     * offset and length of data where the resource appears in the file.  A
1289     * null is returned if the file exists but is compressed.
1290     *
1291     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1292     *
1293     */
1294    public AssetFileDescriptor openRawResourceFd(@RawRes int id)
1295            throws NotFoundException {
1296        final TypedValue value = obtainTempTypedValue(id);
1297        try {
1298            return mAssets.openNonAssetFd(value.assetCookie, value.string.toString());
1299        } catch (Exception e) {
1300            throw new NotFoundException("File " + value.string.toString() + " from drawable "
1301                    + "resource ID #0x" + Integer.toHexString(id), e);
1302        } finally {
1303            releaseTempTypedValue(value);
1304        }
1305    }
1306
1307    /**
1308     * Return the raw data associated with a particular resource ID.
1309     *
1310     * @param id The desired resource identifier, as generated by the aapt
1311     *           tool. This integer encodes the package, type, and resource
1312     *           entry. The value 0 is an invalid identifier.
1313     * @param outValue Object in which to place the resource data.
1314     * @param resolveRefs If true, a resource that is a reference to another
1315     *                    resource will be followed so that you receive the
1316     *                    actual final resource data.  If false, the TypedValue
1317     *                    will be filled in with the reference itself.
1318     *
1319     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1320     *
1321     */
1322    public void getValue(@AnyRes int id, TypedValue outValue, boolean resolveRefs)
1323            throws NotFoundException {
1324        boolean found = mAssets.getResourceValue(id, 0, outValue, resolveRefs);
1325        if (found) {
1326            return;
1327        }
1328        throw new NotFoundException("Resource ID #0x"
1329                                    + Integer.toHexString(id));
1330    }
1331
1332    /**
1333     * Get the raw value associated with a resource with associated density.
1334     *
1335     * @param id resource identifier
1336     * @param density density in DPI
1337     * @param resolveRefs If true, a resource that is a reference to another
1338     *            resource will be followed so that you receive the actual final
1339     *            resource data. If false, the TypedValue will be filled in with
1340     *            the reference itself.
1341     * @throws NotFoundException Throws NotFoundException if the given ID does
1342     *             not exist.
1343     * @see #getValue(String, TypedValue, boolean)
1344     */
1345    public void getValueForDensity(@AnyRes int id, int density, TypedValue outValue,
1346            boolean resolveRefs) throws NotFoundException {
1347        boolean found = mAssets.getResourceValue(id, density, outValue, resolveRefs);
1348        if (found) {
1349            return;
1350        }
1351        throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id));
1352    }
1353
1354    /**
1355     * Return the raw data associated with a particular resource ID.
1356     * See getIdentifier() for information on how names are mapped to resource
1357     * IDs, and getString(int) for information on how string resources are
1358     * retrieved.
1359     *
1360     * <p>Note: use of this function is discouraged.  It is much more
1361     * efficient to retrieve resources by identifier than by name.
1362     *
1363     * @param name The name of the desired resource.  This is passed to
1364     *             getIdentifier() with a default type of "string".
1365     * @param outValue Object in which to place the resource data.
1366     * @param resolveRefs If true, a resource that is a reference to another
1367     *                    resource will be followed so that you receive the
1368     *                    actual final resource data.  If false, the TypedValue
1369     *                    will be filled in with the reference itself.
1370     *
1371     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1372     *
1373     */
1374    public void getValue(String name, TypedValue outValue, boolean resolveRefs)
1375            throws NotFoundException {
1376        int id = getIdentifier(name, "string", null);
1377        if (id != 0) {
1378            getValue(id, outValue, resolveRefs);
1379            return;
1380        }
1381        throw new NotFoundException("String resource name " + name);
1382    }
1383
1384    /**
1385     * This class holds the current attribute values for a particular theme.
1386     * In other words, a Theme is a set of values for resource attributes;
1387     * these are used in conjunction with {@link TypedArray}
1388     * to resolve the final value for an attribute.
1389     *
1390     * <p>The Theme's attributes come into play in two ways: (1) a styled
1391     * attribute can explicit reference a value in the theme through the
1392     * "?themeAttribute" syntax; (2) if no value has been defined for a
1393     * particular styled attribute, as a last resort we will try to find that
1394     * attribute's value in the Theme.
1395     *
1396     * <p>You will normally use the {@link #obtainStyledAttributes} APIs to
1397     * retrieve XML attributes with style and theme information applied.
1398     */
1399    public final class Theme {
1400        /**
1401         * Place new attribute values into the theme.  The style resource
1402         * specified by <var>resid</var> will be retrieved from this Theme's
1403         * resources, its values placed into the Theme object.
1404         *
1405         * <p>The semantics of this function depends on the <var>force</var>
1406         * argument:  If false, only values that are not already defined in
1407         * the theme will be copied from the system resource; otherwise, if
1408         * any of the style's attributes are already defined in the theme, the
1409         * current values in the theme will be overwritten.
1410         *
1411         * @param resId The resource ID of a style resource from which to
1412         *              obtain attribute values.
1413         * @param force If true, values in the style resource will always be
1414         *              used in the theme; otherwise, they will only be used
1415         *              if not already defined in the theme.
1416         */
1417        public void applyStyle(int resId, boolean force) {
1418            synchronized (mKey) {
1419                AssetManager.applyThemeStyle(mTheme, resId, force);
1420
1421                mThemeResId = resId;
1422                mKey.append(resId, force);
1423            }
1424        }
1425
1426        /**
1427         * Set this theme to hold the same contents as the theme
1428         * <var>other</var>.  If both of these themes are from the same
1429         * Resources object, they will be identical after this function
1430         * returns.  If they are from different Resources, only the resources
1431         * they have in common will be set in this theme.
1432         *
1433         * @param other The existing Theme to copy from.
1434         */
1435        public void setTo(Theme other) {
1436            synchronized (mKey) {
1437                synchronized (other.mKey) {
1438                    AssetManager.copyTheme(mTheme, other.mTheme);
1439
1440                    mThemeResId = other.mThemeResId;
1441                    mKey.setTo(other.getKey());
1442                }
1443            }
1444        }
1445
1446        /**
1447         * Return a TypedArray holding the values defined by
1448         * <var>Theme</var> which are listed in <var>attrs</var>.
1449         *
1450         * <p>Be sure to call {@link TypedArray#recycle() TypedArray.recycle()} when you are done
1451         * with the array.
1452         *
1453         * @param attrs The desired attributes.
1454         *
1455         * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1456         *
1457         * @return Returns a TypedArray holding an array of the attribute values.
1458         * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()}
1459         * when done with it.
1460         *
1461         * @see Resources#obtainAttributes
1462         * @see #obtainStyledAttributes(int, int[])
1463         * @see #obtainStyledAttributes(AttributeSet, int[], int, int)
1464         */
1465        public TypedArray obtainStyledAttributes(@StyleableRes int[] attrs) {
1466            synchronized (mKey) {
1467                final int len = attrs.length;
1468                final TypedArray array = TypedArray.obtain(Resources.this, len);
1469                array.mTheme = this;
1470                AssetManager.applyStyle(mTheme, 0, 0, 0, attrs, array.mData, array.mIndices);
1471                return array;
1472            }
1473        }
1474
1475        /**
1476         * Return a TypedArray holding the values defined by the style
1477         * resource <var>resid</var> which are listed in <var>attrs</var>.
1478         *
1479         * <p>Be sure to call {@link TypedArray#recycle() TypedArray.recycle()} when you are done
1480         * with the array.
1481         *
1482         * @param resId The desired style resource.
1483         * @param attrs The desired attributes in the style.
1484         *
1485         * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1486         *
1487         * @return Returns a TypedArray holding an array of the attribute values.
1488         * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()}
1489         * when done with it.
1490         *
1491         * @see Resources#obtainAttributes
1492         * @see #obtainStyledAttributes(int[])
1493         * @see #obtainStyledAttributes(AttributeSet, int[], int, int)
1494         */
1495        public TypedArray obtainStyledAttributes(@StyleRes int resId, @StyleableRes int[] attrs)
1496                throws NotFoundException {
1497            synchronized (mKey) {
1498                final int len = attrs.length;
1499                final TypedArray array = TypedArray.obtain(Resources.this, len);
1500                array.mTheme = this;
1501                AssetManager.applyStyle(mTheme, 0, resId, 0, attrs, array.mData, array.mIndices);
1502                return array;
1503            }
1504        }
1505
1506        /**
1507         * Return a TypedArray holding the attribute values in
1508         * <var>set</var>
1509         * that are listed in <var>attrs</var>.  In addition, if the given
1510         * AttributeSet specifies a style class (through the "style" attribute),
1511         * that style will be applied on top of the base attributes it defines.
1512         *
1513         * <p>Be sure to call {@link TypedArray#recycle() TypedArray.recycle()} when you are done
1514         * with the array.
1515         *
1516         * <p>When determining the final value of a particular attribute, there
1517         * are four inputs that come into play:</p>
1518         *
1519         * <ol>
1520         *     <li> Any attribute values in the given AttributeSet.
1521         *     <li> The style resource specified in the AttributeSet (named
1522         *     "style").
1523         *     <li> The default style specified by <var>defStyleAttr</var> and
1524         *     <var>defStyleRes</var>
1525         *     <li> The base values in this theme.
1526         * </ol>
1527         *
1528         * <p>Each of these inputs is considered in-order, with the first listed
1529         * taking precedence over the following ones.  In other words, if in the
1530         * AttributeSet you have supplied <code>&lt;Button
1531         * textColor="#ff000000"&gt;</code>, then the button's text will
1532         * <em>always</em> be black, regardless of what is specified in any of
1533         * the styles.
1534         *
1535         * @param set The base set of attribute values.  May be null.
1536         * @param attrs The desired attributes to be retrieved.
1537         * @param defStyleAttr An attribute in the current theme that contains a
1538         *                     reference to a style resource that supplies
1539         *                     defaults values for the TypedArray.  Can be
1540         *                     0 to not look for defaults.
1541         * @param defStyleRes A resource identifier of a style resource that
1542         *                    supplies default values for the TypedArray,
1543         *                    used only if defStyleAttr is 0 or can not be found
1544         *                    in the theme.  Can be 0 to not look for defaults.
1545         *
1546         * @return Returns a TypedArray holding an array of the attribute values.
1547         * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()}
1548         * when done with it.
1549         *
1550         * @see Resources#obtainAttributes
1551         * @see #obtainStyledAttributes(int[])
1552         * @see #obtainStyledAttributes(int, int[])
1553         */
1554        public TypedArray obtainStyledAttributes(AttributeSet set,
1555                @StyleableRes int[] attrs, @AttrRes int defStyleAttr, @StyleRes int defStyleRes) {
1556            synchronized (mKey) {
1557                final int len = attrs.length;
1558                final TypedArray array = TypedArray.obtain(Resources.this, len);
1559
1560                // XXX note that for now we only work with compiled XML files.
1561                // To support generic XML files we will need to manually parse
1562                // out the attributes from the XML file (applying type information
1563                // contained in the resources and such).
1564                final XmlBlock.Parser parser = (XmlBlock.Parser) set;
1565                AssetManager.applyStyle(mTheme, defStyleAttr, defStyleRes,
1566                        parser != null ? parser.mParseState : 0,
1567                        attrs, array.mData, array.mIndices);
1568                array.mTheme = this;
1569                array.mXml = parser;
1570
1571                return array;
1572            }
1573        }
1574
1575        /**
1576         * Retrieve the values for a set of attributes in the Theme. The
1577         * contents of the typed array are ultimately filled in by
1578         * {@link Resources#getValue}.
1579         *
1580         * @param values The base set of attribute values, must be equal in
1581         *               length to {@code attrs}. All values must be of type
1582         *               {@link TypedValue#TYPE_ATTRIBUTE}.
1583         * @param attrs The desired attributes to be retrieved.
1584         * @return Returns a TypedArray holding an array of the attribute
1585         *         values. Be sure to call {@link TypedArray#recycle()}
1586         *         when done with it.
1587         * @hide
1588         */
1589        @NonNull
1590        public TypedArray resolveAttributes(@NonNull int[] values, @NonNull int[] attrs) {
1591            synchronized (mKey) {
1592                final int len = attrs.length;
1593                if (values == null || len != values.length) {
1594                    throw new IllegalArgumentException(
1595                            "Base attribute values must the same length as attrs");
1596                }
1597
1598                final TypedArray array = TypedArray.obtain(Resources.this, len);
1599                AssetManager.resolveAttrs(mTheme, 0, 0, values, attrs, array.mData, array.mIndices);
1600                array.mTheme = this;
1601                array.mXml = null;
1602
1603                return array;
1604            }
1605        }
1606
1607        /**
1608         * Retrieve the value of an attribute in the Theme.  The contents of
1609         * <var>outValue</var> are ultimately filled in by
1610         * {@link Resources#getValue}.
1611         *
1612         * @param resid The resource identifier of the desired theme
1613         *              attribute.
1614         * @param outValue Filled in with the ultimate resource value supplied
1615         *                 by the attribute.
1616         * @param resolveRefs If true, resource references will be walked; if
1617         *                    false, <var>outValue</var> may be a
1618         *                    TYPE_REFERENCE.  In either case, it will never
1619         *                    be a TYPE_ATTRIBUTE.
1620         *
1621         * @return boolean Returns true if the attribute was found and
1622         *         <var>outValue</var> is valid, else false.
1623         */
1624        public boolean resolveAttribute(int resid, TypedValue outValue, boolean resolveRefs) {
1625            synchronized (mKey) {
1626                return mAssets.getThemeValue(mTheme, resid, outValue, resolveRefs);
1627            }
1628        }
1629
1630        /**
1631         * Gets all of the attribute ids associated with this {@link Theme}. For debugging only.
1632         *
1633         * @return The int array containing attribute ids associated with this {@link Theme}.
1634         * @hide
1635         */
1636        public int[] getAllAttributes() {
1637            return mAssets.getStyleAttributes(getAppliedStyleResId());
1638        }
1639
1640        /**
1641         * Returns the resources to which this theme belongs.
1642         *
1643         * @return Resources to which this theme belongs.
1644         */
1645        public Resources getResources() {
1646            return Resources.this;
1647        }
1648
1649        /**
1650         * Return a drawable object associated with a particular resource ID
1651         * and styled for the Theme.
1652         *
1653         * @param id The desired resource identifier, as generated by the aapt
1654         *           tool. This integer encodes the package, type, and resource
1655         *           entry. The value 0 is an invalid identifier.
1656         * @return Drawable An object that can be used to draw this resource.
1657         * @throws NotFoundException Throws NotFoundException if the given ID
1658         *         does not exist.
1659         */
1660        public Drawable getDrawable(@DrawableRes int id) throws NotFoundException {
1661            return Resources.this.getDrawable(id, this);
1662        }
1663
1664        /**
1665         * Returns a bit mask of configuration changes that will impact this
1666         * theme (and thus require completely reloading it).
1667         *
1668         * @return a bit mask of configuration changes, as defined by
1669         *         {@link ActivityInfo}
1670         * @see ActivityInfo
1671         */
1672        public int getChangingConfigurations() {
1673            synchronized (mKey) {
1674                final int nativeChangingConfig =
1675                        AssetManager.getThemeChangingConfigurations(mTheme);
1676                return ActivityInfo.activityInfoConfigNativeToJava(nativeChangingConfig);
1677            }
1678        }
1679
1680        /**
1681         * Print contents of this theme out to the log.  For debugging only.
1682         *
1683         * @param priority The log priority to use.
1684         * @param tag The log tag to use.
1685         * @param prefix Text to prefix each line printed.
1686         */
1687        public void dump(int priority, String tag, String prefix) {
1688            synchronized (mKey) {
1689                AssetManager.dumpTheme(mTheme, priority, tag, prefix);
1690            }
1691        }
1692
1693        @Override
1694        protected void finalize() throws Throwable {
1695            super.finalize();
1696            mAssets.releaseTheme(mTheme);
1697        }
1698
1699        /*package*/ Theme() {
1700            mAssets = Resources.this.mAssets;
1701            mTheme = mAssets.createTheme();
1702        }
1703
1704        /** Unique key for the series of styles applied to this theme. */
1705        private final ThemeKey mKey = new ThemeKey();
1706
1707        @SuppressWarnings("hiding")
1708        private final AssetManager mAssets;
1709        private final long mTheme;
1710
1711        /** Resource identifier for the theme. */
1712        private int mThemeResId = 0;
1713
1714        // Needed by layoutlib.
1715        /*package*/ long getNativeTheme() {
1716            return mTheme;
1717        }
1718
1719        /*package*/ int getAppliedStyleResId() {
1720            return mThemeResId;
1721        }
1722
1723        /*package*/ ThemeKey getKey() {
1724            return mKey;
1725        }
1726
1727        private String getResourceNameFromHexString(String hexString) {
1728            return getResourceName(Integer.parseInt(hexString, 16));
1729        }
1730
1731        /**
1732         * Parses {@link #mKey} and returns a String array that holds pairs of
1733         * adjacent Theme data: resource name followed by whether or not it was
1734         * forced, as specified by {@link #applyStyle(int, boolean)}.
1735         *
1736         * @hide
1737         */
1738        @ViewDebug.ExportedProperty(category = "theme", hasAdjacentMapping = true)
1739        public String[] getTheme() {
1740            synchronized (mKey) {
1741                final int N = mKey.mCount;
1742                final String[] themes = new String[N * 2];
1743                for (int i = 0, j = N - 1; i < themes.length; i += 2, --j) {
1744                    final int resId = mKey.mResId[j];
1745                    final boolean forced = mKey.mForce[j];
1746                    try {
1747                        themes[i] = getResourceName(resId);
1748                    } catch (NotFoundException e) {
1749                        themes[i] = Integer.toHexString(i);
1750                    }
1751                    themes[i + 1] = forced ? "forced" : "not forced";
1752                }
1753                return themes;
1754            }
1755        }
1756
1757        /** @hide */
1758        public void encode(@NonNull ViewHierarchyEncoder encoder) {
1759            encoder.beginObject(this);
1760            final String[] properties = getTheme();
1761            for (int i = 0; i < properties.length; i += 2) {
1762                encoder.addProperty(properties[i], properties[i+1]);
1763            }
1764            encoder.endObject();
1765        }
1766
1767        /**
1768         * Rebases the theme against the parent Resource object's current
1769         * configuration by re-applying the styles passed to
1770         * {@link #applyStyle(int, boolean)}.
1771         *
1772         * @hide
1773         */
1774        public void rebase() {
1775            synchronized (mKey) {
1776                AssetManager.clearTheme(mTheme);
1777
1778                // Reapply the same styles in the same order.
1779                for (int i = 0; i < mKey.mCount; i++) {
1780                    final int resId = mKey.mResId[i];
1781                    final boolean force = mKey.mForce[i];
1782                    AssetManager.applyThemeStyle(mTheme, resId, force);
1783                }
1784            }
1785        }
1786    }
1787
1788    static class ThemeKey implements Cloneable {
1789        int[] mResId;
1790        boolean[] mForce;
1791        int mCount;
1792
1793        private int mHashCode = 0;
1794
1795        public void append(int resId, boolean force) {
1796            if (mResId == null) {
1797                mResId = new int[4];
1798            }
1799
1800            if (mForce == null) {
1801                mForce = new boolean[4];
1802            }
1803
1804            mResId = GrowingArrayUtils.append(mResId, mCount, resId);
1805            mForce = GrowingArrayUtils.append(mForce, mCount, force);
1806            mCount++;
1807
1808            mHashCode = 31 * (31 * mHashCode + resId) + (force ? 1 : 0);
1809        }
1810
1811        /**
1812         * Sets up this key as a deep copy of another key.
1813         *
1814         * @param other the key to deep copy into this key
1815         */
1816        public void setTo(ThemeKey other) {
1817            mResId = other.mResId == null ? null : other.mResId.clone();
1818            mForce = other.mForce == null ? null : other.mForce.clone();
1819            mCount = other.mCount;
1820        }
1821
1822        @Override
1823        public int hashCode() {
1824            return mHashCode;
1825        }
1826
1827        @Override
1828        public boolean equals(Object o) {
1829            if (this == o) {
1830                return true;
1831            }
1832
1833            if (o == null || getClass() != o.getClass() || hashCode() != o.hashCode()) {
1834                return false;
1835            }
1836
1837            final ThemeKey t = (ThemeKey) o;
1838            if (mCount != t.mCount) {
1839                return false;
1840            }
1841
1842            final int N = mCount;
1843            for (int i = 0; i < N; i++) {
1844                if (mResId[i] != t.mResId[i] || mForce[i] != t.mForce[i]) {
1845                    return false;
1846                }
1847            }
1848
1849            return true;
1850        }
1851
1852        /**
1853         * @return a shallow copy of this key
1854         */
1855        @Override
1856        public ThemeKey clone() {
1857            final ThemeKey other = new ThemeKey();
1858            other.mResId = mResId;
1859            other.mForce = mForce;
1860            other.mCount = mCount;
1861            other.mHashCode = mHashCode;
1862            return other;
1863        }
1864    }
1865
1866    /**
1867     * Generate a new Theme object for this set of Resources.  It initially
1868     * starts out empty.
1869     *
1870     * @return Theme The newly created Theme container.
1871     */
1872    public final Theme newTheme() {
1873        return new Theme();
1874    }
1875
1876    /**
1877     * Retrieve a set of basic attribute values from an AttributeSet, not
1878     * performing styling of them using a theme and/or style resources.
1879     *
1880     * @param set The current attribute values to retrieve.
1881     * @param attrs The specific attributes to be retrieved.
1882     * @return Returns a TypedArray holding an array of the attribute values.
1883     * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()}
1884     * when done with it.
1885     *
1886     * @see Theme#obtainStyledAttributes(AttributeSet, int[], int, int)
1887     */
1888    public TypedArray obtainAttributes(AttributeSet set, int[] attrs) {
1889        int len = attrs.length;
1890        TypedArray array = TypedArray.obtain(this, len);
1891
1892        // XXX note that for now we only work with compiled XML files.
1893        // To support generic XML files we will need to manually parse
1894        // out the attributes from the XML file (applying type information
1895        // contained in the resources and such).
1896        XmlBlock.Parser parser = (XmlBlock.Parser)set;
1897        mAssets.retrieveAttributes(parser.mParseState, attrs,
1898                array.mData, array.mIndices);
1899
1900        array.mXml = parser;
1901
1902        return array;
1903    }
1904
1905    /**
1906     * Store the newly updated configuration.
1907     */
1908    public void updateConfiguration(Configuration config,
1909            DisplayMetrics metrics) {
1910        updateConfiguration(config, metrics, null);
1911    }
1912
1913    /**
1914     * @hide
1915     */
1916    public void updateConfiguration(Configuration config,
1917            DisplayMetrics metrics, CompatibilityInfo compat) {
1918        synchronized (mAccessLock) {
1919            if (false) {
1920                Slog.i(TAG, "**** Updating config of " + this + ": old config is "
1921                        + mConfiguration + " old compat is " + mCompatibilityInfo);
1922                Slog.i(TAG, "**** Updating config of " + this + ": new config is "
1923                        + config + " new compat is " + compat);
1924            }
1925            if (compat != null) {
1926                mCompatibilityInfo = compat;
1927            }
1928            if (metrics != null) {
1929                mMetrics.setTo(metrics);
1930            }
1931            // NOTE: We should re-arrange this code to create a Display
1932            // with the CompatibilityInfo that is used everywhere we deal
1933            // with the display in relation to this app, rather than
1934            // doing the conversion here.  This impl should be okay because
1935            // we make sure to return a compatible display in the places
1936            // where there are public APIs to retrieve the display...  but
1937            // it would be cleaner and more maintainble to just be
1938            // consistently dealing with a compatible display everywhere in
1939            // the framework.
1940            mCompatibilityInfo.applyToDisplayMetrics(mMetrics);
1941
1942            final int configChanges = calcConfigChanges(config);
1943
1944            LocaleList locales = mConfiguration.getLocales();
1945            if (locales.isEmpty()) {
1946                locales = LocaleList.getAdjustedDefault();
1947                mConfiguration.setLocales(locales);
1948            }
1949            if (mConfiguration.densityDpi != Configuration.DENSITY_DPI_UNDEFINED) {
1950                mMetrics.densityDpi = mConfiguration.densityDpi;
1951                mMetrics.density = mConfiguration.densityDpi * DisplayMetrics.DENSITY_DEFAULT_SCALE;
1952            }
1953            mMetrics.scaledDensity = mMetrics.density * mConfiguration.fontScale;
1954
1955            final int width, height;
1956            if (mMetrics.widthPixels >= mMetrics.heightPixels) {
1957                width = mMetrics.widthPixels;
1958                height = mMetrics.heightPixels;
1959            } else {
1960                //noinspection SuspiciousNameCombination
1961                width = mMetrics.heightPixels;
1962                //noinspection SuspiciousNameCombination
1963                height = mMetrics.widthPixels;
1964            }
1965
1966            final int keyboardHidden;
1967            if (mConfiguration.keyboardHidden == Configuration.KEYBOARDHIDDEN_NO
1968                    && mConfiguration.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES) {
1969                keyboardHidden = Configuration.KEYBOARDHIDDEN_SOFT;
1970            } else {
1971                keyboardHidden = mConfiguration.keyboardHidden;
1972            }
1973
1974            mAssets.setConfiguration(mConfiguration.mcc, mConfiguration.mnc,
1975                    adjustLanguageTag(locales.get(0).toLanguageTag()),
1976                    mConfiguration.orientation,
1977                    mConfiguration.touchscreen,
1978                    mConfiguration.densityDpi, mConfiguration.keyboard,
1979                    keyboardHidden, mConfiguration.navigation, width, height,
1980                    mConfiguration.smallestScreenWidthDp,
1981                    mConfiguration.screenWidthDp, mConfiguration.screenHeightDp,
1982                    mConfiguration.screenLayout, mConfiguration.uiMode,
1983                    Build.VERSION.RESOURCES_SDK_INT);
1984
1985            if (DEBUG_CONFIG) {
1986                Slog.i(TAG, "**** Updating config of " + this + ": final config is "
1987                        + mConfiguration + " final compat is " + mCompatibilityInfo);
1988            }
1989
1990            mDrawableCache.onConfigurationChange(configChanges);
1991            mColorDrawableCache.onConfigurationChange(configChanges);
1992            mComplexColorCache.onConfigurationChange(configChanges);
1993            mAnimatorCache.onConfigurationChange(configChanges);
1994            mStateListAnimatorCache.onConfigurationChange(configChanges);
1995
1996            flushLayoutCache();
1997        }
1998        synchronized (sSync) {
1999            if (mPluralRule != null) {
2000                mPluralRule = PluralRules.forLocale(mConfiguration.getLocales().get(0));
2001            }
2002        }
2003    }
2004
2005    /**
2006     * Called by ConfigurationBoundResourceCacheTest via reflection.
2007     */
2008    private int calcConfigChanges(Configuration config) {
2009        int configChanges = 0xfffffff;
2010        if (config != null) {
2011            mTmpConfig.setTo(config);
2012            int density = config.densityDpi;
2013            if (density == Configuration.DENSITY_DPI_UNDEFINED) {
2014                density = mMetrics.noncompatDensityDpi;
2015            }
2016
2017            mCompatibilityInfo.applyToConfiguration(density, mTmpConfig);
2018
2019            if (mTmpConfig.getLocales().isEmpty()) {
2020                mTmpConfig.setLocales(LocaleList.getDefault());
2021            }
2022            configChanges = mConfiguration.updateFrom(mTmpConfig);
2023            configChanges = ActivityInfo.activityInfoConfigToNative(configChanges);
2024        }
2025        return configChanges;
2026    }
2027
2028    /**
2029     * {@code Locale.toLanguageTag} will transform the obsolete (and deprecated)
2030     * language codes "in", "ji" and "iw" to "id", "yi" and "he" respectively.
2031     *
2032     * All released versions of android prior to "L" used the deprecated language
2033     * tags, so we will need to support them for backwards compatibility.
2034     *
2035     * Note that this conversion needs to take place *after* the call to
2036     * {@code toLanguageTag} because that will convert all the deprecated codes to
2037     * the new ones, even if they're set manually.
2038     */
2039    private static String adjustLanguageTag(String languageTag) {
2040        final int separator = languageTag.indexOf('-');
2041        final String language;
2042        final String remainder;
2043
2044        if (separator == -1) {
2045            language = languageTag;
2046            remainder = "";
2047        } else {
2048            language = languageTag.substring(0, separator);
2049            remainder = languageTag.substring(separator);
2050        }
2051
2052        return Locale.adjustLanguageCode(language) + remainder;
2053    }
2054
2055    /**
2056     * Update the system resources configuration if they have previously
2057     * been initialized.
2058     *
2059     * @hide
2060     */
2061    public static void updateSystemConfiguration(Configuration config, DisplayMetrics metrics,
2062            CompatibilityInfo compat) {
2063        if (mSystem != null) {
2064            mSystem.updateConfiguration(config, metrics, compat);
2065            //Log.i(TAG, "Updated system resources " + mSystem
2066            //        + ": " + mSystem.getConfiguration());
2067        }
2068    }
2069
2070    /**
2071     * Return the current display metrics that are in effect for this resource
2072     * object.  The returned object should be treated as read-only.
2073     *
2074     * @return The resource's current display metrics.
2075     */
2076    public DisplayMetrics getDisplayMetrics() {
2077        if (DEBUG_CONFIG) Slog.v(TAG, "Returning DisplayMetrics: " + mMetrics.widthPixels
2078                + "x" + mMetrics.heightPixels + " " + mMetrics.density);
2079        return mMetrics;
2080    }
2081
2082    /**
2083     * Return the current configuration that is in effect for this resource
2084     * object.  The returned object should be treated as read-only.
2085     *
2086     * @return The resource's current configuration.
2087     */
2088    public Configuration getConfiguration() {
2089        return mConfiguration;
2090    }
2091
2092    /** @hide */
2093    public Configuration[] getSizeConfigurations() {
2094        return mAssets.getSizeConfigurations();
2095    };
2096
2097    /**
2098     * Return the compatibility mode information for the application.
2099     * The returned object should be treated as read-only.
2100     *
2101     * @return compatibility info.
2102     * @hide
2103     */
2104    public CompatibilityInfo getCompatibilityInfo() {
2105        return mCompatibilityInfo;
2106    }
2107
2108    /**
2109     * This is just for testing.
2110     * @hide
2111     */
2112    public void setCompatibilityInfo(CompatibilityInfo ci) {
2113        if (ci != null) {
2114            mCompatibilityInfo = ci;
2115            updateConfiguration(mConfiguration, mMetrics);
2116        }
2117    }
2118
2119    /**
2120     * Return a resource identifier for the given resource name.  A fully
2121     * qualified resource name is of the form "package:type/entry".  The first
2122     * two components (package and type) are optional if defType and
2123     * defPackage, respectively, are specified here.
2124     *
2125     * <p>Note: use of this function is discouraged.  It is much more
2126     * efficient to retrieve resources by identifier than by name.
2127     *
2128     * @param name The name of the desired resource.
2129     * @param defType Optional default resource type to find, if "type/" is
2130     *                not included in the name.  Can be null to require an
2131     *                explicit type.
2132     * @param defPackage Optional default package to find, if "package:" is
2133     *                   not included in the name.  Can be null to require an
2134     *                   explicit package.
2135     *
2136     * @return int The associated resource identifier.  Returns 0 if no such
2137     *         resource was found.  (0 is not a valid resource ID.)
2138     */
2139    public int getIdentifier(String name, String defType, String defPackage) {
2140        if (name == null) {
2141            throw new NullPointerException("name is null");
2142        }
2143        try {
2144            return Integer.parseInt(name);
2145        } catch (Exception e) {
2146            // Ignore
2147        }
2148        return mAssets.getResourceIdentifier(name, defType, defPackage);
2149    }
2150
2151    /**
2152     * Return true if given resource identifier includes a package.
2153     *
2154     * @hide
2155     */
2156    public static boolean resourceHasPackage(@AnyRes int resid) {
2157        return (resid >>> 24) != 0;
2158    }
2159
2160    /**
2161     * Return the full name for a given resource identifier.  This name is
2162     * a single string of the form "package:type/entry".
2163     *
2164     * @param resid The resource identifier whose name is to be retrieved.
2165     *
2166     * @return A string holding the name of the resource.
2167     *
2168     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
2169     *
2170     * @see #getResourcePackageName
2171     * @see #getResourceTypeName
2172     * @see #getResourceEntryName
2173     */
2174    public String getResourceName(@AnyRes int resid) throws NotFoundException {
2175        String str = mAssets.getResourceName(resid);
2176        if (str != null) return str;
2177        throw new NotFoundException("Unable to find resource ID #0x"
2178                + Integer.toHexString(resid));
2179    }
2180
2181    /**
2182     * Return the package name for a given resource identifier.
2183     *
2184     * @param resid The resource identifier whose package name is to be
2185     * retrieved.
2186     *
2187     * @return A string holding the package name of the resource.
2188     *
2189     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
2190     *
2191     * @see #getResourceName
2192     */
2193    public String getResourcePackageName(@AnyRes int resid) throws NotFoundException {
2194        String str = mAssets.getResourcePackageName(resid);
2195        if (str != null) return str;
2196        throw new NotFoundException("Unable to find resource ID #0x"
2197                + Integer.toHexString(resid));
2198    }
2199
2200    /**
2201     * Return the type name for a given resource identifier.
2202     *
2203     * @param resid The resource identifier whose type name is to be
2204     * retrieved.
2205     *
2206     * @return A string holding the type name of the resource.
2207     *
2208     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
2209     *
2210     * @see #getResourceName
2211     */
2212    public String getResourceTypeName(@AnyRes int resid) throws NotFoundException {
2213        String str = mAssets.getResourceTypeName(resid);
2214        if (str != null) return str;
2215        throw new NotFoundException("Unable to find resource ID #0x"
2216                + Integer.toHexString(resid));
2217    }
2218
2219    /**
2220     * Return the entry name for a given resource identifier.
2221     *
2222     * @param resid The resource identifier whose entry name is to be
2223     * retrieved.
2224     *
2225     * @return A string holding the entry name of the resource.
2226     *
2227     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
2228     *
2229     * @see #getResourceName
2230     */
2231    public String getResourceEntryName(@AnyRes int resid) throws NotFoundException {
2232        String str = mAssets.getResourceEntryName(resid);
2233        if (str != null) return str;
2234        throw new NotFoundException("Unable to find resource ID #0x"
2235                + Integer.toHexString(resid));
2236    }
2237
2238    /**
2239     * Parse a series of {@link android.R.styleable#Extra &lt;extra&gt;} tags from
2240     * an XML file.  You call this when you are at the parent tag of the
2241     * extra tags, and it will return once all of the child tags have been parsed.
2242     * This will call {@link #parseBundleExtra} for each extra tag encountered.
2243     *
2244     * @param parser The parser from which to retrieve the extras.
2245     * @param outBundle A Bundle in which to place all parsed extras.
2246     * @throws XmlPullParserException
2247     * @throws IOException
2248     */
2249    public void parseBundleExtras(XmlResourceParser parser, Bundle outBundle)
2250            throws XmlPullParserException, IOException {
2251        int outerDepth = parser.getDepth();
2252        int type;
2253        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2254               && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2255            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2256                continue;
2257            }
2258
2259            String nodeName = parser.getName();
2260            if (nodeName.equals("extra")) {
2261                parseBundleExtra("extra", parser, outBundle);
2262                XmlUtils.skipCurrentTag(parser);
2263
2264            } else {
2265                XmlUtils.skipCurrentTag(parser);
2266            }
2267        }
2268    }
2269
2270    /**
2271     * Parse a name/value pair out of an XML tag holding that data.  The
2272     * AttributeSet must be holding the data defined by
2273     * {@link android.R.styleable#Extra}.  The following value types are supported:
2274     * <ul>
2275     * <li> {@link TypedValue#TYPE_STRING}:
2276     * {@link Bundle#putCharSequence Bundle.putCharSequence()}
2277     * <li> {@link TypedValue#TYPE_INT_BOOLEAN}:
2278     * {@link Bundle#putCharSequence Bundle.putBoolean()}
2279     * <li> {@link TypedValue#TYPE_FIRST_INT}-{@link TypedValue#TYPE_LAST_INT}:
2280     * {@link Bundle#putCharSequence Bundle.putBoolean()}
2281     * <li> {@link TypedValue#TYPE_FLOAT}:
2282     * {@link Bundle#putCharSequence Bundle.putFloat()}
2283     * </ul>
2284     *
2285     * @param tagName The name of the tag these attributes come from; this is
2286     * only used for reporting error messages.
2287     * @param attrs The attributes from which to retrieve the name/value pair.
2288     * @param outBundle The Bundle in which to place the parsed value.
2289     * @throws XmlPullParserException If the attributes are not valid.
2290     */
2291    public void parseBundleExtra(String tagName, AttributeSet attrs,
2292            Bundle outBundle) throws XmlPullParserException {
2293        TypedArray sa = obtainAttributes(attrs,
2294                com.android.internal.R.styleable.Extra);
2295
2296        String name = sa.getString(
2297                com.android.internal.R.styleable.Extra_name);
2298        if (name == null) {
2299            sa.recycle();
2300            throw new XmlPullParserException("<" + tagName
2301                    + "> requires an android:name attribute at "
2302                    + attrs.getPositionDescription());
2303        }
2304
2305        TypedValue v = sa.peekValue(
2306                com.android.internal.R.styleable.Extra_value);
2307        if (v != null) {
2308            if (v.type == TypedValue.TYPE_STRING) {
2309                CharSequence cs = v.coerceToString();
2310                outBundle.putCharSequence(name, cs);
2311            } else if (v.type == TypedValue.TYPE_INT_BOOLEAN) {
2312                outBundle.putBoolean(name, v.data != 0);
2313            } else if (v.type >= TypedValue.TYPE_FIRST_INT
2314                    && v.type <= TypedValue.TYPE_LAST_INT) {
2315                outBundle.putInt(name, v.data);
2316            } else if (v.type == TypedValue.TYPE_FLOAT) {
2317                outBundle.putFloat(name, v.getFloat());
2318            } else {
2319                sa.recycle();
2320                throw new XmlPullParserException("<" + tagName
2321                        + "> only supports string, integer, float, color, and boolean at "
2322                        + attrs.getPositionDescription());
2323            }
2324        } else {
2325            sa.recycle();
2326            throw new XmlPullParserException("<" + tagName
2327                    + "> requires an android:value or android:resource attribute at "
2328                    + attrs.getPositionDescription());
2329        }
2330
2331        sa.recycle();
2332    }
2333
2334    /**
2335     * Retrieve underlying AssetManager storage for these resources.
2336     */
2337    public final AssetManager getAssets() {
2338        return mAssets;
2339    }
2340
2341    /**
2342     * Call this to remove all cached loaded layout resources from the
2343     * Resources object.  Only intended for use with performance testing
2344     * tools.
2345     */
2346    public final void flushLayoutCache() {
2347        synchronized (mCachedXmlBlocks) {
2348            Arrays.fill(mCachedXmlBlockCookies, 0);
2349            Arrays.fill(mCachedXmlBlockFiles, null);
2350
2351            final XmlBlock[] cachedXmlBlocks = mCachedXmlBlocks;
2352            for (int i = 0; i < XML_BLOCK_CACHE_SIZE; i++) {
2353                final XmlBlock oldBlock = cachedXmlBlocks[i];
2354                if (oldBlock != null) {
2355                    oldBlock.close();
2356                }
2357            }
2358            Arrays.fill(cachedXmlBlocks, null);
2359        }
2360    }
2361
2362    /**
2363     * Start preloading of resource data using this Resources object.  Only
2364     * for use by the zygote process for loading common system resources.
2365     * {@hide}
2366     */
2367    public final void startPreloading() {
2368        synchronized (sSync) {
2369            if (sPreloaded) {
2370                throw new IllegalStateException("Resources already preloaded");
2371            }
2372            sPreloaded = true;
2373            mPreloading = true;
2374            mConfiguration.densityDpi = DisplayMetrics.DENSITY_DEVICE;
2375            updateConfiguration(null, null);
2376        }
2377    }
2378
2379    /**
2380     * Called by zygote when it is done preloading resources, to change back
2381     * to normal Resources operation.
2382     */
2383    public final void finishPreloading() {
2384        if (mPreloading) {
2385            mPreloading = false;
2386            flushLayoutCache();
2387        }
2388    }
2389
2390    /**
2391     * @hide
2392     */
2393    public LongSparseArray<ConstantState> getPreloadedDrawables() {
2394        return sPreloadedDrawables[0];
2395    }
2396
2397    private boolean verifyPreloadConfig(int changingConfigurations, int allowVarying,
2398            int resourceId, String name) {
2399        // We allow preloading of resources even if they vary by font scale (which
2400        // doesn't impact resource selection) or density (which we handle specially by
2401        // simply turning off all preloading), as well as any other configs specified
2402        // by the caller.
2403        if (((changingConfigurations&~(ActivityInfo.CONFIG_FONT_SCALE |
2404                ActivityInfo.CONFIG_DENSITY)) & ~allowVarying) != 0) {
2405            String resName;
2406            try {
2407                resName = getResourceName(resourceId);
2408            } catch (NotFoundException e) {
2409                resName = "?";
2410            }
2411            // This should never happen in production, so we should log a
2412            // warning even if we're not debugging.
2413            Log.w(TAG, "Preloaded " + name + " resource #0x"
2414                    + Integer.toHexString(resourceId)
2415                    + " (" + resName + ") that varies with configuration!!");
2416            return false;
2417        }
2418        if (TRACE_FOR_PRELOAD) {
2419            String resName;
2420            try {
2421                resName = getResourceName(resourceId);
2422            } catch (NotFoundException e) {
2423                resName = "?";
2424            }
2425            Log.w(TAG, "Preloading " + name + " resource #0x"
2426                    + Integer.toHexString(resourceId)
2427                    + " (" + resName + ")");
2428        }
2429        return true;
2430    }
2431
2432    @Nullable
2433    Drawable loadDrawable(TypedValue value, int id, Theme theme) throws NotFoundException {
2434        return loadDrawable(value, id, theme, true);
2435    }
2436
2437    @Nullable
2438    Drawable loadDrawable(TypedValue value, int id, Theme theme, boolean useCache)
2439            throws NotFoundException {
2440        try {
2441            if (TRACE_FOR_PRELOAD) {
2442                // Log only framework resources
2443                if ((id >>> 24) == 0x1) {
2444                    final String name = getResourceName(id);
2445                    if (name != null) {
2446                        Log.d("PreloadDrawable", name);
2447                    }
2448                }
2449            }
2450
2451            final boolean isColorDrawable;
2452            final DrawableCache caches;
2453            final long key;
2454            if (value.type >= TypedValue.TYPE_FIRST_COLOR_INT
2455                    && value.type <= TypedValue.TYPE_LAST_COLOR_INT) {
2456                isColorDrawable = true;
2457                caches = mColorDrawableCache;
2458                key = value.data;
2459            } else {
2460                isColorDrawable = false;
2461                caches = mDrawableCache;
2462                key = (((long) value.assetCookie) << 32) | value.data;
2463            }
2464
2465            // First, check whether we have a cached version of this drawable
2466            // that was inflated against the specified theme. Skip the cache if
2467            // we're currently preloading or we're not using the cache.
2468            if (!mPreloading && useCache) {
2469                final Drawable cachedDrawable = caches.getInstance(key, theme);
2470                if (cachedDrawable != null) {
2471                    return cachedDrawable;
2472                }
2473            }
2474
2475            // Next, check preloaded drawables. Preloaded drawables may contain
2476            // unresolved theme attributes.
2477            final ConstantState cs;
2478            if (isColorDrawable) {
2479                cs = sPreloadedColorDrawables.get(key);
2480            } else {
2481                cs = sPreloadedDrawables[mConfiguration.getLayoutDirection()].get(key);
2482            }
2483
2484            Drawable dr;
2485            if (cs != null) {
2486                dr = cs.newDrawable(this);
2487            } else if (isColorDrawable) {
2488                dr = new ColorDrawable(value.data);
2489            } else {
2490                dr = loadDrawableForCookie(value, id, null);
2491            }
2492
2493            // Determine if the drawable has unresolved theme attributes. If it
2494            // does, we'll need to apply a theme and store it in a theme-specific
2495            // cache.
2496            final boolean canApplyTheme = dr != null && dr.canApplyTheme();
2497            if (canApplyTheme && theme != null) {
2498                dr = dr.mutate();
2499                dr.applyTheme(theme);
2500                dr.clearMutated();
2501            }
2502
2503            // If we were able to obtain a drawable, store it in the appropriate
2504            // cache: preload, not themed, null theme, or theme-specific. Don't
2505            // pollute the cache with drawables loaded from a foreign density.
2506            if (dr != null && useCache) {
2507                dr.setChangingConfigurations(value.changingConfigurations);
2508                cacheDrawable(value, isColorDrawable, caches, theme, canApplyTheme, key, dr);
2509            }
2510
2511            return dr;
2512        } catch (Exception e) {
2513            String name;
2514            try {
2515                name = getResourceName(id);
2516            } catch (NotFoundException e2) {
2517                name = "(missing name)";
2518            }
2519
2520            // The target drawable might fail to load for any number of
2521            // reasons, but we always want to include the resource name.
2522            // Since the client already expects this method to throw a
2523            // NotFoundException, just throw one of those.
2524            final NotFoundException nfe = new NotFoundException("Drawable " + name
2525                    + " with resource ID #0x" + Integer.toHexString(id), e);
2526            nfe.setStackTrace(new StackTraceElement[0]);
2527            throw nfe;
2528        }
2529    }
2530
2531    private void cacheDrawable(TypedValue value, boolean isColorDrawable, DrawableCache caches,
2532            Theme theme, boolean usesTheme, long key, Drawable dr) {
2533        final ConstantState cs = dr.getConstantState();
2534        if (cs == null) {
2535            return;
2536        }
2537
2538        if (mPreloading) {
2539            final int changingConfigs = cs.getChangingConfigurations();
2540            if (isColorDrawable) {
2541                if (verifyPreloadConfig(changingConfigs, 0, value.resourceId, "drawable")) {
2542                    sPreloadedColorDrawables.put(key, cs);
2543                }
2544            } else {
2545                if (verifyPreloadConfig(
2546                        changingConfigs, LAYOUT_DIR_CONFIG, value.resourceId, "drawable")) {
2547                    if ((changingConfigs & LAYOUT_DIR_CONFIG) == 0) {
2548                        // If this resource does not vary based on layout direction,
2549                        // we can put it in all of the preload maps.
2550                        sPreloadedDrawables[0].put(key, cs);
2551                        sPreloadedDrawables[1].put(key, cs);
2552                    } else {
2553                        // Otherwise, only in the layout dir we loaded it for.
2554                        sPreloadedDrawables[mConfiguration.getLayoutDirection()].put(key, cs);
2555                    }
2556                }
2557            }
2558        } else {
2559            synchronized (mAccessLock) {
2560                caches.put(key, theme, cs, usesTheme);
2561            }
2562        }
2563    }
2564
2565    /**
2566     * Loads a drawable from XML or resources stream.
2567     */
2568    private Drawable loadDrawableForCookie(TypedValue value, int id, Theme theme) {
2569        if (value.string == null) {
2570            throw new NotFoundException("Resource \"" + getResourceName(id) + "\" ("
2571                    + Integer.toHexString(id) + ") is not a Drawable (color or path): " + value);
2572        }
2573
2574        final String file = value.string.toString();
2575
2576        if (TRACE_FOR_MISS_PRELOAD) {
2577            // Log only framework resources
2578            if ((id >>> 24) == 0x1) {
2579                final String name = getResourceName(id);
2580                if (name != null) {
2581                    Log.d(TAG, "Loading framework drawable #" + Integer.toHexString(id)
2582                            + ": " + name + " at " + file);
2583                }
2584            }
2585        }
2586
2587        if (DEBUG_LOAD) {
2588            Log.v(TAG, "Loading drawable for cookie " + value.assetCookie + ": " + file);
2589        }
2590
2591        final Drawable dr;
2592
2593        Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, file);
2594        try {
2595            if (file.endsWith(".xml")) {
2596                final XmlResourceParser rp = loadXmlResourceParser(
2597                        file, id, value.assetCookie, "drawable");
2598                dr = Drawable.createFromXml(this, rp, theme);
2599                rp.close();
2600            } else {
2601                final InputStream is = mAssets.openNonAsset(
2602                        value.assetCookie, file, AssetManager.ACCESS_STREAMING);
2603                dr = Drawable.createFromResourceStream(this, value, is, file, null);
2604                is.close();
2605            }
2606        } catch (Exception e) {
2607            Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
2608            final NotFoundException rnf = new NotFoundException(
2609                    "File " + file + " from drawable resource ID #0x" + Integer.toHexString(id));
2610            rnf.initCause(e);
2611            throw rnf;
2612        }
2613        Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
2614
2615        return dr;
2616    }
2617
2618    /**
2619     * Given the value and id, we can get the XML filename as in value.data, based on that, we
2620     * first try to load CSL from the cache. If not found, try to get from the constant state.
2621     * Last, parse the XML and generate the CSL.
2622     */
2623    private ComplexColor loadComplexColorFromName(Theme theme, TypedValue value, int id) {
2624        final long key = (((long) value.assetCookie) << 32) | value.data;
2625        final ConfigurationBoundResourceCache<ComplexColor> cache = mComplexColorCache;
2626        ComplexColor complexColor = cache.getInstance(key, theme);
2627        if (complexColor != null) {
2628            return complexColor;
2629        }
2630
2631        final android.content.res.ConstantState<ComplexColor> factory =
2632                sPreloadedComplexColors.get(key);
2633
2634        if (factory != null) {
2635            complexColor = factory.newInstance(this, theme);
2636        }
2637        if (complexColor == null) {
2638            complexColor = loadComplexColorForCookie(value, id, theme);
2639        }
2640
2641        if (complexColor != null) {
2642            if (mPreloading) {
2643                if (verifyPreloadConfig(value.changingConfigurations, 0, value.resourceId,
2644                        "color")) {
2645                    sPreloadedComplexColors.put(key, complexColor.getConstantState());
2646                }
2647            } else {
2648                cache.put(key, theme, complexColor.getConstantState());
2649            }
2650        }
2651        return complexColor;
2652    }
2653
2654    @Nullable
2655    public ComplexColor loadComplexColor(@NonNull TypedValue value, int id, Theme theme) {
2656        if (TRACE_FOR_PRELOAD) {
2657            // Log only framework resources
2658            if ((id >>> 24) == 0x1) {
2659                final String name = getResourceName(id);
2660                if (name != null) android.util.Log.d("loadComplexColor", name);
2661            }
2662        }
2663
2664        final long key = (((long) value.assetCookie) << 32) | value.data;
2665
2666        // Handle inline color definitions.
2667        if (value.type >= TypedValue.TYPE_FIRST_COLOR_INT
2668                && value.type <= TypedValue.TYPE_LAST_COLOR_INT) {
2669            return getColorStateListFromInt(value, key);
2670        }
2671
2672        final String file = value.string.toString();
2673
2674        ComplexColor complexColor;
2675        if (file.endsWith(".xml")) {
2676            try {
2677                complexColor = loadComplexColorFromName(theme, value, id);
2678            } catch (Exception e) {
2679                final NotFoundException rnf = new NotFoundException(
2680                        "File " + file + " from complex color resource ID #0x"
2681                                + Integer.toHexString(id));
2682                rnf.initCause(e);
2683                throw rnf;
2684            }
2685        } else {
2686            throw new NotFoundException(
2687                    "File " + file + " from drawable resource ID #0x"
2688                            + Integer.toHexString(id) + ": .xml extension required");
2689        }
2690
2691        return complexColor;
2692    }
2693
2694    @Nullable
2695    ColorStateList loadColorStateList(TypedValue value, int id, Theme theme)
2696            throws NotFoundException {
2697        if (TRACE_FOR_PRELOAD) {
2698            // Log only framework resources
2699            if ((id >>> 24) == 0x1) {
2700                final String name = getResourceName(id);
2701                if (name != null) android.util.Log.d("PreloadColorStateList", name);
2702            }
2703        }
2704
2705        final long key = (((long) value.assetCookie) << 32) | value.data;
2706
2707        // Handle inline color definitions.
2708        if (value.type >= TypedValue.TYPE_FIRST_COLOR_INT
2709                && value.type <= TypedValue.TYPE_LAST_COLOR_INT) {
2710            return getColorStateListFromInt(value, key);
2711        }
2712
2713        ComplexColor complexColor = loadComplexColorFromName(theme, value, id);
2714        if (complexColor != null && complexColor instanceof ColorStateList) {
2715            return (ColorStateList) complexColor;
2716        }
2717
2718        throw new NotFoundException(
2719                "Can't find ColorStateList from drawable resource ID #0x"
2720                        + Integer.toHexString(id));
2721    }
2722
2723    @NonNull
2724    private ColorStateList getColorStateListFromInt(@NonNull  TypedValue value, long key) {
2725        ColorStateList csl;
2726        final android.content.res.ConstantState<ComplexColor> factory =
2727                sPreloadedComplexColors.get(key);
2728        if (factory != null) {
2729            return (ColorStateList) factory.newInstance();
2730        }
2731
2732        csl = ColorStateList.valueOf(value.data);
2733
2734        if (mPreloading) {
2735            if (verifyPreloadConfig(value.changingConfigurations, 0, value.resourceId,
2736                    "color")) {
2737                sPreloadedComplexColors.put(key, csl.getConstantState());
2738            }
2739        }
2740
2741        return csl;
2742    }
2743
2744    /**
2745     * Load a ComplexColor based on the XML file content. The result can be a GradientColor or
2746     * ColorStateList. Note that pure color will be wrapped into a ColorStateList.
2747     *
2748     * We deferred the parser creation to this function b/c we need to differentiate b/t gradient
2749     * and selector tag.
2750     *
2751     * @return a ComplexColor (GradientColor or ColorStateList) based on the XML file content.
2752     */
2753    @Nullable
2754    private ComplexColor loadComplexColorForCookie(TypedValue value, int id, Theme theme) {
2755        if (value.string == null) {
2756            throw new UnsupportedOperationException(
2757                    "Can't convert to ComplexColor: type=0x" + value.type);
2758        }
2759
2760        final String file = value.string.toString();
2761
2762        if (TRACE_FOR_MISS_PRELOAD) {
2763            // Log only framework resources
2764            if ((id >>> 24) == 0x1) {
2765                final String name = getResourceName(id);
2766                if (name != null) {
2767                    Log.d(TAG, "Loading framework ComplexColor #" + Integer.toHexString(id)
2768                            + ": " + name + " at " + file);
2769                }
2770            }
2771        }
2772
2773        if (DEBUG_LOAD) {
2774            Log.v(TAG, "Loading ComplexColor for cookie " + value.assetCookie + ": " + file);
2775        }
2776
2777        ComplexColor complexColor = null;
2778
2779        Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, file);
2780        if (file.endsWith(".xml")) {
2781            try {
2782                final XmlResourceParser parser = loadXmlResourceParser(
2783                        file, id, value.assetCookie, "ComplexColor");
2784
2785                final AttributeSet attrs = Xml.asAttributeSet(parser);
2786                int type;
2787                while ((type = parser.next()) != XmlPullParser.START_TAG
2788                        && type != XmlPullParser.END_DOCUMENT) {
2789                    // Seek parser to start tag.
2790                }
2791                if (type != XmlPullParser.START_TAG) {
2792                    throw new XmlPullParserException("No start tag found");
2793                }
2794
2795                final String name = parser.getName();
2796                if (name.equals("gradient")) {
2797                    complexColor = GradientColor.createFromXmlInner(this, parser, attrs, theme);
2798                } else if (name.equals("selector")) {
2799                    complexColor = ColorStateList.createFromXmlInner(this, parser, attrs, theme);
2800                }
2801                parser.close();
2802            } catch (Exception e) {
2803                Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
2804                final NotFoundException rnf = new NotFoundException(
2805                        "File " + file + " from ComplexColor resource ID #0x"
2806                                + Integer.toHexString(id));
2807                rnf.initCause(e);
2808                throw rnf;
2809            }
2810        } else {
2811            Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
2812            throw new NotFoundException(
2813                    "File " + file + " from drawable resource ID #0x"
2814                            + Integer.toHexString(id) + ": .xml extension required");
2815        }
2816        Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
2817
2818        return complexColor;
2819    }
2820
2821    /**
2822     * Loads an XML parser for the specified file.
2823     *
2824     * @param id the resource identifier for the file
2825     * @param type the type of resource (used for logging)
2826     * @return a parser for the specified XML file
2827     * @throws NotFoundException if the file could not be loaded
2828     */
2829    @NonNull
2830    XmlResourceParser loadXmlResourceParser(@AnyRes int id, @NonNull String type)
2831            throws NotFoundException {
2832        final TypedValue value = obtainTempTypedValue(id);
2833        try {
2834            if (value.type == TypedValue.TYPE_STRING) {
2835                return loadXmlResourceParser(value.string.toString(), id,
2836                        value.assetCookie, type);
2837            }
2838            throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id)
2839                    + " type #0x" + Integer.toHexString(value.type) + " is not valid");
2840        } finally {
2841            releaseTempTypedValue(value);
2842        }
2843    }
2844
2845    /**
2846     * Loads an XML parser for the specified file.
2847     *
2848     * @param file the path for the XML file to parse
2849     * @param id the resource identifier for the file
2850     * @param assetCookie the asset cookie for the file
2851     * @param type the type of resource (used for logging)
2852     * @return a parser for the specified XML file
2853     * @throws NotFoundException if the file could not be loaded
2854     */
2855    @NonNull
2856    XmlResourceParser loadXmlResourceParser(@NonNull String file, @AnyRes int id,
2857            int assetCookie, @NonNull String type) throws NotFoundException {
2858        if (id != 0) {
2859            try {
2860                synchronized (mCachedXmlBlocks) {
2861                    final int[] cachedXmlBlockCookies = mCachedXmlBlockCookies;
2862                    final String[] cachedXmlBlockFiles = mCachedXmlBlockFiles;
2863                    final XmlBlock[] cachedXmlBlocks = mCachedXmlBlocks;
2864                    // First see if this block is in our cache.
2865                    final int num = cachedXmlBlockFiles.length;
2866                    for (int i = 0; i < num; i++) {
2867                        if (cachedXmlBlockCookies[i] == assetCookie && cachedXmlBlockFiles[i] != null
2868                                && cachedXmlBlockFiles[i].equals(file)) {
2869                            return cachedXmlBlocks[i].newParser();
2870                        }
2871                    }
2872
2873                    // Not in the cache, create a new block and put it at
2874                    // the next slot in the cache.
2875                    final XmlBlock block = mAssets.openXmlBlockAsset(assetCookie, file);
2876                    if (block != null) {
2877                        final int pos = (mLastCachedXmlBlockIndex + 1) % num;
2878                        mLastCachedXmlBlockIndex = pos;
2879                        final XmlBlock oldBlock = cachedXmlBlocks[pos];
2880                        if (oldBlock != null) {
2881                            oldBlock.close();
2882                        }
2883                        cachedXmlBlockCookies[pos] = assetCookie;
2884                        cachedXmlBlockFiles[pos] = file;
2885                        cachedXmlBlocks[pos] = block;
2886                        return block.newParser();
2887                    }
2888                }
2889            } catch (Exception e) {
2890                final NotFoundException rnf = new NotFoundException("File " + file
2891                        + " from xml type " + type + " resource ID #0x" + Integer.toHexString(id));
2892                rnf.initCause(e);
2893                throw rnf;
2894            }
2895        }
2896
2897        throw new NotFoundException("File " + file + " from xml type " + type + " resource ID #0x"
2898                + Integer.toHexString(id));
2899    }
2900
2901    /**
2902     * Obtains styled attributes from the theme, if available, or unstyled
2903     * resources if the theme is null.
2904     *
2905     * @hide
2906     */
2907    public static TypedArray obtainAttributes(
2908            Resources res, Theme theme, AttributeSet set, int[] attrs) {
2909        if (theme == null) {
2910            return res.obtainAttributes(set, attrs);
2911        }
2912        return theme.obtainStyledAttributes(set, attrs, 0, 0);
2913    }
2914
2915    private Resources() {
2916        mAssets = AssetManager.getSystem();
2917        mClassLoader = ClassLoader.getSystemClassLoader();
2918        // NOTE: Intentionally leaving this uninitialized (all values set
2919        // to zero), so that anyone who tries to do something that requires
2920        // metrics will get a very wrong value.
2921        mConfiguration.setToDefaults();
2922        mMetrics.setToDefaults();
2923        updateConfiguration(null, null);
2924        mAssets.ensureStringBlocks();
2925    }
2926}
2927