import java.util.Properties import org.jetbrains.compose.desktop.application.dsl.TargetFormat import org.jetbrains.kotlin.gradle.dsl.JvmTarget import org.jetbrains.kotlin.gradle.plugin.KotlinPlatformType import org.jetbrains.kotlin.gradle.plugin.NATIVE_COMPILER_PLUGIN_CLASSPATH_CONFIGURATION_NAME import org.jetbrains.kotlin.gradle.plugin.PLUGIN_CLASSPATH_CONFIGURATION_NAME plugins { alias(libs.plugins.kotlin.multiplatform) alias(libs.plugins.android.kotlin.multiplatform.library) alias(libs.plugins.jetbrains.compose) alias(libs.plugins.kotlin.compose) alias(libs.plugins.kotlin.serialization) alias(libs.plugins.ksp) alias(libs.plugins.androidx.room) } val desktopJavaHome = providers.gradleProperty("yokan.desktop.java.home").orNull // Release pipelines pass -Pyokan.version= and -Pyokan.versionCode=. val defaultVersion = Properties().apply { rootProject.file("version.xcconfig").inputStream().use { load(it) } }.getProperty("YOKAN_VERSION") val yokanVersion = providers.gradleProperty("yokan.version") .orElse(providers.environmentVariable("YOKAN_VERSION")) .orElse(defaultVersion) .map { it.removePrefix("v") } val versionParts = yokanVersion.get().let { version -> require(Regex("(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)").matches(version)) { "Yokan versions must be MAJOR.MINOR.PATCH, optionally prefixed with v." } version.split('.').map(String::toInt).also { (major, minor, patch) -> require(major <= 2099 && minor <= 999 && patch <= 999) { "Yokan version exceeds Android version-code limits." } } } val yokanChannel = when { versionParts[0] > 0 -> "stable" versionParts[1] > 0 -> "beta" else -> "alpha" } val yokanVersionCode = providers.gradleProperty("yokan.versionCode") .orElse(providers.environmentVariable("YOKAN_VERSION_CODE")) .map(String::toInt) .orElse((versionParts[0] * 1_000_000 + versionParts[1] * 1_000 + versionParts[2]).coerceAtLeast(1)) require(yokanVersionCode.get() in 1..2_100_000_000) { "Yokan versionCode must be between 1 and 2100000000." } // :androidApp reads these for its versionCode/versionName. extra["yokanVersionName"] = yokanVersion.get() extra["yokanVersionCode"] = yokanVersionCode.get() val generatedVersionSources = layout.buildDirectory.dir("generated/yokanVersion/kotlin") val generateYokanVersion = tasks.register("generateYokanVersion") { inputs.property("version", yokanVersion) outputs.dir(generatedVersionSources) doLast { val source = generatedVersionSources.get().file("eu/friedcutlet/yokan/services/updates/YokanVersion.kt").asFile source.parentFile.mkdirs() source.writeText(""" package eu.friedcutlet.yokan.services.updates /** Installed version supplied by the build, shared by every platform. */ const val YOKAN_VERSION = "${yokanVersion.get()}" """.trimIndent() + "\n") } } tasks.register("printYokanVersion") { group = "help" description = "Print the resolved version, channel, and platform build number." doLast { println("version=${yokanVersion.get()}") println("channel=$yokanChannel") println("versionCode=${yokanVersionCode.get()}") } } val javafxPlatform = run { val os = System.getProperty("os.name").lowercase() val arch = System.getProperty("os.arch").lowercase() when { "mac" in os || "darwin" in os -> if ("aarch64" in arch || "arm64" in arch) "mac-aarch64" else "mac" "win" in os -> if ("86" in arch && "64" !in arch) "win-x86" else "win" "linux" in os && ("aarch64" in arch || "arm64" in arch) -> "linux-aarch64" else -> "linux" } } // The upstream jar bundles natives for all five desktop platforms plus a 52 MB macOS dSYM // (140 MB unpacked, ~33 MB usable). Only the host platform can load, so repack just that one. val onnxNativePlatform = when (javafxPlatform) { "mac-aarch64" -> "osx-aarch64" "mac" -> "osx-x64" "win", "win-x86" -> "win-x64" "linux-aarch64" -> "linux-aarch64" else -> "linux-x64" } // 1.24.x no longer ships the Intel macOS JNI binary; retain the last bundled variant there. val onnxDesktopVersion = if (onnxNativePlatform == "osx-x64") libs.versions.onnxruntimeIntelMac.get() else libs.versions.onnxruntime.get() val onnxRuntimeSlim = tasks.register("onnxRuntimeSlim") { val upstream = configurations.detachedConfiguration( dependencies.create("${libs.onnxruntime.jvm.get().module}:$onnxDesktopVersion"), ) archiveBaseName.set("onnxruntime-$onnxNativePlatform") archiveVersion.set(onnxDesktopVersion) from(upstream.elements.map { zipTree(it.single().asFile) }) (setOf("osx-aarch64", "osx-x64", "win-x64", "linux-aarch64", "linux-x64") - onnxNativePlatform) .forEach { exclude("ai/onnxruntime/native/$it/**") } exclude("**/*.dSYM/**") } // Room KMP: persists generated schema next to the source so we can review // migrations in code review and ship them alongside the entity. room { schemaDirectory("$projectDir/schemas") } kotlin { compilerOptions { freeCompilerArgs.add("-Xexpect-actual-classes") // Every target compiles warning-free; keep it that way so deprecations and dead code surface in CI. allWarningsAsErrors.set(true) } // Intermediate source sets on top of the default template (commonMain → iosMain etc.). // A target may sit in several groups; each group gets a Main and Test set, // and Android host tests join the Test side like every other platform test compilation. // withAndroidTarget() only matches the legacy androidTarget(); the AGP KMP library target is androidJvm. @OptIn(org.jetbrains.kotlin.gradle.ExperimentalKotlinGradlePluginApi::class) applyDefaultHierarchyTemplate { common { // Everything but the browser: Room + bundled SQLite, QuickJS (zipline), libmpv. group("nonWeb") { group("jvmCommon") { withCompilations { it.platformType == KotlinPlatformType.androidJvm } withJvm() } group("ios") } group("platformWebView") { withCompilations { it.platformType == KotlinPlatformType.androidJvm } group("ios") } // Compose's Skia-backed targets, where coil3.Bitmap is org.jetbrains.skia.Bitmap. group("skiko") { withJvm() group("ios") withWasmJs() } } } android { namespace = "eu.friedcutlet.yokan" compileSdk = 37 minSdk = 26 compilerOptions { jvmTarget.set(JvmTarget.JVM_17) } androidResources { enable = true } withHostTest {} } jvm("desktop") @OptIn(org.jetbrains.kotlin.gradle.ExperimentalWasmDsl::class) wasmJs { browser { testTask { useKarma { useChromeHeadless() } } } binaries.executable() } // Compose Multiplatform 1.12 no longer publishes iosX64 (Intel simulator) artifacts. listOf( iosArm64(), iosSimulatorArm64(), ).forEach { target -> target.compilations.getByName("main").cinterops.create("embeddedMihon") { definitionFile.set(project.file("src/nativeInterop/cinterop/MihonEmbeddedBridge.def")) includeDirs(rootProject.file("iosApp")) } target.compilations.getByName("main").cinterops.create("panelColorizer") { definitionFile.set(project.file("src/nativeInterop/cinterop/PanelColorizer.def")) includeDirs(rootProject.file("iosApp")) } target.binaries.framework { baseName = "YokanShared" binaryOption("bundleId", "eu.friedcutlet.yokan") isStatic = true // Alongside release dependency caches (gradle.properties), skip this costly // call-graph pass to leave heap headroom on Codemagic's 8 GB M2 runner. // It only removes redundant "file initialized?" checks. freeCompilerArgs += "-Xdisable-phases=RemoveRedundantCallsToStaticInitializersPhase" } // The ObjC++ bridges (iosApp/*.mm) are compiled by the Xcode app target, not by // Gradle, so the test executable resolves their symbols lazily; tests never call them. target.binaries.all { if (this is org.jetbrains.kotlin.gradle.plugin.mpp.TestExecutable) { linkerOpts("-undefined", "dynamic_lookup") } } } sourceSets { named("commonMain") { kotlin.srcDir(generateYokanVersion.map { generatedVersionSources.get() }) dependencies { implementation(libs.compose.runtime) implementation(libs.compose.foundation) implementation(libs.compose.material3) implementation(libs.compose.material.icons.extended) implementation(libs.compose.components.resources) // Multiplatform NavigationBackHandler — wires system back / predictive // back on Android, swipe-back on iOS, ESC on desktop into a // commonMain composable. implementation(libs.navigationevent.compose) implementation(libs.coil.compose) implementation(libs.coil.network.ktor3) implementation(libs.kotlinx.coroutines.core) implementation(libs.kotlinx.serialization.json) implementation(libs.kotlinx.datetime) implementation(libs.cryptography.core) implementation(libs.cryptography.provider.optimal) implementation(libs.ktor.client.core) implementation(libs.ktor.client.websockets) implementation(libs.ktor.client.content.negotiation) implementation(libs.ktor.serialization.kotlinx.json) implementation(libs.androidx.lifecycle.viewmodel) implementation(libs.androidx.lifecycle.viewmodel.compose) implementation(libs.androidx.lifecycle.runtime.compose) implementation(project(":media-compat")) implementation(libs.materialkolor) implementation(libs.yokan.ext) } } // Everything shared by Android/desktop/iOS but impossible on the // browser: Room + bundled SQLite, the QuickJS (zipline) extension // engine, and the native libmpv player bindings. named("nonWebMain") { dependencies { implementation(libs.kmp.mpv) // Room KMP runtime + bundled SQLite driver for non-Android // targets. Replaces the whole-snapshot JSON serializer for // mutation paths once the migration lands. implementation(libs.room.runtime) implementation(libs.sqlite.bundled) implementation(libs.zipline) } } named("platformWebViewMain") { dependencies { implementation(libs.compose.webview.multiplatform) } } named("jvmCommonMain") { dependencies { // yokan-ext's Mihon API brings okhttp, okhttp-brotli and logging-interceptor into // the Android graph; the BOM keeps every OkHttp artifact on the catalog's version // here and in :androidApp. implementation(project.dependencies.platform(libs.okhttp.bom)) implementation(libs.ktor.client.okhttp) implementation(libs.okhttp) } } named("androidMain") { dependencies { implementation(libs.onnxruntime.android) implementation(libs.androidx.activity.compose) implementation(libs.androidx.work.runtime.ktx) // WebView profiles (ProfileStore/setProfile) isolate each extra profile's browser storage. implementation(libs.androidx.webkit) implementation(libs.kotlinx.coroutines.android) } } named("androidHostTest") { dependencies { implementation(kotlin("test")) } } named("desktopMain") { dependencies { // AVIF is not decoded by the bundled Skia codec. Pure Java keeps desktop // support independent of installed codecs and native CPU/OS binaries. implementation(libs.avif) implementation(files(onnxRuntimeSlim)) implementation(compose.desktop.currentOs) implementation(libs.kotlinx.coroutines.swing) // Desktop in-app WebView fallback. Cloudflare challenge flows // are handled through a real external Chromium browser session // in WebViewService.desktop.kt to avoid loading libjcef. // javafx-web needs javafx-media classes; its transitive dependency resolves to the empty, // classifier-less jar, so WebView creation failed with NoClassDefFoundError. listOf(libs.javafx.base, libs.javafx.graphics, libs.javafx.controls, libs.javafx.swing, libs.javafx.web, libs.javafx.media) .forEach { implementation(project.dependencies.variantOf(it) { classifier(javafxPlatform) }) } } } iosMain.dependencies { implementation(libs.ktor.client.darwin) } named("wasmJsMain") { dependencies { implementation(libs.ktor.client.js) implementation(libs.kotlinx.browser) } } named("commonTest") { dependencies { implementation(kotlin("test")) implementation(libs.kotlinx.coroutines.test) implementation(libs.ktor.client.mock) } } } } // Apply Room's KSP processor for every Kotlin target. Configurations // (`kspAndroid`, `kspDesktop`, `kspIosArm64`, …) are created lazily by the // KMP plugin after target declarations, so this block has to sit AFTER the // `kotlin { }` configuration above. dependencies { add(PLUGIN_CLASSPATH_CONFIGURATION_NAME, libs.zipline.kotlin.plugin) add(NATIVE_COMPILER_PLUGIN_CLASSPATH_CONFIGURATION_NAME, libs.zipline.kotlin.plugin) add("kspAndroid", libs.room.compiler) add("kspDesktop", libs.room.compiler) add("kspIosArm64", libs.room.compiler) add("kspIosSimulatorArm64", libs.room.compiler) } // nonWebTest also runs as Android host-JVM unit tests, where zipline's Android // artifact has no libquickjs; these QuickJS tests run on desktop and iOS instead. tasks.withType().matching { it.name == "testAndroidHostTest" }.configureEach { exclude("**/QuickJsJavaScriptEngineTest*", "**/HtmlDomRuntimeTest*") } compose.desktop { application { mainClass = "eu.friedcutlet.yokan.MainKt" buildTypes.release.proguard { optimize.set(false) configurationFiles.from(project.file("release-rules.pro")) } desktopJavaHome?.let { javaHome = it } jvmArgs += listOf( "--add-opens", "java.desktop/sun.awt=ALL-UNNAMED", "--add-opens", "java.desktop/java.awt.peer=ALL-UNNAMED", ) if (System.getProperty("os.name").lowercase().contains("mac")) { jvmArgs += listOf( "--add-opens", "java.desktop/sun.lwawt=ALL-UNNAMED", "--add-opens", "java.desktop/sun.lwawt.macosx=ALL-UNNAMED", ) } nativeDistributions { targetFormats(TargetFormat.Dmg, TargetFormat.Msi, TargetFormat.Deb) // Backup files open Yokan's restore preview (path argument on Windows/Linux, open-file event on macOS). val backupTypes = listOf( "tachibk" to "Tachiyomi backup", "yokanbak" to "Yokan encrypted backup", "backup" to "Mangayomi backup", ) fun org.jetbrains.compose.desktop.application.dsl.AbstractPlatformSettings.backupAssociations() = backupTypes.forEach { (extension, description) -> fileAssociation("application/octet-stream", extension, description) } macOS { iconFile.set(rootProject.file("packaging/icons/Yokan.icns")) // jpackage requires a positive macOS major version, including for previews. // Offset every channel equally to preserve installer upgrade ordering. packageVersion = "${versionParts[0] + 1}.${versionParts[1]}.${versionParts[2]}" backupAssociations() infoPlist { extraKeysRawXml = """ CFBundleURLTypes CFBundleURLName eu.friedcutlet.yokan CFBundleURLSchemes yokan tachiyomi mihon aniyomi animetail """.trimIndent() } } windows { iconFile.set(rootProject.file("packaging/icons/yokan.ico")) backupAssociations() } linux { iconFile.set(rootProject.file("packaging/icons/yokan.png")) backupAssociations() } packageName = "Yokan" // Native installers need a numeric MAJOR.MINOR.PATCH. packageVersion = yokanVersion.get() // Without these the packaged app dies on startup with // NoClassDefFoundError java/net/http/HttpClient — the jlink image only gets // what is listed here. Regenerate with :composeApp:suggestRuntimeModules. modules( "java.instrument", "java.management", "java.net.http", "jdk.jfr", "jdk.jsobject", "jdk.unsupported", "jdk.unsupported.desktop", "jdk.xml.dom", ) } } } listOf( "yokan.generated.repository", "yokan.live.extensions", "yokan.live.itemType", "yokan.live.parallelism", ).forEach { key -> providers.systemProperty(key).orNull?.let { value -> tasks.withType().configureEach { systemProperty(key, value) if (key == "yokan.generated.repository") { inputs.file(value).withPropertyName("yokanGeneratedRepository") } } } } // Anything a test writes under the desktop data root must land in build/, never in the // developer's real ~/.local/share/yokan (desktopDataRoot honours XDG_DATA_HOME). tasks.withType().configureEach { environment("XDG_DATA_HOME", layout.buildDirectory.dir("test-data").get().asFile.absolutePath) } // Packaging tests read these native/installer assets directly, outside the desktop classpath. // Track them so changing only an icon or launcher manifest still reruns the contract checks. tasks.withType().configureEach { if (name == "desktopTest") { inputs.files( file("src/androidMain/AndroidManifest.xml"), fileTree("src/androidMain/res") { include("**/ic_torii_*.xml", "**/ic_launcher*", "values/app_icon_colors.xml") }, rootProject.fileTree("iosApp/Assets.xcassets"), rootProject.fileTree("packaging/icons"), file("src/wasmJsMain/resources/favicon.png"), ) } }