From 1d50e169093b7b58e65c751b580f8f11aff9660e Mon Sep 17 00:00:00 2001 From: Juan Camilo Grisales Date: Sun, 1 Nov 2026 22:56:11 -0500 Subject: [PATCH 1/2] feat(listen-together): explain a missing display name, add room QR codes and a room link Create and Join no longer go grey over a missing name or code. They stay live, and a tap marks the field, says what is missing and moves focus to the name. A tap while disconnected connects first and then carries on, because the session drops a create message with no error when the socket is down. The host can show the room as a QR code. Android scans one with the camera and Desktop reads one from an image file. A phone's camera app can open the simpmusic://listen-together link. A scanned code or a link only fills in the form and never joins by itself. Metrolist's share link is accepted too, since rooms are shared with that app. --- CLAUDE.md | 6 + composeApp/build.gradle.kts | 4 +- .../simpmusic/expect/ui/QrCode.android.kt | 18 ++ .../expect/ui/RoomQrScanner.android.kt | 210 ++++++++++++++++ .../composeResources/values/strings.xml | 14 ++ .../kotlin/com/maxrave/simpmusic/App.kt | 16 ++ .../com/maxrave/simpmusic/expect/ui/QrCode.kt | 15 ++ .../simpmusic/expect/ui/RoomQrScanner.kt | 15 ++ .../simpmusic/ui/component/QrCodeImage.kt | 38 +++ .../com/maxrave/simpmusic/ui/icon/QrCode2.kt | 198 +++++++++++++++ .../simpmusic/ui/icon/QrCodeScanner.kt | 216 +++++++++++++++++ .../ui/screen/home/ListenTogetherScreen.kt | 225 ++++++++++++++++-- .../com/maxrave/simpmusic/utils/AppLinks.kt | 2 +- .../simpmusic/utils/ListenTogetherLink.kt | 89 +++++++ .../viewModel/ListenTogetherViewModel.kt | 113 ++++++++- .../simpmusic/viewModel/SharedViewModel.kt | 9 + .../simpmusic/expect/ui/LibrarySync.jvm.kt | 3 +- .../simpmusic/expect/ui/LoginSync.jvm.kt | 47 +--- .../simpmusic/expect/ui/PhotoPicker.jvm.kt | 2 +- .../maxrave/simpmusic/expect/ui/QrCode.jvm.kt | 18 ++ .../simpmusic/expect/ui/RoomQrScanner.jvm.kt | 62 +++++ .../simpmusic/expect/ui/RoomQrCodeTest.kt | 32 +++ .../simpmusic/utils/ListenTogetherLinkTest.kt | 107 +++++++++ gradle/libs.versions.toml | 2 +- 24 files changed, 1390 insertions(+), 71 deletions(-) create mode 100644 composeApp/src/androidMain/kotlin/com/maxrave/simpmusic/expect/ui/QrCode.android.kt create mode 100644 composeApp/src/androidMain/kotlin/com/maxrave/simpmusic/expect/ui/RoomQrScanner.android.kt create mode 100644 composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/expect/ui/QrCode.kt create mode 100644 composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/expect/ui/RoomQrScanner.kt create mode 100644 composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/QrCodeImage.kt create mode 100644 composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/icon/QrCode2.kt create mode 100644 composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/icon/QrCodeScanner.kt create mode 100644 composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/utils/ListenTogetherLink.kt create mode 100644 composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/expect/ui/QrCode.jvm.kt create mode 100644 composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/expect/ui/RoomQrScanner.jvm.kt create mode 100644 composeApp/src/jvmTest/kotlin/com/maxrave/simpmusic/expect/ui/RoomQrCodeTest.kt create mode 100644 composeApp/src/jvmTest/kotlin/com/maxrave/simpmusic/utils/ListenTogetherLinkTest.kt diff --git a/CLAUDE.md b/CLAUDE.md index 02dbb1944a..a99d32e411 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1179,6 +1179,12 @@ if (getPlatform() == Platform.Android) { - Android Home packs tighter, Desktop unchanged: card sides 8dp (`cardSidePadding`), Quick picks rows 56dp, no 8dp/5dp around Quick picks' own header, no 8dp spacer over each section title. Android's card floor is artwork + `cardTextBlockFloor()`, the tallest text block (two `titleSmall` lines plus the subtitle row) measured with `rememberTextMeasurer`: Desktop's fixed 70dp counts Poppins' line gap (Skia) and left ~10dp spare under every Android card. Keep the floor: without it a row takes the height of the cards on screen and Home jumps when a two-line title scrolls in. Titles stay two lines, as on Spotify's song cards; the spare line belongs under the subtitle, never between title and subtitle. - `AppTheme {}` with no arguments is the app's default cyan dark theme, not the user's: anything drawn outside `App()` (Desktop's `LibrarySyncLoginPrompt`) must read theme mode, colour source and custom colour the way `App()` does. Force-dark `typo()` paints `headlineMedium`/`bodyMedium` in its #A8A8A8 body grey, so text on a scrim (the daily discover hero) names `onSurface`/`onSurfaceVariant`. +- **Listen Together: required-name feedback, room QR codes and a room link (2026-11-02)**: Create and Join no longer go grey over a missing name or code. They stay live, and a tap marks the field, says what is missing and moves focus to the name (`RoomFormProblem`, `roomFormProblems()` in `utils/ListenTogetherLink.kt`). The field is labelled Required throughout. A tap while disconnected connects first and then carries on (`whenConnected`), because `ListenTogetherSession.createRoom` drops its message with no error when the socket is down; only that wait disables the buttons. + - **QR**: the host's poster gains a button opening `RoomQrDialog`. `QrCodeImage` (`ui/component`, moved out of Login Sync's Desktop dialog) draws any text over `encodeQrMatrix` (expect/actual, since ZXing is a plain JVM artifact declared per platform). `RoomQrScanner` is expect/actual: Android uses the camera in a sheet built from Login Sync's pieces; Desktop has no camera API, so it reads the code from an image file through `showOpenFileDialog`. + - **The link is `simpmusic://listen-together?code=X`** (`listenTogetherLink`), handled by the router in `App.kt`, since both platforms already register the scheme. Not `https://simpmusic.org/app/…`: `simpmusic.org/.well-known/assetlinks.json` redirects to `www` (Android does not follow redirects for it) and `www` answers 404, and so does `/app/*`, so a camera app would land on a 404 page. `roomCodeFromText` and the router already accept the https form; once the site serves both, changing `listenTogetherLink` is the whole migration. iOS has no client. + - **A scanned code or a link only fills in the form, it never joins.** It came from outside the app, and joining shows the user's name to that room. `roomCodeFromText` returns only a validated 8-character code, so a QR code cannot open a page either. It also reads Metrolist's `https://metrolist.cc/listen?code=X`, since rooms are shared; a phone's camera cannot open that link in SimpMusic because the domain is not ours, but the in-app scanner and a paste into the code field can. + - A room exists on one server, so a code or QR code from a custom server means nothing to someone on the default one. Deliberately not carried in the link: a QR code could then point the app at any server. + ## 🔄 CLAUDE.md Auto-Update Rule (MANDATORY) After completing any of the following types of changes, the AI agent **MUST** update this CLAUDE.md file: diff --git a/composeApp/build.gradle.kts b/composeApp/build.gradle.kts index a912548aaf..92306782f0 100644 --- a/composeApp/build.gradle.kts +++ b/composeApp/build.gradle.kts @@ -100,7 +100,7 @@ kotlin { implementation(projects.castEmpty) } - // Login sync QR scanner: CameraX + ZXing, not ML Kit, which F-Droid rejects as proprietary + // QR codes and their scanner: CameraX + ZXing, not ML Kit, which F-Droid rejects as proprietary implementation(libs.camera.camera2) implementation(libs.camera.lifecycle) implementation(libs.camera.view) @@ -202,7 +202,7 @@ kotlin { implementation(projects.mediaJvmUi) // macOS: hand window drags to the Window Server (ui/component/MacWindowDrag.kt) implementation(libs.jna) - // Login sync QR code + // QR codes implementation(libs.zxing.core) } } diff --git a/composeApp/src/androidMain/kotlin/com/maxrave/simpmusic/expect/ui/QrCode.android.kt b/composeApp/src/androidMain/kotlin/com/maxrave/simpmusic/expect/ui/QrCode.android.kt new file mode 100644 index 0000000000..0a2c1fb303 --- /dev/null +++ b/composeApp/src/androidMain/kotlin/com/maxrave/simpmusic/expect/ui/QrCode.android.kt @@ -0,0 +1,18 @@ +package com.maxrave.simpmusic.expect.ui + +import com.google.zxing.BarcodeFormat +import com.google.zxing.EncodeHintType +import com.google.zxing.qrcode.QRCodeWriter +import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel + +actual fun encodeQrMatrix(text: String): QrMatrix { + val matrix = + QRCodeWriter().encode( + text, + BarcodeFormat.QR_CODE, + 0, + 0, + mapOf(EncodeHintType.MARGIN to 2, EncodeHintType.ERROR_CORRECTION to ErrorCorrectionLevel.M), + ) + return QrMatrix(matrix.width, BooleanArray(matrix.width * matrix.width) { matrix[it % matrix.width, it / matrix.width] }) +} diff --git a/composeApp/src/androidMain/kotlin/com/maxrave/simpmusic/expect/ui/RoomQrScanner.android.kt b/composeApp/src/androidMain/kotlin/com/maxrave/simpmusic/expect/ui/RoomQrScanner.android.kt new file mode 100644 index 0000000000..b56f5660b1 --- /dev/null +++ b/composeApp/src/androidMain/kotlin/com/maxrave/simpmusic/expect/ui/RoomQrScanner.android.kt @@ -0,0 +1,210 @@ +package com.maxrave.simpmusic.expect.ui + +import android.Manifest +import android.content.pm.PackageManager +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.aspectRatio +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.Text +import androidx.compose.material3.rememberModalBottomSheetState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +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.platform.LocalContext +import androidx.compose.ui.unit.dp +import androidx.core.content.ContextCompat +import androidx.lifecycle.compose.LifecycleResumeEffect +import com.maxrave.simpmusic.extension.findActivity +import com.maxrave.simpmusic.ui.component.QrScanner +import com.maxrave.simpmusic.ui.component.rememberSurfaceDarkColors +import com.maxrave.simpmusic.ui.icon.Close +import com.maxrave.simpmusic.ui.icon.SimpIcons +import com.maxrave.simpmusic.ui.theme.typo +import com.maxrave.simpmusic.utils.roomCodeFromText +import kotlinx.coroutines.launch +import org.jetbrains.compose.resources.stringResource +import simpmusic.composeapp.generated.resources.Res +import simpmusic.composeapp.generated.resources.cancel +import simpmusic.composeapp.generated.resources.login_sync_allow_camera +import simpmusic.composeapp.generated.resources.login_sync_no_camera +import simpmusic.composeapp.generated.resources.login_sync_open_settings +import simpmusic.composeapp.generated.resources.lt_scan_camera_blocked +import simpmusic.composeapp.generated.resources.lt_scan_camera_needed +import simpmusic.composeapp.generated.resources.lt_scan_hint +import simpmusic.composeapp.generated.resources.lt_scan_not_a_room +import simpmusic.composeapp.generated.resources.lt_scan_qr + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +actual fun RoomQrScanner( + onRoomCode: (String) -> Unit, + onUnreadable: () -> Unit, + onDismiss: () -> Unit, +) { + val context = LocalContext.current + val scope = rememberCoroutineScope() + val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true) + val colors = rememberSurfaceDarkColors() + + fun hasCamera() = ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED + + var cameraAllowed by remember { mutableStateOf(hasCamera()) } + var cameraBlocked by remember { mutableStateOf(false) } + var cameraUnavailable by remember { mutableStateOf(false) } + var notARoom by remember { mutableStateOf(false) } + // The camera keeps reporting the same code until the sheet has finished sliding away. + var finished by remember { mutableStateOf(false) } + + val permissionLauncher = + rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted -> + cameraAllowed = granted + // Rationale is false after a denial only when the system will not ask again. + cameraBlocked = !granted && !context.findActivity().shouldShowRequestPermissionRationale(Manifest.permission.CAMERA) + } + + // Back from the system settings page with the camera now allowed. + LifecycleResumeEffect(Unit) { + if (hasCamera()) cameraAllowed = true + onPauseOrDispose { } + } + + fun hideThen(action: () -> Unit) { + scope.launch { sheetState.hide() }.invokeOnCompletion { action() } + } + + ModalBottomSheet( + onDismissRequest = onDismiss, + sheetState = sheetState, + containerColor = Color.Transparent, + contentColor = Color.Transparent, + dragHandle = null, + scrimColor = Color.Black.copy(alpha = .5f), + contentWindowInsets = { WindowInsets(0, 0, 0, 0) }, + ) { + Card( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp), + colors = CardDefaults.cardColors().copy(containerColor = colors.container), + ) { + Column( + modifier = + Modifier + .fillMaxWidth() + .verticalScroll(rememberScrollState()) + .navigationBarsPadding() + .padding(bottom = 24.dp), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + Spacer(Modifier.height(8.dp)) + Box( + Modifier + .width(60.dp) + .height(4.dp) + .clip(RoundedCornerShape(50)) + .background(colors.handle), + ) + Row( + modifier = Modifier.fillMaxWidth().padding(start = 24.dp, end = 8.dp, top = 8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + text = stringResource(Res.string.lt_scan_qr), + style = typo().titleMedium, + color = colors.content, + modifier = Modifier.weight(1f), + ) + IconButton(onClick = { hideThen(onDismiss) }) { + Icon(imageVector = SimpIcons.Close, contentDescription = stringResource(Res.string.cancel), tint = colors.content) + } + } + Text( + text = stringResource(if (notARoom) Res.string.lt_scan_not_a_room else Res.string.lt_scan_hint), + style = typo().bodySmall, + color = if (notARoom) MaterialTheme.colorScheme.error else colors.subtitle, + modifier = Modifier.fillMaxWidth().padding(horizontal = 24.dp), + ) + Spacer(Modifier.height(20.dp)) + val scanning = cameraAllowed && !cameraUnavailable + Box( + modifier = + Modifier + .padding(horizontal = 24.dp) + // Square on a phone; capped so it still fits a phone held sideways. + .widthIn(max = 340.dp) + .fillMaxWidth() + .aspectRatio(1f) + .clip(RoundedCornerShape(24.dp)) + .background(if (scanning) Color.Black else colors.disabled.copy(alpha = 0.15f)), + contentAlignment = Alignment.Center, + ) { + when { + cameraUnavailable -> { + Status(stringResource(Res.string.login_sync_no_camera), progress = false) + } + + cameraAllowed -> { + QrScanner( + onResult = { text -> + val code = roomCodeFromText(text) + if (code == null) { + notARoom = true + } else if (!finished) { + finished = true + hideThen { onRoomCode(code) } + } + }, + onCameraUnavailable = { cameraUnavailable = true }, + modifier = Modifier.fillMaxSize(), + ) + ViewfinderCorners(Modifier.fillMaxSize().padding(20.dp)) + } + + cameraBlocked -> { + Status(stringResource(Res.string.lt_scan_camera_blocked), progress = false) { + SheetButton(stringResource(Res.string.login_sync_open_settings)) { context.openAppSettings() } + } + } + + else -> { + Status(stringResource(Res.string.lt_scan_camera_needed), progress = false) { + SheetButton(stringResource(Res.string.login_sync_allow_camera)) { + permissionLauncher.launch(Manifest.permission.CAMERA) + } + } + } + } + } + } + } + } +} diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 4ea19ff0df..9c6c52618c 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -840,6 +840,20 @@ Waiting for the host They need to let you in. If the code is wrong you will get an error instead. Cancel + Required + Enter a display name to create or join a room + Enter the room code, %1$d letters and numbers + Show QR code + Scan to join + Scan it in SimpMusic, or with a phone's camera app if SimpMusic is installed there. Everyone has to be on the same server. + Scan QR code + Read QR code from an image + Point the camera at the room's QR code + That QR code is not a Listen Together room + No Listen Together QR code found in that image + SimpMusic uses the camera only to scan the room's QR code. + Camera access is turned off for SimpMusic. Turn it on in Settings to scan the code. + Leave this room before joining another one Share lyrics Select lines %1$d lines selected diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/App.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/App.kt index 1dba3cac8b..65fae02e4c 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/App.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/App.kt @@ -84,6 +84,7 @@ import com.maxrave.simpmusic.ui.icon.ArrowForwardIos import com.maxrave.simpmusic.ui.icon.SimpIcons import com.maxrave.simpmusic.ui.navigation.destination.home.AnalyticsDestination import com.maxrave.simpmusic.ui.navigation.destination.home.HomeDestination +import com.maxrave.simpmusic.ui.navigation.destination.home.ListenTogetherDestination import com.maxrave.simpmusic.ui.navigation.destination.home.NotificationDestination import com.maxrave.simpmusic.ui.navigation.destination.home.WrappedDestination import com.maxrave.simpmusic.ui.navigation.destination.library.LibraryDestination @@ -107,9 +108,11 @@ import com.maxrave.simpmusic.ui.theme.desktopWindowLight import com.maxrave.simpmusic.ui.theme.fontFamily import com.maxrave.simpmusic.ui.theme.parseThemeColorHex import com.maxrave.simpmusic.ui.theme.typo +import com.maxrave.simpmusic.utils.LISTEN_TOGETHER_APP_PATH import com.maxrave.simpmusic.utils.VersionManager import com.maxrave.simpmusic.utils.isAppLinkAvailable import com.maxrave.simpmusic.utils.libraryTabOf +import com.maxrave.simpmusic.utils.normalizedRoomCode import com.maxrave.simpmusic.viewModel.SharedViewModel import com.mikepenz.markdown.m3.Markdown import com.mikepenz.markdown.m3.markdownTypography @@ -366,6 +369,19 @@ fun App( } } + // simpmusic://listen-together?code=ROOMCODE — a room's QR code, read by the phone's + // camera app. It only fills in the form: joining a room stays the user's tap. + LISTEN_TOGETHER_APP_PATH -> { + val roomCode = normalizedRoomCode(data.getQueryParameter("code")) + if (roomCode != null) { + viewModel.requestListenTogetherRoom(roomCode) + // Single top: already on Listen Together, that screen takes the request. + navController.navigate(ListenTogetherDestination) { launchSingleTop = true } + } else { + viewModel.makeToast(getString(Res.string.this_link_is_not_supported)) + } + } + // simpmusic://recognize — the Quick Settings tile (Android only): Search with the // song recognition sheet open. "recognize" -> { diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/expect/ui/QrCode.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/expect/ui/QrCode.kt new file mode 100644 index 0000000000..6c3412c258 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/expect/ui/QrCode.kt @@ -0,0 +1,15 @@ +package com.maxrave.simpmusic.expect.ui + +/** A QR code's modules, including its quiet zone. `true` is a dark module. */ +class QrMatrix( + val size: Int, + private val modules: BooleanArray, +) { + operator fun get( + x: Int, + y: Int, + ): Boolean = modules[y * size + x] +} + +/** ZXing is a plain JVM artifact, so each platform declares it and calls it itself. */ +expect fun encodeQrMatrix(text: String): QrMatrix diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/expect/ui/RoomQrScanner.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/expect/ui/RoomQrScanner.kt new file mode 100644 index 0000000000..6636e59683 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/expect/ui/RoomQrScanner.kt @@ -0,0 +1,15 @@ +package com.maxrave.simpmusic.expect.ui + +import androidx.compose.runtime.Composable + +/** + * Reads a Listen Together room's QR code. Android scans with the camera in a bottom sheet, and keeps + * scanning past a code that is not a room. Desktop has no camera API, so it reads the code from an + * image file the user picks, and [onUnreadable] means that image held no room. + */ +@Composable +expect fun RoomQrScanner( + onRoomCode: (String) -> Unit, + onUnreadable: () -> Unit, + onDismiss: () -> Unit, +) diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/QrCodeImage.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/QrCodeImage.kt new file mode 100644 index 0000000000..0594fcfd44 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/QrCodeImage.kt @@ -0,0 +1,38 @@ +package com.maxrave.simpmusic.ui.component + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import com.maxrave.simpmusic.expect.ui.encodeQrMatrix + +/** Dark modules on white whatever the theme: scanners expect that polarity. */ +@Composable +fun QrCodeImage( + text: String, + modifier: Modifier = Modifier, +) { + val matrix = remember(text) { encodeQrMatrix(text) } + Canvas( + modifier + .clip(RoundedCornerShape(12.dp)) + .background(Color.White) + .padding(8.dp), + ) { + val cell = size.minDimension / matrix.size + for (y in 0 until matrix.size) { + for (x in 0 until matrix.size) { + // Half a pixel of overlap hides the seams between fractional-width modules. + if (matrix[x, y]) drawRect(Color.Black, Offset(x * cell, y * cell), Size(cell + 0.5f, cell + 0.5f)) + } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/icon/QrCode2.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/icon/QrCode2.kt new file mode 100644 index 0000000000..5820532818 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/icon/QrCode2.kt @@ -0,0 +1,198 @@ +package com.maxrave.simpmusic.ui.icon + +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.PathFillType +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.graphics.StrokeCap +import androidx.compose.ui.graphics.StrokeJoin +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.graphics.vector.path +import androidx.compose.ui.unit.dp + +@Suppress("CheckReturnValue") +val SimpIcons.QrCode2: ImageVector + get() { + if (_QrCode2 != null) { + return _QrCode2!! + } + _QrCode2 = + ImageVector.Builder( + name = "QrCode2", + defaultWidth = 24.dp, + defaultHeight = 24.dp, + viewportWidth = 24f, + viewportHeight = 24f, + ) + .apply { + path( + fill = SolidColor(Color.Black), + fillAlpha = 1f, + stroke = null, + strokeAlpha = 1f, + strokeLineWidth = 1f, + strokeLineCap = StrokeCap.Butt, + strokeLineJoin = StrokeJoin.Bevel, + strokeLineMiter = 1f, + pathFillType = PathFillType.Companion.NonZero, + ) { + moveTo(13f, 21f) + verticalLineTo(19f) + horizontalLineToRelative(2f) + verticalLineToRelative(2f) + horizontalLineTo(13f) + close() + moveTo(11f, 19f) + verticalLineTo(14f) + horizontalLineToRelative(2f) + verticalLineToRelative(5f) + horizontalLineTo(11f) + close() + moveToRelative(8f, -3f) + verticalLineTo(12f) + horizontalLineToRelative(2f) + verticalLineToRelative(4f) + horizontalLineTo(19f) + close() + moveTo(17f, 12f) + verticalLineTo(10f) + horizontalLineToRelative(2f) + verticalLineToRelative(2f) + horizontalLineTo(17f) + close() + moveTo(5f, 14f) + verticalLineTo(12f) + horizontalLineTo(7f) + verticalLineToRelative(2f) + horizontalLineTo(5f) + close() + moveTo(3f, 12f) + verticalLineTo(10f) + horizontalLineTo(5f) + verticalLineToRelative(2f) + horizontalLineTo(3f) + close() + moveTo(12f, 5f) + verticalLineTo(3f) + horizontalLineToRelative(2f) + verticalLineTo(5f) + horizontalLineTo(12f) + close() + moveTo(4.5f, 7.5f) + horizontalLineToRelative(3f) + verticalLineToRelative(-3f) + horizontalLineToRelative(-3f) + verticalLineToRelative(3f) + close() + moveTo(3f, 8f) + verticalLineTo(4f) + quadTo(3f, 3.57f, 3.29f, 3.29f) + reflectiveQuadTo(4f, 3f) + horizontalLineTo(8f) + quadTo(8.43f, 3f, 8.71f, 3.29f) + reflectiveQuadTo(9f, 4f) + verticalLineTo(8f) + quadTo(9f, 8.42f, 8.71f, 8.71f) + reflectiveQuadTo(8f, 9f) + horizontalLineTo(4f) + quadTo(3.58f, 9f, 3.29f, 8.71f) + reflectiveQuadTo(3f, 8f) + close() + moveTo(4.5f, 19.5f) + horizontalLineToRelative(3f) + verticalLineToRelative(-3f) + horizontalLineToRelative(-3f) + verticalLineToRelative(3f) + close() + moveTo(3f, 20f) + verticalLineTo(16f) + quadTo(3f, 15.58f, 3.29f, 15.29f) + reflectiveQuadTo(4f, 15f) + horizontalLineTo(8f) + quadToRelative(0.43f, 0f, 0.71f, 0.29f) + reflectiveQuadTo(9f, 16f) + verticalLineToRelative(4f) + quadToRelative(0f, 0.43f, -0.29f, 0.71f) + reflectiveQuadTo(8f, 21f) + horizontalLineTo(4f) + quadTo(3.58f, 21f, 3.29f, 20.71f) + quadTo(3f, 20.43f, 3f, 20f) + close() + moveTo(16.5f, 7.5f) + horizontalLineToRelative(3f) + verticalLineToRelative(-3f) + horizontalLineToRelative(-3f) + verticalLineToRelative(3f) + close() + moveTo(15f, 8f) + verticalLineTo(4f) + quadTo(15f, 3.57f, 15.29f, 3.29f) + reflectiveQuadTo(16f, 3f) + horizontalLineToRelative(4f) + quadToRelative(0.43f, 0f, 0.71f, 0.29f) + reflectiveQuadTo(21f, 4f) + verticalLineTo(8f) + quadToRelative(0f, 0.42f, -0.29f, 0.71f) + reflectiveQuadTo(20f, 9f) + horizontalLineTo(16f) + quadTo(15.58f, 9f, 15.29f, 8.71f) + reflectiveQuadTo(15f, 8f) + close() + moveToRelative(2f, 13f) + verticalLineTo(18f) + horizontalLineTo(15f) + verticalLineTo(16f) + horizontalLineToRelative(4f) + verticalLineToRelative(3f) + horizontalLineToRelative(2f) + verticalLineToRelative(2f) + horizontalLineTo(17f) + close() + moveTo(13f, 14f) + verticalLineTo(12f) + horizontalLineToRelative(4f) + verticalLineToRelative(2f) + horizontalLineTo(13f) + close() + moveTo(9f, 14f) + verticalLineTo(12f) + horizontalLineTo(7f) + verticalLineTo(10f) + horizontalLineToRelative(6f) + verticalLineToRelative(2f) + horizontalLineTo(11f) + verticalLineToRelative(2f) + horizontalLineTo(9f) + close() + moveTo(10f, 9f) + verticalLineTo(5f) + horizontalLineToRelative(2f) + verticalLineTo(7f) + horizontalLineToRelative(2f) + verticalLineTo(9f) + horizontalLineTo(10f) + close() + moveTo(5.25f, 6.75f) + verticalLineTo(5.25f) + horizontalLineToRelative(1.5f) + verticalLineToRelative(1.5f) + horizontalLineTo(5.25f) + close() + moveToRelative(0f, 12f) + verticalLineToRelative(-1.5f) + horizontalLineToRelative(1.5f) + verticalLineToRelative(1.5f) + horizontalLineTo(5.25f) + close() + moveToRelative(12f, -12f) + verticalLineTo(5.25f) + horizontalLineToRelative(1.5f) + verticalLineToRelative(1.5f) + horizontalLineToRelative(-1.5f) + close() + } + } + .buildSimpIcon() + return _QrCode2!! + } + +private var _QrCode2: ImageVector? = null diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/icon/QrCodeScanner.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/icon/QrCodeScanner.kt new file mode 100644 index 0000000000..de672233ec --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/icon/QrCodeScanner.kt @@ -0,0 +1,216 @@ +package com.maxrave.simpmusic.ui.icon + +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.PathFillType +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.graphics.StrokeCap +import androidx.compose.ui.graphics.StrokeJoin +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.graphics.vector.path +import androidx.compose.ui.unit.dp + +@Suppress("CheckReturnValue") +val SimpIcons.QrCodeScanner: ImageVector + get() { + if (_QrCodeScanner != null) { + return _QrCodeScanner!! + } + _QrCodeScanner = + ImageVector.Builder( + name = "QrCodeScanner", + defaultWidth = 24.dp, + defaultHeight = 24.dp, + viewportWidth = 24f, + viewportHeight = 24f, + ) + .apply { + path( + fill = SolidColor(Color.Black), + fillAlpha = 1f, + stroke = null, + strokeAlpha = 1f, + strokeLineWidth = 1f, + strokeLineCap = StrokeCap.Butt, + strokeLineJoin = StrokeJoin.Bevel, + strokeLineMiter = 1f, + pathFillType = PathFillType.Companion.NonZero, + ) { + moveTo(3f, 7f) + quadTo(2.58f, 7f, 2.29f, 6.71f) + quadTo(2f, 6.43f, 2f, 6f) + verticalLineTo(3f) + quadTo(2f, 2.57f, 2.29f, 2.29f) + reflectiveQuadTo(3f, 2f) + horizontalLineTo(6f) + quadTo(6.43f, 2f, 6.71f, 2.29f) + reflectiveQuadTo(7f, 3f) + quadTo(7f, 3.42f, 6.71f, 3.71f) + reflectiveQuadTo(6f, 4f) + horizontalLineTo(4f) + verticalLineTo(6f) + quadTo(4f, 6.43f, 3.71f, 6.71f) + reflectiveQuadTo(3f, 7f) + close() + moveTo(3f, 22f) + quadTo(2.58f, 22f, 2.29f, 21.71f) + quadTo(2f, 21.43f, 2f, 21f) + verticalLineTo(18f) + quadTo(2f, 17.58f, 2.29f, 17.29f) + reflectiveQuadTo(3f, 17f) + reflectiveQuadToRelative(0.71f, 0.29f) + reflectiveQuadTo(4f, 18f) + verticalLineToRelative(2f) + horizontalLineTo(6f) + quadToRelative(0.43f, 0f, 0.71f, 0.29f) + reflectiveQuadTo(7f, 21f) + reflectiveQuadTo(6.71f, 21.71f) + reflectiveQuadTo(6f, 22f) + horizontalLineTo(3f) + close() + moveToRelative(15f, 0f) + quadToRelative(-0.43f, 0f, -0.71f, -0.29f) + quadTo(17f, 21.43f, 17f, 21f) + reflectiveQuadToRelative(0.29f, -0.71f) + reflectiveQuadTo(18f, 20f) + horizontalLineToRelative(2f) + verticalLineTo(18f) + quadToRelative(0f, -0.43f, 0.29f, -0.71f) + reflectiveQuadTo(21f, 17f) + quadToRelative(0.43f, 0f, 0.71f, 0.29f) + reflectiveQuadTo(22f, 18f) + verticalLineToRelative(3f) + quadToRelative(0f, 0.43f, -0.29f, 0.71f) + reflectiveQuadTo(21f, 22f) + horizontalLineTo(18f) + close() + moveTo(20.29f, 6.71f) + quadTo(20f, 6.43f, 20f, 6f) + verticalLineTo(4f) + horizontalLineTo(18f) + quadTo(17.58f, 4f, 17.29f, 3.71f) + reflectiveQuadTo(17f, 3f) + quadTo(17f, 2.57f, 17.29f, 2.29f) + reflectiveQuadTo(18f, 2f) + horizontalLineToRelative(3f) + quadToRelative(0.43f, 0f, 0.71f, 0.29f) + reflectiveQuadTo(22f, 3f) + verticalLineTo(6f) + quadToRelative(0f, 0.43f, -0.29f, 0.71f) + reflectiveQuadTo(21f, 7f) + reflectiveQuadTo(20.29f, 6.71f) + close() + moveTo(17.5f, 19f) + verticalLineTo(17.5f) + horizontalLineTo(19f) + verticalLineTo(19f) + horizontalLineTo(17.5f) + close() + moveToRelative(0f, -3f) + verticalLineTo(14.5f) + horizontalLineTo(19f) + verticalLineTo(16f) + horizontalLineTo(17.5f) + close() + moveTo(16f, 17.5f) + verticalLineTo(16f) + horizontalLineToRelative(1.5f) + verticalLineToRelative(1.5f) + horizontalLineTo(16f) + close() + moveTo(14.5f, 19f) + verticalLineTo(17.5f) + horizontalLineTo(16f) + verticalLineTo(19f) + horizontalLineTo(14.5f) + close() + moveTo(13f, 17.5f) + verticalLineTo(16f) + horizontalLineToRelative(1.5f) + verticalLineToRelative(1.5f) + horizontalLineTo(13f) + close() + moveToRelative(3f, -3f) + verticalLineTo(13f) + horizontalLineToRelative(1.5f) + verticalLineToRelative(1.5f) + horizontalLineTo(16f) + close() + moveTo(14.5f, 16f) + verticalLineTo(14.5f) + horizontalLineTo(16f) + verticalLineTo(16f) + horizontalLineTo(14.5f) + close() + moveTo(13f, 14.5f) + verticalLineTo(13f) + horizontalLineToRelative(1.5f) + verticalLineToRelative(1.5f) + horizontalLineTo(13f) + close() + moveTo(14f, 11f) + quadToRelative(-0.42f, 0f, -0.71f, -0.29f) + quadTo(13f, 10.43f, 13f, 10f) + verticalLineTo(6f) + quadTo(13f, 5.57f, 13.29f, 5.29f) + reflectiveQuadTo(14f, 5f) + horizontalLineToRelative(4f) + quadToRelative(0.43f, 0f, 0.71f, 0.29f) + reflectiveQuadTo(19f, 6f) + verticalLineToRelative(4f) + quadToRelative(0f, 0.42f, -0.29f, 0.71f) + reflectiveQuadTo(18f, 11f) + horizontalLineTo(14f) + close() + moveTo(6f, 19f) + quadTo(5.58f, 19f, 5.29f, 18.71f) + quadTo(5f, 18.43f, 5f, 18f) + verticalLineTo(14f) + quadTo(5f, 13.58f, 5.29f, 13.29f) + reflectiveQuadTo(6f, 13f) + horizontalLineToRelative(4f) + quadToRelative(0.43f, 0f, 0.71f, 0.29f) + reflectiveQuadTo(11f, 14f) + verticalLineToRelative(4f) + quadToRelative(0f, 0.43f, -0.29f, 0.71f) + reflectiveQuadTo(10f, 19f) + horizontalLineTo(6f) + close() + moveTo(6f, 11f) + quadTo(5.58f, 11f, 5.29f, 10.71f) + quadTo(5f, 10.43f, 5f, 10f) + verticalLineTo(6f) + quadTo(5f, 5.57f, 5.29f, 5.29f) + reflectiveQuadTo(6f, 5f) + horizontalLineToRelative(4f) + quadToRelative(0.43f, 0f, 0.71f, 0.29f) + reflectiveQuadTo(11f, 6f) + verticalLineToRelative(4f) + quadToRelative(0f, 0.42f, -0.29f, 0.71f) + reflectiveQuadTo(10f, 11f) + horizontalLineTo(6f) + close() + moveToRelative(0.5f, 6.5f) + horizontalLineToRelative(3f) + verticalLineToRelative(-3f) + horizontalLineToRelative(-3f) + verticalLineToRelative(3f) + close() + moveToRelative(0f, -8f) + horizontalLineToRelative(3f) + verticalLineToRelative(-3f) + horizontalLineToRelative(-3f) + verticalLineToRelative(3f) + close() + moveToRelative(8f, 0f) + horizontalLineToRelative(3f) + verticalLineToRelative(-3f) + horizontalLineToRelative(-3f) + verticalLineToRelative(3f) + close() + } + } + .buildSimpIcon() + return _QrCodeScanner!! + } + +private var _QrCodeScanner: ImageVector? = null diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/ListenTogetherScreen.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/ListenTogetherScreen.kt index 6e0c78e0f3..5abcde4b0b 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/ListenTogetherScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/ListenTogetherScreen.kt @@ -21,6 +21,7 @@ import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth @@ -59,6 +60,11 @@ import androidx.compose.ui.graphics.luminance import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.platform.LocalClipboardManager +import androidx.compose.ui.semantics.LiveRegionMode +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.error +import androidx.compose.ui.semantics.liveRegion +import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.TextRange import androidx.compose.ui.text.font.FontFamily @@ -77,34 +83,47 @@ import com.maxrave.domain.data.model.listentogether.RoomConnection import com.maxrave.domain.data.model.listentogether.RoomJoinRequest import com.maxrave.domain.data.model.listentogether.RoomMember import com.maxrave.domain.data.model.listentogether.RoomSuggestion +import com.maxrave.simpmusic.Platform import com.maxrave.simpmusic.expect.shareUrl import com.maxrave.simpmusic.expect.ui.DesktopMiniPlayerClearance import com.maxrave.simpmusic.expect.ui.PlatformBackdrop +import com.maxrave.simpmusic.expect.ui.RoomQrScanner import com.maxrave.simpmusic.expect.ui.VerticalScrollBar import com.maxrave.simpmusic.expect.ui.layerBackdrop import com.maxrave.simpmusic.expect.ui.rememberBackdrop import com.maxrave.simpmusic.extension.angledGradientBackground import com.maxrave.simpmusic.extension.artworkScrimBrush import com.maxrave.simpmusic.extension.rgbFactor +import com.maxrave.simpmusic.getPlatform import com.maxrave.simpmusic.ui.component.EndOfPage import com.maxrave.simpmusic.ui.component.LiquidGlassIconButton +import com.maxrave.simpmusic.ui.component.QrCodeImage import com.maxrave.simpmusic.ui.icon.ArrowBackIosNew import com.maxrave.simpmusic.ui.icon.ArrowForwardIos import com.maxrave.simpmusic.ui.icon.Check import com.maxrave.simpmusic.ui.icon.Close import com.maxrave.simpmusic.ui.icon.ContentCopy import com.maxrave.simpmusic.ui.icon.Logout +import com.maxrave.simpmusic.ui.icon.QrCode2 +import com.maxrave.simpmusic.ui.icon.QrCodeScanner import com.maxrave.simpmusic.ui.icon.Settings import com.maxrave.simpmusic.ui.icon.Share import com.maxrave.simpmusic.ui.icon.SimpIcons import com.maxrave.simpmusic.ui.navigation.destination.home.ListenTogetherSettingsDestination import com.maxrave.simpmusic.ui.theme.typo +import com.maxrave.simpmusic.utils.ROOM_CODE_LENGTH +import com.maxrave.simpmusic.utils.RoomFormProblem +import com.maxrave.simpmusic.utils.listenTogetherLink import com.maxrave.simpmusic.viewModel.ListenTogetherViewModel +import com.maxrave.simpmusic.viewModel.SharedViewModel import kotlinx.coroutines.delay +import org.jetbrains.compose.resources.getString import org.jetbrains.compose.resources.stringResource +import org.koin.compose.koinInject import org.koin.compose.viewmodel.koinViewModel import simpmusic.composeapp.generated.resources.Res import simpmusic.composeapp.generated.resources.listen_together +import simpmusic.composeapp.generated.resources.lt_already_in_room import simpmusic.composeapp.generated.resources.lt_background_warning import simpmusic.composeapp.generated.resources.lt_block import simpmusic.composeapp.generated.resources.lt_block_desc @@ -118,6 +137,7 @@ import simpmusic.composeapp.generated.resources.lt_credit_protocol import simpmusic.composeapp.generated.resources.lt_disconnect import simpmusic.composeapp.generated.resources.lt_display_name import simpmusic.composeapp.generated.resources.lt_display_name_hint +import simpmusic.composeapp.generated.resources.lt_display_name_required import simpmusic.composeapp.generated.resources.lt_host_badge import simpmusic.composeapp.generated.resources.lt_in_room import simpmusic.composeapp.generated.resources.lt_join_requests @@ -128,7 +148,15 @@ import simpmusic.composeapp.generated.resources.lt_kick_desc import simpmusic.composeapp.generated.resources.lt_leave_room import simpmusic.composeapp.generated.resources.lt_not_connected import simpmusic.composeapp.generated.resources.lt_or_join_with_code +import simpmusic.composeapp.generated.resources.lt_qr_desc +import simpmusic.composeapp.generated.resources.lt_qr_title +import simpmusic.composeapp.generated.resources.lt_required import simpmusic.composeapp.generated.resources.lt_room_code +import simpmusic.composeapp.generated.resources.lt_room_code_incomplete +import simpmusic.composeapp.generated.resources.lt_scan_qr +import simpmusic.composeapp.generated.resources.lt_scan_qr_image +import simpmusic.composeapp.generated.resources.lt_scan_unreadable +import simpmusic.composeapp.generated.resources.lt_show_qr import simpmusic.composeapp.generated.resources.lt_suggestions import simpmusic.composeapp.generated.resources.lt_tagline import simpmusic.composeapp.generated.resources.lt_transfer_host @@ -136,6 +164,7 @@ import simpmusic.composeapp.generated.resources.lt_transfer_host_desc import simpmusic.composeapp.generated.resources.lt_waiting_approval import simpmusic.composeapp.generated.resources.lt_waiting_approval_desc import simpmusic.composeapp.generated.resources.lt_you +import simpmusic.composeapp.generated.resources.ok import simpmusic.composeapp.generated.resources.settings /** @@ -157,7 +186,6 @@ private const val TWO_COLUMN_MIN_DP = 900 /** How long the copy button shows a tick before going back to the copy glyph. */ private const val COPIED_FEEDBACK_MS = 1800L -private const val ROOM_CODE_LENGTH = ListenTogetherViewModel.ROOM_CODE_LENGTH /** Avatar tints derived from the theme, so they move with it instead of fighting it. */ @Composable @@ -181,12 +209,26 @@ fun ListenTogetherScreen( navController: NavController, innerPadding: PaddingValues, viewModel: ListenTogetherViewModel = koinViewModel(), + sharedViewModel: SharedViewModel = koinInject(), ) { val state by viewModel.state.collectAsStateWithLifecycle() val displayName by viewModel.displayName.collectAsStateWithLifecycle() val codeInput by viewModel.roomCodeInput.collectAsStateWithLifecycle() val clipboard = LocalClipboardManager.current var managing by remember { mutableStateOf(null) } + // The code it was opened for, not a flag: leaving the room must not bring it back on the next one. + var showingQrFor by remember { mutableStateOf(null) } + + // Clears the request last: that changes this effect's key, which would cancel it mid-way. + val roomRequest by sharedViewModel.listenTogetherRoomRequest.collectAsStateWithLifecycle() + LaunchedEffect(roomRequest) { + roomRequest?.let { code -> + if (!viewModel.onRoomCodeReceived(code)) { + sharedViewModel.makeToast(getString(Res.string.lt_already_in_room)) + } + sharedViewModel.requestListenTogetherRoom(null) + } + } // The back button refracts whatever the page has drawn, so the CONTENT is the backdrop source // and the button is its SIBLING — the same arrangement Album/Playlist/Analytics use. Nesting the @@ -204,8 +246,9 @@ fun ListenTogetherScreen( val copyCode: () -> Unit = { state.roomCode?.let { clipboard.setText(AnnotatedString(it)) } } val shareTitle = stringResource(Res.string.listen_together) val shareCode: () -> Unit = { - state.roomCode?.let { shareUrl(title = shareTitle, url = SHARE_PREFIX + it) } + state.roomCode?.let { shareUrl(title = shareTitle, url = "$SHARE_PREFIX$it\n${listenTogetherLink(it)}") } } + val showQr: () -> Unit = { showingQrFor = state.roomCode } val openSettings: () -> Unit = { navController.navigate(ListenTogetherSettingsDestination) } // Home's ambient top glow, tinted from the THEME rather than artwork — this page has none. @@ -265,7 +308,7 @@ fun ListenTogetherScreen( TitleBlock(inRoom = state.inRoom) ConnectionLine(state.connection, viewModel::connect, viewModel::disconnect) AnimatedVisibility(visible = state.inRoom) { - RoomCodePoster(state, copyCode, shareCode) + RoomCodePoster(state, copyCode, shareCode, showQr) } } VerticalScrollBar( @@ -309,7 +352,7 @@ fun ListenTogetherScreen( TitleBlock(inRoom = state.inRoom) ConnectionLine(state.connection, viewModel::connect, viewModel::disconnect) AnimatedVisibility(visible = state.inRoom) { - RoomCodePoster(state, copyCode, shareCode) + RoomCodePoster(state, copyCode, shareCode, showQr) } WorkArea(state, displayName, codeInput, viewModel, { managing = it }, openSettings) } @@ -340,6 +383,10 @@ fun ListenTogetherScreen( onDismiss = { managing = null }, ) } + + state.roomCode?.takeIf { it == showingQrFor }?.let { code -> + RoomQrDialog(code = code, onDismiss = { showingQrFor = null }) + } } /** @@ -395,24 +442,68 @@ private fun ColumnScope.WorkArea( } else -> { - NameField(displayName, viewModel::onDisplayNameChange) + val problems by viewModel.formProblems.collectAsStateWithLifecycle() + val focusName by viewModel.focusNameField.collectAsStateWithLifecycle() + val connecting by viewModel.connectingForAction.collectAsStateWithLifecycle() + var scanning by remember { mutableStateOf(false) } + val connectingLabel = stringResource(Res.string.lt_connecting) + + NameField( + value = displayName, + onValueChange = viewModel::onDisplayNameChange, + isMissing = RoomFormProblem.NAME_MISSING in problems, + focusRequested = focusName, + onFocusRequestHandled = viewModel::onNameFieldFocused, + ) + // Only a connection in progress disables these. With a name or code missing they stay + // live, because a grey button cannot say what it is waiting for and a tap can. PrimaryButton( - text = stringResource(Res.string.lt_create_room), - enabled = displayName.isNotBlank() && state.isConnected, + text = if (connecting) connectingLabel else stringResource(Res.string.lt_create_room), + enabled = !connecting, onClick = viewModel::createRoom, ) DividerLabel(stringResource(Res.string.lt_or_join_with_code)) CodeInput(codeInput, viewModel::onRoomCodeChange) + when { + RoomFormProblem.QR_UNREADABLE in problems -> FieldError(stringResource(Res.string.lt_scan_unreadable)) + RoomFormProblem.CODE_INCOMPLETE in problems -> { + FieldError(stringResource(Res.string.lt_room_code_incomplete, ROOM_CODE_LENGTH)) + } + } + + TextAction( + icon = SimpIcons.QrCodeScanner, + text = + stringResource( + if (getPlatform() == Platform.Android) Res.string.lt_scan_qr else Res.string.lt_scan_qr_image, + ), + color = MaterialTheme.colorScheme.primary, + onClick = { scanning = true }, + ) SecondaryButton( - text = stringResource(Res.string.lt_join_room), - enabled = displayName.isNotBlank() && codeInput.length == ROOM_CODE_LENGTH && state.isConnected, + text = if (connecting) connectingLabel else stringResource(Res.string.lt_join_room), + enabled = !connecting, onClick = viewModel::joinRoom, ) + if (scanning) { + RoomQrScanner( + onRoomCode = { code -> + scanning = false + viewModel.onRoomCodeReceived(code) + }, + onUnreadable = { + scanning = false + viewModel.onQrUnreadable() + }, + onDismiss = { scanning = false }, + ) + } + Text( text = stringResource(Res.string.lt_background_warning), style = typo().bodySmall, @@ -600,6 +691,7 @@ private fun RoomCodePoster( state: ListenTogetherRoom, onCopyCode: () -> Unit, onShareCode: () -> Unit, + onShowQr: () -> Unit, ) { Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { Text( @@ -663,7 +755,12 @@ private fun RoomCodePoster( copied = true } } - GlyphButton(SimpIcons.Share, onShareCode) + GlyphButton(SimpIcons.Share, onClick = onShareCode) + GlyphButton( + SimpIcons.QrCode2, + contentDescription = stringResource(Res.string.lt_show_qr), + onClick = onShowQr, + ) } } } @@ -964,6 +1061,56 @@ private fun TextAction( } } +/** + * The room's code as a QR code, big enough to scan across a table. Sits on white in both themes, as + * [QrCodeImage] requires, with the code under it for anyone who would rather type. + */ +@Composable +private fun RoomQrDialog( + code: String, + onDismiss: () -> Unit, +) { + val description = stringResource(Res.string.lt_show_qr) + Dialog(onDismissRequest = onDismiss) { + Column( + modifier = + Modifier + .width(320.dp) + .clip(CARD_SHAPE) + .background(MaterialTheme.colorScheme.surfaceContainerHigh) + .padding(20.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + Text( + stringResource(Res.string.lt_qr_title), + style = typo().titleSmall, + color = MaterialTheme.colorScheme.onSurface, + ) + QrCodeImage( + text = listenTogetherLink(code), + modifier = + Modifier + .fillMaxWidth() + .aspectRatio(1f) + .semantics { contentDescription = description }, + ) + Text( + code.chunked(4).joinToString(" "), + style = typo().titleMedium.copy(fontFamily = FontFamily.Monospace, letterSpacing = 3.sp), + color = MaterialTheme.colorScheme.onSurface, + ) + Text( + stringResource(Res.string.lt_qr_desc), + style = typo().bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center, + ) + Chip(stringResource(Res.string.ok), onClick = onDismiss) + } + } +} + @Composable private fun MemberActionDialog( member: RoomMember, @@ -1107,6 +1254,7 @@ private fun Chip( @Composable private fun GlyphButton( icon: androidx.compose.ui.graphics.vector.ImageVector, + contentDescription: String? = null, onClick: () -> Unit, ) { Box( @@ -1118,7 +1266,7 @@ private fun GlyphButton( .clickable { onClick() }, contentAlignment = Alignment.Center, ) { - Icon(icon, contentDescription = null, tint = MaterialTheme.colorScheme.onBackground, modifier = Modifier.size(18.dp)) + Icon(icon, contentDescription = contentDescription, tint = MaterialTheme.colorScheme.onBackground, modifier = Modifier.size(18.dp)) } } @@ -1259,9 +1407,33 @@ private fun DividerLabel(text: String) { private fun NameField( value: String, onValueChange: (String) -> Unit, + isMissing: Boolean, + focusRequested: Boolean, + onFocusRequestHandled: () -> Unit, ) { + val focusRequester = remember { FocusRequester() } + val errorText = stringResource(Res.string.lt_display_name_required) + // Lives here because the requester must already be attached, and the form is not always composed. + LaunchedEffect(focusRequested) { + if (focusRequested) { + focusRequester.requestFocus() + onFocusRequestHandled() + } + } Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { - Text(stringResource(Res.string.lt_display_name), style = typo().bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + stringResource(Res.string.lt_display_name), + style = typo().bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.weight(1f), + ) + Text( + stringResource(Res.string.lt_required), + style = typo().bodySmall, + color = if (isMissing) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant, + ) + } BasicTextField( value = value, onValueChange = onValueChange, @@ -1272,16 +1444,41 @@ private fun NameField( Modifier .fillMaxWidth() .height(54.dp) + .focusRequester(focusRequester) .clip(ROW_SHAPE) - .background(MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.08f)), + .background(MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.08f)) + .then( + if (isMissing) { + Modifier + .border(2.dp, MaterialTheme.colorScheme.error, ROW_SHAPE) + .semantics { error(errorText) } + } else { + Modifier + }, + ), decorationBox = { inner -> Box(Modifier.fillMaxSize().padding(horizontal = 16.dp), contentAlignment = Alignment.CenterStart) { inner() } }, ) - Text(stringResource(Res.string.lt_display_name_hint), style = typo().bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + if (isMissing) { + FieldError(errorText) + } else { + Text(stringResource(Res.string.lt_display_name_hint), style = typo().bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + } } } +/** Announced when it appears, since the error is the only thing that changed on screen. */ +@Composable +private fun FieldError(message: String) { + Text( + text = message, + style = typo().bodySmall, + color = MaterialTheme.colorScheme.error, + modifier = Modifier.semantics { liveRegion = LiveRegionMode.Polite }, + ) +} + @Composable private fun CodeInput( code: String, diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/utils/AppLinks.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/utils/AppLinks.kt index 09db55f548..67e2531fc1 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/utils/AppLinks.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/utils/AppLinks.kt @@ -7,7 +7,7 @@ import com.maxrave.simpmusic.getPlatform // Every path the deep-link router in App.kt opens; anything else gets its "link not supported" toast. // A path added there must be added here too, or no launch banner can point at it. -private val APP_LINK_PATHS = setOf("notification", "watch", "playlist", "channel", "c", "album", "library", "analytics", "taste", "recognize") +private val APP_LINK_PATHS = setOf("notification", "watch", "playlist", "channel", "c", "album", "library", "analytics", "taste", "recognize", LISTEN_TOGETHER_APP_PATH) /** * Whether the screen a `simpmusic://` link opens exists for this user right now. Analytics, the diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/utils/ListenTogetherLink.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/utils/ListenTogetherLink.kt new file mode 100644 index 0000000000..4dd57bd51d --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/utils/ListenTogetherLink.kt @@ -0,0 +1,89 @@ +package com.maxrave.simpmusic.utils + +import com.eygraber.uri.Uri +import com.maxrave.domain.data.model.listentogether.RoomConnection +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.dropWhile +import kotlinx.coroutines.flow.first + +/** The router's path for a room link; also in APP_LINK_PATHS in AppLinks.kt. */ +const val LISTEN_TOGETHER_APP_PATH = "listen-together" + +/** Room codes are eight characters on metroserver. */ +const val ROOM_CODE_LENGTH = 8 + +private val ROOM_CODE = Regex("[A-Za-z0-9]{$ROOM_CODE_LENGTH}") +private val WHITESPACE = Regex("\\s+") + +/** + * What a room's QR code carries. + * + * The custom scheme rather than https://simpmusic.org/app/…: that link only reaches the app once the + * site serves /.well-known/assetlinks.json without a redirect, and until then a camera app would open + * a 404 page in the browser. [roomCodeFromText] and the router already accept the https form, so + * moving to it later changes this one line. + */ +fun listenTogetherLink(roomCode: String): String = "simpmusic://$LISTEN_TOGETHER_APP_PATH?code=$roomCode" + +/** A room code in the server's spelling, or null if [code] cannot be one. */ +fun normalizedRoomCode(code: String?): String? = code?.trim()?.takeIf { ROOM_CODE.matches(it) }?.uppercase() + +/** + * Finds a room code in text that came from outside the app: a scanned QR code or a paste. + * + * Accepts a bare code, our own links, and Metrolist's share link, since rooms are shared between the + * two apps. Anything else is null. The result is only ever a code to put in the form, so a QR code + * cannot use this to open a page or join a room by itself. + */ +fun roomCodeFromText(text: String): String? { + val trimmed = text.trim() + normalizedRoomCode(trimmed)?.let { return it } + return trimmed + .split(WHITESPACE) + .filter { "://" in it } + .firstNotNullOfOrNull(::roomCodeFromLink) +} + +private fun roomCodeFromLink(link: String): String? { + val uri = runCatching { Uri.parse(link) }.getOrNull() ?: return null + val scheme = uri.scheme?.lowercase() + val host = uri.host?.lowercase() + val path = uri.pathSegments + val isRoomLink = + when { + scheme == "simpmusic" -> host == LISTEN_TOGETHER_APP_PATH + scheme != "https" -> false + host == "simpmusic.org" || host == "www.simpmusic.org" -> path == listOf("app", LISTEN_TOGETHER_APP_PATH) + host == "metrolist.cc" || host == "www.metrolist.cc" -> path == listOf("listen") + else -> false + } + return if (isRoomLink) normalizedRoomCode(uri.getQueryParameter("code")) else null +} + +/** What stops the Listen Together form from going ahead, each shown beside its own field. */ +enum class RoomFormProblem { + NAME_MISSING, + CODE_INCOMPLETE, + QR_UNREADABLE, +} + +/** Checks the form before creating a room ([roomCode] null) or joining one. */ +fun roomFormProblems( + displayName: String, + roomCode: String? = null, +): Set = + buildSet { + if (displayName.isBlank()) add(RoomFormProblem.NAME_MISSING) + if (roomCode != null && normalizedRoomCode(roomCode) == null) add(RoomFormProblem.CODE_INCOMPLETE) + } + +/** + * Waits for a connection that was just asked for and says whether it came up. + * + * Skips the Disconnected or Failed the flow may still hold from before the request: the repository + * mirrors the session a moment later, and taking that old value as the outcome would drop the action + * the user is waiting on. + */ +suspend fun Flow.awaitConnected(): Boolean = + dropWhile { it is RoomConnection.Disconnected || it is RoomConnection.Failed } + .first { it !is RoomConnection.Connecting } is RoomConnection.Connected diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/ListenTogetherViewModel.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/ListenTogetherViewModel.kt index 8d320cecbe..b0cd020f6e 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/ListenTogetherViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/ListenTogetherViewModel.kt @@ -5,15 +5,25 @@ import androidx.lifecycle.viewModelScope import com.maxrave.data.listentogether.ListenTogetherPlaybackBridge import com.maxrave.data.listentogether.ListenTogetherPrefs import com.maxrave.domain.data.model.listentogether.ListenTogetherRoom +import com.maxrave.domain.data.model.listentogether.RoomConnection import com.maxrave.domain.repository.ListenTogetherRepository import com.maxrave.domain.manager.DataStoreManager +import com.maxrave.simpmusic.utils.ROOM_CODE_LENGTH +import com.maxrave.simpmusic.utils.RoomFormProblem +import com.maxrave.simpmusic.utils.awaitConnected +import com.maxrave.simpmusic.utils.roomCodeFromText +import com.maxrave.simpmusic.utils.roomFormProblems +import kotlinx.coroutines.Job import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.stateIn +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.withTimeoutOrNull /** * Screen state for Listen Together. @@ -56,26 +66,117 @@ class ListenTogetherViewModel( private val _roomCodeInput = MutableStateFlow("") val roomCodeInput: StateFlow = _roomCodeInput.asStateFlow() + private val _formProblems = MutableStateFlow(emptySet()) + + /** What the form says is wrong. Empty until the user has tried to go ahead, or a link has arrived. */ + val formProblems: StateFlow> = _formProblems.asStateFlow() + + private val _focusNameField = MutableStateFlow(false) + val focusNameField: StateFlow = _focusNameField.asStateFlow() + + private var pendingAction: Job? = null + private val _connectingForAction = MutableStateFlow(false) + + /** A tap on Create or Join is waiting for the connection it started. */ + val connectingForAction: StateFlow = _connectingForAction.asStateFlow() + fun onDisplayNameChange(value: String) { // metroserver caps usernames at 50; trimming here means the server never has to reject it. _displayName.value = value.take(MAX_USERNAME_LENGTH) + if (value.isNotBlank()) _formProblems.update { it - RoomFormProblem.NAME_MISSING } + } + + fun onNameFieldFocused() { + _focusNameField.value = false } fun onRoomCodeChange(value: String) { - _roomCodeInput.value = - value.uppercase().filter { it.isLetterOrDigit() }.take(ROOM_CODE_LENGTH) + // Longer than a code, so it may be a whole link or share message pasted in. Filtering that + // down to its first eight letters would leave a wrong code, like SIMPMUSI. + val pasted = if (value.length > ROOM_CODE_LENGTH) roomCodeFromText(value) else null + val code = pasted ?: value.uppercase().filter { it.isLetterOrDigit() }.take(ROOM_CODE_LENGTH) + _roomCodeInput.value = code + _formProblems.update { problems -> + val fixed = if (code.length == ROOM_CODE_LENGTH) setOf(RoomFormProblem.CODE_INCOMPLETE) else emptySet() + problems - fixed - RoomFormProblem.QR_UNREADABLE + } } fun connect() = repository.connect() - fun disconnect() = repository.disconnect() + fun disconnect() { + pendingAction?.cancel() + repository.disconnect() + } fun createRoom() { - repository.createRoom(_displayName.value) + val name = _displayName.value.trim() + if (!formIsReady(roomFormProblems(name))) return + whenConnected { repository.createRoom(name) } } fun joinRoom() { - repository.joinRoom(_roomCodeInput.value, _displayName.value) + val name = _displayName.value.trim() + val code = _roomCodeInput.value + if (!formIsReady(roomFormProblems(name, code))) return + whenConnected { repository.joinRoom(code, name) } + } + + private fun formIsReady(problems: Set): Boolean { + _formProblems.value = problems + if (RoomFormProblem.NAME_MISSING in problems) _focusNameField.value = true + return problems.isEmpty() + } + + /** + * Runs [action] on a live connection, connecting first if needed: the session drops a create + * message sent while disconnected, with no error, so a tap has to wait for the socket. + */ + private fun whenConnected(action: () -> Unit) { + if (repository.room.value.isConnected) { + action() + return + } + if (pendingAction?.isActive == true) return + pendingAction = + viewModelScope.launch { + _connectingForAction.value = true + try { + if (repository.room.value.connection !is RoomConnection.Connecting) repository.connect() + val connected = + withTimeoutOrNull(CONNECT_WAIT_MS) { + repository.room.map { it.connection }.awaitConnected() + } + if (connected == true) action() + } finally { + _connectingForAction.value = false + } + } + } + + /** + * A room code from a QR code or an app link. Fills in the form and connects, but never joins by + * itself: the code came from outside the app, and joining shows the user's name to that room. + * + * @return false if the user is already in a different room, so nothing changed. + */ + fun onRoomCodeReceived(code: String): Boolean { + val room = repository.room.value + if (room.inRoom) return room.roomCode == code + _roomCodeInput.value = code + _formProblems.update { it - RoomFormProblem.CODE_INCOMPLETE - RoomFormProblem.QR_UNREADABLE } + if (_displayName.value.isBlank()) { + _formProblems.update { it + RoomFormProblem.NAME_MISSING } + _focusNameField.value = true + } + if (room.connection is RoomConnection.Disconnected || room.connection is RoomConnection.Failed) { + repository.connect() + } + return true + } + + fun onQrUnreadable() { + _formProblems.update { it + RoomFormProblem.QR_UNREADABLE } } fun leaveRoom() { @@ -142,7 +243,7 @@ class ListenTogetherViewModel( fun clearError() = repository.clearError() companion object { - const val ROOM_CODE_LENGTH = 8 private const val MAX_USERNAME_LENGTH = 50 + private const val CONNECT_WAIT_MS = 30_000L } } diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/SharedViewModel.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/SharedViewModel.kt index 4dd5884e5c..7e65af0fbf 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/SharedViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/SharedViewModel.kt @@ -801,6 +801,15 @@ class SharedViewModel( _songRecognitionRequest.value = requested } + // A room code from a Listen Together link; that screen puts it in its form the next time it + // composes and clears the request. + private val _listenTogetherRoomRequest = MutableStateFlow(null) + val listenTogetherRoomRequest: StateFlow = _listenTogetherRoomRequest.asStateFlow() + + fun requestListenTogetherRoom(roomCode: String?) { + _listenTogetherRoomRequest.value = roomCode + } + fun putString( key: String, value: String, diff --git a/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/expect/ui/LibrarySync.jvm.kt b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/expect/ui/LibrarySync.jvm.kt index 32dee017eb..143efad5fa 100644 --- a/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/expect/ui/LibrarySync.jvm.kt +++ b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/expect/ui/LibrarySync.jvm.kt @@ -36,6 +36,7 @@ import com.maxrave.domain.data.model.librarysync.SyncPeer import com.maxrave.domain.manager.DataStoreManager import com.maxrave.domain.repository.LibrarySyncHostRepository import com.maxrave.simpmusic.expect.openUrl +import com.maxrave.simpmusic.ui.component.QrCodeImage import com.maxrave.simpmusic.ui.theme.AppTheme import com.maxrave.simpmusic.ui.theme.parseThemeColorHex import com.maxrave.simpmusic.ui.theme.typo @@ -100,7 +101,7 @@ actual fun LibrarySyncDialog(onDismiss: () -> Unit) { } is LibrarySyncPairingState.Waiting -> { - QrCode(p.invite, Modifier.size(240.dp)) + QrCodeImage(p.invite, Modifier.size(240.dp)) Text(text = stringResource(Res.string.library_sync_desktop_instructions), style = typo().bodyMedium, textAlign = TextAlign.Center) Text(text = stringResource(Res.string.login_sync_pick_address), style = typo().bodySmall, textAlign = TextAlign.Center) Column(Modifier.fillMaxWidth()) { diff --git a/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/expect/ui/LoginSync.jvm.kt b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/expect/ui/LoginSync.jvm.kt index 184a620d9e..d069402705 100644 --- a/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/expect/ui/LoginSync.jvm.kt +++ b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/expect/ui/LoginSync.jvm.kt @@ -1,7 +1,5 @@ package com.maxrave.simpmusic.expect.ui -import androidx.compose.foundation.Canvas -import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row @@ -12,7 +10,6 @@ import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.selection.selectable -import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material3.AlertDialog import androidx.compose.material3.CircularProgressIndicator @@ -24,22 +21,14 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue -import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.clip -import androidx.compose.ui.geometry.Offset -import androidx.compose.ui.geometry.Size -import androidx.compose.ui.graphics.Color import androidx.compose.ui.semantics.Role import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle -import com.google.zxing.BarcodeFormat -import com.google.zxing.EncodeHintType -import com.google.zxing.qrcode.QRCodeWriter -import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel import com.maxrave.domain.data.model.loginsync.LoginSyncHostState +import com.maxrave.simpmusic.ui.component.QrCodeImage import com.maxrave.simpmusic.ui.theme.typo import com.maxrave.simpmusic.viewModel.LoginSyncHostViewModel import org.jetbrains.compose.resources.stringResource @@ -87,7 +76,7 @@ actual fun LoginSyncDialog(onDismiss: () -> Unit) { } is LoginSyncHostState.Waiting -> { - QrCode(s.invite, Modifier.size(240.dp)) + QrCodeImage(s.invite, Modifier.size(240.dp)) Text( text = stringResource(Res.string.login_sync_desktop_instructions, stringResource(Res.string.login_sync_android_title)), style = typo().bodyMedium, @@ -168,35 +157,3 @@ actual fun LoginSyncDialog(onDismiss: () -> Unit) { }, ) } - -/** Dark modules on white whatever the theme: scanners expect that polarity. */ -@Composable -internal fun QrCode( - text: String, - modifier: Modifier = Modifier, -) { - val matrix = - remember(text) { - QRCodeWriter().encode( - text, - BarcodeFormat.QR_CODE, - 0, - 0, - mapOf(EncodeHintType.MARGIN to 2, EncodeHintType.ERROR_CORRECTION to ErrorCorrectionLevel.M), - ) - } - Canvas( - modifier - .clip(RoundedCornerShape(12.dp)) - .background(Color.White) - .padding(8.dp), - ) { - val cell = size.minDimension / matrix.width - for (y in 0 until matrix.height) { - for (x in 0 until matrix.width) { - // Half a pixel of overlap hides the seams between fractional-width modules. - if (matrix[x, y]) drawRect(Color.Black, Offset(x * cell, y * cell), Size(cell + 0.5f, cell + 0.5f)) - } - } - } -} diff --git a/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/expect/ui/PhotoPicker.jvm.kt b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/expect/ui/PhotoPicker.jvm.kt index 57cfd0e189..d9e333f821 100644 --- a/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/expect/ui/PhotoPicker.jvm.kt +++ b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/expect/ui/PhotoPicker.jvm.kt @@ -30,7 +30,7 @@ actual fun photoPickerResult(onResultUri: (String?) -> Unit): PhotoPickerLaunche // FileDialog's javadoc says filters do nothing on Windows, but OpenJDK's dialog hook there asks // WFileDialogPeer.checkFilenameFilter about every item (CDN_INCLUDEITEM); macOS and GTK ask too. -private val imageFileFilter = +internal val imageFileFilter = FilenameFilter { dir, name -> File(dir, name).isDirectory || name.substringAfterLast('.', "").lowercase() in setOf("jpg", "jpeg", "png", "webp", "gif", "bmp") diff --git a/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/expect/ui/QrCode.jvm.kt b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/expect/ui/QrCode.jvm.kt new file mode 100644 index 0000000000..0a2c1fb303 --- /dev/null +++ b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/expect/ui/QrCode.jvm.kt @@ -0,0 +1,18 @@ +package com.maxrave.simpmusic.expect.ui + +import com.google.zxing.BarcodeFormat +import com.google.zxing.EncodeHintType +import com.google.zxing.qrcode.QRCodeWriter +import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel + +actual fun encodeQrMatrix(text: String): QrMatrix { + val matrix = + QRCodeWriter().encode( + text, + BarcodeFormat.QR_CODE, + 0, + 0, + mapOf(EncodeHintType.MARGIN to 2, EncodeHintType.ERROR_CORRECTION to ErrorCorrectionLevel.M), + ) + return QrMatrix(matrix.width, BooleanArray(matrix.width * matrix.width) { matrix[it % matrix.width, it / matrix.width] }) +} diff --git a/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/expect/ui/RoomQrScanner.jvm.kt b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/expect/ui/RoomQrScanner.jvm.kt new file mode 100644 index 0000000000..4ee2241630 --- /dev/null +++ b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/expect/ui/RoomQrScanner.jvm.kt @@ -0,0 +1,62 @@ +package com.maxrave.simpmusic.expect.ui + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.rememberUpdatedState +import com.google.zxing.BinaryBitmap +import com.google.zxing.DecodeHintType +import com.google.zxing.RGBLuminanceSource +import com.google.zxing.ReaderException +import com.google.zxing.common.HybridBinarizer +import com.google.zxing.qrcode.QRCodeReader +import com.maxrave.logger.Logger +import com.maxrave.simpmusic.utils.roomCodeFromText +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import java.awt.image.BufferedImage +import java.io.File +import javax.imageio.ImageIO + +@Composable +actual fun RoomQrScanner( + onRoomCode: (String) -> Unit, + onUnreadable: () -> Unit, + onDismiss: () -> Unit, +) { + val currentOnRoomCode by rememberUpdatedState(onRoomCode) + val currentOnUnreadable by rememberUpdatedState(onUnreadable) + val currentOnDismiss by rememberUpdatedState(onDismiss) + val scope = rememberCoroutineScope() + LaunchedEffect(Unit) { + showOpenFileDialog(imageFileFilter) { file -> + if (file == null) { + currentOnDismiss() + } else { + scope.launch { + val code = withContext(Dispatchers.IO) { readQrCode(file) }?.let(::roomCodeFromText) + if (code != null) currentOnRoomCode(code) else currentOnUnreadable() + } + } + } + } +} + +private fun readQrCode(file: File): String? = + runCatching { ImageIO.read(file) } + .onFailure { Logger.w("RoomQrScanner", "image: ${it.message}") } + .getOrNull() + // ImageIO answers null, not an exception, for a format it has no reader for (WebP). + ?.let(::decodeQrCode) + +internal fun decodeQrCode(image: BufferedImage): String? { + val pixels = image.getRGB(0, 0, image.width, image.height, null, 0, image.width) + val source = RGBLuminanceSource(image.width, image.height, pixels) + return try { + QRCodeReader().decode(BinaryBitmap(HybridBinarizer(source)), mapOf(DecodeHintType.TRY_HARDER to true)).text + } catch (e: ReaderException) { + null + } +} diff --git a/composeApp/src/jvmTest/kotlin/com/maxrave/simpmusic/expect/ui/RoomQrCodeTest.kt b/composeApp/src/jvmTest/kotlin/com/maxrave/simpmusic/expect/ui/RoomQrCodeTest.kt new file mode 100644 index 0000000000..9dee3f6175 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/maxrave/simpmusic/expect/ui/RoomQrCodeTest.kt @@ -0,0 +1,32 @@ +package com.maxrave.simpmusic.expect.ui + +import com.maxrave.simpmusic.utils.listenTogetherLink +import com.maxrave.simpmusic.utils.roomCodeFromText +import java.awt.image.BufferedImage +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull + +class RoomQrCodeTest { + private fun QrMatrix.toImage(scale: Int = 6): BufferedImage { + val image = BufferedImage(size * scale, size * scale, BufferedImage.TYPE_INT_RGB) + for (y in 0 until image.height) { + for (x in 0 until image.width) { + image.setRGB(x, y, if (this[x / scale, y / scale]) 0x000000 else 0xFFFFFF) + } + } + return image + } + + @Test + fun aGeneratedRoomQrCodeScansBackToItsRoom() { + val decoded = decodeQrCode(encodeQrMatrix(listenTogetherLink("ABCD1234")).toImage()) + assertEquals(listenTogetherLink("ABCD1234"), decoded) + assertEquals("ABCD1234", roomCodeFromText(decoded.orEmpty())) + } + + @Test + fun anImageWithNoCodeReadsAsNothing() { + assertNull(decodeQrCode(BufferedImage(200, 200, BufferedImage.TYPE_INT_RGB))) + } +} diff --git a/composeApp/src/jvmTest/kotlin/com/maxrave/simpmusic/utils/ListenTogetherLinkTest.kt b/composeApp/src/jvmTest/kotlin/com/maxrave/simpmusic/utils/ListenTogetherLinkTest.kt new file mode 100644 index 0000000000..783054ba34 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/maxrave/simpmusic/utils/ListenTogetherLinkTest.kt @@ -0,0 +1,107 @@ +package com.maxrave.simpmusic.utils + +import com.maxrave.domain.data.model.listentogether.RoomConnection +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.runBlocking +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +class ListenTogetherLinkTest { + @Test + fun aRoomLinkReadsBackItsOwnCode() { + assertEquals("ABCD1234", roomCodeFromText(listenTogetherLink("ABCD1234"))) + } + + @Test + fun acceptsBareCodesInAnyCase() { + assertEquals("ABCD1234", roomCodeFromText("ABCD1234")) + assertEquals("ABCD1234", roomCodeFromText(" abcd1234\n")) + } + + @Test + fun acceptsTheLinksThatCanCarryARoom() { + assertEquals("ABCD1234", roomCodeFromText("https://simpmusic.org/app/listen-together?code=abcd1234")) + assertEquals("ABCD1234", roomCodeFromText("https://www.simpmusic.org/app/listen-together?code=ABCD1234")) + assertEquals("ABCD1234", roomCodeFromText("https://metrolist.cc/listen?code=ABCD1234")) + } + + @Test + fun findsTheLinkInsideTheShareMessage() { + val message = "Join my SimpMusic room with code ABCD1234\n${listenTogetherLink("ABCD1234")}" + assertEquals("ABCD1234", roomCodeFromText(message)) + } + + @Test + fun refusesOtherHostsAndPaths() { + assertNull(roomCodeFromText("https://simpmusic.org.evil.example/app/listen-together?code=ABCD1234")) + assertNull(roomCodeFromText("https://evil.example/listen?code=ABCD1234")) + assertNull(roomCodeFromText("https://simpmusic.org/app/watch?code=ABCD1234")) + assertNull(roomCodeFromText("http://metrolist.cc/listen?code=ABCD1234")) + assertNull(roomCodeFromText("simpmusic://watch?code=ABCD1234")) + assertNull(roomCodeFromText("wordbyword://listen-together?code=ABCD1234")) + } + + @Test + fun refusesMissingOrMalformedCodes() { + assertNull(roomCodeFromText("")) + assertNull(roomCodeFromText("ABC123")) + assertNull(roomCodeFromText("ABCD12345")) + assertNull(roomCodeFromText("ABCD-123")) + assertNull(roomCodeFromText("simpmusic://listen-together")) + assertNull(roomCodeFromText("simpmusic://listen-together?code=ABC")) + assertNull(roomCodeFromText("simpmusic://listen-together?code=ABCD%201234")) + assertNull(roomCodeFromText("not a uri :// at all")) + } + + @Test + fun aBlankNameStopsBothActions() { + assertEquals(setOf(RoomFormProblem.NAME_MISSING), roomFormProblems("")) + assertEquals(setOf(RoomFormProblem.NAME_MISSING), roomFormProblems(" ")) + assertEquals(setOf(RoomFormProblem.NAME_MISSING), roomFormProblems(" ", "ABCD1234")) + } + + @Test + fun joiningAlsoNeedsAWholeCode() { + assertEquals(setOf(RoomFormProblem.CODE_INCOMPLETE), roomFormProblems("Cami", "ABC")) + assertEquals( + setOf(RoomFormProblem.NAME_MISSING, RoomFormProblem.CODE_INCOMPLETE), + roomFormProblems("", ""), + ) + } + + @Test + fun aCompleteFormHasNoProblems() { + assertTrue(roomFormProblems("Cami").isEmpty()) + assertTrue(roomFormProblems("Cami", "ABCD1234").isEmpty()) + } + + @Test + fun aConnectionThatComesUpIsReported() = + runBlocking { + assertTrue(flowOf(RoomConnection.Connecting, RoomConnection.Connected("1")).awaitConnected()) + assertTrue(flowOf(RoomConnection.Connected("1")).awaitConnected()) + } + + @Test + fun aStaleFailureBeforeTheAttemptIsSkipped() = + runBlocking { + assertTrue( + flowOf( + RoomConnection.Failed("old"), + RoomConnection.Disconnected, + RoomConnection.Connecting, + RoomConnection.Connected("1"), + ).awaitConnected(), + ) + } + + @Test + fun aFailureDuringTheAttemptIsReported() = + runBlocking { + assertFalse(flowOf(RoomConnection.Connecting, RoomConnection.Failed("no route")).awaitConnected()) + assertFalse(flowOf(RoomConnection.Connecting, RoomConnection.Disconnected).awaitConnected()) + } +} diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index e9ecffa042..8407dcade8 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -95,7 +95,7 @@ nucleus-notification = "2.5.18" commonsIo = "2.5" packagedeps = "0.2.5" conveyor = "2.0" -# Login sync: QR encode (Desktop) + decode (Android), and the Android scanner's camera +# QR codes (Login sync, Listen Together): encode + decode on both platforms, and the Android scanner's camera zxing = "3.5.4" camerax = "1.6.2" From 05b218ec01fbecdf396b40dfd0809a1c5da9ab15 Mon Sep 17 00:00:00 2001 From: Juan Camilo Grisales Date: Mon, 2 Nov 2026 01:02:22 -0500 Subject: [PATCH 2/2] fix(deeplink): wait for the navigation graph before routing a link A link that launches the app could reach the router before NavHost had set its graph, and navigating then crashed with "You must call setGraph() before calling getGraph()". That is how a room link opens from a phone's camera app. --- composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/App.kt | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/App.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/App.kt index 65fae02e4c..5e1d77624c 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/App.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/App.kt @@ -235,6 +235,10 @@ fun App( val data = intent.data Logger.d("MainActivity", "onCreate: $data") if (data != null) { + // A link that launched the app can get here before NavHost, composed further down, has + // set its graph, and navigating then throws. Wait here, before any setIntent(null): + // clearing the intent changes this effect's key and would cancel the wait. + navController.currentBackStackEntryFlow.first() if (data.scheme == "simpmusic" && data.host == "notification") { viewModel.setIntent(null) navController.navigate(