Skip to content

Commit 89446b2

Browse files
authored
Package HEIC and HEIF image assets as Android raw resources
## Summary: `drawableFileTypes` lists `heic` and `heif`, so the bundle command copies such an asset into a `drawable-*` folder. The Android Gradle plugin (`FileResourceNameValidator`) accepts only `.xml`, `.png`, `.9.png`, `.gif`, `.jpeg`, `.jpg`, `.bmp`, `.webp` and `.avif` files in those folders, and fails resource merging on any other file with "The file name must end with .xml or .png". A release build of an app that requires a HEIC image therefore fails. This change removes both types from `drawableFileTypes`, so these assets go to `raw`, which accepts any file. `ResourceDrawableIdHelper.getResourceDrawableUri`, which turns an image source's name into the `res:` URI that Fresco loads, now looks among the raw resources when no drawable has the name. A drawable keeps precedence. The fallback matches a raw resource by name alone, whatever its type. In an app that bundles `intro.mp3`, an `Image` whose source names `intro` used to stay blank; Fresco now fails to decode the file and the `Image` calls `onError`. `getResourceDrawableUri` is public, so other callers get the fallback too. A raw HEIC may be stored compressed in the APK: `.heic` and `.heif` are not among the extensions AAPT2 leaves uncompressed (`.jpg`, `.png`, `.webp` and others; [`Link.cpp`](https://cs.android.com/android/platform/superproject/main/+/main:frameworks/base/tools/aapt2/cmd/Link.cpp)), so AAPT2 deflates such a file when that makes it smaller. Fresco reads it either way. `LocalResourceFetchProducer` reads the bytes with `Resources.openRawResource`, which decompresses, and uses [`openRawResourceFd`](https://developer.android.com/reference/android/content/res/Resources#openRawResourceFd(int)), which works only on uncompressed data, just to learn the length: it catches the `Resources.NotFoundException` and reads the stream to its end. Decoding a HEIC also needs ExifInterface on the classpath, which #60371 added. `ResourceDrawableIdHelper` now guards its maps with one monitor, the class. On `main`, `clear()` locks the class (`@Synchronized` on a `@JvmStatic` function) and the lookup locks the object, so the two do not exclude each other. Limitations: - `getResourceDrawableId` and `getResourceDrawable` still resolve drawables only: their callers (`defaultSource` and `loadingIndicatorSource` on `Image`, `inlineImageLeft` on `TextInput`, and `ImageLoaderModule`) load the id as a drawable, and a raw resource with the same name, such as a JSON file, would throw `Resources.NotFoundException`. A HEIC image works as an image `source` but not in those props. - Density variants of a raw asset are not kept: `photo@2x.heic` and `photo@3x.heic` are both written to `raw/photo.heic`, as for other raw asset types. - `ktx` stays in the list. AGP rejects it in the same way, but nothing in the open source image pipeline decodes it. ## Changelog: [ANDROID] [FIXED] - Package HEIC and HEIF image assets as raw resources so that release builds accept them ## Test Plan: ```sh yarn jest packages/asset-utils packages/community-cli-plugin/src/commands/bundle ``` New `AndroidPathUtils-test.js` cases check that `heic` and `heif` assets go to `raw`; on `main` they fail (`Expected: "raw"`, `Received: "drawable-mdpi"`). ```sh ./gradlew :packages:react-native:ReactAndroid:testDebugUnitTest --tests com.facebook.react.views.imagehelper.ResourceDrawableIdHelperTest -Preact.internal.useHermesStable=true --console=plain ``` New tests: `uriFallsBackToRawResourceForNameWithoutADrawable` (fails on `main` with an empty URI), `uriPrefersDrawableOverRawResourceWithTheSameName`, and `drawableIdIgnoresRawResources`. The compression behavior comes from the sources and from AAPT2 9.2.1 itself: `aapt2 link` on a `res/raw` folder stores a compressible `.heic` file deflated and a `.jpg` with the same bytes uncompressed, and `javap -p -c` on `LocalResourceFetchProducer` in `imagepipeline-3.9.0` shows the calls and the exception table described above. The accepted extensions come from `javap` on `SdkUtils` and `FileResourceNameValidator` in the `common` and `sdk-common` 32.2.1 jars, which AGP 9.2.1 uses. ESLint, Prettier, `yarn flow-check` and ktfmt are clean. Not run: a release build of an app with a HEIC asset, and showing the image from a raw resource on a device. Differential Revision: D135070431 Pull Request resolved: #60372
1 parent e9b0973 commit 89446b2

