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