├── libres-core ├── gradle.properties ├── src │ ├── commonMain │ │ └── kotlin │ │ │ └── io │ │ │ └── github │ │ │ └── skeptick │ │ │ └── libres │ │ │ ├── images │ │ │ └── Image.common.kt.kt │ │ │ ├── LibresSettings.kt │ │ │ └── strings │ │ │ ├── Language.common.kt │ │ │ ├── FormattedString.kt │ │ │ ├── PluralForms.kt │ │ │ └── PluralString.common.kt │ ├── jvmMain │ │ └── kotlin │ │ │ └── io │ │ │ └── github │ │ │ └── skeptick │ │ │ └── libres │ │ │ ├── images │ │ │ └── Image.jvm.kt │ │ │ └── strings │ │ │ ├── Language.jvm.kt │ │ │ └── PluralString.jvm.kt │ ├── webMain │ │ └── kotlin │ │ │ └── io │ │ │ └── github │ │ │ └── skeptick │ │ │ └── libres │ │ │ ├── images │ │ │ └── Image.web.kt │ │ │ └── strings │ │ │ └── PluralString.web.kt │ ├── androidMain │ │ └── kotlin │ │ │ └── io │ │ │ └── github │ │ │ └── skeptick │ │ │ └── libres │ │ │ ├── images │ │ │ └── Image.android.kt │ │ │ └── strings │ │ │ ├── Language.android.kt │ │ │ └── PluralString.android.kt │ ├── uikitMain │ │ └── kotlin │ │ │ └── io │ │ │ └── github │ │ │ └── skeptick │ │ │ └── libres │ │ │ └── images │ │ │ ├── Image.uikit.kt │ │ │ └── Bundle.kt │ ├── macosMain │ │ └── kotlin │ │ │ └── io │ │ │ └── github │ │ │ └── skeptick │ │ │ └── libres │ │ │ └── images │ │ │ ├── Image.macos.kt │ │ │ └── Bundle.kt │ ├── appleMain │ │ └── kotlin │ │ │ └── io │ │ │ └── github │ │ │ └── skeptick │ │ │ └── libres │ │ │ └── strings │ │ │ ├── Language.apple.kt │ │ │ └── PluralString.apple.kt │ ├── jsMain │ │ └── kotlin │ │ │ └── io │ │ │ └── github │ │ │ └── skeptick │ │ │ └── libres │ │ │ └── strings │ │ │ └── Language.js.kt │ ├── wasmJsMain │ │ └── kotlin │ │ │ └── io │ │ │ └── github │ │ │ └── skeptick │ │ │ └── libres │ │ │ └── strings │ │ │ └── Language.wasmJs.kt │ └── appleAndWebMain │ │ └── kotlin │ │ └── io │ │ └── github │ │ └── skeptick │ │ └── libres │ │ └── strings │ │ └── PluralRules.kt └── build.gradle.kts ├── libres-compose ├── gradle.properties ├── src │ ├── androidMain │ │ └── kotlin │ │ │ └── io │ │ │ └── github │ │ │ └── skeptick │ │ │ └── libres │ │ │ └── compose │ │ │ └── PainterResource.android.kt │ ├── jvmMain │ │ └── kotlin │ │ │ └── io │ │ │ └── github │ │ │ └── skeptick │ │ │ └── libres │ │ │ └── compose │ │ │ └── PainterResource.jvm.kt │ ├── commonMain │ │ └── kotlin │ │ │ └── io │ │ │ └── github │ │ │ └── skeptick │ │ │ └── libres │ │ │ └── compose │ │ │ └── PainterResource.common.kt │ ├── appleMain │ │ └── kotlin │ │ │ └── io │ │ │ └── github │ │ │ └── skeptick │ │ │ └── libres │ │ │ └── compose │ │ │ ├── PainterResource.apple.kt │ │ │ ├── LibresImage+Skia.apple.kt │ │ │ └── AppleSvgPainter.kt │ ├── macosMain │ │ └── kotlin │ │ │ └── io │ │ │ └── github │ │ │ └── skeptick │ │ │ └── libres │ │ │ └── compose │ │ │ └── LibresImage+Skia.macos.kt │ ├── iosMain │ │ └── kotlin │ │ │ └── io │ │ │ └── github │ │ │ └── skeptick │ │ │ └── libres │ │ │ └── compose │ │ │ └── LibresImage+Skia.ios.kt │ ├── jsMain │ │ └── kotlin │ │ │ └── io │ │ │ └── github │ │ │ └── skeptick │ │ │ └── libres │ │ │ └── compose │ │ │ └── PainterResource.js.kt │ ├── wasmJsMain │ │ └── kotlin │ │ │ └── io │ │ │ └── github │ │ │ └── skeptick │ │ │ └── libres │ │ │ └── compose │ │ │ └── PainterResource.wasmJs.kt │ └── webMain │ │ └── kotlin │ │ └── io │ │ └── github │ │ └── skeptick │ │ └── libres │ │ └── compose │ │ └── WebSvgPainter.kt └── build.gradle.kts ├── gradle-plugin ├── gradle.properties ├── src │ ├── main │ │ └── java │ │ │ └── io │ │ │ └── github │ │ │ └── skeptick │ │ │ └── libres │ │ │ └── plugin │ │ │ ├── strings │ │ │ ├── models │ │ │ │ ├── LanguageCode.kt │ │ │ │ ├── TextResource.kt │ │ │ │ ├── StringResource.kt │ │ │ │ └── PluralsResource.kt │ │ │ ├── String+Extensions.kt │ │ │ ├── declarations │ │ │ │ ├── Files.kt │ │ │ │ ├── Properties+Functions.kt │ │ │ │ └── Classes.kt │ │ │ ├── StringsParsing.kt │ │ │ └── StringTypeSpecsBuilder.kt │ │ │ ├── common │ │ │ ├── extensions │ │ │ │ ├── Files.kt │ │ │ │ └── Collections.kt │ │ │ ├── declarations │ │ │ │ ├── Files.kt │ │ │ │ ├── Classes.kt │ │ │ │ └── Properties+Functions.kt │ │ │ └── project │ │ │ │ └── Project+IosBundle.kt │ │ │ ├── images │ │ │ ├── processing │ │ │ │ ├── Size.kt │ │ │ │ └── ImageSpecs+Operations.kt │ │ │ ├── models │ │ │ │ ├── ImageProps.kt │ │ │ │ ├── ImageScale.kt │ │ │ │ └── ImageSetContents.kt │ │ │ ├── declarations │ │ │ │ ├── Files.kt │ │ │ │ ├── Properties+Functions.kt │ │ │ │ └── Classes.kt │ │ │ └── ImagesTypeSpecsBuilder.kt │ │ │ ├── ResourcesPluginExtension.kt │ │ │ ├── LibresResourcesGenerationTask.kt │ │ │ ├── LibresStringGenerationTask.kt │ │ │ ├── LibresBundleGenerationTask.kt │ │ │ ├── LibresImagesGenerationTask.kt │ │ │ ├── SourceSet.kt │ │ │ └── ResourcesPlugin.kt │ └── test │ │ └── kotlin │ │ └── io │ │ └── github │ │ └── skeptick │ │ └── libres │ │ └── plugin │ │ └── HasJavaArgumentsTest.kt └── build.gradle.kts ├── gradle ├── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties └── libs.versions.toml ├── .gitignore ├── settings.gradle.kts ├── gradle.properties ├── docs └── LOCALIZATION.md ├── gradlew.bat ├── README.md ├── gradlew └── LICENSE /libres-core/gradle.properties: -------------------------------------------------------------------------------- 1 | POM_NAME=Libres Core 2 | POM_ARTIFACT_ID=libres -------------------------------------------------------------------------------- /libres-compose/gradle.properties: -------------------------------------------------------------------------------- 1 | POM_NAME=Libres Compose 2 | POM_ARTIFACT_ID=libres-compose -------------------------------------------------------------------------------- /gradle-plugin/gradle.properties: -------------------------------------------------------------------------------- 1 | POM_NAME=Libres Gradle Plugin 2 | POM_ARTIFACT_ID=gradle-plugin -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Skeptick/libres/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /libres-core/src/commonMain/kotlin/io/github/skeptick/libres/images/Image.common.kt.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.images 2 | 3 | public expect class Image -------------------------------------------------------------------------------- /libres-core/src/jvmMain/kotlin/io/github/skeptick/libres/images/Image.jvm.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.images 2 | 3 | public actual typealias Image = String -------------------------------------------------------------------------------- /libres-core/src/webMain/kotlin/io/github/skeptick/libres/images/Image.web.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.images 2 | 3 | public actual typealias Image = String -------------------------------------------------------------------------------- /libres-core/src/androidMain/kotlin/io/github/skeptick/libres/images/Image.android.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.images 2 | 3 | public actual typealias Image = Int -------------------------------------------------------------------------------- /gradle-plugin/src/main/java/io/github/skeptick/libres/plugin/strings/models/LanguageCode.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.plugin.strings.models 2 | 3 | internal typealias LanguageCode = String -------------------------------------------------------------------------------- /libres-core/src/commonMain/kotlin/io/github/skeptick/libres/LibresSettings.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres 2 | 3 | public object LibresSettings { 4 | public var languageCode: String? = null 5 | } -------------------------------------------------------------------------------- /libres-core/src/uikitMain/kotlin/io/github/skeptick/libres/images/Image.uikit.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.images 2 | 3 | import platform.UIKit.UIImage 4 | 5 | public actual typealias Image = UIImage -------------------------------------------------------------------------------- /libres-core/src/macosMain/kotlin/io/github/skeptick/libres/images/Image.macos.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.images 2 | 3 | import platform.AppKit.NSImage 4 | 5 | public actual typealias Image = NSImage -------------------------------------------------------------------------------- /gradle-plugin/src/main/java/io/github/skeptick/libres/plugin/strings/models/TextResource.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.plugin.strings.models 2 | 3 | internal sealed interface TextResource { 4 | val name: String 5 | val parameters: Set 6 | } -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /libres-core/src/jvmMain/kotlin/io/github/skeptick/libres/strings/Language.jvm.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.strings 2 | 3 | import java.util.Locale 4 | 5 | public actual fun getPlatformLanguageCode(): String { 6 | return Locale.getDefault().language 7 | } -------------------------------------------------------------------------------- /gradle-plugin/src/main/java/io/github/skeptick/libres/plugin/common/extensions/Files.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.plugin.common.extensions 2 | 3 | import java.io.File 4 | 5 | internal fun File.deleteFilesInDirectory() { 6 | listFiles()?.forEach { 7 | if (it.isFile) it.delete() 8 | } 9 | } -------------------------------------------------------------------------------- /libres-core/src/androidMain/kotlin/io/github/skeptick/libres/strings/Language.android.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.strings 2 | 3 | import androidx.core.os.LocaleListCompat 4 | 5 | public actual fun getPlatformLanguageCode(): String { 6 | return LocaleListCompat.getDefault()[0]?.language ?: "undefined" 7 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .gradle 3 | .settings 4 | .project 5 | .classpath 6 | .vscode 7 | .idea 8 | .kotlin 9 | !/.idea/codeStyles 10 | .run 11 | build 12 | *.iml 13 | Pods 14 | xcuserdata 15 | local.properties 16 | .externalNativeBuild 17 | .cxx 18 | *.xcuserstate 19 | *.xcbkptlist 20 | /gradle-plugin/generated 21 | /kotlin-js-store/ 22 | -------------------------------------------------------------------------------- /libres-core/src/commonMain/kotlin/io/github/skeptick/libres/strings/Language.common.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.strings 2 | 3 | import io.github.skeptick.libres.LibresSettings 4 | 5 | public fun getCurrentLanguageCode(): String { 6 | return LibresSettings.languageCode ?: getPlatformLanguageCode() 7 | } 8 | 9 | public expect fun getPlatformLanguageCode(): String -------------------------------------------------------------------------------- /libres-core/src/appleMain/kotlin/io/github/skeptick/libres/strings/Language.apple.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.strings 2 | 3 | import platform.Foundation.NSLocale 4 | import platform.Foundation.currentLocale 5 | import platform.Foundation.languageCode 6 | 7 | public actual fun getPlatformLanguageCode(): String { 8 | return NSLocale.currentLocale.languageCode 9 | } -------------------------------------------------------------------------------- /libres-core/src/webMain/kotlin/io/github/skeptick/libres/strings/PluralString.web.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.strings 2 | 3 | public actual fun getPluralizedString(forms: PluralForms, languageCode: String, number: Int): String { 4 | val formName = PluralRules[languageCode].getForm(number).formName 5 | return forms[formName] ?: error("Plural form '$formName' not provided") 6 | } -------------------------------------------------------------------------------- /gradle-plugin/src/main/java/io/github/skeptick/libres/plugin/common/extensions/Collections.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.plugin.common.extensions 2 | 3 | fun List.findDuplicates(): Set { 4 | val exist = mutableSetOf() 5 | val duplicates = mutableSetOf() 6 | for (item in this) if (item in exist) duplicates += item else exist += item 7 | return duplicates 8 | } -------------------------------------------------------------------------------- /libres-core/src/appleMain/kotlin/io/github/skeptick/libres/strings/PluralString.apple.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.strings 2 | 3 | public actual fun getPluralizedString(forms: PluralForms, languageCode: String, number: Int): String { 4 | val formName = PluralRules[languageCode].getForm(number).formName 5 | return forms[formName] ?: error("Plural form '$formName' not provided") 6 | } -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | @file:Suppress("UnstableApiUsage") 2 | 3 | enableFeaturePreview("TYPESAFE_PROJECT_ACCESSORS") 4 | 5 | dependencyResolutionManagement { 6 | repositories { 7 | google() 8 | mavenCentral() 9 | maven(url = "https://maven.pkg.jetbrains.space/public/p/compose/dev") 10 | } 11 | } 12 | 13 | include(":libres-core", ":libres-compose", ":gradle-plugin") -------------------------------------------------------------------------------- /libres-compose/src/androidMain/kotlin/io/github/skeptick/libres/compose/PainterResource.android.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.compose 2 | 3 | import androidx.compose.runtime.Composable 4 | import androidx.compose.ui.graphics.painter.Painter 5 | import io.github.skeptick.libres.images.Image 6 | 7 | @Composable 8 | public actual fun painterResource(image: Image): Painter { 9 | return androidx.compose.ui.res.painterResource(image) 10 | } -------------------------------------------------------------------------------- /libres-compose/src/jvmMain/kotlin/io/github/skeptick/libres/compose/PainterResource.jvm.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.compose 2 | 3 | import androidx.compose.runtime.Composable 4 | import androidx.compose.ui.graphics.painter.Painter 5 | import io.github.skeptick.libres.images.Image 6 | 7 | @Suppress("DEPRECATION") 8 | @Composable 9 | public actual fun painterResource(image: Image): Painter { 10 | return androidx.compose.ui.res.painterResource(image) 11 | } -------------------------------------------------------------------------------- /libres-compose/src/commonMain/kotlin/io/github/skeptick/libres/compose/PainterResource.common.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.compose 2 | 3 | import androidx.compose.runtime.Composable 4 | import androidx.compose.ui.graphics.painter.Painter 5 | import io.github.skeptick.libres.images.Image 6 | 7 | @Composable 8 | public expect fun painterResource(image: Image): Painter 9 | 10 | @Suppress("unused") 11 | @Composable 12 | public fun Image.painterResource() = painterResource(this) -------------------------------------------------------------------------------- /libres-core/src/jsMain/kotlin/io/github/skeptick/libres/strings/Language.js.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.strings 2 | 3 | import kotlinx.browser.window 4 | 5 | public actual fun getPlatformLanguageCode(): String { 6 | return if (window.navigator.languages.isNotEmpty()) { 7 | window.navigator.languages[0].languageCode 8 | } else { 9 | window.navigator.language.languageCode 10 | } 11 | } 12 | 13 | private inline val String.languageCode get() = if (length == 2) this else take(2) -------------------------------------------------------------------------------- /libres-core/src/jvmMain/kotlin/io/github/skeptick/libres/strings/PluralString.jvm.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.strings 2 | 3 | import com.ibm.icu.text.PluralRules 4 | import java.util.Locale 5 | 6 | @Suppress("DEPRECATION") 7 | public actual fun getPluralizedString(forms: PluralForms, languageCode: String, number: Int): String { 8 | val rules = PluralRules.forLocale(Locale(languageCode)) 9 | val form = rules.select(number.toDouble()) 10 | return forms[form] ?: error("Plural form '$form' not provided") 11 | } -------------------------------------------------------------------------------- /libres-core/src/wasmJsMain/kotlin/io/github/skeptick/libres/strings/Language.wasmJs.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.strings 2 | 3 | import kotlinx.browser.window 4 | 5 | public actual fun getPlatformLanguageCode(): String { 6 | return if (window.navigator.languages.length > 0) { 7 | window.navigator.languages[0].toString().languageCode 8 | } else { 9 | window.navigator.language.languageCode 10 | } 11 | } 12 | 13 | private inline val String.languageCode get() = if (length == 2) this else take(2) -------------------------------------------------------------------------------- /gradle-plugin/src/main/java/io/github/skeptick/libres/plugin/strings/models/StringResource.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.plugin.strings.models 2 | 3 | import io.github.skeptick.libres.plugin.strings.extractInterpolationParametersNames 4 | 5 | data class StringResource( 6 | override val name: String, 7 | val value: String 8 | ) : TextResource { 9 | 10 | override val parameters: Set by lazy(LazyThreadSafetyMode.NONE) { 11 | value.extractInterpolationParametersNames().toSet() 12 | } 13 | 14 | } -------------------------------------------------------------------------------- /libres-core/src/commonMain/kotlin/io/github/skeptick/libres/strings/FormattedString.kt: -------------------------------------------------------------------------------- 1 | @file:Suppress("unused") 2 | 3 | package io.github.skeptick.libres.strings 4 | 5 | private val RegularFormatRegex = "%(\\d)\\$[s]".toRegex() 6 | 7 | public class VoidFormattedString(private val value: String) { 8 | public fun format(vararg args: String): String = formatString(value, args) 9 | } 10 | 11 | public fun formatString(value: String, args: Array): String { 12 | return RegularFormatRegex.replace(value) { matchResult -> 13 | args[matchResult.groupValues[1].toInt() - 1] 14 | } 15 | } -------------------------------------------------------------------------------- /libres-core/src/commonMain/kotlin/io/github/skeptick/libres/strings/PluralForms.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.strings 2 | 3 | public class PluralForms( 4 | public val zero: String? = null, 5 | public val one: String? = null, 6 | public val two: String? = null, 7 | public val few: String? = null, 8 | public val many: String? = null, 9 | public val other: String? = null 10 | ) 11 | 12 | internal operator fun PluralForms.get(key: String) = 13 | when (key) { 14 | "zero" -> zero 15 | "one" -> one 16 | "two" -> two 17 | "few" -> few 18 | "many" -> many 19 | else -> other 20 | } -------------------------------------------------------------------------------- /libres-core/src/commonMain/kotlin/io/github/skeptick/libres/strings/PluralString.common.kt: -------------------------------------------------------------------------------- 1 | @file:Suppress("unused") 2 | 3 | package io.github.skeptick.libres.strings 4 | 5 | public class VoidPluralString(private val forms: PluralForms, private val languageCode: String) { 6 | public fun format(number: Int): String = getPluralizedString(forms, languageCode, number) 7 | } 8 | 9 | public class VoidFormattedPluralString(private val forms: PluralForms, private val languageCode: String) { 10 | public fun format(number: Int, vararg args: String): String = formatString(getPluralizedString(forms, languageCode, number), args) 11 | } 12 | 13 | public expect fun getPluralizedString(forms: PluralForms, languageCode: String, number: Int): String -------------------------------------------------------------------------------- /libres-core/src/macosMain/kotlin/io/github/skeptick/libres/images/Bundle.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.images 2 | 3 | import platform.Foundation.NSBundle 4 | import platform.AppKit.NSImage 5 | import platform.AppKit.imageForResource 6 | 7 | public fun NSBundle.Companion.bundleWithName(name: String): NSBundle { 8 | val url = mainBundle.URLForResource(name = name, withExtension = "bundle") ?: error("$name.bundle not found") 9 | return bundleWithURL(url = url) ?: error("Cannot access $name.bundle") 10 | } 11 | 12 | public fun NSBundle.image(name: String, extension: String): NSImage { 13 | val image = imageForResource(name) ?: error("Image $name not found") 14 | image.setName("$name.$extension") 15 | return image 16 | } -------------------------------------------------------------------------------- /gradle-plugin/src/main/java/io/github/skeptick/libres/plugin/common/declarations/Files.kt: -------------------------------------------------------------------------------- 1 | @file:Suppress("FunctionName") 2 | 3 | package io.github.skeptick.libres.plugin.common.declarations 4 | 5 | import com.squareup.kotlinpoet.FileSpec 6 | import com.squareup.kotlinpoet.TypeSpec 7 | import java.io.File 8 | 9 | internal fun ResourcesFile( 10 | packageName: String, 11 | name: String, 12 | resourcesObjectBuilder: TypeSpec.Builder 13 | ): FileSpec { 14 | return FileSpec.builder(packageName, name) 15 | .addType(resourcesObjectBuilder.build()) 16 | .build() 17 | } 18 | 19 | internal fun FileSpec.saveToDirectory(directory: File) { 20 | directory.mkdirs() 21 | File(directory, "$name.${if (isScript) "kts" else "kt"}").writer().use(::writeTo) 22 | } -------------------------------------------------------------------------------- /libres-core/src/uikitMain/kotlin/io/github/skeptick/libres/images/Bundle.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.images 2 | 3 | import platform.Foundation.NSBundle 4 | import platform.UIKit.UIImage 5 | import platform.UIKit.accessibilityValue 6 | 7 | public fun NSBundle.Companion.bundleWithName(name: String): NSBundle { 8 | val url = mainBundle.URLForResource(name = name, withExtension = "bundle", subdirectory = "libres-bundles") ?: error("$name.bundle not found") 9 | return bundleWithURL(url = url) ?: error("Cannot access $name.bundle") 10 | } 11 | 12 | public fun NSBundle.image(name: String, extension: String): UIImage { 13 | val image = UIImage.imageNamed(name = name, inBundle = this, withConfiguration = null) ?: error("Image $name not found") 14 | image.accessibilityValue = "$name.$extension" 15 | return image 16 | } -------------------------------------------------------------------------------- /libres-compose/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | id("multiplatform-setup") 3 | id("android-setup-plugin") 4 | id("com.vanniktech.maven.publish") 5 | id("org.jetbrains.compose") 6 | id("org.jetbrains.kotlin.plugin.compose") 7 | } 8 | 9 | android { 10 | namespace = "io.github.skeptick.libres.compose" 11 | } 12 | 13 | kotlin { 14 | applyDefaultHierarchyTemplate() 15 | 16 | sourceSets { 17 | commonMain { 18 | dependencies { 19 | api(projects.libresCore) 20 | implementation(libs.coroutines.core) 21 | implementation(compose.ui) 22 | } 23 | } 24 | 25 | val webMain by creating { 26 | dependsOn(commonMain.get()) 27 | jsMain.get().dependsOn(this) 28 | wasmJsMain.get().dependsOn(this) 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /gradle-plugin/src/main/java/io/github/skeptick/libres/plugin/images/processing/Size.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.plugin.images.processing 2 | 3 | import org.bytedeco.opencv.opencv_core.Size 4 | 5 | internal fun calculateSize(oldSize: Size, newSideSize: Int): Size { 6 | val height = oldSize.height() 7 | val width = oldSize.width() 8 | 9 | return when { 10 | height == width -> Size(newSideSize, newSideSize) 11 | height > width -> Size((width.toDouble() / height * newSideSize).toInt(), newSideSize) 12 | else -> Size(newSideSize, (height.toDouble() / width * newSideSize).toInt()) 13 | } 14 | } 15 | 16 | internal operator fun Size.compareTo(sideSize: Int): Int { 17 | return when { 18 | width() > sideSize || height() > sideSize -> 1 19 | width() < sideSize && height() < sideSize -> -1 20 | else -> 0 21 | } 22 | } -------------------------------------------------------------------------------- /gradle-plugin/src/main/java/io/github/skeptick/libres/plugin/strings/models/PluralsResource.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.plugin.strings.models 2 | 3 | import io.github.skeptick.libres.plugin.strings.extractInterpolationParametersNames 4 | 5 | data class PluralsResource( 6 | override val name: String, 7 | val items: List 8 | ) : TextResource { 9 | 10 | override val parameters: Set by lazy(LazyThreadSafetyMode.NONE) { 11 | items.flatMap { it.value.extractInterpolationParametersNames() }.toSet() 12 | } 13 | 14 | data class Item( 15 | val quantity: Quantity, 16 | val value: String 17 | ) 18 | 19 | enum class Quantity(val serialName: String) { 20 | Zero("zero"), 21 | One("one"), 22 | Two("two"), 23 | Few("few"), 24 | Many("many"), 25 | Other("other") 26 | } 27 | 28 | companion object { 29 | val quantityBySerialName = Quantity.values().associateBy(Quantity::serialName) 30 | } 31 | 32 | } -------------------------------------------------------------------------------- /gradle-plugin/src/main/java/io/github/skeptick/libres/plugin/images/models/ImageProps.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.plugin.images.models 2 | 3 | import java.io.File 4 | 5 | internal class ImageProps(val file: File) { 6 | 7 | val name: String 8 | val extension: String 9 | val targetSize: Int? 10 | val isTintable: Boolean 11 | 12 | init { 13 | val nameWithoutExtension = file.nameWithoutExtension 14 | val parameters = ParametersRegex.findAll(nameWithoutExtension).toList() 15 | this.name = nameWithoutExtension.substringBefore("_(").lowercase() 16 | this.extension = file.extension.lowercase() 17 | this.targetSize = if (!isVector) parameters.firstNotNullOfOrNull { it.groupValues[1].toIntOrNull() } else null 18 | this.isTintable = parameters.none { it.groupValues[1].startsWith("orig") } 19 | } 20 | 21 | companion object { 22 | private val ParametersRegex = Regex("_\\((.*?)\\)") 23 | } 24 | 25 | } 26 | 27 | internal val ImageProps.isVector: Boolean get() = extension == "svg" -------------------------------------------------------------------------------- /gradle-plugin/src/main/java/io/github/skeptick/libres/plugin/common/declarations/Classes.kt: -------------------------------------------------------------------------------- 1 | @file:Suppress("FunctionName") 2 | 3 | package io.github.skeptick.libres.plugin.common.declarations 4 | 5 | import com.squareup.kotlinpoet.ClassName 6 | import com.squareup.kotlinpoet.PropertySpec 7 | import com.squareup.kotlinpoet.TypeSpec 8 | 9 | /* 10 | * object MainRes { 11 | * val string: MainResStrings = MainResStrings 12 | * val image: MainResImages = MainResImages 13 | * } 14 | */ 15 | internal fun ResourcesObject( 16 | name: String, 17 | stringsPackageName: String, 18 | imagesPackageName: String 19 | ): TypeSpec.Builder { 20 | return TypeSpec.objectBuilder(name) 21 | .addProperty( 22 | PropertySpec.builder("string", ClassName(stringsPackageName, "${name}Strings")) 23 | .initializer("${name}Strings") 24 | .build() 25 | ).addProperty( 26 | PropertySpec.builder("image", ClassName(imagesPackageName, "${name}Images")) 27 | .initializer("${name}Images") 28 | .build() 29 | ) 30 | } -------------------------------------------------------------------------------- /libres-compose/src/appleMain/kotlin/io/github/skeptick/libres/compose/PainterResource.apple.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.compose 2 | 3 | import androidx.compose.runtime.Composable 4 | import androidx.compose.runtime.remember 5 | import androidx.compose.ui.graphics.painter.BitmapPainter 6 | import androidx.compose.ui.graphics.painter.Painter 7 | import androidx.compose.ui.graphics.toComposeImageBitmap 8 | import io.github.skeptick.libres.images.Image 9 | 10 | @Composable 11 | public actual fun painterResource(image: Image): Painter { 12 | return when (image.extension) { 13 | "svg" -> rememberSvgResource(image) 14 | else -> rememberBitmapResource(image) 15 | } 16 | } 17 | 18 | @Composable 19 | internal fun rememberSvgResource(image: Image): Painter { 20 | return remember(image) { 21 | AppleSvgPainter(image) 22 | } 23 | } 24 | 25 | @Composable 26 | internal fun rememberBitmapResource(image: Image): Painter { 27 | return remember(image) { 28 | val skiaImage = image.toSkiaImage() 29 | BitmapPainter(skiaImage.toComposeImageBitmap()) 30 | } 31 | } -------------------------------------------------------------------------------- /libres-compose/src/macosMain/kotlin/io/github/skeptick/libres/compose/LibresImage+Skia.macos.kt: -------------------------------------------------------------------------------- 1 | @file:OptIn(ExperimentalForeignApi::class) 2 | 3 | package io.github.skeptick.libres.compose 4 | 5 | import androidx.compose.ui.unit.IntSize 6 | import io.github.skeptick.libres.images.Image 7 | import kotlinx.cinterop.ExperimentalForeignApi 8 | import kotlinx.cinterop.MemScope 9 | import platform.AppKit.NSImageRep 10 | import platform.CoreGraphics.CGImageRef 11 | import platform.Foundation.NSRectFromCGRect 12 | 13 | internal actual val Image.extension: String? 14 | get() = name()?.substringAfterLast('.') 15 | 16 | internal actual val Image.intSize: IntSize 17 | get() { 18 | val rep = representations.firstOrNull() as? NSImageRep ?: return IntSize.Zero 19 | return IntSize(rep.pixelsWide.toInt(), rep.pixelsHigh.toInt()) 20 | } 21 | 22 | internal actual fun MemScope.libresImageToCGImage(image: Image, size: IntSize): CGImageRef { 23 | val nsRect = NSRectFromCGRect(size.toCGRect()) 24 | return image.CGImageForProposedRect(nsRect.ptr, null, null) ?: error("Cannot get CGImage from NSImage") 25 | } -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | org.gradle.jvmargs=-Xmx4096m -Dfile.encoding=UTF-8 2 | kotlin.code.style=official 3 | kotlin.js.generate.executable.default=false 4 | android.useAndroidX=true 5 | kotlin.mpp.androidSourceSetLayoutVersion=2 6 | org.jetbrains.compose.experimental.uikit.enabled=true 7 | org.jetbrains.compose.experimental.jscanvas.enabled=true 8 | org.jetbrains.compose.experimental.macos.enabled=true 9 | org.jetbrains.compose.experimental.wasm.enabled=true 10 | 11 | GROUP=io.github.skeptick.libres 12 | VERSION_NAME=1.2.4 13 | 14 | SONATYPE_HOST=CENTRAL_PORTAL 15 | 16 | POM_DESCRIPTION=Resources generation in Kotlin Multiplatform. 17 | POM_INCEPTION_YEAR=2022 18 | POM_URL=https://github.com/skeptick/libres 19 | 20 | POM_LICENSE_NAME=The Apache Software License, Version 2.0 21 | POM_LICENSE_URL=https://www.apache.org/licenses/LICENSE-2.0.txt 22 | POM_LICENSE_DIST=repo 23 | 24 | POM_SCM_URL=https://github.com/skeptick/libres 25 | POM_SCM_CONNECTION=scm:git:ssh://git@github.com/skeptick/libres.git 26 | POM_SCM_DEV_CONNECTION=scm:git:ssh://git@github.com/skeptick/libres.git 27 | 28 | POM_DEVELOPER_ID=Skeptick 29 | POM_DEVELOPER_NAME=Danil Yudov 30 | POM_DEVELOPER_URL=https://github.com/skeptick/ -------------------------------------------------------------------------------- /gradle-plugin/src/main/java/io/github/skeptick/libres/plugin/images/models/ImageScale.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.plugin.images.models 2 | 3 | import io.github.skeptick.libres.plugin.KotlinPlatform 4 | 5 | @Suppress("EnumEntryName") 6 | internal enum class ImageScale(vararg val supportedPlatforms: KotlinPlatform) { 7 | x1(KotlinPlatform.Android, KotlinPlatform.Apple, KotlinPlatform.Jvm, KotlinPlatform.Js), 8 | x1_5(KotlinPlatform.Android), 9 | x2(KotlinPlatform.Android, KotlinPlatform.Apple), 10 | x3(KotlinPlatform.Android, KotlinPlatform.Apple), 11 | x4(KotlinPlatform.Android); 12 | } 13 | 14 | internal val ImageScale.androidName: String 15 | get() = when (this) { 16 | ImageScale.x1 -> "mdpi" 17 | ImageScale.x1_5 -> "hdpi" 18 | ImageScale.x2 -> "xhdpi" 19 | ImageScale.x3 -> "xxhdpi" 20 | ImageScale.x4 -> "xxxhdpi" 21 | } 22 | 23 | internal operator fun Int.times(scale: ImageScale): Int = 24 | when (scale) { 25 | ImageScale.x1 -> this 26 | ImageScale.x1_5 -> (this * 1.5).toInt() 27 | ImageScale.x2 -> this * 2 28 | ImageScale.x3 -> this * 3 29 | ImageScale.x4 -> this * 4 30 | } -------------------------------------------------------------------------------- /gradle-plugin/src/main/java/io/github/skeptick/libres/plugin/images/declarations/Files.kt: -------------------------------------------------------------------------------- 1 | @file:Suppress("FunctionName") 2 | 3 | package io.github.skeptick.libres.plugin.images.declarations 4 | 5 | import com.squareup.kotlinpoet.FileSpec 6 | import com.squareup.kotlinpoet.TypeSpec 7 | import io.github.skeptick.libres.plugin.KotlinPlatform 8 | import io.github.skeptick.libres.plugin.ResourcesPlugin 9 | 10 | internal fun ImagesObjectFile( 11 | packageName: String, 12 | imagesObjectBuilder: TypeSpec.Builder, 13 | platform: KotlinPlatform 14 | ): FileSpec { 15 | return imagesObjectBuilder.build().let { imagesObject -> 16 | FileSpec.builder(packageName, imagesObject.name!!) 17 | .addImport(ResourcesPlugin.IMAGES_PACKAGE_NAME, "Image") 18 | .apply { 19 | when (platform) { 20 | KotlinPlatform.Apple -> addImport(ResourcesPlugin.IMAGES_PACKAGE_NAME, "bundleWithName", "image") 21 | KotlinPlatform.Android -> addImport(packageName.substringBeforeLast('.'), "R") 22 | else -> Unit 23 | } 24 | } 25 | .addType(imagesObject) 26 | .build() 27 | } 28 | } -------------------------------------------------------------------------------- /gradle-plugin/src/main/java/io/github/skeptick/libres/plugin/ResourcesPluginExtension.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.plugin 2 | 3 | import io.github.skeptick.libres.plugin.strings.models.LanguageCode 4 | import java.io.Serializable 5 | 6 | open class ResourcesPluginExtension { 7 | var generatedClassName: String = "Res" 8 | var generateNamedArguments: Boolean = false 9 | var baseLocaleLanguageCode: String = "en" 10 | var camelCaseNamesForAppleFramework: Boolean = false 11 | } 12 | 13 | internal data class ResourcesSettings( 14 | val outputPackageName: String, 15 | val outputClassName: String, 16 | val stringsPackageName: String, 17 | val imagesPackageName: String 18 | ) : Serializable 19 | 20 | internal data class StringsSettings( 21 | val outputPackageName: String, 22 | val outputClassName: String, 23 | val generateNamedArguments: Boolean, 24 | val baseLocaleLanguageCode: LanguageCode, 25 | val camelCaseForApple: Boolean 26 | ) : Serializable 27 | 28 | internal data class ImagesSettings( 29 | val outputPackageName: String, 30 | val outputClassName: String, 31 | val camelCaseForApple: Boolean, 32 | val appleBundleName: String 33 | ) : Serializable -------------------------------------------------------------------------------- /libres-core/src/androidMain/kotlin/io/github/skeptick/libres/strings/PluralString.android.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.strings 2 | 3 | import android.icu.text.PluralRules 4 | import android.os.Build 5 | import libcore.icu.NativePluralRules 6 | import java.util.Locale 7 | 8 | public actual fun getPluralizedString(forms: PluralForms, languageCode: String, number: Int): String { 9 | return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { 10 | val rules = PluralRules.forLocale(Locale(languageCode)) 11 | val form = rules.select(number.toDouble()) 12 | forms[form] ?: error("Plural form '$form' not provided") 13 | } else { 14 | val rules = NativePluralRules.forLocale(Locale(languageCode)) 15 | val form = rules.quantityForInt(number).stringForQuantityCode() 16 | forms[form] ?: error("Plural form '$form' not provided") 17 | } 18 | } 19 | 20 | private fun Int.stringForQuantityCode(): String = 21 | when (this) { 22 | NativePluralRules.ZERO -> "zero" 23 | NativePluralRules.ONE -> "one" 24 | NativePluralRules.TWO -> "two" 25 | NativePluralRules.FEW -> "few" 26 | NativePluralRules.MANY -> "many" 27 | else -> "other" 28 | } -------------------------------------------------------------------------------- /gradle-plugin/src/main/java/io/github/skeptick/libres/plugin/common/declarations/Properties+Functions.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.plugin.common.declarations 2 | 3 | import com.squareup.kotlinpoet.AnnotationSpec 4 | import com.squareup.kotlinpoet.ClassName 5 | import com.squareup.kotlinpoet.PropertySpec 6 | import com.squareup.kotlinpoet.TypeSpec 7 | 8 | private val OptIn = ClassName("kotlin", "OptIn") 9 | private val ExperimentalObjCName = ClassName("kotlin.experimental", "ExperimentalObjCName") 10 | private val ObjCName = ClassName("kotlin.native", "ObjCName") 11 | 12 | internal fun TypeSpec.Builder.addExperimentalObjCNameAnnotation(condition: Boolean): TypeSpec.Builder { 13 | return if (!condition) this 14 | else addAnnotation( 15 | AnnotationSpec.builder(OptIn) 16 | .addMember("%T::class", ExperimentalObjCName) 17 | .build() 18 | ) 19 | } 20 | 21 | internal inline fun PropertySpec.Builder.addObjCNameAnnotation( 22 | condition: Boolean, 23 | nameBuilder: () -> String 24 | ): PropertySpec.Builder { 25 | return if (!condition) this 26 | else addAnnotation( 27 | AnnotationSpec.builder(ObjCName) 28 | .addMember("name = %S", nameBuilder()) 29 | .build() 30 | ) 31 | } -------------------------------------------------------------------------------- /libres-compose/src/iosMain/kotlin/io/github/skeptick/libres/compose/LibresImage+Skia.ios.kt: -------------------------------------------------------------------------------- 1 | @file:OptIn(ExperimentalForeignApi::class) 2 | 3 | package io.github.skeptick.libres.compose 4 | 5 | import androidx.compose.ui.unit.IntSize 6 | import io.github.skeptick.libres.images.Image 7 | import kotlinx.cinterop.ExperimentalForeignApi 8 | import kotlinx.cinterop.MemScope 9 | import platform.CoreGraphics.* 10 | import platform.UIKit.* 11 | 12 | private val DefaultImageRendererFormat = UIGraphicsImageRendererFormat().apply { 13 | scale = 1.0 14 | opaque = false 15 | } 16 | 17 | internal actual val Image.extension: String? 18 | get() = accessibilityValue?.substringAfterLast('.') 19 | 20 | internal actual val Image.intSize: IntSize 21 | get() = IntSize( 22 | width = CGImageGetWidth(CGImage).toInt(), 23 | height = CGImageGetHeight(CGImage).toInt() 24 | ) 25 | 26 | internal actual fun MemScope.libresImageToCGImage(image: Image, size: IntSize): CGImageRef { 27 | val width = size.width.toDouble() 28 | val height = size.height.toDouble() 29 | val cgSize = CGSizeMake(width, height) 30 | val newImage = UIGraphicsImageRenderer(cgSize, DefaultImageRendererFormat).imageWithActions { 31 | image.drawInRect(size.toCGRect()) 32 | } 33 | return newImage.CGImage ?: error("Cannot get CGImage from UIImage") 34 | } -------------------------------------------------------------------------------- /libres-core/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | id("multiplatform-setup") 3 | id("android-setup-plugin") 4 | id("com.vanniktech.maven.publish") 5 | } 6 | 7 | android { 8 | namespace = "io.github.skeptick.libres" 9 | } 10 | 11 | kotlin { 12 | tvosX64() 13 | tvosSimulatorArm64() 14 | tvosArm64() 15 | 16 | applyDefaultHierarchyTemplate() 17 | 18 | sourceSets { 19 | androidMain { 20 | dependencies { 21 | implementation(libs.androidx.core) 22 | compileOnly(libs.robovm) 23 | } 24 | } 25 | 26 | jvmMain { 27 | dependencies { 28 | implementation(libs.icu4j) 29 | } 30 | } 31 | 32 | wasmJsMain { 33 | dependencies { 34 | implementation(libs.browser) 35 | } 36 | } 37 | 38 | val webMain by creating { 39 | dependsOn(commonMain.get()) 40 | jsMain.get().dependsOn(this) 41 | wasmJsMain.get().dependsOn(this) 42 | } 43 | 44 | val appleAndWebMain by creating { 45 | dependsOn(commonMain.get()) 46 | appleMain.get().dependsOn(this) 47 | webMain.dependsOn(this) 48 | } 49 | 50 | val uikitMain by creating { 51 | dependsOn(appleMain.get()) 52 | iosMain.get().dependsOn(this) 53 | tvosMain.get().dependsOn(this) 54 | } 55 | } 56 | } -------------------------------------------------------------------------------- /gradle-plugin/src/main/java/io/github/skeptick/libres/plugin/strings/String+Extensions.kt: -------------------------------------------------------------------------------- 1 | @file:Suppress("NOTHING_TO_INLINE", "PrivatePropertyName") 2 | 3 | package io.github.skeptick.libres.plugin.strings 4 | 5 | private val NameRegex = "^[a-zA-Z][a-zA-Z0-9_]*$".toRegex() 6 | 7 | private val JavaFormatRegex = "(^|[^%])%([a-zA-Z]|[0-9]*\\$)".toRegex() 8 | 9 | private val TemplateFormatRegex = "\\$\\{([a-zA-Z][a-zA-Z0-9_]*)}".toRegex() 10 | 11 | internal inline fun String.hasJavaArguments() = contains(JavaFormatRegex) 12 | 13 | internal inline fun String.isValidName() = isNotBlank() && matches(NameRegex) 14 | 15 | internal inline fun String.unescapeXml() = replace("\\n", "\n") 16 | 17 | internal fun String.snakeCaseToCamelCase(startWithLower: Boolean = false) = 18 | split('_').joinToString("") { it.capitalizeUS() }.let { string -> 19 | if (startWithLower) string.decapitalizeUS() else string 20 | } 21 | 22 | internal fun String.extractInterpolationParametersNames() = 23 | TemplateFormatRegex.findAll(this).toList().map { result -> 24 | result.groupValues[1] 25 | } 26 | 27 | internal fun String.replaceNamedArguments(formatter: (index: Int, name: String) -> String): String { 28 | var index = 1 29 | return replace(TemplateFormatRegex) { formatter(index++, it.groupValues[1]) } 30 | } 31 | 32 | internal fun String.capitalizeUS() = replaceFirstChar { it.titlecase() } 33 | 34 | internal fun String.decapitalizeUS() = replaceFirstChar { it.lowercase() } -------------------------------------------------------------------------------- /gradle-plugin/src/main/java/io/github/skeptick/libres/plugin/LibresResourcesGenerationTask.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.plugin 2 | 3 | import org.gradle.api.DefaultTask 4 | import org.gradle.api.tasks.CacheableTask 5 | import org.gradle.api.tasks.Input 6 | import org.gradle.api.tasks.OutputDirectory 7 | import org.gradle.api.tasks.TaskAction 8 | import io.github.skeptick.libres.plugin.common.declarations.ResourcesFile 9 | import io.github.skeptick.libres.plugin.common.declarations.ResourcesObject 10 | import io.github.skeptick.libres.plugin.common.declarations.saveToDirectory 11 | import io.github.skeptick.libres.plugin.common.extensions.deleteFilesInDirectory 12 | import java.io.File 13 | 14 | @CacheableTask 15 | abstract class LibresResourcesGenerationTask : DefaultTask() { 16 | 17 | @get:Input 18 | internal abstract var settings: ResourcesSettings 19 | 20 | @get:OutputDirectory 21 | internal abstract var outputDirectory: File 22 | 23 | @TaskAction 24 | fun apply() { 25 | val className = settings.outputClassName 26 | val packageName = settings.outputPackageName 27 | val stringsPackageName = settings.stringsPackageName 28 | val imagesPackageName = settings.imagesPackageName 29 | 30 | outputDirectory.deleteFilesInDirectory() 31 | val resourcesObjectTypeSpec = ResourcesObject(className, stringsPackageName, imagesPackageName) 32 | val resourcesFileSpec = ResourcesFile(packageName, className, resourcesObjectTypeSpec) 33 | resourcesFileSpec.saveToDirectory(outputDirectory) 34 | } 35 | 36 | } -------------------------------------------------------------------------------- /gradle-plugin/src/main/java/io/github/skeptick/libres/plugin/strings/declarations/Files.kt: -------------------------------------------------------------------------------- 1 | @file:Suppress("FunctionName") 2 | 3 | package io.github.skeptick.libres.plugin.strings.declarations 4 | 5 | import com.squareup.kotlinpoet.FileSpec 6 | import com.squareup.kotlinpoet.TypeSpec 7 | import io.github.skeptick.libres.plugin.ResourcesPlugin 8 | 9 | internal fun StringsInterfaceFile( 10 | packageName: String, 11 | stringsInterfaceBuilder: TypeSpec.Builder 12 | ): FileSpec { 13 | return FileSpec.builder(packageName, "Strings") 14 | .addType(stringsInterfaceBuilder.build()) 15 | .build() 16 | } 17 | 18 | internal fun StringsObjectFile( 19 | packageName: String, 20 | stringsObjectBuilder: TypeSpec.Builder 21 | ): FileSpec { 22 | return stringsObjectBuilder.build().let { stringsObject -> 23 | FileSpec.builder(packageName, stringsObject.name!!) 24 | .addImport(ResourcesPlugin.STRINGS_PACKAGE_NAME, "getCurrentLanguageCode", "PluralForms") 25 | .addType(stringsObject) 26 | .build() 27 | } 28 | } 29 | 30 | internal fun FormattedClassesFile( 31 | packageName: String, 32 | classes: Iterable 33 | ): FileSpec { 34 | return FileSpec.builder(packageName, "FormattedClasses") 35 | .addImport(ResourcesPlugin.STRINGS_PACKAGE_NAME, "formatString", "getPluralizedString") 36 | .addTypes(classes) 37 | .build() 38 | } 39 | 40 | private fun FileSpec.Builder.addTypes(types: Iterable): FileSpec.Builder { 41 | for (type in types) addType(type.build()) 42 | return this 43 | } 44 | -------------------------------------------------------------------------------- /gradle-plugin/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | kotlin("jvm") 3 | id("java-gradle-plugin") 4 | id("com.vanniktech.maven.publish") 5 | } 6 | 7 | version = property("VERSION_NAME").toString() 8 | 9 | kotlin { 10 | jvmToolchain(17) 11 | } 12 | 13 | dependencies { 14 | implementation(projects.libresCore) 15 | implementation(gradleApi()) 16 | implementation(libs.jackson.xml) 17 | implementation(libs.jackson.kotlin) 18 | implementation(libs.kotlinpoet) 19 | implementation(libs.javacv) 20 | compileOnly(libs.android.sdk.tools) 21 | compileOnly(libs.plugin.kotlin) 22 | compileOnly(libs.plugin.android) 23 | testImplementation(libs.junit) 24 | } 25 | 26 | gradlePlugin { 27 | plugins { 28 | create("libres-plugin") { 29 | id = "io.github.skeptick.libres" 30 | implementationClass = "io.github.skeptick.libres.plugin.ResourcesPlugin" 31 | } 32 | } 33 | } 34 | 35 | val libresVersion = tasks.register("libresVersion") { 36 | val outputDir = file("generated") 37 | inputs.property("version", version) 38 | outputs.dir(outputDir) 39 | 40 | doFirst { 41 | val text = """ 42 | // Generated file. Do not edit! 43 | package io.github.skeptick.libres 44 | 45 | val VERSION = "${project.version}" 46 | """.trimIndent() 47 | 48 | val versionFile = file("$outputDir/io/github/skeptick/libres/Version.kt") 49 | versionFile.parentFile.mkdirs() 50 | versionFile.writeText(text) 51 | } 52 | } 53 | 54 | sourceSets.main.configure { 55 | kotlin.srcDir(libresVersion) 56 | } -------------------------------------------------------------------------------- /gradle-plugin/src/main/java/io/github/skeptick/libres/plugin/images/ImagesTypeSpecsBuilder.kt: -------------------------------------------------------------------------------- 1 | @file:Suppress("CanBeParameter") 2 | 3 | package io.github.skeptick.libres.plugin.images 4 | 5 | import io.github.skeptick.libres.plugin.ImagesSettings 6 | import io.github.skeptick.libres.plugin.KotlinPlatform 7 | import io.github.skeptick.libres.plugin.common.declarations.saveToDirectory 8 | import io.github.skeptick.libres.plugin.images.declarations.ImagesObject 9 | import io.github.skeptick.libres.plugin.images.declarations.ImagesObjectFile 10 | import io.github.skeptick.libres.plugin.images.declarations.appendImage 11 | import io.github.skeptick.libres.plugin.images.models.ImageProps 12 | import java.io.File 13 | 14 | internal class ImagesTypeSpecsBuilder( 15 | private val settings: ImagesSettings, 16 | private val platforms: Set 17 | ) { 18 | 19 | private val packageName = settings.outputPackageName 20 | private val className = settings.outputClassName 21 | private val camelCaseForApple = settings.camelCaseForApple 22 | private val appleBundleName = settings.appleBundleName 23 | private val hasCommon = KotlinPlatform.Common in platforms 24 | 25 | private var imagesObjects = platforms.associateWith { 26 | ImagesObject(className, it, hasCommon, appleBundleName, camelCaseForApple) 27 | } 28 | 29 | fun appendImage(imageProps: ImageProps) { 30 | imagesObjects.forEach { (platform, imagesObject) -> 31 | imagesObject.appendImage(imageProps, platform, hasCommon, camelCaseForApple) 32 | } 33 | } 34 | 35 | fun save(directories: Map) { 36 | imagesObjects.forEach { (platform, imagesObject) -> 37 | val directory = directories.getValue(platform) 38 | ImagesObjectFile(packageName, imagesObject, platform).saveToDirectory(directory) 39 | } 40 | } 41 | 42 | } -------------------------------------------------------------------------------- /gradle/libs.versions.toml: -------------------------------------------------------------------------------- 1 | [versions] 2 | plugin-android = "8.7.3" 3 | plugin-publish-maven = "0.31.0" 4 | 5 | kotlin = "2.1.20" 6 | compose-jb = "1.8.0-beta01" 7 | coroutines = "1.10.2" 8 | browser = "0.3" 9 | androidx-core = "1.15.0" 10 | robovm = "1.0.0" 11 | icu4j = "77.1" 12 | jackson = "2.18.3" 13 | kotlinpoet = "2.1.0" 14 | javacv = "1.5.11" 15 | android-sdk-tools = "31.9.1" 16 | 17 | junit = "4.13.2" 18 | 19 | [libraries] 20 | plugin-android = { module = "com.android.tools.build:gradle", version.ref = "plugin-android" } 21 | plugin-kotlin = { module = "org.jetbrains.kotlin:kotlin-gradle-plugin", version.ref = "kotlin" } 22 | plugin-publish-maven = { module = "com.vanniktech:gradle-maven-publish-plugin", version.ref = "plugin-publish-maven" } 23 | plugin-compose = { module = "org.jetbrains.compose:compose-gradle-plugin", version.ref = "compose-jb" } 24 | plugin-composeCompiler = { module = "org.jetbrains.kotlin:compose-compiler-gradle-plugin", version.ref = "kotlin" } 25 | 26 | coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "coroutines" } 27 | browser = { module = "org.jetbrains.kotlinx:kotlinx-browser", version.ref = "browser" } 28 | androidx-core = { module = "androidx.core:core", version.ref = "androidx-core" } 29 | robovm = { module = "org.robovm:robovm-rt", version.ref = "robovm" } 30 | icu4j = { module = "com.ibm.icu:icu4j", version.ref = "icu4j" } 31 | jackson-xml = { module = "com.fasterxml.jackson.dataformat:jackson-dataformat-xml", version.ref = "jackson" } 32 | jackson-kotlin = { module = "com.fasterxml.jackson.module:jackson-module-kotlin", version.ref = "jackson" } 33 | kotlinpoet = { module = "com.squareup:kotlinpoet", version.ref = "kotlinpoet" } 34 | javacv = { module = "org.bytedeco:javacv-platform", version.ref = "javacv" } 35 | android-sdk-tools = { module = "com.android.tools:sdk-common", version.ref = "android-sdk-tools" } 36 | 37 | junit = { module = "junit:junit", version.ref = "junit" } -------------------------------------------------------------------------------- /gradle-plugin/src/test/kotlin/io/github/skeptick/libres/plugin/HasJavaArgumentsTest.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.plugin 2 | 3 | import io.github.skeptick.libres.plugin.strings.hasJavaArguments 4 | import org.junit.Test 5 | 6 | class HasJavaArgumentsTest { 7 | 8 | /* region 'true' cases */ 9 | 10 | @Test 11 | fun `true with percent symbol for formatting`() { 12 | val string = "Скидки до %d от поставщиков на бренды для профи" 13 | assert(string.hasJavaArguments()) 14 | } 15 | @Test 16 | fun `true with percent symbol for formatting and double-percent`() { 17 | val string = "Скидки до 50%% от поставщиков на бренды для %s" 18 | assert(string.hasJavaArguments()) 19 | } 20 | 21 | @Test 22 | fun `true with percent symbol for formatting (numbered) - case 1`() { 23 | val string = "Hello, %1\$s! You have %2\$d new messages." 24 | assert(string.hasJavaArguments()) 25 | } 26 | 27 | @Test 28 | fun `true with percent symbol for formatting (numbered) - case 2 `() { 29 | val string = "Hello, %10\$s!" 30 | assert(string.hasJavaArguments()) 31 | } 32 | 33 | /* endregion */ 34 | 35 | /* region 'false' cases */ 36 | 37 | @Test 38 | fun `false with single percent symbol`() { 39 | val string = "Скидки до 50% от поставщиков на бренды для профи" 40 | assert(!string.hasJavaArguments()) 41 | } 42 | 43 | @Test 44 | fun `false with double-percent`() { 45 | val string = "Скидки до 50%% от поставщиков на бренды для профи" 46 | assert(!string.hasJavaArguments()) 47 | } 48 | 49 | @Test 50 | fun `false without both double-percent and single percent symbol`() { 51 | val string = "Скидки до 50 процентов от поставщиков на бренды для профи" 52 | assert(!string.hasJavaArguments()) 53 | } 54 | 55 | @Test 56 | fun `false with percent symbol and next number symbol`() { 57 | val string = "Hello, %1" 58 | assert(!string.hasJavaArguments()) 59 | } 60 | 61 | /* endregion */ 62 | } -------------------------------------------------------------------------------- /gradle-plugin/src/main/java/io/github/skeptick/libres/plugin/images/models/ImageSetContents.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.plugin.images.models 2 | 3 | import com.fasterxml.jackson.annotation.JsonProperty 4 | 5 | internal data class ImageSetContents( 6 | val images: List, 7 | val info: Info = Info(), 8 | val properties: Properties 9 | ) { 10 | 11 | @Suppress("EnumEntryName") 12 | enum class ImageScale { 13 | @JsonProperty("1x") x1, 14 | @JsonProperty("2x") x2, 15 | @JsonProperty("3x") x3 16 | } 17 | 18 | enum class VectorRenderingType { 19 | @JsonProperty("original") Original, 20 | @JsonProperty("template") Template 21 | } 22 | 23 | data class Image( 24 | val filename: String, 25 | val scale: ImageScale? = null, 26 | val idiom: String = "universal" 27 | ) 28 | 29 | data class Info( 30 | val author: String = "xcode", 31 | val version: Int = 1 32 | ) 33 | 34 | data class Properties( 35 | @JsonProperty("preserves-vector-representation") val preserveVectorRepresentation: Boolean?, 36 | @JsonProperty("template-rendering-intent") val templateRenderingIntent: VectorRenderingType 37 | ) 38 | 39 | } 40 | 41 | internal fun ImageProps.toImageSetContents() = 42 | ImageSetContents( 43 | images = when (targetSize) { 44 | null -> listOf( 45 | ImageSetContents.Image(filename = "$name.$extension") 46 | ) 47 | else -> ImageSetContents.ImageScale.values().map { 48 | ImageSetContents.Image(filename = "${this.name}_${it.name}.$extension", scale = it) 49 | } 50 | }, 51 | properties = ImageSetContents.Properties( 52 | preserveVectorRepresentation = if (isVector) true else null, 53 | templateRenderingIntent = when (isTintable) { 54 | true -> ImageSetContents.VectorRenderingType.Template 55 | false -> ImageSetContents.VectorRenderingType.Original 56 | } 57 | ) 58 | ) -------------------------------------------------------------------------------- /libres-compose/src/appleMain/kotlin/io/github/skeptick/libres/compose/LibresImage+Skia.apple.kt: -------------------------------------------------------------------------------- 1 | @file:OptIn(ExperimentalForeignApi::class) 2 | 3 | package io.github.skeptick.libres.compose 4 | 5 | import androidx.compose.ui.unit.IntSize 6 | import io.github.skeptick.libres.images.Image as LibresImage 7 | import kotlinx.cinterop.* 8 | import org.jetbrains.skia.ColorAlphaType 9 | import org.jetbrains.skia.ColorType 10 | import org.jetbrains.skia.ImageInfo 11 | import org.jetbrains.skia.Image as SkiaImage 12 | import platform.CoreGraphics.* 13 | 14 | internal expect val LibresImage.extension: String? 15 | 16 | internal expect val LibresImage.intSize: IntSize 17 | 18 | internal expect fun MemScope.libresImageToCGImage(image: LibresImage, size: IntSize): CGImageRef 19 | 20 | internal fun LibresImage.toSkiaImage(size: IntSize = intSize): SkiaImage = memScoped { 21 | val imageRef = libresImageToCGImage(image = this@toSkiaImage, size) 22 | val width = size.width.toULong() 23 | val height = size.height.toULong() 24 | val bytesPerComponent = 8UL 25 | val bytesPerRow = width * 4UL 26 | val dataLength = (bytesPerRow * height).toInt() 27 | val rawData = allocArray(dataLength) 28 | 29 | val context = CGBitmapContextCreate( 30 | data = rawData, 31 | width = width, 32 | height = height, 33 | bitsPerComponent = bytesPerComponent, 34 | bytesPerRow = bytesPerRow, 35 | space = CGColorSpaceCreateDeviceRGB(), 36 | bitmapInfo = CGImageAlphaInfo.kCGImageAlphaPremultipliedLast.value 37 | ) 38 | CGContextDrawImage(context, size.toCGRect(), imageRef) 39 | CGContextRelease(context) 40 | 41 | return SkiaImage.makeRaster( 42 | imageInfo = ImageInfo( 43 | width = size.width, 44 | height = size.height, 45 | colorType = ColorType.RGBA_8888, 46 | alphaType = ColorAlphaType.PREMUL 47 | ), 48 | bytes = rawData.readBytes(dataLength), 49 | rowBytes = bytesPerRow.toInt() 50 | ) 51 | } 52 | 53 | internal fun IntSize.toCGRect() = CGRectMake(0.0, 0.0, width.toDouble(), height.toDouble()) -------------------------------------------------------------------------------- /libres-compose/src/appleMain/kotlin/io/github/skeptick/libres/compose/AppleSvgPainter.kt: -------------------------------------------------------------------------------- 1 | @file:Suppress("NOTHING_TO_INLINE") 2 | 3 | package io.github.skeptick.libres.compose 4 | 5 | import androidx.compose.ui.geometry.Size 6 | import androidx.compose.ui.geometry.isSpecified 7 | import androidx.compose.ui.graphics.ColorFilter 8 | import androidx.compose.ui.graphics.ImageBitmap 9 | import androidx.compose.ui.graphics.drawscope.DrawScope 10 | import androidx.compose.ui.graphics.painter.Painter 11 | import androidx.compose.ui.graphics.toComposeImageBitmap 12 | import androidx.compose.ui.unit.IntSize 13 | import androidx.compose.ui.unit.toSize 14 | import io.github.skeptick.libres.images.Image 15 | import kotlin.math.ceil 16 | 17 | internal class AppleSvgPainter(private val sourceImage: Image) : Painter() { 18 | 19 | private val srcSize: Size = sourceImage.intSize.takeIfNotNull()?.toSize() ?: Size.Unspecified 20 | 21 | private lateinit var cachedImage: ImageBitmap 22 | private var cachedSize: Size = Size.Unspecified 23 | 24 | override val intrinsicSize = if (srcSize.isSpecified) srcSize else Size.Unspecified 25 | 26 | private var alpha: Float = 1.0f 27 | 28 | private var colorFilter: ColorFilter? = null 29 | 30 | override fun applyAlpha(alpha: Float): Boolean { 31 | this.alpha = alpha 32 | return true 33 | } 34 | 35 | override fun applyColorFilter(colorFilter: ColorFilter?): Boolean { 36 | this.colorFilter = colorFilter 37 | return true 38 | } 39 | 40 | override fun DrawScope.onDraw() { 41 | if (cachedSize != size) prepareImage() 42 | drawImage(cachedImage, srcSize = cachedSize.toIntSize(), alpha = alpha, colorFilter = colorFilter) 43 | } 44 | 45 | private fun DrawScope.prepareImage() { 46 | val skiaImage = sourceImage.toSkiaImage(size.toIntSize()) 47 | cachedImage = skiaImage.toComposeImageBitmap() 48 | cachedSize = size 49 | cachedImage.prepareToDraw() 50 | } 51 | 52 | } 53 | 54 | private inline fun Size.toIntSize() = IntSize(ceil(width).toInt(), ceil(height).toInt()) 55 | 56 | private fun IntSize.takeIfNotNull() = takeIf { it.width != 0 && it.height != 0 } -------------------------------------------------------------------------------- /gradle-plugin/src/main/java/io/github/skeptick/libres/plugin/common/project/Project+IosBundle.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.plugin.common.project 2 | 3 | import org.gradle.api.Project 4 | import java.io.File 5 | import java.nio.file.Files 6 | import java.nio.file.Path 7 | import kotlin.io.path.Path 8 | import kotlin.io.path.pathString 9 | 10 | private const val appleBundlesDirectory = "generated/libres/apple/libres-bundles" 11 | 12 | internal fun Project.appendAppleBundles(currentResources: String): String { 13 | File(buildDirectory, appleBundlesDirectory).mkdirs() 14 | val path = "'${buildDirectory.relativeTo(projectDir).path}/$appleBundlesDirectory'" 15 | return if (currentResources.isBlank() || currentResources.trim().matches(Regex("^\\[\\s*]$"))) { 16 | "[$path]" 17 | } else { 18 | val existPaths = currentResources.substringAfter('[').substringBeforeLast(']') 19 | "[$existPaths, $path]" 20 | } 21 | } 22 | 23 | internal fun createBundlesSymLinks(umbrella: Project, exports: List) { 24 | val umbrellaBundleName = umbrella.appleBundleName 25 | val bundlesDir = Path(umbrella.buildDirectory.absolutePath, appleBundlesDirectory) 26 | val umbrellaBundle = Path(bundlesDir.pathString, "${umbrellaBundleName}.bundle") 27 | if (!Files.exists(umbrellaBundle)) Files.createDirectories(umbrellaBundle) 28 | exports.forEach { addSymlinkToBundle(bundlesDir = bundlesDir, export = it) } 29 | } 30 | 31 | internal val Project.appleBundleName: String 32 | get() = "Libres" + path.split(":", "-", "_").joinToString("") { partOfName -> 33 | partOfName.replaceFirstChar { it.titlecase() } 34 | } 35 | 36 | private fun addSymlinkToBundle(bundlesDir: Path, export: Project) { 37 | val bundleName = export.appleBundleName 38 | val target = Path(export.buildDirectory.absolutePath, appleBundlesDirectory, "${bundleName}.bundle") 39 | val link = Path(bundlesDir.pathString, "${bundleName}.bundle") 40 | if (!Files.exists(target)) Files.createDirectories(target) 41 | if (!Files.exists(link)) Files.createSymbolicLink(link, target) 42 | } 43 | 44 | private val Project.buildDirectory: File get() = layout.buildDirectory.asFile.get() -------------------------------------------------------------------------------- /libres-compose/src/jsMain/kotlin/io/github/skeptick/libres/compose/PainterResource.js.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.compose 2 | 3 | import androidx.compose.runtime.Composable 4 | import androidx.compose.runtime.getValue 5 | import androidx.compose.runtime.produceState 6 | import androidx.compose.runtime.remember 7 | import androidx.compose.ui.graphics.Color 8 | import androidx.compose.ui.graphics.painter.BitmapPainter 9 | import androidx.compose.ui.graphics.painter.ColorPainter 10 | import androidx.compose.ui.graphics.painter.Painter 11 | import androidx.compose.ui.graphics.toComposeImageBitmap 12 | import androidx.compose.ui.platform.LocalDensity 13 | import io.github.skeptick.libres.images.Image 14 | import kotlinx.browser.window 15 | import kotlinx.coroutines.await 16 | import org.jetbrains.skia.Data 17 | import org.jetbrains.skia.svg.SVGDOM 18 | import org.jetbrains.skia.Image as SkiaImage 19 | import org.khronos.webgl.Int8Array 20 | import org.w3c.fetch.Response 21 | 22 | @Composable 23 | public actual fun painterResource(image: Image): Painter { 24 | val state by produceState(initialValue = null, image) { 25 | val response = window.fetch(image).await() 26 | if (response.ok) value = response.byteArray() 27 | } 28 | 29 | return when (val bytes = state) { 30 | null -> ColorPainter(color = Color.Transparent) 31 | else -> when (image.substringAfterLast(".")) { 32 | "svg" -> rememberSvgResource(image, bytes) 33 | else -> rememberBitmapResource(image, bytes) 34 | } 35 | } 36 | } 37 | 38 | @Composable 39 | private fun rememberSvgResource(name: String, bytes: ByteArray): Painter { 40 | val density = LocalDensity.current 41 | return remember(name, density) { 42 | val data = Data.makeFromBytes(bytes) 43 | WebSvgPainter(SVGDOM(data), density) 44 | } 45 | } 46 | 47 | @Composable 48 | private fun rememberBitmapResource(name: String, bytes: ByteArray): Painter { 49 | return remember(name) { 50 | val skiaImage = SkiaImage.makeFromEncoded(bytes = bytes) 51 | BitmapPainter(image = skiaImage.toComposeImageBitmap()) 52 | } 53 | } 54 | 55 | private suspend fun Response.byteArray() = arrayBuffer().await().let(::Int8Array).unsafeCast() -------------------------------------------------------------------------------- /docs/LOCALIZATION.md: -------------------------------------------------------------------------------- 1 | ## Changing Localization 2 | 3 | As mentioned in the [README](../README.md#strings), the language to which the strings belong 4 | is indicated in the file name before the extension (e.g. `strings_en.xml`). 5 | 6 | During the application runtime, the localization selection is based on the system settings 7 | and changing the language should also be done at the application instance level. 8 | 9 | Examples of setting English language for all supported platforms: 10 | 11 | **Android & JVM** 12 | ```kotlin 13 | Locale.setDefault(Locale("en")) 14 | ``` 15 | > **Note** 16 | > For Android, don't forget to update the configuration as well. 17 | 18 | **iOS & MacOS** 19 | ```swift 20 | UserDefaults.standard.set(["en"], forKey: "AppleLanguages") 21 | ``` 22 | > **Note** 23 | > All used localizations must be declared in XCode project settings. 24 | 25 | **JS** 26 | 27 | In JS, there is no such possibility to change the language (without changing the language in the operating system or browser), 28 | so the best option is to use `LibresSettings`: 29 | 30 | ```kotlin 31 | LibresSettings.languageCode = "en" 32 | ``` 33 | 34 | This solution will also work for all other platforms but remember that this setting applies 35 | only to the selection of localization for strings in Libres, and some 36 | system components may remain untranslated. 37 | > **Warning** 38 | > The value in `LibresSettings.languageCode` has higher priority than system settings. 39 | 40 | ## Plural rules 41 | 42 | In Android, the SDK solution is used to determine the plural form, 43 | in JVM 3rd-party library is used. But in Apple this API is closed and in JS it's completely absent, 44 | so to avoid burdening the library with heavy solutions, "out of the box" only rules are provided 45 | for [some languages](../libres-core/src/appleAndJsMain/kotlin/io/github/skeptick/libres/strings/PluralRules.kt). 46 | 47 | You can create a Pull Request with the required languages or define these values at runtime: 48 | 49 | ```kotlin 50 | import io.github.skeptick.libres.strings.PluralRules 51 | import io.github.skeptick.libres.strings.PluralForm 52 | 53 | PluralRules["en"] = PluralRule { number -> 54 | when (number) { 55 | 1 -> PluralForm.One 56 | else -> PluralForm.Other 57 | } 58 | } 59 | ``` 60 | 61 | When defining rules you can refer to 62 | [this document](https://unicode-org.github.io/cldr-staging/charts/37/supplemental/language_plural_rules.html). -------------------------------------------------------------------------------- /libres-compose/src/wasmJsMain/kotlin/io/github/skeptick/libres/compose/PainterResource.wasmJs.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.compose 2 | 3 | import androidx.compose.runtime.Composable 4 | import androidx.compose.runtime.getValue 5 | import androidx.compose.runtime.produceState 6 | import androidx.compose.runtime.remember 7 | import androidx.compose.ui.graphics.Color 8 | import androidx.compose.ui.graphics.painter.BitmapPainter 9 | import androidx.compose.ui.graphics.painter.ColorPainter 10 | import androidx.compose.ui.graphics.painter.Painter 11 | import androidx.compose.ui.graphics.toComposeImageBitmap 12 | import androidx.compose.ui.platform.LocalDensity 13 | import io.github.skeptick.libres.images.Image 14 | import kotlinx.browser.window 15 | import kotlinx.coroutines.await 16 | import org.jetbrains.skia.Data 17 | import org.jetbrains.skia.svg.SVGDOM 18 | import org.khronos.webgl.ArrayBuffer 19 | import org.jetbrains.skia.Image as SkiaImage 20 | import org.khronos.webgl.Int8Array 21 | import org.khronos.webgl.get 22 | import org.w3c.fetch.Response 23 | 24 | @Composable 25 | public actual fun painterResource(image: Image): Painter { 26 | val state by produceState(initialValue = null, image) { 27 | val response = window.fetch(image).await() 28 | if (response.ok) value = response.byteArray() 29 | } 30 | 31 | return when (val bytes = state) { 32 | null -> ColorPainter(color = Color.Transparent) 33 | else -> when (image.substringAfterLast(".")) { 34 | "svg" -> rememberSvgResource(image, bytes) 35 | else -> rememberBitmapResource(image, bytes) 36 | } 37 | } 38 | } 39 | 40 | @Composable 41 | private fun rememberSvgResource(name: String, bytes: ByteArray): Painter { 42 | val density = LocalDensity.current 43 | return remember(name, density) { 44 | val data = Data.makeFromBytes(bytes) 45 | WebSvgPainter(SVGDOM(data), density) 46 | } 47 | } 48 | 49 | @Composable 50 | private fun rememberBitmapResource(name: String, bytes: ByteArray): Painter { 51 | return remember(name) { 52 | val skiaImage = SkiaImage.makeFromEncoded(bytes = bytes) 53 | BitmapPainter(image = skiaImage.toComposeImageBitmap()) 54 | } 55 | } 56 | 57 | private suspend fun Response.byteArray(): ByteArray { 58 | val int8Array = arrayBuffer().await().let(::Int8Array) 59 | return ByteArray(int8Array.length) { index -> int8Array[index] } 60 | } -------------------------------------------------------------------------------- /libres-core/src/appleAndWebMain/kotlin/io/github/skeptick/libres/strings/PluralRules.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.strings 2 | 3 | import io.github.skeptick.libres.strings.PluralForm.* 4 | 5 | public fun interface PluralRule { 6 | public fun getForm(number: Int): PluralForm 7 | } 8 | 9 | public enum class PluralForm(internal val formName: String) { 10 | Zero("zero"), 11 | One("one"), 12 | Two("two"), 13 | Few("few"), 14 | Many("many"), 15 | Other("other") 16 | } 17 | 18 | public object PluralRules { 19 | 20 | private val custom = mutableMapOf() 21 | 22 | private val English = PluralRule { number -> 23 | when (number) { 24 | 1 -> One 25 | else -> Other 26 | } 27 | } 28 | 29 | private val Russian = PluralRule { number -> 30 | when (number % 100) { 31 | 11, 12, 13, 14 -> Many 32 | else -> when (number % 10) { 33 | 1 -> One 34 | 2, 3, 4 -> Few 35 | else -> Many 36 | } 37 | } 38 | } 39 | 40 | private val Ukrainian = PluralRule { number -> 41 | when (number % 100) { 42 | 11, 12, 13, 14 -> Many 43 | else -> when (number % 10) { 44 | 1 -> One 45 | 2, 3, 4 -> Few 46 | else -> Many 47 | } 48 | } 49 | } 50 | 51 | private val Kazakh = PluralRule { number -> 52 | when (number) { 53 | 1 -> One 54 | else -> Other 55 | } 56 | } 57 | 58 | private val French = PluralRule { number -> 59 | when (number) { 60 | 0, 1 -> One 61 | else -> Other 62 | } 63 | } 64 | 65 | public operator fun set(languageCode: String, value: PluralRule) { 66 | custom[languageCode] = value 67 | } 68 | 69 | public operator fun get(languageCode: String): PluralRule { 70 | return when (languageCode) { 71 | "en" -> English 72 | "ru" -> Russian 73 | "uk" -> Ukrainian 74 | "kk" -> Kazakh 75 | "fr" -> French 76 | else -> custom[languageCode] ?: error("Plural rule for '$languageCode' not provided") 77 | } 78 | } 79 | 80 | public operator fun plus(value: Pair) { 81 | custom[value.first] = value.second 82 | } 83 | 84 | public operator fun plusAssign(map: Map) { 85 | custom += map 86 | } 87 | 88 | } -------------------------------------------------------------------------------- /gradle-plugin/src/main/java/io/github/skeptick/libres/plugin/LibresStringGenerationTask.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.plugin 2 | 3 | import org.gradle.api.DefaultTask 4 | import org.gradle.api.file.FileCollection 5 | import org.gradle.api.tasks.* 6 | import io.github.skeptick.libres.plugin.common.declarations.saveToDirectory 7 | import io.github.skeptick.libres.plugin.common.extensions.deleteFilesInDirectory 8 | import io.github.skeptick.libres.plugin.strings.* 9 | import io.github.skeptick.libres.plugin.strings.declarations.* 10 | import io.github.skeptick.libres.plugin.strings.models.* 11 | import java.io.File 12 | 13 | @CacheableTask 14 | abstract class LibresStringGenerationTask : DefaultTask() { 15 | 16 | @get:Input 17 | internal abstract var settings: StringsSettings 18 | 19 | @get:InputFiles 20 | @get:PathSensitive(PathSensitivity.RELATIVE) 21 | internal abstract var inputDirectory: FileCollection 22 | 23 | @get:OutputDirectory 24 | internal abstract var outputDirectory: File 25 | 26 | @TaskAction 27 | fun apply() { 28 | inputDirectory.files 29 | .takeIf { files -> files.isNotEmpty() } 30 | ?.let { files -> parseStringResources(files, settings.baseLocaleLanguageCode) } 31 | ?.takeIf { resources -> resources.getValue(settings.baseLocaleLanguageCode).isNotEmpty() } 32 | ?.let { resources -> buildResources(resources) } 33 | ?: buildEmptyResources() 34 | } 35 | 36 | private fun buildResources(resources: Map>) { 37 | val builder = StringTypeSpecsBuilder(settings, resources.keys) 38 | val resourceByLanguageCodes = resources.mapValues { it.value.associateBy(TextResource::name) } 39 | 40 | resources.getValue(settings.baseLocaleLanguageCode).forEach { baseResource -> 41 | builder.appendResource( 42 | baseResource = baseResource, 43 | localizedResources = resources.mapValues { 44 | resourceByLanguageCodes[it.key]?.get(baseResource.name) 45 | } 46 | ) 47 | } 48 | 49 | outputDirectory.deleteFilesInDirectory() 50 | builder.save(outputDirectory) 51 | } 52 | 53 | private fun buildEmptyResources() { 54 | val stringObjectTypeSpec = EmptyStringObject(settings.outputClassName) 55 | val stringsFileSpec = StringsObjectFile(settings.outputPackageName, stringObjectTypeSpec) 56 | outputDirectory.deleteFilesInDirectory() 57 | stringsFileSpec.saveToDirectory(outputDirectory) 58 | } 59 | 60 | } -------------------------------------------------------------------------------- /gradle-plugin/src/main/java/io/github/skeptick/libres/plugin/LibresBundleGenerationTask.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.plugin 2 | 3 | import io.github.skeptick.libres.plugin.common.extensions.deleteFilesInDirectory 4 | import org.gradle.api.DefaultTask 5 | import org.gradle.api.tasks.* 6 | import java.io.File 7 | 8 | @CacheableTask 9 | abstract class LibresBundleGenerationTask : DefaultTask() { 10 | 11 | @get:Input 12 | internal abstract var bundleName: String 13 | 14 | @get:InputDirectory 15 | @get:PathSensitive(PathSensitivity.ABSOLUTE) 16 | @get:Optional 17 | internal abstract var directoryToCompile: File? 18 | 19 | @get:InputFiles 20 | @get:PathSensitive(PathSensitivity.ABSOLUTE) 21 | internal abstract var filesToCopy: List 22 | 23 | @get:OutputDirectory 24 | @get:Optional 25 | internal abstract var outputDirectory: File? 26 | 27 | @TaskAction 28 | fun apply() { 29 | val directoryToCompile = directoryToCompile ?: return 30 | val outputDirectory = outputDirectory ?: return 31 | 32 | val bundleDirectory = File(outputDirectory, "$bundleName.bundle") 33 | bundleDirectory.mkdirs() 34 | bundleDirectory.deleteFilesInDirectory() 35 | 36 | ProcessBuilder( 37 | "xcrun", "actool", directoryToCompile.absolutePath, 38 | "--compile", bundleDirectory.absolutePath, 39 | "--output-format", "human-readable-text", 40 | "--notices", "--warnings", 41 | "--platform", "iphoneos", 42 | "--minimum-deployment-target", "13.0", 43 | "--target-device", "iphone", 44 | "--compress-pngs" 45 | ).start().let { process -> 46 | if (process.waitFor() != 0) { 47 | val message1 = process.inputStream.bufferedReader().readText() 48 | val message2 = process.errorStream.bufferedReader().readText() 49 | val errorMessage = listOf(message1, message2).joinToString(".") 50 | logger.error("Error when compiling iOS resources: $errorMessage") 51 | } 52 | } 53 | 54 | val plist = File(bundleDirectory, "Info.plist") 55 | plist.writeText(InfoPlist(bundleName)) 56 | } 57 | 58 | private companion object { 59 | 60 | @Suppress("FunctionName") 61 | fun InfoPlist(bundleName: String) = """ 62 | 63 | 64 | 65 | 66 | CFBundleIdentifier 67 | $bundleName 68 | CFBundlePackageType 69 | BNDL 70 | 71 | 72 | """.trimIndent() 73 | 74 | } 75 | 76 | } -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /gradle-plugin/src/main/java/io/github/skeptick/libres/plugin/LibresImagesGenerationTask.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.plugin 2 | 3 | import org.gradle.api.DefaultTask 4 | import org.gradle.api.file.FileCollection 5 | import org.gradle.api.tasks.* 6 | import org.gradle.work.ChangeType 7 | import org.gradle.work.Incremental 8 | import org.gradle.work.InputChanges 9 | import io.github.skeptick.libres.plugin.common.declarations.saveToDirectory 10 | import io.github.skeptick.libres.plugin.common.extensions.deleteFilesInDirectory 11 | import io.github.skeptick.libres.plugin.images.ImagesTypeSpecsBuilder 12 | import io.github.skeptick.libres.plugin.images.declarations.EmptyImagesObject 13 | import io.github.skeptick.libres.plugin.images.declarations.ImagesObjectFile 14 | import io.github.skeptick.libres.plugin.images.models.ImageProps 15 | import io.github.skeptick.libres.plugin.images.processing.removeImage 16 | import io.github.skeptick.libres.plugin.images.processing.saveImage 17 | import java.io.File 18 | 19 | @CacheableTask 20 | abstract class LibresImagesGenerationTask : DefaultTask() { 21 | 22 | @get:Input 23 | internal abstract var settings: ImagesSettings 24 | 25 | @get:Incremental 26 | @get:InputFiles 27 | @get:PathSensitive(PathSensitivity.RELATIVE) 28 | internal abstract var inputDirectory: FileCollection 29 | 30 | @get:OutputDirectories 31 | internal abstract var outputSourcesDirectories: Map 32 | 33 | @get:OutputDirectories 34 | internal abstract var outputResourcesDirectories: Map 35 | 36 | @TaskAction 37 | fun apply(inputChanges: InputChanges) { 38 | inputChanges.getFileChanges(inputDirectory).forEach { change -> 39 | @Suppress("WHEN_ENUM_CAN_BE_NULL_IN_JAVA") 40 | when (change.changeType) { 41 | ChangeType.REMOVED -> ImageProps(change.file).removeImage(outputResourcesDirectories) 42 | ChangeType.MODIFIED, ChangeType.ADDED -> ImageProps(change.file).saveImage(outputResourcesDirectories) 43 | } 44 | } 45 | 46 | inputDirectory.files 47 | .takeIf { files -> files.isNotEmpty() } 48 | ?.map { file -> ImageProps(file) } 49 | ?.let { imageProps -> buildImages(imageProps) } 50 | ?: buildEmptyImages() 51 | } 52 | 53 | private fun buildImages(imageProps: List) { 54 | val builder = ImagesTypeSpecsBuilder(settings, outputSourcesDirectories.keys) 55 | imageProps.forEach { builder.appendImage(it) } 56 | outputSourcesDirectories.forEach { it.value.deleteFilesInDirectory() } 57 | builder.save(outputSourcesDirectories) 58 | } 59 | 60 | private fun buildEmptyImages() { 61 | val hasCommon = KotlinPlatform.Common in outputSourcesDirectories.keys 62 | outputSourcesDirectories.forEach { (platform, directory) -> 63 | val imagesObjectTypeSpec = EmptyImagesObject(settings.outputClassName, platform, hasCommon) 64 | val imagesObjectFileSpec = ImagesObjectFile(settings.outputPackageName, imagesObjectTypeSpec, platform) 65 | directory.deleteFilesInDirectory() 66 | imagesObjectFileSpec.saveToDirectory(directory) 67 | } 68 | } 69 | 70 | } -------------------------------------------------------------------------------- /libres-compose/src/webMain/kotlin/io/github/skeptick/libres/compose/WebSvgPainter.kt: -------------------------------------------------------------------------------- 1 | @file:Suppress("NOTHING_TO_INLINE") 2 | 3 | package io.github.skeptick.libres.compose 4 | 5 | import androidx.compose.ui.geometry.Size 6 | import androidx.compose.ui.geometry.isSpecified 7 | import androidx.compose.ui.graphics.* 8 | import androidx.compose.ui.graphics.drawscope.CanvasDrawScope 9 | import androidx.compose.ui.graphics.drawscope.DrawScope 10 | import androidx.compose.ui.graphics.drawscope.drawIntoCanvas 11 | import androidx.compose.ui.graphics.painter.Painter 12 | import androidx.compose.ui.unit.Density 13 | import androidx.compose.ui.unit.IntSize 14 | import androidx.compose.ui.unit.LayoutDirection 15 | import org.jetbrains.skia.svg.* 16 | import kotlin.math.ceil 17 | 18 | internal class WebSvgPainter(private val dom: SVGDOM, density: Density) : Painter() { 19 | 20 | private val srcSize: Size = dom.pxSize ?: Size.Unspecified 21 | 22 | private lateinit var cachedImage: ImageBitmap 23 | private lateinit var cachedCanvas: Canvas 24 | private var cachedSize: Size = Size.Unspecified 25 | private val cacheScope: CanvasDrawScope = CanvasDrawScope() 26 | 27 | override val intrinsicSize = if (srcSize.isSpecified) srcSize * density.density else Size.Unspecified 28 | 29 | private var alpha: Float = 1.0f 30 | 31 | private var colorFilter: ColorFilter? = null 32 | 33 | override fun applyAlpha(alpha: Float): Boolean { 34 | this.alpha = alpha 35 | return true 36 | } 37 | 38 | override fun applyColorFilter(colorFilter: ColorFilter?): Boolean { 39 | this.colorFilter = colorFilter 40 | return true 41 | } 42 | 43 | override fun DrawScope.onDraw() { 44 | if (cachedSize != size) prepareImage() 45 | drawImage(cachedImage, srcSize = cachedSize.toIntSize(), alpha = alpha, colorFilter = colorFilter) 46 | } 47 | 48 | private fun DrawScope.prepareImage() { 49 | cachedImage = ImageBitmap(size.toIntSize()) 50 | cachedCanvas = Canvas(cachedImage) 51 | cachedSize = size 52 | cacheScope.clearAndDrawSvg(density = this, layoutDirection, size) 53 | cachedImage.prepareToDraw() 54 | } 55 | 56 | private fun CanvasDrawScope.clearAndDrawSvg(density: Density, layoutDirection: LayoutDirection, size: Size) { 57 | draw(density, layoutDirection, cachedCanvas, size) { 58 | drawRect(color = Color.Black, blendMode = BlendMode.Clear) 59 | drawIntoCanvas { canvas -> 60 | dom.root?.width = SVGLength(size.width, SVGLengthUnit.PX) 61 | dom.root?.height = SVGLength(size.height, SVGLengthUnit.PX) 62 | dom.root?.preserveAspectRatio = SVGPreserveAspectRatio(SVGPreserveAspectRatioAlign.NONE) 63 | dom.render(canvas.nativeCanvas) 64 | } 65 | } 66 | } 67 | 68 | } 69 | 70 | private inline fun ImageBitmap(intSize: IntSize) = ImageBitmap(intSize.width, intSize.height) 71 | 72 | private inline fun Size.toIntSize() = IntSize(ceil(width).toInt(), ceil(height).toInt()) 73 | 74 | private inline val SVGDOM.pxSize: Size? 75 | get() = root?.run { 76 | val width = width.withUnit(SVGLengthUnit.PX).value 77 | val height = height.withUnit(SVGLengthUnit.PX).value 78 | if (width != 0f && height != 0f) Size(width, height) else Size.Unspecified 79 | } -------------------------------------------------------------------------------- /gradle-plugin/src/main/java/io/github/skeptick/libres/plugin/strings/declarations/Properties+Functions.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.plugin.strings.declarations 2 | 3 | import com.squareup.kotlinpoet.* 4 | import io.github.skeptick.libres.plugin.common.declarations.addObjCNameAnnotation 5 | import io.github.skeptick.libres.plugin.strings.models.LanguageCode 6 | import io.github.skeptick.libres.plugin.strings.models.PluralsResource 7 | import io.github.skeptick.libres.plugin.strings.models.StringResource 8 | import io.github.skeptick.libres.plugin.strings.models.TextResource 9 | import io.github.skeptick.libres.plugin.strings.snakeCaseToCamelCase 10 | import io.github.skeptick.libres.plugin.strings.unescapeXml 11 | import io.github.skeptick.libres.strings.PluralForms 12 | import io.github.skeptick.libres.strings.getCurrentLanguageCode 13 | 14 | /* 15 | * val string_name: ClassName? 16 | */ 17 | internal fun TypeSpec.Builder.addTextResourceToInterface( 18 | name: String, 19 | type: ClassName 20 | ): TypeSpec.Builder { 21 | return addProperty( 22 | PropertySpec.builder(name, type.copy(nullable = true)).build() 23 | ) 24 | } 25 | 26 | /* 27 | * for string: override val string_name: ClassName = ClassName(value) 28 | * for plural: override val plural_name: ClassName = ClassName(PluralForms("one", "two"), "ru") 29 | */ 30 | internal fun TypeSpec.Builder.addTextResourceToLocalizedObject( 31 | name: String, 32 | resource: TextResource?, 33 | type: ClassName, 34 | languageCode: LanguageCode 35 | ): TypeSpec.Builder { 36 | return addProperty( 37 | PropertySpec.builder(name, type.copy(nullable = resource == null)) 38 | .addModifiers(KModifier.OVERRIDE) 39 | .apply { 40 | when (resource) { 41 | is PluralsResource -> initializer("%L(%L, %S)", type.simpleName, resource.items.toPluralFormsInitializer(), languageCode) 42 | is StringResource -> when (type.simpleName) { 43 | "String" -> initializer("%S", resource.value.unescapeXml()) 44 | else -> initializer("%L(%S)", type.simpleName, resource.value.unescapeXml()) 45 | } 46 | else -> initializer("null") 47 | } 48 | }.build() 49 | ) 50 | } 51 | 52 | /* 53 | * val string_name: ClassName 54 | * get() = locales[getCurrentLanguageCode()]?.string_name ?: baseLocale.string_name 55 | */ 56 | internal fun TypeSpec.Builder.addTextResourceToStringsObject( 57 | name: String, 58 | type: ClassName, 59 | camelCaseForApple: Boolean 60 | ): TypeSpec.Builder { 61 | return addProperty( 62 | PropertySpec.builder(name, type) 63 | .getter( 64 | FunSpec.getterBuilder() 65 | .addStatement("return locales[${::getCurrentLanguageCode.name}()]?.$name ?: baseLocale.$name") 66 | .build() 67 | ).addObjCNameAnnotation(camelCaseForApple) { 68 | name.snakeCaseToCamelCase(startWithLower = true) 69 | }.build() 70 | ) 71 | } 72 | 73 | private fun List.toPluralFormsInitializer(): CodeBlock { 74 | val builder = CodeBlock.builder() 75 | builder.add(PluralForms::class.simpleName!!) 76 | builder.add("(") 77 | for (item in this) builder.add("%L = %S, ", item.quantity.serialName, item.value.unescapeXml()) 78 | builder.add(")") 79 | return builder.build() 80 | } -------------------------------------------------------------------------------- /gradle-plugin/src/main/java/io/github/skeptick/libres/plugin/images/declarations/Properties+Functions.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.plugin.images.declarations 2 | 3 | import com.squareup.kotlinpoet.* 4 | import io.github.skeptick.libres.plugin.KotlinPlatform 5 | import io.github.skeptick.libres.plugin.ResourcesPlugin 6 | import io.github.skeptick.libres.plugin.common.declarations.addObjCNameAnnotation 7 | import io.github.skeptick.libres.plugin.images.models.ImageProps 8 | import io.github.skeptick.libres.plugin.strings.snakeCaseToCamelCase 9 | 10 | private val Image = ClassName(ResourcesPlugin.IMAGES_PACKAGE_NAME, "Image") 11 | 12 | internal fun TypeSpec.Builder.appendImage( 13 | specs: ImageProps, 14 | platform: KotlinPlatform, 15 | hasCommon: Boolean, 16 | camelCaseForApple: Boolean 17 | ): TypeSpec.Builder { 18 | return when { 19 | platform == KotlinPlatform.Common -> appendExpectImage(specs) 20 | platform == KotlinPlatform.Apple && hasCommon -> appendActualImage(specs, specs.initializerLiteral(platform), camelCaseForApple) 21 | platform == KotlinPlatform.Apple -> appendImage(specs, specs.initializerLiteral(platform), camelCaseForApple) 22 | !hasCommon -> appendImage(specs, specs.initializerLiteral(platform), camelCaseForApple = false) 23 | else -> appendActualImage(specs, specs.initializerLiteral(platform), camelCaseForApple = false) 24 | } 25 | } 26 | 27 | /** 28 | * expect val image_name: Image 29 | */ 30 | private fun TypeSpec.Builder.appendExpectImage(specs: ImageProps): TypeSpec.Builder { 31 | return addProperty( 32 | PropertySpec.builder(specs.name, Image) 33 | .addModifiers(KModifier.EXPECT) 34 | .build() 35 | ) 36 | } 37 | 38 | /** 39 | * actual val image_name: Image 40 | * get() = "image_name" 41 | */ 42 | private fun TypeSpec.Builder.appendActualImage( 43 | specs: ImageProps, 44 | initializerLiteral: String, 45 | camelCaseForApple: Boolean 46 | ): TypeSpec.Builder { 47 | return addProperty( 48 | PropertySpec.builder(specs.name, Image) 49 | .addModifiers(KModifier.ACTUAL) 50 | .getter( 51 | FunSpec.getterBuilder() 52 | .addStatement("return $initializerLiteral") 53 | .build() 54 | ).addObjCNameAnnotation(camelCaseForApple) { 55 | specs.name.snakeCaseToCamelCase(startWithLower = true) 56 | }.build() 57 | ) 58 | } 59 | 60 | /** 61 | * val image_name: Image 62 | * get() = "image_name" 63 | */ 64 | private fun TypeSpec.Builder.appendImage( 65 | specs: ImageProps, 66 | initializerLiteral: String, 67 | camelCaseForApple: Boolean 68 | ): TypeSpec.Builder { 69 | return addProperty( 70 | PropertySpec.builder(specs.name, Image) 71 | .getter( 72 | FunSpec.getterBuilder() 73 | .addStatement("return $initializerLiteral") 74 | .build() 75 | ).addObjCNameAnnotation(camelCaseForApple) { 76 | specs.name.snakeCaseToCamelCase(startWithLower = true) 77 | }.build() 78 | ) 79 | } 80 | 81 | private fun ImageProps.initializerLiteral(platform: KotlinPlatform): String = 82 | when (platform) { 83 | KotlinPlatform.Android -> "R.drawable.$name" 84 | KotlinPlatform.Apple -> "bundle.image(\"$name\", \"$extension\")" 85 | KotlinPlatform.Js, KotlinPlatform.Jvm -> "\"images/$name.$extension\"" 86 | KotlinPlatform.Common -> throw IllegalArgumentException() 87 | } -------------------------------------------------------------------------------- /gradle-plugin/src/main/java/io/github/skeptick/libres/plugin/images/declarations/Classes.kt: -------------------------------------------------------------------------------- 1 | @file:Suppress("FunctionName") 2 | 3 | package io.github.skeptick.libres.plugin.images.declarations 4 | 5 | import com.squareup.kotlinpoet.ClassName 6 | import com.squareup.kotlinpoet.KModifier 7 | import com.squareup.kotlinpoet.PropertySpec 8 | import com.squareup.kotlinpoet.TypeSpec 9 | import io.github.skeptick.libres.plugin.KotlinPlatform 10 | import io.github.skeptick.libres.plugin.common.declarations.addExperimentalObjCNameAnnotation 11 | 12 | private val NSBundle = ClassName("platform.Foundation", "NSBundle") 13 | 14 | internal fun ImagesObject( 15 | name: String, 16 | platform: KotlinPlatform, 17 | hasCommon: Boolean, 18 | appleBundleName: String, 19 | camelCaseForApple: Boolean 20 | ): TypeSpec.Builder { 21 | return when { 22 | platform == KotlinPlatform.Common -> ExpectImagesObject(name) 23 | platform == KotlinPlatform.Apple && hasCommon -> ActualImagesObjectApple(name, appleBundleName, camelCaseForApple) 24 | platform == KotlinPlatform.Apple -> ImagesObjectApple(name, appleBundleName, camelCaseForApple) 25 | !hasCommon -> ImagesObject(name) 26 | else -> ActualImagesObject(name) 27 | } 28 | } 29 | 30 | internal fun EmptyImagesObject( 31 | name: String, 32 | platform: KotlinPlatform, 33 | hasCommon: Boolean 34 | ): TypeSpec.Builder { 35 | return when { 36 | platform == KotlinPlatform.Common -> ExpectImagesObject(name) 37 | !hasCommon -> ImagesObject(name) 38 | else -> ActualImagesObject(name) 39 | } 40 | } 41 | 42 | /** 43 | * expect object MainResImages 44 | */ 45 | private fun ExpectImagesObject(name: String): TypeSpec.Builder { 46 | return TypeSpec.objectBuilder("${name}Images") 47 | .addModifiers(KModifier.EXPECT) 48 | } 49 | 50 | /** 51 | * actual object MainResImages 52 | */ 53 | private fun ActualImagesObject(name: String): TypeSpec.Builder { 54 | return TypeSpec.objectBuilder("${name}Images") 55 | .addModifiers(KModifier.ACTUAL) 56 | } 57 | 58 | /** 59 | * actual object MainResImages { 60 | * private val bundle: NSBundle = NSBundle.bundleWithName(bundleName) 61 | * } 62 | */ 63 | private fun ActualImagesObjectApple( 64 | name: String, 65 | bundleName: String, 66 | camelCaseNames: Boolean 67 | ): TypeSpec.Builder { 68 | return TypeSpec.objectBuilder("${name}Images") 69 | .addExperimentalObjCNameAnnotation(camelCaseNames) 70 | .addModifiers(KModifier.ACTUAL) 71 | .appendAppleBundleProperty(bundleName) 72 | } 73 | 74 | /** 75 | * object MainResImages 76 | */ 77 | private fun ImagesObject(name: String): TypeSpec.Builder { 78 | return TypeSpec.objectBuilder("${name}Images") 79 | } 80 | 81 | /** 82 | * object MainResImages { 83 | * private val bundle: NSBundle = NSBundle.bundleWithName(bundleName) 84 | * } 85 | */ 86 | private fun ImagesObjectApple( 87 | name: String, 88 | bundleName: String, 89 | camelCaseNames: Boolean 90 | ): TypeSpec.Builder { 91 | return TypeSpec.objectBuilder("${name}Images") 92 | .addExperimentalObjCNameAnnotation(camelCaseNames) 93 | .appendAppleBundleProperty(bundleName) 94 | } 95 | 96 | private fun TypeSpec.Builder.appendAppleBundleProperty(bundleName: String): TypeSpec.Builder { 97 | return addProperty( 98 | PropertySpec.builder("bundle", NSBundle) 99 | .addModifiers(KModifier.PRIVATE) 100 | .delegate("lazy { NSBundle.bundleWithName(%S) }", bundleName) 101 | .build() 102 | ) 103 | } -------------------------------------------------------------------------------- /gradle-plugin/src/main/java/io/github/skeptick/libres/plugin/SourceSet.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.plugin 2 | 3 | import com.android.build.api.dsl.AndroidSourceSet 4 | import com.android.build.gradle.BaseExtension 5 | import org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension 6 | import org.jetbrains.kotlin.gradle.dsl.KotlinProjectExtension 7 | import org.jetbrains.kotlin.gradle.dsl.KotlinSingleTargetExtension 8 | import org.jetbrains.kotlin.gradle.plugin.KotlinCompilation 9 | import org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet 10 | import org.jetbrains.kotlin.gradle.plugin.KotlinTarget 11 | import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinAndroidTarget 12 | import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget 13 | import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinWithJavaTarget 14 | import org.jetbrains.kotlin.gradle.targets.js.ir.KotlinJsIrTarget 15 | import org.jetbrains.kotlin.gradle.targets.jvm.KotlinJvmTarget 16 | import org.jetbrains.kotlin.konan.target.Family 17 | import java.io.File 18 | import java.io.Serializable 19 | import java.util.* 20 | 21 | enum class KotlinPlatform { 22 | Common, Jvm, Android, Js, Apple 23 | } 24 | 25 | internal class SourceSet( 26 | val rootDir: File, 27 | val sourcesDir: File, 28 | val resourcesDir: File, 29 | val platform: KotlinPlatform 30 | ) : Serializable 31 | 32 | internal fun KotlinSourceSet.createKotlinSourceSet( 33 | outputDirectory: File, 34 | platform: KotlinPlatform 35 | ): SourceSet { 36 | val rootDir = File(outputDirectory, platform.name.lowercase()) 37 | val sourcesDirectory = File(rootDir, "src") 38 | val resourcesDirectory = File(rootDir, "resources") 39 | kotlin.srcDir(sourcesDirectory) 40 | // don't add to apples source sets, otherwise compose plugin duplicates them 41 | if (platform != KotlinPlatform.Apple) resources.srcDir(resourcesDirectory) 42 | return SourceSet(rootDir = rootDir, sourcesDir = sourcesDirectory, resourcesDir = resourcesDirectory, platform) 43 | } 44 | 45 | internal fun KotlinSourceSet.createAndroidSourceSet( 46 | outputDirectory: File, 47 | androidMainSourceSet: AndroidSourceSet 48 | ): SourceSet { 49 | val rootDir = File(outputDirectory, "android") 50 | val sourcesDirectory = File(rootDir, "src") 51 | val resourcesDirectory = File(rootDir, "resources") 52 | kotlin.srcDir(sourcesDirectory) 53 | androidMainSourceSet.kotlin.srcDir(sourcesDirectory) 54 | androidMainSourceSet.res.srcDir(resourcesDirectory) 55 | return SourceSet(rootDir = rootDir, sourcesDir = sourcesDirectory, resourcesDir = resourcesDirectory, KotlinPlatform.Android) 56 | } 57 | 58 | internal fun List.takeKotlinSourceSet( 59 | outputDirectory: File 60 | ): List = mapNotNull { target -> 61 | val platform = target.platform ?: return@mapNotNull null 62 | val compilation = target.compilations.firstOrNull { it.isMainCompilation } 63 | compilation?.defaultSourceSet?.createKotlinSourceSet(outputDirectory, platform) 64 | } 65 | 66 | internal fun BaseExtension.findAndroidSourceSet( 67 | hasCommon: Boolean, 68 | outputDirectory: File, 69 | kotlinExtension: KotlinProjectExtension 70 | ): SourceSet { 71 | val androidMainSourceSet = sourceSets.getByName(org.gradle.api.tasks.SourceSet.MAIN_SOURCE_SET_NAME) 72 | val kotlinSourceSet = if (!hasCommon) { 73 | kotlinExtension.sourceSets.getByName(androidMainSourceSet.name) 74 | } else { 75 | val androidTarget = kotlinExtension.targets.first { it is KotlinAndroidTarget } 76 | androidTarget.compilations.firstNotNullOf { compilation -> 77 | compilation.kotlinSourceSets.first { sourceSet -> 78 | sourceSet.name.endsWith(androidMainSourceSet.name, ignoreCase = true) 79 | } 80 | } 81 | } 82 | return kotlinSourceSet.createAndroidSourceSet(outputDirectory, androidMainSourceSet) 83 | } 84 | 85 | // Android isn't kotlin (-_-) 86 | internal val KotlinTarget.platform: KotlinPlatform? 87 | get() = when (this) { 88 | is KotlinJvmTarget, is KotlinWithJavaTarget<*, *> -> KotlinPlatform.Jvm 89 | is KotlinJsIrTarget -> KotlinPlatform.Js 90 | is KotlinNativeTarget -> when (konanTarget.family) { 91 | Family.IOS, Family.OSX, Family.TVOS -> KotlinPlatform.Apple 92 | else -> null 93 | } 94 | else -> null 95 | } 96 | 97 | internal val KotlinProjectExtension.targets: List 98 | get() = when (this) { 99 | is KotlinSingleTargetExtension<*> -> listOf(target) 100 | is KotlinMultiplatformExtension -> targets.toList() 101 | else -> error("Unexpected 'kotlin' extension $this") 102 | } 103 | 104 | internal val KotlinCompilation<*>.isMainCompilation: Boolean 105 | get() = name == "main" -------------------------------------------------------------------------------- /gradle-plugin/src/main/java/io/github/skeptick/libres/plugin/strings/StringsParsing.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.plugin.strings 2 | 3 | import io.github.skeptick.libres.plugin.common.extensions.findDuplicates 4 | import com.fasterxml.jackson.databind.JsonNode 5 | import com.fasterxml.jackson.dataformat.xml.XmlMapper 6 | import io.github.skeptick.libres.plugin.strings.models.* 7 | import java.io.File 8 | 9 | private typealias Resources = Map> 10 | 11 | private val xmlMapper = XmlMapper() 12 | 13 | internal fun parseStringResources(inputFiles: Set, baseLocaleLanguageCode: LanguageCode): Resources { 14 | val filesByLocale = inputFiles.groupBy { it.name.substringAfterLast("_").substringBefore(".") } 15 | if (filesByLocale[baseLocaleLanguageCode].isNullOrEmpty()) throw BaseStringResourcesNotFoundException() 16 | 17 | val resources = filesByLocale.mapValues { (_, files) -> files.map(xmlMapper::readTree).flatMap(JsonNode::parseResources) } 18 | resources.validateNames(baseLocaleLanguageCode) 19 | resources.validateDuplicatesAndArguments() 20 | return resources 21 | } 22 | 23 | private fun Resources.validateNames(baseLocaleLanguageCode: LanguageCode) { 24 | val baseResources = get(baseLocaleLanguageCode) ?: throw BaseStringResourcesNotFoundException() 25 | val baseNames = baseResources.map(TextResource::name) 26 | if (!baseNames.all(String::isValidName)) throw UnavailableNameException(baseNames.first { !it.isValidName() }) 27 | } 28 | 29 | private fun Resources.validateDuplicatesAndArguments() { 30 | forEach { (languageCode, localizedResources) -> 31 | val names = localizedResources.map(TextResource::name) 32 | val stringValues = localizedResources.filterIsInstance().map(StringResource::value) 33 | val pluralValues = localizedResources.filterIsInstance().flatMap { it.items.map(PluralsResource.Item::value) } 34 | names.findDuplicates().let { if (it.isNotEmpty()) throw NamesClashException(languageCode, it) } 35 | stringValues.find(String::hasJavaArguments)?.let { throw UnavailableFormatException(languageCode, it) } 36 | pluralValues.find(String::hasJavaArguments)?.let { throw UnavailableFormatException(languageCode, it) } 37 | } 38 | } 39 | 40 | class UnavailableNameException internal constructor(name: String) : Exception( 41 | "Name '$name' isn't available. Please use only Latin letters, numbers and underscore." 42 | ) 43 | 44 | class NamesClashException internal constructor(languageCode: LanguageCode, names: Set) : Exception( 45 | "Found strings with the identical names: $names. Locale: '$languageCode'." 46 | ) 47 | 48 | class UnavailableFormatException internal constructor(languageCode: LanguageCode, stringName: String) : Exception( 49 | "Don't use java style formatting. Use \${template_like}. Locale: '$languageCode'. String: '$stringName'." 50 | ) 51 | 52 | class BaseStringResourcesNotFoundException internal constructor() : Exception( 53 | "Couldn't find resource files for base localization." 54 | ) 55 | 56 | class ParameterNotFoundException internal constructor(languageCode: LanguageCode, stringName: String, parameterName: String) : Exception( 57 | "Localized strings cannot have parameters missing in base localization. Locale: '$languageCode'. String: '$stringName'. Parameter: '$parameterName'." 58 | ) 59 | 60 | class PluralStringWithoutQuantityException internal constructor(stringName: String) : Exception( 61 | "Plural string doesn't contain any quantity. String: $stringName" 62 | ) 63 | 64 | class InvalidPluralQuantityException internal constructor(quantity: String) : Exception( 65 | "invalid quantity in plural string: '$quantity'." 66 | ) 67 | 68 | private fun JsonNode.parseResources(): List { 69 | return this["string"]?.parseAsArray(JsonNode::parseString).orEmpty() + 70 | this["plurals"]?.parseAsArray(JsonNode::parsePlural).orEmpty() 71 | } 72 | 73 | private fun JsonNode.parseString(): StringResource { 74 | return StringResource( 75 | name = this["name"].asText(), 76 | value = this[""]?.asText() ?: "" 77 | ) 78 | } 79 | 80 | private fun JsonNode.parsePlural(): PluralsResource { 81 | return PluralsResource( 82 | name = this["name"].asText(), 83 | items = this["item"]?.parseAsArray(JsonNode::parsePluralItem) ?: throw PluralStringWithoutQuantityException(this["name"].asText()) 84 | ) 85 | } 86 | 87 | private fun JsonNode.parsePluralItem(): PluralsResource.Item { 88 | return PluralsResource.Item( 89 | quantity = PluralsResource.quantityBySerialName[this["quantity"].asText()] ?: throw InvalidPluralQuantityException(this["quantity"].asText()), 90 | value = this[""]?.asText() ?: "" 91 | ) 92 | } 93 | 94 | private inline fun JsonNode.parseAsArray(block: (JsonNode) -> T): List { 95 | return if (isArray) map(block) else listOf(block(this)) 96 | } -------------------------------------------------------------------------------- /gradle-plugin/src/main/java/io/github/skeptick/libres/plugin/strings/StringTypeSpecsBuilder.kt: -------------------------------------------------------------------------------- 1 | @file:Suppress("CanBeParameter") 2 | 3 | package io.github.skeptick.libres.plugin.strings 4 | 5 | import com.squareup.kotlinpoet.ClassName 6 | import com.squareup.kotlinpoet.TypeSpec 7 | import com.squareup.kotlinpoet.asTypeName 8 | import io.github.skeptick.libres.plugin.StringsSettings 9 | import io.github.skeptick.libres.plugin.common.declarations.saveToDirectory 10 | import io.github.skeptick.libres.plugin.strings.declarations.* 11 | import io.github.skeptick.libres.plugin.strings.models.* 12 | import io.github.skeptick.libres.strings.* 13 | import java.io.File 14 | 15 | internal class StringTypeSpecsBuilder( 16 | private val settings: StringsSettings, 17 | private val languageCodes: Set 18 | ) { 19 | 20 | private val packageName = settings.outputPackageName 21 | private val className = settings.outputClassName 22 | private val baseLanguageCode = settings.baseLocaleLanguageCode 23 | private val generateNamedArguments = settings.generateNamedArguments 24 | private val camelCaseForApple = settings.camelCaseForApple 25 | 26 | private val stringsInterface = StringsInterface() 27 | private val localizedObjects = languageCodes.associateWith { LocalizedStringsObject(packageName, it) } 28 | private val baseLocalizedObject = localizedObjects.getValue(baseLanguageCode) 29 | private val stringObject = StringObject(packageName, className, baseLanguageCode, languageCodes, camelCaseForApple) 30 | private val customClasses = mutableListOf() 31 | 32 | fun appendResource(baseResource: TextResource, localizedResources: Map) { 33 | val resourceName = baseResource.name 34 | val baseParameters = baseResource.parameters 35 | val formattedResource = baseResource.replaceParameters(baseParameters, baseLanguageCode) 36 | val type = baseResource.fetchClass(packageName, baseParameters.isNotEmpty(), generateNamedArguments) 37 | 38 | baseResource.appendLocalizedResources(localizedResources, type) 39 | stringsInterface.addTextResourceToInterface(resourceName, type) 40 | baseLocalizedObject.addTextResourceToLocalizedObject(resourceName, formattedResource, type, baseLanguageCode) 41 | stringObject.addTextResourceToStringsObject(resourceName, type, camelCaseForApple) 42 | if (generateNamedArguments && baseParameters.isNotEmpty()) customClasses += CustomFormattedTextResourceClass(type, baseResource) 43 | } 44 | 45 | fun save(outputDirectory: File) { 46 | StringsInterfaceFile(packageName, stringsInterface).saveToDirectory(outputDirectory) 47 | StringsObjectFile(packageName, stringObject).saveToDirectory(outputDirectory) 48 | localizedObjects.forEach { StringsObjectFile(packageName, it.value).saveToDirectory(outputDirectory) } 49 | if (customClasses.isNotEmpty()) FormattedClassesFile(packageName, customClasses).saveToDirectory(outputDirectory) 50 | } 51 | 52 | private fun TextResource.appendLocalizedResources(localizedResources: Map, type: ClassName) { 53 | for (languageCode in languageCodes) { 54 | if (languageCode == baseLanguageCode) continue 55 | val localizedObject = localizedObjects.getValue(languageCode) 56 | when (val localizedResource = localizedResources[languageCode]) { 57 | null -> localizedObject.addTextResourceToLocalizedObject(name, null, type, languageCode) 58 | else -> localizedResource.replaceParameters(parameters, languageCode).also { 59 | localizedObject.addTextResourceToLocalizedObject(name, it, type, languageCode) 60 | } 61 | } 62 | } 63 | } 64 | 65 | } 66 | 67 | private fun TextResource.fetchClass(packageName: String, hasParameters: Boolean, generateNamedArguments: Boolean) = 68 | when (this) { 69 | is StringResource -> when { 70 | !hasParameters -> String::class.asTypeName() 71 | generateNamedArguments -> ClassName(packageName, "LibresFormat" + name.snakeCaseToCamelCase()) 72 | else -> VoidFormattedString::class.asTypeName() 73 | } 74 | is PluralsResource -> when { 75 | !hasParameters -> VoidPluralString::class.asTypeName() 76 | generateNamedArguments -> ClassName(packageName, "LibresFormat" + name.snakeCaseToCamelCase()) 77 | else -> VoidFormattedPluralString::class.asTypeName() 78 | } 79 | } 80 | 81 | private fun TextResource.replaceParameters(parameters: Set, languageCode: LanguageCode) = 82 | when (this) { 83 | is StringResource -> copy( 84 | value = value.replaceNamedArguments { _, argument -> 85 | val actualIndex = parameters.indexOf(argument) 86 | if (actualIndex != -1) "%${actualIndex + 1}\$s" 87 | else throw ParameterNotFoundException(languageCode, name, argument) 88 | } 89 | ) 90 | is PluralsResource -> copy( 91 | items = items.map { item -> 92 | item.copy( 93 | value = item.value.replaceNamedArguments { _, argument -> 94 | val actualIndex = parameters.indexOf(argument) 95 | if (actualIndex != -1) "%${actualIndex + 1}\$s" 96 | else throw ParameterNotFoundException(languageCode, name, argument) 97 | } 98 | ) 99 | } 100 | ) 101 | } -------------------------------------------------------------------------------- /gradle-plugin/src/main/java/io/github/skeptick/libres/plugin/images/processing/ImageSpecs+Operations.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.plugin.images.processing 2 | 3 | import com.android.ide.common.vectordrawable.Svg2Vector 4 | import com.fasterxml.jackson.annotation.JsonInclude 5 | import com.fasterxml.jackson.core.util.DefaultIndenter 6 | import com.fasterxml.jackson.core.util.DefaultPrettyPrinter 7 | import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper 8 | import org.bytedeco.opencv.global.opencv_imgcodecs 9 | import org.bytedeco.opencv.global.opencv_imgproc 10 | import org.bytedeco.opencv.opencv_core.Mat 11 | import io.github.skeptick.libres.plugin.KotlinPlatform 12 | import io.github.skeptick.libres.plugin.images.models.* 13 | import io.github.skeptick.libres.plugin.images.models.ImageScale 14 | import io.github.skeptick.libres.plugin.images.models.ImageProps 15 | import io.github.skeptick.libres.plugin.images.models.androidName 16 | import java.io.File 17 | import java.io.FileOutputStream 18 | import java.io.OutputStream 19 | 20 | private val jsonWriter = jacksonObjectMapper().let { 21 | it.setSerializationInclusion(JsonInclude.Include.NON_NULL) 22 | it.writer(DefaultPrettyPrinter().apply { 23 | indentArraysWith(DefaultIndenter.SYSTEM_LINEFEED_INSTANCE) 24 | }) 25 | } 26 | 27 | internal fun ImageProps.saveImage(directories: Map) { 28 | directories[KotlinPlatform.Apple]?.let { 29 | saveImageSetContents(it) 30 | } 31 | 32 | if (targetSize == null) { 33 | saveOriginal(directories) 34 | } else { 35 | val src = opencv_imgcodecs.imread(file.absolutePath, opencv_imgcodecs.IMREAD_UNCHANGED) 36 | for (scale in ImageScale.values()) { 37 | if (!directories.any { it.key in scale.supportedPlatforms }) continue 38 | val newSideSize = targetSize * scale 39 | when { 40 | src.size() < newSideSize -> error("Image '$name' has too low resolution") 41 | src.size() > newSideSize -> resizeAndSave(src, scale, targetSize, directories) 42 | else -> saveOriginal(scale, directories) 43 | } 44 | } 45 | } 46 | } 47 | 48 | internal fun ImageProps.removeImage(directories: Map) { 49 | for ((platform, directory) in directories) { 50 | when { 51 | platform == KotlinPlatform.Common -> continue 52 | platform == KotlinPlatform.Apple -> File(directory, "$name.imageset").deleteRecursively() 53 | platform == KotlinPlatform.Android && targetSize != null -> ImageScale.values().forEach { 54 | File(directory, targetFilePath(platform, it)).delete() 55 | } 56 | else -> File(directory, targetFilePath(platform)).delete() 57 | } 58 | } 59 | } 60 | 61 | private fun ImageProps.saveOriginal(directories: Map) { 62 | for ((platform, directory) in directories) { 63 | when { 64 | platform == KotlinPlatform.Common -> continue 65 | platform == KotlinPlatform.Android && isVector -> { 66 | val targetFile = File(directory, targetFilePath(platform)) 67 | targetFile.parentFile.mkdirs() 68 | val output = FileOutputStream(targetFile) 69 | parseSvgToXml(file, output) 70 | } 71 | else -> { 72 | val targetFile = File(directory, targetFilePath(platform)) 73 | targetFile.parentFile.mkdirs() 74 | file.copyTo(targetFile, overwrite = true) 75 | } 76 | } 77 | } 78 | } 79 | 80 | private fun ImageProps.saveOriginal(scale: ImageScale, directories: Map) { 81 | for ((platform, directory) in directories) { 82 | if (platform in scale.supportedPlatforms) { 83 | val targetFile = File(directory, targetFilePath(platform, scale)) 84 | file.parentFile.mkdirs() 85 | file.copyTo(targetFile, overwrite = true) 86 | } 87 | } 88 | } 89 | 90 | private fun ImageProps.resizeAndSave(src: Mat, scale: ImageScale, size: Int, directories: Map) { 91 | val destinationImage = Mat() 92 | val newSize = calculateSize(src.size(), size * scale) 93 | opencv_imgproc.resize(src, destinationImage, newSize) 94 | 95 | for ((platform, directory) in directories) { 96 | if (platform in scale.supportedPlatforms) { 97 | val targetPath = directory.absolutePath + targetFilePath(platform, scale) 98 | File(targetPath).parentFile.mkdirs() 99 | opencv_imgcodecs.imwrite(targetPath, destinationImage) 100 | } 101 | } 102 | } 103 | 104 | private fun ImageProps.saveImageSetContents(directory: File) { 105 | val text = jsonWriter.writeValueAsString(toImageSetContents()) 106 | val file = File(directory, "$name.imageset/Contents.json") 107 | file.parentFile.mkdirs() 108 | file.writeText(text) 109 | } 110 | 111 | private fun ImageProps.targetFilePath(platform: KotlinPlatform, scale: ImageScale? = null): String = 112 | when (platform) { 113 | KotlinPlatform.Android -> "/drawable-${scale?.androidName ?: "nodpi"}/$name.${if (isVector) "xml" else extension}" 114 | KotlinPlatform.Apple -> "/$name.imageset/$name${if (scale != null) "_${scale.name}" else ""}.$extension" 115 | KotlinPlatform.Jvm, KotlinPlatform.Js -> "/$name.$extension" 116 | KotlinPlatform.Common -> throw IllegalArgumentException() 117 | } 118 | 119 | /** 120 | * Workaround for Svg2Vector::parseSvgToXml 121 | */ 122 | private fun parseSvgToXml(inputSvg: File, output: OutputStream) { 123 | val method = Svg2Vector::class.java.declaredMethods.first { it.name == "parseSvgToXml" } 124 | when (method.parameterTypes[0]) { 125 | File::class.java -> method(null, inputSvg, output) 126 | else -> method(null, inputSvg.toPath(), output) 127 | } 128 | } -------------------------------------------------------------------------------- /gradle-plugin/src/main/java/io/github/skeptick/libres/plugin/strings/declarations/Classes.kt: -------------------------------------------------------------------------------- 1 | @file:Suppress("FunctionName") 2 | 3 | package io.github.skeptick.libres.plugin.strings.declarations 4 | 5 | import com.squareup.kotlinpoet.* 6 | import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy 7 | import io.github.skeptick.libres.plugin.common.declarations.addExperimentalObjCNameAnnotation 8 | import io.github.skeptick.libres.plugin.strings.capitalizeUS 9 | import io.github.skeptick.libres.plugin.strings.models.LanguageCode 10 | import io.github.skeptick.libres.plugin.strings.models.PluralsResource 11 | import io.github.skeptick.libres.plugin.strings.models.StringResource 12 | import io.github.skeptick.libres.plugin.strings.models.TextResource 13 | import io.github.skeptick.libres.plugin.strings.snakeCaseToCamelCase 14 | import io.github.skeptick.libres.strings.PluralForms 15 | import io.github.skeptick.libres.strings.formatString 16 | import io.github.skeptick.libres.strings.getPluralizedString 17 | 18 | /* 19 | * interface Strings 20 | */ 21 | internal fun StringsInterface(): TypeSpec.Builder { 22 | return TypeSpec.interfaceBuilder("Strings") 23 | } 24 | 25 | /* 26 | * object StringsRu : Strings 27 | */ 28 | internal fun LocalizedStringsObject( 29 | packageName: String, 30 | languageCode: LanguageCode 31 | ): TypeSpec.Builder { 32 | return TypeSpec.objectBuilder("Strings${languageCode.capitalizeUS()}") 33 | .addSuperinterface(ClassName(packageName, "Strings")) 34 | } 35 | 36 | /* 37 | * object MainResStrings { 38 | * private val baseLocale: StringsRu = StringsRu 39 | * private val locales: Map = mapOf("ru" to StringsRu, "en" to StringsEn) 40 | * } 41 | */ 42 | internal fun StringObject( 43 | packageName: String, 44 | name: String, 45 | baseLanguageCode: LanguageCode, 46 | languageCodes: Set, 47 | camelCaseForApple: Boolean 48 | ): TypeSpec.Builder { 49 | return TypeSpec.objectBuilder("${name}Strings") 50 | .addExperimentalObjCNameAnnotation(camelCaseForApple) 51 | .addProperty( 52 | PropertySpec.builder("baseLocale", ClassName(packageName, "Strings${baseLanguageCode.capitalizeUS()}")) 53 | .addModifiers(KModifier.PRIVATE) 54 | .initializer("Strings${baseLanguageCode.capitalizeUS()}") 55 | .build() 56 | ).addProperty( 57 | PropertySpec.builder("locales", LocalesMapTypeName(packageName)) 58 | .initializer("mapOf(%L)", languageCodes.joinToString(", ") { "\"$it\" to Strings${it.capitalizeUS()}" }) 59 | .addModifiers(KModifier.PRIVATE) 60 | .build() 61 | ) 62 | } 63 | 64 | /* 65 | * object MainResStrings 66 | */ 67 | internal fun EmptyStringObject(name: String): TypeSpec.Builder { 68 | return TypeSpec.objectBuilder("${name}Strings") 69 | } 70 | 71 | internal fun CustomFormattedTextResourceClass(type: ClassName, resource: TextResource): TypeSpec.Builder { 72 | return when (resource) { 73 | is StringResource -> CustomFormattedStringClass(type, resource) 74 | is PluralsResource -> CustomFormattedPluralStringClass(type, resource) 75 | } 76 | } 77 | 78 | /* 79 | * class VoidCustomFormattedString(private val value: String) { 80 | * fun format(arg1: String, arg2: String): String { 81 | * return formatString(value, arrayOf(arg1, arg2)) 82 | * } 83 | * } 84 | */ 85 | private fun CustomFormattedStringClass(type: ClassName, resource: StringResource): TypeSpec.Builder { 86 | val parameters = resource.parameters.map { it.snakeCaseToCamelCase(startWithLower = true) }.toSet() 87 | return TypeSpec.classBuilder(type.simpleName) 88 | .primaryConstructor( 89 | FunSpec.constructorBuilder().addParameter("value", String::class).build() 90 | ).addProperty( 91 | PropertySpec.builder("value", String::class).initializer("value").addModifiers(KModifier.PRIVATE).build() 92 | ).addFunction( 93 | FunSpec.builder("format") 94 | .addParameters(parameters.map { ParameterSpec.builder(it, String::class).build() }) 95 | .returns(String::class) 96 | .addStatement("return %L(value, arrayOf(%L))", ::formatString.name, parameters.joinToString(",")) 97 | .build() 98 | ) 99 | } 100 | 101 | /* 102 | * class VoidCustomFormattedPluralString(private val forms: PluralForms, private val languageCode: String) { 103 | * fun format(number: Int, arg1: String, arg2: String) { 104 | * return formatString(getPluralizedString(forms, languageCode, number), arrayOf(arg1, arg2)) 105 | * } 106 | * } 107 | */ 108 | private fun CustomFormattedPluralStringClass(type: ClassName, resource: PluralsResource): TypeSpec.Builder { 109 | val parameters = resource.parameters.map { it.snakeCaseToCamelCase(startWithLower = true) }.toSet() 110 | return TypeSpec.classBuilder(type.simpleName) 111 | .primaryConstructor( 112 | FunSpec.constructorBuilder() 113 | .addParameter("forms", PluralForms::class.asClassName()) 114 | .addParameter("languageCode", String::class) 115 | .build() 116 | ).addProperty( 117 | PropertySpec.builder("forms", PluralForms::class.asClassName()).initializer("forms").addModifiers(KModifier.PRIVATE).build() 118 | ).addProperty( 119 | PropertySpec.builder("languageCode", String::class).initializer("languageCode").addModifiers(KModifier.PRIVATE).build() 120 | ).addFunction( 121 | FunSpec.builder("format") 122 | .addParameter("number", Int::class) 123 | .addParameters(parameters.map { ParameterSpec.builder(it, String::class).build() }) 124 | .returns(String::class) 125 | .addStatement("return %L(%L(forms, languageCode, number), arrayOf(%L))", ::formatString.name, ::getPluralizedString.name, parameters.joinToString(",")) 126 | .build() 127 | ) 128 | } 129 | 130 | private fun LocalesMapTypeName(packageName: String): TypeName { 131 | return Map::class.asClassName().parameterizedBy(String::class.asClassName(), ClassName(packageName, "Strings")) 132 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Libres 2 | 3 | Resources generation in Kotlin Multiplatform. 4 | 5 | ## Setup 6 | 7 | ```kotlin 8 | // build.gradle.kts (project) 9 | 10 | buildscript { 11 | dependencies { 12 | classpath("io.github.skeptick.libres:gradle-plugin:1.2.4") 13 | } 14 | } 15 | ``` 16 | 17 | ```kotlin 18 | // build.gradle.kts (module) 19 | 20 | plugins { 21 | id("io.github.skeptick.libres") 22 | } 23 | 24 | libres { 25 | generatedClassName = "MainRes" // "Res" by default 26 | generateNamedArguments = true // false by default 27 | baseLocaleLanguageCode = "ru" // "en" by default 28 | camelCaseNamesForAppleFramework = false // false by default 29 | } 30 | ``` 31 | 32 | ## Jetpack Compose 33 | 34 | ```kotlin 35 | // build.gradle.kts (module) 36 | 37 | kotlin { 38 | commonMain { 39 | dependencies { 40 | implementation("io.github.skeptick.libres:libres-compose:1.2.4") 41 | } 42 | } 43 | } 44 | ``` 45 | 46 | This artifact provides `painterResource` function that can be used 47 | to get `Painter` from `io.github.skeptick.libres.Image` in common code. 48 | 49 | ## Supported platforms 50 | 51 | - **Android**, **JVM**, **iOS**, **MacOS** and **JS** in Kotlin Multiplatform projects. 52 | - Pure Android or JVM projects with Kotlin. 53 | 54 | ## Requirements 55 | 56 | | | | 57 | |-----------------------|-------------------------------| 58 | | Kotlin | 1.6.20+ | 59 | | Android | 4.1+ (API level 16) | 60 | | Android Gradle Plugin | 7.0+ | 61 | | iOS | 13+ (when using vector icons) | 62 | 63 | \ 64 | :bangbang: Also you need to use [CocoaPods](https://cocoapods.org/) and 65 | [CocoaPods Gradle plugin](https://kotlinlang.org/docs/native-cocoapods-dsl-reference.html) 66 | to export images to iOS application. 67 | If you aren't reusing images in iOS then this condition is optional. 68 | 69 | ## Known issues 70 | 71 | ### iOS 72 | :warning: Cocoapods caches list of resource directories when `pod install` is called, 73 | so bundles directory must exist at this time. 74 | You won't see this issue if your `.podspec` is in `.gitignore` 75 | in any case it's best to be safe with this hook in your Podfile. 76 | 77 | Suppose your Kotlin Framework is added like this: 78 | ```ruby 79 | pod 'umbrella', :path => '../common/umbrella/umbrella.podspec' 80 | ``` 81 | 82 | Then this hook will look like this: 83 | ```ruby 84 | pre_install do |installer| 85 | FileUtils.mkdir_p(installer.sandbox.root.to_s + '/../../common/umbrella/build/generated/libres/apple/libres-bundles') 86 | end 87 | ``` 88 | 89 | ## Usage 90 | 91 | Resources must be stored in `{yourSourceSetName}/libres` 92 | 93 | Multiplatform: 94 | ``` 95 | ├── commonMain 96 | │ ├── kotlin 97 | │ └── libres 98 | │ ├── images 99 | │ │ ├── vector_image.svg 100 | │ │ └── raster_image.png 101 | │ └── strings 102 | │ ├── strings_en.xml 103 | │ └── strings_ru.xml 104 | ``` 105 | 106 | Android or JVM: 107 | ``` 108 | ├── main 109 | │ ├── java 110 | │ └── libres 111 | │ ├── images 112 | │ │ ├── vector_image.svg 113 | │ │ └── raster_image.png 114 | │ └── strings 115 | │ ├── strings_en.xml 116 | │ └── strings_ru.xml 117 | ``` 118 | 119 | ### Strings 120 | Strings are stored in usual for Android form in `xml` files. 121 | The file postfix must contain language code for which these strings are intended. E.g.: `my_app_strings_en.xml` 122 | For each of languages you can create several files and they will be merged during compilation. 123 | ```xml 124 | 125 | 126 | Hello! 127 | Hello ${name}! 128 | 129 | resource 130 | resources 131 | 132 | 133 | ``` 134 | 135 | Kotlin: 136 | ```kotlin 137 | MainRes.string.simple_string 138 | MainRes.string.string_with_arguments.format(name = "John") 139 | MainRes.string.plural_string.format(5) 140 | ``` 141 | Swift: 142 | ```swift 143 | MainRes.shared.string.simple_string 144 | // or MainRes.shared.string.simpleString if `camelCaseNamesForAppleFramework` enabled 145 | ``` 146 | *** 147 | > **Note** 148 | > In this example `MainRes.string.simple_string` will return a string, 149 | > so for better localization support it's not recommended to store the value. 150 | > Get it directly at the place where it's displayed in UI. 151 | > This seems familiar but ability to work directly with strings instead of resource IDs can be misused. 152 | *** 153 | #### [More about localization](docs/LOCALIZATION.md) 154 | 155 | ### Images 156 | 157 | Supported formats: 158 | - PNG 159 | - JPG 160 | - WEBP (Android 4.3+, iOS 14+) 161 | - SVG (iOS 13+) 162 | 163 | For Android SVGs are converted to 164 | [vector drawable](https://developer.android.com/develop/ui/views/graphics/vector-drawable-resources), 165 | for other platforms they copied as is. 166 | 167 | #### Image modifiers 168 | The image filename can contain modifiers in parentheses listed through underscores. 169 | 170 | > **orig** 171 | > 172 | > Used for iOS. Marks image as `Original` (similar to `Render As: Original Image` in XCode Assets Manager). 173 | Recommended for multicolor images. 174 | 175 | > **size** 176 | > 177 | > Applies to bitmaps. Reduces image resolution to specified size. 178 | > - For Android generate images from mdpi to xxxhdpi (where mdpi is 1:1 in pixels to specified size) 179 | > - For iOS generate images from @1x to @3x (where @1x is 1:1 in pixels to specified size) 180 | > - For JVM and JS a single image of specified size is generated. 181 | 182 | Filename examples: 183 | ``` 184 | some_hd_image_(100).jpg 185 | app_logo_(orig).svg 186 | my_colorful_bitmap_(orig)_(150).png 187 | ``` 188 | Kotlin: 189 | ```kotlin 190 | MainRes.image.some_hd_image 191 | MainRes.image.app_logo 192 | MainRes.image.my_colorful_bitmap 193 | ``` 194 | Swift: 195 | ```swift 196 | MainRes.shared.image.some_hd_image 197 | // or MainRes.shared.image.someHdImage if `camelCaseNamesForAppleFramework` enabled 198 | ``` 199 | 200 |
201 |

Why do I see a black/blue box instead of my picture?

202 | 203 | I'm pretty sure your picture is multicolor JPG/SVG with opaque background. 204 | This happens because UIKit recolors this image with accent color. 205 | 206 | Solution: add (orig) modifier to image filename, e.g.: `my_image_(orig).png` 207 |
208 | 209 |
210 |

How to export bitmap from Figma?

211 | 212 | To obtain bundle of PNG images with different resolutions (mdpi-xxxhdpi for Android and @1x-@3x for iOS) do following steps: 213 | 1. Export image from Figma with x4 scale (it matches to the biggest used size — xxxhdpi on Android) 214 | 2. Put it to `libres/images` package 215 | 3. Remember the biggest side value of image represented in Figma 216 | 4. Rename image with the value of the biggest side: 217 | **pic.png** -> **pic_(orig)_({side_value}).png** or **pic_({side_value}).png** 218 | 219 | Sample: 220 | Image size in Figma is **240x89**. Final image name is **pic_(orig)_(240).png** 221 |
222 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | https://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | Copyright 2013-2018 Docker, Inc. 179 | 180 | Licensed under the Apache License, Version 2.0 (the "License"); 181 | you may not use this file except in compliance with the License. 182 | You may obtain a copy of the License at 183 | 184 | https://www.apache.org/licenses/LICENSE-2.0 185 | 186 | Unless required by applicable law or agreed to in writing, software 187 | distributed under the License is distributed on an "AS IS" BASIS, 188 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 189 | See the License for the specific language governing permissions and 190 | limitations under the License. -------------------------------------------------------------------------------- /gradle-plugin/src/main/java/io/github/skeptick/libres/plugin/ResourcesPlugin.kt: -------------------------------------------------------------------------------- 1 | package io.github.skeptick.libres.plugin 2 | 3 | import io.github.skeptick.libres.VERSION 4 | import io.github.skeptick.libres.plugin.common.project.* 5 | import com.android.build.gradle.BaseExtension 6 | import com.android.build.gradle.internal.api.DefaultAndroidSourceFile 7 | import com.android.build.gradle.tasks.GenerateResValues 8 | import com.android.ide.common.symbols.getPackageNameFromManifest 9 | import org.apache.tools.ant.taskdefs.condition.Os 10 | import org.gradle.api.Plugin 11 | import org.gradle.api.Project 12 | import org.gradle.api.artifacts.ProjectDependency 13 | import org.gradle.api.plugins.ExtensionAware 14 | import org.gradle.api.tasks.SourceSet 15 | import org.gradle.jvm.tasks.Jar 16 | import org.gradle.language.jvm.tasks.ProcessResources 17 | import org.gradle.util.GradleVersion 18 | import org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension 19 | import org.jetbrains.kotlin.gradle.dsl.KotlinProjectExtension 20 | import org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet 21 | import org.jetbrains.kotlin.gradle.plugin.cocoapods.CocoapodsExtension 22 | import org.jetbrains.kotlin.gradle.plugin.cocoapods.KotlinCocoapodsPlugin 23 | import org.jetbrains.kotlin.gradle.plugin.mpp.Framework 24 | import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget 25 | import org.jetbrains.kotlin.gradle.plugin.sources.DefaultKotlinSourceSet 26 | import org.jetbrains.kotlin.gradle.tasks.KotlinNativeCompile 27 | import org.jetbrains.kotlin.gradle.tasks.KotlinNativeLink 28 | import org.jetbrains.kotlin.gradle.tasks.PodspecTask 29 | import java.io.File 30 | import io.github.skeptick.libres.plugin.SourceSet as PluginSourceSet 31 | 32 | class ResourcesPlugin : Plugin { 33 | 34 | private var isAndroid = false 35 | private var isKotlin = false 36 | 37 | private lateinit var pluginExtension: ResourcesPluginExtension 38 | private lateinit var inputDirectory: File 39 | private lateinit var mainSourceSet: PluginSourceSet 40 | private val allSourceSets = mutableListOf() 41 | private var outputPackageName: String? = null 42 | 43 | override fun apply(project: Project) { 44 | pluginExtension = project.extensions.create("libres", ResourcesPluginExtension::class.java) 45 | 46 | val setupTasks: (afterAndroid: Boolean) -> Unit = { afterAndroid -> 47 | project.afterEvaluate { 48 | if (!isKotlin || (isAndroid && !afterAndroid)) return@afterEvaluate 49 | it.fetchSourceSets() 50 | it.setDependencies() 51 | it.registerGeneratorsTasks() 52 | it.registerSetupIosExportTasks() 53 | } 54 | } 55 | 56 | val androidPluginHandler = { _: Plugin<*> -> 57 | isAndroid = true 58 | setupTasks(true) 59 | } 60 | 61 | project.plugins.withId("com.android.application", androidPluginHandler) 62 | project.plugins.withId("com.android.library", androidPluginHandler) 63 | project.plugins.withId("com.android.instantapp", androidPluginHandler) 64 | project.plugins.withId("com.android.feature", androidPluginHandler) 65 | project.plugins.withId("com.android.dynamic-feature", androidPluginHandler) 66 | 67 | val kotlinPluginHandler = { _: Plugin<*> -> 68 | isKotlin = true 69 | setupTasks(false) 70 | } 71 | 72 | project.plugins.withId("org.jetbrains.kotlin.multiplatform", kotlinPluginHandler) 73 | project.plugins.withId("org.jetbrains.kotlin.android", kotlinPluginHandler) 74 | project.plugins.withId("org.jetbrains.kotlin.jvm", kotlinPluginHandler) 75 | project.plugins.withId("org.jetbrains.kotlin.js", kotlinPluginHandler) 76 | } 77 | 78 | private fun Project.setDependencies() { 79 | if (project.plugins.hasPlugin("org.jetbrains.kotlin.multiplatform")) { 80 | val sourceSets = project.extensions.getByType(KotlinMultiplatformExtension::class.java).sourceSets 81 | val sourceSet = sourceSets.getByName("commonMain") as DefaultKotlinSourceSet 82 | project.configurations.getByName(sourceSet.apiConfigurationName).dependencies.add( 83 | project.dependencies.create("io.github.skeptick.libres:libres:$VERSION") 84 | ) 85 | } else { 86 | project.configurations.getByName("api").dependencies.add( 87 | project.dependencies.create("io.github.skeptick.libres:libres:$VERSION") 88 | ) 89 | } 90 | } 91 | 92 | private fun Project.fetchSourceSets() { 93 | val buildDir = layout.buildDirectory.asFile.get() 94 | val outputDirectory = File(buildDir, "generated/libres") 95 | val kotlinExtension = project.extensions.getByType(KotlinProjectExtension::class.java) 96 | val commonSourceSet = kotlinExtension.sourceSets.findByName(KotlinSourceSet.COMMON_MAIN_SOURCE_SET_NAME) 97 | val androidExtension = project.extensions.findByName("android") as BaseExtension? 98 | outputPackageName = androidExtension?.packageName 99 | 100 | when { 101 | commonSourceSet != null -> { 102 | inputDirectory = commonSourceSet.resources.sourceDirectories.first().resolveSibling("libres") 103 | mainSourceSet = commonSourceSet.createKotlinSourceSet(outputDirectory, KotlinPlatform.Common) 104 | allSourceSets += kotlinExtension.targets.takeKotlinSourceSet(outputDirectory) 105 | if (androidExtension != null) allSourceSets += androidExtension.findAndroidSourceSet(true, outputDirectory, kotlinExtension) 106 | allSourceSets += mainSourceSet 107 | } 108 | androidExtension != null -> { 109 | val androidMainSourceSet = androidExtension.sourceSets.getByName(SourceSet.MAIN_SOURCE_SET_NAME) 110 | inputDirectory = androidMainSourceSet.resources.srcDirs.first().resolveSibling("libres") 111 | mainSourceSet = androidExtension.findAndroidSourceSet(false, outputDirectory, kotlinExtension) 112 | allSourceSets += mainSourceSet 113 | } 114 | else -> { 115 | val target = kotlinExtension.targets.firstOrNull { it.platform != null } ?: return 116 | val defaultSourceSet = target.compilations.firstOrNull { it.isMainCompilation }?.defaultSourceSet ?: return 117 | mainSourceSet = defaultSourceSet.createKotlinSourceSet(outputDirectory, target.platform!!) 118 | inputDirectory = defaultSourceSet.resources.sourceDirectories.first().resolveSibling("libres") 119 | allSourceSets += mainSourceSet 120 | } 121 | } 122 | } 123 | 124 | private fun Project.registerGeneratorsTasks() { 125 | val stringsInputDirectory = File(inputDirectory, "strings") 126 | val imagesInputDirectory = File(inputDirectory, "images") 127 | val stringsOutputPackageName = listOfNotNull(outputPackageName, "strings").joinToString(".") 128 | val imagesOutputPackageName = listOfNotNull(outputPackageName, "images").joinToString(".") 129 | 130 | val stringsTask = project.tasks.register(GENERATE_STRINGS_TASK_NAME, LibresStringGenerationTask::class.java) { task -> 131 | task.group = TASK_GROUP 132 | task.settings = StringsSettings( 133 | outputPackageName = stringsOutputPackageName, 134 | outputClassName = pluginExtension.generatedClassName, 135 | generateNamedArguments = pluginExtension.generateNamedArguments, 136 | baseLocaleLanguageCode = pluginExtension.baseLocaleLanguageCode, 137 | camelCaseForApple = pluginExtension.camelCaseNamesForAppleFramework && allSourceSets.any { it.platform == KotlinPlatform.Apple } 138 | ) 139 | task.inputDirectory = fileTree(stringsInputDirectory) { config -> 140 | config.include { element -> 141 | !element.isDirectory && element.file.extension.lowercase() in STRINGS_EXTENSIONS 142 | } 143 | } 144 | task.outputDirectory = mainSourceSet.sourcesDir.toOutputDirectory(stringsOutputPackageName) 145 | } 146 | 147 | val imagesTask = project.tasks.register(GENERATE_IMAGES_TASK_NAME, LibresImagesGenerationTask::class.java) { task -> 148 | task.group = TASK_GROUP 149 | task.settings = ImagesSettings( 150 | outputPackageName = imagesOutputPackageName, 151 | outputClassName = pluginExtension.generatedClassName, 152 | camelCaseForApple = pluginExtension.camelCaseNamesForAppleFramework, 153 | appleBundleName = project.appleBundleName 154 | ) 155 | task.inputDirectory = fileTree(imagesInputDirectory) { config -> 156 | config.include { element -> 157 | !element.isDirectory && element.file.extension.lowercase() in IMAGES_EXTENSIONS 158 | } 159 | } 160 | task.outputSourcesDirectories = allSourceSets.associateBy(PluginSourceSet::platform) { 161 | it.sourcesDir.toOutputDirectory(imagesOutputPackageName) 162 | } 163 | task.outputResourcesDirectories = allSourceSets.associateBy(PluginSourceSet::platform) { 164 | when (it.platform) { 165 | KotlinPlatform.Apple -> it.appleAssetsDir(project) 166 | KotlinPlatform.Js, KotlinPlatform.Jvm -> File(it.resourcesDir, "images") 167 | else -> it.resourcesDir 168 | } 169 | } 170 | } 171 | 172 | val bundleTask = project.tasks.register(GENERATE_BUNDLE_TASK_NAME, LibresBundleGenerationTask::class.java) { task -> 173 | task.group = TASK_GROUP 174 | task.bundleName = project.appleBundleName 175 | task.filesToCopy = emptyList() 176 | task.directoryToCompile = allSourceSets.firstNotNullOfOrNull { 177 | if (it.platform == KotlinPlatform.Apple) it.appleAssetsDir(project) else null 178 | } 179 | task.outputDirectory = allSourceSets.firstNotNullOfOrNull { 180 | if (it.platform == KotlinPlatform.Apple) File(it.rootDir, "libres-bundles") else null 181 | } 182 | 183 | task.onlyIf { Os.isFamily(Os.FAMILY_MAC) } 184 | task.dependsOn(GENERATE_IMAGES_TASK_NAME) 185 | } 186 | 187 | val resourcesTask = project.tasks.register(GENERATE_RESOURCES_TASK_NAME, LibresResourcesGenerationTask::class.java) { task -> 188 | task.group = TASK_GROUP 189 | task.settings = ResourcesSettings( 190 | outputPackageName = outputPackageName.orEmpty(), 191 | outputClassName = pluginExtension.generatedClassName, 192 | stringsPackageName = stringsOutputPackageName, 193 | imagesPackageName = imagesOutputPackageName 194 | ) 195 | task.outputDirectory = mainSourceSet.sourcesDir.toOutputDirectory(outputPackageName.orEmpty()) 196 | task.dependsOn(stringsTask) 197 | task.dependsOn(imagesTask) 198 | } 199 | 200 | project.tasks.configureEach { projectTask -> 201 | when { 202 | projectTask is KotlinNativeCompile -> projectTask.dependsOn(bundleTask, resourcesTask) 203 | projectTask is org.jetbrains.kotlin.gradle.dsl.KotlinCompile<*> -> projectTask.dependsOn(resourcesTask) 204 | projectTask is org.jetbrains.kotlin.gradle.tasks.KotlinCompilationTask<*> -> projectTask.dependsOn(resourcesTask) 205 | projectTask is ProcessResources -> projectTask.dependsOn(imagesTask) 206 | projectTask is Jar -> projectTask.dependsOn(resourcesTask) 207 | isAndroid && projectTask is GenerateResValues -> projectTask.dependsOn(imagesTask) 208 | projectTask.name.endsWith("ComposeResourcesForIos") -> projectTask.dependsOn(imagesTask) 209 | } 210 | } 211 | } 212 | 213 | private fun Project.registerSetupIosExportTasks() { 214 | if (!plugins.hasPlugin(KotlinCocoapodsPlugin::class.java)) return 215 | val multiplatformExtension = extensions.findByType(KotlinMultiplatformExtension::class.java) ?: return 216 | 217 | val createBundlesSymlinksTask = tasks.register(CREATE_SYMLINKS_TASK_NAME) { task -> 218 | task.group = TASK_GROUP 219 | task.onlyIf { Os.isFamily(Os.FAMILY_MAC) } 220 | task.doLast { 221 | val exports = getCocoapodsExports(multiplatformExtension).filter { it.isPluginApplied } 222 | createBundlesSymLinks(project, exports) 223 | } 224 | } 225 | 226 | val setupPodspecTask = tasks.register(SETUP_PODSPEC_TASK_NAME) { task -> 227 | task.group = TASK_GROUP 228 | task.doLast { 229 | multiplatformExtension.cocoapodsExtensionOrNull?.let { cocoapods -> 230 | val currentResources = cocoapods.extraSpecAttributes["resources"] ?: "" 231 | cocoapods.extraSpecAttributes["resources"] = project.appendAppleBundles(currentResources) 232 | } 233 | } 234 | } 235 | 236 | tasks.configureEach { projectTask -> 237 | when (projectTask) { 238 | is PodspecTask -> projectTask.dependsOn(setupPodspecTask) 239 | is KotlinNativeLink -> projectTask.dependsOn(createBundlesSymlinksTask) 240 | } 241 | } 242 | } 243 | 244 | private fun Project.getCocoapodsExports(multiplatformExtension: KotlinMultiplatformExtension): List { 245 | val configName = multiplatformExtension.cocoapodsExportConfigurationName ?: return emptyList() 246 | return configurations.getByName(configName).dependencies.filterIsInstance().map { dependency -> 247 | if (GradleVersion.current() < GradleVersion.version("8.11")) { 248 | @Suppress("DEPRECATION") 249 | dependency.dependencyProject 250 | } else { 251 | project(dependency.path) 252 | } 253 | } 254 | } 255 | 256 | companion object { 257 | 258 | private const val LIBRARY_PACKAGE_NAME = "io.github.skeptick.libres" 259 | internal const val STRINGS_PACKAGE_NAME = "$LIBRARY_PACKAGE_NAME.strings" 260 | internal const val IMAGES_PACKAGE_NAME = "$LIBRARY_PACKAGE_NAME.images" 261 | 262 | private const val TASK_GROUP = "libres" 263 | const val GENERATE_RESOURCES_TASK_NAME = "libresGenerateResources" 264 | const val GENERATE_STRINGS_TASK_NAME = "libresGenerateStrings" 265 | const val GENERATE_IMAGES_TASK_NAME = "libresGenerateImages" 266 | const val GENERATE_BUNDLE_TASK_NAME = "libresGenerateIosBundle" 267 | const val CREATE_SYMLINKS_TASK_NAME = "libresCreateSymlinkedBundles" 268 | const val SETUP_PODSPEC_TASK_NAME = "libresSetupPodspecExports" 269 | 270 | private val STRINGS_EXTENSIONS = listOf("xml") 271 | private val IMAGES_EXTENSIONS = listOf("png", "jpg", "jpeg", "webp", "svg") 272 | 273 | private val BaseExtension.packageName: String? 274 | get() = namespace ?: run { 275 | val sourceSet = sourceSets.getByName(SourceSet.MAIN_SOURCE_SET_NAME) 276 | val manifest = sourceSet.manifest as? DefaultAndroidSourceFile ?: return@run null 277 | manifest.srcFile.takeIf(File::exists)?.let(::getPackageNameFromManifest) 278 | } 279 | 280 | private val KotlinMultiplatformExtension?.cocoapodsExtensionOrNull: CocoapodsExtension? 281 | get() = (this as? ExtensionAware)?.extensions?.findByType(CocoapodsExtension::class.java) 282 | 283 | private val KotlinMultiplatformExtension.cocoapodsExportConfigurationName: String? 284 | get() = targets 285 | .filterIsInstance().firstOrNull { it.konanTarget.family.isAppleFamily } 286 | ?.binaries?.filterIsInstance()?.firstOrNull()?.exportConfigurationName 287 | 288 | private fun File.toOutputDirectory(packageName: String) = 289 | File(absolutePath, packageName.replace('.', File.separatorChar)) 290 | 291 | private fun PluginSourceSet.appleAssetsDir(project: Project): File = 292 | File(resourcesDir, "images/${project.appleBundleName}.xcassets") 293 | 294 | private val Project.isPluginApplied: Boolean 295 | get() = plugins.hasPlugin(ResourcesPlugin::class.java) 296 | 297 | } 298 | 299 | } --------------------------------------------------------------------------------