4 files changed

Lines changed: 62 additions & 12 deletions

File tree

‎packages/asset-utils/src/AndroidPathUtils.js‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,10 +48,11 @@ function getAndroidAssetSuffix(scale /*: number */) /*: string */ {
4848
}
4949

5050
// See https://developer.android.com/guide/topics/resources/drawable-resource.html
51+
// HEIC and HEIF are absent because the Android Gradle plugin fails the build on
52+
// such a file in a drawable folder, so those images are packaged as raw
53+
// resources.
5154
const drawableFileTypes /*: Set<string> */ = new Set([
5255
'gif',
53-
'heic',
54-
'heif',
5556
'jpeg',
5657
'jpg',
5758
'ktx',

‎packages/asset-utils/src/__tests__/AndroidPathUtils-test.js‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,12 @@ describe('getAndroidResourceFolderName', () => {
7272
expect(getAndroidResourceFolderName(NON_DRAWABLE_ASSET, 1)).toBe('raw');
7373
expect(getAndroidResourceFolderName(NON_DRAWABLE_ASSET, 1.25)).toBe('raw');
7474
});
75+
76+
test.each(['heic', 'heif'])('returns "raw" for %s images', type => {
77+
expect(getAndroidResourceFolderName({...DRAWABLE_ASSET, type}, 1)).toBe(
78+
'raw',
79+
);
80+
});
7581
});
7682

