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