Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pack all resources to assets on the android target. #4965

Merged
merged 13 commits into from
Jun 20, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions components/resources/library/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,7 @@ android {
assets.srcDir("src/androidInstrumentedTest/assets")
}
named("test") { resources.srcDir(commonTestResources) }
named("main") { manifest.srcFile("src/androidMain/AndroidManifest.xml") }
}
}

Expand Down
13 changes: 13 additions & 0 deletions components/resources/library/src/androidMain/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">

<application>
<provider
android:authorities="org.jetbrains.compose.resources.AndroidContextProvider"
terrakok marked this conversation as resolved.
Show resolved Hide resolved
android:name="org.jetbrains.compose.resources.AndroidContextProvider"
android:exported="false"
android:enabled="true">
</provider>
</application>

</manifest>
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package org.jetbrains.compose.resources

import android.annotation.SuppressLint
import android.content.ContentProvider
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.net.Uri

internal val androidContext get() = AndroidContextProvider.ANDROID_CONTEXT

//https://andretietz.com/2017/09/06/autoinitialise-android-library/
internal class AndroidContextProvider : ContentProvider() {
terrakok marked this conversation as resolved.
Show resolved Hide resolved
companion object {
@SuppressLint("StaticFieldLeak")
lateinit var ANDROID_CONTEXT: Context
private set
}

override fun onCreate(): Boolean {
ANDROID_CONTEXT = context ?: error("AndroidContextProvider context is null")
return true
}

override fun query(
uri: Uri,
projection: Array<out String>?,
selection: String?,
selectionArgs: Array<out String>?,
sortOrder: String?
): Cursor? = null
override fun getType(uri: Uri): String? = null
override fun insert(uri: Uri, values: ContentValues?): Uri? = null
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int = 0
override fun update(
uri: Uri,
values: ContentValues?,
selection: String?,
selectionArgs: Array<out String>?
): Int = 0
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,5 @@ import androidx.compose.ui.text.font.*
actual fun Font(resource: FontResource, weight: FontWeight, style: FontStyle): Font {
val environment = LocalComposeEnvironment.current.rememberEnvironment()
val path = remember(environment, resource) { resource.getResourceItemByEnvironment(environment).path }
return Font(path, LocalContext.current.assets, weight, style)
return Font(path, androidContext.assets, weight, style)
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
package org.jetbrains.compose.resources

import java.io.File
import android.content.res.AssetManager
import android.net.Uri
import java.io.IOException
import java.io.InputStream

internal actual fun getPlatformResourceReader(): ResourceReader = object : ResourceReader {
private val assets: AssetManager = androidContext.assets

override suspend fun read(path: String): ByteArray {
val resource = getResourceAsStream(path)
return resource.readBytes()
Expand Down Expand Up @@ -40,32 +44,39 @@ internal actual fun getPlatformResourceReader(): ResourceReader = object : Resou
}

override fun getUri(path: String): String {
val classLoader = getClassLoader()
val resource = classLoader.getResource(path) ?: run {
//try to find a font in the android assets
if (File(path).isFontResource()) {
classLoader.getResource("assets/$path")
} else null
} ?: throw MissingResourceException(path)
return resource.toURI().toString()
val uri = if (assets.hasFile(path)) {
Uri.parse("file:///android_asset/$path")
} else {
val classLoader = getClassLoader()
val resource = classLoader.getResource(path) ?: throw MissingResourceException(path)
resource.toURI()
}
return uri.toString()
}

private fun getResourceAsStream(path: String): InputStream {
val classLoader = getClassLoader()
val resource = classLoader.getResourceAsStream(path) ?: run {
//try to find a font in the android assets
if (File(path).isFontResource()) {
classLoader.getResourceAsStream("assets/$path")
} else null
} ?: throw MissingResourceException(path)
return resource
}

private fun File.isFontResource(): Boolean {
return this.parentFile?.name.orEmpty().startsWith("font")
return try {
assets.open(path)
} catch (e: IOException) {
terrakok marked this conversation as resolved.
Show resolved Hide resolved
val classLoader = getClassLoader()
classLoader.getResourceAsStream(path) ?: throw MissingResourceException(path)
}
}

private fun getClassLoader(): ClassLoader {
return this.javaClass.classLoader ?: error("Cannot find class loader")
}

private fun AssetManager.hasFile(path: String): Boolean {
var inputStream: InputStream? = null
val result = try {
inputStream = open(path)
true
} catch (e: IOException) {
false
} finally {
inputStream?.close()
}
return result
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,6 @@ internal fun Project.configureAndroidComposeResources(
.all { androidSourceSet ->
(compilation.allKotlinSourceSets as? ObservableSet<KotlinSourceSet>)?.forAll { kotlinSourceSet ->
val preparedComposeResources = getPreparedComposeResourcesDir(kotlinSourceSet)
androidSourceSet.resources.srcDirs(preparedComposeResources)
igordmn marked this conversation as resolved.
Show resolved Hide resolved

//fix for AGP < 8.0
//usually 'androidSourceSet.resources.srcDir(preparedCommonResources)' should be enough
compilation.androidVariant.processJavaResourcesProvider.configure {
Expand Down Expand Up @@ -69,22 +67,20 @@ internal fun Project.configureAndroidComposeResources(
}
}

val copyFonts = registerTask<CopyAndroidFontsToAssetsTask>(
"copy${variant.name.uppercaseFirstChar()}FontsToAndroidAssets"
val copyResources = registerTask<CopyResourcesToAndroidAssetsTask>(
"copy${variant.name.uppercaseFirstChar()}ResourcesToAndroidAssets"
) {
from.set(variantResources)
}
variant.sources?.assets?.addGeneratedSourceDirectory(
taskProvider = copyFonts,
wiredWith = CopyAndroidFontsToAssetsTask::outputDirectory
taskProvider = copyResources,
wiredWith = CopyResourcesToAndroidAssetsTask::outputDirectory
)
//exclude a duplication of fonts in apks
variant.packaging.resources.excludes.add("**/font*/*")
}
}

//Copy task doesn't work with 'variant.sources?.assets?.addGeneratedSourceDirectory' API
internal abstract class CopyAndroidFontsToAssetsTask : DefaultTask() {
internal abstract class CopyResourcesToAndroidAssetsTask : DefaultTask() {
@get:Inject
abstract val fileSystem: FileSystemOperations

Expand All @@ -100,7 +96,6 @@ internal abstract class CopyAndroidFontsToAssetsTask : DefaultTask() {
fileSystem.copy {
it.includeEmptyDirs = false
it.from(from)
it.include("**/font*/*")
it.into(outputDirectory)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,28 +32,26 @@ internal fun Project.configureKmpResources(
logger.info("Configure resources publication for '${target.targetName}' target")
val packedResourceDir = config.getModuleResourcesDir(project)

kmpResources.publishResourcesAsKotlinComponent(
target,
{ sourceSet ->
KotlinTargetResourcesPublication.ResourceRoot(
getPreparedComposeResourcesDir(sourceSet),
emptyList(),
//for android target exclude fonts
if (target is KotlinAndroidTarget) listOf("**/font*/*") else emptyList()
)
},
packedResourceDir
)

if (target is KotlinAndroidTarget) {
//for android target publish fonts in assets
logger.info("Configure fonts relocation for '${target.targetName}' target")
if (target !is KotlinAndroidTarget) {
kmpResources.publishResourcesAsKotlinComponent(
target,
{ sourceSet ->
KotlinTargetResourcesPublication.ResourceRoot(
getPreparedComposeResourcesDir(sourceSet),
emptyList(),
emptyList()
)
},
packedResourceDir
)
} else {
//for android target publish resources in assets
kmpResources.publishInAndroidAssets(
target,
{ sourceSet ->
KotlinTargetResourcesPublication.ResourceRoot(
getPreparedComposeResourcesDir(sourceSet),
listOf("**/font*/*"),
emptyList(),
emptyList()
)
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -251,32 +251,13 @@ class ResourcesTest : GradlePluginTestBase() {
"my-mvn/me/sample/library/cmplib-$target/1.0/cmplib-$target-1.0$ext"

val aar = file(libpath("android", ".aar"))
val innerClassesJar = aar.parentFile.resolve("aar-inner-classes.jar")
assertTrue(aar.exists(), "File not found: " + aar.path)
ZipFile(aar).use { zip ->
resourcesFiles
.filter { it.startsWith("font") }
.forEach { fontRes ->
ZipFile(aar).use { zip -> resourcesFiles.forEach { fontRes ->
terrakok marked this conversation as resolved.
Show resolved Hide resolved
assertNotNull(
zip.getEntry("assets/composeResources/$subdir/$fontRes"),
"Resource not found: '$fontRes' in aar '${aar.path}'"
)
}

innerClassesJar.writeBytes(
zip.getInputStream(zip.getEntry("classes.jar")).readBytes()
)
}
ZipFile(innerClassesJar).use { zip ->
resourcesFiles
.filterNot { it.startsWith("font") }
.forEach { res ->
assertNotNull(
zip.getEntry("composeResources/$subdir/$res"),
"Resource not found: '$res' in aar/classes.jar '${aar.path}'"
)
}
}
} }

val jar = file(libpath("jvm", ".jar"))
checkResourcesZip(jar, resourcesFiles, subdir)
Expand Down Expand Up @@ -393,37 +374,37 @@ class ResourcesTest : GradlePluginTestBase() {
.getConvertedResources(commonResourcesDir)

gradle("build").checks {
check.taskSuccessful(":copyDemoDebugFontsToAndroidAssets")
check.taskSuccessful(":copyDemoReleaseFontsToAndroidAssets")
check.taskSuccessful(":copyFullDebugFontsToAndroidAssets")
check.taskSuccessful(":copyFullReleaseFontsToAndroidAssets")
check.taskSuccessful(":copyDemoDebugResourcesToAndroidAssets")
check.taskSuccessful(":copyDemoReleaseResourcesToAndroidAssets")
check.taskSuccessful(":copyFullDebugResourcesToAndroidAssets")
check.taskSuccessful(":copyFullReleaseResourcesToAndroidAssets")

getAndroidApk("demo", "debug", "Resources-Test").let { apk ->
checkResourcesInZip(apk, commonResourcesFiles, true)
assertEquals(
"android demo-debug",
readFileInZip(apk, "files/platform.txt").decodeToString()
readFileInZip(apk, "assets/files/platform.txt").decodeToString()
)
}
getAndroidApk("demo", "release", "Resources-Test").let { apk ->
checkResourcesInZip(apk, commonResourcesFiles, true)
assertEquals(
"android demo-release",
readFileInZip(apk, "files/platform.txt").decodeToString()
readFileInZip(apk, "assets/files/platform.txt").decodeToString()
)
}
getAndroidApk("full", "debug", "Resources-Test").let { apk ->
checkResourcesInZip(apk, commonResourcesFiles, true)
assertEquals(
"android full-debug",
readFileInZip(apk, "files/platform.txt").decodeToString()
readFileInZip(apk, "assets/files/platform.txt").decodeToString()
)
}
getAndroidApk("full", "release", "Resources-Test").let { apk ->
checkResourcesInZip(apk, commonResourcesFiles, true)
assertEquals(
"android full-release",
readFileInZip(apk, "files/platform.txt").decodeToString()
readFileInZip(apk, "assets/files/platform.txt").decodeToString()
)
}

Expand All @@ -443,36 +424,6 @@ class ResourcesTest : GradlePluginTestBase() {
}
}

@Test
fun testAndroidFonts(): Unit = with(testProject("misc/commonResources")) {
val commonResourcesDir = file("src/commonMain/composeResources")
val commonResourcesFiles = commonResourcesDir.walkTopDown()
.filter { !it.isDirectory && !it.isHidden }
.getConvertedResources(commonResourcesDir)

gradle("assembleDebug").checks {
check.taskSuccessful(":copyDebugFontsToAndroidAssets")

getAndroidApk("", "debug", "Resources-Test").let { apk ->
checkResourcesInZip(apk, commonResourcesFiles, true)
}
}

file("src/commonMain/composeResources/font-en").renameTo(
file("src/commonMain/composeResources/font-mdpi")
)
val newCommonResourcesFiles = commonResourcesDir.walkTopDown()
.filter { !it.isDirectory && !it.isHidden }
.getConvertedResources(commonResourcesDir)
gradle("assembleDebug").checks {
check.taskSuccessful(":copyDebugFontsToAndroidAssets")

getAndroidApk("", "debug", "Resources-Test").let { apk ->
checkResourcesInZip(apk, newCommonResourcesFiles, true)
}
}
}

private fun Sequence<File>.getConvertedResources(baseDir: File) = map { file ->
val newFile = if (
file.parentFile.name.startsWith("value") &&
Expand All @@ -486,7 +437,6 @@ class ResourcesTest : GradlePluginTestBase() {
newFile.relativeTo(baseDir).invariantSeparatorsPath
}


private fun File.writeNewFile(text: String) {
parentFile.mkdirs()
createNewFile()
Expand All @@ -507,8 +457,8 @@ class ResourcesTest : GradlePluginTestBase() {
ZipFile(file).use { zip ->
commonResourcesFiles.forEach { res ->
println("check '$res' file")
if (isAndroid && res.startsWith("font")) {
//android fonts should be only in assets
if (isAndroid) {
//android resources should be only in assets
assertNull(zip.getEntry(res), "file = '$res'")
assertNotNull(zip.getEntry("assets/$res"), "file = 'assets/$res'")
} else {
Expand Down
Loading