import java.io.ByteArrayOutputStream import java.io.FileInputStream import java.util.Properties import javax.inject.Inject import org.gradle.api.DefaultTask import org.gradle.api.file.RegularFileProperty import org.gradle.api.provider.Property import org.gradle.api.tasks.Input import org.gradle.api.tasks.InputFile import org.gradle.api.tasks.Optional import org.gradle.api.tasks.OutputFile import org.gradle.api.tasks.TaskAction import org.gradle.process.ExecOperations import org.jetbrains.compose.desktop.application.dsl.TargetFormat import org.jetbrains.kotlin.gradle.dsl.JvmTarget import org.jetbrains.kotlin.gradle.ExperimentalKotlinGradlePluginApi abstract class FinalizeApkTask @Inject constructor( private val execOperations: ExecOperations ) : DefaultTask() { @get:Input abstract val alignmentTool: Property @get:Input abstract val apksignerTool: Property @get:Input abstract val adbTool: Property @get:InputFile abstract val inputApk: RegularFileProperty @get:OutputFile abstract val alignedApk: RegularFileProperty @get:OutputFile abstract val finalApk: RegularFileProperty @get:Input @get:Optional abstract val storeFilePath: Property @get:Input @get:Optional abstract val storePassword: Property @get:Input @get:Optional abstract val keyAlias: Property @get:Input @get:Optional abstract val keyPassword: Property @TaskAction fun run() { println("=== Début de la finalisation de l'APK (Alignement & Signature) ===") val input = inputApk.get().asFile val aligned = alignedApk.get().asFile val signed = finalApk.get().asFile if (!input.exists()) { println("Erreur : L'APK non signé est introuvable à l'emplacement : ${input.absolutePath}") return } // Étape 1 : Zipalign println("1. Exécution de zipalign...") val alignResult = execOperations.exec { commandLine(alignmentTool.get(), "-f", "4", input.absolutePath, aligned.absolutePath) isIgnoreExitValue = true } if (alignResult.exitValue != 0) { println("Erreur lors de l'alignement zipalign (code ${alignResult.exitValue}).") return } println("-> Zipalign réussi.") // Étape 2 : Signature println("2. Signature de l'APK...") val signResult = execOperations.exec { commandLine( apksignerTool.get(), "sign", "--ks", storeFilePath.orElse("").get(), "--ks-pass", "pass:${storePassword.orElse("").get()}", "--key-pass", "pass:${keyPassword.orElse("").get()}", "--ks-key-alias", keyAlias.orElse("").get(), "--out", signed.absolutePath, aligned.absolutePath ) isIgnoreExitValue = true } if (signResult.exitValue != 0) { println("Erreur lors de la signature de l'APK (code ${signResult.exitValue}).") return } println("-> APK signé avec succès : ${signed.absolutePath}") // Étape 3 : Vérification et installation via ADB println("3. Vérification des appareils connectés...") val stdout = ByteArrayOutputStream() val devicesResult = execOperations.exec { commandLine(adbTool.get(), "devices") standardOutput = stdout isIgnoreExitValue = true } if (devicesResult.exitValue != 0) { println("Avertissement : Impossible d'interroger adb devices (code ${devicesResult.exitValue}).") return } val connectedDevices = stdout.toString() .lines() .drop(1) .filter { it.isNotBlank() && it.contains("device") && !it.contains("offline") } if (connectedDevices.isNotEmpty()) { println("-> Appareil(s) détecté(s). Installation de l'APK en cours...") val installResult = execOperations.exec { commandLine(adbTool.get(), "install", "-r", signed.absolutePath) isIgnoreExitValue = true } if (installResult.exitValue == 0) { println("-> Application installée avec succès sur le téléphone !") } else { println("Avertissement : Échec de l'installation via adb (code ${installResult.exitValue}).") } } else { println("-> Aucun appareil connecté. Installation ignorée.") } println("=== Processus terminé ===") } } tasks.register("finalizeApk") { dependsOn("assembleRelease") val apkReleaseDir = layout.buildDirectory.dir("outputs/apk/release") val buildToolsVersion = android.buildToolsVersion val sdkDir = android.sdkDirectory val releaseSigning = android.signingConfigs.getByName("release") alignmentTool.set(sdkDir.resolve("build-tools/$buildToolsVersion/zipalign").absolutePath) apksignerTool.set(sdkDir.resolve("build-tools/$buildToolsVersion/apksigner").absolutePath) adbTool.set(sdkDir.resolve("platform-tools/adb").absolutePath) inputApk.set(apkReleaseDir.map { it.file("composeApp-release.apk") }) alignedApk.set(apkReleaseDir.map { it.file("app-release-aligned.apk") }) finalApk.set(apkReleaseDir.map { it.file("app-release-signed.apk") }) storeFilePath.set(releaseSigning.storeFile?.absolutePath ?: "") storePassword.set(releaseSigning.storePassword ?: "") keyAlias.set(releaseSigning.keyAlias ?: "") keyPassword.set(releaseSigning.keyPassword ?: "") } plugins { alias(libs.plugins.kotlinMultiplatform) alias(libs.plugins.androidApplication) alias(libs.plugins.composeMultiplatform) alias(libs.plugins.composeCompiler) //alias(libs.plugins.composeHotReload) alias(libs.plugins.kotlinSerialization) } val gitVersionCode = getGitCommitCount() val gitVersionName = getGVN() val windowsVersion = getWindowsVersion(gitVersionName) val debianVersion = getDebianVersion(gitVersionName) val desktopVersionName = getCleanDesktopVersion(gitVersionName) kotlin { /*linuxX64 { binaries { executable { } } }*/ androidTarget { @OptIn(ExperimentalKotlinGradlePluginApi::class) compilerOptions { jvmTarget.set(JvmTarget.JVM_11) } } jvm("desktop") afterEvaluate { afterEvaluate { tasks.configureEach { if ( name.startsWith("compile") && name.endsWith("KotlinMetadata") ) { println("disabling $name") enabled = false } } } } sourceSets { val desktopMain by getting androidMain.dependencies { implementation(compose.preview) implementation(libs.androidx.activity.compose) implementation(libs.koin.android) // Koin Android-specific extensions implementation(libs.koin.androidx.compose) implementation("com.google.zxing:core:3.5.4") implementation("com.github.billthefarmer:mididriver:1.25") implementation("com.tom-roush:pdfbox-android:2.0.27.0") implementation("androidx.camera:camera-core:1.3.4") implementation("androidx.camera:camera-camera2:1.3.4") implementation("androidx.camera:camera-lifecycle:1.3.4") implementation("androidx.camera:camera-view:1.3.4") } commonMain.dependencies { // implementation(compose.components.resources) implementation(compose.runtime) implementation(compose.foundation) implementation(compose.material3) implementation(compose.ui) implementation(compose.components.resources) implementation(compose.components.uiToolingPreview) implementation(libs.androidx.lifecycle.viewmodel) implementation(libs.androidx.lifecycle.runtimeCompose) implementation(libs.koin.core) // Koin core for shared logic implementation(libs.koin.compose) // Koin for Compose Multiplatform UI implementation(libs.koin.compose.viewmodel) // Koin for KMP ViewModels implementation(libs.kotlinx.serialization.json) implementation(libs.bundles.voyager) implementation(libs.cafe.voyager.koin) implementation(libs.multiplatform.settings) implementation(compose.materialIconsExtended) //implementation(kotlin("stdlib-jdk8")) //implementation("org.jetbrains.compose.foundation:foundation-desktop") implementation("com.russhwolf:multiplatform-settings-no-arg:1.3.0") implementation("io.github.pdvrieze.xmlutil:serialization:0.91.3") // Dépendance sous-jacente pour XML //implementation(libs.ktmidi) } commonTest.dependencies { implementation(libs.kotlin.test) } desktopMain.dependencies { implementation(compose.desktop.currentOs) implementation(libs.kotlinx.coroutinesSwing) implementation("com.google.zxing:core:3.5.4") implementation("com.google.zxing:javase:3.5.4") implementation("org.apache.pdfbox:pdfbox:3.0.7") } } targets.all { compilations.all { compileTaskProvider.configure { compilerOptions { freeCompilerArgs.add("-Xexpect-actual-classes") } } } } } compose.resources { publicResClass = true } android { val localProperties = Properties().apply { val localPropertiesFile = File(rootDir, "local.properties") if (localPropertiesFile.exists()) { FileInputStream(localPropertiesFile).use { load(it) } } } namespace = "mg.dot.feufaro" compileSdk = libs.versions.android.compileSdk.get().toInt() signingConfigs { create("release") { storeFile = file(localProperties.getProperty("signing.storeFile") ?: "fallback.jks") storePassword = localProperties.getProperty("signing.storePassword") keyAlias = localProperties.getProperty("signing.keyAlias") keyPassword = localProperties.getProperty("signing.keyPassword") } } defaultConfig { applicationId = "mg.dot.feufaro" minSdk = libs.versions.android.minSdk.get().toInt() targetSdk = libs.versions.android.targetSdk.get().toInt() versionCode = gitVersionCode versionName = gitVersionName } packaging { resources { excludes += listOf("/META-INF/{AL2.0,LGPL2.1}", "org/bouncycastle/pqc/**", "assets/com/tom_roush/fontbox/resources/cmap/**" ) } jniLibs { useLegacyPackaging = false } } buildTypes { getByName("release") { val enableR8 = project.hasProperty("enableR8") && project.property("enableR8") == "true" isMinifyEnabled = enableR8 isShrinkResources = enableR8 proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") signingConfig = signingConfigs.getByName("release") } } compileOptions { sourceCompatibility = JavaVersion.VERSION_11 targetCompatibility = JavaVersion.VERSION_11 } } dependencies { debugImplementation(compose.uiTooling) } compose.desktop { application { mainClass = "mg.dot.feufaro.MainKt" nativeDistributions { targetFormats(TargetFormat.Exe, TargetFormat.Dmg, TargetFormat.Msi, TargetFormat.Deb) packageName = "Feufar.ooo" packageVersion = windowsVersion licenseFile.set(rootProject.file("LICENSE")) description = "L'application pour lire, éditer et analyser vos partitions Solfa. Ecrivez et créez des harmonies, écoutez ses mélodies et organisez votre playlist en toute simplicité." copyright = "© 2026 dot.mg" vendor = "dotMG Feufarooo" jvmArgs("-Dapp.version=$gitVersionName", "-Dapp.build=$gitVersionCode" ) modules("java.base", "java.desktop", "jdk.unsupported", "java.naming") windows { packageVersion = windowsVersion iconFile.set(project.file("icons/icon.ico")) menuGroup = "Feufaro" perUserInstall = true dirChooser = true shortcut = true menu = true } linux { packageVersion = debianVersion iconFile.set(project.file("icons/icon-linux.png")) shortcut = true appCategory = "Qt;KDE;Audio;" debMaintainer = "feufar.ooo" packageName = "feufar.ooo" } buildTypes.release.proguard { isEnabled.set(false) } } } } val generateFilesIndex = tasks.register("generateFilesIndex") { val resourcesDir = file("src/commonMain/composeResources/files") val outputFile = file("src/commonMain/composeResources/files/feuList.json") inputs.dir(resourcesDir) outputs.file(outputFile) doLast { if (resourcesDir.exists()) { val files = resourcesDir.listFiles() ?.filter { it.extension == "txt" && it.name != "feuList.json" } ?.sortedBy { it.name } ?: emptyList() val jsonContent = buildString { append("{\n") append(" \"internalFeu\": [\n") files.forEachIndexed { index, file -> var title = "Sans titre" file.useLines { lines -> for (l in lines) { if (l.contains("|t:")) { title = l.substringAfter("|t:").substringBefore("|").trim() title = title.replace("\"", "\\\"") break } } } append(" {\n") append(" \"id\": ${index + 1},\n") append(" \"fileName\": \"${file.name}\",\n") append(" \"title\": \"$title\",\n") append(" \"path\": \"assets://${file.name}\"\n") append(" }${if (index < files.size - 1) "," else ""}\n") } append(" ]\n") append("}") } outputFile.writeText(jsonContent) println("Index JSON généré : ${files.size} fichiers.") } } } tasks.configureEach { if (name.startsWith("copyNonXmlValueResources") || name.startsWith("generateComposeResClass")) { dependsOn(generateFilesIndex) } } tasks.register("exportLibs") { group = "distribution" description = "Copie les bibliothèques partagées pour le Thin JAR" // On utilise named("...") pour éviter l'erreur de compilation du script // Dans un projet KMP, la configuration s'appelle généralement "desktopRuntimeClasspath" // ou "jvmRuntimeClasspath" selon le nom de votre cible. val configName = if (configurations.findByName("desktopRuntimeClasspath") != null) { "desktopRuntimeClasspath" } else { "jvmRuntimeClasspath" } from(configurations.named(configName)) into(layout.buildDirectory.dir("libs/shared")) duplicatesStrategy = DuplicatesStrategy.EXCLUDE } fun getGitCommitCount(): Int { return try { val execResult = providers.exec { commandLine("git", "rev-list", "--count", "HEAD") } val countStr = execResult.standardOutput.asText.get().trim() val count = countStr.toIntOrNull() ?: 1 if (count > 0) count else 1 } catch (e: Exception) { 1 } } fun getGVN(): String { val execResult = providers.exec { commandLine("git", "describe", "--tags", "--always", "--abbrev=0") } val rawVersion = execResult.standardOutput.asText.get().trim() return if (rawVersion.isNotEmpty()) { rawVersion } else { "v1.0.0" } } fun getCleanDesktopVersion(versionName: String): String { val regex = Regex("""^\d+(\.\d+)*""") return regex.find(versionName)?.value ?: "1.0.0" } fun getWindowsVersion(rawVersion: String): String { val cleanVersion = rawVersion.trimStart('v', 'V') val semverRegex = Regex("""^(\d+)(?:\.(\d+))?(?:\.(\d+))?""") val match = semverRegex.find(cleanVersion) return if (match != null) { val major = match.groupValues[1].ifEmpty { "0" } val minor = match.groupValues[2].ifEmpty { "0" } val build = match.groupValues[3].ifEmpty { "0" } "$major.$minor.$build" } else { "0.0.0.0" } } fun getDebianVersion(rawVersion: String): String { var clean = rawVersion.trimStart('v', 'V') clean = clean.replace(Regex("""[^a-zA-Z0-9.\+\-~]"""), "-") if (clean.isEmpty() || !clean.first().isDigit()) { clean = "0.$clean".trimEnd('.') } return clean }