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