Yokan / rebuild
Course 1 8624561

build.gradle.kts

composeApp/build.gradle.kts

configuration / resource463 lines
1import java.util.Properties2import org.jetbrains.compose.desktop.application.dsl.TargetFormat3import org.jetbrains.kotlin.gradle.dsl.JvmTarget4import org.jetbrains.kotlin.gradle.plugin.KotlinPlatformType5import org.jetbrains.kotlin.gradle.plugin.NATIVE_COMPILER_PLUGIN_CLASSPATH_CONFIGURATION_NAME6import org.jetbrains.kotlin.gradle.plugin.PLUGIN_CLASSPATH_CONFIGURATION_NAME78plugins {9    alias(libs.plugins.kotlin.multiplatform)10    alias(libs.plugins.android.kotlin.multiplatform.library)11    alias(libs.plugins.jetbrains.compose)12    alias(libs.plugins.kotlin.compose)13    alias(libs.plugins.kotlin.serialization)14    alias(libs.plugins.ksp)15    alias(libs.plugins.androidx.room)16}1718val desktopJavaHome = providers.gradleProperty("yokan.desktop.java.home").orNull19// Release pipelines pass -Pyokan.version=<tag without v> and -Pyokan.versionCode=<n>.20val defaultVersion = Properties().apply {21    rootProject.file("version.xcconfig").inputStream().use { load(it) }22}.getProperty("YOKAN_VERSION")23val yokanVersion = providers.gradleProperty("yokan.version")24    .orElse(providers.environmentVariable("YOKAN_VERSION"))25    .orElse(defaultVersion)26    .map { it.removePrefix("v") }27val versionParts = yokanVersion.get().let { version ->28    require(Regex("(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)").matches(version)) {29        "Yokan versions must be MAJOR.MINOR.PATCH, optionally prefixed with v."30    }31    version.split('.').map(String::toInt).also { (major, minor, patch) ->32        require(major <= 2099 && minor <= 999 && patch <= 999) { "Yokan version exceeds Android version-code limits." }33    }34}35val yokanChannel = when {36    versionParts[0] > 0 -> "stable"37    versionParts[1] > 0 -> "beta"38    else -> "alpha"39}40val yokanVersionCode = providers.gradleProperty("yokan.versionCode")41    .orElse(providers.environmentVariable("YOKAN_VERSION_CODE"))42    .map(String::toInt)43    .orElse((versionParts[0] * 1_000_000 + versionParts[1] * 1_000 + versionParts[2]).coerceAtLeast(1))44require(yokanVersionCode.get() in 1..2_100_000_000) { "Yokan versionCode must be between 1 and 2100000000." }45// :androidApp reads these for its versionCode/versionName.46extra["yokanVersionName"] = yokanVersion.get()47extra["yokanVersionCode"] = yokanVersionCode.get()4849val generatedVersionSources = layout.buildDirectory.dir("generated/yokanVersion/kotlin")50val generateYokanVersion = tasks.register("generateYokanVersion") {51    inputs.property("version", yokanVersion)52    outputs.dir(generatedVersionSources)53    doLast {54        val source = generatedVersionSources.get().file("eu/friedcutlet/yokan/services/updates/YokanVersion.kt").asFile55        source.parentFile.mkdirs()56        source.writeText("""57            package eu.friedcutlet.yokan.services.updates5859            /** Installed version supplied by the build, shared by every platform. */60            const val YOKAN_VERSION = "${yokanVersion.get()}"61        """.trimIndent() + "\n")62    }63}64tasks.register("printYokanVersion") {65    group = "help"66    description = "Print the resolved version, channel, and platform build number."67    doLast {68        println("version=${yokanVersion.get()}")69        println("channel=$yokanChannel")70        println("versionCode=${yokanVersionCode.get()}")71    }72}73val javafxPlatform = run {74    val os = System.getProperty("os.name").lowercase()75    val arch = System.getProperty("os.arch").lowercase()76    when {77        "mac" in os || "darwin" in os -> if ("aarch64" in arch || "arm64" in arch) "mac-aarch64" else "mac"78        "win" in os -> if ("86" in arch && "64" !in arch) "win-x86" else "win"79        "linux" in os && ("aarch64" in arch || "arm64" in arch) -> "linux-aarch64"80        else -> "linux"81    }82}83// The upstream jar bundles natives for all five desktop platforms plus a 52 MB macOS dSYM84// (140 MB unpacked, ~33 MB usable). Only the host platform can load, so repack just that one.85val onnxNativePlatform = when (javafxPlatform) {86    "mac-aarch64" -> "osx-aarch64"87    "mac" -> "osx-x64"88    "win", "win-x86" -> "win-x64"89    "linux-aarch64" -> "linux-aarch64"90    else -> "linux-x64"91}92// 1.24.x no longer ships the Intel macOS JNI binary; retain the last bundled variant there.93val onnxDesktopVersion =94    if (onnxNativePlatform == "osx-x64") libs.versions.onnxruntimeIntelMac.get() else libs.versions.onnxruntime.get()95val onnxRuntimeSlim = tasks.register<Jar>("onnxRuntimeSlim") {96    val upstream = configurations.detachedConfiguration(97        dependencies.create("${libs.onnxruntime.jvm.get().module}:$onnxDesktopVersion"),98    )99    archiveBaseName.set("onnxruntime-$onnxNativePlatform")100    archiveVersion.set(onnxDesktopVersion)101    from(upstream.elements.map { zipTree(it.single().asFile) })102    (setOf("osx-aarch64", "osx-x64", "win-x64", "linux-aarch64", "linux-x64") - onnxNativePlatform)103        .forEach { exclude("ai/onnxruntime/native/$it/**") }104    exclude("**/*.dSYM/**")105}106107// Room KMP: persists generated schema next to the source so we can review108// migrations in code review and ship them alongside the entity.109room {110    schemaDirectory("$projectDir/schemas")111}112113kotlin {114    compilerOptions {115        freeCompilerArgs.add("-Xexpect-actual-classes")116        // Every target compiles warning-free; keep it that way so deprecations and dead code surface in CI.117        allWarningsAsErrors.set(true)118    }119120    // Intermediate source sets on top of the default template (commonMain → iosMain etc.).121    // A target may sit in several groups; each group gets a <name>Main and <name>Test set,122    // and Android host tests join the Test side like every other platform test compilation.123    // withAndroidTarget() only matches the legacy androidTarget(); the AGP KMP library target is androidJvm.124    @OptIn(org.jetbrains.kotlin.gradle.ExperimentalKotlinGradlePluginApi::class)125    applyDefaultHierarchyTemplate {126        common {127            // Everything but the browser: Room + bundled SQLite, QuickJS (zipline), libmpv.128            group("nonWeb") {129                group("jvmCommon") {130                    withCompilations { it.platformType == KotlinPlatformType.androidJvm }131                    withJvm()132                }133                group("ios")134            }135            group("platformWebView") {136                withCompilations { it.platformType == KotlinPlatformType.androidJvm }137                group("ios")138            }139            // Compose's Skia-backed targets, where coil3.Bitmap is org.jetbrains.skia.Bitmap.140            group("skiko") {141                withJvm()142                group("ios")143                withWasmJs()144            }145        }146    }147148    android {149        namespace = "eu.friedcutlet.yokan"150        compileSdk = 37151        minSdk = 26152        compilerOptions {153            jvmTarget.set(JvmTarget.JVM_17)154        }155        androidResources { enable = true }156        withHostTest {}157    }158159    jvm("desktop")160161    @OptIn(org.jetbrains.kotlin.gradle.ExperimentalWasmDsl::class)162    wasmJs {163        browser {164            testTask { useKarma { useChromeHeadless() } }165        }166        binaries.executable()167    }168169    // Compose Multiplatform 1.12 no longer publishes iosX64 (Intel simulator) artifacts.170    listOf(171        iosArm64(),172        iosSimulatorArm64(),173    ).forEach { target ->174        target.compilations.getByName("main").cinterops.create("embeddedMihon") {175            definitionFile.set(project.file("src/nativeInterop/cinterop/MihonEmbeddedBridge.def"))176            includeDirs(rootProject.file("iosApp"))177        }178        target.compilations.getByName("main").cinterops.create("panelColorizer") {179            definitionFile.set(project.file("src/nativeInterop/cinterop/PanelColorizer.def"))180            includeDirs(rootProject.file("iosApp"))181        }182        target.binaries.framework {183            baseName = "YokanShared"184            binaryOption("bundleId", "eu.friedcutlet.yokan")185            isStatic = true186            // Alongside release dependency caches (gradle.properties), skip this costly187            // call-graph pass to leave heap headroom on Codemagic's 8 GB M2 runner.188            // It only removes redundant "file initialized?" checks.189            freeCompilerArgs += "-Xdisable-phases=RemoveRedundantCallsToStaticInitializersPhase"190        }191        // The ObjC++ bridges (iosApp/*.mm) are compiled by the Xcode app target, not by192        // Gradle, so the test executable resolves their symbols lazily; tests never call them.193        target.binaries.all {194            if (this is org.jetbrains.kotlin.gradle.plugin.mpp.TestExecutable) {195                linkerOpts("-undefined", "dynamic_lookup")196            }197        }198    }199200    sourceSets {201        named("commonMain") {202            kotlin.srcDir(generateYokanVersion.map { generatedVersionSources.get() })203            dependencies {204                implementation(libs.compose.runtime)205                implementation(libs.compose.foundation)206                implementation(libs.compose.material3)207                implementation(libs.compose.material.icons.extended)208                implementation(libs.compose.components.resources)209                // Multiplatform NavigationBackHandler — wires system back / predictive210                // back on Android, swipe-back on iOS, ESC on desktop into a211                // commonMain composable.212                implementation(libs.navigationevent.compose)213                implementation(libs.coil.compose)214                implementation(libs.coil.network.ktor3)215                implementation(libs.kotlinx.coroutines.core)216                implementation(libs.kotlinx.serialization.json)217                implementation(libs.kotlinx.datetime)218                implementation(libs.cryptography.core)219                implementation(libs.cryptography.provider.optimal)220                implementation(libs.ktor.client.core)221                implementation(libs.ktor.client.websockets)222                implementation(libs.ktor.client.content.negotiation)223                implementation(libs.ktor.serialization.kotlinx.json)224                implementation(libs.androidx.lifecycle.viewmodel)225                implementation(libs.androidx.lifecycle.viewmodel.compose)226                implementation(libs.androidx.lifecycle.runtime.compose)227                implementation(project(":media-compat"))228                implementation(libs.materialkolor)229                implementation(libs.yokan.ext)230            }231        }232233        // Everything shared by Android/desktop/iOS but impossible on the234        // browser: Room + bundled SQLite, the QuickJS (zipline) extension235        // engine, and the native libmpv player bindings.236        named("nonWebMain") {237            dependencies {238                implementation(libs.kmp.mpv)239                // Room KMP runtime + bundled SQLite driver for non-Android240                // targets. Replaces the whole-snapshot JSON serializer for241                // mutation paths once the migration lands.242                implementation(libs.room.runtime)243                implementation(libs.sqlite.bundled)244                implementation(libs.zipline)245            }246        }247248        named("platformWebViewMain") {249            dependencies {250                implementation(libs.compose.webview.multiplatform)251            }252        }253254        named("jvmCommonMain") {255            dependencies {256                // yokan-ext's Mihon API brings okhttp, okhttp-brotli and logging-interceptor into257                // the Android graph; the BOM keeps every OkHttp artifact on the catalog's version258                // here and in :androidApp.259                implementation(project.dependencies.platform(libs.okhttp.bom))260                implementation(libs.ktor.client.okhttp)261                implementation(libs.okhttp)262            }263        }264265        named("androidMain") {266            dependencies {267                implementation(libs.onnxruntime.android)268                implementation(libs.androidx.activity.compose)269                implementation(libs.androidx.work.runtime.ktx)270                // WebView profiles (ProfileStore/setProfile) isolate each extra profile's browser storage.271                implementation(libs.androidx.webkit)272                implementation(libs.kotlinx.coroutines.android)273            }274        }275276        named("androidHostTest") {277            dependencies {278                implementation(kotlin("test"))279            }280        }281282        named("desktopMain") {283            dependencies {284                // AVIF is not decoded by the bundled Skia codec. Pure Java keeps desktop285                // support independent of installed codecs and native CPU/OS binaries.286                implementation(libs.avif)287                implementation(files(onnxRuntimeSlim))288                implementation(compose.desktop.currentOs)289                implementation(libs.kotlinx.coroutines.swing)290                // Desktop in-app WebView fallback. Cloudflare challenge flows291                // are handled through a real external Chromium browser session292                // in WebViewService.desktop.kt to avoid loading libjcef.293                // javafx-web needs javafx-media classes; its transitive dependency resolves to the empty,294                // classifier-less jar, so WebView creation failed with NoClassDefFoundError.295                listOf(libs.javafx.base, libs.javafx.graphics, libs.javafx.controls, libs.javafx.swing, libs.javafx.web, libs.javafx.media)296                    .forEach { implementation(project.dependencies.variantOf(it) { classifier(javafxPlatform) }) }297            }298        }299300        iosMain.dependencies {301            implementation(libs.ktor.client.darwin)302        }303304        named("wasmJsMain") {305            dependencies {306                implementation(libs.ktor.client.js)307                implementation(libs.kotlinx.browser)308            }309        }310311        named("commonTest") {312            dependencies {313                implementation(kotlin("test"))314                implementation(libs.kotlinx.coroutines.test)315                implementation(libs.ktor.client.mock)316            }317        }318    }319}320321// Apply Room's KSP processor for every Kotlin target. Configurations322// (`kspAndroid`, `kspDesktop`, `kspIosArm64`, …) are created lazily by the323// KMP plugin after target declarations, so this block has to sit AFTER the324// `kotlin { }` configuration above.325dependencies {326    add(PLUGIN_CLASSPATH_CONFIGURATION_NAME, libs.zipline.kotlin.plugin)327    add(NATIVE_COMPILER_PLUGIN_CLASSPATH_CONFIGURATION_NAME, libs.zipline.kotlin.plugin)328    add("kspAndroid", libs.room.compiler)329    add("kspDesktop", libs.room.compiler)330    add("kspIosArm64", libs.room.compiler)331    add("kspIosSimulatorArm64", libs.room.compiler)332}333334// nonWebTest also runs as Android host-JVM unit tests, where zipline's Android335// artifact has no libquickjs; these QuickJS tests run on desktop and iOS instead.336tasks.withType<org.gradle.api.tasks.testing.Test>().matching { it.name == "testAndroidHostTest" }.configureEach {337    exclude("**/QuickJsJavaScriptEngineTest*", "**/HtmlDomRuntimeTest*")338}339340compose.desktop {341    application {342        mainClass = "eu.friedcutlet.yokan.MainKt"343        buildTypes.release.proguard {344            optimize.set(false)345            configurationFiles.from(project.file("release-rules.pro"))346        }347        desktopJavaHome?.let { javaHome = it }348        jvmArgs += listOf(349            "--add-opens",350            "java.desktop/sun.awt=ALL-UNNAMED",351            "--add-opens",352            "java.desktop/java.awt.peer=ALL-UNNAMED",353        )354        if (System.getProperty("os.name").lowercase().contains("mac")) {355            jvmArgs += listOf(356                "--add-opens",357                "java.desktop/sun.lwawt=ALL-UNNAMED",358                "--add-opens",359                "java.desktop/sun.lwawt.macosx=ALL-UNNAMED",360            )361        }362363        nativeDistributions {364            targetFormats(TargetFormat.Dmg, TargetFormat.Msi, TargetFormat.Deb)365            // Backup files open Yokan's restore preview (path argument on Windows/Linux, open-file event on macOS).366            val backupTypes = listOf(367                "tachibk" to "Tachiyomi backup",368                "yokanbak" to "Yokan encrypted backup",369                "backup" to "Mangayomi backup",370            )371            fun org.jetbrains.compose.desktop.application.dsl.AbstractPlatformSettings.backupAssociations() =372                backupTypes.forEach { (extension, description) -> fileAssociation("application/octet-stream", extension, description) }373            macOS {374                iconFile.set(rootProject.file("packaging/icons/Yokan.icns"))375                // jpackage requires a positive macOS major version, including for previews.376                // Offset every channel equally to preserve installer upgrade ordering.377                packageVersion = "${versionParts[0] + 1}.${versionParts[1]}.${versionParts[2]}"378                backupAssociations()379                infoPlist {380                    extraKeysRawXml = """381                        <key>CFBundleURLTypes</key>382                        <array>383                            <dict>384                                <key>CFBundleURLName</key>385                                <string>eu.friedcutlet.yokan</string>386                                <key>CFBundleURLSchemes</key>387                                <array>388                                    <string>yokan</string>389                                    <string>tachiyomi</string>390                                    <string>mihon</string>391                                    <string>aniyomi</string>392                                    <string>animetail</string>393                                </array>394                            </dict>395                        </array>396                    """.trimIndent()397                }398            }399            windows {400                iconFile.set(rootProject.file("packaging/icons/yokan.ico"))401                backupAssociations()402            }403            linux {404                iconFile.set(rootProject.file("packaging/icons/yokan.png"))405                backupAssociations()406            }407            packageName = "Yokan"408            // Native installers need a numeric MAJOR.MINOR.PATCH.409            packageVersion = yokanVersion.get()410            // Without these the packaged app dies on startup with411            // NoClassDefFoundError java/net/http/HttpClient — the jlink image only gets412            // what is listed here. Regenerate with :composeApp:suggestRuntimeModules.413            modules(414                "java.instrument",415                "java.management",416                "java.net.http",417                "jdk.jfr",418                "jdk.jsobject",419                "jdk.unsupported",420                "jdk.unsupported.desktop",421                "jdk.xml.dom",422            )423        }424    }425}426427listOf(428    "yokan.generated.repository",429    "yokan.live.extensions",430    "yokan.live.itemType",431    "yokan.live.parallelism",432).forEach { key ->433    providers.systemProperty(key).orNull?.let { value ->434        tasks.withType<org.gradle.api.tasks.testing.Test>().configureEach {435            systemProperty(key, value)436            if (key == "yokan.generated.repository") {437                inputs.file(value).withPropertyName("yokanGeneratedRepository")438            }439        }440    }441}442443// Anything a test writes under the desktop data root must land in build/, never in the444// developer's real ~/.local/share/yokan (desktopDataRoot honours XDG_DATA_HOME).445tasks.withType<org.gradle.api.tasks.testing.Test>().configureEach {446    environment("XDG_DATA_HOME", layout.buildDirectory.dir("test-data").get().asFile.absolutePath)447}448449// Packaging tests read these native/installer assets directly, outside the desktop classpath.450// Track them so changing only an icon or launcher manifest still reruns the contract checks.451tasks.withType<org.gradle.api.tasks.testing.Test>().configureEach {452    if (name == "desktopTest") {453        inputs.files(454            file("src/androidMain/AndroidManifest.xml"),455            fileTree("src/androidMain/res") {456                include("**/ic_torii_*.xml", "**/ic_launcher*", "values/app_icon_colors.xml")457            },458            rootProject.fileTree("iosApp/Assets.xcassets"),459            rootProject.fileTree("packaging/icons"),460            file("src/wasmJsMain/resources/favicon.png"),461        )462    }463}464

Search chapters, reference and source filenames.