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