7783
describe('getAndroidResourceIdentifier', () => {

‎packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/imagehelper/ResourceDrawableIdHelper.kt‎

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -17,15 +17,25 @@ import javax.annotation.concurrent.ThreadSafe
1717
@ThreadSafe
1818
public object ResourceDrawableIdHelper {
1919
private val resourceDrawableIdMap: MutableMap<String, Int> = HashMap()
20+
private val rawResourceIdMap: MutableMap<String, Int> = HashMap()
2021

2122
@Synchronized
2223
@JvmStatic
2324
public fun clear() {
2425
resourceDrawableIdMap.clear()
26+
rawResourceIdMap.clear()
2527
}
2628

2729
@JvmStatic
28-
public fun getResourceDrawableId(context: Context, name: String?): Int {
30+
public fun getResourceDrawableId(context: Context, name: String?): Int =
31+
getResourceId(context, name, "drawable", resourceDrawableIdMap)
32+
33+
private fun getResourceId(
34+
context: Context,
35+
name: String?,
36+
type: String,
37+
idMap: MutableMap<String, Int>,
38+
): Int {
2939
if (name.isNullOrEmpty()) {
3040
return 0
3141
}
@@ -37,17 +47,13 @@ public object ResourceDrawableIdHelper {
3747
return it
3848
}
3949

40-
synchronized(this) {
41-
return resourceDrawableIdMap.get(normalizedName) ?: addDrawableId(context, normalizedName)
50+
synchronized(ResourceDrawableIdHelper::class.java) {
51+
return idMap.getOrPut(normalizedName) {
52+
context.resources.getIdentifier(normalizedName, type, context.packageName)
53+
}
4254
}
4355
}
4456

45-
private fun addDrawableId(context: Context, normalizedName: String): Int {
46-
val newId = context.resources.getIdentifier(normalizedName, "drawable", context.packageName)
47-
resourceDrawableIdMap[normalizedName] = newId
48-
return newId
49-
}
50-
5157
@JvmStatic
5258
public fun getResourceDrawable(context: Context, name: String?): Drawable? {
5359
val resId = getResourceDrawableId(context, name)
@@ -56,7 +62,11 @@ public object ResourceDrawableIdHelper {
5662

5763
@JvmStatic
5864
public fun getResourceDrawableUri(context: Context, name: String?): Uri {
59-
val resId = getResourceDrawableId(context, name)
65+
val drawableId = getResourceDrawableId(context, name)
66+
// An image in a format that cannot be packaged as a drawable, such as HEIC, is bundled as a
67+
// raw resource.
68+
val resId =
69+
if (drawableId > 0) drawableId else getResourceId(context, name, "raw", rawResourceIdMap)
6070
return if (resId > 0) {
6171
Uri.Builder().scheme(LOCAL_RESOURCE_SCHEME).path(resId.toString()).build()
6272
} else {

‎packages/react-native/ReactAndroid/src/test/java/com/facebook/react/views/imagehelper/ResourceDrawableIdHelperTest.kt‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,23 +8,31 @@
88
package com.facebook.react.views.imagehelper
99

1010
import android.content.Context
11+
import android.content.res.Resources
12+
import android.net.Uri
1113
import org.assertj.core.api.Assertions.assertThat
1214
import org.junit.After
1315
import org.junit.Before
1416
import org.junit.Test
1517
import org.junit.runner.RunWith
18+
import org.mockito.kotlin.mock
19+
import org.mockito.kotlin.whenever
1620
import org.robolectric.RobolectricTestRunner
1721
import org.robolectric.RuntimeEnvironment
1822

1923
@RunWith(RobolectricTestRunner::class)
2024
class ResourceDrawableIdHelperTest {
2125

2226
private lateinit var context: Context
27+
private val mockContext = mock<Context>()
28+
private val resources = mock<Resources>()
2329

2430
@Before
2531
fun setUp() {
2632
context = RuntimeEnvironment.getApplication()
2733
ResourceDrawableIdHelper.clear()
34+
whenever(mockContext.resources).thenReturn(resources)
35+
whenever(mockContext.packageName).thenReturn("test.images")
2836
}
2937

3038
@After
@@ -72,4 +80,29 @@ class ResourceDrawableIdHelperTest {
7280
assertThat(ResourceDrawableIdHelper.getResourceDrawableId(context, "unknown_image"))
7381
.isEqualTo(0)
7482
}
83+
84+
@Test
85+
fun uriFallsBackToRawResourceForNameWithoutADrawable() {
86+
whenever(resources.getIdentifier("photo", "raw", "test.images")).thenReturn(42)
87+
88+
assertThat(ResourceDrawableIdHelper.getResourceDrawableUri(mockContext, "photo"))
89+
.isEqualTo(Uri.parse("res:/42"))
90+
}
91+
92+
@Test
93+
fun uriPrefersDrawableOverRawResourceWithTheSameName() {
94+
whenever(resources.getIdentifier("photo", "drawable", "test.images")).thenReturn(23)
95+
whenever(resources.getIdentifier("photo", "raw", "test.images")).thenReturn(42)
96+
97+
assertThat(ResourceDrawableIdHelper.getResourceDrawableUri(mockContext, "photo"))
98+
.isEqualTo(Uri.parse("res:/23"))
99+
}
100+
101+
@Test
102+
fun drawableIdIgnoresRawResources() {
103+
whenever(resources.getIdentifier("photo", "raw", "test.images")).thenReturn(42)
104+
105+
assertThat(ResourceDrawableIdHelper.getResourceDrawableId(mockContext, "photo")).isEqualTo(0)
106+
assertThat(ResourceDrawableIdHelper.getResourceDrawable(mockContext, "photo")).isNull()
107+
}
75108
}

0 commit comments

Comments
 (0)