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

Introduce a 'composeResources/files' directory for any files. #4079

Merged
merged 4 commits into from
Jan 3, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import org.jetbrains.compose.resources.readResourceBytes
import components.resources.demo.generated.resources.Res

@Composable
fun FileRes(paddingValues: PaddingValues) {
Expand All @@ -28,7 +28,7 @@ fun FileRes(paddingValues: PaddingValues) {
) {
Text(
modifier = Modifier.padding(16.dp),
text = "File: 'composeRes/drawable/droid_icon.xml'",
text = "File: 'files/icon.xml'",
style = MaterialTheme.typography.titleLarge
)
OutlinedCard(
Expand All @@ -38,7 +38,7 @@ fun FileRes(paddingValues: PaddingValues) {
) {
var bytes by remember { mutableStateOf(ByteArray(0)) }
LaunchedEffect(Unit) {
bytes = readResourceBytes("composeRes/drawable/droid_icon.xml")
bytes = Res.readBytes("files/icon.xml")
}
Text(
modifier = Modifier.padding(8.dp).height(200.dp).verticalScroll(rememberScrollState()),
Expand All @@ -54,7 +54,7 @@ fun FileRes(paddingValues: PaddingValues) {
mutableStateOf(ByteArray(0))
}
LaunchedEffect(Unit) {
bytes = readResourceBytes("composeRes/drawable/droid_icon.xml")
bytes = Res.readFileBytes("files/icon.xml")
}
Text(bytes.decodeToString())
""".trimIndent()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ fun StringRes(paddingValues: PaddingValues) {
) {
Text(
modifier = Modifier.padding(16.dp),
text = "composeRes/values/strings.xml",
text = "values/strings.xml",
style = MaterialTheme.typography.titleLarge
)
OutlinedCard(
Expand All @@ -43,7 +43,7 @@ fun StringRes(paddingValues: PaddingValues) {
) {
var bytes by remember { mutableStateOf(ByteArray(0)) }
LaunchedEffect(Unit) {
bytes = readResourceBytes("composeRes/values/strings.xml")
bytes = Res.readBytes("values/strings.xml")
}
Text(
modifier = Modifier.padding(8.dp),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path
android:fillType="evenOdd"
android:pathData="M32,64C32,64 38.39,52.99 44.13,50.95C51.37,48.37 70.14,49.57 70.14,49.57L108.26,87.69L108,109.01L75.97,107.97L32,64Z"
android:strokeWidth="1"
android:strokeColor="#00000000">
<aapt:attr name="android:fillColor">
<gradient
android:endX="78.5885"
android:endY="90.9159"
android:startX="48.7653"
android:startY="61.0927"
android:type="linear">
<item
android:color="#44000000"
android:offset="0.0" />
<item
android:color="#00000000"
android:offset="1.0" />
</gradient>
</aapt:attr>
</path>
<path
android:fillColor="#FFFFFF"
android:fillType="nonZero"
android:pathData="M66.94,46.02L66.94,46.02C72.44,50.07 76,56.61 76,64L32,64C32,56.61 35.56,50.11 40.98,46.06L36.18,41.19C35.45,40.45 35.45,39.3 36.18,38.56C36.91,37.81 38.05,37.81 38.78,38.56L44.25,44.05C47.18,42.57 50.48,41.71 54,41.71C57.48,41.71 60.78,42.57 63.68,44.05L69.11,38.56C69.84,37.81 70.98,37.81 71.71,38.56C72.44,39.3 72.44,40.45 71.71,41.19L66.94,46.02ZM62.94,56.92C64.08,56.92 65,56.01 65,54.88C65,53.76 64.08,52.85 62.94,52.85C61.8,52.85 60.88,53.76 60.88,54.88C60.88,56.01 61.8,56.92 62.94,56.92ZM45.06,56.92C46.2,56.92 47.13,56.01 47.13,54.88C47.13,53.76 46.2,52.85 45.06,52.85C43.92,52.85 43,53.76 43,54.88C43,56.01 43.92,56.92 45.06,56.92Z"
android:strokeWidth="1"
android:strokeColor="#00000000" />
</vector>
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ import androidx.compose.runtime.Immutable
@RequiresOptIn("This API is experimental and is likely to change in the future.")
annotation class ExperimentalResourceApi

@RequiresOptIn("This is internal API of the Compose gradle plugin.")
annotation class InternalResourceApi

/**
* Represents a resource with an ID and a set of resource items.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,15 @@ class MissingResourceException(path: String) : Exception("Missing resource with
* @param path The path of the file to read in the resource's directory.
* @return The content of the file as a byte array.
*/
@ExperimentalResourceApi
@InternalResourceApi
expect suspend fun readResourceBytes(path: String): ByteArray

internal interface ResourceReader {
suspend fun read(path: String): ByteArray
}

internal val DefaultResourceReader: ResourceReader = object : ResourceReader {
@OptIn(ExperimentalResourceApi::class)
@OptIn(InternalResourceApi::class)
override suspend fun read(path: String): ByteArray = readResourceBytes(path)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import platform.Foundation.NSBundle
import platform.Foundation.NSFileManager
import platform.posix.memcpy

@ExperimentalResourceApi
@OptIn(ExperimentalResourceApi::class)
actual suspend fun readResourceBytes(path: String): ByteArray {
val fileManager = NSFileManager.defaultManager()
// todo: support fallback path at bundle root?
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import org.khronos.webgl.Int8Array
private fun ArrayBuffer.toByteArray(): ByteArray =
Int8Array(this, 0, byteLength).unsafeCast<ByteArray>()

@ExperimentalResourceApi
@OptIn(ExperimentalResourceApi::class)
actual suspend fun readResourceBytes(path: String): ByteArray {
val resPath = WebResourcesConfiguration.getResourcePath(path)
val response = window.fetch(resPath).await()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package org.jetbrains.compose.resources

private object JvmResourceReader

@ExperimentalResourceApi
@OptIn(ExperimentalResourceApi::class)
actual suspend fun readResourceBytes(path: String): ByteArray {
val classLoader = Thread.currentThread().contextClassLoader ?: JvmResourceReader.javaClass.classLoader
val resource = classLoader.getResourceAsStream(path) ?: throw MissingResourceException(path)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import kotlinx.cinterop.usePinned
import platform.Foundation.NSFileManager
import platform.posix.memcpy

@ExperimentalResourceApi
@OptIn(ExperimentalResourceApi::class)
actual suspend fun readResourceBytes(path: String): ByteArray {
val currentDirectoryPath = NSFileManager.defaultManager().currentDirectoryPath
val contentsAtPath = NSFileManager.defaultManager().run {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import kotlin.wasm.unsafe.withScopedMemoryAllocator
* @param path The path of the file to read in the resource's directory.
* @return The content of the file as a byte array.
*/
@ExperimentalResourceApi
@OptIn(ExperimentalResourceApi::class)
actual suspend fun readResourceBytes(path: String): ByteArray {
val resPath = WebResourcesConfiguration.getResourcePath(path)
val response = window.fetch(resPath).await<Response>()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import kotlin.io.path.relativeTo
abstract class GenerateResClassTask : DefaultTask() {
@get:Input
abstract val packageName: Property<String>

@get:InputDirectory
@get:PathSensitive(PathSensitivity.RELATIVE)
abstract val resDir: DirectoryProperty
Expand All @@ -34,14 +34,20 @@ abstract class GenerateResClassTask : DefaultTask() {
logger.info("Generate resources for $rootResDir")

//get first level dirs
val dirs = rootResDir.listFiles { f -> f.isDirectory }.orEmpty()
val dirs = rootResDir.listFiles().orEmpty()

dirs.forEach { f ->
if (!f.isDirectory) {
error("${f.name} is not directory! Raw files should be placed in '${rootResDir.name}/files' directory.")
}
}

//type -> id -> resource item
val resources: Map<ResourceType, Map<String, List<ResourceItem>>> = dirs
.flatMap { dir ->
dir.listFiles { f -> !f.isDirectory }
dir.listFiles()
.orEmpty()
.mapNotNull { it.fileToResourceItems(rootResDir.parentFile.toPath()) }
.mapNotNull { it.fileToResourceItems(rootResDir.toPath()) }
.flatten()
}
.groupBy { it.type }
Expand All @@ -61,7 +67,6 @@ abstract class GenerateResClassTask : DefaultTask() {
relativeTo: Path
): List<ResourceItem>? {
val file = this
if (file.isDirectory) return null
val dirName = file.parentFile.name ?: return null
val typeAndQualifiers = dirName.split("-")
if (typeAndQualifiers.isEmpty()) return null
Expand All @@ -70,20 +75,25 @@ abstract class GenerateResClassTask : DefaultTask() {
val qualifiers = typeAndQualifiers.takeLast(typeAndQualifiers.size - 1)
val path = file.toPath().relativeTo(relativeTo)

return if (typeString == "values" && file.name.equals("strings.xml", true)) {

if (typeString == "string") {
error("Forbidden directory name '$dirName'! String resources should be declared in 'values/strings.xml'.")
}

if (typeString == "files") {
if (qualifiers.isNotEmpty()) error("The 'files' directory doesn't support qualifiers: '$dirName'.")
return null
}

if (typeString == "values" && file.name.equals("strings.xml", true)) {
val stringIds = getStringIds(file)
stringIds.map { strId ->
return stringIds.map { strId ->
ResourceItem(ResourceType.STRING, qualifiers, strId.asUnderscoredIdentifier(), path)
}
} else {
val type = try {
ResourceType.fromString(typeString)
} catch (e: Exception) {
logger.warn("w: Skip file: $path\n${e.message}")
return null
}
listOf(ResourceItem(type, qualifiers, file.nameWithoutExtension.asUnderscoredIdentifier(), path))
}

val type = ResourceType.fromString(typeString)
return listOf(ResourceItem(type, qualifiers, file.nameWithoutExtension.asUnderscoredIdentifier(), path))
}

private val stringTypeNames = listOf("string", "string-array")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,72 +6,75 @@ import org.jetbrains.compose.ComposeExtension
import org.jetbrains.compose.ComposePlugin
import org.jetbrains.compose.ExperimentalComposeLibrary
import org.jetbrains.compose.desktop.application.internal.ComposeProperties
import org.jetbrains.compose.internal.KOTLIN_MPP_PLUGIN_ID
import org.jetbrains.kotlin.gradle.dsl.KotlinProjectExtension
import org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet
import java.io.File

private const val COMPOSE_RESOURCES_DIR = "composeRes"
internal const val COMPOSE_RESOURCES_DIR = "composeResources"
private const val RES_GEN_DIR = "generated/compose/resourceGenerator"

internal fun Project.configureResourceGenerator() {
val kotlinExtension = project.extensions.getByType(KotlinProjectExtension::class.java)
val commonSourceSet = kotlinExtension.sourceSets.findByName(KotlinSourceSet.COMMON_MAIN_SOURCE_SET_NAME) ?: return
val commonResourcesDir = provider { commonSourceSet.resources.sourceDirectories.first() }
pluginManager.withPlugin(KOTLIN_MPP_PLUGIN_ID) {
val kotlinExtension = project.extensions.getByType(KotlinProjectExtension::class.java)
val commonSourceSet = kotlinExtension.sourceSets.findByName(KotlinSourceSet.COMMON_MAIN_SOURCE_SET_NAME) ?: return@withPlugin
val commonResourcesDir = provider { commonSourceSet.resources.sourceDirectories.first() }

val packageName = provider {
buildString {
val group = project.group.toString().asUnderscoredIdentifier()
append(group)
if (group.isNotEmpty()) append(".")
append("generated.resources")
val packageName = provider {
buildString {
val group = project.group.toString().asUnderscoredIdentifier()
append(group)
if (group.isNotEmpty()) append(".")
append("generated.resources")
}
}
}

fun buildDir(path: String) = layout.dir(layout.buildDirectory.map { File(it.asFile, path) })
fun buildDir(path: String) = layout.dir(layout.buildDirectory.map { File(it.asFile, path) })

val resDir = layout.dir(commonResourcesDir.map { it.resolve(COMPOSE_RESOURCES_DIR) })
val resDir = layout.dir(commonResourcesDir.map { it.resolve(COMPOSE_RESOURCES_DIR) })

//lazy check a dependency on the Resources library
val shouldGenerateResourceAccessors: Provider<Boolean> = provider {
if (ComposeProperties.alwaysGenerateResourceAccessors(providers).get()) {
true
} else {
configurations
.getByName(commonSourceSet.implementationConfigurationName)
.allDependencies.any { dep ->
val depStringNotation = dep.let { "${it.group}:${it.name}:${it.version}" }
depStringNotation == ComposePlugin.CommonComponentsDependencies.resources
}
//lazy check a dependency on the Resources library
val shouldGenerateResourceAccessors: Provider<Boolean> = provider {
if (ComposeProperties.alwaysGenerateResourceAccessors(providers).get()) {
true
} else {
configurations
.getByName(commonSourceSet.implementationConfigurationName)
.allDependencies.any { dep ->
val depStringNotation = dep.let { "${it.group}:${it.name}:${it.version}" }
depStringNotation == ComposePlugin.CommonComponentsDependencies.resources
}
}
}
}

val genTask = tasks.register(
"generateComposeResClass",
GenerateResClassTask::class.java
) {
it.packageName.set(packageName)
it.resDir.set(resDir)
it.codeDir.set(buildDir("$RES_GEN_DIR/kotlin"))
it.onlyIf { shouldGenerateResourceAccessors.get() }
}
val genTask = tasks.register(
"generateComposeResClass",
GenerateResClassTask::class.java
) {
it.packageName.set(packageName)
it.resDir.set(resDir)
it.codeDir.set(buildDir("$RES_GEN_DIR/kotlin"))
it.onlyIf { shouldGenerateResourceAccessors.get() }
}

//register generated source set
commonSourceSet.kotlin.srcDir(genTask.map { it.codeDir })
//register generated source set
commonSourceSet.kotlin.srcDir(genTask.map { it.codeDir })

//setup task execution during IDE import
tasks.configureEach {
if (it.name == "prepareKotlinIdeaImport") {
it.dependsOn(genTask)
//setup task execution during IDE import
tasks.configureEach {
if (it.name == "prepareKotlinIdeaImport") {
it.dependsOn(genTask)
}
}
}

val androidExtension = project.extensions.findByName("android")
if (androidExtension != null) {
configureAndroidResources(
commonResourcesDir,
buildDir("$RES_GEN_DIR/androidFonts").map { it.asFile },
shouldGenerateResourceAccessors
)
val androidExtension = project.extensions.findByName("android")
if (androidExtension != null) {
configureAndroidResources(
commonResourcesDir,
buildDir("$RES_GEN_DIR/androidFonts").map { it.asFile },
shouldGenerateResourceAccessors
)
}
}
}

Loading