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