From ffc525fe27ad770b4cbb08f397395d3f59ae43ca Mon Sep 17 00:00:00 2001 From: dotmg Date: Sat, 21 Nov 2026 05:53:31 +0100 Subject: [PATCH] Shrink apk size : remove dep to mlkit --- composeApp/build.gradle.kts | 257 +++++++++------ .../mg/dot/feufaro/ui/QRScannerActivity.kt | 304 +++++++++++++----- 2 files changed, 382 insertions(+), 179 deletions(-) diff --git a/composeApp/build.gradle.kts b/composeApp/build.gradle.kts index 27c7ee2..90e4bce 100644 --- a/composeApp/build.gradle.kts +++ b/composeApp/build.gradle.kts @@ -1,9 +1,163 @@ -import org.jetbrains.compose.desktop.application.dsl.TargetFormat -import org.jetbrains.kotlin.gradle.ExperimentalKotlinGradlePluginApi -import org.jetbrains.kotlin.gradle.dsl.JvmTarget import java.io.ByteArrayOutputStream -import java.util.Properties 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) @@ -64,7 +218,6 @@ kotlin { implementation("androidx.camera:camera-camera2:1.3.4") implementation("androidx.camera:camera-lifecycle:1.3.4") implementation("androidx.camera:camera-view:1.3.4") - implementation("com.google.mlkit:barcode-scanning:17.3.0") } commonMain.dependencies { // implementation(compose.components.resources) @@ -155,8 +308,8 @@ val localProperties = Properties().apply { buildTypes { getByName("release") { val enableR8 = project.hasProperty("enableR8") && project.property("enableR8") == "true" - isMinifyEnabled = true - isShrinkResources = true + isMinifyEnabled = enableR8 + isShrinkResources = enableR8 proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") signingConfig = signingConfigs.getByName("release") } @@ -263,97 +416,7 @@ tasks.configureEach { dependsOn(generateFilesIndex) } } -tasks.register("finalizeApk") { - dependsOn("assembleRelease") - val apkUnsignedDir = layout.buildDirectory.dir("outputs/apk/release").get().asFile - val buildToolsVersion = android.buildToolsVersion - val sdkDir = android.sdkDirectory - - val alignmentTool = sdkDir.resolve("build-tools/$buildToolsVersion/zipalign").absolutePath - val apksignerTool = sdkDir.resolve("build-tools/$buildToolsVersion/apksigner").absolutePath - val adbTool = sdkDir.resolve("platform-tools/adb").absolutePath - - val inputApk = File(apkUnsignedDir, "composeApp-release.apk") - val alignedApk = File(apkUnsignedDir, "app-release-aligned.apk") - val finalApk = File(apkUnsignedDir, "app-release-signed.apk") - - doLast { - println("=== Début de la finalisation de l'APK (Alignement & Signature) ===") - - if (!inputApk.exists()) { - println("Erreur : L'APK non signé est introuvable à l'emplacement : ${inputApk.absolutePath}") - return@doLast - } - - // Étape 1 : Zipalign - println("1. Exécution de zipalign...") - val alignResult = exec { - commandLine(alignmentTool, "-f", "4", inputApk.absolutePath, alignedApk.absolutePath) - } - - if (alignResult.exitValue != 0) { - println("Erreur lors de l'alignement zipalign.") - return@doLast - } - println("-> Zipalign réussi.") - - // Étape 2 : Signature - println("2. Signature de l'APK...") - val releaseConfig = android.signingConfigs.getByName("release") - val storeFile = releaseConfig.storeFile?.absolutePath ?: "" - val storePassword = releaseConfig.storePassword ?: "" - val keyAlias = releaseConfig.keyAlias ?: "" - val keyPassword = releaseConfig.keyPassword ?: "" - - val signResult = exec { - commandLine( - apksignerTool, "sign", - "--ks", storeFile, - "--ks-pass", "pass:$storePassword", - "--key-pass", "pass:$keyPassword", - "--ks-key-alias", keyAlias, - "--out", finalApk.absolutePath, - alignedApk.absolutePath - ) - } - - if (signResult.exitValue != 0) { - println("Erreur lors de la signature de l'APK.") - return@doLast - } - println("-> APK signé avec succès : ${finalApk.absolutePath}") - - // Étape 3 : Vérification et installation via ADB - println("3. Vérification des appareils connectés...") - val stdout = ByteArrayOutputStream() - exec { - commandLine(adbTool, "devices") - standardOutput = stdout - } - - val deviceOutput = stdout.toString() - // Analyse des lignes de la sortie 'adb devices' (on ignore l'en-tête et les lignes vides) - val connectedDevices = deviceOutput.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 = exec { - commandLine(adbTool, "install", "-r", finalApk.absolutePath) - } - 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.") - } - } else { - println("-> Aucun appareil connecté. Installation ignorée.") - } - println("=== Processus terminé ===") - } -} tasks.register("exportLibs") { group = "distribution" description = "Copie les bibliothèques partagées pour le Thin JAR" diff --git a/composeApp/src/androidMain/kotlin/mg/dot/feufaro/ui/QRScannerActivity.kt b/composeApp/src/androidMain/kotlin/mg/dot/feufaro/ui/QRScannerActivity.kt index 2fb95ff..0467b51 100644 --- a/composeApp/src/androidMain/kotlin/mg/dot/feufaro/ui/QRScannerActivity.kt +++ b/composeApp/src/androidMain/kotlin/mg/dot/feufaro/ui/QRScannerActivity.kt @@ -1,9 +1,11 @@ package mg.dot.feufaro.ui -import android.Manifest import android.annotation.SuppressLint import android.content.pm.PackageManager +import android.graphics.Bitmap import android.graphics.BitmapFactory +import android.graphics.ImageFormat +import android.Manifest import android.os.Bundle import android.os.Handler import android.os.Looper @@ -12,37 +14,46 @@ import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.result.contract.ActivityResultContracts import androidx.camera.core.* +import androidx.camera.core.ImageAnalysis +import androidx.camera.core.ImageProxy import androidx.camera.lifecycle.ProcessCameraProvider import androidx.camera.view.PreviewView +import androidx.compose.foundation.background import androidx.compose.foundation.Canvas import androidx.compose.foundation.Image -import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material.icons.Icons +import androidx.compose.material3.* import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.Image -import androidx.compose.material3.* +import androidx.compose.material.icons.Icons import androidx.compose.runtime.* import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.nativeCanvas +import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.ui.viewinterop.AndroidView import androidx.core.content.ContextCompat -import com.google.mlkit.vision.barcode.BarcodeScannerOptions -import com.google.mlkit.vision.barcode.BarcodeScanning -import com.google.mlkit.vision.barcode.common.Barcode -import com.google.mlkit.vision.common.InputImage -import feufaro.composeapp.generated.resources.Res +import com.google.zxing.BarcodeFormat +import com.google.zxing.BinaryBitmap +import com.google.zxing.ChecksumException +import com.google.zxing.common.HybridBinarizer +import com.google.zxing.DecodeHintType +import com.google.zxing.FormatException +import com.google.zxing.MultiFormatReader +import com.google.zxing.NotFoundException +import com.google.zxing.PlanarYUVLuminanceSource +import com.google.zxing.qrcode.QRCodeReader +import com.google.zxing.RGBLuminanceSource import feufaro.composeapp.generated.resources.icon -import org.jetbrains.compose.resources.painterResource +import feufaro.composeapp.generated.resources.Res import java.util.concurrent.Executors +import org.jetbrains.compose.resources.painterResource class QRScannerActivity : ComponentActivity() { @@ -52,47 +63,77 @@ class QRScannerActivity : ComponentActivity() { private val cameraExecutor = Executors.newSingleThreadExecutor() private val mainHandler = Handler(Looper.getMainLooper()) - private val scanner = BarcodeScanning.getClient( - BarcodeScannerOptions.Builder() - .setBarcodeFormats(Barcode.FORMAT_QR_CODE) - .enableAllPotentialBarcodes() - .build() - ) - private val galleryLauncher = registerForActivityResult(ActivityResultContracts.GetContent()) { uri -> - uri?.let { +private val galleryLauncher = registerForActivityResult(ActivityResultContracts.GetContent()) { uri -> + if (uri == null) return@registerForActivityResult + + cameraExecutor.execute { + var bitmap: Bitmap? = null try { - val inputStream = contentResolver.openInputStream(uri) - val bitmap = BitmapFactory.decodeStream(inputStream) - if (bitmap != null) { - val image = InputImage.fromBitmap(bitmap, 0) - scanner.process(image) - .addOnSuccessListener { barcodes -> - for (barcode in barcodes) { - val rawValue = barcode.rawValue ?: barcode.rawBytes?.let { String(it, Charsets.UTF_8) } - if (!rawValue.isNullOrBlank()) { - mainHandler.post { - println("QR Code décodé depuis la galerie : $rawValue") - Toast.makeText(this, "QR Code détecté depuis la galerie !", Toast.LENGTH_SHORT).show() - pendingResultCallback?.invoke(rawValue) - pendingResultCallback = null - finish() - } - return@addOnSuccessListener - } - } - Toast.makeText(this, "Aucun QR code valide trouvé dans l'image", Toast.LENGTH_SHORT).show() - } - .addOnFailureListener { - Toast.makeText(this, "Erreur lors de la lecture de l'image", Toast.LENGTH_SHORT).show() - } + bitmap = contentResolver.openInputStream(uri)?.use { inputStream -> + BitmapFactory.decodeStream(inputStream) + } + + if (bitmap == null) { + mainHandler.post { + Toast.makeText(this, "Erreur lors de la lecture de l'image", Toast.LENGTH_SHORT).show() + } + return@execute + } + + val decodedText = decodeQrCodeFromBitmap(bitmap) + + mainHandler.post { + if (!decodedText.isNullOrBlank()) { + println("QR Code décodé depuis la galerie : $decodedText") + Toast.makeText(this, "QR Code détecté depuis la galerie !", Toast.LENGTH_SHORT).show() + pendingResultCallback?.invoke(decodedText) + pendingResultCallback = null + finish() + } else { + Toast.makeText(this, "Aucun QR code valide trouvé dans l'image", Toast.LENGTH_SHORT).show() + } } } catch (e: Exception) { e.printStackTrace() + mainHandler.post { + Toast.makeText(this, "Erreur lors de la lecture de l'image", Toast.LENGTH_SHORT).show() + } + } finally { + bitmap?.recycle() } } } + private fun decodeQrCodeFromBitmap(bitmap: Bitmap): String? { + val width = bitmap.width + val height = bitmap.height + if (width <= 0 || height <= 0) return null + + val pixels = IntArray(width * height) + bitmap.getPixels(pixels, 0, width, 0, 0, width, height) + + val source = RGBLuminanceSource(width, height, pixels) + val binaryBitmap = BinaryBitmap(HybridBinarizer(source)) + val reader = QRCodeReader() + val hints = mapOf( + DecodeHintType.POSSIBLE_FORMATS to listOf(BarcodeFormat.QR_CODE), + DecodeHintType.TRY_HARDER to true + ) + + return try { + reader.decode(binaryBitmap, hints).text + } catch (_: NotFoundException) { + null + } catch (_: ChecksumException) { + null + } catch (_: FormatException) { + null + } finally { + reader.reset() + } + } + private val requestPermissionLauncher = registerForActivityResult( ActivityResultContracts.RequestPermission() ) { isGranted -> @@ -210,7 +251,7 @@ class QRScannerActivity : ComponentActivity() { containerColor = MaterialTheme.colorScheme.onPrimary.copy(alpha = 0.15f), contentColor = MaterialTheme.colorScheme.onPrimary ), - border = ButtonDefaults.outlinedButtonBorder.copy(width = 0.dp), + border = ButtonDefaults.outlinedButtonBorder(enabled = true).copy(width = 0.dp), shape = RoundedCornerShape(24.dp), modifier = Modifier.height(48.dp) ) { @@ -250,26 +291,33 @@ class QRScannerActivity : ComponentActivity() { } } - private fun startCamera(previewView: PreviewView, onScan: (String) -> Unit) { +private fun startCamera(previewView: PreviewView, onScan: (String) -> Unit) { + if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { + return + } + if (cameraExecutor.isShutdown) return + val cameraProviderFuture = ProcessCameraProvider.getInstance(this) cameraProviderFuture.addListener({ - val cameraProvider = cameraProviderFuture.get() - val preview = Preview.Builder().build().also { - it.setSurfaceProvider(previewView.surfaceProvider) - } - - val imageAnalyzer = ImageAnalysis.Builder() - .setTargetResolution(android.util.Size(1280, 720)) - .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST) - .build() - .also { - it.setAnalyzer(cameraExecutor, MLKitBarcodeAnalyzer(scanner) { qrResult -> - onScan(qrResult) - }) - } + if (isFinishing || isDestroyed || cameraExecutor.isShutdown) return@addListener try { + val cameraProvider = cameraProviderFuture.get() + val preview = Preview.Builder().build().also { + it.setSurfaceProvider(previewView.surfaceProvider) + } + + val imageAnalyzer = ImageAnalysis.Builder() + .setTargetResolution(android.util.Size(1280, 720)) + .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST) + .build() + .also { analyzerUseCase -> + analyzerUseCase.setAnalyzer(cameraExecutor, ZxingBarcodeAnalyzer { qrResult -> + onScan(qrResult) + }) + } + cameraProvider.unbindAll() cameraProvider.bindToLifecycle( this, @@ -289,37 +337,129 @@ class QRScannerActivity : ComponentActivity() { } } -class MLKitBarcodeAnalyzer( - private val scanner: com.google.mlkit.vision.barcode.BarcodeScanner, +class ZxingBarcodeAnalyzer( private val onQrCodeDetected: (String) -> Unit ) : ImageAnalysis.Analyzer { - private var isScanning = false - @SuppressLint("UnsafeOptInUsageError") + private val reader = QRCodeReader() + private val hints = mapOf( + DecodeHintType.POSSIBLE_FORMATS to listOf(com.google.zxing.BarcodeFormat.QR_CODE), + DecodeHintType.TRY_HARDER to true + ) + + @Volatile + private var isHandled = false + override fun analyze(imageProxy: ImageProxy) { - val mediaImage = imageProxy.image - if (mediaImage != null && !isScanning) { - val image = InputImage.fromMediaImage(mediaImage, imageProxy.imageInfo.rotationDegrees) - isScanning = true - scanner.process(image) - .addOnSuccessListener { barcodes -> - for (barcode in barcodes) { - val rawValue = barcode.rawValue ?: barcode.rawBytes?.let { String(it, Charsets.UTF_8) } - if (!rawValue.isNullOrBlank()) { - onQrCodeDetected(rawValue) - return@addOnSuccessListener + try { + if (isHandled) return + if (imageProxy.format != ImageFormat.YUV_420_888) return + + val yPlane = imageProxy.planes[0] + val srcWidth = imageProxy.width + val srcHeight = imageProxy.height + val rowStride = yPlane.rowStride + val pixelStride = yPlane.pixelStride + val buffer = yPlane.buffer + + // Extraction propre du plan Y en tenant compte de rowStride et pixelStride + val rawY = ByteArray(srcWidth * srcHeight) + val rowData = ByteArray(rowStride) + var outIdx = 0 + + for (row in 0 until srcHeight) { + val rowStart = row * rowStride + if (rowStart + rowStride > buffer.capacity()) return + buffer.position(rowStart) + val bytesToRead = minOf(rowStride, buffer.remaining()) + buffer.get(rowData, 0, bytesToRead) + + if (pixelStride == 1) { + System.arraycopy(rowData, 0, rawY, outIdx, srcWidth) + outIdx += srcWidth + } else { + for (col in 0 until srcWidth) { + val idx = col * pixelStride + if (idx < bytesToRead) { + rawY[outIdx++] = rowData[idx] } } } - .addOnFailureListener { + } - } - .addOnCompleteListener { - imageProxy.close() - isScanning = false - } - } else { + val rotation = imageProxy.imageInfo.rotationDegrees + val (orientedY, outW, outH) = rotateYuv90Multiple(rawY, srcWidth, srcHeight, rotation) + + val source = PlanarYUVLuminanceSource( + orientedY, + outW, + outH, + 0, + 0, + outW, + outH, + false + ) + val bitmap = BinaryBitmap(HybridBinarizer(source)) + + val text = try { + reader.decode(bitmap, hints).text + } catch (_: NotFoundException) { + null + } catch (_: ChecksumException) { + null + } catch (_: FormatException) { + null + } finally { + reader.reset() + } + + if (!text.isNullOrBlank()) { + isHandled = true + onQrCodeDetected(text) + } + } finally { imageProxy.close() } } -} \ No newline at end of file + + private fun rotateYuv90Multiple( + data: ByteArray, + width: Int, + height: Int, + rotationDegrees: Int + ): Triple { + return when ((rotationDegrees % 360 + 360) % 360) { + 90 -> { + val rotated = ByteArray(width * height) + for (y in 0 until height) { + for (x in 0 until width) { + val newX = height - 1 - y + val newY = x + rotated[newY * height + newX] = data[y * width + x] + } + } + Triple(rotated, height, width) + } + 180 -> { + val rotated = ByteArray(width * height) + for (i in data.indices) { + rotated[data.size - 1 - i] = data[i] + } + Triple(rotated, width, height) + } + 270 -> { + val rotated = ByteArray(width * height) + for (y in 0 until height) { + for (x in 0 until width) { + val newX = y + val newY = width - 1 - x + rotated[newY * height + newX] = data[y * width + x] + } + } + Triple(rotated, height, width) + } + else -> Triple(data, width, height) + } + } +}