Debian Codegraph @

core/java/android/content/res/ResourcesImpl.java

raw symbols SCIP
1 /*
2 * Copyright 2018 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 package android.content.res;
17
18 import static android.content.res.Resources.ID_NULL;
19
20 import android.animation.Animator;
21 import android.animation.StateListAnimator;
22 import android.annotation.AnyRes;
23 import android.annotation.AttrRes;
24 import android.annotation.NonNull;
25 import android.annotation.Nullable;
26 import android.annotation.PluralsRes;
27 import android.annotation.RawRes;
28 import android.annotation.StyleRes;
29 import android.annotation.StyleableRes;
30 import android.compat.annotation.UnsupportedAppUsage;
31 import android.content.pm.ActivityInfo;
32 import android.content.pm.ActivityInfo.Config;
33 import android.content.res.AssetManager.AssetInputStream;
34 import android.content.res.Configuration.NativeConfig;
35 import android.content.res.Resources.NotFoundException;
36 import android.graphics.ImageDecoder;
37 import android.graphics.Typeface;
38 import android.graphics.drawable.ColorDrawable;
39 import android.graphics.drawable.ColorStateListDrawable;
40 import android.graphics.drawable.Drawable;
41 import android.graphics.drawable.DrawableContainer;
42 import android.icu.text.PluralRules;
43 import android.os.Build;
44 import android.os.LocaleList;
45 import android.os.Trace;
46 import android.util.AttributeSet;
47 import android.util.DisplayMetrics;
48 import android.util.Log;
49 import android.util.LongSparseArray;
50 import android.util.Slog;
51 import android.util.TypedValue;
52 import android.util.Xml;
53 import android.view.DisplayAdjustments;
54
55 import com.android.internal.util.GrowingArrayUtils;
56
57 import libcore.util.NativeAllocationRegistry;
58
59 import org.xmlpull.v1.XmlPullParser;
60 import org.xmlpull.v1.XmlPullParserException;
61
62 import java.io.IOException;
63 import java.io.InputStream;
64 import java.io.PrintWriter;
65 import java.util.Arrays;
66 import java.util.Locale;
67
68 /**
69 * The implementation of Resource access. This class contains the AssetManager and all caches
70 * associated with it.
71 *
72 * {@link Resources} is just a thing wrapper around this class. When a configuration change
73 * occurs, clients can retain the same {@link Resources} reference because the underlying
74 * {@link ResourcesImpl} object will be updated or re-created.
75 *
76 * @hide
77 */
78 public class ResourcesImpl {
79 static final String TAG = "Resources";
80
81 private static final boolean DEBUG_LOAD = false;
82 private static final boolean DEBUG_CONFIG = false;
83
84 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
85 private static final boolean TRACE_FOR_PRELOAD = false; // Do we still need it?
86 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
87 private static final boolean TRACE_FOR_MISS_PRELOAD = false; // Do we still need it?
88
89 private static final int ID_OTHER = 0x01000004;
90
91 private static final Object sSync = new Object();
92
93 private static boolean sPreloaded;
94 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
95 private boolean mPreloading;
96
97 // Information about preloaded resources. Note that they are not
98 // protected by a lock, because while preloading in zygote we are all
99 // single-threaded, and after that these are immutable.
100 @UnsupportedAppUsage
101 private static final LongSparseArray<Drawable.ConstantState>[] sPreloadedDrawables;
102 @UnsupportedAppUsage
103 private static final LongSparseArray<Drawable.ConstantState> sPreloadedColorDrawables
104 = new LongSparseArray<>();
105 @UnsupportedAppUsage
106 private static final LongSparseArray<android.content.res.ConstantState<ComplexColor>>
107 sPreloadedComplexColors = new LongSparseArray<>();
108
109 /** Lock object used to protect access to caches and configuration. */
110 @UnsupportedAppUsage
111 private final Object mAccessLock = new Object();
112
113 // These are protected by mAccessLock.
114 private final Configuration mTmpConfig = new Configuration();
115 @UnsupportedAppUsage
116 private final DrawableCache mDrawableCache = new DrawableCache();
117 @UnsupportedAppUsage
118 private final DrawableCache mColorDrawableCache = new DrawableCache();
119 private final ConfigurationBoundResourceCache<ComplexColor> mComplexColorCache =
120 new ConfigurationBoundResourceCache<>();
121 @UnsupportedAppUsage
122 private final ConfigurationBoundResourceCache<Animator> mAnimatorCache =
123 new ConfigurationBoundResourceCache<>();
124 @UnsupportedAppUsage
125 private final ConfigurationBoundResourceCache<StateListAnimator> mStateListAnimatorCache =
126 new ConfigurationBoundResourceCache<>();
127
128 // A stack of all the resourceIds already referenced when parsing a resource. This is used to
129 // detect circular references in the xml.
130 // Using a ThreadLocal variable ensures that we have different stacks for multiple parallel
131 // calls to ResourcesImpl
132 private final ThreadLocal<LookupStack> mLookupStack =
133 ThreadLocal.withInitial(() -> new LookupStack());
134
135 /** Size of the cyclical cache used to map XML files to blocks. */
136 private static final int XML_BLOCK_CACHE_SIZE = 4;
137
138 // Cyclical cache used for recently-accessed XML files.
139 private int mLastCachedXmlBlockIndex = -1;
140 private final int[] mCachedXmlBlockCookies = new int[XML_BLOCK_CACHE_SIZE];
141 private final String[] mCachedXmlBlockFiles = new String[XML_BLOCK_CACHE_SIZE];
142 private final XmlBlock[] mCachedXmlBlocks = new XmlBlock[XML_BLOCK_CACHE_SIZE];
143
144
145 @UnsupportedAppUsage
146 final AssetManager mAssets;
147 private final DisplayMetrics mMetrics = new DisplayMetrics();
148 private final DisplayAdjustments mDisplayAdjustments;
149
150 private PluralRules mPluralRule;
151
152 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
153 private final Configuration mConfiguration = new Configuration();
154
155 static {
156 sPreloadedDrawables = new LongSparseArray[2];
157 sPreloadedDrawables[0] = new LongSparseArray<>();
158 sPreloadedDrawables[1] = new LongSparseArray<>();
159 }
160
161 /**
162 * Creates a new ResourcesImpl object with CompatibilityInfo.
163 *
164 * @param assets Previously created AssetManager.
165 * @param metrics Current display metrics to consider when
166 * selecting/computing resource values.
167 * @param config Desired device configuration to consider when
168 * selecting/computing resource values (optional).
169 * @param displayAdjustments this resource's Display override and compatibility info.
170 * Must not be null.
171 */
172 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
173 public ResourcesImpl(@NonNull AssetManager assets, @Nullable DisplayMetrics metrics,
174 @Nullable Configuration config, @NonNull DisplayAdjustments displayAdjustments) {
175 mAssets = assets;
176 mMetrics.setToDefaults();
177 mDisplayAdjustments = displayAdjustments;
178 mConfiguration.setToDefaults();
179 updateConfiguration(config, metrics, displayAdjustments.getCompatibilityInfo());
180 }
181
182 public DisplayAdjustments getDisplayAdjustments() {
183 return mDisplayAdjustments;
184 }
185
186 @UnsupportedAppUsage
187 public AssetManager getAssets() {
188 return mAssets;
189 }
190
191 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
192 DisplayMetrics getDisplayMetrics() {
193 if (DEBUG_CONFIG) Slog.v(TAG, "Returning DisplayMetrics: " + mMetrics.widthPixels
194 + "x" + mMetrics.heightPixels + " " + mMetrics.density);
195 return mMetrics;
196 }
197
198 Configuration getConfiguration() {
199 return mConfiguration;
200 }
201
202 Configuration[] getSizeConfigurations() {
203 return mAssets.getSizeConfigurations();
204 }
205
206 CompatibilityInfo getCompatibilityInfo() {
207 return mDisplayAdjustments.getCompatibilityInfo();
208 }
209
210 private PluralRules getPluralRule() {
211 synchronized (sSync) {
212 if (mPluralRule == null) {
213 mPluralRule = PluralRules.forLocale(mConfiguration.getLocales().get(0));
214 }
215 return mPluralRule;
216 }
217 }
218
219 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
220 void getValue(@AnyRes int id, TypedValue outValue, boolean resolveRefs)
221 throws NotFoundException {
222 boolean found = mAssets.getResourceValue(id, 0, outValue, resolveRefs);
223 if (found) {
224 return;
225 }
226 throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id));
227 }
228
229 void getValueForDensity(@AnyRes int id, int density, TypedValue outValue,
230 boolean resolveRefs) throws NotFoundException {
231 boolean found = mAssets.getResourceValue(id, density, outValue, resolveRefs);
232 if (found) {
233 return;
234 }
235 throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id));
236 }
237
238 void getValue(String name, TypedValue outValue, boolean resolveRefs)
239 throws NotFoundException {
240 int id = getIdentifier(name, "string", null);
241 if (id != 0) {
242 getValue(id, outValue, resolveRefs);
243 return;
244 }
245 throw new NotFoundException("String resource name " + name);
246 }
247
248 int getIdentifier(String name, String defType, String defPackage) {
249 if (name == null) {
250 throw new NullPointerException("name is null");
251 }
252 try {
253 return Integer.parseInt(name);
254 } catch (Exception e) {
255 // Ignore
256 }
257 return mAssets.getResourceIdentifier(name, defType, defPackage);
258 }
259
260 @NonNull
261 String getResourceName(@AnyRes int resid) throws NotFoundException {
262 String str = mAssets.getResourceName(resid);
263 if (str != null) return str;
264 throw new NotFoundException("Unable to find resource ID #0x"
265 + Integer.toHexString(resid));
266 }
267
268 @NonNull
269 String getResourcePackageName(@AnyRes int resid) throws NotFoundException {
270 String str = mAssets.getResourcePackageName(resid);
271 if (str != null) return str;
272 throw new NotFoundException("Unable to find resource ID #0x"
273 + Integer.toHexString(resid));
274 }
275
276 @NonNull
277 String getResourceTypeName(@AnyRes int resid) throws NotFoundException {
278 String str = mAssets.getResourceTypeName(resid);
279 if (str != null) return str;
280 throw new NotFoundException("Unable to find resource ID #0x"
281 + Integer.toHexString(resid));
282 }
283
284 @NonNull
285 String getResourceEntryName(@AnyRes int resid) throws NotFoundException {
286 String str = mAssets.getResourceEntryName(resid);
287 if (str != null) return str;
288 throw new NotFoundException("Unable to find resource ID #0x"
289 + Integer.toHexString(resid));
290 }
291
292 @NonNull
293 String getLastResourceResolution() throws NotFoundException {
294 String str = mAssets.getLastResourceResolution();
295 if (str != null) return str;
296 throw new NotFoundException("Associated AssetManager hasn't resolved a resource");
297 }
298
299 @NonNull
300 CharSequence getQuantityText(@PluralsRes int id, int quantity) throws NotFoundException {
301 PluralRules rule = getPluralRule();
302 CharSequence res = mAssets.getResourceBagText(id,
303 attrForQuantityCode(rule.select(quantity)));
304 if (res != null) {
305 return res;
306 }
307 res = mAssets.getResourceBagText(id, ID_OTHER);
308 if (res != null) {
309 return res;
310 }
311 throw new NotFoundException("Plural resource ID #0x" + Integer.toHexString(id)
312 + " quantity=" + quantity
313 + " item=" + rule.select(quantity));
314 }
315
316 private static int attrForQuantityCode(String quantityCode) {
317 switch (quantityCode) {
318 case PluralRules.KEYWORD_ZERO: return 0x01000005;
319 case PluralRules.KEYWORD_ONE: return 0x01000006;
320 case PluralRules.KEYWORD_TWO: return 0x01000007;
321 case PluralRules.KEYWORD_FEW: return 0x01000008;
322 case PluralRules.KEYWORD_MANY: return 0x01000009;
323 default: return ID_OTHER;
324 }
325 }
326
327 @NonNull
328 AssetFileDescriptor openRawResourceFd(@RawRes int id, TypedValue tempValue)
329 throws NotFoundException {
330 getValue(id, tempValue, true);
331 try {
332 return mAssets.openNonAssetFd(tempValue.assetCookie, tempValue.string.toString());
333 } catch (Exception e) {
334 throw new NotFoundException("File " + tempValue.string.toString() + " from "
335 + "resource ID #0x" + Integer.toHexString(id), e);
336 }
337 }
338
339 @NonNull
340 InputStream openRawResource(@RawRes int id, TypedValue value) throws NotFoundException {
341 getValue(id, value, true);
342 try {
343 return mAssets.openNonAsset(value.assetCookie, value.string.toString(),
344 AssetManager.ACCESS_STREAMING);
345 } catch (Exception e) {
346 // Note: value.string might be null
347 NotFoundException rnf = new NotFoundException("File "
348 + (value.string == null ? "(null)" : value.string.toString())
349 + " from resource ID #0x" + Integer.toHexString(id));
350 rnf.initCause(e);
351 throw rnf;
352 }
353 }
354
355 ConfigurationBoundResourceCache<Animator> getAnimatorCache() {
356 return mAnimatorCache;
357 }
358
359 ConfigurationBoundResourceCache<StateListAnimator> getStateListAnimatorCache() {
360 return mStateListAnimatorCache;
361 }
362
363 public void updateConfiguration(Configuration config, DisplayMetrics metrics,
364 CompatibilityInfo compat) {
365 Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, "ResourcesImpl#updateConfiguration");
366 try {
367 synchronized (mAccessLock) {
368 if (DEBUG_CONFIG) {
369 Slog.i(TAG, "**** Updating config of " + this + ": old config is "
370 + mConfiguration + " old compat is "
371 + mDisplayAdjustments.getCompatibilityInfo());
372 Slog.i(TAG, "**** Updating config of " + this + ": new config is "
373 + config + " new compat is " + compat);
374 }
375 if (compat != null) {
376 mDisplayAdjustments.setCompatibilityInfo(compat);
377 }
378 if (metrics != null) {
379 mMetrics.setTo(metrics);
380 }
381 // NOTE: We should re-arrange this code to create a Display
382 // with the CompatibilityInfo that is used everywhere we deal
383 // with the display in relation to this app, rather than
384 // doing the conversion here. This impl should be okay because
385 // we make sure to return a compatible display in the places
386 // where there are public APIs to retrieve the display... but
387 // it would be cleaner and more maintainable to just be
388 // consistently dealing with a compatible display everywhere in
389 // the framework.
390 mDisplayAdjustments.getCompatibilityInfo().applyToDisplayMetrics(mMetrics);
391
392 final @Config int configChanges = calcConfigChanges(config);
393
394 // If even after the update there are no Locales set, grab the default locales.
395 LocaleList locales = mConfiguration.getLocales();
396 if (locales.isEmpty()) {
397 locales = LocaleList.getDefault();
398 mConfiguration.setLocales(locales);
399 }
400
401 if ((configChanges & ActivityInfo.CONFIG_LOCALE) != 0) {
402 if (locales.size() > 1) {
403 // The LocaleList has changed. We must query the AssetManager's available
404 // Locales and figure out the best matching Locale in the new LocaleList.
405 String[] availableLocales = mAssets.getNonSystemLocales();
406 if (LocaleList.isPseudoLocalesOnly(availableLocales)) {
407 // No app defined locales, so grab the system locales.
408 availableLocales = mAssets.getLocales();
409 if (LocaleList.isPseudoLocalesOnly(availableLocales)) {
410 availableLocales = null;
411 }
412 }
413
414 if (availableLocales != null) {
415 final Locale bestLocale = locales.getFirstMatchWithEnglishSupported(
416 availableLocales);
417 if (bestLocale != null && bestLocale != locales.get(0)) {
418 mConfiguration.setLocales(new LocaleList(bestLocale, locales));
419 }
420 }
421 }
422 }
423
424 if (mConfiguration.densityDpi != Configuration.DENSITY_DPI_UNDEFINED) {
425 mMetrics.densityDpi = mConfiguration.densityDpi;
426 mMetrics.density =
427 mConfiguration.densityDpi * DisplayMetrics.DENSITY_DEFAULT_SCALE;
428 }
429
430 // Protect against an unset fontScale.
431 mMetrics.scaledDensity = mMetrics.density *
432 (mConfiguration.fontScale != 0 ? mConfiguration.fontScale : 1.0f);
433
434 final int width, height;
435 if (mMetrics.widthPixels >= mMetrics.heightPixels) {
436 width = mMetrics.widthPixels;
437 height = mMetrics.heightPixels;
438 } else {
439 //noinspection SuspiciousNameCombination
440 width = mMetrics.heightPixels;
441 //noinspection SuspiciousNameCombination
442 height = mMetrics.widthPixels;
443 }
444
445 final int keyboardHidden;
446 if (mConfiguration.keyboardHidden == Configuration.KEYBOARDHIDDEN_NO
447 && mConfiguration.hardKeyboardHidden
448 == Configuration.HARDKEYBOARDHIDDEN_YES) {
449 keyboardHidden = Configuration.KEYBOARDHIDDEN_SOFT;
450 } else {
451 keyboardHidden = mConfiguration.keyboardHidden;
452 }
453
454 mAssets.setConfiguration(mConfiguration.mcc, mConfiguration.mnc,
455 adjustLanguageTag(mConfiguration.getLocales().get(0).toLanguageTag()),
456 mConfiguration.orientation,
457 mConfiguration.touchscreen,
458 mConfiguration.densityDpi, mConfiguration.keyboard,
459 keyboardHidden, mConfiguration.navigation, width, height,
460 mConfiguration.smallestScreenWidthDp,
461 mConfiguration.screenWidthDp, mConfiguration.screenHeightDp,
462 mConfiguration.screenLayout, mConfiguration.uiMode,
463 mConfiguration.colorMode, Build.VERSION.RESOURCES_SDK_INT);
464
465 if (DEBUG_CONFIG) {
466 Slog.i(TAG, "**** Updating config of " + this + ": final config is "
467 + mConfiguration + " final compat is "
468 + mDisplayAdjustments.getCompatibilityInfo());
469 }
470
471 mDrawableCache.onConfigurationChange(configChanges);
472 mColorDrawableCache.onConfigurationChange(configChanges);
473 mComplexColorCache.onConfigurationChange(configChanges);
474 mAnimatorCache.onConfigurationChange(configChanges);
475 mStateListAnimatorCache.onConfigurationChange(configChanges);
476
477 flushLayoutCache();
478 }
479 synchronized (sSync) {
480 if (mPluralRule != null) {
481 mPluralRule = PluralRules.forLocale(mConfiguration.getLocales().get(0));
482 }
483 }
484 } finally {
485 Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
486 }
487 }
488
489 /**
490 * Applies the new configuration, returning a bitmask of the changes
491 * between the old and new configurations.
492 *
493 * @param config the new configuration
494 * @return bitmask of config changes
495 */
496 public @Config int calcConfigChanges(@Nullable Configuration config) {
497 if (config == null) {
498 // If there is no configuration, assume all flags have changed.
499 return 0xFFFFFFFF;
500 }
501
502 mTmpConfig.setTo(config);
503 int density = config.densityDpi;
504 if (density == Configuration.DENSITY_DPI_UNDEFINED) {
505 density = mMetrics.noncompatDensityDpi;
506 }
507
508 mDisplayAdjustments.getCompatibilityInfo().applyToConfiguration(density, mTmpConfig);
509
510 if (mTmpConfig.getLocales().isEmpty()) {
511 mTmpConfig.setLocales(LocaleList.getDefault());
512 }
513 return mConfiguration.updateFrom(mTmpConfig);
514 }
515
516 /**
517 * {@code Locale.toLanguageTag} will transform the obsolete (and deprecated)
518 * language codes "in", "ji" and "iw" to "id", "yi" and "he" respectively.
519 *
520 * All released versions of android prior to "L" used the deprecated language
521 * tags, so we will need to support them for backwards compatibility.
522 *
523 * Note that this conversion needs to take place *after* the call to
524 * {@code toLanguageTag} because that will convert all the deprecated codes to
525 * the new ones, even if they're set manually.
526 */
527 private static String adjustLanguageTag(String languageTag) {
528 final int separator = languageTag.indexOf('-');
529 final String language;
530 final String remainder;
531
532 if (separator == -1) {
533 language = languageTag;
534 remainder = "";
535 } else {
536 language = languageTag.substring(0, separator);
537 remainder = languageTag.substring(separator);
538 }
539
540 // No need to convert to lower cases because the language in the return value of
541 // Locale.toLanguageTag has been lower-cased.
542 final String adjustedLanguage;
543 switch(language) {
544 case "id":
545 adjustedLanguage = "in";
546 break;
547 case "yi":
548 adjustedLanguage = "ji";
549 break;
550 case "he":
551 adjustedLanguage = "iw";
552 break;
553 default:
554 adjustedLanguage = language;
555 break;
556 }
557 return adjustedLanguage + remainder;
558 }
559
560 /**
561 * Call this to remove all cached loaded layout resources from the
562 * Resources object. Only intended for use with performance testing
563 * tools.
564 */
565 public void flushLayoutCache() {
566 synchronized (mCachedXmlBlocks) {
567 Arrays.fill(mCachedXmlBlockCookies, 0);
568 Arrays.fill(mCachedXmlBlockFiles, null);
569
570 final XmlBlock[] cachedXmlBlocks = mCachedXmlBlocks;
571 for (int i = 0; i < XML_BLOCK_CACHE_SIZE; i++) {
572 final XmlBlock oldBlock = cachedXmlBlocks[i];
573 if (oldBlock != null) {
574 oldBlock.close();
575 }
576 }
577 Arrays.fill(cachedXmlBlocks, null);
578 }
579 }
580
581 /**
582 * Wipe all caches that might be read and return an outdated object when resolving a resource.
583 */
584 public void clearAllCaches() {
585 synchronized (mAccessLock) {
586 mDrawableCache.clear();
587 mColorDrawableCache.clear();
588 mComplexColorCache.clear();
589 mAnimatorCache.clear();
590 mStateListAnimatorCache.clear();
591 flushLayoutCache();
592 }
593 }
594
595 @Nullable
596 Drawable loadDrawable(@NonNull Resources wrapper, @NonNull TypedValue value, int id,
597 int density, @Nullable Resources.Theme theme)
598 throws NotFoundException {
599 // If the drawable's XML lives in our current density qualifier,
600 // it's okay to use a scaled version from the cache. Otherwise, we
601 // need to actually load the drawable from XML.
602 final boolean useCache = density == 0 || value.density == mMetrics.densityDpi;
603
604 // Pretend the requested density is actually the display density. If
605 // the drawable returned is not the requested density, then force it
606 // to be scaled later by dividing its density by the ratio of
607 // requested density to actual device density. Drawables that have
608 // undefined density or no density don't need to be handled here.
609 if (density > 0 && value.density > 0 && value.density != TypedValue.DENSITY_NONE) {
610 if (value.density == density) {
611 value.density = mMetrics.densityDpi;
612 } else {
613 value.density = (value.density * mMetrics.densityDpi) / density;
614 }
615 }
616
617 try {
618 if (TRACE_FOR_PRELOAD) {
619 // Log only framework resources
620 if ((id >>> 24) == 0x1) {
621 final String name = getResourceName(id);
622 if (name != null) {
623 Log.d("PreloadDrawable", name);
624 }
625 }
626 }
627
628 final boolean isColorDrawable;
629 final DrawableCache caches;
630 final long key;
631 if (value.type >= TypedValue.TYPE_FIRST_COLOR_INT
632 && value.type <= TypedValue.TYPE_LAST_COLOR_INT) {
633 isColorDrawable = true;
634 caches = mColorDrawableCache;
635 key = value.data;
636 } else {
637 isColorDrawable = false;
638 caches = mDrawableCache;
639 key = (((long) value.assetCookie) << 32) | value.data;
640 }
641
642 // First, check whether we have a cached version of this drawable
643 // that was inflated against the specified theme. Skip the cache if
644 // we're currently preloading or we're not using the cache.
645 if (!mPreloading && useCache) {
646 final Drawable cachedDrawable = caches.getInstance(key, wrapper, theme);
647 if (cachedDrawable != null) {
648 cachedDrawable.setChangingConfigurations(value.changingConfigurations);
649 return cachedDrawable;
650 }
651 }
652
653 // Next, check preloaded drawables. Preloaded drawables may contain
654 // unresolved theme attributes.
655 final Drawable.ConstantState cs;
656 if (isColorDrawable) {
657 cs = sPreloadedColorDrawables.get(key);
658 } else {
659 cs = sPreloadedDrawables[mConfiguration.getLayoutDirection()].get(key);
660 }
661
662 Drawable dr;
663 boolean needsNewDrawableAfterCache = false;
664 if (cs != null) {
665 dr = cs.newDrawable(wrapper);
666 } else if (isColorDrawable) {
667 dr = new ColorDrawable(value.data);
668 } else {
669 dr = loadDrawableForCookie(wrapper, value, id, density);
670 }
671 // DrawableContainer' constant state has drawables instances. In order to leave the
672 // constant state intact in the cache, we need to create a new DrawableContainer after
673 // added to cache.
674 if (dr instanceof DrawableContainer) {
675 needsNewDrawableAfterCache = true;
676 }
677
678 // Determine if the drawable has unresolved theme attributes. If it
679 // does, we'll need to apply a theme and store it in a theme-specific
680 // cache.
681 final boolean canApplyTheme = dr != null && dr.canApplyTheme();
682 if (canApplyTheme && theme != null) {
683 dr = dr.mutate();
684 dr.applyTheme(theme);
685 dr.clearMutated();
686 }
687
688 // If we were able to obtain a drawable, store it in the appropriate
689 // cache: preload, not themed, null theme, or theme-specific. Don't
690 // pollute the cache with drawables loaded from a foreign density.
691 if (dr != null) {
692 dr.setChangingConfigurations(value.changingConfigurations);
693 if (useCache) {
694 cacheDrawable(value, isColorDrawable, caches, theme, canApplyTheme, key, dr);
695 if (needsNewDrawableAfterCache) {
696 Drawable.ConstantState state = dr.getConstantState();
697 if (state != null) {
698 dr = state.newDrawable(wrapper);
699 }
700 }
701 }
702 }
703
704 return dr;
705 } catch (Exception e) {
706 String name;
707 try {
708 name = getResourceName(id);
709 } catch (NotFoundException e2) {
710 name = "(missing name)";
711 }
712
713 // The target drawable might fail to load for any number of
714 // reasons, but we always want to include the resource name.
715 // Since the client already expects this method to throw a
716 // NotFoundException, just throw one of those.
717 final NotFoundException nfe = new NotFoundException("Drawable " + name
718 + " with resource ID #0x" + Integer.toHexString(id), e);
719 nfe.setStackTrace(new StackTraceElement[0]);
720 throw nfe;
721 }
722 }
723
724 private void cacheDrawable(TypedValue value, boolean isColorDrawable, DrawableCache caches,
725 Resources.Theme theme, boolean usesTheme, long key, Drawable dr) {
726 final Drawable.ConstantState cs = dr.getConstantState();
727 if (cs == null) {
728 return;
729 }
730
731 if (mPreloading) {
732 final int changingConfigs = cs.getChangingConfigurations();
733 if (isColorDrawable) {
734 if (verifyPreloadConfig(changingConfigs, 0, value.resourceId, "drawable")) {
735 sPreloadedColorDrawables.put(key, cs);
736 }
737 } else {
738 if (verifyPreloadConfig(
739 changingConfigs, ActivityInfo.CONFIG_LAYOUT_DIRECTION, value.resourceId, "drawable")) {
740 if ((changingConfigs & ActivityInfo.CONFIG_LAYOUT_DIRECTION) == 0) {
741 // If this resource does not vary based on layout direction,
742 // we can put it in all of the preload maps.
743 sPreloadedDrawables[0].put(key, cs);
744 sPreloadedDrawables[1].put(key, cs);
745 } else {
746 // Otherwise, only in the layout dir we loaded it for.
747 sPreloadedDrawables[mConfiguration.getLayoutDirection()].put(key, cs);
748 }
749 }
750 }
751 } else {
752 synchronized (mAccessLock) {
753 caches.put(key, theme, cs, usesTheme);
754 }
755 }
756 }
757
758 private boolean verifyPreloadConfig(@Config int changingConfigurations,
759 @Config int allowVarying, @AnyRes int resourceId, @Nullable String name) {
760 // We allow preloading of resources even if they vary by font scale (which
761 // doesn't impact resource selection) or density (which we handle specially by
762 // simply turning off all preloading), as well as any other configs specified
763 // by the caller.
764 if (((changingConfigurations&~(ActivityInfo.CONFIG_FONT_SCALE |
765 ActivityInfo.CONFIG_DENSITY)) & ~allowVarying) != 0) {
766 String resName;
767 try {
768 resName = getResourceName(resourceId);
769 } catch (NotFoundException e) {
770 resName = "?";
771 }
772 // This should never happen in production, so we should log a
773 // warning even if we're not debugging.
774 Log.w(TAG, "Preloaded " + name + " resource #0x"
775 + Integer.toHexString(resourceId)
776 + " (" + resName + ") that varies with configuration!!");
777 return false;
778 }
779 if (TRACE_FOR_PRELOAD) {
780 String resName;
781 try {
782 resName = getResourceName(resourceId);
783 } catch (NotFoundException e) {
784 resName = "?";
785 }
786 Log.w(TAG, "Preloading " + name + " resource #0x"
787 + Integer.toHexString(resourceId)
788 + " (" + resName + ")");
789 }
790 return true;
791 }
792
793 /**
794 * Loads a Drawable from an encoded image stream, or null.
795 *
796 * This call will handle closing ais.
797 */
798 @Nullable
799 private Drawable decodeImageDrawable(@NonNull AssetInputStream ais,
800 @NonNull Resources wrapper, @NonNull TypedValue value) {
801 ImageDecoder.Source src = new ImageDecoder.AssetInputStreamSource(ais,
802 wrapper, value);
803 try {
804 return ImageDecoder.decodeDrawable(src, (decoder, info, s) -> {
805 decoder.setAllocator(ImageDecoder.ALLOCATOR_SOFTWARE);
806 });
807 } catch (IOException ioe) {
808 // This is okay. This may be something that ImageDecoder does not
809 // support, like SVG.
810 return null;
811 }
812 }
813
814 /**
815 * Loads a drawable from XML or resources stream.
816 *
817 * @return Drawable, or null if Drawable cannot be decoded.
818 */
819 @Nullable
820 private Drawable loadDrawableForCookie(@NonNull Resources wrapper, @NonNull TypedValue value,
821 int id, int density) {
822 if (value.string == null) {
823 throw new NotFoundException("Resource \"" + getResourceName(id) + "\" ("
824 + Integer.toHexString(id) + ") is not a Drawable (color or path): " + value);
825 }
826
827 final String file = value.string.toString();
828
829 if (TRACE_FOR_MISS_PRELOAD) {
830 // Log only framework resources
831 if ((id >>> 24) == 0x1) {
832 final String name = getResourceName(id);
833 if (name != null) {
834 Log.d(TAG, "Loading framework drawable #" + Integer.toHexString(id)
835 + ": " + name + " at " + file);
836 }
837 }
838 }
839
840 if (DEBUG_LOAD) {
841 Log.v(TAG, "Loading drawable for cookie " + value.assetCookie + ": " + file);
842 }
843
844
845 final Drawable dr;
846
847 Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, file);
848 LookupStack stack = mLookupStack.get();
849 try {
850 // Perform a linear search to check if we have already referenced this resource before.
851 if (stack.contains(id)) {
852 throw new Exception("Recursive reference in drawable");
853 }
854 stack.push(id);
855 try {
856 if (file.endsWith(".xml")) {
857 final String typeName = getResourceTypeName(id);
858 if (typeName != null && typeName.equals("color")) {
859 dr = loadColorOrXmlDrawable(wrapper, value, id, density, file);
860 } else {
861 dr = loadXmlDrawable(wrapper, value, id, density, file);
862 }
863 } else {
864 final InputStream is = mAssets.openNonAsset(
865 value.assetCookie, file, AssetManager.ACCESS_STREAMING);
866 final AssetInputStream ais = (AssetInputStream) is;
867 dr = decodeImageDrawable(ais, wrapper, value);
868 }
869 } finally {
870 stack.pop();
871 }
872 } catch (Exception | StackOverflowError e) {
873 Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
874 final NotFoundException rnf = new NotFoundException(
875 "File " + file + " from drawable resource ID #0x" + Integer.toHexString(id));
876 rnf.initCause(e);
877 throw rnf;
878 }
879 Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
880
881 return dr;
882 }
883
884 private Drawable loadColorOrXmlDrawable(@NonNull Resources wrapper, @NonNull TypedValue value,
885 int id, int density, String file) {
886 try {
887 ColorStateList csl = loadColorStateList(wrapper, value, id, null);
888 return new ColorStateListDrawable(csl);
889 } catch (NotFoundException originalException) {
890 // If we fail to load as color, try as normal XML drawable
891 try {
892 return loadXmlDrawable(wrapper, value, id, density, file);
893 } catch (Exception ignored) {
894 // If fallback also fails, throw the original exception
895 throw originalException;
896 }
897 }
898 }
899
900 private Drawable loadXmlDrawable(@NonNull Resources wrapper, @NonNull TypedValue value,
901 int id, int density, String file)
902 throws IOException, XmlPullParserException {
903 try (
904 XmlResourceParser rp =
905 loadXmlResourceParser(file, id, value.assetCookie, "drawable")
906 ) {
907 return Drawable.createFromXmlForDensity(wrapper, rp, density, null);
908 }
909 }
910
911 /**
912 * Loads a font from XML or resources stream.
913 */
914 @Nullable
915 public Typeface loadFont(Resources wrapper, TypedValue value, int id) {
916 if (value.string == null) {
917 throw new NotFoundException("Resource \"" + getResourceName(id) + "\" ("
918 + Integer.toHexString(id) + ") is not a Font: " + value);
919 }
920
921 final String file = value.string.toString();
922 if (!file.startsWith("res/")) {
923 return null;
924 }
925
926 Typeface cached = Typeface.findFromCache(mAssets, file);
927 if (cached != null) {
928 return cached;
929 }
930
931 if (DEBUG_LOAD) {
932 Log.v(TAG, "Loading font for cookie " + value.assetCookie + ": " + file);
933 }
934
935 Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, file);
936 try {
937 if (file.endsWith("xml")) {
938 final XmlResourceParser rp = loadXmlResourceParser(
939 file, id, value.assetCookie, "font");
940 final FontResourcesParser.FamilyResourceEntry familyEntry =
941 FontResourcesParser.parse(rp, wrapper);
942 if (familyEntry == null) {
943 return null;
944 }
945 return Typeface.createFromResources(familyEntry, mAssets, file);
946 }
947 return new Typeface.Builder(mAssets, file, false /* isAsset */, value.assetCookie)
948 .build();
949 } catch (XmlPullParserException e) {
950 Log.e(TAG, "Failed to parse xml resource " + file, e);
951 } catch (IOException e) {
952 Log.e(TAG, "Failed to read xml resource " + file, e);
953 } finally {
954 Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
955 }
956 return null;
957 }
958
959 /**
960 * Given the value and id, we can get the XML filename as in value.data, based on that, we
961 * first try to load CSL from the cache. If not found, try to get from the constant state.
962 * Last, parse the XML and generate the CSL.
963 */
964 @Nullable
965 private ComplexColor loadComplexColorFromName(Resources wrapper, Resources.Theme theme,
966 TypedValue value, int id) {
967 final long key = (((long) value.assetCookie) << 32) | value.data;
968 final ConfigurationBoundResourceCache<ComplexColor> cache = mComplexColorCache;
969 ComplexColor complexColor = cache.getInstance(key, wrapper, theme);
970 if (complexColor != null) {
971 return complexColor;
972 }
973
974 final android.content.res.ConstantState<ComplexColor> factory =
975 sPreloadedComplexColors.get(key);
976
977 if (factory != null) {
978 complexColor = factory.newInstance(wrapper, theme);
979 }
980 if (complexColor == null) {
981 complexColor = loadComplexColorForCookie(wrapper, value, id, theme);
982 }
983
984 if (complexColor != null) {
985 complexColor.setBaseChangingConfigurations(value.changingConfigurations);
986
987 if (mPreloading) {
988 if (verifyPreloadConfig(complexColor.getChangingConfigurations(),
989 0, value.resourceId, "color")) {
990 sPreloadedComplexColors.put(key, complexColor.getConstantState());
991 }
992 } else {
993 cache.put(key, theme, complexColor.getConstantState());
994 }
995 }
996 return complexColor;
997 }
998
999 @Nullable
1000 ComplexColor loadComplexColor(Resources wrapper, @NonNull TypedValue value, int id,
1001 Resources.Theme theme) {
1002 if (TRACE_FOR_PRELOAD) {
1003 // Log only framework resources
1004 if ((id >>> 24) == 0x1) {
1005 final String name = getResourceName(id);
1006 if (name != null) android.util.Log.d("loadComplexColor", name);
1007 }
1008 }
1009
1010 final long key = (((long) value.assetCookie) << 32) | value.data;
1011
1012 // Handle inline color definitions.
1013 if (value.type >= TypedValue.TYPE_FIRST_COLOR_INT
1014 && value.type <= TypedValue.TYPE_LAST_COLOR_INT) {
1015 return getColorStateListFromInt(value, key);
1016 }
1017
1018 final String file = value.string.toString();
1019
1020 ComplexColor complexColor;
1021 if (file.endsWith(".xml")) {
1022 try {
1023 complexColor = loadComplexColorFromName(wrapper, theme, value, id);
1024 } catch (Exception e) {
1025 final NotFoundException rnf = new NotFoundException(
1026 "File " + file + " from complex color resource ID #0x"
1027 + Integer.toHexString(id));
1028 rnf.initCause(e);
1029 throw rnf;
1030 }
1031 } else {
1032 throw new NotFoundException(
1033 "File " + file + " from drawable resource ID #0x"
1034 + Integer.toHexString(id) + ": .xml extension required");
1035 }
1036
1037 return complexColor;
1038 }
1039
1040 @NonNull
1041 ColorStateList loadColorStateList(Resources wrapper, TypedValue value, int id,
1042 Resources.Theme theme)
1043 throws NotFoundException {
1044 if (TRACE_FOR_PRELOAD) {
1045 // Log only framework resources
1046 if ((id >>> 24) == 0x1) {
1047 final String name = getResourceName(id);
1048 if (name != null) android.util.Log.d("PreloadColorStateList", name);
1049 }
1050 }
1051
1052 final long key = (((long) value.assetCookie) << 32) | value.data;
1053
1054 // Handle inline color definitions.
1055 if (value.type >= TypedValue.TYPE_FIRST_COLOR_INT
1056 && value.type <= TypedValue.TYPE_LAST_COLOR_INT) {
1057 return getColorStateListFromInt(value, key);
1058 }
1059
1060 ComplexColor complexColor = loadComplexColorFromName(wrapper, theme, value, id);
1061 if (complexColor != null && complexColor instanceof ColorStateList) {
1062 return (ColorStateList) complexColor;
1063 }
1064
1065 throw new NotFoundException(
1066 "Can't find ColorStateList from drawable resource ID #0x"
1067 + Integer.toHexString(id));
1068 }
1069
1070 @NonNull
1071 private ColorStateList getColorStateListFromInt(@NonNull TypedValue value, long key) {
1072 ColorStateList csl;
1073 final android.content.res.ConstantState<ComplexColor> factory =
1074 sPreloadedComplexColors.get(key);
1075 if (factory != null) {
1076 return (ColorStateList) factory.newInstance();
1077 }
1078
1079 csl = ColorStateList.valueOf(value.data);
1080
1081 if (mPreloading) {
1082 if (verifyPreloadConfig(value.changingConfigurations, 0, value.resourceId,
1083 "color")) {
1084 sPreloadedComplexColors.put(key, csl.getConstantState());
1085 }
1086 }
1087
1088 return csl;
1089 }
1090
1091 /**
1092 * Load a ComplexColor based on the XML file content. The result can be a GradientColor or
1093 * ColorStateList. Note that pure color will be wrapped into a ColorStateList.
1094 *
1095 * We deferred the parser creation to this function b/c we need to differentiate b/t gradient
1096 * and selector tag.
1097 *
1098 * @return a ComplexColor (GradientColor or ColorStateList) based on the XML file content, or
1099 * {@code null} if the XML file is neither.
1100 */
1101 @NonNull
1102 private ComplexColor loadComplexColorForCookie(Resources wrapper, TypedValue value, int id,
1103 Resources.Theme theme) {
1104 if (value.string == null) {
1105 throw new UnsupportedOperationException(
1106 "Can't convert to ComplexColor: type=0x" + value.type);
1107 }
1108
1109 final String file = value.string.toString();
1110
1111 if (TRACE_FOR_MISS_PRELOAD) {
1112 // Log only framework resources
1113 if ((id >>> 24) == 0x1) {
1114 final String name = getResourceName(id);
1115 if (name != null) {
1116 Log.d(TAG, "Loading framework ComplexColor #" + Integer.toHexString(id)
1117 + ": " + name + " at " + file);
1118 }
1119 }
1120 }
1121
1122 if (DEBUG_LOAD) {
1123 Log.v(TAG, "Loading ComplexColor for cookie " + value.assetCookie + ": " + file);
1124 }
1125
1126 ComplexColor complexColor = null;
1127
1128 Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, file);
1129 if (file.endsWith(".xml")) {
1130 try {
1131 final XmlResourceParser parser = loadXmlResourceParser(
1132 file, id, value.assetCookie, "ComplexColor");
1133
1134 final AttributeSet attrs = Xml.asAttributeSet(parser);
1135 int type;
1136 while ((type = parser.next()) != XmlPullParser.START_TAG
1137 && type != XmlPullParser.END_DOCUMENT) {
1138 // Seek parser to start tag.
1139 }
1140 if (type != XmlPullParser.START_TAG) {
1141 throw new XmlPullParserException("No start tag found");
1142 }
1143
1144 final String name = parser.getName();
1145 if (name.equals("gradient")) {
1146 complexColor = GradientColor.createFromXmlInner(wrapper, parser, attrs, theme);
1147 } else if (name.equals("selector")) {
1148 complexColor = ColorStateList.createFromXmlInner(wrapper, parser, attrs, theme);
1149 }
1150 parser.close();
1151 } catch (Exception e) {
1152 Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
1153 final NotFoundException rnf = new NotFoundException(
1154 "File " + file + " from ComplexColor resource ID #0x"
1155 + Integer.toHexString(id));
1156 rnf.initCause(e);
1157 throw rnf;
1158 }
1159 } else {
1160 Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
1161 throw new NotFoundException(
1162 "File " + file + " from drawable resource ID #0x"
1163 + Integer.toHexString(id) + ": .xml extension required");
1164 }
1165 Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
1166
1167 return complexColor;
1168 }
1169
1170 /**
1171 * Loads an XML parser for the specified file.
1172 *
1173 * @param file the path for the XML file to parse
1174 * @param id the resource identifier for the file
1175 * @param assetCookie the asset cookie for the file
1176 * @param type the type of resource (used for logging)
1177 * @return a parser for the specified XML file
1178 * @throws NotFoundException if the file could not be loaded
1179 */
1180 @NonNull
1181 XmlResourceParser loadXmlResourceParser(@NonNull String file, @AnyRes int id, int assetCookie,
1182 @NonNull String type)
1183 throws NotFoundException {
1184 if (id != 0) {
1185 try {
1186 synchronized (mCachedXmlBlocks) {
1187 final int[] cachedXmlBlockCookies = mCachedXmlBlockCookies;
1188 final String[] cachedXmlBlockFiles = mCachedXmlBlockFiles;
1189 final XmlBlock[] cachedXmlBlocks = mCachedXmlBlocks;
1190 // First see if this block is in our cache.
1191 final int num = cachedXmlBlockFiles.length;
1192 for (int i = 0; i < num; i++) {
1193 if (cachedXmlBlockCookies[i] == assetCookie && cachedXmlBlockFiles[i] != null
1194 && cachedXmlBlockFiles[i].equals(file)) {
1195 return cachedXmlBlocks[i].newParser(id);
1196 }
1197 }
1198
1199 // Not in the cache, create a new block and put it at
1200 // the next slot in the cache.
1201 final XmlBlock block = mAssets.openXmlBlockAsset(assetCookie, file);
1202 if (block != null) {
1203 final int pos = (mLastCachedXmlBlockIndex + 1) % num;
1204 mLastCachedXmlBlockIndex = pos;
1205 final XmlBlock oldBlock = cachedXmlBlocks[pos];
1206 if (oldBlock != null) {
1207 oldBlock.close();
1208 }
1209 cachedXmlBlockCookies[pos] = assetCookie;
1210 cachedXmlBlockFiles[pos] = file;
1211 cachedXmlBlocks[pos] = block;
1212 return block.newParser(id);
1213 }
1214 }
1215 } catch (Exception e) {
1216 final NotFoundException rnf = new NotFoundException("File " + file
1217 + " from xml type " + type + " resource ID #0x" + Integer.toHexString(id));
1218 rnf.initCause(e);
1219 throw rnf;
1220 }
1221 }
1222
1223 throw new NotFoundException("File " + file + " from xml type " + type + " resource ID #0x"
1224 + Integer.toHexString(id));
1225 }
1226
1227 /**
1228 * Start preloading of resource data using this Resources object. Only
1229 * for use by the zygote process for loading common system resources.
1230 * {@hide}
1231 */
1232 public final void startPreloading() {
1233 synchronized (sSync) {
1234 if (sPreloaded) {
1235 throw new IllegalStateException("Resources already preloaded");
1236 }
1237 sPreloaded = true;
1238 mPreloading = true;
1239 mConfiguration.densityDpi = DisplayMetrics.DENSITY_DEVICE;
1240 updateConfiguration(null, null, null);
1241 }
1242 }
1243
1244 /**
1245 * Called by zygote when it is done preloading resources, to change back
1246 * to normal Resources operation.
1247 */
1248 void finishPreloading() {
1249 if (mPreloading) {
1250 mPreloading = false;
1251 flushLayoutCache();
1252 }
1253 }
1254
1255 @AnyRes
1256 static int getAttributeSetSourceResId(@Nullable AttributeSet set) {
1257 if (set == null || !(set instanceof XmlBlock.Parser)) {
1258 return ID_NULL;
1259 }
1260 return ((XmlBlock.Parser) set).getSourceResId();
1261 }
1262
1263 LongSparseArray<Drawable.ConstantState> getPreloadedDrawables() {
1264 return sPreloadedDrawables[0];
1265 }
1266
1267 ThemeImpl newThemeImpl() {
1268 return new ThemeImpl();
1269 }
1270
1271 private static final NativeAllocationRegistry sThemeRegistry =
1272 NativeAllocationRegistry.createMalloced(ResourcesImpl.class.getClassLoader(),
1273 AssetManager.getThemeFreeFunction());
1274
1275 void dump(PrintWriter pw, String prefix) {
1276 pw.println(prefix + "class=" + getClass());
1277 pw.println(prefix + "assets");
1278 mAssets.dump(pw, prefix + " ");
1279 }
1280
1281 public class ThemeImpl {
1282 /**
1283 * Unique key for the series of styles applied to this theme.
1284 */
1285 private final Resources.ThemeKey mKey = new Resources.ThemeKey();
1286
1287 @SuppressWarnings("hiding")
1288 private AssetManager mAssets;
1289 private final long mTheme;
1290
1291 /**
1292 * Resource identifier for the theme.
1293 */
1294 private int mThemeResId = 0;
1295
1296 /*package*/ ThemeImpl() {
1297 mAssets = ResourcesImpl.this.mAssets;
1298 mTheme = mAssets.createTheme();
1299 sThemeRegistry.registerNativeAllocation(this, mTheme);
1300 }
1301
1302 @Override
1303 protected void finalize() throws Throwable {
1304 super.finalize();
1305 mAssets.releaseTheme(mTheme);
1306 }
1307
1308 /*package*/ Resources.ThemeKey getKey() {
1309 return mKey;
1310 }
1311
1312 /*package*/ long getNativeTheme() {
1313 return mTheme;
1314 }
1315
1316 /*package*/ int getAppliedStyleResId() {
1317 return mThemeResId;
1318 }
1319
1320 @StyleRes
1321 /*package*/ int getParentThemeIdentifier(@StyleRes int resId) {
1322 if (resId > 0) {
1323 return mAssets.getParentThemeIdentifier(resId);
1324 }
1325 return 0;
1326 }
1327
1328 void applyStyle(int resId, boolean force) {
1329 mAssets.applyStyleToTheme(mTheme, resId, force);
1330 mThemeResId = resId;
1331 mKey.append(resId, force);
1332 }
1333
1334 void setTo(ThemeImpl other) {
1335 mAssets.setThemeTo(mTheme, other.mAssets, other.mTheme);
1336
1337 mThemeResId = other.mThemeResId;
1338 mKey.setTo(other.getKey());
1339 }
1340
1341 @NonNull
1342 TypedArray obtainStyledAttributes(@NonNull Resources.Theme wrapper,
1343 AttributeSet set,
1344 @StyleableRes int[] attrs,
1345 @AttrRes int defStyleAttr,
1346 @StyleRes int defStyleRes) {
1347 final int len = attrs.length;
1348 final TypedArray array = TypedArray.obtain(wrapper.getResources(), len);
1349
1350 // XXX note that for now we only work with compiled XML files.
1351 // To support generic XML files we will need to manually parse
1352 // out the attributes from the XML file (applying type information
1353 // contained in the resources and such).
1354 final XmlBlock.Parser parser = (XmlBlock.Parser) set;
1355 mAssets.applyStyle(mTheme, defStyleAttr, defStyleRes, parser, attrs,
1356 array.mDataAddress, array.mIndicesAddress);
1357 array.mTheme = wrapper;
1358 array.mXml = parser;
1359 return array;
1360 }
1361
1362 @NonNull
1363 TypedArray resolveAttributes(@NonNull Resources.Theme wrapper,
1364 @NonNull int[] values,
1365 @NonNull int[] attrs) {
1366 final int len = attrs.length;
1367 if (values == null || len != values.length) {
1368 throw new IllegalArgumentException(
1369 "Base attribute values must the same length as attrs");
1370 }
1371
1372 final TypedArray array = TypedArray.obtain(wrapper.getResources(), len);
1373 mAssets.resolveAttrs(mTheme, 0, 0, values, attrs, array.mData, array.mIndices);
1374 array.mTheme = wrapper;
1375 array.mXml = null;
1376 return array;
1377 }
1378
1379 boolean resolveAttribute(int resid, TypedValue outValue, boolean resolveRefs) {
1380 return mAssets.getThemeValue(mTheme, resid, outValue, resolveRefs);
1381 }
1382
1383 int[] getAllAttributes() {
1384 return mAssets.getStyleAttributes(getAppliedStyleResId());
1385 }
1386
1387 @Config int getChangingConfigurations() {
1388 final @NativeConfig int nativeChangingConfig =
1389 AssetManager.nativeThemeGetChangingConfigurations(mTheme);
1390 return ActivityInfo.activityInfoConfigNativeToJava(nativeChangingConfig);
1391 }
1392
1393 public void dump(int priority, String tag, String prefix) {
1394 mAssets.dumpTheme(mTheme, priority, tag, prefix);
1395 }
1396
1397 String[] getTheme() {
1398 final int n = mKey.mCount;
1399 final String[] themes = new String[n * 2];
1400 for (int i = 0, j = n - 1; i < themes.length; i += 2, --j) {
1401 final int resId = mKey.mResId[j];
1402 final boolean forced = mKey.mForce[j];
1403 try {
1404 themes[i] = getResourceName(resId);
1405 } catch (NotFoundException e) {
1406 themes[i] = Integer.toHexString(i);
1407 }
1408 themes[i + 1] = forced ? "forced" : "not forced";
1409 }
1410 return themes;
1411 }
1412
1413 /**
1414 * Rebases the theme against the parent Resource object's current
1415 * configuration by re-applying the styles passed to
1416 * {@link #applyStyle(int, boolean)}.
1417 */
1418 void rebase() {
1419 rebase(mAssets);
1420 }
1421
1422 /**
1423 * Rebases the theme against the {@code newAssets} by re-applying the styles passed to
1424 * {@link #applyStyle(int, boolean)}.
1425 *
1426 * The theme will use {@code newAssets} for all future invocations of
1427 * {@link #applyStyle(int, boolean)}.
1428 */
1429 void rebase(AssetManager newAssets) {
1430 mAssets = mAssets.rebaseTheme(mTheme, newAssets, mKey.mResId, mKey.mForce, mKey.mCount);
1431 }
1432
1433 /**
1434 * Returns the ordered list of resource ID that are considered when resolving attribute
1435 * values when making an equivalent call to
1436 * {@link #obtainStyledAttributes(Resources.Theme, AttributeSet, int[], int, int)}. The list
1437 * will include a set of explicit styles ({@code explicitStyleRes} and it will include the
1438 * default styles ({@code defStyleAttr} and {@code defStyleRes}).
1439 *
1440 * @param defStyleAttr An attribute in the current theme that contains a
1441 * reference to a style resource that supplies
1442 * defaults values for the TypedArray. Can be
1443 * 0 to not look for defaults.
1444 * @param defStyleRes A resource identifier of a style resource that
1445 * supplies default values for the TypedArray,
1446 * used only if defStyleAttr is 0 or can not be found
1447 * in the theme. Can be 0 to not look for defaults.
1448 * @param explicitStyleRes A resource identifier of an explicit style resource.
1449 * @return ordered list of resource ID that are considered when resolving attribute values.
1450 */
1451 @Nullable
1452 public int[] getAttributeResolutionStack(@AttrRes int defStyleAttr,
1453 @StyleRes int defStyleRes, @StyleRes int explicitStyleRes) {
1454 return mAssets.getAttributeResolutionStack(
1455 mTheme, defStyleAttr, defStyleRes, explicitStyleRes);
1456 }
1457 }
1458
1459 private static class LookupStack {
1460
1461 // Pick a reasonable default size for the array, it is grown as needed.
1462 private int[] mIds = new int[4];
1463 private int mSize = 0;
1464
1465 public void push(int id) {
1466 mIds = GrowingArrayUtils.append(mIds, mSize, id);
1467 mSize++;
1468 }
1469
1470 public boolean contains(int id) {
1471 for (int i = 0; i < mSize; i++) {
1472 if (mIds[i] == id) {
1473 return true;
1474 }
1475 }
1476 return false;
1477 }
1478
1479 public void pop() {
1480 mSize--;
1481 }
1482 }
1483 }