From 4179e3d0cecb5afcf774bea2626f72089757c076 Mon Sep 17 00:00:00 2001 From: Hasinjato Date: Fri, 23 Oct 2026 15:34:39 +0300 Subject: [PATCH] Support sharing playlist on qr & Add QR Scanner(Android) --- composeApp/build.gradle.kts | 11 +- .../src/androidMain/AndroidManifest.xml | 7 +- .../kotlin/mg/dot/feufaro/MainActivity.kt | 96 +----- .../mg/dot/feufaro/data/DeepLinkHandler.kt | 35 ++ .../mg/dot/feufaro/data/QRCodeScanner.kt | 15 + .../mg/dot/feufaro/ui/QRScannerActivity.kt | 325 ++++++++++++++++++ .../mg/dot/feufaro/data/DeepLinkHandler.kt | 93 ++++- .../mg/dot/feufaro/data/QRCodeScanner.kt | 3 + .../kotlin/mg/dot/feufaro/ui/DrawerUI.kt | 15 +- .../mg/dot/feufaro/ui/PlaylistDialog.kt | 69 +++- .../kotlin/mg/dot/feufaro/ui/QRDisplay.kt | 51 ++- .../mg/dot/feufaro/ui/SimpleDrawerContent.kt | 48 ++- .../feufaro/viewmodel/SharedScreenModel.kt | 70 +++- .../mg/dot/feufaro/data/DeepLinkHandler.kt | 20 ++ .../mg/dot/feufaro/data/QRCodeScanner.kt | 5 + 15 files changed, 743 insertions(+), 120 deletions(-) create mode 100644 composeApp/src/androidMain/kotlin/mg/dot/feufaro/data/DeepLinkHandler.kt create mode 100644 composeApp/src/androidMain/kotlin/mg/dot/feufaro/data/QRCodeScanner.kt create mode 100644 composeApp/src/androidMain/kotlin/mg/dot/feufaro/ui/QRScannerActivity.kt create mode 100644 composeApp/src/commonMain/kotlin/mg/dot/feufaro/data/QRCodeScanner.kt create mode 100644 composeApp/src/desktopMain/kotlin/mg/dot/feufaro/data/DeepLinkHandler.kt create mode 100644 composeApp/src/desktopMain/kotlin/mg/dot/feufaro/data/QRCodeScanner.kt diff --git a/composeApp/build.gradle.kts b/composeApp/build.gradle.kts index 0fd5ef4..e8d2c03 100644 --- a/composeApp/build.gradle.kts +++ b/composeApp/build.gradle.kts @@ -58,6 +58,11 @@ kotlin { 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") + implementation("com.google.mlkit:barcode-scanning:17.3.0") } commonMain.dependencies { // implementation(compose.components.resources) @@ -124,10 +129,14 @@ android { resources { excludes += "/META-INF/{AL2.0,LGPL2.1}" } + jniLibs { + useLegacyPackaging = false + } } buildTypes { getByName("release") { - isMinifyEnabled = false + isMinifyEnabled = true + isShrinkResources = true } } compileOptions { diff --git a/composeApp/src/androidMain/AndroidManifest.xml b/composeApp/src/androidMain/AndroidManifest.xml index 99054bb..04e20cd 100644 --- a/composeApp/src/androidMain/AndroidManifest.xml +++ b/composeApp/src/androidMain/AndroidManifest.xml @@ -5,6 +5,7 @@ + - + + Unit) { + val context = AppContext.instance + val intent = Intent(context, QRScannerActivity::class.java).apply { + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + } + + QRScannerActivity.pendingResultCallback = onResult + context.startActivity(intent) +} \ No newline at end of file diff --git a/composeApp/src/androidMain/kotlin/mg/dot/feufaro/ui/QRScannerActivity.kt b/composeApp/src/androidMain/kotlin/mg/dot/feufaro/ui/QRScannerActivity.kt new file mode 100644 index 0000000..2fb95ff --- /dev/null +++ b/composeApp/src/androidMain/kotlin/mg/dot/feufaro/ui/QRScannerActivity.kt @@ -0,0 +1,325 @@ +package mg.dot.feufaro.ui + +import android.Manifest +import android.annotation.SuppressLint +import android.content.pm.PackageManager +import android.graphics.BitmapFactory +import android.os.Bundle +import android.os.Handler +import android.os.Looper +import android.widget.Toast +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.activity.result.contract.ActivityResultContracts +import androidx.camera.core.* +import androidx.camera.lifecycle.ProcessCameraProvider +import androidx.camera.view.PreviewView +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.material.icons.filled.Close +import androidx.compose.material.icons.filled.Image +import androidx.compose.material3.* +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.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 feufaro.composeapp.generated.resources.icon +import org.jetbrains.compose.resources.painterResource +import java.util.concurrent.Executors + +class QRScannerActivity : ComponentActivity() { + + companion object { + var pendingResultCallback: ((String) -> Unit)? = null + } + + 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 { + 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() + } + } + } catch (e: Exception) { + e.printStackTrace() + } + } + } + + private val requestPermissionLauncher = registerForActivityResult( + ActivityResultContracts.RequestPermission() + ) { isGranted -> + if (!isGranted) { + Toast.makeText(this, "Permission caméra requise pour scanner le QR Code", Toast.LENGTH_LONG).show() + finish() + } + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { + requestPermissionLauncher.launch(Manifest.permission.CAMERA) + } + + setContent { + Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.onSecondary) { + Box(modifier = Modifier.fillMaxSize()) { + AndroidView( + factory = { context -> + PreviewView(context).apply { + scaleType = PreviewView.ScaleType.FILL_CENTER + startCamera(this) { scannedValue -> + mainHandler.post { + println("Résultat QR Code scanné : $scannedValue") + Toast.makeText(this@QRScannerActivity, "QR Code détecté !", Toast.LENGTH_SHORT).show() + + pendingResultCallback?.invoke(scannedValue) + pendingResultCallback = null + finish() + } + } + } + }, + modifier = Modifier.fillMaxSize() + ) + + Column( + modifier = Modifier + .fillMaxSize() + .padding(24.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.SpaceBetween + ) { + Column( + horizontalAlignment = Alignment.CenterHorizontally, + modifier = Modifier.padding(top = 48.dp) + ) { + Text( + text = "Scanner un QR code Feufar.ooo", + style = MaterialTheme.typography.titleLarge.copy( + color = MaterialTheme.colorScheme.onPrimary, + fontWeight = FontWeight.Bold, + fontSize = 22.sp + ) + ) + } + + Box( + modifier = Modifier.size(280.dp), + contentAlignment = Alignment.Center + ) { + Canvas(modifier = Modifier.fillMaxSize()) { + val strokeWidth = 8f + val length = 40f + val color = android.graphics.Color.WHITE + val paint = android.graphics.Paint().apply { + this.color = color + this.strokeWidth = strokeWidth + this.style = android.graphics.Paint.Style.STROKE + this.isAntiAlias = true + this.strokeCap = android.graphics.Paint.Cap.ROUND + } + + val w = size.width + val h = size.height + + drawContext.canvas.nativeCanvas.apply { + drawLine(0f, 0f, length, 0f, paint) + drawLine(0f, 0f, 0f, length, paint) + drawLine(w, 0f, w - length, 0f, paint) + drawLine(w, 0f, w, length, paint) + drawLine(0f, h, length, h, paint) + drawLine(0f, h, 0f, h - length, paint) + drawLine(w, h, w - length, h, paint) + drawLine(w, h, w, h - length, paint) + } + } + + Box( + modifier = Modifier + .size(45.dp) + .background(MaterialTheme.colorScheme.onPrimary, shape = RoundedCornerShape(8.dp)) + .padding(4.dp), + contentAlignment = Alignment.Center + ) { + Image( + painter = painterResource(Res.drawable.icon), + contentDescription = "App Logo", + modifier = Modifier + .fillMaxSize() + .clip(RoundedCornerShape(6.dp)) + ) + } + } + + Column( + horizontalAlignment = Alignment.CenterHorizontally, + modifier = Modifier.padding(bottom = 24.dp) + ) { + OutlinedButton( + onClick = { galleryLauncher.launch("image/*") }, + colors = ButtonDefaults.outlinedButtonColors( + containerColor = MaterialTheme.colorScheme.onPrimary.copy(alpha = 0.15f), + contentColor = MaterialTheme.colorScheme.onPrimary + ), + border = ButtonDefaults.outlinedButtonBorder.copy(width = 0.dp), + shape = RoundedCornerShape(24.dp), + modifier = Modifier.height(48.dp) + ) { + Icon( + imageVector = Icons.Default.Image, + contentDescription = "Galerie", + modifier = Modifier.size(20.dp) + ) + Spacer(modifier = Modifier.width(8.dp)) + Text( + text = "Importer depuis la galerie", + fontWeight = FontWeight.Medium, + fontSize = 14.sp + ) + } + + Spacer(modifier = Modifier.height(16.dp)) + + IconButton( + onClick = { finish() }, + modifier = Modifier + .size(56.dp) + .clip(CircleShape) + .background(MaterialTheme.colorScheme.onPrimary.copy(alpha = 0.2f)) + ) { + Icon( + imageVector = Icons.Default.Close, + contentDescription = "Fermer le scanner", + tint = MaterialTheme.colorScheme.onPrimary, + modifier = Modifier.size(28.dp) + ) + } + } + } + } + } + } + } + + private fun startCamera(previewView: PreviewView, onScan: (String) -> Unit) { + 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) + }) + } + + try { + cameraProvider.unbindAll() + cameraProvider.bindToLifecycle( + this, + CameraSelector.DEFAULT_BACK_CAMERA, + preview, + imageAnalyzer + ) + } catch (exc: Exception) { + exc.printStackTrace() + } + }, ContextCompat.getMainExecutor(this)) + } + + override fun onDestroy() { + super.onDestroy() + cameraExecutor.shutdown() + } +} + +class MLKitBarcodeAnalyzer( + private val scanner: com.google.mlkit.vision.barcode.BarcodeScanner, + private val onQrCodeDetected: (String) -> Unit +) : ImageAnalysis.Analyzer { + private var isScanning = false + + @SuppressLint("UnsafeOptInUsageError") + 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 + } + } + } + .addOnFailureListener { + + } + .addOnCompleteListener { + imageProxy.close() + isScanning = false + } + } else { + imageProxy.close() + } + } +} \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/mg/dot/feufaro/data/DeepLinkHandler.kt b/composeApp/src/commonMain/kotlin/mg/dot/feufaro/data/DeepLinkHandler.kt index 7294fe1..7c25ad7 100644 --- a/composeApp/src/commonMain/kotlin/mg/dot/feufaro/data/DeepLinkHandler.kt +++ b/composeApp/src/commonMain/kotlin/mg/dot/feufaro/data/DeepLinkHandler.kt @@ -1,5 +1,12 @@ package mg.dot.feufaro +import SharedScreenModel +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import mg.dot.feufaro.viewmodel.SolfaScreenModel +import java.util.zip.GZIPInputStream +import kotlin.io.encoding.Base64 + object DeepLinkHandler { var hasConsumedDeepLink = false private var pendingData: Pair? = null @@ -13,7 +20,7 @@ object DeepLinkHandler { } fun handleSongContent(fileContent: String, filePath: String) { - var hasConsumedDeepLink = true + hasConsumedDeepLink = true val callback = onSongReceived if (callback != null) { println("DeepLink: callback dispo → appel immédiat") @@ -31,4 +38,86 @@ object DeepLinkHandler { pendingData = null } } -} \ No newline at end of file + + @OptIn(kotlin.io.encoding.ExperimentalEncodingApi::class) + fun decodeAndDecompress(base64Data: String): String { + return try { + val cleanBase64 = base64Data + .replace(" ", "+") + .replace("-", "+") + .replace("_", "/") + .trim() + val paddedBase64 = cleanBase64 + "=".repeat((4 - (cleanBase64.length % 4)) % 4) + val compressedBytes = Base64.Default.decode(paddedBase64) + GZIPInputStream(compressedBytes.inputStream()).bufferedReader(Charsets.UTF_8).use { + it.readText() + } + } catch (e: Exception) { + base64Data + } + } + + suspend fun processDeeplinkData( + uriString: String, + sharedScreenModel: SharedScreenModel, + solfaScreenModel: SolfaScreenModel + ) { + if (!uriString.startsWith("feufaro://")) return + + val rawPath = uriString.removePrefix("feufaro://") + println("Bien reçu ici DLHLR ! $rawPath") + when { + rawPath.startsWith("playlist?") -> { + val query = rawPath.substringAfter("?") + val params = parseQuery(query) + val playlistName = params["name"] ?: "Playlist" + val dataBase64 = params["data"] ?: return + + val rawText = decodeAndDecompress(dataBase64) + if (rawText.isNotBlank()) { + val (alreadyExists, firstSongPath) = sharedScreenModel.loadPlaylistFromQrCode(playlistName, rawText) + withContext(Dispatchers.Main) { + if (alreadyExists) { + showPlatformToast("La playlist $playlistName existe déjà") + } else { + if (!firstSongPath.isNullOrEmpty()) { + sharedScreenModel.reset() + solfaScreenModel.loadFromFile(firstSongPath) + sharedScreenModel.loadNewSong("whawyd3.mid") + } + showPlatformToast("Playlist $playlistName importée avec succès") + } + } + } + } + rawPath.startsWith("song?") -> { + val query = rawPath.substringAfter("?") + val params = parseQuery(query) + val fileBase64 = params["file"] ?: return + val fileName = params["name"] ?: "partition.txt" + + val rawContent = decodeAndDecompress(fileBase64) + + val savedPath = saveFileToPlatformStorage(fileName, rawContent) + if (savedPath != null) { + withContext(Dispatchers.Main) { + handleSongContent(rawContent, savedPath) + showPlatformToast("Partition ${fileName.removeSuffix(".txt")} importée avec succès") + } + } + } + } + } + + private fun parseQuery(query: String): Map { + return query.split("&").associate { + val parts = it.split("=", limit = 2) + val key = parts.getOrNull(0) ?: "" + val value = parts.getOrNull(1) ?: "" + key to java.net.URLDecoder.decode(value, "UTF-8") + } + } +} + +expect fun showPlatformToast(message: String) +expect suspend fun saveFileToPlatformStorage(fileName: String, content: String): String? diff --git a/composeApp/src/commonMain/kotlin/mg/dot/feufaro/data/QRCodeScanner.kt b/composeApp/src/commonMain/kotlin/mg/dot/feufaro/data/QRCodeScanner.kt new file mode 100644 index 0000000..59e5640 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mg/dot/feufaro/data/QRCodeScanner.kt @@ -0,0 +1,3 @@ +package mg.dot.feufaro.data + +expect fun openQRCodeScanner(onResult: (String) -> Unit) diff --git a/composeApp/src/commonMain/kotlin/mg/dot/feufaro/ui/DrawerUI.kt b/composeApp/src/commonMain/kotlin/mg/dot/feufaro/ui/DrawerUI.kt index 0ed108e..25f0241 100644 --- a/composeApp/src/commonMain/kotlin/mg/dot/feufaro/ui/DrawerUI.kt +++ b/composeApp/src/commonMain/kotlin/mg/dot/feufaro/ui/DrawerUI.kt @@ -197,6 +197,7 @@ fun MainScreenWithDrawer( } val isQrVisible = sharedScreenModel.isQRCodeVisible.value + val qrData = sharedScreenModel.qrData.value val sharedInteractionSource = remember { MutableInteractionSource() } @@ -216,6 +217,7 @@ fun MainScreenWithDrawer( } BackHandler(enabled = isQrVisible) { sharedScreenModel.toggleQRCodeVisibility() + sharedScreenModel.hideQRCode() } BackHandler(enabled = (!showMidiCtrl && isExpanded)) { sharedScreenModel.setExpandedFAB(!isExpanded) @@ -351,6 +353,14 @@ fun MainScreenWithDrawer( } } }, + onShare = { + scope.launch { + sharedScreenModel.selectPlaylist(selectedPlaylist) + val rawText = sharedScreenModel.currentPlaylistRawText.value + sharedScreenModel.showPlaylistQRCode(selectedPlaylist, rawText) + drawerState.close() + } + }, onDismiss = { showPlaylistDialog = false } ) } @@ -1081,7 +1091,10 @@ fun MainScreenWithDrawer( ) { QRDisplay( sharedScreenModel = sharedScreenModel, - fileRepository = solfaScreenModel.fileRepository + fileRepository = solfaScreenModel.fileRepository, + playlistName = qrData?.playlistName, + playlistRawText = qrData?.rawText, + onClose = { sharedScreenModel.hideQRCode() } ) } diff --git a/composeApp/src/commonMain/kotlin/mg/dot/feufaro/ui/PlaylistDialog.kt b/composeApp/src/commonMain/kotlin/mg/dot/feufaro/ui/PlaylistDialog.kt index d6f9691..733b767 100644 --- a/composeApp/src/commonMain/kotlin/mg/dot/feufaro/ui/PlaylistDialog.kt +++ b/composeApp/src/commonMain/kotlin/mg/dot/feufaro/ui/PlaylistDialog.kt @@ -240,6 +240,7 @@ fun PlaylistDialog( onAddFromLibrary: () -> Unit = {}, onSave: (rawText: String) -> Unit, onPlay: (rawText: String) -> Unit, + onShare: (playlistName: String) -> Unit, onDismiss: () -> Unit, ) { var rawText by rememberSaveable(initialRawText) { mutableStateOf(initialRawText) } @@ -404,17 +405,43 @@ fun PlaylistDialog( overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f) ) - OutlinedButton( - onClick = { playlistToDelete = selectedPlaylist }, - modifier = Modifier.height(36.dp), - shape = RoundedCornerShape(50), - border = BorderStroke(1.dp, MaterialTheme.colorScheme.error.copy(alpha = 0.7f)), - colors = ButtonDefaults.outlinedButtonColors(contentColor = MaterialTheme.colorScheme.error), - contentPadding = PaddingValues(horizontal = 12.dp) + Row( + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalAlignment = Alignment.CenterVertically ) { - Icon(Icons.Default.Delete, contentDescription = null, modifier = Modifier.size(18.dp)) - Spacer(Modifier.width(6.dp)) - Text("Supprimer", style = MaterialTheme.typography.labelLarge, fontWeight = FontWeight.Bold) + OutlinedButton( + onClick = { + onSave(rawText) + onDismiss() + onShare(selectedPlaylist) + }, + modifier = Modifier.height(36.dp), + shape = RoundedCornerShape(50), + border = BorderStroke(1.dp, MaterialTheme.colorScheme.primary.copy(alpha = 0.7f)), + colors = ButtonDefaults.outlinedButtonColors(contentColor = MaterialTheme.colorScheme.primary), + contentPadding = PaddingValues(horizontal = 12.dp) + ) { + Icon( + Icons.Default.QrCode2, + contentDescription = null, + modifier = Modifier.size(18.dp) + ) + Spacer(Modifier.width(6.dp)) + Text("Partager", style = MaterialTheme.typography.labelLarge, fontWeight = FontWeight.Bold) + } + + OutlinedButton( + onClick = { playlistToDelete = selectedPlaylist }, + modifier = Modifier.height(36.dp), + shape = RoundedCornerShape(50), + border = BorderStroke(1.dp, MaterialTheme.colorScheme.error.copy(alpha = 0.7f)), + colors = ButtonDefaults.outlinedButtonColors(contentColor = MaterialTheme.colorScheme.error), + contentPadding = PaddingValues(horizontal = 12.dp) + ) { + Icon(Icons.Default.Delete, contentDescription = null, modifier = Modifier.size(18.dp)) + Spacer(Modifier.width(6.dp)) + Text("Supprimer", style = MaterialTheme.typography.labelLarge, fontWeight = FontWeight.Bold) + } } } } @@ -439,7 +466,12 @@ fun PlaylistDialog( playlistToRename = selectedPlaylist renameText = selectedPlaylist }, - onDelete = { playlistToDelete = selectedPlaylist } + onDelete = { playlistToDelete = selectedPlaylist }, + onShare = { + onSave(rawText) + onDismiss() + onShare(selectedPlaylist) + } ) PlaylistEditor( isAndroid = true, @@ -659,6 +691,7 @@ private fun PlaylistSelector( onNew: () -> Unit, onRename: () -> Unit, onDelete: () -> Unit, + onShare: () -> Unit, ) { var open by remember { mutableStateOf(false) } Box(modifier = Modifier.fillMaxWidth()) { @@ -696,6 +729,20 @@ private fun PlaylistSelector( } } + OutlinedIconButton( + onClick = onShare, + modifier = Modifier.size(44.dp), + shape = RoundedCornerShape(12.dp), + border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline.copy(alpha = 0.3f)) + ) { + Icon( + Icons.Default.QrCode2, + contentDescription = "Partager la playlist via QR Code", + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(20.dp) + ) + } + OutlinedIconButton( onClick = onRename, modifier = Modifier.size(44.dp), diff --git a/composeApp/src/commonMain/kotlin/mg/dot/feufaro/ui/QRDisplay.kt b/composeApp/src/commonMain/kotlin/mg/dot/feufaro/ui/QRDisplay.kt index 172c0a2..24f0e59 100644 --- a/composeApp/src/commonMain/kotlin/mg/dot/feufaro/ui/QRDisplay.kt +++ b/composeApp/src/commonMain/kotlin/mg/dot/feufaro/ui/QRDisplay.kt @@ -37,31 +37,48 @@ import mg.dot.feufaro.solfa.ColorPrefixB import mg.dot.feufaro.solfa.ColorValue import org.jetbrains.compose.resources.painterResource import java.io.ByteArrayOutputStream +import java.net.URLEncoder import java.util.zip.GZIPOutputStream import kotlin.io.encoding.Base64 @Composable -fun QRDisplay(sharedScreenModel: SharedScreenModel, fileRepository: FileRepository) { - +fun QRDisplay( + sharedScreenModel: SharedScreenModel, + fileRepository: FileRepository, + playlistName: String? = null, + playlistRawText: String? = null, + onClose: () -> Unit = { sharedScreenModel.toggleQRCodeVisibility() } +) { val content by sharedScreenModel.fileContent val path by sharedScreenModel.activeFilePath - val fileName = path.substringAfterLast('/').substringAfterLast(':').replace(' ','_') + val fileName = path.substringAfterLast('/').substringAfterLast(':') - val qrCodeImage by produceState(initialValue = null, content, path) { - val expandedSource = expandInclusions( - content = content, - currentFilePath = path, - fileRepository = fileRepository - ) - if(expandedSource.isNotEmpty()) { + val qrCodeImage by produceState(initialValue = null, content, path, playlistName, playlistRawText) { + if (!playlistName.isNullOrEmpty() && !playlistRawText.isNullOrEmpty()) { val bos = ByteArrayOutputStream() - GZIPOutputStream(bos).use { it.write(expandedSource.toByteArray(Charsets.UTF_8)) } - val compressedBytes = bos.toByteArray() + GZIPOutputStream(bos).use { it.write(playlistRawText.toByteArray(Charsets.UTF_8)) } + val compressedData = Base64.UrlSafe.encode(bos.toByteArray()).trim('=') + val encodedName = URLEncoder.encode(playlistName, "UTF-8") - val compressedData = Base64.UrlSafe.encode(compressedBytes).trim('=') - - val uri = "feufaro://song?file=${compressedData}&name=$fileName" + val uri = "feufaro://playlist?name=${encodedName}&data=$compressedData" value = generateQRCode(uri, size = 1200) + } else { + val expandedSource = expandInclusions( + content = content, + currentFilePath = path, + fileRepository = fileRepository + ) + if (expandedSource.isNotEmpty()) { + val bos = ByteArrayOutputStream() + GZIPOutputStream(bos).use { it.write(expandedSource.toByteArray(Charsets.UTF_8)) } + val compressedBytes = bos.toByteArray() + + val compressedData = Base64.UrlSafe.encode(compressedBytes).trim('=') + val encodedFName = URLEncoder.encode(fileName, "UTF-8") + + val uri = "feufaro://song?file=${compressedData}&name=$encodedFName" + value = generateQRCode(uri, size = 1200) + } } } @@ -103,7 +120,7 @@ fun QRDisplay(sharedScreenModel: SharedScreenModel, fileRepository: FileReposito Spacer(modifier = Modifier.height(12.dp)) Text( - text = "Scanner ce QR Code", + text = if (!playlistName.isNullOrEmpty()) "Playlist : $playlistName" else "Scanner ce QR Code", style = MaterialTheme.typography.titleLarge.copy( fontWeight = FontWeight.Bold, fontSize = 22.sp @@ -170,7 +187,7 @@ fun QRDisplay(sharedScreenModel: SharedScreenModel, fileRepository: FileReposito Spacer(modifier = Modifier.height(2.dp)) Text( - text = "Partager et charger rapidement cette partition", + text = if (!playlistName.isNullOrEmpty()) "Partager la playlist complète" else "Partager et charger rapidement cette partition", style = MaterialTheme.typography.bodyMedium.copy( color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.6f), letterSpacing = 0.2.sp diff --git a/composeApp/src/commonMain/kotlin/mg/dot/feufaro/ui/SimpleDrawerContent.kt b/composeApp/src/commonMain/kotlin/mg/dot/feufaro/ui/SimpleDrawerContent.kt index 03daf08..7300e68 100644 --- a/composeApp/src/commonMain/kotlin/mg/dot/feufaro/ui/SimpleDrawerContent.kt +++ b/composeApp/src/commonMain/kotlin/mg/dot/feufaro/ui/SimpleDrawerContent.kt @@ -33,8 +33,10 @@ import feufaro.composeapp.generated.resources.Res import feufaro.composeapp.generated.resources.icon import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch +import mg.dot.feufaro.DeepLinkHandler import mg.dot.feufaro.data.ActivePlaylistSong import mg.dot.feufaro.data.DrawerItem +import mg.dot.feufaro.data.openQRCodeScanner import mg.dot.feufaro.getPlatform import mg.dot.feufaro.solfa.Solfa import mg.dot.feufaro.viewmodel.SolfaScreenModel @@ -321,7 +323,15 @@ fun SimpleDrawerContent( onSongSelected(midi) } } - } + }, + onShare = { + scope.launch { + sharedScreenModel.selectPlaylist(pl.name) + val rawText = sharedScreenModel.currentPlaylistRawText.value + sharedScreenModel.showPlaylistQRCode(pl.name, rawText) + drawerState.close() + } + }, ) } @@ -439,6 +449,33 @@ fun SimpleDrawerContent( } } + if (getPlatform().name.contains("Android", ignoreCase = true)) { + TooltipBox( + positionProvider = TooltipDefaults.rememberPlainTooltipPositionProvider(), + tooltip = { PlainTooltip { Text("Scanner un QR Code") } }, + state = rememberTooltipState() + ) { + IconButton(onClick = { + scope.launch { + drawerState.close() + openQRCodeScanner { scannedUri -> + if (scannedUri.startsWith("feufaro://")) { + scope.launch { + DeepLinkHandler.processDeeplinkData( + uriString = scannedUri, + sharedScreenModel = sharedScreenModel, + solfaScreenModel = solfaScreenModel + ) + } + } + } + } + }) { + Icon(Icons.Default.QrCodeScanner, contentDescription = "Btn to scan QR code", tint = MaterialTheme.colorScheme.onSecondary) + } + } + } + TooltipBox( positionProvider = TooltipDefaults.rememberPlainTooltipPositionProvider(), tooltip = { PlainTooltip { Text("Gèrer la playlist") } }, @@ -597,6 +634,7 @@ fun DrawerPlaylistRow( onToggle: () -> Unit, onPlay: () -> Unit, onDelete: () -> Unit, + onShare: () -> Unit, ) { val rotation by animateFloatAsState(if (expanded) 180f else 0f) @@ -635,6 +673,14 @@ fun DrawerPlaylistRow( color = MaterialTheme.colorScheme.onSurfaceVariant ) } + IconButton(onClick = onShare, modifier = Modifier.size(36.dp)) { + Icon( + imageVector = Icons.Default.QrCode2, + contentDescription = "Partager la playlist $name", + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(20.dp) + ) + } IconButton( onClick = onPlay, enabled = songCount > 0, diff --git a/composeApp/src/commonMain/kotlin/mg/dot/feufaro/viewmodel/SharedScreenModel.kt b/composeApp/src/commonMain/kotlin/mg/dot/feufaro/viewmodel/SharedScreenModel.kt index 64912d7..f871e4b 100644 --- a/composeApp/src/commonMain/kotlin/mg/dot/feufaro/viewmodel/SharedScreenModel.kt +++ b/composeApp/src/commonMain/kotlin/mg/dot/feufaro/viewmodel/SharedScreenModel.kt @@ -348,7 +348,7 @@ class SharedScreenModel(private val fileRepository: FileRepository) : ScreenMode } } - suspend fun savePlaylist(playlistName: String, rawText: String) { + suspend fun savePlaylist(playlistName: String, rawText: String)= withContext(Dispatchers.IO) { try { val entries = parseRawTextToEntries(rawText) @@ -373,15 +373,21 @@ class SharedScreenModel(private val fileRepository: FileRepository) : ScreenMode PlaylistsFile(emptyList()) } - val updatedList = currentData.playlist.map { map -> - if (map.containsKey(playlistName)) { - mapOf(playlistName to songEntries) - } else { - map + val exists = currentData.playlist.any { it.containsKey(playlistName) } + val updatedList = if (exists) { + currentData.playlist.map { map -> + if (map.containsKey(playlistName)) { + mapOf(playlistName to songEntries) + } else { + map + } } + } else { + currentData.playlist + mapOf(playlistName to songEntries) } file.writeText(jsonFormat.encodeToString(PlaylistsFile(updatedList))) + playlistNames.value = updatedList.flatMap { it.keys } refreshAllPlaylists() currentPlaylistRawText.value = rawText } catch (e: Exception) { @@ -596,6 +602,32 @@ class SharedScreenModel(private val fileRepository: FileRepository) : ScreenMode } } + suspend fun loadPlaylistFromQrCode(playlistName: String, rawText: String): Pair = withContext(Dispatchers.IO) { + try { + val alreadyExists = playlistNames.value.any { it.equals(playlistName, ignoreCase = true) } + + if (alreadyExists) { + return@withContext Pair(true, null) + } + savePlaylist(playlistName, rawText) + + selectPlaylist(playlistName) + + val songs = parseRawTextToEntries(rawText).mapNotNull { entry -> + val song = findMatchingSong(entry.query, drawerItems.value) ?: return@mapNotNull null + ActivePlaylistSong( + path = song.path, + stanzas = parseVerses(entry.verseStr)?.sorted() ?: emptyList() + ) + } + + val firstPath = startPlaylist(songs) + Pair(false, firstPath) + } catch (e: Exception) { + e.printStackTrace() + Pair(false, null) + } + } @OptIn(ExperimentalCoroutinesApi::class) val filteredSongs: StateFlow> = combine(drawerItems, searchTitle) { items, query -> if (query.isBlank()) { @@ -615,6 +647,29 @@ class SharedScreenModel(private val fileRepository: FileRepository) : ScreenMode private val _isQRCodeVisible = mutableStateOf(false) val isQRCodeVisible: State = _isQRCodeVisible + data class QRData(val playlistName: String? = null, val rawText: String? = null) + + private val _qrData = mutableStateOf(null) + val qrData: State = _qrData + + fun toggleQRCodeVisibility() { + _isQRCodeVisible.value = !_isQRCodeVisible.value + if (!_isQRCodeVisible.value) { + _qrData.value = null + } + } + + fun showPlaylistQRCode(playlistName: String, rawText: String) { + _qrData.value = QRData(playlistName = playlistName, rawText = rawText) + _isQRCodeVisible.value = true + _showMidiCtrl.value = false + } + + fun hideQRCode() { + _isQRCodeVisible.value = false + _qrData.value = null + } + private val _sourceModeState = mutableStateOf(false) val sourceModeState: State = _sourceModeState @@ -706,9 +761,6 @@ class SharedScreenModel(private val fileRepository: FileRepository) : ScreenMode _stanza.value = 1 } } - fun toggleQRCodeVisibility() { - _isQRCodeVisible.value = !_isQRCodeVisible.value - } fun toggleSourceMode() { _sourceModeState.value = !_sourceModeState.value } diff --git a/composeApp/src/desktopMain/kotlin/mg/dot/feufaro/data/DeepLinkHandler.kt b/composeApp/src/desktopMain/kotlin/mg/dot/feufaro/data/DeepLinkHandler.kt new file mode 100644 index 0000000..580d568 --- /dev/null +++ b/composeApp/src/desktopMain/kotlin/mg/dot/feufaro/data/DeepLinkHandler.kt @@ -0,0 +1,20 @@ +package mg.dot.feufaro + +import java.io.File + +actual fun showPlatformToast(message: String) { + println("PC Notification: $message") +} + +actual suspend fun saveFileToPlatformStorage(fileName: String, content: String): String? { + return try { + val userHome = System.getProperty("user.home") + val appDir = File(userHome, "Feufaro").apply { mkdirs() } + val file = File(appDir, fileName) + file.writeText(content) + file.absolutePath + } catch (e: Exception) { + e.printStackTrace() + null + } +} \ No newline at end of file diff --git a/composeApp/src/desktopMain/kotlin/mg/dot/feufaro/data/QRCodeScanner.kt b/composeApp/src/desktopMain/kotlin/mg/dot/feufaro/data/QRCodeScanner.kt new file mode 100644 index 0000000..54a35e4 --- /dev/null +++ b/composeApp/src/desktopMain/kotlin/mg/dot/feufaro/data/QRCodeScanner.kt @@ -0,0 +1,5 @@ +package mg.dot.feufaro.data + +actual fun openQRCodeScanner(onResult: (String) -> Unit) { + +} \ No newline at end of file