Resources.java revision 6090995951c6e2e4dcf38102f01793f8a94166e1
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 com.android.internal.util.XmlUtils;
20
21import org.xmlpull.v1.XmlPullParser;
22import org.xmlpull.v1.XmlPullParserException;
23
24import android.content.pm.ActivityInfo;
25import android.graphics.Movie;
26import android.graphics.drawable.Drawable;
27import android.graphics.drawable.ColorDrawable;
28import android.graphics.drawable.Drawable.ConstantState;
29import android.os.Build;
30import android.os.Bundle;
31import android.os.IBinder;
32import android.os.Trace;
33import android.util.AttributeSet;
34import android.util.DisplayMetrics;
35import android.util.Log;
36import android.util.Slog;
37import android.util.TypedValue;
38import android.util.LongSparseArray;
39
40import java.io.IOException;
41import java.io.InputStream;
42import java.lang.ref.WeakReference;
43import java.util.Locale;
44
45import libcore.icu.NativePluralRules;
46
47/**
48 * Class for accessing an application's resources.  This sits on top of the
49 * asset manager of the application (accessible through {@link #getAssets}) and
50 * provides a high-level API for getting typed data from the assets.
51 *
52 * <p>The Android resource system keeps track of all non-code assets associated with an
53 * application. You can use this class to access your application's resources. You can generally
54 * acquire the {@link android.content.res.Resources} instance associated with your application
55 * with {@link android.content.Context#getResources getResources()}.</p>
56 *
57 * <p>The Android SDK tools compile your application's resources into the application binary
58 * at build time.  To use a resource, you must install it correctly in the source tree (inside
59 * your project's {@code res/} directory) and build your application.  As part of the build
60 * process, the SDK tools generate symbols for each resource, which you can use in your application
61 * code to access the resources.</p>
62 *
63 * <p>Using application resources makes it easy to update various characteristics of your
64 * application without modifying code, and&mdash;by providing sets of alternative
65 * resources&mdash;enables you to optimize your application for a variety of device configurations
66 * (such as for different languages and screen sizes). This is an important aspect of developing
67 * Android applications that are compatible on different types of devices.</p>
68 *
69 * <p>For more information about using resources, see the documentation about <a
70 * href="{@docRoot}guide/topics/resources/index.html">Application Resources</a>.</p>
71 */
72public class Resources {
73    static final String TAG = "Resources";
74    private static final boolean DEBUG_LOAD = false;
75    private static final boolean DEBUG_CONFIG = false;
76    private static final boolean DEBUG_ATTRIBUTES_CACHE = false;
77    private static final boolean TRACE_FOR_PRELOAD = false;
78    private static final boolean TRACE_FOR_MISS_PRELOAD = false;
79
80    private static final int ID_OTHER = 0x01000004;
81
82    private static final Object sSync = new Object();
83    /*package*/ static Resources mSystem = null;
84
85    // Information about preloaded resources.  Note that they are not
86    // protected by a lock, because while preloading in zygote we are all
87    // single-threaded, and after that these are immutable.
88    private static final LongSparseArray<Drawable.ConstantState>[] sPreloadedDrawables;
89    private static final LongSparseArray<Drawable.ConstantState> sPreloadedColorDrawables
90            = new LongSparseArray<Drawable.ConstantState>();
91    private static final LongSparseArray<ColorStateList> sPreloadedColorStateLists
92            = new LongSparseArray<ColorStateList>();
93
94    private static boolean sPreloaded;
95    private static int sPreloadedDensity;
96
97    // These are protected by mAccessLock.
98
99    /*package*/ final Object mAccessLock = new Object();
100    /*package*/ final Configuration mTmpConfig = new Configuration();
101    /*package*/ TypedValue mTmpValue = new TypedValue();
102    /*package*/ final LongSparseArray<WeakReference<Drawable.ConstantState> > mDrawableCache
103            = new LongSparseArray<WeakReference<Drawable.ConstantState> >(0);
104    /*package*/ final LongSparseArray<WeakReference<ColorStateList> > mColorStateListCache
105            = new LongSparseArray<WeakReference<ColorStateList> >(0);
106    /*package*/ final LongSparseArray<WeakReference<Drawable.ConstantState> > mColorDrawableCache
107            = new LongSparseArray<WeakReference<Drawable.ConstantState> >(0);
108    /*package*/ boolean mPreloading;
109
110    /*package*/ TypedArray mCachedStyledAttributes = null;
111    RuntimeException mLastRetrievedAttrs = null;
112
113    private int mLastCachedXmlBlockIndex = -1;
114    private final int[] mCachedXmlBlockIds = { 0, 0, 0, 0 };
115    private final XmlBlock[] mCachedXmlBlocks = new XmlBlock[4];
116
117    /*package*/ final AssetManager mAssets;
118    private final Configuration mConfiguration = new Configuration();
119    /*package*/ final DisplayMetrics mMetrics = new DisplayMetrics();
120    private NativePluralRules mPluralRule;
121
122    private CompatibilityInfo mCompatibilityInfo = CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO;
123    private WeakReference<IBinder> mToken;
124
125    static {
126        sPreloadedDrawables = new LongSparseArray[2];
127        sPreloadedDrawables[0] = new LongSparseArray<Drawable.ConstantState>();
128        sPreloadedDrawables[1] = new LongSparseArray<Drawable.ConstantState>();
129    }
130
131    /** @hide */
132    public static int selectDefaultTheme(int curTheme, int targetSdkVersion) {
133        return selectSystemTheme(curTheme, targetSdkVersion,
134                com.android.internal.R.style.Theme,
135                com.android.internal.R.style.Theme_Holo,
136                com.android.internal.R.style.Theme_DeviceDefault);
137    }
138
139    /** @hide */
140    public static int selectSystemTheme(int curTheme, int targetSdkVersion,
141            int orig, int holo, int deviceDefault) {
142        if (curTheme != 0) {
143            return curTheme;
144        }
145        if (targetSdkVersion < Build.VERSION_CODES.HONEYCOMB) {
146            return orig;
147        }
148        if (targetSdkVersion < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
149            return holo;
150        }
151        return deviceDefault;
152    }
153
154    /**
155     * This exception is thrown by the resource APIs when a requested resource
156     * can not be found.
157     */
158    public static class NotFoundException extends RuntimeException {
159        public NotFoundException() {
160        }
161
162        public NotFoundException(String name) {
163            super(name);
164        }
165    }
166
167    /**
168     * Create a new Resources object on top of an existing set of assets in an
169     * AssetManager.
170     *
171     * @param assets Previously created AssetManager.
172     * @param metrics Current display metrics to consider when
173     *                selecting/computing resource values.
174     * @param config Desired device configuration to consider when
175     *               selecting/computing resource values (optional).
176     */
177    public Resources(AssetManager assets, DisplayMetrics metrics, Configuration config) {
178        this(assets, metrics, config, CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO, null);
179    }
180
181    /**
182     * Creates a new Resources object with CompatibilityInfo.
183     *
184     * @param assets Previously created AssetManager.
185     * @param metrics Current display metrics to consider when
186     *                selecting/computing resource values.
187     * @param config Desired device configuration to consider when
188     *               selecting/computing resource values (optional).
189     * @param compatInfo this resource's compatibility info. Must not be null.
190     * @param token The Activity token for determining stack affiliation. Usually null.
191     * @hide
192     */
193    public Resources(AssetManager assets, DisplayMetrics metrics, Configuration config,
194            CompatibilityInfo compatInfo, IBinder token) {
195        mAssets = assets;
196        mMetrics.setToDefaults();
197        if (compatInfo != null) {
198            mCompatibilityInfo = compatInfo;
199        }
200        mToken = new WeakReference<IBinder>(token);
201        updateConfiguration(config, metrics);
202        assets.ensureStringBlocks();
203    }
204
205    /**
206     * Return a global shared Resources object that provides access to only
207     * system resources (no application resources), and is not configured for
208     * the current screen (can not use dimension units, does not change based
209     * on orientation, etc).
210     */
211    public static Resources getSystem() {
212        synchronized (sSync) {
213            Resources ret = mSystem;
214            if (ret == null) {
215                ret = new Resources();
216                mSystem = ret;
217            }
218
219            return ret;
220        }
221    }
222
223    /**
224     * Return the string value associated with a particular resource ID.  The
225     * returned object will be a String if this is a plain string; it will be
226     * some other type of CharSequence if it is styled.
227     * {@more}
228     *
229     * @param id The desired resource identifier, as generated by the aapt
230     *           tool. This integer encodes the package, type, and resource
231     *           entry. The value 0 is an invalid identifier.
232     *
233     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
234     *
235     * @return CharSequence The string data associated with the resource, plus
236     *         possibly styled text information.
237     */
238    public CharSequence getText(int id) throws NotFoundException {
239        CharSequence res = mAssets.getResourceText(id);
240        if (res != null) {
241            return res;
242        }
243        throw new NotFoundException("String resource ID #0x"
244                                    + Integer.toHexString(id));
245    }
246
247    /**
248     * Returns the character sequence necessary for grammatically correct pluralization
249     * of the given resource ID for the given quantity.
250     * Note that the character sequence is selected based solely on grammatical necessity,
251     * and that such rules differ between languages. Do not assume you know which string
252     * will be returned for a given quantity. See
253     * <a href="{@docRoot}guide/topics/resources/string-resource.html#Plurals">String Resources</a>
254     * for more detail.
255     *
256     * @param id The desired resource identifier, as generated by the aapt
257     *           tool. This integer encodes the package, type, and resource
258     *           entry. The value 0 is an invalid identifier.
259     * @param quantity The number used to get the correct string for the current language's
260     *           plural rules.
261     *
262     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
263     *
264     * @return CharSequence The string data associated with the resource, plus
265     *         possibly styled text information.
266     */
267    public CharSequence getQuantityText(int id, int quantity) throws NotFoundException {
268        NativePluralRules rule = getPluralRule();
269        CharSequence res = mAssets.getResourceBagText(id,
270                attrForQuantityCode(rule.quantityForInt(quantity)));
271        if (res != null) {
272            return res;
273        }
274        res = mAssets.getResourceBagText(id, ID_OTHER);
275        if (res != null) {
276            return res;
277        }
278        throw new NotFoundException("Plural resource ID #0x" + Integer.toHexString(id)
279                + " quantity=" + quantity
280                + " item=" + stringForQuantityCode(rule.quantityForInt(quantity)));
281    }
282
283    private NativePluralRules getPluralRule() {
284        synchronized (sSync) {
285            if (mPluralRule == null) {
286                mPluralRule = NativePluralRules.forLocale(mConfiguration.locale);
287            }
288            return mPluralRule;
289        }
290    }
291
292    private static int attrForQuantityCode(int quantityCode) {
293        switch (quantityCode) {
294            case NativePluralRules.ZERO: return 0x01000005;
295            case NativePluralRules.ONE:  return 0x01000006;
296            case NativePluralRules.TWO:  return 0x01000007;
297            case NativePluralRules.FEW:  return 0x01000008;
298            case NativePluralRules.MANY: return 0x01000009;
299            default:                     return ID_OTHER;
300        }
301    }
302
303    private static String stringForQuantityCode(int quantityCode) {
304        switch (quantityCode) {
305            case NativePluralRules.ZERO: return "zero";
306            case NativePluralRules.ONE:  return "one";
307            case NativePluralRules.TWO:  return "two";
308            case NativePluralRules.FEW:  return "few";
309            case NativePluralRules.MANY: return "many";
310            default:                     return "other";
311        }
312    }
313
314    /**
315     * Return the string value associated with a particular resource ID.  It
316     * will be stripped of any styled text information.
317     * {@more}
318     *
319     * @param id The desired resource identifier, as generated by the aapt
320     *           tool. This integer encodes the package, type, and resource
321     *           entry. The value 0 is an invalid identifier.
322     *
323     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
324     *
325     * @return String The string data associated with the resource,
326     * stripped of styled text information.
327     */
328    public String getString(int id) throws NotFoundException {
329        CharSequence res = getText(id);
330        if (res != null) {
331            return res.toString();
332        }
333        throw new NotFoundException("String resource ID #0x"
334                                    + Integer.toHexString(id));
335    }
336
337
338    /**
339     * Return the string value associated with a particular resource ID,
340     * substituting the format arguments as defined in {@link java.util.Formatter}
341     * and {@link java.lang.String#format}. It will be stripped of any styled text
342     * information.
343     * {@more}
344     *
345     * @param id The desired resource identifier, as generated by the aapt
346     *           tool. This integer encodes the package, type, and resource
347     *           entry. The value 0 is an invalid identifier.
348     *
349     * @param formatArgs The format arguments that will be used for substitution.
350     *
351     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
352     *
353     * @return String The string data associated with the resource,
354     * stripped of styled text information.
355     */
356    public String getString(int id, Object... formatArgs) throws NotFoundException {
357        String raw = getString(id);
358        return String.format(mConfiguration.locale, raw, formatArgs);
359    }
360
361    /**
362     * Formats the string necessary for grammatically correct pluralization
363     * of the given resource ID for the given quantity, using the given arguments.
364     * Note that the string is selected based solely on grammatical necessity,
365     * and that such rules differ between languages. Do not assume you know which string
366     * will be returned for a given quantity. See
367     * <a href="{@docRoot}guide/topics/resources/string-resource.html#Plurals">String Resources</a>
368     * for more detail.
369     *
370     * <p>Substitution of format arguments works as if using
371     * {@link java.util.Formatter} and {@link java.lang.String#format}.
372     * The resulting string will be stripped of any styled text information.
373     *
374     * @param id The desired resource identifier, as generated by the aapt
375     *           tool. This integer encodes the package, type, and resource
376     *           entry. The value 0 is an invalid identifier.
377     * @param quantity The number used to get the correct string for the current language's
378     *           plural rules.
379     * @param formatArgs The format arguments that will be used for substitution.
380     *
381     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
382     *
383     * @return String The string data associated with the resource,
384     * stripped of styled text information.
385     */
386    public String getQuantityString(int id, int quantity, Object... formatArgs)
387            throws NotFoundException {
388        String raw = getQuantityText(id, quantity).toString();
389        return String.format(mConfiguration.locale, raw, formatArgs);
390    }
391
392    /**
393     * Returns the string necessary for grammatically correct pluralization
394     * of the given resource ID for the given quantity.
395     * Note that the string is selected based solely on grammatical necessity,
396     * and that such rules differ between languages. Do not assume you know which string
397     * will be returned for a given quantity. See
398     * <a href="{@docRoot}guide/topics/resources/string-resource.html#Plurals">String Resources</a>
399     * for more detail.
400     *
401     * @param id The desired resource identifier, as generated by the aapt
402     *           tool. This integer encodes the package, type, and resource
403     *           entry. The value 0 is an invalid identifier.
404     * @param quantity The number used to get the correct string for the current language's
405     *           plural rules.
406     *
407     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
408     *
409     * @return String The string data associated with the resource,
410     * stripped of styled text information.
411     */
412    public String getQuantityString(int id, int quantity) throws NotFoundException {
413        return getQuantityText(id, quantity).toString();
414    }
415
416    /**
417     * Return the string value associated with a particular resource ID.  The
418     * returned object will be a String if this is a plain string; it will be
419     * some other type of CharSequence if it is styled.
420     *
421     * @param id The desired resource identifier, as generated by the aapt
422     *           tool. This integer encodes the package, type, and resource
423     *           entry. The value 0 is an invalid identifier.
424     *
425     * @param def The default CharSequence to return.
426     *
427     * @return CharSequence The string data associated with the resource, plus
428     *         possibly styled text information, or def if id is 0 or not found.
429     */
430    public CharSequence getText(int id, CharSequence def) {
431        CharSequence res = id != 0 ? mAssets.getResourceText(id) : null;
432        return res != null ? res : def;
433    }
434
435    /**
436     * Return the styled text array associated with a particular resource ID.
437     *
438     * @param id The desired resource identifier, as generated by the aapt
439     *           tool. This integer encodes the package, type, and resource
440     *           entry. The value 0 is an invalid identifier.
441     *
442     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
443     *
444     * @return The styled text array associated with the resource.
445     */
446    public CharSequence[] getTextArray(int id) throws NotFoundException {
447        CharSequence[] res = mAssets.getResourceTextArray(id);
448        if (res != null) {
449            return res;
450        }
451        throw new NotFoundException("Text array resource ID #0x"
452                                    + Integer.toHexString(id));
453    }
454
455    /**
456     * Return the string array associated with a particular resource ID.
457     *
458     * @param id The desired resource identifier, as generated by the aapt
459     *           tool. This integer encodes the package, type, and resource
460     *           entry. The value 0 is an invalid identifier.
461     *
462     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
463     *
464     * @return The string array associated with the resource.
465     */
466    public String[] getStringArray(int id) throws NotFoundException {
467        String[] res = mAssets.getResourceStringArray(id);
468        if (res != null) {
469            return res;
470        }
471        throw new NotFoundException("String array resource ID #0x"
472                                    + Integer.toHexString(id));
473    }
474
475    /**
476     * Return the int array associated with a particular resource ID.
477     *
478     * @param id The desired resource identifier, as generated by the aapt
479     *           tool. This integer encodes the package, type, and resource
480     *           entry. The value 0 is an invalid identifier.
481     *
482     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
483     *
484     * @return The int array associated with the resource.
485     */
486    public int[] getIntArray(int id) throws NotFoundException {
487        int[] res = mAssets.getArrayIntResource(id);
488        if (res != null) {
489            return res;
490        }
491        throw new NotFoundException("Int array resource ID #0x"
492                                    + Integer.toHexString(id));
493    }
494
495    /**
496     * Return an array of heterogeneous values.
497     *
498     * @param id The desired resource identifier, as generated by the aapt
499     *           tool. This integer encodes the package, type, and resource
500     *           entry. The value 0 is an invalid identifier.
501     *
502     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
503     *
504     * @return Returns a TypedArray holding an array of the array values.
505     * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()}
506     * when done with it.
507     */
508    public TypedArray obtainTypedArray(int id) throws NotFoundException {
509        int len = mAssets.getArraySize(id);
510        if (len < 0) {
511            throw new NotFoundException("Array resource ID #0x"
512                                        + Integer.toHexString(id));
513        }
514
515        TypedArray array = getCachedStyledAttributes(len);
516        array.mLength = mAssets.retrieveArray(id, array.mData);
517        array.mIndices[0] = 0;
518
519        return array;
520    }
521
522    /**
523     * Retrieve a dimensional for a particular resource ID.  Unit
524     * conversions are based on the current {@link DisplayMetrics} associated
525     * with the resources.
526     *
527     * @param id The desired resource identifier, as generated by the aapt
528     *           tool. This integer encodes the package, type, and resource
529     *           entry. The value 0 is an invalid identifier.
530     *
531     * @return Resource dimension value multiplied by the appropriate
532     * metric.
533     *
534     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
535     *
536     * @see #getDimensionPixelOffset
537     * @see #getDimensionPixelSize
538     */
539    public float getDimension(int id) throws NotFoundException {
540        synchronized (mAccessLock) {
541            TypedValue value = mTmpValue;
542            if (value == null) {
543                mTmpValue = value = new TypedValue();
544            }
545            getValue(id, value, true);
546            if (value.type == TypedValue.TYPE_DIMENSION) {
547                return TypedValue.complexToDimension(value.data, mMetrics);
548            }
549            throw new NotFoundException(
550                    "Resource ID #0x" + Integer.toHexString(id) + " type #0x"
551                    + Integer.toHexString(value.type) + " is not valid");
552        }
553    }
554
555    /**
556     * Retrieve a dimensional for a particular resource ID for use
557     * as an offset in raw pixels.  This is the same as
558     * {@link #getDimension}, except the returned value is converted to
559     * integer pixels for you.  An offset conversion involves simply
560     * truncating the base value to an integer.
561     *
562     * @param id The desired resource identifier, as generated by the aapt
563     *           tool. This integer encodes the package, type, and resource
564     *           entry. The value 0 is an invalid identifier.
565     *
566     * @return Resource dimension value multiplied by the appropriate
567     * metric and truncated to integer pixels.
568     *
569     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
570     *
571     * @see #getDimension
572     * @see #getDimensionPixelSize
573     */
574    public int getDimensionPixelOffset(int id) throws NotFoundException {
575        synchronized (mAccessLock) {
576            TypedValue value = mTmpValue;
577            if (value == null) {
578                mTmpValue = value = new TypedValue();
579            }
580            getValue(id, value, true);
581            if (value.type == TypedValue.TYPE_DIMENSION) {
582                return TypedValue.complexToDimensionPixelOffset(
583                        value.data, mMetrics);
584            }
585            throw new NotFoundException(
586                    "Resource ID #0x" + Integer.toHexString(id) + " type #0x"
587                    + Integer.toHexString(value.type) + " is not valid");
588        }
589    }
590
591    /**
592     * Retrieve a dimensional for a particular resource ID for use
593     * as a size in raw pixels.  This is the same as
594     * {@link #getDimension}, except the returned value is converted to
595     * integer pixels for use as a size.  A size conversion involves
596     * rounding the base value, and ensuring that a non-zero base value
597     * is at least one pixel in size.
598     *
599     * @param id The desired resource identifier, as generated by the aapt
600     *           tool. This integer encodes the package, type, and resource
601     *           entry. The value 0 is an invalid identifier.
602     *
603     * @return Resource dimension value multiplied by the appropriate
604     * metric and truncated to integer pixels.
605     *
606     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
607     *
608     * @see #getDimension
609     * @see #getDimensionPixelOffset
610     */
611    public int getDimensionPixelSize(int id) throws NotFoundException {
612        synchronized (mAccessLock) {
613            TypedValue value = mTmpValue;
614            if (value == null) {
615                mTmpValue = value = new TypedValue();
616            }
617            getValue(id, value, true);
618            if (value.type == TypedValue.TYPE_DIMENSION) {
619                return TypedValue.complexToDimensionPixelSize(
620                        value.data, mMetrics);
621            }
622            throw new NotFoundException(
623                    "Resource ID #0x" + Integer.toHexString(id) + " type #0x"
624                    + Integer.toHexString(value.type) + " is not valid");
625        }
626    }
627
628    /**
629     * Retrieve a fractional unit for a particular resource ID.
630     *
631     * @param id The desired resource identifier, as generated by the aapt
632     *           tool. This integer encodes the package, type, and resource
633     *           entry. The value 0 is an invalid identifier.
634     * @param base The base value of this fraction.  In other words, a
635     *             standard fraction is multiplied by this value.
636     * @param pbase The parent base value of this fraction.  In other
637     *             words, a parent fraction (nn%p) is multiplied by this
638     *             value.
639     *
640     * @return Attribute fractional value multiplied by the appropriate
641     * base value.
642     *
643     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
644     */
645    public float getFraction(int id, int base, int pbase) {
646        synchronized (mAccessLock) {
647            TypedValue value = mTmpValue;
648            if (value == null) {
649                mTmpValue = value = new TypedValue();
650            }
651            getValue(id, value, true);
652            if (value.type == TypedValue.TYPE_FRACTION) {
653                return TypedValue.complexToFraction(value.data, base, pbase);
654            }
655            throw new NotFoundException(
656                    "Resource ID #0x" + Integer.toHexString(id) + " type #0x"
657                    + Integer.toHexString(value.type) + " is not valid");
658        }
659    }
660
661    /**
662     * Return a drawable object associated with a particular resource ID.
663     * Various types of objects will be returned depending on the underlying
664     * resource -- for example, a solid color, PNG image, scalable image, etc.
665     * The Drawable API hides these implementation details.
666     *
667     * <p class="note"><strong>Note:</strong> Prior to
668     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN}, this function
669     * would not correctly retrieve the final configuration density when
670     * the resource ID passed here is an alias to another Drawable resource.
671     * This means that if the density configuration of the alias resource
672     * is different than the actual resource, the density of the returned
673     * Drawable would be incorrect, resulting in bad scaling.  To work
674     * around this, you can instead retrieve the Drawable through
675     * {@link TypedArray#getDrawable TypedArray.getDrawable}.  Use
676     * {@link android.content.Context#obtainStyledAttributes(int[])
677     * Context.obtainStyledAttributes} with
678     * an array containing the resource ID of interest to create the TypedArray.</p>
679     *
680     * @param id The desired resource identifier, as generated by the aapt
681     *           tool. This integer encodes the package, type, and resource
682     *           entry. The value 0 is an invalid identifier.
683     *
684     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
685     *
686     * @return Drawable An object that can be used to draw this resource.
687     */
688    public Drawable getDrawable(int id) throws NotFoundException {
689        TypedValue value;
690        synchronized (mAccessLock) {
691            value = mTmpValue;
692            if (value == null) {
693                value = new TypedValue();
694            } else {
695                mTmpValue = null;
696            }
697            getValue(id, value, true);
698        }
699        Drawable res = loadDrawable(value, id);
700        synchronized (mAccessLock) {
701            if (mTmpValue == null) {
702                mTmpValue = value;
703            }
704        }
705        return res;
706    }
707
708    /**
709     * Return a drawable object associated with a particular resource ID for the
710     * given screen density in DPI. This will set the drawable's density to be
711     * the device's density multiplied by the ratio of actual drawable density
712     * to requested density. This allows the drawable to be scaled up to the
713     * correct size if needed. Various types of objects will be returned
714     * depending on the underlying resource -- for example, a solid color, PNG
715     * image, scalable image, etc. The Drawable API hides these implementation
716     * details.
717     *
718     * @param id The desired resource identifier, as generated by the aapt tool.
719     *            This integer encodes the package, type, and resource entry.
720     *            The value 0 is an invalid identifier.
721     * @param density the desired screen density indicated by the resource as
722     *            found in {@link DisplayMetrics}.
723     * @throws NotFoundException Throws NotFoundException if the given ID does
724     *             not exist.
725     * @return Drawable An object that can be used to draw this resource.
726     */
727    public Drawable getDrawableForDensity(int id, int density) throws NotFoundException {
728        TypedValue value;
729        synchronized (mAccessLock) {
730            value = mTmpValue;
731            if (value == null) {
732                value = new TypedValue();
733            } else {
734                mTmpValue = null;
735            }
736            getValueForDensity(id, density, value, true);
737
738            /*
739             * Pretend the requested density is actually the display density. If
740             * the drawable returned is not the requested density, then force it
741             * to be scaled later by dividing its density by the ratio of
742             * requested density to actual device density. Drawables that have
743             * undefined density or no density don't need to be handled here.
744             */
745            if (value.density > 0 && value.density != TypedValue.DENSITY_NONE) {
746                if (value.density == density) {
747                    value.density = mMetrics.densityDpi;
748                } else {
749                    value.density = (value.density * mMetrics.densityDpi) / density;
750                }
751            }
752        }
753
754        Drawable res = loadDrawable(value, id);
755        synchronized (mAccessLock) {
756            if (mTmpValue == null) {
757                mTmpValue = value;
758            }
759        }
760        return res;
761    }
762
763    /**
764     * Return a movie object associated with the particular resource ID.
765     * @param id The desired resource identifier, as generated by the aapt
766     *           tool. This integer encodes the package, type, and resource
767     *           entry. The value 0 is an invalid identifier.
768     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
769     *
770     */
771    public Movie getMovie(int id) throws NotFoundException {
772        InputStream is = openRawResource(id);
773        Movie movie = Movie.decodeStream(is);
774        try {
775            is.close();
776        }
777        catch (java.io.IOException e) {
778            // don't care, since the return value is valid
779        }
780        return movie;
781    }
782
783    /**
784     * Return a color integer associated with a particular resource ID.
785     * If the resource holds a complex
786     * {@link android.content.res.ColorStateList}, then the default color from
787     * the set is returned.
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     *
793     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
794     *
795     * @return Returns a single color value in the form 0xAARRGGBB.
796     */
797    public int getColor(int id) throws NotFoundException {
798        TypedValue value;
799        synchronized (mAccessLock) {
800            value = mTmpValue;
801            if (value == null) {
802                value = new TypedValue();
803            }
804            getValue(id, value, true);
805            if (value.type >= TypedValue.TYPE_FIRST_INT
806                && value.type <= TypedValue.TYPE_LAST_INT) {
807                mTmpValue = value;
808                return value.data;
809            } else if (value.type != TypedValue.TYPE_STRING) {
810                throw new NotFoundException(
811                    "Resource ID #0x" + Integer.toHexString(id) + " type #0x"
812                    + Integer.toHexString(value.type) + " is not valid");
813            }
814            mTmpValue = null;
815        }
816        ColorStateList csl = loadColorStateList(value, id);
817        synchronized (mAccessLock) {
818            if (mTmpValue == null) {
819                mTmpValue = value;
820            }
821        }
822        return csl.getDefaultColor();
823    }
824
825    /**
826     * Return a color state list associated with a particular resource ID.  The
827     * resource may contain either a single raw color value, or a complex
828     * {@link android.content.res.ColorStateList} holding multiple possible colors.
829     *
830     * @param id The desired resource identifier of a {@link ColorStateList},
831     *        as generated by the aapt tool. This integer encodes the package, type, and resource
832     *        entry. The value 0 is an invalid identifier.
833     *
834     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
835     *
836     * @return Returns a ColorStateList object containing either a single
837     * solid color or multiple colors that can be selected based on a state.
838     */
839    public ColorStateList getColorStateList(int id) throws NotFoundException {
840        TypedValue value;
841        synchronized (mAccessLock) {
842            value = mTmpValue;
843            if (value == null) {
844                value = new TypedValue();
845            } else {
846                mTmpValue = null;
847            }
848            getValue(id, value, true);
849        }
850        ColorStateList res = loadColorStateList(value, id);
851        synchronized (mAccessLock) {
852            if (mTmpValue == null) {
853                mTmpValue = value;
854            }
855        }
856        return res;
857    }
858
859    /**
860     * Return a boolean associated with a particular resource ID.  This can be
861     * used with any integral resource value, and will return true if it is
862     * non-zero.
863     *
864     * @param id The desired resource identifier, as generated by the aapt
865     *           tool. This integer encodes the package, type, and resource
866     *           entry. The value 0 is an invalid identifier.
867     *
868     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
869     *
870     * @return Returns the boolean value contained in the resource.
871     */
872    public boolean getBoolean(int id) throws NotFoundException {
873        synchronized (mAccessLock) {
874            TypedValue value = mTmpValue;
875            if (value == null) {
876                mTmpValue = value = new TypedValue();
877            }
878            getValue(id, value, true);
879            if (value.type >= TypedValue.TYPE_FIRST_INT
880                && value.type <= TypedValue.TYPE_LAST_INT) {
881                return value.data != 0;
882            }
883            throw new NotFoundException(
884                "Resource ID #0x" + Integer.toHexString(id) + " type #0x"
885                + Integer.toHexString(value.type) + " is not valid");
886        }
887    }
888
889    /**
890     * Return an integer associated with a particular resource ID.
891     *
892     * @param id The desired resource identifier, as generated by the aapt
893     *           tool. This integer encodes the package, type, and resource
894     *           entry. The value 0 is an invalid identifier.
895     *
896     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
897     *
898     * @return Returns the integer value contained in the resource.
899     */
900    public int getInteger(int id) throws NotFoundException {
901        synchronized (mAccessLock) {
902            TypedValue value = mTmpValue;
903            if (value == null) {
904                mTmpValue = value = new TypedValue();
905            }
906            getValue(id, value, true);
907            if (value.type >= TypedValue.TYPE_FIRST_INT
908                && value.type <= TypedValue.TYPE_LAST_INT) {
909                return value.data;
910            }
911            throw new NotFoundException(
912                "Resource ID #0x" + Integer.toHexString(id) + " type #0x"
913                + Integer.toHexString(value.type) + " is not valid");
914        }
915    }
916
917    /**
918     * Return an XmlResourceParser through which you can read a view layout
919     * description for the given resource ID.  This parser has limited
920     * functionality -- in particular, you can't change its input, and only
921     * the high-level events are available.
922     *
923     * <p>This function is really a simple wrapper for calling
924     * {@link #getXml} with a layout resource.
925     *
926     * @param id The desired resource identifier, as generated by the aapt
927     *           tool. This integer encodes the package, type, and resource
928     *           entry. The value 0 is an invalid identifier.
929     *
930     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
931     *
932     * @return A new parser object through which you can read
933     *         the XML data.
934     *
935     * @see #getXml
936     */
937    public XmlResourceParser getLayout(int id) throws NotFoundException {
938        return loadXmlResourceParser(id, "layout");
939    }
940
941    /**
942     * Return an XmlResourceParser through which you can read an animation
943     * description for the given resource ID.  This parser has limited
944     * functionality -- in particular, you can't change its input, and only
945     * the high-level events are available.
946     *
947     * <p>This function is really a simple wrapper for calling
948     * {@link #getXml} with an animation resource.
949     *
950     * @param id The desired resource identifier, as generated by the aapt
951     *           tool. This integer encodes the package, type, and resource
952     *           entry. The value 0 is an invalid identifier.
953     *
954     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
955     *
956     * @return A new parser object through which you can read
957     *         the XML data.
958     *
959     * @see #getXml
960     */
961    public XmlResourceParser getAnimation(int id) throws NotFoundException {
962        return loadXmlResourceParser(id, "anim");
963    }
964
965    /**
966     * Return an XmlResourceParser through which you can read a generic XML
967     * resource for the given resource ID.
968     *
969     * <p>The XmlPullParser implementation returned here has some limited
970     * functionality.  In particular, you can't change its input, and only
971     * high-level parsing events are available (since the document was
972     * pre-parsed for you at build time, which involved merging text and
973     * stripping comments).
974     *
975     * @param id The desired resource identifier, as generated by the aapt
976     *           tool. This integer encodes the package, type, and resource
977     *           entry. The value 0 is an invalid identifier.
978     *
979     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
980     *
981     * @return A new parser object through which you can read
982     *         the XML data.
983     *
984     * @see android.util.AttributeSet
985     */
986    public XmlResourceParser getXml(int id) throws NotFoundException {
987        return loadXmlResourceParser(id, "xml");
988    }
989
990    /**
991     * Open a data stream for reading a raw resource.  This can only be used
992     * with resources whose value is the name of an asset files -- that is, it can be
993     * used to open drawable, sound, and raw resources; it will fail on string
994     * and color resources.
995     *
996     * @param id The resource identifier to open, as generated by the appt
997     *           tool.
998     *
999     * @return InputStream Access to the resource data.
1000     *
1001     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1002     *
1003     */
1004    public InputStream openRawResource(int id) throws NotFoundException {
1005        TypedValue value;
1006        synchronized (mAccessLock) {
1007            value = mTmpValue;
1008            if (value == null) {
1009                value = new TypedValue();
1010            } else {
1011                mTmpValue = null;
1012            }
1013        }
1014        InputStream res = openRawResource(id, value);
1015        synchronized (mAccessLock) {
1016            if (mTmpValue == null) {
1017                mTmpValue = value;
1018            }
1019        }
1020        return res;
1021    }
1022
1023    /**
1024     * Open a data stream for reading a raw resource.  This can only be used
1025     * with resources whose value is the name of an asset file -- that is, it can be
1026     * used to open drawable, sound, and raw resources; it will fail on string
1027     * and color resources.
1028     *
1029     * @param id The resource identifier to open, as generated by the appt tool.
1030     * @param value The TypedValue object to hold the resource information.
1031     *
1032     * @return InputStream Access to the resource data.
1033     *
1034     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1035     */
1036    public InputStream openRawResource(int id, TypedValue value) throws NotFoundException {
1037        getValue(id, value, true);
1038
1039        try {
1040            return mAssets.openNonAsset(value.assetCookie, value.string.toString(),
1041                    AssetManager.ACCESS_STREAMING);
1042        } catch (Exception e) {
1043            NotFoundException rnf = new NotFoundException("File " + value.string.toString() +
1044                    " from drawable resource ID #0x" + Integer.toHexString(id));
1045            rnf.initCause(e);
1046            throw rnf;
1047        }
1048    }
1049
1050    /**
1051     * Open a file descriptor for reading a raw resource.  This can only be used
1052     * with resources whose value is the name of an asset files -- that is, it can be
1053     * used to open drawable, sound, and raw resources; it will fail on string
1054     * and color resources.
1055     *
1056     * <p>This function only works for resources that are stored in the package
1057     * as uncompressed data, which typically includes things like mp3 files
1058     * and png images.
1059     *
1060     * @param id The resource identifier to open, as generated by the appt
1061     *           tool.
1062     *
1063     * @return AssetFileDescriptor A new file descriptor you can use to read
1064     * the resource.  This includes the file descriptor itself, as well as the
1065     * offset and length of data where the resource appears in the file.  A
1066     * null is returned if the file exists but is compressed.
1067     *
1068     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1069     *
1070     */
1071    public AssetFileDescriptor openRawResourceFd(int id) throws NotFoundException {
1072        TypedValue value;
1073        synchronized (mAccessLock) {
1074            value = mTmpValue;
1075            if (value == null) {
1076                value = new TypedValue();
1077            } else {
1078                mTmpValue = null;
1079            }
1080            getValue(id, value, true);
1081        }
1082        try {
1083            return mAssets.openNonAssetFd(
1084                value.assetCookie, value.string.toString());
1085        } catch (Exception e) {
1086            NotFoundException rnf = new NotFoundException(
1087                "File " + value.string.toString()
1088                + " from drawable resource ID #0x"
1089                + Integer.toHexString(id));
1090            rnf.initCause(e);
1091            throw rnf;
1092        } finally {
1093            synchronized (mAccessLock) {
1094                if (mTmpValue == null) {
1095                    mTmpValue = value;
1096                }
1097            }
1098        }
1099    }
1100
1101    /**
1102     * Return the raw data associated with a particular resource ID.
1103     *
1104     * @param id The desired resource identifier, as generated by the aapt
1105     *           tool. This integer encodes the package, type, and resource
1106     *           entry. The value 0 is an invalid identifier.
1107     * @param outValue Object in which to place the resource data.
1108     * @param resolveRefs If true, a resource that is a reference to another
1109     *                    resource will be followed so that you receive the
1110     *                    actual final resource data.  If false, the TypedValue
1111     *                    will be filled in with the reference itself.
1112     *
1113     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1114     *
1115     */
1116    public void getValue(int id, TypedValue outValue, boolean resolveRefs)
1117            throws NotFoundException {
1118        boolean found = mAssets.getResourceValue(id, 0, outValue, resolveRefs);
1119        if (found) {
1120            return;
1121        }
1122        throw new NotFoundException("Resource ID #0x"
1123                                    + Integer.toHexString(id));
1124    }
1125
1126    /**
1127     * Get the raw value associated with a resource with associated density.
1128     *
1129     * @param id resource identifier
1130     * @param density density in DPI
1131     * @param resolveRefs If true, a resource that is a reference to another
1132     *            resource will be followed so that you receive the actual final
1133     *            resource data. If false, the TypedValue will be filled in with
1134     *            the reference itself.
1135     * @throws NotFoundException Throws NotFoundException if the given ID does
1136     *             not exist.
1137     * @see #getValue(String, TypedValue, boolean)
1138     */
1139    public void getValueForDensity(int id, int density, TypedValue outValue, boolean resolveRefs)
1140            throws NotFoundException {
1141        boolean found = mAssets.getResourceValue(id, density, outValue, resolveRefs);
1142        if (found) {
1143            return;
1144        }
1145        throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id));
1146    }
1147
1148    /**
1149     * Return the raw data associated with a particular resource ID.
1150     * See getIdentifier() for information on how names are mapped to resource
1151     * IDs, and getString(int) for information on how string resources are
1152     * retrieved.
1153     *
1154     * <p>Note: use of this function is discouraged.  It is much more
1155     * efficient to retrieve resources by identifier than by name.
1156     *
1157     * @param name The name of the desired resource.  This is passed to
1158     *             getIdentifier() with a default type of "string".
1159     * @param outValue Object in which to place the resource data.
1160     * @param resolveRefs If true, a resource that is a reference to another
1161     *                    resource will be followed so that you receive the
1162     *                    actual final resource data.  If false, the TypedValue
1163     *                    will be filled in with the reference itself.
1164     *
1165     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1166     *
1167     */
1168    public void getValue(String name, TypedValue outValue, boolean resolveRefs)
1169            throws NotFoundException {
1170        int id = getIdentifier(name, "string", null);
1171        if (id != 0) {
1172            getValue(id, outValue, resolveRefs);
1173            return;
1174        }
1175        throw new NotFoundException("String resource name " + name);
1176    }
1177
1178    /**
1179     * This class holds the current attribute values for a particular theme.
1180     * In other words, a Theme is a set of values for resource attributes;
1181     * these are used in conjunction with {@link TypedArray}
1182     * to resolve the final value for an attribute.
1183     *
1184     * <p>The Theme's attributes come into play in two ways: (1) a styled
1185     * attribute can explicit reference a value in the theme through the
1186     * "?themeAttribute" syntax; (2) if no value has been defined for a
1187     * particular styled attribute, as a last resort we will try to find that
1188     * attribute's value in the Theme.
1189     *
1190     * <p>You will normally use the {@link #obtainStyledAttributes} APIs to
1191     * retrieve XML attributes with style and theme information applied.
1192     */
1193    public final class Theme {
1194        /**
1195         * Place new attribute values into the theme.  The style resource
1196         * specified by <var>resid</var> will be retrieved from this Theme's
1197         * resources, its values placed into the Theme object.
1198         *
1199         * <p>The semantics of this function depends on the <var>force</var>
1200         * argument:  If false, only values that are not already defined in
1201         * the theme will be copied from the system resource; otherwise, if
1202         * any of the style's attributes are already defined in the theme, the
1203         * current values in the theme will be overwritten.
1204         *
1205         * @param resid The resource ID of a style resource from which to
1206         *              obtain attribute values.
1207         * @param force If true, values in the style resource will always be
1208         *              used in the theme; otherwise, they will only be used
1209         *              if not already defined in the theme.
1210         */
1211        public void applyStyle(int resid, boolean force) {
1212            AssetManager.applyThemeStyle(mTheme, resid, force);
1213        }
1214
1215        /**
1216         * Set this theme to hold the same contents as the theme
1217         * <var>other</var>.  If both of these themes are from the same
1218         * Resources object, they will be identical after this function
1219         * returns.  If they are from different Resources, only the resources
1220         * they have in common will be set in this theme.
1221         *
1222         * @param other The existing Theme to copy from.
1223         */
1224        public void setTo(Theme other) {
1225            AssetManager.copyTheme(mTheme, other.mTheme);
1226        }
1227
1228        /**
1229         * Return a TypedArray holding the values defined by
1230         * <var>Theme</var> which are listed in <var>attrs</var>.
1231         *
1232         * <p>Be sure to call {@link TypedArray#recycle() TypedArray.recycle()} when you are done
1233         * with the array.
1234         *
1235         * @param attrs The desired attributes.
1236         *
1237         * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1238         *
1239         * @return Returns a TypedArray holding an array of the attribute values.
1240         * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()}
1241         * when done with it.
1242         *
1243         * @see Resources#obtainAttributes
1244         * @see #obtainStyledAttributes(int, int[])
1245         * @see #obtainStyledAttributes(AttributeSet, int[], int, int)
1246         */
1247        public TypedArray obtainStyledAttributes(int[] attrs) {
1248            int len = attrs.length;
1249            TypedArray array = getCachedStyledAttributes(len);
1250            array.mRsrcs = attrs;
1251            AssetManager.applyStyle(mTheme, 0, 0, 0, attrs,
1252                    array.mData, array.mIndices);
1253            return array;
1254        }
1255
1256        /**
1257         * Return a TypedArray holding the values defined by the style
1258         * resource <var>resid</var> which are listed in <var>attrs</var>.
1259         *
1260         * <p>Be sure to call {@link TypedArray#recycle() TypedArray.recycle()} when you are done
1261         * with the array.
1262         *
1263         * @param resid The desired style resource.
1264         * @param attrs The desired attributes in the style.
1265         *
1266         * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1267         *
1268         * @return Returns a TypedArray holding an array of the attribute values.
1269         * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()}
1270         * when done with it.
1271         *
1272         * @see Resources#obtainAttributes
1273         * @see #obtainStyledAttributes(int[])
1274         * @see #obtainStyledAttributes(AttributeSet, int[], int, int)
1275         */
1276        public TypedArray obtainStyledAttributes(int resid, int[] attrs)
1277                throws NotFoundException {
1278            int len = attrs.length;
1279            TypedArray array = getCachedStyledAttributes(len);
1280            array.mRsrcs = attrs;
1281
1282            AssetManager.applyStyle(mTheme, 0, resid, 0, attrs,
1283                    array.mData, array.mIndices);
1284            if (false) {
1285                int[] data = array.mData;
1286
1287                System.out.println("**********************************************************");
1288                System.out.println("**********************************************************");
1289                System.out.println("**********************************************************");
1290                System.out.println("Attributes:");
1291                String s = "  Attrs:";
1292                int i;
1293                for (i=0; i<attrs.length; i++) {
1294                    s = s + " 0x" + Integer.toHexString(attrs[i]);
1295                }
1296                System.out.println(s);
1297                s = "  Found:";
1298                TypedValue value = new TypedValue();
1299                for (i=0; i<attrs.length; i++) {
1300                    int d = i*AssetManager.STYLE_NUM_ENTRIES;
1301                    value.type = data[d+AssetManager.STYLE_TYPE];
1302                    value.data = data[d+AssetManager.STYLE_DATA];
1303                    value.assetCookie = data[d+AssetManager.STYLE_ASSET_COOKIE];
1304                    value.resourceId = data[d+AssetManager.STYLE_RESOURCE_ID];
1305                    s = s + " 0x" + Integer.toHexString(attrs[i])
1306                        + "=" + value;
1307                }
1308                System.out.println(s);
1309            }
1310            return array;
1311        }
1312
1313        /**
1314         * Return a TypedArray holding the attribute values in
1315         * <var>set</var>
1316         * that are listed in <var>attrs</var>.  In addition, if the given
1317         * AttributeSet specifies a style class (through the "style" attribute),
1318         * that style will be applied on top of the base attributes it defines.
1319         *
1320         * <p>Be sure to call {@link TypedArray#recycle() TypedArray.recycle()} when you are done
1321         * with the array.
1322         *
1323         * <p>When determining the final value of a particular attribute, there
1324         * are four inputs that come into play:</p>
1325         *
1326         * <ol>
1327         *     <li> Any attribute values in the given AttributeSet.
1328         *     <li> The style resource specified in the AttributeSet (named
1329         *     "style").
1330         *     <li> The default style specified by <var>defStyleAttr</var> and
1331         *     <var>defStyleRes</var>
1332         *     <li> The base values in this theme.
1333         * </ol>
1334         *
1335         * <p>Each of these inputs is considered in-order, with the first listed
1336         * taking precedence over the following ones.  In other words, if in the
1337         * AttributeSet you have supplied <code>&lt;Button
1338         * textColor="#ff000000"&gt;</code>, then the button's text will
1339         * <em>always</em> be black, regardless of what is specified in any of
1340         * the styles.
1341         *
1342         * @param set The base set of attribute values.  May be null.
1343         * @param attrs The desired attributes to be retrieved.
1344         * @param defStyleAttr An attribute in the current theme that contains a
1345         *                     reference to a style resource that supplies
1346         *                     defaults values for the TypedArray.  Can be
1347         *                     0 to not look for defaults.
1348         * @param defStyleRes A resource identifier of a style resource that
1349         *                    supplies default values for the TypedArray,
1350         *                    used only if defStyleAttr is 0 or can not be found
1351         *                    in the theme.  Can be 0 to not look for defaults.
1352         *
1353         * @return Returns a TypedArray holding an array of the attribute values.
1354         * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()}
1355         * when done with it.
1356         *
1357         * @see Resources#obtainAttributes
1358         * @see #obtainStyledAttributes(int[])
1359         * @see #obtainStyledAttributes(int, int[])
1360         */
1361        public TypedArray obtainStyledAttributes(AttributeSet set,
1362                int[] attrs, int defStyleAttr, int defStyleRes) {
1363            int len = attrs.length;
1364            TypedArray array = getCachedStyledAttributes(len);
1365
1366            // XXX note that for now we only work with compiled XML files.
1367            // To support generic XML files we will need to manually parse
1368            // out the attributes from the XML file (applying type information
1369            // contained in the resources and such).
1370            XmlBlock.Parser parser = (XmlBlock.Parser)set;
1371            AssetManager.applyStyle(
1372                mTheme, defStyleAttr, defStyleRes,
1373                parser != null ? parser.mParseState : 0, attrs,
1374                        array.mData, array.mIndices);
1375
1376            array.mRsrcs = attrs;
1377            array.mXml = parser;
1378
1379            if (false) {
1380                int[] data = array.mData;
1381
1382                System.out.println("Attributes:");
1383                String s = "  Attrs:";
1384                int i;
1385                for (i=0; i<set.getAttributeCount(); i++) {
1386                    s = s + " " + set.getAttributeName(i);
1387                    int id = set.getAttributeNameResource(i);
1388                    if (id != 0) {
1389                        s = s + "(0x" + Integer.toHexString(id) + ")";
1390                    }
1391                    s = s + "=" + set.getAttributeValue(i);
1392                }
1393                System.out.println(s);
1394                s = "  Found:";
1395                TypedValue value = new TypedValue();
1396                for (i=0; i<attrs.length; i++) {
1397                    int d = i*AssetManager.STYLE_NUM_ENTRIES;
1398                    value.type = data[d+AssetManager.STYLE_TYPE];
1399                    value.data = data[d+AssetManager.STYLE_DATA];
1400                    value.assetCookie = data[d+AssetManager.STYLE_ASSET_COOKIE];
1401                    value.resourceId = data[d+AssetManager.STYLE_RESOURCE_ID];
1402                    s = s + " 0x" + Integer.toHexString(attrs[i])
1403                        + "=" + value;
1404                }
1405                System.out.println(s);
1406            }
1407
1408            return array;
1409        }
1410
1411        /**
1412         * Retrieve the value of an attribute in the Theme.  The contents of
1413         * <var>outValue</var> are ultimately filled in by
1414         * {@link Resources#getValue}.
1415         *
1416         * @param resid The resource identifier of the desired theme
1417         *              attribute.
1418         * @param outValue Filled in with the ultimate resource value supplied
1419         *                 by the attribute.
1420         * @param resolveRefs If true, resource references will be walked; if
1421         *                    false, <var>outValue</var> may be a
1422         *                    TYPE_REFERENCE.  In either case, it will never
1423         *                    be a TYPE_ATTRIBUTE.
1424         *
1425         * @return boolean Returns true if the attribute was found and
1426         *         <var>outValue</var> is valid, else false.
1427         */
1428        public boolean resolveAttribute(int resid, TypedValue outValue,
1429                boolean resolveRefs) {
1430            boolean got = mAssets.getThemeValue(mTheme, resid, outValue, resolveRefs);
1431            if (false) {
1432                System.out.println(
1433                    "resolveAttribute #" + Integer.toHexString(resid)
1434                    + " got=" + got + ", type=0x" + Integer.toHexString(outValue.type)
1435                    + ", data=0x" + Integer.toHexString(outValue.data));
1436            }
1437            return got;
1438        }
1439
1440        /**
1441         * Print contents of this theme out to the log.  For debugging only.
1442         *
1443         * @param priority The log priority to use.
1444         * @param tag The log tag to use.
1445         * @param prefix Text to prefix each line printed.
1446         */
1447        public void dump(int priority, String tag, String prefix) {
1448            AssetManager.dumpTheme(mTheme, priority, tag, prefix);
1449        }
1450
1451        protected void finalize() throws Throwable {
1452            super.finalize();
1453            mAssets.releaseTheme(mTheme);
1454        }
1455
1456        /*package*/ Theme() {
1457            mAssets = Resources.this.mAssets;
1458            mTheme = mAssets.createTheme();
1459        }
1460
1461        private final AssetManager mAssets;
1462        private final int mTheme;
1463    }
1464
1465    /**
1466     * Generate a new Theme object for this set of Resources.  It initially
1467     * starts out empty.
1468     *
1469     * @return Theme The newly created Theme container.
1470     */
1471    public final Theme newTheme() {
1472        return new Theme();
1473    }
1474
1475    /**
1476     * Retrieve a set of basic attribute values from an AttributeSet, not
1477     * performing styling of them using a theme and/or style resources.
1478     *
1479     * @param set The current attribute values to retrieve.
1480     * @param attrs The specific attributes to be retrieved.
1481     * @return Returns a TypedArray holding an array of the attribute values.
1482     * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()}
1483     * when done with it.
1484     *
1485     * @see Theme#obtainStyledAttributes(AttributeSet, int[], int, int)
1486     */
1487    public TypedArray obtainAttributes(AttributeSet set, int[] attrs) {
1488        int len = attrs.length;
1489        TypedArray array = getCachedStyledAttributes(len);
1490
1491        // XXX note that for now we only work with compiled XML files.
1492        // To support generic XML files we will need to manually parse
1493        // out the attributes from the XML file (applying type information
1494        // contained in the resources and such).
1495        XmlBlock.Parser parser = (XmlBlock.Parser)set;
1496        mAssets.retrieveAttributes(parser.mParseState, attrs,
1497                array.mData, array.mIndices);
1498
1499        array.mRsrcs = attrs;
1500        array.mXml = parser;
1501
1502        return array;
1503    }
1504
1505    /**
1506     * Store the newly updated configuration.
1507     */
1508    public void updateConfiguration(Configuration config,
1509            DisplayMetrics metrics) {
1510        updateConfiguration(config, metrics, null);
1511    }
1512
1513    /**
1514     * @hide
1515     */
1516    public void updateConfiguration(Configuration config,
1517            DisplayMetrics metrics, CompatibilityInfo compat) {
1518        synchronized (mAccessLock) {
1519            if (false) {
1520                Slog.i(TAG, "**** Updating config of " + this + ": old config is "
1521                        + mConfiguration + " old compat is " + mCompatibilityInfo);
1522                Slog.i(TAG, "**** Updating config of " + this + ": new config is "
1523                        + config + " new compat is " + compat);
1524            }
1525            if (compat != null) {
1526                mCompatibilityInfo = compat;
1527            }
1528            if (metrics != null) {
1529                mMetrics.setTo(metrics);
1530            }
1531            // NOTE: We should re-arrange this code to create a Display
1532            // with the CompatibilityInfo that is used everywhere we deal
1533            // with the display in relation to this app, rather than
1534            // doing the conversion here.  This impl should be okay because
1535            // we make sure to return a compatible display in the places
1536            // where there are public APIs to retrieve the display...  but
1537            // it would be cleaner and more maintainble to just be
1538            // consistently dealing with a compatible display everywhere in
1539            // the framework.
1540            mCompatibilityInfo.applyToDisplayMetrics(mMetrics);
1541
1542            int configChanges = 0xfffffff;
1543            if (config != null) {
1544                mTmpConfig.setTo(config);
1545                int density = config.densityDpi;
1546                if (density == Configuration.DENSITY_DPI_UNDEFINED) {
1547                    density = mMetrics.noncompatDensityDpi;
1548                }
1549
1550                mCompatibilityInfo.applyToConfiguration(density, mTmpConfig);
1551
1552                if (mTmpConfig.locale == null) {
1553                    mTmpConfig.locale = Locale.getDefault();
1554                    mTmpConfig.setLayoutDirection(mTmpConfig.locale);
1555                }
1556                configChanges = mConfiguration.updateFrom(mTmpConfig);
1557                configChanges = ActivityInfo.activityInfoConfigToNative(configChanges);
1558            }
1559            if (mConfiguration.locale == null) {
1560                mConfiguration.locale = Locale.getDefault();
1561                mConfiguration.setLayoutDirection(mConfiguration.locale);
1562            }
1563            if (mConfiguration.densityDpi != Configuration.DENSITY_DPI_UNDEFINED) {
1564                mMetrics.densityDpi = mConfiguration.densityDpi;
1565                mMetrics.density = mConfiguration.densityDpi * DisplayMetrics.DENSITY_DEFAULT_SCALE;
1566            }
1567            mMetrics.scaledDensity = mMetrics.density * mConfiguration.fontScale;
1568
1569            String locale = null;
1570            if (mConfiguration.locale != null) {
1571                locale = mConfiguration.locale.getLanguage();
1572                if (mConfiguration.locale.getCountry() != null) {
1573                    locale += "-" + mConfiguration.locale.getCountry();
1574                }
1575            }
1576            int width, height;
1577            if (mMetrics.widthPixels >= mMetrics.heightPixels) {
1578                width = mMetrics.widthPixels;
1579                height = mMetrics.heightPixels;
1580            } else {
1581                //noinspection SuspiciousNameCombination
1582                width = mMetrics.heightPixels;
1583                //noinspection SuspiciousNameCombination
1584                height = mMetrics.widthPixels;
1585            }
1586            int keyboardHidden = mConfiguration.keyboardHidden;
1587            if (keyboardHidden == Configuration.KEYBOARDHIDDEN_NO
1588                    && mConfiguration.hardKeyboardHidden
1589                            == Configuration.HARDKEYBOARDHIDDEN_YES) {
1590                keyboardHidden = Configuration.KEYBOARDHIDDEN_SOFT;
1591            }
1592            mAssets.setConfiguration(mConfiguration.mcc, mConfiguration.mnc,
1593                    locale, mConfiguration.orientation,
1594                    mConfiguration.touchscreen,
1595                    mConfiguration.densityDpi, mConfiguration.keyboard,
1596                    keyboardHidden, mConfiguration.navigation, width, height,
1597                    mConfiguration.smallestScreenWidthDp,
1598                    mConfiguration.screenWidthDp, mConfiguration.screenHeightDp,
1599                    mConfiguration.screenLayout, mConfiguration.uiMode,
1600                    Build.VERSION.RESOURCES_SDK_INT);
1601
1602            if (DEBUG_CONFIG) {
1603                Slog.i(TAG, "**** Updating config of " + this + ": final config is " + mConfiguration
1604                        + " final compat is " + mCompatibilityInfo);
1605            }
1606
1607            clearDrawableCacheLocked(mDrawableCache, configChanges);
1608            clearDrawableCacheLocked(mColorDrawableCache, configChanges);
1609
1610            mColorStateListCache.clear();
1611
1612            flushLayoutCache();
1613        }
1614        synchronized (sSync) {
1615            if (mPluralRule != null) {
1616                mPluralRule = NativePluralRules.forLocale(config.locale);
1617            }
1618        }
1619    }
1620
1621    private void clearDrawableCacheLocked(
1622            LongSparseArray<WeakReference<ConstantState>> cache,
1623            int configChanges) {
1624        int N = cache.size();
1625        if (DEBUG_CONFIG) {
1626            Log.d(TAG, "Cleaning up drawables config changes: 0x"
1627                    + Integer.toHexString(configChanges));
1628        }
1629        for (int i=0; i<N; i++) {
1630            WeakReference<Drawable.ConstantState> ref = cache.valueAt(i);
1631            if (ref != null) {
1632                Drawable.ConstantState cs = ref.get();
1633                if (cs != null) {
1634                    if (Configuration.needNewResources(
1635                            configChanges, cs.getChangingConfigurations())) {
1636                        if (DEBUG_CONFIG) {
1637                            Log.d(TAG, "FLUSHING #0x"
1638                                    + Long.toHexString(mDrawableCache.keyAt(i))
1639                                    + " / " + cs + " with changes: 0x"
1640                                    + Integer.toHexString(cs.getChangingConfigurations()));
1641                        }
1642                        cache.setValueAt(i, null);
1643                    } else if (DEBUG_CONFIG) {
1644                        Log.d(TAG, "(Keeping #0x"
1645                                + Long.toHexString(cache.keyAt(i))
1646                                + " / " + cs + " with changes: 0x"
1647                                + Integer.toHexString(cs.getChangingConfigurations())
1648                                + ")");
1649                    }
1650                }
1651            }
1652        }
1653    }
1654
1655    /**
1656     * Update the system resources configuration if they have previously
1657     * been initialized.
1658     *
1659     * @hide
1660     */
1661    public static void updateSystemConfiguration(Configuration config, DisplayMetrics metrics,
1662            CompatibilityInfo compat) {
1663        if (mSystem != null) {
1664            mSystem.updateConfiguration(config, metrics, compat);
1665            //Log.i(TAG, "Updated system resources " + mSystem
1666            //        + ": " + mSystem.getConfiguration());
1667        }
1668    }
1669
1670    /**
1671     * Return the current display metrics that are in effect for this resource
1672     * object.  The returned object should be treated as read-only.
1673     *
1674     * @return The resource's current display metrics.
1675     */
1676    public DisplayMetrics getDisplayMetrics() {
1677        if (DEBUG_CONFIG) Slog.v(TAG, "Returning DisplayMetrics: " + mMetrics.widthPixels
1678                + "x" + mMetrics.heightPixels + " " + mMetrics.density);
1679        return mMetrics;
1680    }
1681
1682    /**
1683     * Return the current configuration that is in effect for this resource
1684     * object.  The returned object should be treated as read-only.
1685     *
1686     * @return The resource's current configuration.
1687     */
1688    public Configuration getConfiguration() {
1689        return mConfiguration;
1690    }
1691
1692    /**
1693     * Return the compatibility mode information for the application.
1694     * The returned object should be treated as read-only.
1695     *
1696     * @return compatibility info.
1697     * @hide
1698     */
1699    public CompatibilityInfo getCompatibilityInfo() {
1700        return mCompatibilityInfo;
1701    }
1702
1703    /**
1704     * This is just for testing.
1705     * @hide
1706     */
1707    public void setCompatibilityInfo(CompatibilityInfo ci) {
1708        if (ci != null) {
1709            mCompatibilityInfo = ci;
1710            updateConfiguration(mConfiguration, mMetrics);
1711        }
1712    }
1713
1714    /**
1715     * Return a resource identifier for the given resource name.  A fully
1716     * qualified resource name is of the form "package:type/entry".  The first
1717     * two components (package and type) are optional if defType and
1718     * defPackage, respectively, are specified here.
1719     *
1720     * <p>Note: use of this function is discouraged.  It is much more
1721     * efficient to retrieve resources by identifier than by name.
1722     *
1723     * @param name The name of the desired resource.
1724     * @param defType Optional default resource type to find, if "type/" is
1725     *                not included in the name.  Can be null to require an
1726     *                explicit type.
1727     * @param defPackage Optional default package to find, if "package:" is
1728     *                   not included in the name.  Can be null to require an
1729     *                   explicit package.
1730     *
1731     * @return int The associated resource identifier.  Returns 0 if no such
1732     *         resource was found.  (0 is not a valid resource ID.)
1733     */
1734    public int getIdentifier(String name, String defType, String defPackage) {
1735        if (name == null) {
1736            throw new NullPointerException("name is null");
1737        }
1738        try {
1739            return Integer.parseInt(name);
1740        } catch (Exception e) {
1741            // Ignore
1742        }
1743        return mAssets.getResourceIdentifier(name, defType, defPackage);
1744    }
1745
1746    /**
1747     * Return true if given resource identifier includes a package.
1748     *
1749     * @hide
1750     */
1751    public static boolean resourceHasPackage(int resid) {
1752        return (resid >>> 24) != 0;
1753    }
1754
1755    /**
1756     * Return the full name for a given resource identifier.  This name is
1757     * a single string of the form "package:type/entry".
1758     *
1759     * @param resid The resource identifier whose name is to be retrieved.
1760     *
1761     * @return A string holding the name of the resource.
1762     *
1763     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1764     *
1765     * @see #getResourcePackageName
1766     * @see #getResourceTypeName
1767     * @see #getResourceEntryName
1768     */
1769    public String getResourceName(int resid) throws NotFoundException {
1770        String str = mAssets.getResourceName(resid);
1771        if (str != null) return str;
1772        throw new NotFoundException("Unable to find resource ID #0x"
1773                + Integer.toHexString(resid));
1774    }
1775
1776    /**
1777     * Return the package name for a given resource identifier.
1778     *
1779     * @param resid The resource identifier whose package name is to be
1780     * retrieved.
1781     *
1782     * @return A string holding the package name of the resource.
1783     *
1784     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1785     *
1786     * @see #getResourceName
1787     */
1788    public String getResourcePackageName(int resid) throws NotFoundException {
1789        String str = mAssets.getResourcePackageName(resid);
1790        if (str != null) return str;
1791        throw new NotFoundException("Unable to find resource ID #0x"
1792                + Integer.toHexString(resid));
1793    }
1794
1795    /**
1796     * Return the type name for a given resource identifier.
1797     *
1798     * @param resid The resource identifier whose type name is to be
1799     * retrieved.
1800     *
1801     * @return A string holding the type name of the resource.
1802     *
1803     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1804     *
1805     * @see #getResourceName
1806     */
1807    public String getResourceTypeName(int resid) throws NotFoundException {
1808        String str = mAssets.getResourceTypeName(resid);
1809        if (str != null) return str;
1810        throw new NotFoundException("Unable to find resource ID #0x"
1811                + Integer.toHexString(resid));
1812    }
1813
1814    /**
1815     * Return the entry name for a given resource identifier.
1816     *
1817     * @param resid The resource identifier whose entry name is to be
1818     * retrieved.
1819     *
1820     * @return A string holding the entry name of the resource.
1821     *
1822     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1823     *
1824     * @see #getResourceName
1825     */
1826    public String getResourceEntryName(int resid) throws NotFoundException {
1827        String str = mAssets.getResourceEntryName(resid);
1828        if (str != null) return str;
1829        throw new NotFoundException("Unable to find resource ID #0x"
1830                + Integer.toHexString(resid));
1831    }
1832
1833    /**
1834     * Parse a series of {@link android.R.styleable#Extra &lt;extra&gt;} tags from
1835     * an XML file.  You call this when you are at the parent tag of the
1836     * extra tags, and it will return once all of the child tags have been parsed.
1837     * This will call {@link #parseBundleExtra} for each extra tag encountered.
1838     *
1839     * @param parser The parser from which to retrieve the extras.
1840     * @param outBundle A Bundle in which to place all parsed extras.
1841     * @throws XmlPullParserException
1842     * @throws IOException
1843     */
1844    public void parseBundleExtras(XmlResourceParser parser, Bundle outBundle)
1845            throws XmlPullParserException, IOException {
1846        int outerDepth = parser.getDepth();
1847        int type;
1848        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1849               && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1850            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1851                continue;
1852            }
1853
1854            String nodeName = parser.getName();
1855            if (nodeName.equals("extra")) {
1856                parseBundleExtra("extra", parser, outBundle);
1857                XmlUtils.skipCurrentTag(parser);
1858
1859            } else {
1860                XmlUtils.skipCurrentTag(parser);
1861            }
1862        }
1863    }
1864
1865    /**
1866     * Parse a name/value pair out of an XML tag holding that data.  The
1867     * AttributeSet must be holding the data defined by
1868     * {@link android.R.styleable#Extra}.  The following value types are supported:
1869     * <ul>
1870     * <li> {@link TypedValue#TYPE_STRING}:
1871     * {@link Bundle#putCharSequence Bundle.putCharSequence()}
1872     * <li> {@link TypedValue#TYPE_INT_BOOLEAN}:
1873     * {@link Bundle#putCharSequence Bundle.putBoolean()}
1874     * <li> {@link TypedValue#TYPE_FIRST_INT}-{@link TypedValue#TYPE_LAST_INT}:
1875     * {@link Bundle#putCharSequence Bundle.putBoolean()}
1876     * <li> {@link TypedValue#TYPE_FLOAT}:
1877     * {@link Bundle#putCharSequence Bundle.putFloat()}
1878     * </ul>
1879     *
1880     * @param tagName The name of the tag these attributes come from; this is
1881     * only used for reporting error messages.
1882     * @param attrs The attributes from which to retrieve the name/value pair.
1883     * @param outBundle The Bundle in which to place the parsed value.
1884     * @throws XmlPullParserException If the attributes are not valid.
1885     */
1886    public void parseBundleExtra(String tagName, AttributeSet attrs,
1887            Bundle outBundle) throws XmlPullParserException {
1888        TypedArray sa = obtainAttributes(attrs,
1889                com.android.internal.R.styleable.Extra);
1890
1891        String name = sa.getString(
1892                com.android.internal.R.styleable.Extra_name);
1893        if (name == null) {
1894            sa.recycle();
1895            throw new XmlPullParserException("<" + tagName
1896                    + "> requires an android:name attribute at "
1897                    + attrs.getPositionDescription());
1898        }
1899
1900        TypedValue v = sa.peekValue(
1901                com.android.internal.R.styleable.Extra_value);
1902        if (v != null) {
1903            if (v.type == TypedValue.TYPE_STRING) {
1904                CharSequence cs = v.coerceToString();
1905                outBundle.putCharSequence(name, cs);
1906            } else if (v.type == TypedValue.TYPE_INT_BOOLEAN) {
1907                outBundle.putBoolean(name, v.data != 0);
1908            } else if (v.type >= TypedValue.TYPE_FIRST_INT
1909                    && v.type <= TypedValue.TYPE_LAST_INT) {
1910                outBundle.putInt(name, v.data);
1911            } else if (v.type == TypedValue.TYPE_FLOAT) {
1912                outBundle.putFloat(name, v.getFloat());
1913            } else {
1914                sa.recycle();
1915                throw new XmlPullParserException("<" + tagName
1916                        + "> only supports string, integer, float, color, and boolean at "
1917                        + attrs.getPositionDescription());
1918            }
1919        } else {
1920            sa.recycle();
1921            throw new XmlPullParserException("<" + tagName
1922                    + "> requires an android:value or android:resource attribute at "
1923                    + attrs.getPositionDescription());
1924        }
1925
1926        sa.recycle();
1927    }
1928
1929    /**
1930     * Retrieve underlying AssetManager storage for these resources.
1931     */
1932    public final AssetManager getAssets() {
1933        return mAssets;
1934    }
1935
1936    /**
1937     * Call this to remove all cached loaded layout resources from the
1938     * Resources object.  Only intended for use with performance testing
1939     * tools.
1940     */
1941    public final void flushLayoutCache() {
1942        synchronized (mCachedXmlBlockIds) {
1943            // First see if this block is in our cache.
1944            final int num = mCachedXmlBlockIds.length;
1945            for (int i=0; i<num; i++) {
1946                mCachedXmlBlockIds[i] = -0;
1947                XmlBlock oldBlock = mCachedXmlBlocks[i];
1948                if (oldBlock != null) {
1949                    oldBlock.close();
1950                }
1951                mCachedXmlBlocks[i] = null;
1952            }
1953        }
1954    }
1955
1956    /**
1957     * Start preloading of resource data using this Resources object.  Only
1958     * for use by the zygote process for loading common system resources.
1959     * {@hide}
1960     */
1961    public final void startPreloading() {
1962        synchronized (sSync) {
1963            if (sPreloaded) {
1964                throw new IllegalStateException("Resources already preloaded");
1965            }
1966            sPreloaded = true;
1967            mPreloading = true;
1968            sPreloadedDensity = DisplayMetrics.DENSITY_DEVICE;
1969            mConfiguration.densityDpi = sPreloadedDensity;
1970            updateConfiguration(null, null);
1971        }
1972    }
1973
1974    /**
1975     * Called by zygote when it is done preloading resources, to change back
1976     * to normal Resources operation.
1977     */
1978    public final void finishPreloading() {
1979        if (mPreloading) {
1980            mPreloading = false;
1981            flushLayoutCache();
1982        }
1983    }
1984
1985    /**
1986     * @hide
1987     */
1988    public LongSparseArray<Drawable.ConstantState> getPreloadedDrawables() {
1989        return sPreloadedDrawables[0];
1990    }
1991
1992    private boolean verifyPreloadConfig(int changingConfigurations, int allowVarying,
1993            int resourceId, String name) {
1994        // We allow preloading of resources even if they vary by font scale (which
1995        // doesn't impact resource selection) or density (which we handle specially by
1996        // simply turning off all preloading), as well as any other configs specified
1997        // by the caller.
1998        if (((changingConfigurations&~(ActivityInfo.CONFIG_FONT_SCALE |
1999                ActivityInfo.CONFIG_DENSITY)) & ~allowVarying) != 0) {
2000            String resName;
2001            try {
2002                resName = getResourceName(resourceId);
2003            } catch (NotFoundException e) {
2004                resName = "?";
2005            }
2006            Log.w(TAG, "Preloaded " + name + " resource #0x"
2007                    + Integer.toHexString(resourceId)
2008                    + " (" + resName + ") that varies with configuration!!");
2009            return false;
2010        }
2011        if (TRACE_FOR_PRELOAD) {
2012            String resName;
2013            try {
2014                resName = getResourceName(resourceId);
2015            } catch (NotFoundException e) {
2016                resName = "?";
2017            }
2018            Log.w(TAG, "Preloading " + name + " resource #0x"
2019                    + Integer.toHexString(resourceId)
2020                    + " (" + resName + ")");
2021        }
2022        return true;
2023    }
2024
2025    static private final int LAYOUT_DIR_CONFIG = ActivityInfo.activityInfoConfigToNative(
2026            ActivityInfo.CONFIG_LAYOUT_DIRECTION);
2027
2028    /*package*/ Drawable loadDrawable(TypedValue value, int id)
2029            throws NotFoundException {
2030
2031        if (TRACE_FOR_PRELOAD) {
2032            // Log only framework resources
2033            if ((id >>> 24) == 0x1) {
2034                final String name = getResourceName(id);
2035                if (name != null) android.util.Log.d("PreloadDrawable", name);
2036            }
2037        }
2038
2039        boolean isColorDrawable = false;
2040        if (value.type >= TypedValue.TYPE_FIRST_COLOR_INT &&
2041                value.type <= TypedValue.TYPE_LAST_COLOR_INT) {
2042            isColorDrawable = true;
2043        }
2044        final long key = isColorDrawable ? value.data :
2045                (((long) value.assetCookie) << 32) | value.data;
2046
2047        Drawable dr = getCachedDrawable(isColorDrawable ? mColorDrawableCache : mDrawableCache, key);
2048
2049        if (dr != null) {
2050            return dr;
2051        }
2052        Drawable.ConstantState cs;
2053        if (isColorDrawable) {
2054            cs = sPreloadedColorDrawables.get(key);
2055        } else {
2056            cs = sPreloadedDrawables[mConfiguration.getLayoutDirection()].get(key);
2057        }
2058        if (cs != null) {
2059            dr = cs.newDrawable(this);
2060        } else {
2061            if (isColorDrawable) {
2062                dr = new ColorDrawable(value.data);
2063            }
2064
2065            if (dr == null) {
2066                if (value.string == null) {
2067                    throw new NotFoundException(
2068                            "Resource is not a Drawable (color or path): " + value);
2069                }
2070
2071                String file = value.string.toString();
2072
2073                if (TRACE_FOR_MISS_PRELOAD) {
2074                    // Log only framework resources
2075                    if ((id >>> 24) == 0x1) {
2076                        final String name = getResourceName(id);
2077                        if (name != null) android.util.Log.d(TAG, "Loading framework drawable #"
2078                                + Integer.toHexString(id) + ": " + name
2079                                + " at " + file);
2080                    }
2081                }
2082
2083                if (DEBUG_LOAD) Log.v(TAG, "Loading drawable for cookie "
2084                        + value.assetCookie + ": " + file);
2085
2086                if (file.endsWith(".xml")) {
2087                    Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, file);
2088                    try {
2089                        XmlResourceParser rp = loadXmlResourceParser(
2090                                file, id, value.assetCookie, "drawable");
2091                        dr = Drawable.createFromXml(this, rp);
2092                        rp.close();
2093                    } catch (Exception e) {
2094                        Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
2095                        NotFoundException rnf = new NotFoundException(
2096                            "File " + file + " from drawable resource ID #0x"
2097                            + Integer.toHexString(id));
2098                        rnf.initCause(e);
2099                        throw rnf;
2100                    }
2101                    Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
2102
2103                } else {
2104                    Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, file);
2105                    try {
2106                        InputStream is = mAssets.openNonAsset(
2107                                value.assetCookie, file, AssetManager.ACCESS_STREAMING);
2108        //                System.out.println("Opened file " + file + ": " + is);
2109                        dr = Drawable.createFromResourceStream(this, value, is,
2110                                file, null);
2111                        is.close();
2112        //                System.out.println("Created stream: " + dr);
2113                    } catch (Exception e) {
2114                        Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
2115                        NotFoundException rnf = new NotFoundException(
2116                            "File " + file + " from drawable resource ID #0x"
2117                            + Integer.toHexString(id));
2118                        rnf.initCause(e);
2119                        throw rnf;
2120                    }
2121                    Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
2122                }
2123            }
2124        }
2125
2126        if (dr != null) {
2127            dr.setChangingConfigurations(value.changingConfigurations);
2128            cs = dr.getConstantState();
2129            if (cs != null) {
2130                if (mPreloading) {
2131                    final int changingConfigs = cs.getChangingConfigurations();
2132                    if (isColorDrawable) {
2133                        if (verifyPreloadConfig(changingConfigs, 0, value.resourceId,
2134                                "drawable")) {
2135                            sPreloadedColorDrawables.put(key, cs);
2136                        }
2137                    } else {
2138                        if (verifyPreloadConfig(changingConfigs,
2139                                LAYOUT_DIR_CONFIG, value.resourceId, "drawable")) {
2140                            if ((changingConfigs&LAYOUT_DIR_CONFIG) == 0) {
2141                                // If this resource does not vary based on layout direction,
2142                                // we can put it in all of the preload maps.
2143                                sPreloadedDrawables[0].put(key, cs);
2144                                sPreloadedDrawables[1].put(key, cs);
2145                            } else {
2146                                // Otherwise, only in the layout dir we loaded it for.
2147                                final LongSparseArray<Drawable.ConstantState> preloads
2148                                        = sPreloadedDrawables[mConfiguration.getLayoutDirection()];
2149                                preloads.put(key, cs);
2150                            }
2151                        }
2152                    }
2153                } else {
2154                    synchronized (mAccessLock) {
2155                        //Log.i(TAG, "Saving cached drawable @ #" +
2156                        //        Integer.toHexString(key.intValue())
2157                        //        + " in " + this + ": " + cs);
2158                        if (isColorDrawable) {
2159                            mColorDrawableCache.put(key, new WeakReference<Drawable.ConstantState>(cs));
2160                        } else {
2161                            mDrawableCache.put(key, new WeakReference<Drawable.ConstantState>(cs));
2162                        }
2163                    }
2164                }
2165            }
2166        }
2167
2168        return dr;
2169    }
2170
2171    private Drawable getCachedDrawable(
2172            LongSparseArray<WeakReference<ConstantState>> drawableCache,
2173            long key) {
2174        synchronized (mAccessLock) {
2175            WeakReference<Drawable.ConstantState> wr = drawableCache.get(key);
2176            if (wr != null) {   // we have the key
2177                Drawable.ConstantState entry = wr.get();
2178                if (entry != null) {
2179                    //Log.i(TAG, "Returning cached drawable @ #" +
2180                    //        Integer.toHexString(((Integer)key).intValue())
2181                    //        + " in " + this + ": " + entry);
2182                    return entry.newDrawable(this);
2183                }
2184                else {  // our entry has been purged
2185                    drawableCache.delete(key);
2186                }
2187            }
2188        }
2189        return null;
2190    }
2191
2192    /*package*/ ColorStateList loadColorStateList(TypedValue value, int id)
2193            throws NotFoundException {
2194        if (TRACE_FOR_PRELOAD) {
2195            // Log only framework resources
2196            if ((id >>> 24) == 0x1) {
2197                final String name = getResourceName(id);
2198                if (name != null) android.util.Log.d("PreloadColorStateList", name);
2199            }
2200        }
2201
2202        final long key = (((long) value.assetCookie) << 32) | value.data;
2203
2204        ColorStateList csl;
2205
2206        if (value.type >= TypedValue.TYPE_FIRST_COLOR_INT &&
2207                value.type <= TypedValue.TYPE_LAST_COLOR_INT) {
2208
2209            csl = sPreloadedColorStateLists.get(key);
2210            if (csl != null) {
2211                return csl;
2212            }
2213
2214            csl = ColorStateList.valueOf(value.data);
2215            if (mPreloading) {
2216                if (verifyPreloadConfig(value.changingConfigurations, 0, value.resourceId,
2217                        "color")) {
2218                    sPreloadedColorStateLists.put(key, csl);
2219                }
2220            }
2221
2222            return csl;
2223        }
2224
2225        csl = getCachedColorStateList(key);
2226        if (csl != null) {
2227            return csl;
2228        }
2229
2230        csl = sPreloadedColorStateLists.get(key);
2231        if (csl != null) {
2232            return csl;
2233        }
2234
2235        if (value.string == null) {
2236            throw new NotFoundException(
2237                    "Resource is not a ColorStateList (color or path): " + value);
2238        }
2239
2240        String file = value.string.toString();
2241
2242        if (file.endsWith(".xml")) {
2243            Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, file);
2244            try {
2245                XmlResourceParser rp = loadXmlResourceParser(
2246                        file, id, value.assetCookie, "colorstatelist");
2247                csl = ColorStateList.createFromXml(this, rp);
2248                rp.close();
2249            } catch (Exception e) {
2250                Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
2251                NotFoundException rnf = new NotFoundException(
2252                    "File " + file + " from color state list resource ID #0x"
2253                    + Integer.toHexString(id));
2254                rnf.initCause(e);
2255                throw rnf;
2256            }
2257            Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
2258        } else {
2259            throw new NotFoundException(
2260                    "File " + file + " from drawable resource ID #0x"
2261                    + Integer.toHexString(id) + ": .xml extension required");
2262        }
2263
2264        if (csl != null) {
2265            if (mPreloading) {
2266                if (verifyPreloadConfig(value.changingConfigurations, 0, value.resourceId,
2267                        "color")) {
2268                    sPreloadedColorStateLists.put(key, csl);
2269                }
2270            } else {
2271                synchronized (mAccessLock) {
2272                    //Log.i(TAG, "Saving cached color state list @ #" +
2273                    //        Integer.toHexString(key.intValue())
2274                    //        + " in " + this + ": " + csl);
2275                    mColorStateListCache.put(key, new WeakReference<ColorStateList>(csl));
2276                }
2277            }
2278        }
2279
2280        return csl;
2281    }
2282
2283    private ColorStateList getCachedColorStateList(long key) {
2284        synchronized (mAccessLock) {
2285            WeakReference<ColorStateList> wr = mColorStateListCache.get(key);
2286            if (wr != null) {   // we have the key
2287                ColorStateList entry = wr.get();
2288                if (entry != null) {
2289                    //Log.i(TAG, "Returning cached color state list @ #" +
2290                    //        Integer.toHexString(((Integer)key).intValue())
2291                    //        + " in " + this + ": " + entry);
2292                    return entry;
2293                } else {  // our entry has been purged
2294                    mColorStateListCache.delete(key);
2295                }
2296            }
2297        }
2298        return null;
2299    }
2300
2301    /*package*/ XmlResourceParser loadXmlResourceParser(int id, String type)
2302            throws NotFoundException {
2303        synchronized (mAccessLock) {
2304            TypedValue value = mTmpValue;
2305            if (value == null) {
2306                mTmpValue = value = new TypedValue();
2307            }
2308            getValue(id, value, true);
2309            if (value.type == TypedValue.TYPE_STRING) {
2310                return loadXmlResourceParser(value.string.toString(), id,
2311                        value.assetCookie, type);
2312            }
2313            throw new NotFoundException(
2314                    "Resource ID #0x" + Integer.toHexString(id) + " type #0x"
2315                    + Integer.toHexString(value.type) + " is not valid");
2316        }
2317    }
2318
2319    /*package*/ XmlResourceParser loadXmlResourceParser(String file, int id,
2320            int assetCookie, String type) throws NotFoundException {
2321        if (id != 0) {
2322            try {
2323                // These may be compiled...
2324                synchronized (mCachedXmlBlockIds) {
2325                    // First see if this block is in our cache.
2326                    final int num = mCachedXmlBlockIds.length;
2327                    for (int i=0; i<num; i++) {
2328                        if (mCachedXmlBlockIds[i] == id) {
2329                            //System.out.println("**** REUSING XML BLOCK!  id="
2330                            //                   + id + ", index=" + i);
2331                            return mCachedXmlBlocks[i].newParser();
2332                        }
2333                    }
2334
2335                    // Not in the cache, create a new block and put it at
2336                    // the next slot in the cache.
2337                    XmlBlock block = mAssets.openXmlBlockAsset(
2338                            assetCookie, file);
2339                    if (block != null) {
2340                        int pos = mLastCachedXmlBlockIndex+1;
2341                        if (pos >= num) pos = 0;
2342                        mLastCachedXmlBlockIndex = pos;
2343                        XmlBlock oldBlock = mCachedXmlBlocks[pos];
2344                        if (oldBlock != null) {
2345                            oldBlock.close();
2346                        }
2347                        mCachedXmlBlockIds[pos] = id;
2348                        mCachedXmlBlocks[pos] = block;
2349                        //System.out.println("**** CACHING NEW XML BLOCK!  id="
2350                        //                   + id + ", index=" + pos);
2351                        return block.newParser();
2352                    }
2353                }
2354            } catch (Exception e) {
2355                NotFoundException rnf = new NotFoundException(
2356                        "File " + file + " from xml type " + type + " resource ID #0x"
2357                        + Integer.toHexString(id));
2358                rnf.initCause(e);
2359                throw rnf;
2360            }
2361        }
2362
2363        throw new NotFoundException(
2364                "File " + file + " from xml type " + type + " resource ID #0x"
2365                + Integer.toHexString(id));
2366    }
2367
2368    private TypedArray getCachedStyledAttributes(int len) {
2369        synchronized (mAccessLock) {
2370            TypedArray attrs = mCachedStyledAttributes;
2371            if (attrs != null) {
2372                mCachedStyledAttributes = null;
2373                if (DEBUG_ATTRIBUTES_CACHE) {
2374                    mLastRetrievedAttrs = new RuntimeException("here");
2375                    mLastRetrievedAttrs.fillInStackTrace();
2376                }
2377
2378                attrs.mLength = len;
2379                int fullLen = len * AssetManager.STYLE_NUM_ENTRIES;
2380                if (attrs.mData.length >= fullLen) {
2381                    return attrs;
2382                }
2383                attrs.mData = new int[fullLen];
2384                attrs.mIndices = new int[1+len];
2385                return attrs;
2386            }
2387            if (DEBUG_ATTRIBUTES_CACHE) {
2388                RuntimeException here = new RuntimeException("here");
2389                here.fillInStackTrace();
2390                if (mLastRetrievedAttrs != null) {
2391                    Log.i(TAG, "Allocated new TypedArray of " + len + " in " + this, here);
2392                    Log.i(TAG, "Last retrieved attributes here", mLastRetrievedAttrs);
2393                }
2394                mLastRetrievedAttrs = here;
2395            }
2396            return new TypedArray(this,
2397                    new int[len*AssetManager.STYLE_NUM_ENTRIES],
2398                    new int[1+len], len);
2399        }
2400    }
2401
2402    private Resources() {
2403        mAssets = AssetManager.getSystem();
2404        // NOTE: Intentionally leaving this uninitialized (all values set
2405        // to zero), so that anyone who tries to do something that requires
2406        // metrics will get a very wrong value.
2407        mConfiguration.setToDefaults();
2408        mMetrics.setToDefaults();
2409        updateConfiguration(null, null);
2410        mAssets.ensureStringBlocks();
2411    }
2412}
2413