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