Resources.java revision ebff8f92f13513ce37bd74759eb1db63f2220590
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.screenWidthDp, mConfiguration.screenHeightDp,
1462                    mConfiguration.screenLayout, mConfiguration.uiMode,
1463                    Build.VERSION.RESOURCES_SDK_INT);
1464
1465            clearDrawableCache(mDrawableCache, configChanges);
1466            clearDrawableCache(mColorDrawableCache, configChanges);
1467
1468            mColorStateListCache.clear();
1469
1470            flushLayoutCache();
1471        }
1472        synchronized (mSync) {
1473            if (mPluralRule != null) {
1474                mPluralRule = NativePluralRules.forLocale(config.locale);
1475            }
1476        }
1477    }
1478
1479    private void clearDrawableCache(
1480            LongSparseArray<WeakReference<ConstantState>> cache,
1481            int configChanges) {
1482        int N = cache.size();
1483        if (DEBUG_CONFIG) {
1484            Log.d(TAG, "Cleaning up drawables config changes: 0x"
1485                    + Integer.toHexString(configChanges));
1486        }
1487        for (int i=0; i<N; i++) {
1488            WeakReference<Drawable.ConstantState> ref = cache.valueAt(i);
1489            if (ref != null) {
1490                Drawable.ConstantState cs = ref.get();
1491                if (cs != null) {
1492                    if (Configuration.needNewResources(
1493                            configChanges, cs.getChangingConfigurations())) {
1494                        if (DEBUG_CONFIG) {
1495                            Log.d(TAG, "FLUSHING #0x"
1496                                    + Long.toHexString(mDrawableCache.keyAt(i))
1497                                    + " / " + cs + " with changes: 0x"
1498                                    + Integer.toHexString(cs.getChangingConfigurations()));
1499                        }
1500                        cache.setValueAt(i, null);
1501                    } else if (DEBUG_CONFIG) {
1502                        Log.d(TAG, "(Keeping #0x"
1503                                + Long.toHexString(cache.keyAt(i))
1504                                + " / " + cs + " with changes: 0x"
1505                                + Integer.toHexString(cs.getChangingConfigurations())
1506                                + ")");
1507                    }
1508                }
1509            }
1510        }
1511    }
1512
1513    /**
1514     * Update the system resources configuration if they have previously
1515     * been initialized.
1516     *
1517     * @hide
1518     */
1519    public static void updateSystemConfiguration(Configuration config, DisplayMetrics metrics,
1520            CompatibilityInfo compat) {
1521        if (mSystem != null) {
1522            mSystem.updateConfiguration(config, metrics, compat);
1523            //Log.i(TAG, "Updated system resources " + mSystem
1524            //        + ": " + mSystem.getConfiguration());
1525        }
1526    }
1527
1528    /**
1529     * @hide
1530     */
1531    public static void updateSystemConfiguration(Configuration config, DisplayMetrics metrics) {
1532        updateSystemConfiguration(config, metrics, null);
1533    }
1534
1535    /**
1536     * Return the current display metrics that are in effect for this resource
1537     * object.  The returned object should be treated as read-only.
1538     *
1539     * @return The resource's current display metrics.
1540     */
1541    public DisplayMetrics getDisplayMetrics() {
1542        return mMetrics;
1543    }
1544
1545    /**
1546     * Return the current configuration that is in effect for this resource
1547     * object.  The returned object should be treated as read-only.
1548     *
1549     * @return The resource's current configuration.
1550     */
1551    public Configuration getConfiguration() {
1552        return mConfiguration;
1553    }
1554
1555    /**
1556     * Return the compatibility mode information for the application.
1557     * The returned object should be treated as read-only.
1558     *
1559     * @return compatibility info. null if the app does not require compatibility mode.
1560     * @hide
1561     */
1562    public CompatibilityInfo getCompatibilityInfo() {
1563        return mCompatibilityInfo;
1564    }
1565
1566    /**
1567     * This is just for testing.
1568     * @hide
1569     */
1570    public void setCompatibilityInfo(CompatibilityInfo ci) {
1571        mCompatibilityInfo = ci;
1572        updateConfiguration(mConfiguration, mMetrics);
1573    }
1574
1575    /**
1576     * Return a resource identifier for the given resource name.  A fully
1577     * qualified resource name is of the form "package:type/entry".  The first
1578     * two components (package and type) are optional if defType and
1579     * defPackage, respectively, are specified here.
1580     *
1581     * <p>Note: use of this function is discouraged.  It is much more
1582     * efficient to retrieve resources by identifier than by name.
1583     *
1584     * @param name The name of the desired resource.
1585     * @param defType Optional default resource type to find, if "type/" is
1586     *                not included in the name.  Can be null to require an
1587     *                explicit type.
1588     * @param defPackage Optional default package to find, if "package:" is
1589     *                   not included in the name.  Can be null to require an
1590     *                   explicit package.
1591     *
1592     * @return int The associated resource identifier.  Returns 0 if no such
1593     *         resource was found.  (0 is not a valid resource ID.)
1594     */
1595    public int getIdentifier(String name, String defType, String defPackage) {
1596        try {
1597            return Integer.parseInt(name);
1598        } catch (Exception e) {
1599            // Ignore
1600        }
1601        return mAssets.getResourceIdentifier(name, defType, defPackage);
1602    }
1603
1604    /**
1605     * Return the full name for a given resource identifier.  This name is
1606     * a single string of the form "package:type/entry".
1607     *
1608     * @param resid The resource identifier whose name is to be retrieved.
1609     *
1610     * @return A string holding the name of the resource.
1611     *
1612     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1613     *
1614     * @see #getResourcePackageName
1615     * @see #getResourceTypeName
1616     * @see #getResourceEntryName
1617     */
1618    public String getResourceName(int resid) throws NotFoundException {
1619        String str = mAssets.getResourceName(resid);
1620        if (str != null) return str;
1621        throw new NotFoundException("Unable to find resource ID #0x"
1622                + Integer.toHexString(resid));
1623    }
1624
1625    /**
1626     * Return the package name for a given resource identifier.
1627     *
1628     * @param resid The resource identifier whose package name is to be
1629     * retrieved.
1630     *
1631     * @return A string holding the package name of the resource.
1632     *
1633     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1634     *
1635     * @see #getResourceName
1636     */
1637    public String getResourcePackageName(int resid) throws NotFoundException {
1638        String str = mAssets.getResourcePackageName(resid);
1639        if (str != null) return str;
1640        throw new NotFoundException("Unable to find resource ID #0x"
1641                + Integer.toHexString(resid));
1642    }
1643
1644    /**
1645     * Return the type name for a given resource identifier.
1646     *
1647     * @param resid The resource identifier whose type name is to be
1648     * retrieved.
1649     *
1650     * @return A string holding the type name of the resource.
1651     *
1652     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1653     *
1654     * @see #getResourceName
1655     */
1656    public String getResourceTypeName(int resid) throws NotFoundException {
1657        String str = mAssets.getResourceTypeName(resid);
1658        if (str != null) return str;
1659        throw new NotFoundException("Unable to find resource ID #0x"
1660                + Integer.toHexString(resid));
1661    }
1662
1663    /**
1664     * Return the entry name for a given resource identifier.
1665     *
1666     * @param resid The resource identifier whose entry name is to be
1667     * retrieved.
1668     *
1669     * @return A string holding the entry name of the resource.
1670     *
1671     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1672     *
1673     * @see #getResourceName
1674     */
1675    public String getResourceEntryName(int resid) throws NotFoundException {
1676        String str = mAssets.getResourceEntryName(resid);
1677        if (str != null) return str;
1678        throw new NotFoundException("Unable to find resource ID #0x"
1679                + Integer.toHexString(resid));
1680    }
1681
1682    /**
1683     * Parse a series of {@link android.R.styleable#Extra &lt;extra&gt;} tags from
1684     * an XML file.  You call this when you are at the parent tag of the
1685     * extra tags, and it will return once all of the child tags have been parsed.
1686     * This will call {@link #parseBundleExtra} for each extra tag encountered.
1687     *
1688     * @param parser The parser from which to retrieve the extras.
1689     * @param outBundle A Bundle in which to place all parsed extras.
1690     * @throws XmlPullParserException
1691     * @throws IOException
1692     */
1693    public void parseBundleExtras(XmlResourceParser parser, Bundle outBundle)
1694            throws XmlPullParserException, IOException {
1695        int outerDepth = parser.getDepth();
1696        int type;
1697        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1698               && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1699            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1700                continue;
1701            }
1702
1703            String nodeName = parser.getName();
1704            if (nodeName.equals("extra")) {
1705                parseBundleExtra("extra", parser, outBundle);
1706                XmlUtils.skipCurrentTag(parser);
1707
1708            } else {
1709                XmlUtils.skipCurrentTag(parser);
1710            }
1711        }
1712    }
1713
1714    /**
1715     * Parse a name/value pair out of an XML tag holding that data.  The
1716     * AttributeSet must be holding the data defined by
1717     * {@link android.R.styleable#Extra}.  The following value types are supported:
1718     * <ul>
1719     * <li> {@link TypedValue#TYPE_STRING}:
1720     * {@link Bundle#putCharSequence Bundle.putCharSequence()}
1721     * <li> {@link TypedValue#TYPE_INT_BOOLEAN}:
1722     * {@link Bundle#putCharSequence Bundle.putBoolean()}
1723     * <li> {@link TypedValue#TYPE_FIRST_INT}-{@link TypedValue#TYPE_LAST_INT}:
1724     * {@link Bundle#putCharSequence Bundle.putBoolean()}
1725     * <li> {@link TypedValue#TYPE_FLOAT}:
1726     * {@link Bundle#putCharSequence Bundle.putFloat()}
1727     * </ul>
1728     *
1729     * @param tagName The name of the tag these attributes come from; this is
1730     * only used for reporting error messages.
1731     * @param attrs The attributes from which to retrieve the name/value pair.
1732     * @param outBundle The Bundle in which to place the parsed value.
1733     * @throws XmlPullParserException If the attributes are not valid.
1734     */
1735    public void parseBundleExtra(String tagName, AttributeSet attrs,
1736            Bundle outBundle) throws XmlPullParserException {
1737        TypedArray sa = obtainAttributes(attrs,
1738                com.android.internal.R.styleable.Extra);
1739
1740        String name = sa.getString(
1741                com.android.internal.R.styleable.Extra_name);
1742        if (name == null) {
1743            sa.recycle();
1744            throw new XmlPullParserException("<" + tagName
1745                    + "> requires an android:name attribute at "
1746                    + attrs.getPositionDescription());
1747        }
1748
1749        TypedValue v = sa.peekValue(
1750                com.android.internal.R.styleable.Extra_value);
1751        if (v != null) {
1752            if (v.type == TypedValue.TYPE_STRING) {
1753                CharSequence cs = v.coerceToString();
1754                outBundle.putCharSequence(name, cs);
1755            } else if (v.type == TypedValue.TYPE_INT_BOOLEAN) {
1756                outBundle.putBoolean(name, v.data != 0);
1757            } else if (v.type >= TypedValue.TYPE_FIRST_INT
1758                    && v.type <= TypedValue.TYPE_LAST_INT) {
1759                outBundle.putInt(name, v.data);
1760            } else if (v.type == TypedValue.TYPE_FLOAT) {
1761                outBundle.putFloat(name, v.getFloat());
1762            } else {
1763                sa.recycle();
1764                throw new XmlPullParserException("<" + tagName
1765                        + "> only supports string, integer, float, color, and boolean at "
1766                        + attrs.getPositionDescription());
1767            }
1768        } else {
1769            sa.recycle();
1770            throw new XmlPullParserException("<" + tagName
1771                    + "> requires an android:value or android:resource attribute at "
1772                    + attrs.getPositionDescription());
1773        }
1774
1775        sa.recycle();
1776    }
1777
1778    /**
1779     * Retrieve underlying AssetManager storage for these resources.
1780     */
1781    public final AssetManager getAssets() {
1782        return mAssets;
1783    }
1784
1785    /**
1786     * Call this to remove all cached loaded layout resources from the
1787     * Resources object.  Only intended for use with performance testing
1788     * tools.
1789     */
1790    public final void flushLayoutCache() {
1791        synchronized (mCachedXmlBlockIds) {
1792            // First see if this block is in our cache.
1793            final int num = mCachedXmlBlockIds.length;
1794            for (int i=0; i<num; i++) {
1795                mCachedXmlBlockIds[i] = -0;
1796                XmlBlock oldBlock = mCachedXmlBlocks[i];
1797                if (oldBlock != null) {
1798                    oldBlock.close();
1799                }
1800                mCachedXmlBlocks[i] = null;
1801            }
1802        }
1803    }
1804
1805    /**
1806     * Start preloading of resource data using this Resources object.  Only
1807     * for use by the zygote process for loading common system resources.
1808     * {@hide}
1809     */
1810    public final void startPreloading() {
1811        synchronized (mSync) {
1812            if (mPreloaded) {
1813                throw new IllegalStateException("Resources already preloaded");
1814            }
1815            mPreloaded = true;
1816            mPreloading = true;
1817        }
1818    }
1819
1820    /**
1821     * Called by zygote when it is done preloading resources, to change back
1822     * to normal Resources operation.
1823     */
1824    public final void finishPreloading() {
1825        if (mPreloading) {
1826            mPreloading = false;
1827            flushLayoutCache();
1828        }
1829    }
1830
1831    /*package*/ Drawable loadDrawable(TypedValue value, int id)
1832            throws NotFoundException {
1833
1834        if (TRACE_FOR_PRELOAD) {
1835            // Log only framework resources
1836            if ((id >>> 24) == 0x1) {
1837                final String name = getResourceName(id);
1838                if (name != null) android.util.Log.d("PreloadDrawable", name);
1839            }
1840        }
1841
1842        final long key = (((long) value.assetCookie) << 32) | value.data;
1843        boolean isColorDrawable = false;
1844        if (value.type >= TypedValue.TYPE_FIRST_COLOR_INT &&
1845                value.type <= TypedValue.TYPE_LAST_COLOR_INT) {
1846            isColorDrawable = true;
1847        }
1848        Drawable dr = getCachedDrawable(isColorDrawable ? mColorDrawableCache : mDrawableCache, key);
1849
1850        if (dr != null) {
1851            return dr;
1852        }
1853
1854        Drawable.ConstantState cs = isColorDrawable ? sPreloadedColorDrawables.get(key) : sPreloadedDrawables.get(key);
1855        if (cs != null) {
1856            dr = cs.newDrawable(this);
1857        } else {
1858            if (value.type >= TypedValue.TYPE_FIRST_COLOR_INT &&
1859                    value.type <= TypedValue.TYPE_LAST_COLOR_INT) {
1860                dr = new ColorDrawable(value.data);
1861            }
1862
1863            if (dr == null) {
1864                if (value.string == null) {
1865                    throw new NotFoundException(
1866                            "Resource is not a Drawable (color or path): " + value);
1867                }
1868
1869                String file = value.string.toString();
1870
1871                if (DEBUG_LOAD) Log.v(TAG, "Loading drawable for cookie "
1872                        + value.assetCookie + ": " + file);
1873
1874                if (file.endsWith(".xml")) {
1875                    try {
1876                        XmlResourceParser rp = loadXmlResourceParser(
1877                                file, id, value.assetCookie, "drawable");
1878                        dr = Drawable.createFromXml(this, rp);
1879                        rp.close();
1880                    } catch (Exception e) {
1881                        NotFoundException rnf = new NotFoundException(
1882                            "File " + file + " from drawable resource ID #0x"
1883                            + Integer.toHexString(id));
1884                        rnf.initCause(e);
1885                        throw rnf;
1886                    }
1887
1888                } else {
1889                    try {
1890                        InputStream is = mAssets.openNonAsset(
1891                                value.assetCookie, file, AssetManager.ACCESS_STREAMING);
1892        //                System.out.println("Opened file " + file + ": " + is);
1893                        dr = Drawable.createFromResourceStream(this, value, is,
1894                                file, null);
1895                        is.close();
1896        //                System.out.println("Created stream: " + dr);
1897                    } catch (Exception e) {
1898                        NotFoundException rnf = new NotFoundException(
1899                            "File " + file + " from drawable resource ID #0x"
1900                            + Integer.toHexString(id));
1901                        rnf.initCause(e);
1902                        throw rnf;
1903                    }
1904                }
1905            }
1906        }
1907
1908        if (dr != null) {
1909            dr.setChangingConfigurations(value.changingConfigurations);
1910            cs = dr.getConstantState();
1911            if (cs != null) {
1912                if (mPreloading) {
1913                    if (isColorDrawable) {
1914                        sPreloadedColorDrawables.put(key, cs);
1915                    } else {
1916                        sPreloadedDrawables.put(key, cs);
1917                    }
1918                } else {
1919                    synchronized (mTmpValue) {
1920                        //Log.i(TAG, "Saving cached drawable @ #" +
1921                        //        Integer.toHexString(key.intValue())
1922                        //        + " in " + this + ": " + cs);
1923                        if (isColorDrawable) {
1924                            mColorDrawableCache.put(key, new WeakReference<Drawable.ConstantState>(cs));
1925                        } else {
1926                            mDrawableCache.put(key, new WeakReference<Drawable.ConstantState>(cs));
1927                        }
1928                    }
1929                }
1930            }
1931        }
1932
1933        return dr;
1934    }
1935
1936    private Drawable getCachedDrawable(
1937            LongSparseArray<WeakReference<ConstantState>> drawableCache,
1938            long key) {
1939        synchronized (mTmpValue) {
1940            WeakReference<Drawable.ConstantState> wr = drawableCache.get(key);
1941            if (wr != null) {   // we have the key
1942                Drawable.ConstantState entry = wr.get();
1943                if (entry != null) {
1944                    //Log.i(TAG, "Returning cached drawable @ #" +
1945                    //        Integer.toHexString(((Integer)key).intValue())
1946                    //        + " in " + this + ": " + entry);
1947                    return entry.newDrawable(this);
1948                }
1949                else {  // our entry has been purged
1950                    drawableCache.delete(key);
1951                }
1952            }
1953        }
1954        return null;
1955    }
1956
1957    /*package*/ ColorStateList loadColorStateList(TypedValue value, int id)
1958            throws NotFoundException {
1959        if (TRACE_FOR_PRELOAD) {
1960            // Log only framework resources
1961            if ((id >>> 24) == 0x1) {
1962                final String name = getResourceName(id);
1963                if (name != null) android.util.Log.d("PreloadColorStateList", name);
1964            }
1965        }
1966
1967        final int key = (value.assetCookie << 24) | value.data;
1968
1969        ColorStateList csl;
1970
1971        if (value.type >= TypedValue.TYPE_FIRST_COLOR_INT &&
1972                value.type <= TypedValue.TYPE_LAST_COLOR_INT) {
1973
1974            csl = mPreloadedColorStateLists.get(key);
1975            if (csl != null) {
1976                return csl;
1977            }
1978
1979            csl = ColorStateList.valueOf(value.data);
1980            if (mPreloading) {
1981                mPreloadedColorStateLists.put(key, csl);
1982            }
1983
1984            return csl;
1985        }
1986
1987        csl = getCachedColorStateList(key);
1988        if (csl != null) {
1989            return csl;
1990        }
1991
1992        csl = mPreloadedColorStateLists.get(key);
1993        if (csl != null) {
1994            return csl;
1995        }
1996
1997        if (value.string == null) {
1998            throw new NotFoundException(
1999                    "Resource is not a ColorStateList (color or path): " + value);
2000        }
2001
2002        String file = value.string.toString();
2003
2004        if (file.endsWith(".xml")) {
2005            try {
2006                XmlResourceParser rp = loadXmlResourceParser(
2007                        file, id, value.assetCookie, "colorstatelist");
2008                csl = ColorStateList.createFromXml(this, rp);
2009                rp.close();
2010            } catch (Exception e) {
2011                NotFoundException rnf = new NotFoundException(
2012                    "File " + file + " from color state list resource ID #0x"
2013                    + Integer.toHexString(id));
2014                rnf.initCause(e);
2015                throw rnf;
2016            }
2017        } else {
2018            throw new NotFoundException(
2019                    "File " + file + " from drawable resource ID #0x"
2020                    + Integer.toHexString(id) + ": .xml extension required");
2021        }
2022
2023        if (csl != null) {
2024            if (mPreloading) {
2025                mPreloadedColorStateLists.put(key, csl);
2026            } else {
2027                synchronized (mTmpValue) {
2028                    //Log.i(TAG, "Saving cached color state list @ #" +
2029                    //        Integer.toHexString(key.intValue())
2030                    //        + " in " + this + ": " + csl);
2031                    mColorStateListCache.put(
2032                        key, new WeakReference<ColorStateList>(csl));
2033                }
2034            }
2035        }
2036
2037        return csl;
2038    }
2039
2040    private ColorStateList getCachedColorStateList(int key) {
2041        synchronized (mTmpValue) {
2042            WeakReference<ColorStateList> wr = mColorStateListCache.get(key);
2043            if (wr != null) {   // we have the key
2044                ColorStateList entry = wr.get();
2045                if (entry != null) {
2046                    //Log.i(TAG, "Returning cached color state list @ #" +
2047                    //        Integer.toHexString(((Integer)key).intValue())
2048                    //        + " in " + this + ": " + entry);
2049                    return entry;
2050                }
2051                else {  // our entry has been purged
2052                    mColorStateListCache.delete(key);
2053                }
2054            }
2055        }
2056        return null;
2057    }
2058
2059    /*package*/ XmlResourceParser loadXmlResourceParser(int id, String type)
2060            throws NotFoundException {
2061        synchronized (mTmpValue) {
2062            TypedValue value = mTmpValue;
2063            getValue(id, value, true);
2064            if (value.type == TypedValue.TYPE_STRING) {
2065                return loadXmlResourceParser(value.string.toString(), id,
2066                        value.assetCookie, type);
2067            }
2068            throw new NotFoundException(
2069                    "Resource ID #0x" + Integer.toHexString(id) + " type #0x"
2070                    + Integer.toHexString(value.type) + " is not valid");
2071        }
2072    }
2073
2074    /*package*/ XmlResourceParser loadXmlResourceParser(String file, int id,
2075            int assetCookie, String type) throws NotFoundException {
2076        if (id != 0) {
2077            try {
2078                // These may be compiled...
2079                synchronized (mCachedXmlBlockIds) {
2080                    // First see if this block is in our cache.
2081                    final int num = mCachedXmlBlockIds.length;
2082                    for (int i=0; i<num; i++) {
2083                        if (mCachedXmlBlockIds[i] == id) {
2084                            //System.out.println("**** REUSING XML BLOCK!  id="
2085                            //                   + id + ", index=" + i);
2086                            return mCachedXmlBlocks[i].newParser();
2087                        }
2088                    }
2089
2090                    // Not in the cache, create a new block and put it at
2091                    // the next slot in the cache.
2092                    XmlBlock block = mAssets.openXmlBlockAsset(
2093                            assetCookie, file);
2094                    if (block != null) {
2095                        int pos = mLastCachedXmlBlockIndex+1;
2096                        if (pos >= num) pos = 0;
2097                        mLastCachedXmlBlockIndex = pos;
2098                        XmlBlock oldBlock = mCachedXmlBlocks[pos];
2099                        if (oldBlock != null) {
2100                            oldBlock.close();
2101                        }
2102                        mCachedXmlBlockIds[pos] = id;
2103                        mCachedXmlBlocks[pos] = block;
2104                        //System.out.println("**** CACHING NEW XML BLOCK!  id="
2105                        //                   + id + ", index=" + pos);
2106                        return block.newParser();
2107                    }
2108                }
2109            } catch (Exception e) {
2110                NotFoundException rnf = new NotFoundException(
2111                        "File " + file + " from xml type " + type + " resource ID #0x"
2112                        + Integer.toHexString(id));
2113                rnf.initCause(e);
2114                throw rnf;
2115            }
2116        }
2117
2118        throw new NotFoundException(
2119                "File " + file + " from xml type " + type + " resource ID #0x"
2120                + Integer.toHexString(id));
2121    }
2122
2123    /**
2124     * Returns the display adjusted for the Resources' metrics.
2125     * @hide
2126     */
2127    public Display getDefaultDisplay(Display defaultDisplay) {
2128        if (mDefaultDisplay == null) {
2129            if (!mCompatibilityInfo.isScalingRequired() && mCompatibilityInfo.supportsScreen()) {
2130                // the app supports the display. just use the default one.
2131                mDefaultDisplay = defaultDisplay;
2132            } else {
2133                // display needs adjustment.
2134                mDefaultDisplay = Display.createMetricsBasedDisplay(
2135                        defaultDisplay.getDisplayId(), mMetrics);
2136            }
2137        }
2138        return mDefaultDisplay;
2139    }
2140
2141    private TypedArray getCachedStyledAttributes(int len) {
2142        synchronized (mTmpValue) {
2143            TypedArray attrs = mCachedStyledAttributes;
2144            if (attrs != null) {
2145                mCachedStyledAttributes = null;
2146
2147                attrs.mLength = len;
2148                int fullLen = len * AssetManager.STYLE_NUM_ENTRIES;
2149                if (attrs.mData.length >= fullLen) {
2150                    return attrs;
2151                }
2152                attrs.mData = new int[fullLen];
2153                attrs.mIndices = new int[1+len];
2154                return attrs;
2155            }
2156            return new TypedArray(this,
2157                    new int[len*AssetManager.STYLE_NUM_ENTRIES],
2158                    new int[1+len], len);
2159        }
2160    }
2161
2162    private Resources() {
2163        mAssets = AssetManager.getSystem();
2164        // NOTE: Intentionally leaving this uninitialized (all values set
2165        // to zero), so that anyone who tries to do something that requires
2166        // metrics will get a very wrong value.
2167        mConfiguration.setToDefaults();
2168        mMetrics.setToDefaults();
2169        updateConfiguration(null, null);
2170        mAssets.ensureStringBlocks();
2171        mCompatibilityInfo = CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO;
2172    }
2173}
2174