From 6ff9ba79b355519862a2b1c77f2075ac9b1d2e55 Mon Sep 17 00:00:00 2001 From: SiddartthVS Date: Sat, 26 Sep 2026 17:19:24 +0530 Subject: [PATCH 01/29] fix: dismiss keyboard when selecting search result --- .../com/maxrave/simpmusic/ui/screen/other/SearchScreen.kt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/SearchScreen.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/SearchScreen.kt index cc4e05f0c6..a5aea297bf 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/SearchScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/SearchScreen.kt @@ -396,6 +396,7 @@ fun SearchScreen( onItemClick = { item -> when (item) { is SongsResult, is VideosResult -> { + focusManager.clearFocus() val firstTrack: Track = (item as? SongsResult)?.toTrack() ?: (item as VideosResult).toTrack() searchViewModel.setQueueData( QueueData.Data( @@ -777,6 +778,7 @@ fun SearchScreen( onMoreClick(result.toTrack().toSongEntity()) }, onClickListener = { + focusManager.clearFocus() val firstTrack = result.toTrack() searchViewModel.setQueueData( QueueData.Data( @@ -816,6 +818,7 @@ fun SearchScreen( onMoreClick(result.toTrack().toSongEntity()) }, onClickListener = { + focusManager.clearFocus() val firstTrack = result.toTrack() searchViewModel.setQueueData( QueueData.Data( From a289c76de6028f675ceac77bd08e3a0ed9bbb330 Mon Sep 17 00:00:00 2001 From: Cuong-Tran <16017808+cuong-tran@users.noreply.github.com> Date: Mon, 19 Oct 2026 12:00:21 +0700 Subject: [PATCH 02/29] feat(downloads): swipe a song left in Library's Downloaded list to remove its download, add Remove download to that list's multi-select sheet in place of Download, keep search results in step with removals and spring a cancelled swipe back --- .../composeResources/values/strings.xml | 1 + .../simpmusic/ui/component/FullWidthItems.kt | 56 ++++++++++++++++--- .../library/LibraryDynamicPlaylistScreen.kt | 44 +++++++++++++-- .../LibraryDynamicPlaylistViewModel.kt | 26 +++++++++ 4 files changed, 113 insertions(+), 14 deletions(-) diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 39861b4b07..5151b85236 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -128,6 +128,7 @@ Downloaded Cache Cached Remove from cache + Remove download Thumbnail Cache Backup Backup Your Data diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/FullWidthItems.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/FullWidthItems.kt index e0d3c4b071..f472de70d0 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/FullWidthItems.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/FullWidthItems.kt @@ -80,6 +80,7 @@ import com.maxrave.domain.utils.isLive import com.maxrave.domain.utils.toListName import com.maxrave.simpmusic.ui.icon.Add import com.maxrave.simpmusic.ui.icon.Check +import com.maxrave.simpmusic.ui.icon.Delete import com.maxrave.simpmusic.ui.icon.DownloadForOffline import com.maxrave.simpmusic.ui.icon.DragHandle import com.maxrave.simpmusic.ui.icon.MoreVert @@ -102,6 +103,7 @@ import simpmusic.composeapp.generated.resources.play_next import simpmusic.composeapp.generated.resources.playlist import simpmusic.composeapp.generated.resources.podcasts import simpmusic.composeapp.generated.resources.radio +import simpmusic.composeapp.generated.resources.remove_download import simpmusic.composeapp.generated.resources.you import kotlin.math.roundToInt @@ -111,6 +113,9 @@ import kotlin.math.roundToInt * Multi-selection is opt-in per screen: pass [onLongClick] to let a long press start it, then * drive [selectionMode] and [isSelected] from the screen's * [com.maxrave.simpmusic.ui.component.selection.SongSelectionState]. + * + * Swipes are opt-in too: [onAddToQueue] answers a swipe toward the end, [onSwipeToDelete] one + * toward the start. Both fire only once the row is dragged all the way. */ @OptIn(ExperimentalFoundationApi::class) @Composable @@ -123,6 +128,7 @@ fun SongFullWidthItems( onMoreClickListener: ((videoId: String) -> Unit)? = null, onClickListener: ((videoId: String) -> Unit)? = null, onAddToQueue: ((videoId: String) -> Unit)? = null, + onSwipeToDelete: ((videoId: String) -> Unit)? = null, selectionMode: Boolean = false, isSelected: Boolean = false, onLongClick: ((videoId: String) -> Unit)? = null, @@ -176,7 +182,30 @@ fun SongFullWidthItems( } } } + Crossfade( + offsetX.value <= -maxOffset / 2, + modifier = Modifier.align(Alignment.CenterEnd), + ) { shouldShowDelete -> + if (shouldShowDelete) { + Box( + modifier = + Modifier + .height(heightDp) + .aspectRatio(1f) + .padding(end = 15.dp), + contentAlignment = Alignment.Center, + ) { + Icon( + tint = Color.Red, + imageVector = SimpIcons.Delete, + contentDescription = stringResource(Res.string.remove_download), + ) + } + } + } val itemVideoId = track?.videoId ?: songEntity?.videoId ?: "" + val canSwipeToQueue = !isPlaying && onAddToQueue != null + val canSwipeToDelete = onSwipeToDelete != null Box( modifier = modifier @@ -200,29 +229,38 @@ fun SongFullWidthItems( ).animateContentSize() // Keyed on selectionMode so the swipe detector is torn down when selection // starts — keyed on Unit it would keep running with the stale flag captured. - .pointerInput(selectionMode) { - if (!isPlaying && onAddToQueue != null && !selectionMode) { + // The same goes for the two directions the row may move in. + .pointerInput(selectionMode, canSwipeToQueue, canSwipeToDelete) { + if (!selectionMode && (canSwipeToQueue || canSwipeToDelete)) { + // A direction with nothing behind it stays shut, so the row cannot be + // dragged out to reveal an empty slot. + val minOffset = if (canSwipeToDelete) -maxOffset else 0f + val maxQueueOffset = if (canSwipeToQueue) maxOffset else 0f detectHorizontalDragGestures( onHorizontalDrag = { change, dragAmount -> - if (offsetX.value + dragAmount > 0) { + val target = (offsetX.value + dragAmount).coerceIn(minOffset, maxQueueOffset) + if (target != offsetX.value) { change.consume() coroutineScope.launch { - offsetX.snapTo( - (offsetX.value + dragAmount).coerceAtMost(maxOffset), - ) + offsetX.snapTo(target) } } }, onDragEnd = { if (offsetX.value == maxOffset) { - onAddToQueue( - track?.videoId ?: songEntity?.videoId ?: "", - ) + onAddToQueue?.invoke(itemVideoId) + } else if (offsetX.value == -maxOffset) { + onSwipeToDelete?.invoke(itemVideoId) } coroutineScope.launch { offsetX.animateTo(0f) } }, + onDragCancel = { + coroutineScope.launch { + offsetX.animateTo(0f) + } + }, ) } }.onGloballyPositioned { coordinates -> diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/library/LibraryDynamicPlaylistScreen.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/library/LibraryDynamicPlaylistScreen.kt index 358b2cab03..a7adf781a4 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/library/LibraryDynamicPlaylistScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/library/LibraryDynamicPlaylistScreen.kt @@ -61,10 +61,12 @@ import com.maxrave.simpmusic.ui.component.PlaylistFullWidthItems import com.maxrave.simpmusic.ui.component.RippleIconButton import com.maxrave.simpmusic.ui.component.SongFullWidthItems import com.maxrave.simpmusic.ui.component.selection.SelectedSongsBottomSheet +import com.maxrave.simpmusic.ui.component.selection.SongSelectionAction import com.maxrave.simpmusic.ui.component.selection.SongSelectionTopAppBar import com.maxrave.simpmusic.ui.component.selection.rememberSongSelectionState import com.maxrave.simpmusic.ui.icon.ArrowBackIosNew import com.maxrave.simpmusic.ui.icon.Close +import com.maxrave.simpmusic.ui.icon.Delete import com.maxrave.simpmusic.ui.icon.PlayCircle import com.maxrave.simpmusic.ui.icon.Search import com.maxrave.simpmusic.ui.icon.Shuffle @@ -102,6 +104,7 @@ import simpmusic.composeapp.generated.resources.liked_songs import simpmusic.composeapp.generated.resources.liked_songs_count import simpmusic.composeapp.generated.resources.lower_plays import simpmusic.composeapp.generated.resources.most_played +import simpmusic.composeapp.generated.resources.remove_download import simpmusic.composeapp.generated.resources.search import simpmusic.composeapp.generated.resources.seconds import simpmusic.composeapp.generated.resources.wrapped @@ -178,7 +181,9 @@ fun LibraryDynamicPlaylistScreen( parsed.topListRange()?.let { (start, end) -> analyticsViewModel.showRange(start, end) } } - LaunchedEffect(query) { + // Keyed on the downloaded list as well: a download removed while searching has to leave the + // filtered list too, not only the full one. + LaunchedEffect(query, downloaded) { tempFavorite = favorite.filter { it.matches(query) } tempFollowed = followed.filter { it.name.contains(query, ignoreCase = true) } tempMostPlayed = mostPlayed.filter { it.matches(query) } @@ -447,6 +452,12 @@ fun LibraryDynamicPlaylistScreen( arrayListOf(song.toTrack()), ) }, + onSwipeToDelete = + if (type == LibraryDynamicPlaylistType.Downloaded) { + { viewModel.removeDownloads(listOf(it)) } + } else { + null + }, selectionMode = selectionState.isActive, isSelected = selectionState.isSelected(song.videoId), onLongClick = { selectionState.start(it) }, @@ -460,6 +471,8 @@ fun LibraryDynamicPlaylistScreen( } if (showSelectionSheet) { val selectedIds = selectionState.selected.toList() + val isDownloadedList = LibraryDynamicPlaylistType.toType(type) == LibraryDynamicPlaylistType.Downloaded + val removeDownloadLabel = stringResource(Res.string.remove_download) SelectedSongsBottomSheet( count = selectedIds.size, onDismiss = { showSelectionSheet = false }, @@ -472,14 +485,35 @@ fun LibraryDynamicPlaylistScreen( selectionState.exit() }, onAddToPlaylist = { showSelectionAddToPlaylist = true }, - onDownload = { - selectionViewModel.download(selectedIds) - selectionState.exit() - }, + // Everything in the Downloaded list is downloaded already, so Download would do nothing. + onDownload = + if (isDownloadedList) { + null + } else { + { + selectionViewModel.download(selectedIds) + selectionState.exit() + } + }, onAddToFavorite = { selectionViewModel.addToFavorite(selectedIds) selectionState.exit() }, + extraActions = + if (isDownloadedList) { + listOf( + SongSelectionAction( + icon = SimpIcons.Delete, + label = removeDownloadLabel, + tint = Color.Red, + ) { + viewModel.removeDownloads(selectedIds) + selectionState.exit() + }, + ) + } else { + emptyList() + }, ) } if (showSelectionAddToPlaylist) { diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/LibraryDynamicPlaylistViewModel.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/LibraryDynamicPlaylistViewModel.kt index 158f946dd1..cfd1dcc28a 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/LibraryDynamicPlaylistViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/LibraryDynamicPlaylistViewModel.kt @@ -7,6 +7,7 @@ import com.maxrave.domain.data.entities.ArtistEntity import com.maxrave.domain.data.entities.DownloadState import com.maxrave.domain.data.entities.SongEntity import com.maxrave.domain.extension.now +import com.maxrave.domain.mediaservice.handler.DownloadHandler import com.maxrave.domain.mediaservice.handler.PlaylistType import com.maxrave.domain.mediaservice.handler.QueueData import com.maxrave.domain.repository.AnalyticsRepository @@ -25,6 +26,7 @@ import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.firstOrNull import kotlinx.coroutines.flow.lastOrNull +import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.datetime.DateTimeUnit import kotlinx.datetime.LocalDate @@ -32,8 +34,10 @@ import kotlinx.datetime.Month import kotlinx.datetime.atTime import kotlinx.datetime.minus import kotlinx.datetime.plus +import org.koin.core.component.inject import simpmusic.composeapp.generated.resources.Res import simpmusic.composeapp.generated.resources.playlist +import simpmusic.composeapp.generated.resources.removed_download import simpmusic.composeapp.generated.resources.wrapped_recap_month import simpmusic.composeapp.generated.resources.wrapped_recap_month_year @@ -43,6 +47,8 @@ class LibraryDynamicPlaylistViewModel( private val analyticsRepository: AnalyticsRepository, private val cacheRepository: CacheRepository, ) : BaseViewModel() { + private val downloadUtils: DownloadHandler by inject() + private val _listFavoriteSong: MutableStateFlow> = MutableStateFlow(emptyList()) val listFavoriteSong: StateFlow> get() = _listFavoriteSong @@ -202,6 +208,26 @@ class LibraryDynamicPlaylistViewModel( } } + /** + * Removes the downloads behind the Downloaded list's swipe and its multi-select action, the + * same way the song menu's Download toggle does. + * + * The rows leave the list first: [SongRepository.getDownloadedSongs] is read once rather than + * observed, so nothing else would take them off the screen. + */ + fun removeDownloads(videoIds: List) { + if (videoIds.isEmpty()) return + _listDownloadedSong.update { songs -> songs.filterNot { it.videoId in videoIds } } + viewModelScope.launch { + videoIds.forEach { videoId -> + downloadUtils.removeDownload(videoId) + songRepository.updateDownloadState(videoId, DownloadState.STATE_NOT_DOWNLOADED) + } + // One toast for the batch, as the other selection actions do. + makeToast(getString(Res.string.removed_download)) + } + } + fun removeFromCache(videoId: String) { viewModelScope.launch { cacheRepository.removeCachedSong(videoId) From c46199b314c31b4a26a28b2953a35e2766847fd3 Mon Sep 17 00:00:00 2001 From: Cuong-Tran <16017808+cuong-tran@users.noreply.github.com> Date: Mon, 19 Oct 2026 12:00:51 +0700 Subject: [PATCH 03/29] fix(downloads): remove downloads from the Downloaded list off the main thread, since Desktop scans the downloads folder once per song --- .../viewModel/LibraryDynamicPlaylistViewModel.kt | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/LibraryDynamicPlaylistViewModel.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/LibraryDynamicPlaylistViewModel.kt index cfd1dcc28a..3724b78827 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/LibraryDynamicPlaylistViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/LibraryDynamicPlaylistViewModel.kt @@ -19,6 +19,7 @@ import com.maxrave.domain.utils.toTrack import com.maxrave.simpmusic.ui.screen.home.analytics.monthFullNameResource import com.maxrave.simpmusic.ui.screen.library.LibraryDynamicPlaylistType import com.maxrave.simpmusic.viewModel.base.BaseViewModel +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow @@ -28,6 +29,7 @@ import kotlinx.coroutines.flow.firstOrNull import kotlinx.coroutines.flow.lastOrNull import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext import kotlinx.datetime.DateTimeUnit import kotlinx.datetime.LocalDate import kotlinx.datetime.Month @@ -219,9 +221,13 @@ class LibraryDynamicPlaylistViewModel( if (videoIds.isEmpty()) return _listDownloadedSong.update { songs -> songs.filterNot { it.videoId in videoIds } } viewModelScope.launch { - videoIds.forEach { videoId -> - downloadUtils.removeDownload(videoId) - songRepository.updateDownloadState(videoId, DownloadState.STATE_NOT_DOWNLOADED) + // Off the main thread: Desktop's removeDownload scans the downloads folder once per + // song, and a selection can hold 25 of them. + withContext(Dispatchers.IO) { + videoIds.forEach { videoId -> + downloadUtils.removeDownload(videoId) + songRepository.updateDownloadState(videoId, DownloadState.STATE_NOT_DOWNLOADED) + } } // One toast for the batch, as the other selection actions do. makeToast(getString(Res.string.removed_download)) From 74e691c88cef5bfc7bfbb99cdd6468a3889bcf05 Mon Sep 17 00:00:00 2001 From: Cuong-Tran <16017808+cuong-tran@users.noreply.github.com> Date: Mon, 19 Oct 2026 12:01:20 +0700 Subject: [PATCH 04/29] fix(ui): spring a song row back when its swipe detector restarts mid-drag, which happens when the row starts or stops playing or selection starts, instead of leaving it pushed aside --- .../simpmusic/ui/component/FullWidthItems.kt | 57 +++++++++++-------- 1 file changed, 33 insertions(+), 24 deletions(-) diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/FullWidthItems.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/FullWidthItems.kt index f472de70d0..082654abb3 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/FullWidthItems.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/FullWidthItems.kt @@ -236,32 +236,41 @@ fun SongFullWidthItems( // dragged out to reveal an empty slot. val minOffset = if (canSwipeToDelete) -maxOffset else 0f val maxQueueOffset = if (canSwipeToQueue) maxOffset else 0f - detectHorizontalDragGestures( - onHorizontalDrag = { change, dragAmount -> - val target = (offsetX.value + dragAmount).coerceIn(minOffset, maxQueueOffset) - if (target != offsetX.value) { - change.consume() + try { + detectHorizontalDragGestures( + onHorizontalDrag = { change, dragAmount -> + val target = (offsetX.value + dragAmount).coerceIn(minOffset, maxQueueOffset) + if (target != offsetX.value) { + change.consume() + coroutineScope.launch { + offsetX.snapTo(target) + } + } + }, + onDragEnd = { + if (offsetX.value == maxOffset) { + onAddToQueue?.invoke(itemVideoId) + } else if (offsetX.value == -maxOffset) { + onSwipeToDelete?.invoke(itemVideoId) + } coroutineScope.launch { - offsetX.snapTo(target) + offsetX.animateTo(0f) } - } - }, - onDragEnd = { - if (offsetX.value == maxOffset) { - onAddToQueue?.invoke(itemVideoId) - } else if (offsetX.value == -maxOffset) { - onSwipeToDelete?.invoke(itemVideoId) - } - coroutineScope.launch { - offsetX.animateTo(0f) - } - }, - onDragCancel = { - coroutineScope.launch { - offsetX.animateTo(0f) - } - }, - ) + }, + onDragCancel = { + coroutineScope.launch { + offsetX.animateTo(0f) + } + }, + ) + } finally { + // A key change (the row starts playing, selection starts) cancels + // this detector mid-drag, and cancelling it does not call + // onDragCancel — without this the row would stay pushed aside. + coroutineScope.launch { + offsetX.animateTo(0f) + } + } } }.onGloballyPositioned { coordinates -> with(density) { From 683957fc30f16b6d1cd526975360e889142e59d0 Mon Sep 17 00:00:00 2001 From: Cuong-Tran <16017808+cuong-tran@users.noreply.github.com> Date: Mon, 19 Oct 2026 12:01:58 +0700 Subject: [PATCH 05/29] fix(rtl): make a swiped song row follow the finger in right-to-left languages, where offset mirrors but drag amounts stay physical, so a swipe toward the end reveals Add to queue and one toward the start reveals delete, as in left-to-right --- .../maxrave/simpmusic/ui/component/FullWidthItems.kt | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/FullWidthItems.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/FullWidthItems.kt index 082654abb3..e2ff8300f8 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/FullWidthItems.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/FullWidthItems.kt @@ -54,7 +54,9 @@ import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp import coil3.compose.AsyncImage import coil3.compose.LocalPlatformContext @@ -206,6 +208,9 @@ fun SongFullWidthItems( val itemVideoId = track?.videoId ?: songEntity?.videoId ?: "" val canSwipeToQueue = !isPlaying && onAddToQueue != null val canSwipeToDelete = onSwipeToDelete != null + // offset {} mirrors in a right-to-left layout while drag amounts stay physical, so the drag + // is flipped there too — otherwise the row moves against the finger. + val dragDirection = if (LocalLayoutDirection.current == LayoutDirection.Rtl) -1f else 1f Box( modifier = modifier @@ -230,7 +235,7 @@ fun SongFullWidthItems( // Keyed on selectionMode so the swipe detector is torn down when selection // starts — keyed on Unit it would keep running with the stale flag captured. // The same goes for the two directions the row may move in. - .pointerInput(selectionMode, canSwipeToQueue, canSwipeToDelete) { + .pointerInput(selectionMode, canSwipeToQueue, canSwipeToDelete, dragDirection) { if (!selectionMode && (canSwipeToQueue || canSwipeToDelete)) { // A direction with nothing behind it stays shut, so the row cannot be // dragged out to reveal an empty slot. @@ -239,7 +244,9 @@ fun SongFullWidthItems( try { detectHorizontalDragGestures( onHorizontalDrag = { change, dragAmount -> - val target = (offsetX.value + dragAmount).coerceIn(minOffset, maxQueueOffset) + val target = + (offsetX.value + dragAmount * dragDirection) + .coerceIn(minOffset, maxQueueOffset) if (target != offsetX.value) { change.consume() coroutineScope.launch { From f8d8715c4ee1a3be3acea49133fa2a0d6fc6d0bc Mon Sep 17 00:00:00 2001 From: Cuong-Tran <16017808+cuong-tran@users.noreply.github.com> Date: Mon, 19 Oct 2026 14:29:56 +0700 Subject: [PATCH 06/29] fix(downloads): name the song menu's download row by what a tap does Downloaded becomes Remove download, and Downloading becomes Cancel download. The icon already shows the state, and a label that only repeated it hid the one place a single download could be removed (#2176). --- .../commonMain/composeResources/values/strings.xml | 1 + .../simpmusic/ui/component/ModalBottomSheet.kt | 11 ++++++++--- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 5151b85236..14385738fb 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -129,6 +129,7 @@ Cached Remove from cache Remove download + Cancel download Thumbnail Cache Backup Backup Your Data diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/ModalBottomSheet.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/ModalBottomSheet.kt index 51c3bc9760..eaaf9c05b9 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/ModalBottomSheet.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/ModalBottomSheet.kt @@ -211,6 +211,7 @@ import simpmusic.composeapp.generated.resources.bitrate import simpmusic.composeapp.generated.resources.bpm import simpmusic.composeapp.generated.resources.can_not_be_empty import simpmusic.composeapp.generated.resources.cancel +import simpmusic.composeapp.generated.resources.cancel_download import simpmusic.composeapp.generated.resources.crop_cover import simpmusic.composeapp.generated.resources.codec import simpmusic.composeapp.generated.resources.copied_to_clipboard @@ -266,6 +267,7 @@ import simpmusic.composeapp.generated.resources.plays import simpmusic.composeapp.generated.resources.processing import simpmusic.composeapp.generated.resources.queue import simpmusic.composeapp.generated.resources.radio +import simpmusic.composeapp.generated.resources.remove_download import simpmusic.composeapp.generated.resources.remove_from_cache import simpmusic.composeapp.generated.resources.save import simpmusic.composeapp.generated.resources.save_to_local_playlist @@ -1765,15 +1767,18 @@ fun NowPlayingBottomSheet( } else { Color.Unspecified }, + // The row names what a tap does rather than the state: the icon already + // shows the state, and a label that only repeated it hid the one place a + // single download could be removed (#2176). text = if (downloadBlockedAsLive) { Res.string.download_disabled_live } else { when (uiState.songUIState.downloadState) { DownloadState.STATE_NOT_DOWNLOADED -> Res.string.download - DownloadState.STATE_DOWNLOADING -> Res.string.downloading - DownloadState.STATE_DOWNLOADED -> Res.string.downloaded - DownloadState.STATE_PREPARING -> Res.string.downloading + DownloadState.STATE_DOWNLOADING -> Res.string.cancel_download + DownloadState.STATE_DOWNLOADED -> Res.string.remove_download + DownloadState.STATE_PREPARING -> Res.string.cancel_download else -> Res.string.download } }, From 15266ec9cf21b28ded58c86c980ef04372b028a7 Mon Sep 17 00:00:00 2001 From: maxrave-dev Date: Mon, 2 Nov 2026 14:43:05 +0700 Subject: [PATCH 07/29] chore(core): bump for the FOSS build keeping its foreground service past a precached track change --- core | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core b/core index 1830a60416..9df595d817 160000 --- a/core +++ b/core @@ -1 +1 @@ -Subproject commit 1830a60416dcac82d402fcedcc92c09fde94d567 +Subproject commit 9df595d817a40f503e892a0d126dcdb97a68f93e From b6dd3eb2c35d876f34a69cabf7f8eed0f2824939 Mon Sep 17 00:00:00 2001 From: maxrave-dev Date: Mon, 2 Nov 2026 15:06:31 +0700 Subject: [PATCH 08/29] fix(search): keep the focus clear only on the suggestion tap, the one place the keyboard is open --- .../com/maxrave/simpmusic/ui/screen/other/SearchScreen.kt | 2 -- 1 file changed, 2 deletions(-) diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/SearchScreen.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/SearchScreen.kt index a5aea297bf..65bf47ee9b 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/SearchScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/SearchScreen.kt @@ -778,7 +778,6 @@ fun SearchScreen( onMoreClick(result.toTrack().toSongEntity()) }, onClickListener = { - focusManager.clearFocus() val firstTrack = result.toTrack() searchViewModel.setQueueData( QueueData.Data( @@ -818,7 +817,6 @@ fun SearchScreen( onMoreClick(result.toTrack().toSongEntity()) }, onClickListener = { - focusManager.clearFocus() val firstTrack = result.toTrack() searchViewModel.setQueueData( QueueData.Data( From 53cb9ccbe038ba0874546c0a5b72a6cc5c8a7025 Mon Sep 17 00:00:00 2001 From: maxrave-dev Date: Mon, 2 Nov 2026 15:41:27 +0700 Subject: [PATCH 09/29] chore(core): bump for removed and cancelled downloads going back to not downloaded right away --- core | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core b/core index 9df595d817..344d6149d3 160000 --- a/core +++ b/core @@ -1 +1 @@ -Subproject commit 9df595d817a40f503e892a0d126dcdb97a68f93e +Subproject commit 344d6149d38cab5791dc0164958709ac44e7e298 From 5e0cdbc876497f97f69d937e4fece2bd0e31f5d6 Mon Sep 17 00:00:00 2001 From: maxrave-dev Date: Mon, 2 Nov 2026 17:23:12 +0700 Subject: [PATCH 10/29] refactor(downloads): drop the swipe-to-remove and draw Remove download in the sheet's default colour --- .../simpmusic/ui/component/FullWidthItems.kt | 98 +++++-------------- .../library/LibraryDynamicPlaylistScreen.kt | 7 -- .../LibraryDynamicPlaylistViewModel.kt | 4 +- 3 files changed, 24 insertions(+), 85 deletions(-) diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/FullWidthItems.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/FullWidthItems.kt index e2ff8300f8..e0d3c4b071 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/FullWidthItems.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/FullWidthItems.kt @@ -54,9 +54,7 @@ import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.platform.LocalDensity -import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.unit.IntOffset -import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp import coil3.compose.AsyncImage import coil3.compose.LocalPlatformContext @@ -82,7 +80,6 @@ import com.maxrave.domain.utils.isLive import com.maxrave.domain.utils.toListName import com.maxrave.simpmusic.ui.icon.Add import com.maxrave.simpmusic.ui.icon.Check -import com.maxrave.simpmusic.ui.icon.Delete import com.maxrave.simpmusic.ui.icon.DownloadForOffline import com.maxrave.simpmusic.ui.icon.DragHandle import com.maxrave.simpmusic.ui.icon.MoreVert @@ -105,7 +102,6 @@ import simpmusic.composeapp.generated.resources.play_next import simpmusic.composeapp.generated.resources.playlist import simpmusic.composeapp.generated.resources.podcasts import simpmusic.composeapp.generated.resources.radio -import simpmusic.composeapp.generated.resources.remove_download import simpmusic.composeapp.generated.resources.you import kotlin.math.roundToInt @@ -115,9 +111,6 @@ import kotlin.math.roundToInt * Multi-selection is opt-in per screen: pass [onLongClick] to let a long press start it, then * drive [selectionMode] and [isSelected] from the screen's * [com.maxrave.simpmusic.ui.component.selection.SongSelectionState]. - * - * Swipes are opt-in too: [onAddToQueue] answers a swipe toward the end, [onSwipeToDelete] one - * toward the start. Both fire only once the row is dragged all the way. */ @OptIn(ExperimentalFoundationApi::class) @Composable @@ -130,7 +123,6 @@ fun SongFullWidthItems( onMoreClickListener: ((videoId: String) -> Unit)? = null, onClickListener: ((videoId: String) -> Unit)? = null, onAddToQueue: ((videoId: String) -> Unit)? = null, - onSwipeToDelete: ((videoId: String) -> Unit)? = null, selectionMode: Boolean = false, isSelected: Boolean = false, onLongClick: ((videoId: String) -> Unit)? = null, @@ -184,33 +176,7 @@ fun SongFullWidthItems( } } } - Crossfade( - offsetX.value <= -maxOffset / 2, - modifier = Modifier.align(Alignment.CenterEnd), - ) { shouldShowDelete -> - if (shouldShowDelete) { - Box( - modifier = - Modifier - .height(heightDp) - .aspectRatio(1f) - .padding(end = 15.dp), - contentAlignment = Alignment.Center, - ) { - Icon( - tint = Color.Red, - imageVector = SimpIcons.Delete, - contentDescription = stringResource(Res.string.remove_download), - ) - } - } - } val itemVideoId = track?.videoId ?: songEntity?.videoId ?: "" - val canSwipeToQueue = !isPlaying && onAddToQueue != null - val canSwipeToDelete = onSwipeToDelete != null - // offset {} mirrors in a right-to-left layout while drag amounts stay physical, so the drag - // is flipped there too — otherwise the row moves against the finger. - val dragDirection = if (LocalLayoutDirection.current == LayoutDirection.Rtl) -1f else 1f Box( modifier = modifier @@ -234,50 +200,30 @@ fun SongFullWidthItems( ).animateContentSize() // Keyed on selectionMode so the swipe detector is torn down when selection // starts — keyed on Unit it would keep running with the stale flag captured. - // The same goes for the two directions the row may move in. - .pointerInput(selectionMode, canSwipeToQueue, canSwipeToDelete, dragDirection) { - if (!selectionMode && (canSwipeToQueue || canSwipeToDelete)) { - // A direction with nothing behind it stays shut, so the row cannot be - // dragged out to reveal an empty slot. - val minOffset = if (canSwipeToDelete) -maxOffset else 0f - val maxQueueOffset = if (canSwipeToQueue) maxOffset else 0f - try { - detectHorizontalDragGestures( - onHorizontalDrag = { change, dragAmount -> - val target = - (offsetX.value + dragAmount * dragDirection) - .coerceIn(minOffset, maxQueueOffset) - if (target != offsetX.value) { - change.consume() - coroutineScope.launch { - offsetX.snapTo(target) - } - } - }, - onDragEnd = { - if (offsetX.value == maxOffset) { - onAddToQueue?.invoke(itemVideoId) - } else if (offsetX.value == -maxOffset) { - onSwipeToDelete?.invoke(itemVideoId) - } - coroutineScope.launch { - offsetX.animateTo(0f) - } - }, - onDragCancel = { + .pointerInput(selectionMode) { + if (!isPlaying && onAddToQueue != null && !selectionMode) { + detectHorizontalDragGestures( + onHorizontalDrag = { change, dragAmount -> + if (offsetX.value + dragAmount > 0) { + change.consume() coroutineScope.launch { - offsetX.animateTo(0f) + offsetX.snapTo( + (offsetX.value + dragAmount).coerceAtMost(maxOffset), + ) } - }, - ) - } finally { - // A key change (the row starts playing, selection starts) cancels - // this detector mid-drag, and cancelling it does not call - // onDragCancel — without this the row would stay pushed aside. - coroutineScope.launch { - offsetX.animateTo(0f) - } - } + } + }, + onDragEnd = { + if (offsetX.value == maxOffset) { + onAddToQueue( + track?.videoId ?: songEntity?.videoId ?: "", + ) + } + coroutineScope.launch { + offsetX.animateTo(0f) + } + }, + ) } }.onGloballyPositioned { coordinates -> with(density) { diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/library/LibraryDynamicPlaylistScreen.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/library/LibraryDynamicPlaylistScreen.kt index a7adf781a4..b572f01306 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/library/LibraryDynamicPlaylistScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/library/LibraryDynamicPlaylistScreen.kt @@ -452,12 +452,6 @@ fun LibraryDynamicPlaylistScreen( arrayListOf(song.toTrack()), ) }, - onSwipeToDelete = - if (type == LibraryDynamicPlaylistType.Downloaded) { - { viewModel.removeDownloads(listOf(it)) } - } else { - null - }, selectionMode = selectionState.isActive, isSelected = selectionState.isSelected(song.videoId), onLongClick = { selectionState.start(it) }, @@ -505,7 +499,6 @@ fun LibraryDynamicPlaylistScreen( SongSelectionAction( icon = SimpIcons.Delete, label = removeDownloadLabel, - tint = Color.Red, ) { viewModel.removeDownloads(selectedIds) selectionState.exit() diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/LibraryDynamicPlaylistViewModel.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/LibraryDynamicPlaylistViewModel.kt index 3724b78827..5fc77ecf2e 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/LibraryDynamicPlaylistViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/LibraryDynamicPlaylistViewModel.kt @@ -211,8 +211,8 @@ class LibraryDynamicPlaylistViewModel( } /** - * Removes the downloads behind the Downloaded list's swipe and its multi-select action, the - * same way the song menu's Download toggle does. + * Removes the downloads behind the Downloaded list's multi-select action, the same way the + * song menu's Download toggle does. * * The rows leave the list first: [SongRepository.getDownloadedSongs] is read once rather than * observed, so nothing else would take them off the screen. From 0920c20563ca45d9c600c0fec9ce41fb5b42dbd5 Mon Sep 17 00:00:00 2001 From: maxrave-dev Date: Mon, 2 Nov 2026 22:05:31 +0700 Subject: [PATCH 11/29] fix(desktop): let macOS drag the window across displays natively and stop the title bar crashing on a null pointer position --- CLAUDE.md | 3 +- composeApp/build.gradle.kts | 2 + .../simpmusic/ui/component/CustomTitleBar.kt | 11 ++- .../simpmusic/ui/component/MacWindowDrag.kt | 86 +++++++++++++++++++ .../ui/mini_player/MiniPlayerRoot.kt | 13 ++- .../ui/mini_player/MiniPlayerWindow.kt | 1 + 6 files changed, 111 insertions(+), 5 deletions(-) create mode 100644 composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/ui/component/MacWindowDrag.kt diff --git a/CLAUDE.md b/CLAUDE.md index 434fd3092f..f8a482ebff 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1109,6 +1109,7 @@ if (getPlatform() == Platform.Android) { - Left out of the port: Metrolist's 5-minute signature cache (a new recording never repeats a signature) and its 1-second request limiter (the sheet cannot ask more than once per 12 s recording), plus its history table and widget. Its Quick Settings tile became a shortcut (below). - The pass runs in the sheet's composition: closing the sheet cancels it and stops the recording within one buffer, and a rotation starts listening again. `RECORD_AUDIO` is asked from the sheet (Open settings after a permanent denial, the Login Sync camera flow; `openAppSettings()` is now `internal` for it), and the manifest pairs it with `uses-feature android.hardware.microphone required="false"`, since the permission alone implies a required microphone. - **Quick Settings tile (2026-10-31)**: `RecognitionTileService` (androidApp `service/`) is a shortcut into the app, not a background recognizer. It opens `MainActivity` at `simpmusic://recognize`; the router calls `requestSongRecognition(true)` and navigates to Search with `launchSingleTop` (a Search already on top takes the request; a second copy would race the one leaving for it), and `SearchScreen` opens the sheet and clears the request, the `libraryTabRequest` pattern. `isAppLinkAvailable` keeps `recognize` Android-only. From Android 14 the tile must call `startActivityAndCollapse(PendingIntent)`, because the `Intent` overload throws `UnsupportedOperationException`; lint (`StartActivityAndCollapseDeprecated`) flags the pre-14 branch whatever the version guard, hence its `@Suppress`. The label and icon are Android resources (`widget_strings.xml`, `rounded_graphic_eq_24.xml`, path copied from `GraphicEq.kt`), since the tile editor reads them before any code runs. Metrolist's tile records in the background instead, through a transparent activity and a microphone foreground service: such a service may start only while an activity is visible, and tiles are not exempt. The owner chose the shortcut. +- **macOS window drags go through the Window Server (2026-11-02)**: the custom title bar and the mini player moved their window from code on every drag event (`window.setLocation`, `windowState.position`), so macOS drew it on one display and then jumped it whole to the other, while a native app's window is drawn on both displays as it crosses. `MacWindowDrag.start(window)` (`ui/component/MacWindowDrag.kt`, JNA, so composeApp now declares `libs.jna`) hands the drag to macOS with `-[NSWindow performWindowDragWithEvent:]` from the first drag event, which per Apple also lets the window take part in Spaces. The NSWindow comes from `ComposeWindow.windowHandle`. The call is posted with `dispatch_async_f` onto the main queue, never sync: AppKit can be waiting on the AWT thread while it delivers mouse events, so a sync hop can leave both waiting on each other. It runs only while `[NSApp currentEvent]` is still a left-button down or drag, since the button may be up by then. Apple warns that a mouse-up may not be sent afterwards; Compose's `SyntheticEventSender.sendMissingReleases` releases the pointer on the next mouse event, so the gesture still ends. The one JNA callback lives for the whole process, because JNA frees a callback's native stub once its object is collected. A maximized main window keeps the restore-then-follow path; off macOS, or when the natives fail to load, `start()` returns false and both windows move from code as before. Compose's own `WindowDraggableArea` does not help: it uses JBR's native move only on Linux. ## 🔄 CLAUDE.md Auto-Update Rule (MANDATORY) @@ -1134,6 +1135,6 @@ After completing any of the following types of changes, the AI agent **MUST** up *This document helps AI Agents quickly understand the SimpMusic project. Update regularly when there are major changes to architecture or structure.* -**Last updated**: 2026-10-31 +**Last updated**: 2026-11-02 **Project version**: Check latest release on GitHub **Maintained by**: maxrave-dev and contributors diff --git a/composeApp/build.gradle.kts b/composeApp/build.gradle.kts index 7f53fd9f0e..00ac31ccf7 100644 --- a/composeApp/build.gradle.kts +++ b/composeApp/build.gradle.kts @@ -198,6 +198,8 @@ kotlin { implementation(libs.native.tray) implementation(libs.nucleus.core.runtime) implementation(projects.mediaJvmUi) + // macOS: hand window drags to the Window Server (ui/component/MacWindowDrag.kt) + implementation(libs.jna) // Login sync QR code implementation(libs.zxing.core) } diff --git a/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/ui/component/CustomTitleBar.kt b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/ui/component/CustomTitleBar.kt index ae5ad4e4cc..f66f2bb789 100644 --- a/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/ui/component/CustomTitleBar.kt +++ b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/ui/component/CustomTitleBar.kt @@ -96,15 +96,22 @@ fun CustomTitleBar( }, ) }.pointerInput(Unit) { + // True while macOS itself moves the window for the current drag (MacWindowDrag) + var nativeDrag = false detectDragGestures( onDragStart = { - val mouseLocation = MouseInfo.getPointerInfo().location + // A maximized window keeps the restore-then-follow path below. + nativeDrag = windowState.placement == WindowPlacement.Floating && MacWindowDrag.start(window) + if (nativeDrag) return@detectDragGestures + // Null while the pointer is on no screen's bounds; skip that event, as Compose's WindowDraggableArea does. + val mouseLocation = MouseInfo.getPointerInfo()?.location ?: return@detectDragGestures dragStartX = mouseLocation.x - window.x dragStartY = mouseLocation.y - window.y }, onDrag = { change, _ -> change.consume() - val mouseLocation = MouseInfo.getPointerInfo().location + if (nativeDrag) return@detectDragGestures + val mouseLocation = MouseInfo.getPointerInfo()?.location ?: return@detectDragGestures // If maximized, restore before moving if (windowState.placement == WindowPlacement.Maximized) { windowState.placement = WindowPlacement.Floating diff --git a/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/ui/component/MacWindowDrag.kt b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/ui/component/MacWindowDrag.kt new file mode 100644 index 0000000000..9398b8678d --- /dev/null +++ b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/ui/component/MacWindowDrag.kt @@ -0,0 +1,86 @@ +package com.maxrave.simpmusic.ui.component + +import androidx.compose.ui.awt.ComposeWindow +import com.maxrave.logger.Logger +import com.sun.jna.Callback +import com.sun.jna.NativeLibrary +import com.sun.jna.Pointer +import java.awt.Window + +/** + * Hands a window drag to macOS with `-[NSWindow performWindowDragWithEvent:]`, so the Window Server + * moves the window the way it moves every other Mac app: drawn on both displays while it crosses + * between them, and taking part in Spaces and Mission Control. A window moved from code with + * `setLocation` stays drawn on one display and then jumps whole to the other. + */ +internal object MacWindowDrag { + private const val TAG = "MacWindowDrag" + private const val LEFT_MOUSE_DOWN = 1L // NSEventTypeLeftMouseDown + private const val LEFT_MOUSE_DRAGGED = 6L // NSEventTypeLeftMouseDragged + + private class Natives { + private val objc = NativeLibrary.getInstance("objc") + private val system = NativeLibrary.getInstance("System") + private val registerSelector = objc.getFunction("sel_registerName") + val msgSend = objc.getFunction("objc_msgSend") + val dispatchAsync = system.getFunction("dispatch_async_f") + + // dispatch_get_main_queue() is &_dispatch_main_q, so the symbol's address is the queue. + val mainQueue: Pointer = system.getGlobalVariableAddress("_dispatch_main_q") + val appClass: Pointer = objc.getFunction("objc_getClass").invokePointer(arrayOf("NSApplication")) + val sharedApplication = sel("sharedApplication") + val currentEvent = sel("currentEvent") + val type = sel("type") + val performWindowDrag = sel("performWindowDragWithEvent:") + + private fun sel(name: String): Pointer = registerSelector.invokePointer(arrayOf(name)) + } + + private val natives: Natives? by lazy { + if (!System.getProperty("os.name", "").contains("Mac", ignoreCase = true)) return@lazy null + runCatching { Natives() } + .onFailure { Logger.w(TAG, "Native window drag unavailable, windows move from code: $it") } + .getOrNull() + } + + // Runs on the AppKit main thread, with the NSWindow as context. One instance for the whole + // process: JNA frees a callback's native stub once its object is garbage collected. + private val work = + object : MacMainQueueWork { + override fun invoke(context: Pointer?) { + val n = natives ?: return + runCatching { + val app = n.msgSend.invokePointer(arrayOf(n.appClass, n.sharedApplication)) + val event = n.msgSend.invokePointer(arrayOf(app, n.currentEvent)) ?: return + // The button may be up by the time this runs; only a held left button starts a drag. + val type = n.msgSend.invokeLong(arrayOf(event, n.type)) + if (type == LEFT_MOUSE_DOWN || type == LEFT_MOUSE_DRAGGED) { + n.msgSend.invokeVoid(arrayOf(context, n.performWindowDrag, event)) + } + }.onFailure { Logger.w(TAG, "performWindowDragWithEvent failed: $it") } + } + } + + /** + * Starts a native drag of [window] for the drag gesture in progress. Returns false off macOS or + * when the call cannot be made, and the caller then moves the window itself. + * + * Apple's docs warn that a mouse-up may not be sent after this; Compose's SyntheticEventSender + * synthesizes the missing release from the next mouse event, so the gesture still ends. + */ + fun start(window: Window): Boolean { + val n = natives ?: return false + val handle = (window as? ComposeWindow)?.windowHandle ?: return false + if (handle == 0L) return false + // Async on purpose: AppKit can be waiting on the AWT thread while it delivers mouse events, + // so waiting on AppKit from here could leave the two threads waiting on each other. + return runCatching { + n.dispatchAsync.invokeVoid(arrayOf(n.mainQueue, Pointer(handle), work)) + }.isSuccess + } +} + +/** `dispatch_function_t`. Top-level, like core/data's `DispatchWork`, so JNA can reach its method. */ +internal interface MacMainQueueWork : Callback { + fun invoke(context: Pointer?) +} diff --git a/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/ui/mini_player/MiniPlayerRoot.kt b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/ui/mini_player/MiniPlayerRoot.kt index 365f7787f3..800bf0937e 100644 --- a/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/ui/mini_player/MiniPlayerRoot.kt +++ b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/ui/mini_player/MiniPlayerRoot.kt @@ -28,11 +28,13 @@ import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.unit.dp import androidx.compose.ui.window.WindowState import androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.maxrave.simpmusic.ui.component.MacWindowDrag import com.maxrave.simpmusic.ui.icon.Close import com.maxrave.simpmusic.ui.icon.SimpIcons import com.maxrave.simpmusic.viewModel.SharedViewModel import java.awt.Cursor import java.awt.MouseInfo +import java.awt.Window /** * Root composable for the mini player window content. @@ -49,6 +51,7 @@ fun MiniPlayerRoot( sharedViewModel: SharedViewModel, onClose: () -> Unit, windowState: WindowState, + window: Window, ) { val nowPlayingData by sharedViewModel.nowPlayingScreenData.collectAsStateWithLifecycle() val controllerState by sharedViewModel.controllerState.collectAsStateWithLifecycle() @@ -149,10 +152,15 @@ fun MiniPlayerRoot( .fillMaxWidth(0.5f) .height(28.dp) .pointerInput(Unit) { + // True while macOS itself moves the window for the current drag (MacWindowDrag) + var nativeDrag = false detectDragGestures( onDragStart = { + nativeDrag = MacWindowDrag.start(window) + if (nativeDrag) return@detectDragGestures // Store initial mouse and window positions - val mousePos = MouseInfo.getPointerInfo().location + // Null while the pointer is on no screen's bounds; skip that event, as Compose's WindowDraggableArea does. + val mousePos = MouseInfo.getPointerInfo()?.location ?: return@detectDragGestures dragStartMousePos = Pair(mousePos.x, mousePos.y) val currentPos = windowState.position if (currentPos is androidx.compose.ui.window.WindowPosition.Absolute) { @@ -161,10 +169,11 @@ fun MiniPlayerRoot( }, onDrag = { change, _ -> change.consume() + if (nativeDrag) return@detectDragGestures val startMouse = dragStartMousePos val startWindow = dragStartWindowPos if (startMouse != null && startWindow != null) { - val currentMousePos = MouseInfo.getPointerInfo().location + val currentMousePos = MouseInfo.getPointerInfo()?.location ?: return@detectDragGestures val deltaX = currentMousePos.x - startMouse.first val deltaY = currentMousePos.y - startMouse.second windowState.position = diff --git a/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/ui/mini_player/MiniPlayerWindow.kt b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/ui/mini_player/MiniPlayerWindow.kt index edd3eac4cd..3fe139535c 100644 --- a/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/ui/mini_player/MiniPlayerWindow.kt +++ b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/ui/mini_player/MiniPlayerWindow.kt @@ -128,6 +128,7 @@ fun MiniPlayerWindow( sharedViewModel = sharedViewModel, onClose = onCloseRequest, windowState = windowState, + window = window, ) } } \ No newline at end of file From 1b7297485966f98bb66dfd9c3a7f83c59ea866aa Mon Sep 17 00:00:00 2001 From: maxrave-dev Date: Tue, 3 Nov 2026 17:15:28 +0700 Subject: [PATCH 12/29] feat(discord): log in to Discord over OAuth on Full builds and keep kizzy for FOSS --- .github/workflows/android-release.yml | 6 + .github/workflows/android.yml | 4 + .github/workflows/desktop-package.yml | 2 + CLAUDE.md | 18 +- .../maxrave/simpmusic/SimpMusicApplication.kt | 3 + composeApp/build.gradle.kts | 10 + .../composeResources/values/strings.xml | 4 + .../kotlin/com/maxrave/simpmusic/App.kt | 7 + .../maxrave/simpmusic/di/ViewModelModule.kt | 3 + .../ui/navigation/graph/LoginScreenGraph.kt | 25 +- .../screen/login/DiscordOAuthLoginScreen.kt | 245 ++++++++++++++++++ .../ui/screen/login/LastfmLoginScreen.kt | 2 +- .../simpmusic/viewModel/LogInViewModel.kt | 57 ++++ .../simpmusic/viewModel/SettingsViewModel.kt | 8 +- .../simpmusic/viewModel/SharedViewModel.kt | 17 ++ .../com/maxrave/simpmusic/DesktopApp.kt | 4 + .../simpmusic/DesktopDeepLinkHandler.kt | 4 + core | 2 +- settings.gradle.kts | 2 + 19 files changed, 407 insertions(+), 16 deletions(-) create mode 100644 composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/login/DiscordOAuthLoginScreen.kt diff --git a/.github/workflows/android-release.yml b/.github/workflows/android-release.yml index 415af555ee..6bfded2194 100644 --- a/.github/workflows/android-release.yml +++ b/.github/workflows/android-release.yml @@ -47,9 +47,11 @@ jobs: env: LASTFM_API_KEY: ${{ secrets.LASTFM_API_KEY }} LASTFM_SECRET: ${{ secrets.LASTFM_SECRET }} + DISCORD_CLIENT_ID: ${{ secrets.DISCORD_CLIENT_ID }} run: | echo "LASTFM_API_KEY=${{ secrets.LASTFM_API_KEY }}" >> ./local.properties echo "LASTFM_SECRET=${{ secrets.LASTFM_SECRET }}" >> ./local.properties + echo "DISCORD_CLIENT_ID=${{ secrets.DISCORD_CLIENT_ID }}" >> ./local.properties - name: Update environment variables env: @@ -107,9 +109,11 @@ jobs: env: LASTFM_API_KEY: ${{ secrets.LASTFM_API_KEY }} LASTFM_SECRET: ${{ secrets.LASTFM_SECRET }} + DISCORD_CLIENT_ID: ${{ secrets.DISCORD_CLIENT_ID }} run: | echo "LASTFM_API_KEY=${{ secrets.LASTFM_API_KEY }}" >> ./local.properties echo "LASTFM_SECRET=${{ secrets.LASTFM_SECRET }}" >> ./local.properties + echo "DISCORD_CLIENT_ID=${{ secrets.DISCORD_CLIENT_ID }}" >> ./local.properties - name: Update environment variables env: @@ -220,9 +224,11 @@ jobs: env: LASTFM_API_KEY: ${{ secrets.LASTFM_API_KEY }} LASTFM_SECRET: ${{ secrets.LASTFM_SECRET }} + DISCORD_CLIENT_ID: ${{ secrets.DISCORD_CLIENT_ID }} run: | echo "LASTFM_API_KEY=${{ secrets.LASTFM_API_KEY }}" >> ./local.properties echo "LASTFM_SECRET=${{ secrets.LASTFM_SECRET }}" >> ./local.properties + echo "DISCORD_CLIENT_ID=${{ secrets.DISCORD_CLIENT_ID }}" >> ./local.properties - name: Generate aboutLibraries.json run: ./gradlew exportLibraryDefinitions diff --git a/.github/workflows/android.yml b/.github/workflows/android.yml index 8ff6a18fb0..a5cf3a9b1f 100644 --- a/.github/workflows/android.yml +++ b/.github/workflows/android.yml @@ -53,9 +53,11 @@ jobs: env: LASTFM_API_KEY: ${{ secrets.LASTFM_API_KEY }} LASTFM_SECRET: ${{ secrets.LASTFM_SECRET }} + DISCORD_CLIENT_ID: ${{ secrets.DISCORD_CLIENT_ID }} run: | echo "LASTFM_API_KEY=${{ secrets.LASTFM_API_KEY }}" >> ./local.properties echo "LASTFM_SECRET=${{ secrets.LASTFM_SECRET }}" >> ./local.properties + echo "DISCORD_CLIENT_ID=${{ secrets.DISCORD_CLIENT_ID }}" >> ./local.properties - name: Generate aboutLibraries.json run: ./gradlew exportLibraryDefinitions @@ -123,9 +125,11 @@ jobs: env: LASTFM_API_KEY: ${{ secrets.LASTFM_API_KEY }} LASTFM_SECRET: ${{ secrets.LASTFM_SECRET }} + DISCORD_CLIENT_ID: ${{ secrets.DISCORD_CLIENT_ID }} run: | echo "LASTFM_API_KEY=${{ secrets.LASTFM_API_KEY }}" >> ./local.properties echo "LASTFM_SECRET=${{ secrets.LASTFM_SECRET }}" >> ./local.properties + echo "DISCORD_CLIENT_ID=${{ secrets.DISCORD_CLIENT_ID }}" >> ./local.properties - name: Generate aboutLibraries.json run: ./gradlew exportLibraryDefinitions diff --git a/.github/workflows/desktop-package.yml b/.github/workflows/desktop-package.yml index 84e843c05e..93b10ef5cd 100644 --- a/.github/workflows/desktop-package.yml +++ b/.github/workflows/desktop-package.yml @@ -77,9 +77,11 @@ jobs: env: LASTFM_API_KEY: ${{ secrets.LASTFM_API_KEY }} LASTFM_SECRET: ${{ secrets.LASTFM_SECRET }} + DISCORD_CLIENT_ID: ${{ secrets.DISCORD_CLIENT_ID }} run: | echo "LASTFM_API_KEY=${{ secrets.LASTFM_API_KEY }}" >> ./local.properties echo "LASTFM_SECRET=${{ secrets.LASTFM_SECRET }}" >> ./local.properties + echo "DISCORD_CLIENT_ID=${{ secrets.DISCORD_CLIENT_ID }}" >> ./local.properties - name: Generate aboutLibraries.json run: ./gradlew exportLibraryDefinitions diff --git a/CLAUDE.md b/CLAUDE.md index f8a482ebff..e3b9dacb1b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -111,7 +111,8 @@ Service modules: - **lyricsService/**: Lyrics fetching (LRCLIB, SimpMusic Lyrics, BetterLyrics) - **listenTogether/**: shared listening rooms, wire-compatible with Metrolist (`MetrolistGroup/metroproto`) - **loginSync/**: the QR-paired transport that moves sign-ins from the Android app to the Desktop app (Ktor client on the phone, one-shot Ktor CIO server on the Desktop, AES-256-GCM). Android + JVM targets only; carries opaque bytes — the data layer decides what they mean -- **kizzy/**: Discord Rich Presence +- **kizzy/**: Discord Rich Presence for FOSS builds (the user's own token, from a WebView login on Android or pasted on Desktop). Left untouched by the OAuth work below +- **discord/**: Discord Rich Presence over OAuth for Full builds (package `org.simpmusic.discord`): PKCE login, a Ktor gateway client that identifies with a Bearer token, and the presence itself. Used instead of kizzy whenever the build carries a Discord application id - **ktorExt/**: Ktor extensions for networking #### 4. **crashlytics/** & **crashlytics-empty/** @@ -232,7 +233,7 @@ Before implementing code, researching code, or answering technical questions, th **This workflow does NOT apply to**: Simple bug fixes in existing code, minor refactoring, or tasks using libraries already well-established in the project. ### Verification After Code Changes -- **Do NOT build the app** to verify code changes. Instead, use **JetBrains MCP** tools (`get_file_problems`, `getDiagnostics`) to check for compile errors and warnings in real-time. +- **Do NOT build the app** to verify code changes. - Only run Gradle build when explicitly requested by the user or for final release verification. ### Testing @@ -797,7 +798,7 @@ if (getPlatform() == Platform.Android) { - **lavfi path escaping was measured, not reasoned.** Two parsers sit under mpv — `av_get_token` (filtergraph) then `av_opt_set_from_string` (the filter's options) — and each strips one backslash layer, so inside an `amovie` filename `:` and `=` need `\\`, `'` needs `\\\`, `[ ] , ;` need `\`, spaces nothing, and backslashes become `/` first. **One backslash before `:` makes ffmpeg open a truncated path with NO error**, and every Windows path has a colon. mpv adds no layer of its own. - The IR lives at `~/.simpmusic/reverb/-v.wav` (float32, stereo, 48 kHz), written temp-file + atomic rename, and its LENGTH is validated on every use: a WAV truncated mid-data opens fine and silently yields a shorter room. `amovie` opens the file at PARSE time, so a missing file fails the whole `af` write; a null path therefore means "no reverb entry". Tiered fallback in `MpvPlayer.setAudioEffects`: `[echo, reverb]` → `[echo]` (latches the process-wide `reverbFiltersUnavailable`, one warning) → `[]` — never leave a rejected entry behind, or every later equalizer write fails with it. A stereo IR on a mono or 5.1 source is fine: lavfi auto-converts the IR's layout. - **Linux bundle: the whitelist gained `afir,amovie,asplit,amix`** (`scripts/mpv-linux/Dockerfile`), and the rebuilt slice no longer bundles `libglib-2.0.so.0` (the `java.awt.Desktop` cure finally lands). Trap on Apple Silicon: `docker buildx` is absent, so `--platform linux/amd64` is **silently ignored** by the legacy builder and `mpvSetupLinuxCi` produces an arm64 slice whose ELF check (e_type only) passes — pin the amd64 `ubuntu:22.04` base by digest (or install buildx) and check `e_machine == 62`. Built in 8 min under colima (vz + Rosetta); the tarball (16,909,206 B, SHA-256 `6cc64efb…`) replaced the Linux asset on the `abc` release of `simpmusic-files` on 2026-09-02 and is pinned in `mpvNativesChecksums`. An older pinned tarball would make Linux fall back to Delay-only through the tiered drop. - - Verification lives in JVM tests against ffmpeg-generated reference vectors under `core/media/media3/src/test/resources/audio/` (echo bit-exact, convolver < 1e-4). **kotlin-lsp is not a compile gate here**: it has no KMP support and answers "No diagnostics" for a broken `commonMain` file; the JetBrains MCP is the only gate. + - Verification lives in JVM tests against ffmpeg-generated reference vectors under `core/media/media3/src/test/resources/audio/` (echo bit-exact, convolver < 1e-4). **kotlin-lsp is not a compile gate here**: it has no KMP support and answers "No diagnostics" for a broken `commonMain` file. - **Lyrics timing offset (2026-09-12, half of issue #2338)**: one signed `lyrics_offset_ms` in DataStore, default 0, edited by typing a number in Settings → Lyrics. It exists for **Bluetooth**, where the sink buffers and the ear trails the player, so it is a property of the listener's audio path and therefore **global — not per song**. (The other half of #2338, editing lyrics by hand, does need per-song storage and is untouched.) - **Applied at READ time, never to the lyric rows.** Every display picks its line from `position - offset`; nothing is written back into `Lyrics`. That is not a style choice — the state write at `SharedViewModel.kt:1288` is immediately followed by `insertLyrics` (Room cache) and, on the translated branch at `:1248`, by `insertSimpMusicTranslatedLyrics`, which **uploads to the community lyrics database**. Shifting the data instead would bake a personal correction into the cache (compounding on every reload) and push it to everyone. @@ -874,7 +875,7 @@ if (getPlatform() == Platform.Android) { - Now Playing's artwork pager snaps instead of animating when the index moves more than one page — a trim drops it by ~47 without changing the track, and animating that flings the pager through dozens of covers. - **Login sync: sign-ins from phone to desktop over the LAN (2026-09-21)**: Settings → Content gains a row that reads *Send sign-ins to desktop* on Android and *Sign in from your phone* on Desktop. Desktop shows a QR (`simpmusic://login-sync?h=&p=&k=`) and runs a one-shot **Ktor server (CIO engine)** only while that dialog is open — 5 minutes, restarted when the phone connects. Android scans it (CameraX + ZXing), sends a sealed hello, gets the computer's name back sealed under the same key, asks *Trust ()?*, then lets the user tick services and sends only those. Layered like Listen Together: **service** `core/service/loginSync` owns the transport and nothing else — invite/QR, AES-GCM, `LoginSyncClient` (commonMain, `ktorExt`'s engine) and `LoginSyncServer` + `reachableAddresses()` (jvmMain, `ktor-server-cio`); it moves one opaque payload. **domain** holds `LoginSyncHostRepository` (Desktop) and `LoginSyncSenderRepository` (Android) plus `model/loginsync` types. **data** holds what the payload means — `LoginBundle` and `LoginSyncStore` in `commonMain` — and the two impls in `jvmMain` / `androidMain`, each bound by `loadLoginSyncModule()` on its own platform (iOS binds nothing); core/data itself imports no Ktor. **composeApp** holds only `LoginSyncHostViewModel` / `LoginSyncSenderViewModel` and the dialog/sheet. Two repository interfaces rather than one so no platform carries methods it cannot implement; both VMs are declared in the common Koin module, which is safe because Koin resolves a dependency when the VM is created, and each platform only ever creates its own. - - **Only sign-ins travel, by allowlist**: YouTube (every `GoogleAccountEntity` row — each carries its own cookie in `cache` and `netscapeCookie` — plus the current `cookie`/`page_id`/`auth_user`/`data_sync_id`/`logged_in`), Spotify `sp_dc`, the Discord token, the Last.fm session. No settings, no AI keys, no proxy credentials. The picker lists service names only, never account names. + - **Only sign-ins travel, by allowlist**: YouTube (every `GoogleAccountEntity` row — each carries its own cookie in `cache` and `netscapeCookie` — plus the current `cookie`/`page_id`/`auth_user`/`data_sync_id`/`logged_in`), Spotify `sp_dc`, the Last.fm session (Discord was dropped on 2026-11-03: the Desktop, a Full build, logs in to Discord through its own browser, and a FOSS phone's token would not work there). No settings, no AI keys, no proxy credentials. The picker lists service names only, never account names. - **Room before DataStore on restore.** `CommonRepositoryImpl` rewrites `ytdlp-cookie.txt` from the *used* account the moment the DataStore cookie changes, so writing the cookie first writes the previous account's file with no error anywhere. A new `sp_dc` also clears Spotify's personal token, as the logout does. - **The key travels on the screen, never over the network.** Every body is AES-256-GCM (`nonce || ciphertext || tag`) with `simpmusic-login-sync/v1//` as associated data, so a hello cannot be replayed as a login bundle and a request cannot pass as a reply. The name coming back sealed is what proves the machine answering is the one showing the QR. - **composeApp's `commonMain` can use the JDK** (it targets only Android and JVM — `Platform.kt` already calls `System.getProperty`), and the loginSync service targets only Android + JVM for the same reason, so its cipher is plain javax.crypto in commonMain. Its server handlers are suspend functions, so the restore is a plain call. `core/service/loginSync/src/jvmTest` has a real client↔server round trip on 127.0.0.1 — hello, payload, reply, then the spent code refused. `stop()` / `disconnect()` are deliberately NOT suspend: callers are teardown paths whose scope is already being cancelled, so the repository runs them on its own scope, and the server stop is `NonCancellable` so a cancelled caller cannot leave the port open. **Do not go back to JDK `com.sun.net.httpserver`**: with its default executor every handler runs on the dispatcher thread, and `HttpServer.stop()` joins that thread — the first version called it from `onDispose` on the UI thread while a restore was in flight, and the desktop app froze. @@ -1110,6 +1111,13 @@ if (getPlatform() == Platform.Android) { - The pass runs in the sheet's composition: closing the sheet cancels it and stops the recording within one buffer, and a rotation starts listening again. `RECORD_AUDIO` is asked from the sheet (Open settings after a permanent denial, the Login Sync camera flow; `openAppSettings()` is now `internal` for it), and the manifest pairs it with `uses-feature android.hardware.microphone required="false"`, since the permission alone implies a required microphone. - **Quick Settings tile (2026-10-31)**: `RecognitionTileService` (androidApp `service/`) is a shortcut into the app, not a background recognizer. It opens `MainActivity` at `simpmusic://recognize`; the router calls `requestSongRecognition(true)` and navigates to Search with `launchSingleTop` (a Search already on top takes the request; a second copy would race the one leaving for it), and `SearchScreen` opens the sheet and clears the request, the `libraryTabRequest` pattern. `isAppLinkAvailable` keeps `recognize` Android-only. From Android 14 the tile must call `startActivityAndCollapse(PendingIntent)`, because the `Intent` overload throws `UnsupportedOperationException`; lint (`StartActivityAndCollapseDeprecated`) flags the pre-14 branch whatever the version guard, hence its `@Suppress`. The label and icon are Android resources (`widget_strings.xml`, `rounded_graphic_eq_24.xml`, path copied from `GraphicEq.kt`), since the tile editor reads them before any code runs. Metrolist's tile records in the background instead, through a transparent activity and a microphone foreground service: such a service may start only while an activity is visible, and tiles are not exempt. The owner chose the shortcut. - **macOS window drags go through the Window Server (2026-11-02)**: the custom title bar and the mini player moved their window from code on every drag event (`window.setLocation`, `windowState.position`), so macOS drew it on one display and then jumped it whole to the other, while a native app's window is drawn on both displays as it crosses. `MacWindowDrag.start(window)` (`ui/component/MacWindowDrag.kt`, JNA, so composeApp now declares `libs.jna`) hands the drag to macOS with `-[NSWindow performWindowDragWithEvent:]` from the first drag event, which per Apple also lets the window take part in Spaces. The NSWindow comes from `ComposeWindow.windowHandle`. The call is posted with `dispatch_async_f` onto the main queue, never sync: AppKit can be waiting on the AWT thread while it delivers mouse events, so a sync hop can leave both waiting on each other. It runs only while `[NSApp currentEvent]` is still a left-button down or drag, since the button may be up by then. Apple warns that a mouse-up may not be sent afterwards; Compose's `SyntheticEventSender.sendMissingReleases` releases the pointer on the next mouse event, so the gesture still ends. The one JNA callback lives for the whole process, because JNA frees a callback's native stub once its object is collected. A maximized main window keeps the restore-then-follow path; off macOS, or when the natives fail to load, `start()` returns false and both windows move from code as before. Compose's own `WindowDraggableArea` does not help: it uses JBR's native move only on Linux. +- **Discord Rich Presence over OAuth for Full builds (2026-11-03)**: kizzy logs in by reading the user's whole-account token out of a WebView (`localStorage.token`), which Discord's rules on automated user accounts forbid; a Full build now logs in through Discord's own page instead, the way Metrolist has since 2026-06-16 (MetrolistGroup/Metrolist#3874, #3980). FOSS keeps kizzy exactly as it was: the new code is a separate module, `core/service/discord`, and no kizzy file changed. + - **Which path runs is decided by one value, the Discord application id.** `BuildKonfig.discordClientId` comes from `DISCORD_CLIENT_ID` in `local.properties` on Full builds and is empty on FOSS (CI writes it from the `DISCORD_CLIENT_ID` secret next to the Last.fm keys). Startup hands it to `configDiscord()` **before `startKoin`** on both platforms, because `DiscordRepository` is created at start and reads `isDiscordOAuthAvailable()` once. A Full build without the key falls back to kizzy, the same way Last.fm hides itself without its keys. + - The application is SimpMusic's own, and its id is kept out of the repository like the Last.fm keys. The id hardcoded in kizzy's `DiscordRPC.kt`, `1271273225120125040`, belongs to InnerTune — Discord's public `/applications/{id}/rpc` answers with that name — and came in with kizzy in `8a00692`. Developer Portal setup: OAuth2 redirect `simpmusic://discord-auth`, Public Client on, the Social SDK enabled through its Getting Started form (it sits under "Games"), Install Link None, Public Bot off. The Rich Presence art-asset tab is unused: artwork goes through `external-assets`. + - **Login**: authorization code with PKCE as a public client, so no client secret exists anywhere; scopes `openid sdk.social_layer_presence` (the Social SDK's presence set) are sent by the app in the authorize link, nothing is configured for them on the Portal. `DiscordOAuthLoginScreen` (Last.fm's layout, `NumberedStep` now `internal`) opens the browser; Discord redirects to `simpmusic://discord-auth?code=…&state=…`, which Android already routes (the `simpmusic` intent-filter has no host), `DesktopDeepLinkHandler` passes through untouched instead of rewriting it to `simpmusic.org`, and `App.kt` hands to `SharedViewModel.completeDiscordLogin`. The pending verifier and state live in memory only, so a login the process does not survive just fails and is retried; a pasted callback link works like Last.fm's. + - **Gateway**: `DiscordGateway` identifies with `"Bearer "`, `intents = 0` and Metrolist's properties. Discord documents this only for its Social SDK library, so it is a reimplementation — if Discord ever stops accepting it, presence stops; nothing crashes or loops. Close 4004 gets exactly one retry with a force-refreshed token; 4010-4014 stop; after giving up it stays down until `closeRPC()`, so a rejected token cannot recreate #2157. `external-assets` is called with the same Bearer token and kizzy's user agent; Metrolist also sends `X-Super-Properties`, which is not sent here — add it if artwork ever fails to resolve. + - **Session**: three keys (`discord_access_token`, `discord_refresh_token`, `discord_token_expires_at`) in the settings file, so they ride in backups like every other sign-in. Access tokens last about 7 days; `DiscordRepository.accessToken()` refreshes under a mutex when under 10 minutes are left, and an `invalid_grant` on refresh clears the session, which logs the user out and tears the RPC down through `loggedIn`. On a Full build the old `discord_token` is cleared at start: it was a whole-account token this build no longer uses. Log out does not call Discord's revoke endpoint; SimpMusic stays in the user's Authorized Apps until they remove it. + - Both playback handlers now hold a `RichPresenceClient` (`core/data/.../mediaservice/RichPresenceClient.kt`) built by `createRichPresenceClient(discordRepository)`, and run on `richPresenceEnabled && discordRepository.loggedIn`; the rest of the RPC job is unchanged. Login Sync no longer carries Discord. ## 🔄 CLAUDE.md Auto-Update Rule (MANDATORY) @@ -1135,6 +1143,6 @@ After completing any of the following types of changes, the AI agent **MUST** up *This document helps AI Agents quickly understand the SimpMusic project. Update regularly when there are major changes to architecture or structure.* -**Last updated**: 2026-11-02 +**Last updated**: 2026-11-03 **Project version**: Check latest release on GitHub **Maintained by**: maxrave-dev and contributors diff --git a/androidApp/src/main/java/com/maxrave/simpmusic/SimpMusicApplication.kt b/androidApp/src/main/java/com/maxrave/simpmusic/SimpMusicApplication.kt index 06f285a755..00b831b514 100644 --- a/androidApp/src/main/java/com/maxrave/simpmusic/SimpMusicApplication.kt +++ b/androidApp/src/main/java/com/maxrave/simpmusic/SimpMusicApplication.kt @@ -39,6 +39,7 @@ import org.koin.core.context.loadKoinModules import org.koin.core.context.startKoin import org.koin.core.logger.Level import org.simpmusic.crashlytics.configCrashlytics +import org.simpmusic.discord.configDiscord import org.simpmusic.lastfm.configLastfm import java.io.File import java.lang.reflect.Field @@ -58,6 +59,8 @@ class SimpMusicApplication : Logger.enableFileLogging(File(filesDir, "logs").path) configCrashlytics(this, BuildKonfig.sentryDsn) configLastfm(BuildKonfig.lastfmApiKey, BuildKonfig.lastfmSecret) + // Before Koin: DiscordRepository is created at start and reads which login this build uses. + configDiscord(BuildKonfig.discordClientId) startKoin { androidLogger(level = Level.DEBUG) androidContext(this@SimpMusicApplication) diff --git a/composeApp/build.gradle.kts b/composeApp/build.gradle.kts index 00ac31ccf7..6da9993d56 100644 --- a/composeApp/build.gradle.kts +++ b/composeApp/build.gradle.kts @@ -138,6 +138,8 @@ kotlin { } else { api(projects.lastfmEmpty) } + // `api` for the same reason: :androidApp hands it the Discord application id at startup. + api(projects.discord) // Navigation Compose implementation(libs.navigation.compose) @@ -862,11 +864,17 @@ buildkonfig { "lastfmSecret", properties.getProperty("LASTFM_SECRET") ?: "", ) + buildConfigField( + STRING, + "discordClientId", + properties.getProperty("DISCORD_CLIENT_ID") ?: "", + ) } catch (e: Exception) { println("Failed to load secrets from local.properties: ${e.message}") buildConfigField(STRING, "sentryDsn", "") buildConfigField(STRING, "lastfmApiKey", "") buildConfigField(STRING, "lastfmSecret", "") + buildConfigField(STRING, "discordClientId", "") } } else { buildConfigField(STRING, "sentryDsn", "") @@ -874,6 +882,8 @@ buildkonfig { // the feature hides itself. The stub module is linked in this flavour anyway. buildConfigField(STRING, "lastfmApiKey", "") buildConfigField(STRING, "lastfmSecret", "") + // No Discord application either, so Rich Presence keeps going through kizzy. + buildConfigField(STRING, "discordClientId", "") } } } diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 13b183458a..e688e3244c 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -667,6 +667,10 @@ Did not come back automatically? Paste the link your browser was redirected to Continue with this link + Open Discord and allow SimpMusic to show what you're listening to. + SimpMusic opens again on its own once you have allowed it. + Open Discord + Could not log in to Discord. Please try again. Logged in as %1$s YouTube Liked Music Keep showing your YouTube playlist when offline diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/App.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/App.kt index a291809cdf..1dba3cac8b 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/App.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/App.kt @@ -249,6 +249,13 @@ fun App( // of it. The token is handed straight to the shared view model, and the screen // closes itself when it sees a session key appear. token?.let { viewModel.completeLastfmLogin(it) } + } else if (data.scheme == "simpmusic" && data.host == "discord-auth") { + // Discord sends the user back here after they approve SimpMusic (Full builds): + // simpmusic://discord-auth?code=…&state=…. No navigation, as with Last.fm: the login + // screen is already open and closes itself once the login is stored. + Logger.d("MainActivity", "Discord callback, code present: ${!data.getQueryParameter("code").isNullOrEmpty()}") + viewModel.setIntent(null) + viewModel.completeDiscordLogin(data.toString()) } else if (data.host == "simpmusic.org" || data.scheme == "simpmusic") { // https://simpmusic.org/app/watch?v=VIDEO_ID // https://simpmusic.org/app/playlist?list=PLAYLIST_ID diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/di/ViewModelModule.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/di/ViewModelModule.kt index a3f860007d..9b3e55c422 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/di/ViewModelModule.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/di/ViewModelModule.kt @@ -46,6 +46,7 @@ val viewModelModule = get(), get(), get(), + get(), ) } single { @@ -127,6 +128,7 @@ val viewModelModule = get(), get(), get(), + get(), ) } viewModel { @@ -146,6 +148,7 @@ val viewModelModule = viewModel { LogInViewModel( get(), + get(), ) } viewModel { diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/navigation/graph/LoginScreenGraph.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/navigation/graph/LoginScreenGraph.kt index 2d6b5d3cea..70f52a4055 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/navigation/graph/LoginScreenGraph.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/navigation/graph/LoginScreenGraph.kt @@ -9,9 +9,11 @@ import com.maxrave.simpmusic.ui.navigation.destination.login.LastfmLoginDestinat import com.maxrave.simpmusic.ui.navigation.destination.login.LoginDestination import com.maxrave.simpmusic.ui.navigation.destination.login.SpotifyLoginDestination import com.maxrave.simpmusic.ui.screen.login.DiscordLoginScreen +import com.maxrave.simpmusic.ui.screen.login.DiscordOAuthLoginScreen import com.maxrave.simpmusic.ui.screen.login.LastfmLoginScreen import com.maxrave.simpmusic.ui.screen.login.LoginScreen import com.maxrave.simpmusic.ui.screen.login.SpotifyLoginScreen +import org.simpmusic.discord.isDiscordOAuthAvailable fun NavGraphBuilder.loginScreenGraph( innerPadding: PaddingValues, @@ -38,12 +40,23 @@ fun NavGraphBuilder.loginScreenGraph( } composable { - DiscordLoginScreen( - innerPadding = innerPadding, - navController = navController, - hideBottomNavigation = hideBottomBar, - showBottomNavigation = showBottomBar, - ) + // A Full build carries a Discord application and logs in through Discord's own page; a FOSS + // build keeps the WebView login whose token kizzy uses. + if (isDiscordOAuthAvailable()) { + DiscordOAuthLoginScreen( + innerPadding = innerPadding, + navController = navController, + hideBottomNavigation = hideBottomBar, + showBottomNavigation = showBottomBar, + ) + } else { + DiscordLoginScreen( + innerPadding = innerPadding, + navController = navController, + hideBottomNavigation = hideBottomBar, + showBottomNavigation = showBottomBar, + ) + } } composable { diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/login/DiscordOAuthLoginScreen.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/login/DiscordOAuthLoginScreen.kt new file mode 100644 index 0000000000..fe5be0b5f8 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/login/DiscordOAuthLoginScreen.kt @@ -0,0 +1,245 @@ +package com.maxrave.simpmusic.ui.screen.login + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.Button +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalUriHandler +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.navigation.NavController +import com.maxrave.simpmusic.ui.component.RippleIconButton +import com.maxrave.simpmusic.ui.icon.ArrowBackIosNew +import com.maxrave.simpmusic.ui.icon.SimpIcons +import com.maxrave.simpmusic.ui.theme.typo +import com.maxrave.simpmusic.viewModel.DiscordLoginState +import com.maxrave.simpmusic.viewModel.LogInViewModel +import org.jetbrains.compose.resources.getString +import org.jetbrains.compose.resources.stringResource +import org.koin.compose.viewmodel.koinViewModel +import simpmusic.composeapp.generated.resources.Res +import simpmusic.composeapp.generated.resources.discord_login_failed +import simpmusic.composeapp.generated.resources.discord_login_step_1 +import simpmusic.composeapp.generated.resources.discord_login_step_2 +import simpmusic.composeapp.generated.resources.discord_open_authorize_page +import simpmusic.composeapp.generated.resources.lastfm_paste_callback_confirm +import simpmusic.composeapp.generated.resources.lastfm_paste_callback_hint +import simpmusic.composeapp.generated.resources.lastfm_paste_callback_title +import simpmusic.composeapp.generated.resources.log_in_to_discord +import simpmusic.composeapp.generated.resources.login_success +import simpmusic.composeapp.generated.resources.rich_presence_info + +/** Desktop is far wider than any reading measure — the column stops here and centres. */ +private val CONTENT_MAX_WIDTH = 420.dp + +/** + * Discord login for Full builds, laid out like [LastfmLoginScreen]: no WebView and no token, the + * user approves SimpMusic on Discord's own page in their browser, and the redirect brings them back + * through `simpmusic://discord-auth`, which SharedViewModel completes. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun DiscordOAuthLoginScreen( + innerPadding: PaddingValues, + navController: NavController, + viewModel: LogInViewModel = koinViewModel(), + hideBottomNavigation: () -> Unit, + showBottomNavigation: () -> Unit, +) { + val state by viewModel.discordLoginState.collectAsStateWithLifecycle() + val loggedIn by viewModel.discordLoggedIn.collectAsStateWithLifecycle() + val uriHandler = LocalUriHandler.current + var callbackInput by rememberSaveable { mutableStateOf("") } + + LaunchedEffect(Unit) { + hideBottomNavigation() + } + + DisposableEffect(Unit) { + onDispose { + viewModel.resetDiscordLoginState() + showBottomNavigation() + } + } + + // Closes on the stored login rather than on this screen's own state, because the redirect is + // handled by SharedViewModel and never reaches this screen. + LaunchedEffect(loggedIn) { + if (loggedIn) { + navController.navigateUp() + } + } + + LaunchedEffect(state) { + when (val current = state) { + is DiscordLoginState.AwaitingApproval -> uriHandler.openUri(current.authorizeUrl) + is DiscordLoginState.LoggedIn -> viewModel.makeToast(getString(Res.string.login_success)) + is DiscordLoginState.Failed -> viewModel.makeToast(getString(Res.string.discord_login_failed)) + else -> Unit + } + } + + val busy = state is DiscordLoginState.CompletingLogin + + Box(modifier = Modifier.fillMaxSize()) { + Column( + modifier = + Modifier + .fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(horizontal = 24.dp), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + Spacer(Modifier.height(innerPadding.calculateTopPadding() + 96.dp)) + + Column( + modifier = Modifier.widthIn(max = CONTENT_MAX_WIDTH), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + Text( + text = stringResource(Res.string.rich_presence_info), + style = typo().bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center, + ) + + Spacer(Modifier.height(32.dp)) + + if (busy) { + CircularProgressIndicator() + } else { + NumberedStep( + number = "1", + text = stringResource(Res.string.discord_login_step_1), + ) + Spacer(Modifier.height(12.dp)) + Button( + onClick = { viewModel.startDiscordLogin() }, + modifier = Modifier.fillMaxWidth().height(48.dp), + shape = CircleShape, + ) { + Text( + text = stringResource(Res.string.discord_open_authorize_page), + // typo() bakes a colour into the style, so a Text inside a filled + // button keeps the body colour unless the colour is set here. + style = typo().labelMedium, + color = MaterialTheme.colorScheme.onPrimary, + ) + } + + // Everything below only matters once the browser is open. + if (state is DiscordLoginState.AwaitingApproval) { + Spacer(Modifier.height(28.dp)) + NumberedStep( + number = "2", + text = stringResource(Res.string.discord_login_step_2), + ) + + Spacer(Modifier.height(28.dp)) + HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant) + Spacer(Modifier.height(20.dp)) + + // Last resort when the redirect never reaches the app: no handler for the + // scheme (common on Linux), or a browser that will not hand off to an app. + Text( + text = stringResource(Res.string.lastfm_paste_callback_title), + style = typo().labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Spacer(Modifier.height(10.dp)) + OutlinedTextField( + value = callbackInput, + onValueChange = { callbackInput = it }, + singleLine = true, + textStyle = typo().bodySmall, + placeholder = { + Text( + text = stringResource(Res.string.lastfm_paste_callback_hint), + style = typo().bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + }, + modifier = Modifier.fillMaxWidth(), + ) + Spacer(Modifier.height(10.dp)) + OutlinedButton( + onClick = { viewModel.completeDiscordLoginFromCallback(callbackInput) }, + enabled = callbackInput.isNotBlank(), + modifier = Modifier.fillMaxWidth().height(48.dp), + shape = CircleShape, + ) { + Text( + text = stringResource(Res.string.lastfm_paste_callback_confirm), + style = typo().labelSmall, + color = + if (callbackInput.isNotBlank()) { + MaterialTheme.colorScheme.primary + } else { + MaterialTheme.colorScheme.onSurfaceVariant + }, + ) + } + } + } + } + + Spacer(Modifier.height(48.dp)) + } + + TopAppBar( + modifier = Modifier.align(Alignment.TopCenter), + colors = + TopAppBarDefaults.topAppBarColors( + containerColor = Color.Transparent, + ), + title = { + Text( + text = stringResource(Res.string.log_in_to_discord), + style = typo().titleMedium, + ) + }, + navigationIcon = { + Box(Modifier.padding(horizontal = 5.dp)) { + RippleIconButton( + SimpIcons.ArrowBackIosNew, + Modifier.size(32.dp), + true, + tint = MaterialTheme.colorScheme.onSurface, + ) { + navController.navigateUp() + } + } + }, + ) + } +} diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/login/LastfmLoginScreen.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/login/LastfmLoginScreen.kt index 1f39b24a9d..e6f6d87cb1 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/login/LastfmLoginScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/login/LastfmLoginScreen.kt @@ -257,7 +257,7 @@ fun LastfmLoginScreen( /** A step marker plus its instruction, so the two actions read as an ordered pair. */ @Composable -private fun NumberedStep( +internal fun NumberedStep( number: String, text: String, ) { diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/LogInViewModel.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/LogInViewModel.kt index f504346229..aea7a0026e 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/LogInViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/LogInViewModel.kt @@ -2,6 +2,7 @@ package com.maxrave.simpmusic.viewModel import androidx.lifecycle.viewModelScope import com.maxrave.domain.manager.DataStoreManager +import com.maxrave.domain.repository.DiscordRepository import com.maxrave.logger.Logger import com.maxrave.simpmusic.viewModel.base.BaseViewModel import kotlinx.coroutines.flow.MutableStateFlow @@ -16,6 +17,7 @@ import org.simpmusic.lastfm.completeLogin class LogInViewModel( private val dataStoreManager: DataStoreManager, + private val discordRepository: DiscordRepository, ) : BaseViewModel() { private val _spotifyStatus: MutableStateFlow = MutableStateFlow(false) val spotifyStatus: StateFlow get() = _spotifyStatus @@ -151,6 +153,61 @@ class LogInViewModel( fun resetLastfmState() { _lastfmState.value = LastfmLoginState.Idle } + + private val _discordLoginState: MutableStateFlow = MutableStateFlow(DiscordLoginState.Idle) + val discordLoginState: StateFlow get() = _discordLoginState.asStateFlow() + + // True once a Discord login is stored, whoever finished it: SharedViewModel takes the redirect, + // this view model the pasted link, and the screen closes itself on either. + private val _discordLoggedIn = MutableStateFlow(false) + val discordLoggedIn: StateFlow get() = _discordLoggedIn.asStateFlow() + + init { + viewModelScope.launch { + discordRepository.loggedIn.collect { _discordLoggedIn.value = it } + } + } + + /** Sends the user to Discord's authorization page (Full builds). */ + fun startDiscordLogin() { + val url = discordRepository.startLogin() + _discordLoginState.value = + if (url != null) { + DiscordLoginState.AwaitingApproval(authorizeUrl = url) + } else { + DiscordLoginState.Failed + } + } + + /** Finishes the login from the link the user pasted, for when the redirect never reaches the app. */ + fun completeDiscordLoginFromCallback(input: String) { + val link = input.trim() + if (link.isEmpty()) return + viewModelScope.launch { + _discordLoginState.value = DiscordLoginState.CompletingLogin + _discordLoginState.value = + if (discordRepository.completeLogin(link)) DiscordLoginState.LoggedIn else DiscordLoginState.Failed + } + } + + fun resetDiscordLoginState() { + _discordLoginState.value = DiscordLoginState.Idle + } +} + +sealed interface DiscordLoginState { + data object Idle : DiscordLoginState + + /** The browser is open and the user has not come back yet. */ + data class AwaitingApproval( + val authorizeUrl: String, + ) : DiscordLoginState + + data object CompletingLogin : DiscordLoginState + + data object LoggedIn : DiscordLoginState + + data object Failed : DiscordLoginState } sealed interface LastfmLoginState { diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/SettingsViewModel.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/SettingsViewModel.kt index 17bdaf7e9e..f1c67be76b 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/SettingsViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/SettingsViewModel.kt @@ -20,6 +20,7 @@ import com.maxrave.domain.mediaservice.handler.DownloadHandler import com.maxrave.domain.repository.AccountRepository import com.maxrave.domain.repository.ArtistRepository import com.maxrave.domain.repository.CacheRepository +import com.maxrave.domain.repository.DiscordRepository import com.maxrave.domain.repository.CommonRepository import com.maxrave.domain.repository.LyricsRomanizerRepository import com.maxrave.domain.repository.SongRepository @@ -79,6 +80,7 @@ class SettingsViewModel( private val cacheRepository: CacheRepository, private val artistRepository: ArtistRepository, private val lyricsRomanizerRepository: LyricsRomanizerRepository, + private val discordRepository: DiscordRepository, ) : BaseViewModel() { private val databasePath: String? = commonRepository.getDatabasePath() private val downloadUtils: DownloadHandler by inject() @@ -570,8 +572,8 @@ class SettingsViewModel( private fun getDiscordLoggedIn() { viewModelScope.launch { - dataStoreManager.discordToken.collect { loggedIn -> - _discordLoggedIn.value = loggedIn.isNotEmpty() + discordRepository.loggedIn.collect { loggedIn -> + _discordLoggedIn.value = loggedIn } } } @@ -615,7 +617,7 @@ class SettingsViewModel( fun logOutDiscord() { viewModelScope.launch { - dataStoreManager.setDiscordToken("") + discordRepository.logout() // Turn Rich Presence off on logout: without a token it can't run, and leaving the flag on // would both strand the user (the toggle greys out when logged out) and let the player keep // a dead RPC alive (issue #2157). The existing richPresenceEnabled collector refreshes the UI. 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 8924abc504..4dd5884e5c 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/SharedViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/SharedViewModel.kt @@ -53,6 +53,7 @@ import com.maxrave.domain.mediaservice.handler.SleepTimerState import com.maxrave.domain.mediaservice.handler.addToQueueBlock import com.maxrave.domain.repository.AlbumRepository import com.maxrave.domain.repository.CacheRepository +import com.maxrave.domain.repository.DiscordRepository import com.maxrave.domain.repository.LocalPlaylistRepository import com.maxrave.domain.repository.LyricsCanvasRepository import com.maxrave.domain.repository.PlaylistRepository @@ -117,6 +118,7 @@ import simpmusic.composeapp.generated.resources.added_to_queue import simpmusic.composeapp.generated.resources.added_to_youtube_liked import simpmusic.composeapp.generated.resources.disliked import simpmusic.composeapp.generated.resources.error +import simpmusic.composeapp.generated.resources.discord_login_failed import simpmusic.composeapp.generated.resources.lastfm_login_failed import simpmusic.composeapp.generated.resources.login_success import simpmusic.composeapp.generated.resources.play_next @@ -145,6 +147,7 @@ class SharedViewModel( private val playlistRepository: PlaylistRepository, private val lyricsCanvasRepository: LyricsCanvasRepository, private val cacheRepository: CacheRepository, + private val discordRepository: DiscordRepository, ) : BaseViewModel() { var isFirstLiked: Boolean = false var isFirstMiniplayer: Boolean = false @@ -632,6 +635,20 @@ class SharedViewModel( } } + /** + * Finishes a Discord login from the `simpmusic://discord-auth` redirect (Full builds). Like the + * Last.fm callback, the login screen is already open and closes itself once a login is stored. + */ + fun completeDiscordLogin(callbackUrl: String) { + viewModelScope.launch { + if (discordRepository.completeLogin(callbackUrl)) { + makeToast(getString(Res.string.login_success)) + } else { + makeToast(getString(Res.string.discord_login_failed)) + } + } + } + fun showNotificationPermissionDialog() { _showNotificationPermissionDialog.value = true } diff --git a/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/DesktopApp.kt b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/DesktopApp.kt index b28f89603a..c3638644a2 100644 --- a/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/DesktopApp.kt +++ b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/DesktopApp.kt @@ -69,6 +69,7 @@ import org.koin.core.context.loadKoinModules import org.koin.core.context.startKoin import org.koin.java.KoinJavaComponent.inject import org.koin.mp.KoinPlatform.getKoin +import org.simpmusic.discord.configDiscord import org.simpmusic.lastfm.configLastfm import simpmusic.composeapp.generated.resources.Res import simpmusic.composeapp.generated.resources.app_name @@ -189,6 +190,9 @@ fun runDesktopApp(args: Array = emptyArray()) { deepLinkArg?.let { DesktopDeepLinkHandler.onNewUri(it) } } + // Before Koin: DiscordRepository is created at start and reads which login this build uses. + configDiscord(BuildKonfig.discordClientId) + // Initialize Koin ONCE before application starts startKoin { loadAllModules( diff --git a/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/DesktopDeepLinkHandler.kt b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/DesktopDeepLinkHandler.kt index 66a356b92a..f351e42f16 100644 --- a/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/DesktopDeepLinkHandler.kt +++ b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/DesktopDeepLinkHandler.kt @@ -118,6 +118,10 @@ object DesktopDeepLinkHandler { } } + // simpmusic://discord-auth?code=…&state=… → pass through untouched: it is Discord's OAuth + // redirect, which App.kt matches on this exact scheme and host, not a page to open. + parsed.scheme == "simpmusic" && parsed.host == "discord-auth" -> parsed + // simpmusic://watch?v=xxx → https://simpmusic.org/app/watch?v=xxx // simpmusic://playlist?list=xxx → https://simpmusic.org/app/playlist?list=xxx // simpmusic://channel/UCxxx → https://simpmusic.org/app/channel/UCxxx diff --git a/core b/core index 344d6149d3..fd835d23a7 160000 --- a/core +++ b/core @@ -1 +1 @@ -Subproject commit 344d6149d38cab5791dc0164958709ac44e7e298 +Subproject commit fd835d23a7aa20011b644205bdc14f7227ae29c5 diff --git a/settings.gradle.kts b/settings.gradle.kts index 7feae70604..a389d077dd 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -60,6 +60,7 @@ include( ":lastfm", ":lastfm-empty", ":kizzy", + ":discord", ":listenTogether", ":loginSync", ) @@ -77,6 +78,7 @@ project(":lyricsService").projectDir = File(serviceDir, "lyricsService") project(":kotlinYtmusicScraper").projectDir = File(serviceDir, "kotlinYtmusicScraper") project(":spotify").projectDir = File(serviceDir, "spotify") project(":kizzy").projectDir = File(serviceDir, "kizzy") +project(":discord").projectDir = File(serviceDir, "discord") project(":listenTogether").projectDir = File(serviceDir, "listenTogether") project(":loginSync").projectDir = File(serviceDir, "loginSync") From aae9ba17171fb20c704170b1c1106750881e8c8e Mon Sep 17 00:00:00 2001 From: maxrave-dev Date: Tue, 3 Nov 2026 20:29:01 +0700 Subject: [PATCH 13/29] chore(core): bump for the discord module ignoring its build directory --- core | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core b/core index fd835d23a7..bb68195953 160000 --- a/core +++ b/core @@ -1 +1 @@ -Subproject commit fd835d23a7aa20011b644205bdc14f7227ae29c5 +Subproject commit bb681959532959305ac040c4bb9e42eff30bdb93 From 2f1460cff99ef485038b395a9a5704df97c2d501 Mon Sep 17 00:00:00 2001 From: maxrave-dev Date: Fri, 6 Nov 2026 09:30:28 +0700 Subject: [PATCH 14/29] chore(core): bump for the Discord OAuth merge into multiplatform --- core | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core b/core index bb68195953..f2a065d605 160000 --- a/core +++ b/core @@ -1 +1 @@ -Subproject commit bb681959532959305ac040c4bb9e42eff30bdb93 +Subproject commit f2a065d605c0f199edc3126a0b4e1c06d1e6f9d2 From 55ebef8285e76831bd722608ba1b1a0f20fa943b Mon Sep 17 00:00:00 2001 From: maxrave-dev Date: Fri, 6 Nov 2026 17:33:44 +0700 Subject: [PATCH 15/29] feat(player): add the SoundCloud Now Playing style --- CLAUDE.md | 11 +- composeApp/build.gradle.kts | 2 +- .../composeResources/values/strings.xml | 3 + .../maxrave/simpmusic/di/ViewModelModule.kt | 2 + .../ui/component/CommentsBottomSheet.kt | 11 +- .../simpmusic/ui/component/DescriptionView.kt | 10 +- .../simpmusic/ui/screen/home/SettingScreen.kt | 2 + .../ui/screen/player/NowPlayingScreen.kt | 19 +- .../content/NowPlayingContentSoundCloud.kt | 1013 +++++++++++++++++ .../player/content/NowPlayingContentState.kt | 8 + .../applemusic/AppleMusicLyricStrip.kt | 2 +- .../content/soundcloud/SoundCloudWaveform.kt | 312 +++++ .../viewModel/SoundCloudPlayerViewModel.kt | 120 ++ core | 2 +- scripts/mpv-linux/Dockerfile | 8 +- 15 files changed, 1516 insertions(+), 9 deletions(-) create mode 100644 composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentSoundCloud.kt create mode 100644 composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/soundcloud/SoundCloudWaveform.kt create mode 100644 composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/SoundCloudPlayerViewModel.kt diff --git a/CLAUDE.md b/CLAUDE.md index e3b9dacb1b..897fc83ffe 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1119,6 +1119,15 @@ if (getPlatform() == Platform.Android) { - **Session**: three keys (`discord_access_token`, `discord_refresh_token`, `discord_token_expires_at`) in the settings file, so they ride in backups like every other sign-in. Access tokens last about 7 days; `DiscordRepository.accessToken()` refreshes under a mutex when under 10 minutes are left, and an `invalid_grant` on refresh clears the session, which logs the user out and tears the RPC down through `loggedIn`. On a Full build the old `discord_token` is cleared at start: it was a whole-account token this build no longer uses. Log out does not call Discord's revoke endpoint; SimpMusic stays in the user's Authorized Apps until they remove it. - Both playback handlers now hold a `RichPresenceClient` (`core/data/.../mediaservice/RichPresenceClient.kt`) built by `createRichPresenceClient(discordRepository)`, and run on `richPresenceEnabled && discordRepository.loggedIn`; the rest of the RPC job is unchanged. Login Sync no longer carries Discord. +- **SoundCloud Now Playing style (2026-11-06)**: a fourth style, `NOW_PLAYING_STYLE_SOUNDCLOUD` (`content/NowPlayingContentSoundCloud.kt`), laid out after SoundCloud's own player as captured on Mobbin and in the owner's own iOS captures: the artwork (or canvas, or the video at its own shape) fills a rounded card; title (up to 3 lines), artist (2) and a "Song info" chip sit top-left on black strips, ONE STRIP PER LINE as wide as that line (drawn per line from `onTextLayout`, line height 1.75em with `LineHeightStyle.Trim.None` so the first and last lines get the same room); dismiss, the output button Classic and M3E use (`Headphones` → `AudioOutputSheetHost`, primary while casting) and Lyrics (`SimpIcons.Lyrics`, opening the fullscreen lyrics page) run down the top-right corner, joined while a music video plays by Fullscreen and the subtitles toggle (lyrics over the video, on by default as in the other styles); paused on a video, the transport gains the other styles' ±5s steps on its outer ends (the first version had no video controls at all, and the owner: "code xong bỏ bê cái video hả"). The transport, the waveform and the action row sit in `LeftToRight`, the app's RTL rule; like · comments · shuffle · repeat · queue · more (`MoreVert`) below the card, like and comments with counts, the queue on phones only (Desktop's capsule player already opens it; the owner: a phone has no other way in). The owner moved Lyrics into the corner (a Lyrics button leading the bottom row, then one beside Queue, both read as random to him) and removed the follow button the first version had: no other Now Playing style has one. The owner rejected new icons for this style ("dùng cũ đi") and its share button: every icon is one the app already uses for the same action. The style follows the app's liquid-glass setting (`LocalLiquidGlassEnabled`): on, the round buttons (dismiss, output, lyrics, the paused transport) are glass circles with a 1dp highlight and the comment box a static glass pill, refracting the artwork, which is the backdrop source with its dim and scrim drawn into it; off, SoundCloud's black circles and plain corner icons. The label strips stay black either way. Above the waveform runs the Apple Music style's `AppleMusicLyricStrip` (owner's request; a tap opens the fullscreen lyrics page), and from the card's bottom up to that line the cover melts into a 32dp-blurred copy of itself (ArtistScreen's DstIn-masked copy; it fades with the cover, so a canvas or video gets the scrim alone) under the scheme's `scrim`, both ramping in on smoothstep over the 80dp above the line, the scrim 60% at the line and 85% at the bottom. The line's position comes from the lower block's measured height (`lyricLineY`). A plain 75% scrim over a 64dp ramp came first; the owner: "fade kiểu gì v? blur đâu, smooth đâu". Playing, the card shows only artwork and labels and a tap anywhere pauses; paused, the artwork blurs (20dp `BlurEffect` in a `graphicsLayer`, Android 12+ and Desktop) under a 45% `surface` scrim drawn as a sibling (a video surface takes no Compose effect, but what is drawn above it covers it), the strips fade to plain text, the waveform folds into a 2dp line, and previous / play / next come up across the middle (the owner's call: SoundCloud has controls). "Paused" is not the raw `isPlaying`: the player also reports not-playing while it buffers, sometimes a beat before `timeline.loading`, so only not-playing-and-not-loading for 250 ms counts, while a tap on the card flips it at once. Under the waveform sits a "Comment…" box with 🔥 👏 🥹: the box opens the comments sheet, an emoji opens it with that emoji typed (`NowPlayingContentActions.onWriteComment` → `CommentsBottomSheet(initialDraft)`, applied only while the sheet shows the video it opened on). Every colour is a role of the artwork-seeded dark scheme `NowPlayingExpressiveTheme` builds for the M3 Expressive style: the black label strips and buttons are `surfaceContainerLowest`, text is `onSurface`/`onSurfaceVariant`. The one exception is where SoundCloud puts its orange: the waveform's played part is the APP's `primary`, read in `NowPlayingContentSoundCloud` before the artwork scheme is entered and the same on every track, crossfade included (owner's call; it first followed the artwork scheme's primary). No colour is written into these files; the first build used the `seed` constant and the owner caught it. Its extra data comes from `SoundCloudPlayerViewModel`, which the screen drives (`load(videoId)`) so nothing is decoded or fetched while the player is closed or another style is in use; the id is `NowPlayingContentState.videoId`, the shell's prefix-stripped id off the media item. + - **The waveform is asked for before the stream is ready.** The screen asks the moment a track appears, while the player may still be replacing the format stored for it — on 2026-11-06 a previous session's URL answered 403 and the fresh one landed 1.3 s later, so the Desktop source check refused the dead URL and the track never got a waveform (the old ViewModel never asked twice). The ViewModel now asks again at 3, 8 and 20 s while the track is on screen and afresh when a track without one comes back, and every failure branch in both readers logs under `Waveform`. On Android the reader reads the format's length only after opening the first chunk, because opening is what makes the resolver replace a stale format. + - **The cover stays composed under a video.** Its `onSuccess` is the only thing that hands the artwork to the shell (`setBitmap`, reset to null on every track change), and `NowPlayingExpressiveTheme` falls back to the app `seed` (`#8ECAE6`) without it. The first version skipped the cover while a video played, so every video track drew the waveform and the rest of the style cyan. M3 Expressive keeps its cover under video for the same reason. + - **Waveform** (`content/soundcloud/SoundCloudWaveform.kt`): bars slide past a playhead fixed at the centre, so dragging LEFT goes forward — the opposite of a slider; while dragging, the labels and controls give way to the time in large type. The step and the bar width are whole pixels while the origin stays fractional. A 3.8px step put each bar on a different fraction of a pixel, sharp beside smeared, and the owner saw that pattern crawl "like an old TV"; with whole-pixel steps every bar shares one fraction and the waveform glides as one. Do not snap the origin as well: that made it tick along in one-pixel steps ("giật quá"). A waveform that arrives (seconds after the track, once decoded) rises out of the flat line over 350ms from the playhead outward, each bar on smoothstep and a little after its neighbour nearer the playhead; a track change sinks the old one back over 150ms first (700/250ms read as slow). It used to swap from flat to bars in one frame (`bars ?: FLAT_LEVEL`), and the owner asked where the animation was. + - **The waveform has a playhead of its own, `rememberSteadyPlayhead`.** On Desktop the reported position runs, pauses and runs again: mpv moves `time-pos` a few times a second and the handler's smoothing holds rather than step back. `rememberSweepPlayhead` (the Apple Music lyric strip's) leans toward each report within 150ms and passed that on: measured frame by frame on a screen recording, the bars scrolled fast for ~0.2s and nearly stopped for the next ~0.2s, about 2.5 times a second. The steady one runs on the frame clock and eases toward the last report carried forward at 1x (at most 1s) over 3s, so the end of a hold slows it by a few percent and never throws it back; it jumps only across a gap wider than 2s (a seek, a new track), and while a scrub settles (`pendingSeekMs`) it is not running and follows the reports. A first version also jumped whenever a report broke 400ms from the run: that fired at the end of every handler hold and threw the bars back ("giật đùng đùng"). It assumes 1x between reports (at another speed it trails by about (speed − 1) × 3s). The position is read where it is drawn (the canvas, a `derivedStateOf` for the elapsed text and the timed comment), so the card does not recompose every frame, and the artwork's modifier (glass source, paused blur, dim and scrim) is remembered so the shell's per-report recompositions do not redraw the blur and the glass. The time label stands ON the baseline with its divider on the playhead, the time played to its left and the length to its right, as SoundCloud sets it (it was centred across the baseline, half into the reflection). Paused, the time label loses its strip and the folded line is lit where the track has played and a 35% hairline ahead. Position comes from `rememberSweepPlayhead` (now `internal`), and a scrub holds its value until the player reports the new spot, so the bars do not spring back. + - **Waveform data**: `MediaPlayerInterface.loadWaveform(mediaId)`, default null, which draws the same bars as a flat line. Android: `WaveformReader` (`core/media/media3/.../waveform/`) reads the audio through the player's own resolving, cache-backed data source chain — no second download — one resolver chunk at a time up to the format's `contentLength` (it never opens at the end of the file, where HTTP answers 416), decodes it with MediaExtractor + MediaCodec, and keeps one RMS byte per 0.8 s (`WAVEFORM_BARS_PER_SECOND` = 1.25) under `cacheDir/waveforms/`. Desktop: `MpvWaveformReader` (`media-jvm/.../mpv/`) plays the audio once more through a second, silent mpv handle — mpv shares no cache between handles — with `ao=null` + `ao-null-untimed` (decodes as fast as the stream arrives) and the lavfi chain `aresample=8000,aformat=mono,asetnsamples,astats,ametadata` printing one RMS line per bar to a file that is read back; the result is stored under `~/.simpmusic/waveforms/` in the same one-byte-per-bar format. The source is a download first, then the format's own audio URL, with no fallback extraction. Linux: `asetnsamples`, `astats` and `ametadata` were added to the slice's whitelist (`scripts/mpv-linux/Dockerfile`) and the slice rebuilt, republished on `abc` and re-pinned (`ab9957e8…1d05`, 2026-11-06); the macOS and Windows slices carry every filter already. Checked by running the exact graph on the new libmpv against a WAV of known loudness (10 s decoded in 0.02 s, bars as expected); the previous slice ends that file with an error and writes nothing, which is the flat-line fallback any slice without the filters gets. + - **Timed comments**: YouTube comments carry no moment of their own, so only the ones whose text names one float over the waveform, at the first "m:ss" or "h:mm:ss" in them — read with `TIMESTAMP_REGEX`, the regex `DescriptionView` uses for its seek links, so both read a moment by one rule. They come from the first comments page of the track; the comment count beside the icon comes from the same page. + - The landscape fullscreen-lyrics page has no SoundCloud rows; its `when` falls to `else` and borrows Classic's. + ## 🔄 CLAUDE.md Auto-Update Rule (MANDATORY) After completing any of the following types of changes, the AI agent **MUST** update this CLAUDE.md file: @@ -1143,6 +1152,6 @@ After completing any of the following types of changes, the AI agent **MUST** up *This document helps AI Agents quickly understand the SimpMusic project. Update regularly when there are major changes to architecture or structure.* -**Last updated**: 2026-11-03 +**Last updated**: 2026-11-06 **Project version**: Check latest release on GitHub **Maintained by**: maxrave-dev and contributors diff --git a/composeApp/build.gradle.kts b/composeApp/build.gradle.kts index 6da9993d56..8d4a3f2d56 100644 --- a/composeApp/build.gradle.kts +++ b/composeApp/build.gradle.kts @@ -764,7 +764,7 @@ val mpvBundleAll by tasks.registering { */ val mpvNativesChecksums = mapOf( - "linux-x64" to "f583c29531355f83579b9f5509424c659bed2a122624a03d47fb41682afb24c4", + "linux-x64" to "ab9957e812f6b27ef28d24b13d38a00b428a6529c87876c1c80d0427d8251d05", "macos-arm64" to "e527daac8f6cc196324ea6f0ce54d119d04450af9795ff2856c1891806c1d5e0", "macos-x64" to "95170ea54e1f637fdee148a9efd97993c305a92e233b8478d3764fbecce3eb02", "windows-x64" to "256f17cf402c7583b8684d5a7cf585ad1b59695469219671f4887b9d8d272a99", diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index e688e3244c..bf52a546cb 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -443,6 +443,8 @@ Classic Material 3 Expressive Apple Music + SoundCloud + Song info AI translated Lyrics style Classic @@ -1027,6 +1029,7 @@ Couldn't load comments Couldn't post your comment Create a YouTube channel to comment + Comment… Local playlist Build a playlist on this device Start or join a room diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/di/ViewModelModule.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/di/ViewModelModule.kt index 9b3e55c422..9291b439f7 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/di/ViewModelModule.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/di/ViewModelModule.kt @@ -8,6 +8,7 @@ import com.maxrave.simpmusic.viewModel.ListenTogetherViewModel import com.maxrave.simpmusic.viewModel.ArtistViewModel import com.maxrave.simpmusic.viewModel.BrowseViewModel import com.maxrave.simpmusic.viewModel.CommentsViewModel +import com.maxrave.simpmusic.viewModel.SoundCloudPlayerViewModel import com.maxrave.simpmusic.viewModel.HomeViewModel import com.maxrave.simpmusic.viewModel.ImportViewModel import com.maxrave.simpmusic.viewModel.LibraryDynamicPlaylistViewModel @@ -67,6 +68,7 @@ val viewModelModule = viewModel { LoginSyncHostViewModel(get()) } viewModel { LoginSyncSenderViewModel(get()) } viewModel { CommentsViewModel(get(), get()) } + viewModel { SoundCloudPlayerViewModel(get()) } viewModel { NowPlayingBottomSheetViewModel( get(), diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/CommentsBottomSheet.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/CommentsBottomSheet.kt index e676ed86f3..d89a7cebb4 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/CommentsBottomSheet.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/CommentsBottomSheet.kt @@ -114,6 +114,9 @@ private val LinkColor = Color(0xFF00B0FF) * Reading needs no account. Writing (post, reply, like, dislike) needs YouTube: signed out, every * one of them asks to log in instead. Comment text is handled the way a description is: a * timestamp seeks the track, a link opens normally. + * + * [initialDraft] starts the comment box with text already in it (the SoundCloud style's emoji), for + * the video the sheet opened on only. */ @OptIn(ExperimentalMaterial3Api::class) @Composable @@ -123,8 +126,10 @@ fun CommentsBottomSheet( onTimestamp: (String) -> Unit, onLogIn: () -> Unit, onDismiss: () -> Unit, + initialDraft: String = "", viewModel: CommentsViewModel = koinViewModel(), ) { + val draftVideoId = remember { videoId } val colors = rememberSurfaceDarkColors() val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = false) val scope = rememberCoroutineScope() @@ -235,6 +240,7 @@ fun CommentsBottomSheet( onFocus = { scope.launch { sheetState.expand() } }, onPost = { text, clear -> viewModel.post(text, clear) }, onLogIn = { showLogIn = true }, + initialDraft = if (uiState.videoId == draftVideoId) initialDraft else "", modifier = Modifier .align(Alignment.BottomCenter) @@ -526,6 +532,7 @@ private fun CommentInput( onFocus: () -> Unit, onPost: (text: String, clear: () -> Unit) -> Unit, onLogIn: () -> Unit, + initialDraft: String, modifier: Modifier = Modifier, ) { Column( @@ -564,6 +571,7 @@ private fun CommentInput( onCancelReply = onCancelReply, onFocus = onFocus, onPost = onPost, + initialDraft = initialDraft, ) } } @@ -579,8 +587,9 @@ private fun SignedInInput( onCancelReply: () -> Unit, onFocus: () -> Unit, onPost: (text: String, clear: () -> Unit) -> Unit, + initialDraft: String, ) { - var text by remember { mutableStateOf("") } + var text by remember { mutableStateOf(initialDraft) } Column(Modifier.fillMaxWidth()) { if (replyingTo != null) { Row( diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/DescriptionView.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/DescriptionView.kt index 1135691b41..e3942542b1 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/DescriptionView.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/DescriptionView.kt @@ -76,7 +76,7 @@ fun DescriptionView( } } - val timeRegex = Regex("""(\d+):(\d+)(?::(\d+))?""") + val timeRegex = TIMESTAMP_REGEX // Parentheses count only as a pair: descriptions wrap links in them — "From Wikipedia // (https://…/Ariana_Grande)" — and `\S+` swallowed the closing one into the URL, while // "…/Queen_(band)" must keep its own. @@ -203,4 +203,10 @@ fun DescriptionView( ) } } -} \ No newline at end of file +} + +/** + * A moment written into text, "m:ss" or "h:mm:ss". Descriptions and comments turn it into a seek link, + * and the SoundCloud style places a comment at it, so both read a moment by the same rule. + */ +internal val TIMESTAMP_REGEX = Regex("""(\d+):(\d+)(?::(\d+))?""") diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/SettingScreen.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/SettingScreen.kt index 02f2682874..3cfd640dc0 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/SettingScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/SettingScreen.kt @@ -358,6 +358,7 @@ import simpmusic.composeapp.generated.resources.normalize_volume import simpmusic.composeapp.generated.resources.not_available_while_casting import simpmusic.composeapp.generated.resources.now_playing_style import simpmusic.composeapp.generated.resources.now_playing_style_apple_music +import simpmusic.composeapp.generated.resources.now_playing_style_soundcloud import simpmusic.composeapp.generated.resources.now_playing_style_m3_expressive import simpmusic.composeapp.generated.resources.now_playing_style_spotify import simpmusic.composeapp.generated.resources.ok @@ -766,6 +767,7 @@ fun SettingScreen( DataStoreManager.NOW_PLAYING_STYLE_M3_EXPRESSIVE to stringResource(Res.string.now_playing_style_m3_expressive), DataStoreManager.NOW_PLAYING_STYLE_APPLE_MUSIC to stringResource(Res.string.now_playing_style_apple_music) + requiresAndroid12, + DataStoreManager.NOW_PLAYING_STYLE_SOUNDCLOUD to stringResource(Res.string.now_playing_style_soundcloud), ) SettingItem( title = stringResource(Res.string.now_playing_style), diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/NowPlayingScreen.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/NowPlayingScreen.kt index e85976381b..9a39bee9d3 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/NowPlayingScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/NowPlayingScreen.kt @@ -100,6 +100,7 @@ import com.maxrave.simpmusic.ui.navigation.destination.login.LoginDestination import com.maxrave.simpmusic.ui.navigation.destination.player.FullscreenDestination import com.maxrave.simpmusic.ui.screen.player.content.NowPlayingContentActions import com.maxrave.simpmusic.ui.screen.player.content.NowPlayingContentAppleMusic +import com.maxrave.simpmusic.ui.screen.player.content.NowPlayingContentSoundCloud import com.maxrave.simpmusic.ui.screen.player.content.NowPlayingContentM3Expressive import com.maxrave.simpmusic.ui.screen.player.content.NowPlayingContentSpotify import com.maxrave.simpmusic.ui.screen.player.content.NowPlayingContentState @@ -419,6 +420,7 @@ fun NowPlayingScreenContent( var showCommentsSheet by rememberSaveable { mutableStateOf(false) } + var commentDraft by rememberSaveable { mutableStateOf("") } var showVoteDialog by rememberSaveable { mutableStateOf(false) @@ -662,6 +664,7 @@ fun NowPlayingScreenContent( audioQualityLabel = formatState.toAudioQualityLabel(), lyricsOffsetMs = lyricsOffsetMs.toLong(), videoAspectRatio = rememberVideoAspectRatio(MAIN_PLAYER) ?: 16f / 9, + videoId = commentsVideoId, ) val actions = NowPlayingContentActions( @@ -707,7 +710,14 @@ fun NowPlayingScreenContent( onShowQueue = { showQueueBottomSheet = true }, onShowInfo = { showInfoBottomSheet = true }, onShowAddToPlaylist = { showAddToPlaylistDirectly = true }, - onShowComments = { showCommentsSheet = true }, + onShowComments = { + commentDraft = "" + showCommentsSheet = true + }, + onWriteComment = { draft -> + commentDraft = draft + showCommentsSheet = true + }, onShowFullscreenLyrics = { showFullscreenLyrics = true }, onShowVoteDialog = { showVoteDialog = true }, onLyricsOffsetChange = { sharedViewModel.setLyricsOffsetMs(it) }, @@ -903,6 +913,7 @@ fun NowPlayingScreenContent( navController.navigate(LoginDestination) }, onDismiss = { showCommentsSheet = false }, + initialDraft = commentDraft, ) } } @@ -987,6 +998,12 @@ fun NowPlayingScreenContent( actions = actions, ) + DataStoreManager.NOW_PLAYING_STYLE_SOUNDCLOUD -> + NowPlayingContentSoundCloud( + state = state, + actions = actions, + ) + else -> NowPlayingContentSpotify( state = state, diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentSoundCloud.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentSoundCloud.kt new file mode 100644 index 0000000000..80744647b6 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentSoundCloud.kt @@ -0,0 +1,1013 @@ +package com.maxrave.simpmusic.ui.screen.player.content + +import androidx.compose.animation.AnimatedContent +import androidx.compose.animation.core.animateFloatAsState +import androidx.compose.animation.core.tween +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.togetherWith +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +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.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.navigationBars +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.statusBars +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.windowInsetsPadding +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.FilledIconButton +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.IconButtonDefaults +import androidx.compose.material3.LocalContentColor +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.IntState +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.derivedStateOf +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableLongStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshotFlow +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha +import androidx.compose.ui.draw.blur +import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.drawBehind +import androidx.compose.ui.draw.drawWithContent +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.BlendMode +import androidx.compose.ui.graphics.BlurEffect +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.CompositingStrategy +import androidx.compose.ui.graphics.TileMode +import androidx.compose.ui.graphics.drawscope.DrawScope +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.text.TextLayoutResult +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.LineHeightStyle +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.em +import androidx.compose.ui.unit.sp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import coil3.compose.AsyncImage +import coil3.compose.LocalPlatformContext +import coil3.request.CachePolicy +import coil3.request.ImageRequest +import coil3.request.crossfade +import com.kyant.backdrop.highlight.Highlight +import com.maxrave.common.Config.MAIN_PLAYER +import com.maxrave.domain.data.model.comments.YouTubeComment +import com.maxrave.domain.mediaservice.handler.RepeatState +import com.maxrave.simpmusic.Platform +import com.maxrave.simpmusic.expect.ui.MediaPlayerView +import com.maxrave.simpmusic.expect.ui.MediaPlayerViewWithSubtitle +import com.maxrave.simpmusic.expect.ui.PlatformBackdrop +import com.maxrave.simpmusic.expect.ui.layerBackdrop +import com.maxrave.simpmusic.expect.ui.rememberBackdrop +import com.maxrave.simpmusic.expect.ui.toImageBitmap +import com.maxrave.simpmusic.extension.LeftToRight +import com.maxrave.simpmusic.extension.formatDuration +import com.maxrave.simpmusic.extension.lengthLabel +import com.maxrave.simpmusic.extension.smoothScrimBrush +import com.maxrave.simpmusic.getPlatform +import com.maxrave.simpmusic.ui.component.LiquidGlassContainer +import com.maxrave.simpmusic.ui.component.RippleIconButton +import com.maxrave.simpmusic.ui.component.TIMESTAMP_REGEX +import com.maxrave.simpmusic.ui.component.liquidGlass +import com.maxrave.simpmusic.ui.component.rememberHolderPainter +import com.maxrave.simpmusic.ui.icon.CommentOutline +import com.maxrave.simpmusic.ui.icon.Favorite +import com.maxrave.simpmusic.ui.icon.FavoriteBorder +import com.maxrave.simpmusic.ui.icon.Forward5 +import com.maxrave.simpmusic.ui.icon.Fullscreen +import com.maxrave.simpmusic.ui.icon.GraphicEq +import com.maxrave.simpmusic.ui.icon.Headphones +import com.maxrave.simpmusic.ui.icon.Lyrics +import com.maxrave.simpmusic.ui.icon.MoreVert +import com.maxrave.simpmusic.ui.icon.PlayArrow +import com.maxrave.simpmusic.ui.icon.QueueMusic +import com.maxrave.simpmusic.ui.icon.Repeat +import com.maxrave.simpmusic.ui.icon.RepeatOne +import com.maxrave.simpmusic.ui.icon.Replay5 +import com.maxrave.simpmusic.ui.icon.Shuffle +import com.maxrave.simpmusic.ui.icon.SimpIcons +import com.maxrave.simpmusic.ui.icon.SkipNext +import com.maxrave.simpmusic.ui.icon.SkipPrevious +import com.maxrave.simpmusic.ui.icon.Subtitles +import com.maxrave.simpmusic.ui.icon.SubtitlesOff +import com.maxrave.simpmusic.ui.screen.player.content.applemusic.AppleMusicLyricStrip +import com.maxrave.simpmusic.ui.screen.player.content.applemusic.AudioOutputSheetHost +import com.maxrave.simpmusic.ui.screen.player.content.applemusic.rememberAppleMusicTypography +import com.maxrave.simpmusic.ui.screen.player.content.soundcloud.SoundCloudWaveform +import com.maxrave.simpmusic.ui.screen.player.content.soundcloud.rememberSteadyPlayhead +import com.maxrave.simpmusic.ui.theme.LocalLiquidGlassEnabled +import com.maxrave.simpmusic.ui.theme.typo +import com.maxrave.simpmusic.viewModel.SoundCloudPlayerViewModel +import com.maxrave.simpmusic.viewModel.UIEvent +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.withTimeoutOrNull +import org.jetbrains.compose.resources.stringResource +import org.koin.compose.viewmodel.koinViewModel +import simpmusic.composeapp.generated.resources.Res +import simpmusic.composeapp.generated.resources.comment_placeholder +import simpmusic.composeapp.generated.resources.song_info +import kotlin.math.abs +import kotlin.math.roundToInt + +/** + * Now Playing laid out like SoundCloud's player (Mobbin, iOS 2024 and Android, and the owner's own + * iOS captures): the artwork fills a rounded card; title, artist and a "Song info" chip sit on black + * strips in its top-left corner, one strip per line; dismiss, follow, output and lyrics run down its + * top-right; the waveform slides past a playhead fixed at the centre, with the Apple Music style's + * line of lyrics and the comments that name a moment above it and a comment box below it; like, + * comments, shuffle, repeat and more run along the bottom. Every colour is a role of the + * artwork-seeded dark scheme that [NowPlayingExpressiveTheme] builds for the M3 Expressive style, + * except where SoundCloud puts its orange: the played part of the waveform keeps the app's own + * primary on every track. + * + * Playing, the card shows nothing but the artwork and its labels; a tap anywhere on it pauses. + * Paused, the artwork blurs and dims, the strips give way to plain text, the waveform folds into a + * line, and previous, play and next come up across the middle. Dragging the waveform scrubs: the + * labels and controls give way to the time in large type, as SoundCloud's Android player does. + */ +@Composable +fun NowPlayingContentSoundCloud( + state: NowPlayingContentState, + actions: NowPlayingContentActions, +) { + // The waveform keeps the app's own primary on every track (owner's call), so it is read here, + // before the artwork scheme is entered. + val appPrimary = MaterialTheme.colorScheme.primary + NowPlayingExpressiveTheme(state = state) { + NowPlayingSoundCloudLayout(state = state, actions = actions, waveformColor = appPrimary) + } +} + +@Composable +private fun NowPlayingSoundCloudLayout( + state: NowPlayingContentState, + actions: NowPlayingContentActions, + waveformColor: Color, +) { + val colors = MaterialTheme.colorScheme + val glassOn = LocalLiquidGlassEnabled.current + val backdrop = rememberBackdrop(colors.surface) + val viewModel: SoundCloudPlayerViewModel = koinViewModel() + val waveform by viewModel.waveform.collectAsStateWithLifecycle() + val trackComments by viewModel.comments.collectAsStateWithLifecycle() + var showOutputSheet by rememberSaveable { mutableStateOf(false) } + // The same condition the other styles show their inline video on. + val showVideo = state.screenData.canvasData == null && state.screenData.isVideo && state.shouldShowVideo + var showSubtitle by rememberSaveable { mutableStateOf(true) } + + // Off the media item, prefix stripped (see NowPlayingContentState.videoId). + val videoId = state.videoId.orEmpty() + LaunchedEffect(videoId) { viewModel.load(videoId) } + // No scroll and no collapsing toolbar here, as in the Apple Music style. + LaunchedEffect(Unit) { actions.onToolbarVisibilityChange(false) } + + val timeline = state.timelineState + val durationMs = timeline.total.coerceAtLeast(0L) + val isPlaying = state.controllerState.isPlaying + // Paused as the listener sees it. The player also reports "not playing" while it buffers (a track + // change, a seek), sometimes a beat before it reports loading, so only a pause that lasts shows as + // one; a tap on the card shows its own outcome at once. + var paused by remember { mutableStateOf(!isPlaying && !timeline.loading) } + LaunchedEffect(isPlaying, timeline.loading) { + if (isPlaying) { + paused = false + } else if (!timeline.loading) { + delay(PAUSE_SETTLE_MS) + paused = true + } + } + val togglePlayPause = { + paused = !paused + actions.onUIEvent(UIEvent.PlayPause) + } + var scrubbing by remember { mutableStateOf(false) } + var scrubMs by remember { mutableLongStateOf(0L) } + // After a scrub the player takes a moment to report the new spot; holding the scrubbed value + // until it does keeps the waveform from springing back to where the drag started. + var pendingSeekMs by remember { mutableStateOf(null) } + val latestReported by rememberUpdatedState(timeline.current) + LaunchedEffect(pendingSeekMs) { + val target = pendingSeekMs ?: return@LaunchedEffect + withTimeoutOrNull(SEEK_SETTLE_TIMEOUT_MS) { snapshotFlow { latestReported }.first { abs(it - target) < SEEK_SETTLED_WITHIN_MS } } + pendingSeekMs = null + } + // Not running while a scrub settles either: it then follows the reports, so it starts again from + // where the player actually landed instead of gliding there from where the drag began. + val playhead = rememberSteadyPlayhead(rawMs = timeline.current, running = isPlaying && !scrubbing && pendingSeekMs == null) + // Read where it is used (the waveform draws it every frame) rather than here, so a moving + // playhead redraws the waveform without recomposing the whole card each frame. + val position = remember { { if (scrubbing) scrubMs else pendingSeekMs ?: playhead.value } } + // Read while drawing, so the pause and fold animations redraw without recomposing. + val pausedProgress = animateFloatAsState(if (paused) 1f else 0f, tween(PAUSE_FADE_MS), label = "soundCloudPaused") + val waveformFold = animateFloatAsState(if (paused && !scrubbing) 1f else 0f, tween(PAUSE_FADE_MS), label = "soundCloudFold") + val stripAlpha = { 1f - pausedProgress.value } + val pausedBlur = + remember(pausedProgress) { + Modifier.graphicsLayer { + val radius = PAUSED_BLUR.toPx() * pausedProgress.value + renderEffect = if (radius > 0f) BlurEffect(radius, radius, TileMode.Clamp) else null + } + } + // The lower block's height, which places the lyric line for the blur and the scrim under it. + val lowerBlockHeight = remember { mutableIntStateOf(0) } + // Remembered, so the shell's recompositions (one per position report) do not redraw the artwork, + // the blur over it and the glass that samples it. + val surface = colors.surface + val scrim = colors.scrim + val artworkModifier = + remember(glassOn, backdrop, pausedBlur, surface, scrim, lowerBlockHeight) { + Modifier + // The glass source while glass is on: the artwork as it is shown, dim and scrim + // included. The glass buttons are its siblings, never inside it. + .then(if (glassOn) Modifier.layerBackdrop(backdrop) else Modifier) + .then(pausedBlur) + // Drawn after the artwork's own content, so it covers a video surface too, which + // takes no Compose effect: the paused dim, then from the card's bottom up to the line + // of lyrics the scheme's scrim over the blurred cover. The scrim ramps in over the band + // above the line, on the same curve as the blur, and keeps darkening to the bottom. + .drawWithContent { + drawContent() + drawRect(color = surface, alpha = PAUSED_DIM * pausedProgress.value) + val lineY = lyricLineY(lowerBlockHeight.intValue) + val fadeTop = lineY - LOWER_FADE_BAND.toPx() + val atLine = scrim.copy(alpha = LOWER_SCRIM_AT_LINE) + drawRect( + brush = smoothScrimBrush(from = scrim.copy(alpha = 0f), to = atLine, startY = fadeTop, endY = lineY), + topLeft = Offset(0f, fadeTop), + size = Size(size.width, lineY - fadeTop), + ) + if (size.height > lineY) { + drawRect( + brush = + smoothScrimBrush( + from = atLine, + to = scrim.copy(alpha = LOWER_SCRIM_AT_BOTTOM), + startY = lineY, + endY = size.height, + ), + topLeft = Offset(0f, lineY), + size = Size(size.width, size.height - lineY), + ) + } + } + } + + val timedComments = remember(trackComments) { trackComments.comments.mapNotNull { it.toTimedComment() } } + val shownComment by remember(timedComments) { + derivedStateOf { + val now = position() + timedComments.lastOrNull { now in it.positionMs until it.positionMs + COMMENT_SHOWN_MS } + } + } + + Column( + modifier = + Modifier + .fillMaxSize() + .background(colors.surface) + .windowInsetsPadding(WindowInsets.statusBars), + ) { + Box( + modifier = + Modifier + .fillMaxWidth() + .weight(1f) + .clip(CARD_SHAPE) + .background(colors.surfaceContainer) + .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null, onClick = togglePlayPause), + ) { + SoundCloudArtwork( + state = state, + actions = actions, + showVideo = showVideo, + showSubtitle = showSubtitle, + lowerBlockHeight = lowerBlockHeight, + modifier = artworkModifier, + ) + + androidx.compose.animation.AnimatedVisibility( + visible = !scrubbing, + enter = fadeIn(), + exit = fadeOut(), + modifier = + Modifier + .align(Alignment.TopStart) + .padding(CARD_PADDING) + .fillMaxWidth(LABELS_WIDTH_FRACTION), + ) { + Column(horizontalAlignment = Alignment.Start) { + SoundCloudLabel( + text = state.screenData.nowPlayingTitle, + textStyle = typo().titleMedium.copy(fontSize = 16.sp), + color = colors.onSurface, + maxLines = TITLE_MAX_LINES, + stripAlpha = stripAlpha, + ) + SoundCloudLabel( + text = state.screenData.artistName, + textStyle = typo().bodyMedium.copy(fontSize = 14.sp), + color = colors.onSurfaceVariant, + maxLines = ARTIST_MAX_LINES, + stripAlpha = stripAlpha, + onClick = actions.onNavigateToArtist, + ) + Spacer(modifier = Modifier.height(6.dp)) + SongInfoChip(stripAlpha = stripAlpha, onClick = actions.onShowInfo) + } + } + + androidx.compose.animation.AnimatedVisibility( + visible = !scrubbing, + enter = fadeIn(), + exit = fadeOut(), + modifier = Modifier.align(Alignment.TopEnd).padding(CARD_PADDING), + ) { + Column( + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(10.dp), + ) { + RoundButton(backdrop = backdrop, icon = state.dismissIcon, size = 40.dp, iconSize = 24.dp, onClick = actions.onDismiss) + // The output button Classic and M3 Expressive use, opening the same sheet. + CornerIconButton( + backdrop = backdrop, + icon = SimpIcons.Headphones, + tint = if (state.castState.isRemote) colors.primary else colors.onSurface, + onClick = { showOutputSheet = true }, + ) + CornerIconButton( + backdrop = backdrop, + icon = SimpIcons.Lyrics, + tint = colors.onSurface, + onClick = actions.onShowFullscreenLyrics, + ) + // A music video gets what the other styles put over theirs: fullscreen, and the + // lyrics as subtitles on the video (on by default, as there). + if (showVideo) { + CornerIconButton( + backdrop = backdrop, + icon = SimpIcons.Fullscreen, + tint = colors.onSurface, + onClick = actions.onEnterFullscreenVideo, + ) + if (state.screenData.lyricsData != null) { + CornerIconButton( + backdrop = backdrop, + icon = if (showSubtitle) SimpIcons.SubtitlesOff else SimpIcons.Subtitles, + tint = colors.onSurface, + onClick = { showSubtitle = !showSubtitle }, + ) + } + } + } + } + + androidx.compose.animation.AnimatedVisibility( + visible = paused && !scrubbing, + enter = fadeIn(tween(PAUSE_FADE_MS)), + exit = fadeOut(tween(PAUSE_FADE_MS)), + modifier = + Modifier + .align(Alignment.Center) + .fillMaxWidth() + .padding(horizontal = CARD_PADDING), + ) { + // Left to right in every language, as every player style's transport is. + LeftToRight { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically, + ) { + // A video also gets the other styles' 5-second steps, on the outside. + if (showVideo) { + RoundButton(backdrop = backdrop, icon = SimpIcons.Replay5, size = 44.dp, iconSize = 26.dp) { + actions.onUIEvent(UIEvent.Backward) + } + } + RoundButton(backdrop = backdrop, icon = SimpIcons.SkipPrevious, size = 52.dp, iconSize = 30.dp) { + actions.onUIEvent(UIEvent.Previous) + } + RoundButton(backdrop = backdrop, icon = SimpIcons.PlayArrow, size = 76.dp, iconSize = 44.dp, onClick = togglePlayPause) + RoundButton( + backdrop = backdrop, + icon = SimpIcons.SkipNext, + size = 52.dp, + iconSize = 30.dp, + enabled = state.controllerState.isNextAvailable, + ) { + actions.onUIEvent(UIEvent.Next) + } + if (showVideo) { + RoundButton(backdrop = backdrop, icon = SimpIcons.Forward5, size = 44.dp, iconSize = 26.dp) { + actions.onUIEvent(UIEvent.Forward) + } + } + } + } + } + + androidx.compose.animation.AnimatedVisibility( + visible = scrubbing, + enter = fadeIn(), + exit = fadeOut(), + modifier = Modifier.align(Alignment.Center), + ) { + Text( + text = formatDuration(scrubMs) + " | " + formatDuration(durationMs), + style = typo().titleLarge.copy(fontSize = 24.sp, fontWeight = FontWeight.Normal), + color = colors.onSurface, + ) + } + + Column( + modifier = + Modifier + .align(Alignment.BottomCenter) + .fillMaxWidth() + .onSizeChanged { lowerBlockHeight.intValue = it.height } + .padding(bottom = CARD_PADDING), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + // Height reserved whether or not a comment is up, so the waveform never moves. + Box(modifier = Modifier.height(COMMENT_ROW_HEIGHT), contentAlignment = Alignment.Center) { + AnimatedContent( + targetState = shownComment, + transitionSpec = { fadeIn() togetherWith fadeOut() }, + label = "soundCloudComment", + ) { comment -> + if (comment != null) TimedCommentBubble(comment) + } + } + Spacer(modifier = Modifier.height(LYRIC_STRIP_SPACING)) + // The Apple Music style's line of lyrics, lit as it is sung; a tap opens the lyrics page. + AppleMusicLyricStrip( + state = state, + typography = rememberAppleMusicTypography(), + onClick = actions.onShowFullscreenLyrics, + ) + Spacer(modifier = Modifier.height(6.dp)) + if (timeline.isLive) { + SoundCloudLabel( + text = timeline.lengthLabel(), + textStyle = typo().labelMedium, + color = colors.onSurface, + maxLines = 1, + stripAlpha = { 1f }, + ) + } else { + // Time runs left to right in every language: the waveform's drag, its playhead and its label. + LeftToRight { + SoundCloudWaveform( + bars = waveform?.takeIf { it.videoId == videoId }?.bars, + position = position, + durationMs = durationMs, + playedColor = waveformColor, + fold = { waveformFold.value }, + onScrubStart = { + scrubMs = position() + scrubbing = true + }, + onScrub = { scrubMs = it }, + onScrubEnd = { target -> + scrubbing = false + if (durationMs > 0L) { + pendingSeekMs = target + actions.onSliderChange(target * 100f / durationMs) + actions.onSliderChangeFinished() + } + }, + ) + } + } + Spacer(modifier = Modifier.height(12.dp)) + CommentBox( + backdrop = backdrop, + onOpen = actions.onShowComments, + onReaction = actions.onWriteComment, + modifier = Modifier.padding(horizontal = CARD_PADDING), + ) + } + } + + // Left to right in every language, as the action rows of the other styles are. + LeftToRight { + Row( + modifier = + Modifier + .fillMaxWidth() + .windowInsetsPadding(WindowInsets.navigationBars) + .height(ACTION_ROW_HEIGHT) + .padding(horizontal = 8.dp), + horizontalArrangement = Arrangement.SpaceEvenly, + verticalAlignment = Alignment.CenterVertically, + ) { + // Like and comments (the track's counts), shuffle and repeat (how it plays), the queue, then more. + CountButton( + icon = if (state.likeStatus) SimpIcons.Favorite else SimpIcons.FavoriteBorder, + tint = if (state.likeStatus) colors.primary else colors.onSurface, + count = state.screenData.songInfoData?.like?.toCompactCount(), + onClick = { actions.onUIEvent(UIEvent.ToggleLike) }, + ) + CountButton( + icon = SimpIcons.CommentOutline, + count = trackComments.takeIf { it.videoId == videoId }?.count, + onClick = actions.onShowComments, + ) + RippleIconButton( + imageVector = SimpIcons.Shuffle, + tint = if (state.controllerState.isShuffle) colors.primary else colors.onSurface, + onClick = { actions.onUIEvent(UIEvent.Shuffle) }, + ) + val repeatState = state.controllerState.repeatState + RippleIconButton( + imageVector = if (repeatState is RepeatState.One) SimpIcons.RepeatOne else SimpIcons.Repeat, + tint = if (repeatState is RepeatState.None) colors.onSurface else colors.primary, + onClick = { actions.onUIEvent(UIEvent.Repeat) }, + ) + // Not on Desktop, whose capsule player already opens the queue; a phone has no other way in. + if (getPlatform() != Platform.Desktop) { + RippleIconButton(imageVector = SimpIcons.QueueMusic, tint = colors.onSurface, onClick = actions.onShowQueue) + } + RippleIconButton(imageVector = SimpIcons.MoreVert, tint = colors.onSurface, onClick = actions.onShowMoreSheet) + } + } + } + + if (showOutputSheet) { + AudioOutputSheetHost( + castState = state.castState, + onDismiss = { showOutputSheet = false }, + ) + } +} + +/** + * The artwork filling the card, or what plays in its place: a canvas (Spotify's, or Apple Music's + * animated cover) cropped to the card, or the music video at its own shape on black. A video surface + * is composited under the window, so Compose cannot fade IT; the cover is drawn over the canvas + * instead and fades out once the canvas has its first frame. + * + * The cover stays composed under a video too, as M3 Expressive keeps it: its onSuccess is the only + * thing that hands the artwork to the shell, and without it the scheme this style is drawn in sits on + * the app's seed colour for the whole video. + */ +@Composable +private fun SoundCloudArtwork( + state: NowPlayingContentState, + actions: NowPlayingContentActions, + showVideo: Boolean, + showSubtitle: Boolean, + lowerBlockHeight: IntState, + modifier: Modifier = Modifier, +) { + val canvas = state.screenData.canvasData + Box(modifier = modifier.fillMaxSize()) { + var canvasReady by remember(canvas?.url) { mutableStateOf(false) } + if (canvas != null) { + MediaPlayerView( + url = canvas.url, + modifier = Modifier.fillMaxSize(), + cropToBounds = true, + onFirstFrame = { canvasReady = true }, + ) + } + val coverAlpha by animateFloatAsState( + targetValue = if (showVideo || (canvas != null && canvasReady)) 0f else 1f, + animationSpec = tween(COVER_FADE_MS), + label = "soundCloudCover", + ) + var artworkUrl by remember(state.screenData.thumbnailURL) { mutableStateOf(state.screenData.thumbnailURL) } + val request = + ImageRequest + .Builder(LocalPlatformContext.current) + .data(artworkUrl) + .diskCachePolicy(CachePolicy.ENABLED) + .diskCacheKey(artworkUrl + "BIGGER") + .crossfade(550) + .build() + AsyncImage( + model = request, + contentDescription = null, + onSuccess = { actions.onArtworkBitmap(it.result.image.toImageBitmap()) }, + onError = { + val fallback = artworkUrl?.replace("maxresdefault", "hqdefault") + if (fallback != null && fallback != artworkUrl) artworkUrl = fallback + }, + contentScale = ContentScale.Crop, + placeholder = rememberHolderPainter(), + error = rememberHolderPainter(), + modifier = Modifier.fillMaxSize().alpha(coverAlpha), + ) + // From the bottom up to the line of lyrics the cover melts into a blurred copy of itself, faded + // in by a DstIn mask on the smoothstep curve the scrim over it uses. At the top of the ramp the + // copy is fully transparent, so it leaves no seam (ArtistScreen's header does the same). It fades + // with the cover, so a canvas or a video that takes over gets the scrim alone. Below Android 12 + // blur is a no-op and the copy matches the cover. + val scrim = MaterialTheme.colorScheme.scrim + val lowerBlur = + remember(lowerBlockHeight, scrim) { + Modifier + .graphicsLayer { compositingStrategy = CompositingStrategy.Offscreen } + .drawWithContent { + drawContent() + val lineY = lyricLineY(lowerBlockHeight.intValue) + drawRect( + brush = smoothScrimBrush(from = scrim.copy(alpha = 0f), to = scrim, startY = lineY - LOWER_FADE_BAND.toPx(), endY = lineY), + blendMode = BlendMode.DstIn, + ) + }.blur(LOWER_BLUR) + } + AsyncImage( + model = request, + contentDescription = null, + contentScale = ContentScale.Crop, + modifier = Modifier.fillMaxSize().alpha(coverAlpha).then(lowerBlur), + ) + if (showVideo) { + Box(modifier = Modifier.fillMaxSize().background(MaterialTheme.colorScheme.surfaceContainerLowest)) { + MediaPlayerViewWithSubtitle( + playerName = MAIN_PLAYER, + // fillMaxWidth, never fillMaxSize: a free height lets the video keep its shape. + modifier = Modifier.fillMaxWidth().align(Alignment.Center), + shouldShowSubtitle = showSubtitle, + shouldScaleDownSubtitle = true, + isInPipMode = state.isInPipMode, + timelineState = state.timelineState, + lyricsData = state.screenData.lyricsData?.lyrics, + translatedLyricsData = state.screenData.lyricsData?.translatedLyrics?.first, + mainTextStyle = typo().bodyLarge, + translatedTextStyle = typo().bodyMedium, + ) + } + } + } +} + +/** + * SoundCloud's label: text on black strips, one per line and only as wide as that line, so a title + * that wraps reads as a stack of strips. [stripAlpha] is read while drawing; paused, the strips give + * way to plain text over the dimmed artwork. + */ +@Composable +private fun SoundCloudLabel( + text: String, + textStyle: TextStyle, + color: Color, + maxLines: Int, + stripAlpha: () -> Float, + onClick: (() -> Unit)? = null, +) { + val strip = MaterialTheme.colorScheme.surfaceContainerLowest + var layout by remember { mutableStateOf(null) } + Text( + text = text, + // Room above and below every line, the first and last included, for the strip around it. + style = + textStyle.copy( + lineHeight = LABEL_LINE_HEIGHT, + lineHeightStyle = LineHeightStyle(LineHeightStyle.Alignment.Center, LineHeightStyle.Trim.None), + ), + color = color, + maxLines = maxLines, + overflow = TextOverflow.Ellipsis, + onTextLayout = { layout = it }, + modifier = + Modifier + .then(if (onClick != null) Modifier.clickable(onClick = onClick) else Modifier) + .drawBehind { + val lines = layout ?: return@drawBehind + val alpha = stripAlpha() + if (alpha <= 0f) return@drawBehind + val padX = LABEL_PADDING_X.toPx() + val gap = LABEL_LINE_GAP.toPx() + // Text coordinates sit padX in from this box, so each strip reaches padX past both + // ends of its line. + for (line in 0 until lines.lineCount) { + val left = lines.getLineLeft(line) + val top = lines.getLineTop(line) + gap / 2 + drawRect( + color = strip, + alpha = alpha, + topLeft = Offset(left, top), + size = Size(lines.getLineRight(line) - left + 2 * padX, lines.getLineBottom(line) - gap / 2 - top), + ) + } + }.padding(horizontal = LABEL_PADDING_X), + ) +} + +/** The "Song info" chip under the labels, on a strip of its own that fades with theirs. */ +@Composable +private fun SongInfoChip( + stripAlpha: () -> Float, + onClick: () -> Unit, +) { + val colors = MaterialTheme.colorScheme + Row( + modifier = + Modifier + .drawBehind { drawRect(color = colors.surfaceContainerLowest, alpha = stripAlpha()) } + .clickable(onClick = onClick) + .padding(horizontal = LABEL_PADDING_X, vertical = 2.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Icon(imageVector = SimpIcons.GraphicEq, contentDescription = null, tint = colors.onSurface, modifier = Modifier.size(14.dp)) + Spacer(modifier = Modifier.width(5.dp)) + Text( + text = stringResource(Res.string.song_info), + style = typo().bodyMedium.copy(fontSize = 12.sp), + color = colors.onSurface, + maxLines = 1, + ) + } +} + +/** + * A round button: liquid glass over the artwork while the app's glass is on, otherwise the black + * circle SoundCloud gives its dismiss control and its paused transport. + */ +@Composable +private fun RoundButton( + backdrop: PlatformBackdrop, + icon: ImageVector, + size: Dp, + iconSize: Dp, + enabled: Boolean = true, + tint: Color = MaterialTheme.colorScheme.onSurface, + onClick: () -> Unit, +) { + if (!LocalLiquidGlassEnabled.current) { + FilledIconButton( + onClick = onClick, + enabled = enabled, + modifier = Modifier.size(size), + colors = + IconButtonDefaults.filledIconButtonColors( + containerColor = MaterialTheme.colorScheme.surfaceContainerLowest, + contentColor = tint, + disabledContainerColor = MaterialTheme.colorScheme.surfaceContainerLowest.copy(alpha = 0.6f), + disabledContentColor = tint.copy(alpha = 0.38f), + ), + ) { + Icon(imageVector = icon, contentDescription = null, modifier = Modifier.size(iconSize)) + } + return + } + // A 1dp highlight, as on the other small round glass buttons: a circle this size catches only a + // short arc of the default directional rim and reads as rimless. + LiquidGlassContainer(backdrop = backdrop, modifier = Modifier.size(size), highlight = Highlight(width = 1.dp)) { + IconButton(onClick = onClick, enabled = enabled, modifier = Modifier.fillMaxSize()) { + Icon( + imageVector = icon, + contentDescription = null, + tint = if (enabled) tint else tint.copy(alpha = 0.38f), + modifier = Modifier.size(iconSize), + ) + } + } +} + +/** + * Follow and output in the card's corner: plain icons on the artwork as SoundCloud draws them, or + * glass circles matching the dismiss button above them while the app's glass is on. + */ +@Composable +private fun CornerIconButton( + backdrop: PlatformBackdrop, + icon: ImageVector, + tint: Color, + onClick: () -> Unit, +) { + if (LocalLiquidGlassEnabled.current) { + RoundButton(backdrop = backdrop, icon = icon, size = 40.dp, iconSize = 24.dp, tint = tint, onClick = onClick) + } else { + RippleIconButton(imageVector = icon, tint = tint, onClick = onClick) + } +} + +/** An icon with its count beside it, as SoundCloud draws like and comments. */ +@Composable +private fun CountButton( + icon: ImageVector, + count: String?, + onClick: () -> Unit, + tint: Color = MaterialTheme.colorScheme.onSurface, +) { + TextButton( + onClick = onClick, + colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.onSurface), + // Tighter than a TextButton's 12dp, so the six buttons a phone shows fit across 360dp. + contentPadding = PaddingValues(horizontal = 8.dp), + ) { + Icon(imageVector = icon, contentDescription = null, tint = tint, modifier = Modifier.size(24.dp)) + if (count != null) { + Spacer(modifier = Modifier.width(6.dp)) + Text(text = count, style = typo().labelLarge, color = LocalContentColor.current) + } + } +} + +/** + * SoundCloud's comment box under the waveform: a tap opens the comments sheet, an emoji opens it + * with that emoji already typed. + */ +@Composable +private fun CommentBox( + backdrop: PlatformBackdrop, + onOpen: () -> Unit, + onReaction: (String) -> Unit, + modifier: Modifier = Modifier, +) { + val colors = MaterialTheme.colorScheme + Row( + modifier = + modifier + .fillMaxWidth() + .height(COMMENT_BOX_HEIGHT) + .then( + // Glass while the app's glass is on; static, since a press would bulge a pill this + // wide (the tap still ripples). + if (LocalLiquidGlassEnabled.current) { + Modifier.liquidGlass(backdrop = backdrop, shape = CircleShape, interactive = false) + } else { + Modifier.clip(CircleShape).background(colors.surfaceContainerLowest.copy(alpha = 0.6f)) + }, + ).clip(CircleShape) + .clickable(onClick = onOpen) + .padding(start = 16.dp, end = 6.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + text = stringResource(Res.string.comment_placeholder), + style = typo().bodyMedium, + color = colors.onSurfaceVariant, + maxLines = 1, + modifier = Modifier.weight(1f), + ) + QUICK_REACTIONS.forEach { emoji -> + Text( + text = emoji, + style = typo().bodyMedium.copy(fontSize = 18.sp), + modifier = + Modifier + .clip(CircleShape) + .clickable { onReaction(emoji) } + .padding(horizontal = 8.dp, vertical = 4.dp), + ) + } + } +} + +@Composable +private fun TimedCommentBubble(comment: TimedComment) { + Row( + modifier = Modifier.padding(horizontal = 24.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + AsyncImage( + model = comment.authorAvatar, + contentDescription = null, + placeholder = rememberHolderPainter(), + error = rememberHolderPainter(), + contentScale = ContentScale.Crop, + modifier = Modifier.size(28.dp).clip(CircleShape), + ) + Spacer(modifier = Modifier.width(8.dp)) + Text( + text = comment.text, + style = typo().bodyMedium.copy(fontSize = 13.sp), + color = MaterialTheme.colorScheme.onSurface, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = + Modifier + .clip(RoundedCornerShape(14.dp)) + .background(MaterialTheme.colorScheme.surfaceContainerLowest.copy(alpha = 0.6f)) + .padding(horizontal = 12.dp, vertical = 5.dp), + ) + } +} + +/** + * The top of the lyric line in the card's coordinates. The lower block (timed comments, lyric line, + * waveform, comment box) sits on the card's bottom edge, and the line is the second thing in it. + */ +private fun DrawScope.lyricLineY(lowerBlockHeight: Int): Float = size.height - lowerBlockHeight + (COMMENT_ROW_HEIGHT + LYRIC_STRIP_SPACING).toPx() + +/** A comment placed at the first moment its text names. */ +private data class TimedComment( + val id: String, + val positionMs: Long, + val authorAvatar: String?, + val text: String, +) + +/** + * The comment at the first "m:ss" or "h:mm:ss" its text names — the same rule descriptions use for + * their seek links — or null when it names none. A moment past the end of the track simply never + * comes up. + */ +private fun YouTubeComment.toTimedComment(): TimedComment? { + val match = TIMESTAMP_REGEX.find(text) ?: return null + val (first, second, third) = match.destructured + val a = first.toLongOrNull() ?: return null + val b = second.toLongOrNull()?.takeIf { it < 60 } ?: return null + val seconds = + if (third.isEmpty()) { + a * 60 + b + } else { + val c = third.toLongOrNull()?.takeIf { it < 60 } ?: return null + a * 3600 + b * 60 + c + } + return TimedComment(id = id, positionMs = seconds * 1000, authorAvatar = authorAvatar, text = text) +} + +/** 48000 → "48K", 1234 → "1.2K", 1500000 → "1.5M". */ +private fun Int.toCompactCount(): String = + when { + this >= 1_000_000 -> compact(this / 1_000_000.0, "M") + this >= 1_000 -> compact(this / 1_000.0, "K") + else -> toString() + } + +private fun compact( + value: Double, + suffix: String, +): String { + val tenths = (value * 10).roundToInt() + val text = if (value >= 10 || tenths % 10 == 0) (tenths / 10).toString() else "${tenths / 10}.${tenths % 10}" + return text + suffix +} + +// Read off SoundCloud's own player (Mobbin, iOS 2024, and the owner's iOS captures), converted from +// its 390pt-wide frame. +private val CARD_SHAPE = RoundedCornerShape(20.dp) +private val CARD_PADDING = 16.dp +private const val LABELS_WIDTH_FRACTION = 0.78f +private const val TITLE_MAX_LINES = 3 +private const val ARTIST_MAX_LINES = 2 +private val LABEL_LINE_HEIGHT = 1.75.em +private val LABEL_LINE_GAP = 3.dp +private val LABEL_PADDING_X = 6.dp +private val COMMENT_ROW_HEIGHT = 32.dp +private val LYRIC_STRIP_SPACING = 4.dp + +// The lower card, from the bottom up to the line of lyrics, sits on a blurred copy of the cover under +// the scheme's scrim (the owner's call, so the white line reads on any cover). Both ramp in over this +// band above the line; the scrim then keeps darkening down to the bottom. +private val LOWER_FADE_BAND = 80.dp +private val LOWER_BLUR = 32.dp +private const val LOWER_SCRIM_AT_LINE = 0.6f +private const val LOWER_SCRIM_AT_BOTTOM = 0.85f +private val COMMENT_BOX_HEIGHT = 40.dp +private val QUICK_REACTIONS = listOf("🔥", "👏", "🥹") +private val ACTION_ROW_HEIGHT = 64.dp +private const val COVER_FADE_MS = 400 + +// Paused, the artwork blurs (Android 12 and later, and Desktop) and sits under the page colour. +private val PAUSED_BLUR = 20.dp +private const val PAUSED_DIM = 0.45f +private const val PAUSE_FADE_MS = 250 + +// How long "not playing, not loading" must last before it counts as a pause. +private const val PAUSE_SETTLE_MS = 250L + +// A comment stays up this long after the moment it names. +private const val COMMENT_SHOWN_MS = 4_500L +private const val SEEK_SETTLE_TIMEOUT_MS = 2_000L +private const val SEEK_SETTLED_WITHIN_MS = 1_000L diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentState.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentState.kt index 6f535519de..b081d726ce 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentState.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentState.kt @@ -146,6 +146,12 @@ class NowPlayingContentState( * its video frame from this one value, so a frame and the spacer that measures it cannot drift. */ val videoAspectRatio: Float = 16f / 9, + /** + * The YouTube id of the track playing, "Video" prefix stripped, or null before anything plays. + * Read off the media item rather than the queue's track, which is null while the queue restored + * at startup is still being rebuilt: the same id the comments sheet uses. + */ + val videoId: String? = null, ) /** @@ -169,6 +175,8 @@ class NowPlayingContentActions( val onShowAddToPlaylist: () -> Unit, /** Opens the comments sheet for the track playing. */ val onShowComments: () -> Unit, + /** Opens the comments sheet with [draft] already in its box (the SoundCloud style's emoji). */ + val onWriteComment: (draft: String) -> Unit, val onShowFullscreenLyrics: () -> Unit, val onShowVoteDialog: () -> Unit, /** Writes the lyrics timing offset — the same value Settings › Lyrics edits. */ diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/applemusic/AppleMusicLyricStrip.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/applemusic/AppleMusicLyricStrip.kt index 95ffc355c7..0a1d0e97ce 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/applemusic/AppleMusicLyricStrip.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/applemusic/AppleMusicLyricStrip.kt @@ -265,7 +265,7 @@ private fun sweepX( * goes straight there. While [running] is false it simply follows the reports. */ @Composable -private fun rememberSweepPlayhead( +internal fun rememberSweepPlayhead( rawMs: Long, running: Boolean, ): State { diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/soundcloud/SoundCloudWaveform.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/soundcloud/SoundCloudWaveform.kt new file mode 100644 index 0000000000..274557e079 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/soundcloud/SoundCloudWaveform.kt @@ -0,0 +1,312 @@ +package com.maxrave.simpmusic.ui.screen.player.content.soundcloud + +import androidx.compose.animation.core.Animatable +import androidx.compose.animation.core.LinearEasing +import androidx.compose.animation.core.tween +import androidx.compose.animation.core.withInfiniteAnimationFrameNanos +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.background +import androidx.compose.foundation.gestures.detectHorizontalDragGestures +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.offset +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.State +import androidx.compose.runtime.derivedStateOf +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableLongStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshotFlow +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.drawBehind +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.drawscope.DrawScope +import androidx.compose.ui.graphics.drawscope.clipRect +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.dp +import com.maxrave.domain.mediaservice.player.WAVEFORM_BARS_PER_SECOND +import com.maxrave.simpmusic.extension.formatDuration +import com.maxrave.simpmusic.ui.theme.typo +import kotlin.math.abs +import kotlin.math.ceil +import kotlin.math.floor +import kotlin.math.roundToInt +import kotlin.math.roundToLong + +/** + * SoundCloud's seek bar. The track's waveform slides past a playhead fixed at the centre, played + * bars in [playedColor] and the rest in the scheme's onSurface, each mirrored as a faint reflection + * under the baseline. The time sits on a black label at the playhead. + * + * Dragging moves the waveform itself, so a drag to the LEFT goes forward in time: the opposite of a + * slider. While [bars] is null (still decoding, or a backend with no waveform) the same bars are + * drawn as a flat line, so the bar still scrolls and still scrubs; when they arrive they rise out of + * that line from the playhead outward, and a track change sinks them back first. [fold] (0 open, + * 1 folded, read while drawing) sinks the bars into one line along the baseline, as SoundCloud does + * while paused. + */ +@Composable +internal fun SoundCloudWaveform( + bars: FloatArray?, + position: () -> Long, + durationMs: Long, + playedColor: Color, + fold: () -> Float, + onScrubStart: () -> Unit, + onScrub: (Long) -> Unit, + onScrubEnd: (Long) -> Unit, + modifier: Modifier = Modifier, +) { + val density = LocalDensity.current + // The step and the bar width are whole pixels, so every bar sits at the same fraction of a pixel and + // the waveform glides as one. With a 3.8px step each bar landed on a different fraction, sharp + // beside smeared, and that pattern crawled across the bars like an old TV. The origin itself stays + // fractional: snapping it too made the waveform tick along in one-pixel steps. + val stepPx = with(density) { BAR_STEP.roundToPx() }.coerceAtLeast(2) + val pxPerMs = stepPx * WAVEFORM_BARS_PER_SECOND / 1000f + // Read while drawing (and once per drag start), never during composition: the playhead moves + // every frame, and only the canvas has to follow it. The label recomposes once a second. + val currentPosition by rememberUpdatedState(position) + // The whole second the playhead is in, so the label recomposes once a second (formatDuration is + // @Composable, so it is called below, not in here). + val elapsedSecondMs by remember { derivedStateOf { currentPosition().let { if (it < 0L) it else it / 1000L * 1000L } } } + val latestDuration by rememberUpdatedState(durationMs) + // The drag handler outlives recompositions (pointerInput is keyed on the scale only), so it + // must reach the caller's current callbacks, not the ones from when the gesture started. + val currentOnScrubStart by rememberUpdatedState(onScrubStart) + val currentOnScrub by rememberUpdatedState(onScrub) + val currentOnScrubEnd by rememberUpdatedState(onScrubEnd) + var elapsedWidth by remember { mutableIntStateOf(0) } + var labelHeight by remember { mutableIntStateOf(0) } + val playedReflection = playedColor.copy(alpha = REFLECTION_ALPHA) + val colors = MaterialTheme.colorScheme + val unplayedColor = colors.onSurface + val unplayedReflection = unplayedColor.copy(alpha = REFLECTION_ALPHA) + // The bars on screen, and how far they have risen out of the flat line (0 flat, 1 risen). A track's + // waveform arrives a few seconds after the track, once it is decoded: it rises out of the line + // instead of popping in, and on a track change the old one sinks back into the line first. + var shownBars by remember { mutableStateOf(null) } + val rise = remember { Animatable(0f) } + LaunchedEffect(bars) { + if (bars === shownBars) return@LaunchedEffect + if (shownBars != null) rise.animateTo(0f, tween(SINK_MS, easing = LinearEasing)) + shownBars = bars + if (bars != null) rise.animateTo(1f, tween(RISE_MS, easing = LinearEasing)) + } + + BoxWithConstraints( + modifier = + modifier + .fillMaxWidth() + .height(WAVEFORM_HEIGHT) + .pointerInput(pxPerMs) { + var scrubMs = 0L + detectHorizontalDragGestures( + onDragStart = { + scrubMs = currentPosition() + currentOnScrubStart() + }, + onDragEnd = { currentOnScrubEnd(scrubMs) }, + onDragCancel = { currentOnScrubEnd(scrubMs) }, + onHorizontalDrag = { change, dragAmount -> + change.consume() + scrubMs = (scrubMs - dragAmount / pxPerMs).roundToLong().coerceIn(0L, latestDuration.coerceAtLeast(0L)) + currentOnScrub(scrubMs) + }, + ) + }, + ) { + val playheadX = floor(with(density) { maxWidth.toPx() } / 2f) + Canvas(modifier = Modifier.fillMaxWidth().height(WAVEFORM_HEIGHT)) { + val positionMs = currentPosition() + val shown = shownBars + val barCount = shown?.size ?: (durationMs / 1000f * WAVEFORM_BARS_PER_SECOND).toInt() + if (barCount <= 0) return@Canvas + val step = stepPx.toFloat() + val barWidth = BAR_WIDTH.roundToPx().coerceIn(1, stepPx - 1).toFloat() + val baseline = BAR_MAX_UP.roundToPx().toFloat() + val maxDown = BAR_MAX_DOWN.toPx() + val gap = BASELINE_GAP.roundToPx().toFloat() + val folded = fold() + val open = 1f - folded + val lineHeight = FOLDED_LINE_HEIGHT.roundToPx().coerceAtLeast(1).toFloat() + // x of bar 0, so that the moment the song has reached sits exactly under the playhead. + val origin = playheadX - positionMs / 1000f * WAVEFORM_BARS_PER_SECOND * step + val first = floor(-origin / step).toInt().coerceAtLeast(0) + val last = ceil((size.width - origin) / step).toInt().coerceAtMost(barCount - 1) + // Bars near the playhead rise first and the rise travels outward (a sink runs back the + // same way): each bar starts a little after its neighbour nearer the playhead, and eases + // in and out on smoothstep. + val risen = rise.value + val playheadBar = (playheadX - origin) / step + val reach = (size.width / 2f / step).coerceAtLeast(1f) + + fun levelAt(i: Int): Float { + val target = shown?.getOrNull(i) ?: return FLAT_LEVEL + val t = (risen * (1f + RISE_STAGGER) - abs(i - playheadBar) / reach * RISE_STAGGER).coerceIn(0f, 1f) + return FLAT_LEVEL + (target - FLAT_LEVEL) * t * t * (3f - 2f * t) + } + + fun DrawScope.drawBars( + color: Color, + reflection: Color, + lineAlpha: Float, + ) { + for (i in first..last) { + val x = origin + i * step + val level = levelAt(i) + val up = level * baseline * open + drawRect(color = color, topLeft = Offset(x, baseline - up), size = Size(barWidth, up)) + drawRect(color = reflection, topLeft = Offset(x, baseline + gap), size = Size(barWidth, level * maxDown * open)) + } + // Folding, the bars sink into this line as it comes up. + val start = origin + first * step + val end = origin + last * step + barWidth + if (lineAlpha > 0f && end > start) { + drawRect( + color = color, + alpha = lineAlpha, + topLeft = Offset(start, baseline - lineHeight), + size = Size(end - start, lineHeight), + ) + } + } + // Drawn twice and cut at the playhead, the way the word-by-word lyrics light a word + // (AppleMusicLyricStrip): the bars slide past the cut every frame, so a bar fills in as it + // crosses instead of changing colour whole. + clipRect(left = playheadX) { drawBars(unplayedColor, unplayedReflection, folded * FOLDED_UNPLAYED_ALPHA) } + clipRect(right = playheadX) { drawBars(playedColor, playedReflection, folded) } + } + Row( + modifier = + Modifier + .onSizeChanged { labelHeight = it.height } + // Where SoundCloud sets it: standing on the baseline, its divider on the playhead, + // the time played to the left and the length to the right. + .offset { + IntOffset( + (playheadX - elapsedWidth - 2 * TIME_LABEL_PADDING.toPx()).roundToInt(), + BAR_MAX_UP.roundToPx() - labelHeight, + ) + } + // Paused, the label loses its strip like the card's other labels. + .drawBehind { drawRect(color = colors.surfaceContainerLowest, alpha = 1f - fold()) } + .padding(horizontal = TIME_LABEL_PADDING, vertical = 1.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + text = formatDuration(elapsedSecondMs), + style = typo().labelSmall, + color = colors.onSurface, + modifier = Modifier.onSizeChanged { elapsedWidth = it.width }, + ) + Box( + modifier = + Modifier + .padding(horizontal = TIME_LABEL_PADDING) + .width(1.dp) + .height(10.dp) + .background(colors.outlineVariant), + ) + Text(text = formatDuration(durationMs), style = typo().labelSmall, color = colors.onSurfaceVariant) + } + } +} + +// Read off SoundCloud's own player (Mobbin, iOS, 2024), converted from its 390pt-wide frame. +private val BAR_WIDTH = 2.2.dp +private val BAR_STEP = 3.8.dp +private val BAR_MAX_UP = 64.dp +private val BAR_MAX_DOWN = 38.dp +private val BASELINE_GAP = 1.dp +internal val WAVEFORM_HEIGHT = BAR_MAX_UP + BASELINE_GAP + BAR_MAX_DOWN +private val TIME_LABEL_PADDING = 5.dp +// Folded, what has played stays lit and what is still to come is a faint hairline (the owner's iOS +// captures of SoundCloud paused). +private val FOLDED_LINE_HEIGHT = 1.dp +private const val FOLDED_UNPLAYED_ALPHA = 0.35f +private const val REFLECTION_ALPHA = 0.45f + +// A waveform that arrives rises out of the flat line over RISE_MS, the farthest bar starting +// RISE_STAGGER of the way in; the one a track change replaces sinks back over SINK_MS first. +// 700/250 ms read as slow (owner, 2026-11-06). +private const val RISE_MS = 350 +private const val SINK_MS = 150 +private const val RISE_STAGGER = 0.6f + +/** + * The playhead the waveform scrolls by, steady where the reports are not. + * + * On Desktop mpv moves `time-pos` only a few times a second and the handler smooths it but holds + * rather than step back, so the reported position runs, pauses and runs again. The Apple Music lyric + * strip's playhead leans toward each report within 150 ms and passed that on: measured on a screen + * recording, the bars scrolled fast for about 0.2 s and nearly stopped for the next 0.2 s, over and + * over. This one runs on the frame clock and eases toward the last report carried forward at 1x over + * [STEADY_DRIFT_MS], so the end of a hold slows it by a few percent for a moment and never moves it + * back. Only a gap wider than [STEADY_SNAP_MS] (a seek, a new track) is jumped across: a first + * version also jumped whenever a report broke 400 ms from the run, which fired at the end of every + * hold and threw the bars back. + */ +@Composable +internal fun rememberSteadyPlayhead( + rawMs: Long, + running: Boolean, +): State { + val playhead = remember { mutableLongStateOf(rawMs) } + val latestRaw by rememberUpdatedState(rawMs) + LaunchedEffect(running) { + if (!running) { + snapshotFlow { latestRaw }.collect { playhead.longValue = it } + return@LaunchedEffect + } + var position = latestRaw.toDouble() + var reported = latestRaw + var reportedAt = -1L + var lastFrame = -1L + while (true) { + withInfiniteAnimationFrameNanos { now -> + if (reportedAt < 0L || latestRaw != reported) { + reported = latestRaw + reportedAt = now + } + // ponytail: carries the report forward at 1x; at another playback speed the bars trail + // by about (speed - 1) × STEADY_DRIFT_MS. Hand the speed in if that ever shows. + // Capped, so a player that stops reporting does not drag the bars on. + val trend = reported + ((now - reportedAt) / 1_000_000.0).coerceAtMost(STEADY_MAX_CARRY_MS) + val step = if (lastFrame < 0L) 0.0 else (now - lastFrame) / 1_000_000.0 + lastFrame = now + position = + if (abs(trend - position) > STEADY_SNAP_MS) { + trend + } else { + position + step + (trend - position) * (step / STEADY_DRIFT_MS).coerceAtMost(1.0) + } + playhead.longValue = position.roundToLong() + } + } + } + return playhead +} + +private const val STEADY_DRIFT_MS = 3_000.0 +private const val STEADY_SNAP_MS = 2_000.0 +private const val STEADY_MAX_CARRY_MS = 1_000.0 +private const val FLAT_LEVEL = 0.04f diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/SoundCloudPlayerViewModel.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/SoundCloudPlayerViewModel.kt new file mode 100644 index 0000000000..aced8ffeb9 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/SoundCloudPlayerViewModel.kt @@ -0,0 +1,120 @@ +package com.maxrave.simpmusic.viewModel + +import androidx.lifecycle.viewModelScope +import com.maxrave.domain.data.model.comments.YouTubeComment +import com.maxrave.domain.repository.SongRepository +import com.maxrave.domain.utils.Resource +import com.maxrave.logger.Logger +import com.maxrave.simpmusic.viewModel.base.BaseViewModel +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.firstOrNull +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +/** A track's waveform: one level per 1 / WAVEFORM_BARS_PER_SECOND seconds, each 0..1. */ +class TrackWaveform( + val videoId: String, + val bars: FloatArray, +) + +/** The first page of a track's YouTube comments, as the SoundCloud style reads it. */ +data class TrackComments( + val videoId: String = "", + val comments: List = emptyList(), + val count: String? = null, +) + +/** + * What the SoundCloud Now Playing style draws beyond the shared contract, for the track on screen: + * its waveform and its comments (the ones naming a moment float over the waveform). + * + * Loading is driven by the screen ([load]) rather than by the player, so nothing is decoded or + * fetched while the player is closed or another style is in use. + */ +class SoundCloudPlayerViewModel( + private val songRepository: SongRepository, +) : BaseViewModel() { + private val _waveform = MutableStateFlow(null) + val waveform: StateFlow = _waveform.asStateFlow() + + private val _comments = MutableStateFlow(TrackComments()) + val comments: StateFlow = _comments.asStateFlow() + + private var waveformVideoId: String? = null + private var waveformJob: Job? = null + private var commentsVideoId: String? = null + private var commentsJob: Job? = null + + /** Loads [videoId]'s waveform and comments. Reopening the player on the same track reuses them. */ + fun load(videoId: String) { + if (videoId.isBlank()) return + loadWaveform(videoId) + loadComments(videoId) + } + + /** + * The track is asked for the moment it shows up, which is often before the player has resolved its + * stream: the format stored for it can still be a previous session's, already refused (403), and the + * fresh one lands a second or so later. So a miss is asked again a few times while the track is + * still on screen, and a track came back to without a waveform is tried afresh. + */ + private fun loadWaveform(videoId: String) { + if (_waveform.value?.videoId == videoId) return + if (videoId == waveformVideoId && waveformJob?.isActive == true) return + waveformVideoId = videoId + waveformJob?.cancel() + _waveform.value = null + waveformJob = + viewModelScope.launch { + WAVEFORM_ATTEMPT_DELAYS_MS.forEachIndexed { attempt, wait -> + delay(wait) + val bars = + try { + withContext(Dispatchers.IO) { mediaPlayerHandler.player.loadWaveform(videoId) } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Logger.w(tag, "Waveform for $videoId threw: ${e.message}") + null + } + if (bars != null && bars.isNotEmpty()) { + _waveform.value = TrackWaveform(videoId, bars) + return@launch + } + Logger.d(tag, "No waveform for $videoId yet, attempt ${attempt + 1} of ${WAVEFORM_ATTEMPT_DELAYS_MS.size}") + } + Logger.w(tag, "Gave up on a waveform for $videoId after ${WAVEFORM_ATTEMPT_DELAYS_MS.size} attempts") + } + } + + private fun loadComments(videoId: String) { + if (videoId == commentsVideoId) return + commentsVideoId = videoId + commentsJob?.cancel() + _comments.value = TrackComments(videoId = videoId) + commentsJob = + viewModelScope.launch { + val result = songRepository.getComments(videoId).firstOrNull() + val page = (if (result is Resource.Success) result.data else null) ?: return@launch + _comments.value = + TrackComments( + videoId = videoId, + // YouTube sometimes repeats a comment; CommentsViewModel drops the repeats too. + comments = page.comments.distinctBy { it.id }, + count = page.header?.countShort ?: page.header?.countText, + ) + } + } + + private companion object { + // Right away, then while the player resolves the stream (it took 1.3 s in the case that + // showed this up), then twice more for a slow extraction. + val WAVEFORM_ATTEMPT_DELAYS_MS = listOf(0L, 3_000L, 8_000L, 20_000L) + } +} diff --git a/core b/core index f2a065d605..c1bc55d022 160000 --- a/core +++ b/core @@ -1 +1 @@ -Subproject commit f2a065d605c0f199edc3126a0b4e1c06d1e6f9d2 +Subproject commit c1bc55d0225489f24820db1cd688dc64fc247283 diff --git a/scripts/mpv-linux/Dockerfile b/scripts/mpv-linux/Dockerfile index f11f9f445b..8080999fa7 100644 --- a/scripts/mpv-linux/Dockerfile +++ b/scripts/mpv-linux/Dockerfile @@ -69,6 +69,12 @@ RUN git clone --depth 1 --branch v7.351.0 --recursive \ # asplit + amix - the wet/dry blend: afir's dry/wet are input/output GAIN, not # a mix, so the dry path is split off before afir and mixed back after # (amix `weights` is a runtime command -> live mix slider). +# +# The three after amix measure the SoundCloud Now Playing style's waveform +# (MpvWaveformReader), on a second, silent handle: +# asetnsamples - cuts the audio into one frame per waveform bar, +# astats - measures each frame's RMS and exports it as frame metadata, +# ametadata - prints that metadata to a file the app reads back. # --------------------------------------------------------------------------- RUN git clone --depth 1 --branch n7.1.1 https://github.com/FFmpeg/FFmpeg.git ffmpeg && \ cd ffmpeg && \ @@ -77,7 +83,7 @@ RUN git clone --depth 1 --branch n7.1.1 https://github.com/FFmpeg/FFmpeg.git ffm --enable-shared --disable-static \ --disable-programs --disable-doc --disable-debug \ --disable-encoders --disable-muxers --disable-devices \ - --disable-filters --enable-filter=aresample,atempo,rubberband,scale,format,aformat,anull,null,volume,lavfi,acompressor,firequalizer,equalizer,highpass,lowpass,dynaudnorm,loudnorm,aecho,afir,amovie,asplit,amix \ + --disable-filters --enable-filter=aresample,atempo,rubberband,scale,format,aformat,anull,null,volume,lavfi,acompressor,firequalizer,equalizer,highpass,lowpass,dynaudnorm,loudnorm,aecho,afir,amovie,asplit,amix,asetnsamples,astats,ametadata \ --enable-openssl --enable-protocol=https,http,tls,file,pipe,crypto,hls,data \ --enable-libdav1d \ --enable-version3 \ From ed2358051f7b9d8a164091fc480c31d57797949c Mon Sep 17 00:00:00 2001 From: maxrave-dev Date: Fri, 6 Nov 2026 21:47:59 +0700 Subject: [PATCH 16/29] feat(player): refine the SoundCloud style and add music app color presets --- CLAUDE.md | 2 +- .../composeResources/values/strings.xml | 1 - .../simpmusic/ui/screen/home/SettingScreen.kt | 71 +++-- .../content/NowPlayingContentSoundCloud.kt | 245 +++++++++++++----- .../applemusic/AppleMusicLyricsView.kt | 16 +- .../content/applemusic/AppleMusicShared.kt | 16 +- 6 files changed, 254 insertions(+), 97 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 897fc83ffe..527a389bae 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1119,7 +1119,7 @@ if (getPlatform() == Platform.Android) { - **Session**: three keys (`discord_access_token`, `discord_refresh_token`, `discord_token_expires_at`) in the settings file, so they ride in backups like every other sign-in. Access tokens last about 7 days; `DiscordRepository.accessToken()` refreshes under a mutex when under 10 minutes are left, and an `invalid_grant` on refresh clears the session, which logs the user out and tears the RPC down through `loggedIn`. On a Full build the old `discord_token` is cleared at start: it was a whole-account token this build no longer uses. Log out does not call Discord's revoke endpoint; SimpMusic stays in the user's Authorized Apps until they remove it. - Both playback handlers now hold a `RichPresenceClient` (`core/data/.../mediaservice/RichPresenceClient.kt`) built by `createRichPresenceClient(discordRepository)`, and run on `richPresenceEnabled && discordRepository.loggedIn`; the rest of the RPC job is unchanged. Login Sync no longer carries Discord. -- **SoundCloud Now Playing style (2026-11-06)**: a fourth style, `NOW_PLAYING_STYLE_SOUNDCLOUD` (`content/NowPlayingContentSoundCloud.kt`), laid out after SoundCloud's own player as captured on Mobbin and in the owner's own iOS captures: the artwork (or canvas, or the video at its own shape) fills a rounded card; title (up to 3 lines), artist (2) and a "Song info" chip sit top-left on black strips, ONE STRIP PER LINE as wide as that line (drawn per line from `onTextLayout`, line height 1.75em with `LineHeightStyle.Trim.None` so the first and last lines get the same room); dismiss, the output button Classic and M3E use (`Headphones` → `AudioOutputSheetHost`, primary while casting) and Lyrics (`SimpIcons.Lyrics`, opening the fullscreen lyrics page) run down the top-right corner, joined while a music video plays by Fullscreen and the subtitles toggle (lyrics over the video, on by default as in the other styles); paused on a video, the transport gains the other styles' ±5s steps on its outer ends (the first version had no video controls at all, and the owner: "code xong bỏ bê cái video hả"). The transport, the waveform and the action row sit in `LeftToRight`, the app's RTL rule; like · comments · shuffle · repeat · queue · more (`MoreVert`) below the card, like and comments with counts, the queue on phones only (Desktop's capsule player already opens it; the owner: a phone has no other way in). The owner moved Lyrics into the corner (a Lyrics button leading the bottom row, then one beside Queue, both read as random to him) and removed the follow button the first version had: no other Now Playing style has one. The owner rejected new icons for this style ("dùng cũ đi") and its share button: every icon is one the app already uses for the same action. The style follows the app's liquid-glass setting (`LocalLiquidGlassEnabled`): on, the round buttons (dismiss, output, lyrics, the paused transport) are glass circles with a 1dp highlight and the comment box a static glass pill, refracting the artwork, which is the backdrop source with its dim and scrim drawn into it; off, SoundCloud's black circles and plain corner icons. The label strips stay black either way. Above the waveform runs the Apple Music style's `AppleMusicLyricStrip` (owner's request; a tap opens the fullscreen lyrics page), and from the card's bottom up to that line the cover melts into a 32dp-blurred copy of itself (ArtistScreen's DstIn-masked copy; it fades with the cover, so a canvas or video gets the scrim alone) under the scheme's `scrim`, both ramping in on smoothstep over the 80dp above the line, the scrim 60% at the line and 85% at the bottom. The line's position comes from the lower block's measured height (`lyricLineY`). A plain 75% scrim over a 64dp ramp came first; the owner: "fade kiểu gì v? blur đâu, smooth đâu". Playing, the card shows only artwork and labels and a tap anywhere pauses; paused, the artwork blurs (20dp `BlurEffect` in a `graphicsLayer`, Android 12+ and Desktop) under a 45% `surface` scrim drawn as a sibling (a video surface takes no Compose effect, but what is drawn above it covers it), the strips fade to plain text, the waveform folds into a 2dp line, and previous / play / next come up across the middle (the owner's call: SoundCloud has controls). "Paused" is not the raw `isPlaying`: the player also reports not-playing while it buffers, sometimes a beat before `timeline.loading`, so only not-playing-and-not-loading for 250 ms counts, while a tap on the card flips it at once. Under the waveform sits a "Comment…" box with 🔥 👏 🥹: the box opens the comments sheet, an emoji opens it with that emoji typed (`NowPlayingContentActions.onWriteComment` → `CommentsBottomSheet(initialDraft)`, applied only while the sheet shows the video it opened on). Every colour is a role of the artwork-seeded dark scheme `NowPlayingExpressiveTheme` builds for the M3 Expressive style: the black label strips and buttons are `surfaceContainerLowest`, text is `onSurface`/`onSurfaceVariant`. The one exception is where SoundCloud puts its orange: the waveform's played part is the APP's `primary`, read in `NowPlayingContentSoundCloud` before the artwork scheme is entered and the same on every track, crossfade included (owner's call; it first followed the artwork scheme's primary). No colour is written into these files; the first build used the `seed` constant and the owner caught it. Its extra data comes from `SoundCloudPlayerViewModel`, which the screen drives (`load(videoId)`) so nothing is decoded or fetched while the player is closed or another style is in use; the id is `NowPlayingContentState.videoId`, the shell's prefix-stripped id off the media item. +- **SoundCloud Now Playing style (2026-11-06)**: a fourth style, `NOW_PLAYING_STYLE_SOUNDCLOUD` (`content/NowPlayingContentSoundCloud.kt`), laid out after SoundCloud's own player as captured on Mobbin and in the owner's own iOS captures: the artwork (or canvas, or the video in a frame of its own shape, `state.videoAspectRatio`, fitted above the lower block and centred in the card when it fits, so its subtitles land on the picture rather than under the comment box) fills a rounded card; title (up to 3 lines), artist (2) and a play-count chip (▶ plus the YouTube view count, compact as "12M"; hidden until the track's info arrives, a tap opens the info sheet) sit top-left on black strips, ONE STRIP PER LINE as wide as that line (drawn per line from `onTextLayout`, line height 1.75em with `LineHeightStyle.Trim.None` so the first and last lines get the same room); dismiss, the output button Classic and M3E use (`Headphones` → `AudioOutputSheetHost`, primary while casting) and Lyrics (`SimpIcons.Lyrics`; it and a tap on the lyric line open the Apple Music style's Lyrics page, `AppleMusicLyricsView` with `showBottomCluster = false` over `AppleMusicArtworkBackdrop`, and a back button on the floating buttons' 38dp circle at the start of the page's header (`AppleMusicCompactHeader(onBack)`, or Back on Android) returns to the card; that header keeps only ⋮, since like and add-to-liked live on the card; dimmed and doing nothing while the track has no lyrics, as the Apple Music style's Lyrics pill is disabled then) run down the top-right corner, then add-to-YouTube-Liked (signed in only, a tick once liked) and add-to-playlist with the other styles' actions, joined while a music video plays by Fullscreen and the subtitles toggle (lyrics over the video, on by default as in the other styles); paused on a video, the transport gains the other styles' ±5s steps on its outer ends (the first version had no video controls at all, and the owner: "code xong bỏ bê cái video hả"). The transport, the waveform and the action row sit in `LeftToRight`, the app's RTL rule; like · comments · shuffle · repeat · queue · more (`MoreVert`) below the card with no counts (owner's call: the heart is the app's own like, `controllerState.isLiked` with `ToggleLike` as in the other styles, and has no count), the queue on every platform as in the other three styles. The owner moved Lyrics into the corner (a Lyrics button leading the bottom row, then one beside Queue, both read as random to him) and removed the follow button the first version had: no other Now Playing style has one. The owner rejected new icons for this style ("dùng cũ đi") and its share button: every icon is one the app already uses for the same action. The style follows the app's liquid-glass setting (`LocalLiquidGlassEnabled`): on, the round buttons (dismiss, output, lyrics, the paused transport) are glass circles with a 1dp highlight and the comment box a static glass pill, refracting the artwork, which is the backdrop source with its dim and scrim drawn into it; off, SoundCloud's black circles and plain corner icons. The label strips stay black either way. Above the waveform runs the Apple Music style's `AppleMusicLyricStrip` (owner's request; a tap opens the fullscreen lyrics page), and from the card's bottom up to that line the cover melts into a 32dp-blurred copy of itself (ArtistScreen's DstIn-masked copy; it fades with the cover, so a canvas or video gets the scrim alone) under the scheme's `scrim`, both ramping in on smoothstep over the 80dp above the line, the scrim 60% at the line and 85% at the bottom. The line's position comes from the lower block's measured height (`lyricLineY`). A plain 75% scrim over a 64dp ramp came first; the owner: "fade kiểu gì v? blur đâu, smooth đâu". Playing, the card shows only artwork and labels and a tap anywhere pauses; paused, the artwork blurs (20dp `BlurEffect` in a `graphicsLayer`, Android 12+ and Desktop) under a 45% `surface` scrim drawn as a sibling (a video surface takes no Compose effect, but what is drawn above it covers it), the strips fade to plain text, the waveform folds into a 2dp line, and previous / play / next come up across the middle (the owner's call: SoundCloud has controls). "Paused" is not the raw `isPlaying`: the player also reports not-playing while it buffers, sometimes a beat before `timeline.loading`, so only not-playing-and-not-loading for 250 ms counts, while a tap on the card flips it at once. Under the waveform sits a "Comment…" box with 🔥 👏 🥹: the box opens the comments sheet, an emoji opens it with that emoji typed (`NowPlayingContentActions.onWriteComment` → `CommentsBottomSheet(initialDraft)`, applied only while the sheet shows the video it opened on). Every colour is a role of the artwork-seeded dark scheme `NowPlayingExpressiveTheme` builds for the M3 Expressive style: the black label strips and buttons are `surfaceContainerLowest`, text is `onSurface`/`onSurfaceVariant`. The one exception is where SoundCloud puts its orange: the waveform's played part is the APP's `primary`, read in `NowPlayingContentSoundCloud` before the artwork scheme is entered and the same on every track, crossfade included (owner's call; it first followed the artwork scheme's primary). No colour is written into these files; the first build used the `seed` constant and the owner caught it. Its extra data comes from `SoundCloudPlayerViewModel`, which the screen drives (`load(videoId)`) so nothing is decoded or fetched while the player is closed or another style is in use; the id is `NowPlayingContentState.videoId`, the shell's prefix-stripped id off the media item. - **The waveform is asked for before the stream is ready.** The screen asks the moment a track appears, while the player may still be replacing the format stored for it — on 2026-11-06 a previous session's URL answered 403 and the fresh one landed 1.3 s later, so the Desktop source check refused the dead URL and the track never got a waveform (the old ViewModel never asked twice). The ViewModel now asks again at 3, 8 and 20 s while the track is on screen and afresh when a track without one comes back, and every failure branch in both readers logs under `Waveform`. On Android the reader reads the format's length only after opening the first chunk, because opening is what makes the resolver replace a stale format. - **The cover stays composed under a video.** Its `onSuccess` is the only thing that hands the artwork to the shell (`setBitmap`, reset to null on every track change), and `NowPlayingExpressiveTheme` falls back to the app `seed` (`#8ECAE6`) without it. The first version skipped the cover while a video played, so every video track drew the waveform and the rest of the style cyan. M3 Expressive keeps its cover under video for the same reason. - **Waveform** (`content/soundcloud/SoundCloudWaveform.kt`): bars slide past a playhead fixed at the centre, so dragging LEFT goes forward — the opposite of a slider; while dragging, the labels and controls give way to the time in large type. The step and the bar width are whole pixels while the origin stays fractional. A 3.8px step put each bar on a different fraction of a pixel, sharp beside smeared, and the owner saw that pattern crawl "like an old TV"; with whole-pixel steps every bar shares one fraction and the waveform glides as one. Do not snap the origin as well: that made it tick along in one-pixel steps ("giật quá"). A waveform that arrives (seconds after the track, once decoded) rises out of the flat line over 350ms from the playhead outward, each bar on smoothstep and a little after its neighbour nearer the playhead; a track change sinks the old one back over 150ms first (700/250ms read as slow). It used to swap from flat to bars in one frame (`bars ?: FLAT_LEVEL`), and the owner asked where the animation was. diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index bf52a546cb..fdf61d1400 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -444,7 +444,6 @@ Material 3 Expressive Apple Music SoundCloud - Song info AI translated Lyrics style Classic diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/SettingScreen.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/SettingScreen.kt index 3cfd640dc0..f5de7582ed 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/SettingScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/SettingScreen.kt @@ -2887,18 +2887,18 @@ fun SettingScreen( ) } if (showColorPickerDialog) { + // The primary colour of each music app, as its brand publishes it. Names are brand names and + // are not translated. val presetColors = listOf( - "FF8ECAE6", - "FF4C82EF", - "FF9B72CF", - "FFEF6C9B", - "FFEF5350", - "FFF4A340", - "FFFFCA28", - "FF66BB6A", - "FF26A69A", - "FFBDBDBD", + "FF1ED760" to "Spotify", + "FFFF5500" to "SoundCloud", + "FFFA243C" to "Apple Music", + "FFFF0000" to "YouTube Music", + "FFA238FF" to "Deezer", + "FF3668FF" to "Pandora", + "FFFFA200" to "Audiomack", + "FF1DA0C3" to "Bandcamp", ) var pendingHex by rememberSaveable { mutableStateOf(customThemeColorHex.takeLast(6)) } val parsedColor = parseThemeColorHex(pendingHex) @@ -2907,24 +2907,47 @@ fun SettingScreen( title = { Text(text = stringResource(Res.string.custom_color), style = typo().titleSmall) }, text = { Column { - presetColors.chunked(5).forEach { rowColors -> - Row(modifier = Modifier.padding(vertical = 4.dp)) { - rowColors.forEach { hex -> + // Four across: at five, a cell is too narrow for "SoundCloud" under its swatch. + presetColors.chunked(4).forEach { rowColors -> + Row(modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp)) { + rowColors.forEach { (hex, name) -> val color = parseThemeColorHex(hex) ?: Color.Gray val isSelected = pendingHex.equals(hex.takeLast(6), ignoreCase = true) - Box( + Column( modifier = Modifier - .padding(4.dp) - .size(36.dp) - .clip(CircleShape) - .background(color) - .border( - width = if (isSelected) 3.dp else 0.dp, - color = if (isSelected) MaterialTheme.colorScheme.onSurface else Color.Transparent, - shape = CircleShape, - ).clickable { pendingHex = hex.takeLast(6) }, - ) + .weight(1f) + .clip(RoundedCornerShape(12.dp)) + .clickable { pendingHex = hex.takeLast(6) } + .padding(vertical = 4.dp), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + Box( + modifier = + Modifier + .size(40.dp) + .clip(CircleShape) + .background(color) + .border( + width = if (isSelected) 3.dp else 0.dp, + color = if (isSelected) MaterialTheme.colorScheme.onSurface else Color.Transparent, + shape = CircleShape, + ), + ) + Spacer(Modifier.height(6.dp)) + Text( + text = name, + style = typo().bodySmall, + color = + if (isSelected) { + MaterialTheme.colorScheme.onSurface + } else { + MaterialTheme.colorScheme.onSurfaceVariant + }, + textAlign = TextAlign.Center, + maxLines = 2, + ) + } } } } diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentSoundCloud.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentSoundCloud.kt index 80744647b6..51650ea255 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentSoundCloud.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentSoundCloud.kt @@ -1,6 +1,7 @@ package com.maxrave.simpmusic.ui.screen.player.content import androidx.compose.animation.AnimatedContent +import androidx.compose.animation.Crossfade import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.tween import androidx.compose.animation.fadeIn @@ -11,8 +12,8 @@ import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.WindowInsets @@ -27,15 +28,12 @@ import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.windowInsetsPadding import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.FilledIconButton import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.IconButtonDefaults -import androidx.compose.material3.LocalContentColor import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text -import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.IntState import androidx.compose.runtime.LaunchedEffect @@ -68,6 +66,7 @@ import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.text.TextLayoutResult import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight @@ -90,6 +89,7 @@ import com.maxrave.domain.mediaservice.handler.RepeatState import com.maxrave.simpmusic.Platform import com.maxrave.simpmusic.expect.ui.MediaPlayerView import com.maxrave.simpmusic.expect.ui.MediaPlayerViewWithSubtitle +import com.maxrave.simpmusic.expect.ui.PlatformBackHandler import com.maxrave.simpmusic.expect.ui.PlatformBackdrop import com.maxrave.simpmusic.expect.ui.layerBackdrop import com.maxrave.simpmusic.expect.ui.rememberBackdrop @@ -104,16 +104,18 @@ import com.maxrave.simpmusic.ui.component.RippleIconButton import com.maxrave.simpmusic.ui.component.TIMESTAMP_REGEX import com.maxrave.simpmusic.ui.component.liquidGlass import com.maxrave.simpmusic.ui.component.rememberHolderPainter +import com.maxrave.simpmusic.ui.icon.AddCircleOutline +import com.maxrave.simpmusic.ui.icon.CheckCircle import com.maxrave.simpmusic.ui.icon.CommentOutline import com.maxrave.simpmusic.ui.icon.Favorite import com.maxrave.simpmusic.ui.icon.FavoriteBorder import com.maxrave.simpmusic.ui.icon.Forward5 import com.maxrave.simpmusic.ui.icon.Fullscreen -import com.maxrave.simpmusic.ui.icon.GraphicEq import com.maxrave.simpmusic.ui.icon.Headphones import com.maxrave.simpmusic.ui.icon.Lyrics import com.maxrave.simpmusic.ui.icon.MoreVert import com.maxrave.simpmusic.ui.icon.PlayArrow +import com.maxrave.simpmusic.ui.icon.PlaylistAdd import com.maxrave.simpmusic.ui.icon.QueueMusic import com.maxrave.simpmusic.ui.icon.Repeat import com.maxrave.simpmusic.ui.icon.RepeatOne @@ -125,11 +127,14 @@ import com.maxrave.simpmusic.ui.icon.SkipPrevious import com.maxrave.simpmusic.ui.icon.Subtitles import com.maxrave.simpmusic.ui.icon.SubtitlesOff import com.maxrave.simpmusic.ui.screen.player.content.applemusic.AppleMusicLyricStrip +import com.maxrave.simpmusic.ui.screen.player.content.applemusic.AppleMusicLyricsView +import com.maxrave.simpmusic.ui.screen.player.content.applemusic.AppleMusicView import com.maxrave.simpmusic.ui.screen.player.content.applemusic.AudioOutputSheetHost import com.maxrave.simpmusic.ui.screen.player.content.applemusic.rememberAppleMusicTypography import com.maxrave.simpmusic.ui.screen.player.content.soundcloud.SoundCloudWaveform import com.maxrave.simpmusic.ui.screen.player.content.soundcloud.rememberSteadyPlayhead import com.maxrave.simpmusic.ui.theme.LocalLiquidGlassEnabled +import com.maxrave.simpmusic.ui.theme.seed import com.maxrave.simpmusic.ui.theme.typo import com.maxrave.simpmusic.viewModel.SoundCloudPlayerViewModel import com.maxrave.simpmusic.viewModel.UIEvent @@ -140,7 +145,6 @@ import org.jetbrains.compose.resources.stringResource import org.koin.compose.viewmodel.koinViewModel import simpmusic.composeapp.generated.resources.Res import simpmusic.composeapp.generated.resources.comment_placeholder -import simpmusic.composeapp.generated.resources.song_info import kotlin.math.abs import kotlin.math.roundToInt @@ -168,8 +172,87 @@ fun NowPlayingContentSoundCloud( // The waveform keeps the app's own primary on every track (owner's call), so it is read here, // before the artwork scheme is entered. val appPrimary = MaterialTheme.colorScheme.primary - NowPlayingExpressiveTheme(state = state) { - NowPlayingSoundCloudLayout(state = state, actions = actions, waveformColor = appPrimary) + // The Apple Music style's Lyrics page, borrowed without its bottom cluster (owner's call). + var showLyrics by rememberSaveable { mutableStateOf(false) } + // As the Apple Music style does: every track change starts with no lyrics until they arrive, so + // only a track that still has none after the wait sends the page back to the card. + LaunchedEffect(state.screenData.lyricsData, showLyrics) { + if (!showLyrics || state.screenData.lyricsData != null) return@LaunchedEffect + delay(SOUNDCLOUD_LYRICS_GRACE_MS) + showLyrics = false + } + Crossfade(targetState = showLyrics, animationSpec = tween(300), label = "soundCloudView") { lyrics -> + if (lyrics) { + SoundCloudLyricsPage(state = state, actions = actions, onBack = { showLyrics = false }) + } else { + NowPlayingExpressiveTheme(state = state) { + NowPlayingSoundCloudLayout( + state = state, + actions = actions, + waveformColor = appPrimary, + // Nothing without lyrics, as the Apple Music style's Lyrics pill is disabled then. + onOpenLyrics = { if (state.screenData.lyricsData != null) showLyrics = true }, + ) + } + } + } +} + +/** + * The Apple Music style's Lyrics page as that style draws it — frosted cover, compact header, the + * app's lyrics renderer and its floating buttons — minus the bottom cluster. The header (or Back on + * Android) returns to the card. + */ +@Composable +private fun SoundCloudLyricsPage( + state: NowPlayingContentState, + actions: NowPlayingContentActions, + onBack: () -> Unit, +) { + val paletteColor = state.startColor.value + val seedColor = if (paletteColor == Color.Black) seed else paletteColor + val localDensity = LocalDensity.current + PlatformBackHandler(enabled = true, onBack = onBack) + Box(modifier = Modifier.fillMaxSize().background(Color.Black)) { + AppleMusicArtworkBackdrop(state = state, actions = actions, seedColor = seedColor) + AppleMusicLyricsView( + state = state, + actions = actions, + typography = rememberAppleMusicTypography(), + viewState = AppleMusicView.LYRICS, + onSelectView = {}, + activePillContainer = Color.Transparent, + activePillContent = Color.Transparent, + deviceVolumeController = null, + outputName = null, + onOpenOutput = {}, + showBottomCluster = false, + onBack = onBack, + ) + // The Apple Music style's grabber, which this page leaves room for; Desktop draws none on its + // Lyrics page either. + if (getPlatform() != Platform.Desktop) { + Box( + modifier = + Modifier + .align(Alignment.TopCenter) + .padding(top = with(localDensity) { WindowInsets.statusBars.getTop(localDensity).toDp() }) + .size(width = 64.dp, height = SOUNDCLOUD_GRABBER_HEIGHT) + .clickable( + indication = null, + interactionSource = remember { MutableInteractionSource() }, + ) { actions.onDismiss() }, + contentAlignment = Alignment.Center, + ) { + Box( + modifier = + Modifier + .size(width = 36.dp, height = 5.dp) + .clip(RoundedCornerShape(50)) + .background(Color.White.copy(alpha = 0.35f)), + ) + } + } } } @@ -178,6 +261,7 @@ private fun NowPlayingSoundCloudLayout( state: NowPlayingContentState, actions: NowPlayingContentActions, waveformColor: Color, + onOpenLyrics: () -> Unit, ) { val colors = MaterialTheme.colorScheme val glassOn = LocalLiquidGlassEnabled.current @@ -346,8 +430,20 @@ private fun NowPlayingSoundCloudLayout( stripAlpha = stripAlpha, onClick = actions.onNavigateToArtist, ) - Spacer(modifier = Modifier.height(6.dp)) - SongInfoChip(stripAlpha = stripAlpha, onClick = actions.onShowInfo) + // Hidden until the track's info has arrived, then faded in. AnimatedContent, so + // the outgoing chip keeps its own count while it fades. + AnimatedContent( + targetState = state.screenData.songInfoData?.viewCount?.toCompactCount(), + transitionSpec = { fadeIn() togetherWith fadeOut() }, + label = "soundCloudPlayCount", + ) { count -> + if (count != null) { + Column { + Spacer(modifier = Modifier.height(6.dp)) + PlayCountChip(count = count, stripAlpha = stripAlpha, onClick = actions.onShowInfo) + } + } + } } } @@ -372,8 +468,25 @@ private fun NowPlayingSoundCloudLayout( CornerIconButton( backdrop = backdrop, icon = SimpIcons.Lyrics, + // Dimmed while the track has no lyrics, when it does nothing. + tint = if (state.screenData.lyricsData != null) colors.onSurface else colors.onSurface.copy(alpha = 0.38f), + onClick = onOpenLyrics, + ) + // The other styles' add-to-YouTube-Liked (signed in only, a tick once liked) and + // add-to-playlist, with the same actions. + if (state.isUserLoggedIn) { + CornerIconButton( + backdrop = backdrop, + icon = if (state.likeStatus) SimpIcons.CheckCircle else SimpIcons.AddCircleOutline, + tint = colors.onSurface, + onClick = actions.onAddToYouTubeLiked, + ) + } + CornerIconButton( + backdrop = backdrop, + icon = SimpIcons.PlaylistAdd, tint = colors.onSurface, - onClick = actions.onShowFullscreenLyrics, + onClick = actions.onShowAddToPlaylist, ) // A music video gets what the other styles put over theirs: fullscreen, and the // lyrics as subtitles on the video (on by default, as there). @@ -478,7 +591,7 @@ private fun NowPlayingSoundCloudLayout( AppleMusicLyricStrip( state = state, typography = rememberAppleMusicTypography(), - onClick = actions.onShowFullscreenLyrics, + onClick = onOpenLyrics, ) Spacer(modifier = Modifier.height(6.dp)) if (timeline.isLive) { @@ -536,18 +649,14 @@ private fun NowPlayingSoundCloudLayout( horizontalArrangement = Arrangement.SpaceEvenly, verticalAlignment = Alignment.CenterVertically, ) { - // Like and comments (the track's counts), shuffle and repeat (how it plays), the queue, then more. - CountButton( - icon = if (state.likeStatus) SimpIcons.Favorite else SimpIcons.FavoriteBorder, - tint = if (state.likeStatus) colors.primary else colors.onSurface, - count = state.screenData.songInfoData?.like?.toCompactCount(), + // Like and comments, shuffle and repeat (how it plays), the queue, then more. No counts + // (owner's call): the like is the app's own, which has none. + RippleIconButton( + imageVector = if (state.controllerState.isLiked) SimpIcons.Favorite else SimpIcons.FavoriteBorder, + tint = if (state.controllerState.isLiked) colors.primary else colors.onSurface, onClick = { actions.onUIEvent(UIEvent.ToggleLike) }, ) - CountButton( - icon = SimpIcons.CommentOutline, - count = trackComments.takeIf { it.videoId == videoId }?.count, - onClick = actions.onShowComments, - ) + RippleIconButton(imageVector = SimpIcons.CommentOutline, tint = colors.onSurface, onClick = actions.onShowComments) RippleIconButton( imageVector = SimpIcons.Shuffle, tint = if (state.controllerState.isShuffle) colors.primary else colors.onSurface, @@ -559,10 +668,7 @@ private fun NowPlayingSoundCloudLayout( tint = if (repeatState is RepeatState.None) colors.onSurface else colors.primary, onClick = { actions.onUIEvent(UIEvent.Repeat) }, ) - // Not on Desktop, whose capsule player already opens the queue; a phone has no other way in. - if (getPlatform() != Platform.Desktop) { - RippleIconButton(imageVector = SimpIcons.QueueMusic, tint = colors.onSurface, onClick = actions.onShowQueue) - } + RippleIconButton(imageVector = SimpIcons.QueueMusic, tint = colors.onSurface, onClick = actions.onShowQueue) RippleIconButton(imageVector = SimpIcons.MoreVert, tint = colors.onSurface, onClick = actions.onShowMoreSheet) } } @@ -659,20 +765,38 @@ private fun SoundCloudArtwork( modifier = Modifier.fillMaxSize().alpha(coverAlpha).then(lowerBlur), ) if (showVideo) { - Box(modifier = Modifier.fillMaxSize().background(MaterialTheme.colorScheme.surfaceContainerLowest)) { - MediaPlayerViewWithSubtitle( - playerName = MAIN_PLAYER, - // fillMaxWidth, never fillMaxSize: a free height lets the video keep its shape. - modifier = Modifier.fillMaxWidth().align(Alignment.Center), - shouldShowSubtitle = showSubtitle, - shouldScaleDownSubtitle = true, - isInPipMode = state.isInPipMode, - timelineState = state.timelineState, - lyricsData = state.screenData.lyricsData?.lyrics, - translatedLyricsData = state.screenData.lyricsData?.translatedLyrics?.first, - mainTextStyle = typo().bodyLarge, - translatedTextStyle = typo().bodyMedium, - ) + BoxWithConstraints(modifier = Modifier.fillMaxSize().background(MaterialTheme.colorScheme.surfaceContainerLowest)) { + // A frame of the video's own shape, as M3 Expressive and the Apple Music style give + // theirs. Without it the view grows to the whole card (its subtitle layer fills its + // parent), so the subtitles sat on the card's bottom edge under the comment box and + // the scrim, and Desktop letterboxed the picture across the whole card. The frame fits + // above the lower block, and stays centred in the card unless that would run it under. + val ratio = state.videoAspectRatio.takeIf { it > 0f } ?: (16f / 9) + val lowerBlock = with(LocalDensity.current) { lowerBlockHeight.intValue.toDp() } + val zone = (maxHeight - lowerBlock).coerceAtLeast(0.dp) + val frameHeight = minOf(maxWidth / ratio, zone) + val frameTop = minOf((maxHeight - frameHeight) / 2, zone - frameHeight).coerceAtLeast(0.dp) + Box( + modifier = + Modifier + .align(Alignment.TopCenter) + .padding(top = frameTop) + .size(width = frameHeight * ratio, height = frameHeight), + ) { + MediaPlayerViewWithSubtitle( + playerName = MAIN_PLAYER, + // fillMaxWidth, never fillMaxSize: a free height lets the video keep its shape. + modifier = Modifier.fillMaxWidth().align(Alignment.Center), + shouldShowSubtitle = showSubtitle, + shouldScaleDownSubtitle = true, + isInPipMode = state.isInPipMode, + timelineState = state.timelineState, + lyricsData = state.screenData.lyricsData?.lyrics, + translatedLyricsData = state.screenData.lyricsData?.translatedLyrics?.first, + mainTextStyle = typo().bodyLarge, + translatedTextStyle = typo().bodyMedium, + ) + } } } } @@ -731,9 +855,13 @@ private fun SoundCloudLabel( ) } -/** The "Song info" chip under the labels, on a strip of its own that fades with theirs. */ +/** + * The track's YouTube view count under the labels, where SoundCloud shows its play count, on a strip + * of its own that fades with theirs. A tap opens the track's info, as the chip did before. + */ @Composable -private fun SongInfoChip( +private fun PlayCountChip( + count: String, stripAlpha: () -> Float, onClick: () -> Unit, ) { @@ -746,10 +874,10 @@ private fun SongInfoChip( .padding(horizontal = LABEL_PADDING_X, vertical = 2.dp), verticalAlignment = Alignment.CenterVertically, ) { - Icon(imageVector = SimpIcons.GraphicEq, contentDescription = null, tint = colors.onSurface, modifier = Modifier.size(14.dp)) - Spacer(modifier = Modifier.width(5.dp)) + Icon(imageVector = SimpIcons.PlayArrow, contentDescription = null, tint = colors.onSurface, modifier = Modifier.size(14.dp)) + Spacer(modifier = Modifier.width(4.dp)) Text( - text = stringResource(Res.string.song_info), + text = count, style = typo().bodyMedium.copy(fontSize = 12.sp), color = colors.onSurface, maxLines = 1, @@ -820,28 +948,6 @@ private fun CornerIconButton( } } -/** An icon with its count beside it, as SoundCloud draws like and comments. */ -@Composable -private fun CountButton( - icon: ImageVector, - count: String?, - onClick: () -> Unit, - tint: Color = MaterialTheme.colorScheme.onSurface, -) { - TextButton( - onClick = onClick, - colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.onSurface), - // Tighter than a TextButton's 12dp, so the six buttons a phone shows fit across 360dp. - contentPadding = PaddingValues(horizontal = 8.dp), - ) { - Icon(imageVector = icon, contentDescription = null, tint = tint, modifier = Modifier.size(24.dp)) - if (count != null) { - Spacer(modifier = Modifier.width(6.dp)) - Text(text = count, style = typo().labelLarge, color = LocalContentColor.current) - } - } -} - /** * SoundCloud's comment box under the waveform: a tap opens the comments sheet, an emoji opens it * with that emoji already typed. @@ -1011,3 +1117,8 @@ private const val PAUSE_SETTLE_MS = 250L private const val COMMENT_SHOWN_MS = 4_500L private const val SEEK_SETTLE_TIMEOUT_MS = 2_000L private const val SEEK_SETTLED_WITHIN_MS = 1_000L + +// How long the Lyrics page waits for a track's lyrics before going back to the card (the Apple Music +// style's wait), and the height of the grabber it draws as that style does. +private const val SOUNDCLOUD_LYRICS_GRACE_MS = 2_500L +private val SOUNDCLOUD_GRABBER_HEIGHT = 28.dp diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/applemusic/AppleMusicLyricsView.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/applemusic/AppleMusicLyricsView.kt index 4f8985a6aa..f06aec7422 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/applemusic/AppleMusicLyricsView.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/applemusic/AppleMusicLyricsView.kt @@ -18,6 +18,7 @@ import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.statusBars +import androidx.compose.foundation.layout.systemBars import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.Icon import androidx.compose.material3.Text @@ -97,6 +98,11 @@ internal fun AppleMusicLyricsView( outputName: String?, onOpenOutput: () -> Unit, modifier: Modifier = Modifier, + // The SoundCloud style borrows this page without the bottom cluster (owner's call): it has its + // own transport on its card, so it returns there through a back button in the header instead of + // the Lyrics pill. + showBottomCluster: Boolean = true, + onBack: (() -> Unit)? = null, dataStoreManager: DataStoreManager = koinInject(), ) { val localDensity = LocalDensity.current @@ -156,7 +162,7 @@ internal fun AppleMusicLyricsView( with(localDensity) { WindowInsets.statusBars.getTop(localDensity).toDp() } + 20.dp, ), ) - AppleMusicCompactHeader(state = state, actions = actions, typography = typography) + AppleMusicCompactHeader(state = state, actions = actions, typography = typography, onBack = onBack) Box( modifier = @@ -312,11 +318,15 @@ internal fun AppleMusicLyricsView( ) } + // Without the cluster, only the gesture bar's room is kept under the lyrics. + if (!showBottomCluster) { + Spacer(modifier = Modifier.height(with(localDensity) { WindowInsets.systemBars.getBottom(localDensity).toDp() })) + } // expand/shrink, not just fade: the Box above holds weight(1f), so removing the cluster // from the layout is what lets the lyrics grow into the freed space — a fade alone would // leave an empty band where the transport used to be. androidx.compose.animation.AnimatedVisibility( - visible = showCluster, + visible = showCluster && showBottomCluster, enter = expandVertically() + fadeIn(), exit = shrinkVertically() + fadeOut(), ) { @@ -341,7 +351,7 @@ internal fun AppleMusicLyricsView( private const val CLUSTER_AUTO_HIDE_MS = 8_000L @Composable -private fun AppleMusicFloatingCircleButton( +internal fun AppleMusicFloatingCircleButton( icon: ImageVector, onClick: () -> Unit, ) { diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/applemusic/AppleMusicShared.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/applemusic/AppleMusicShared.kt index ad0650bb5b..ce80a25997 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/applemusic/AppleMusicShared.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/applemusic/AppleMusicShared.kt @@ -88,6 +88,7 @@ import com.maxrave.simpmusic.ui.component.heartBurst import com.maxrave.simpmusic.ui.component.rememberHeartBurstState import com.maxrave.simpmusic.ui.component.rememberHolderPainter import com.maxrave.simpmusic.ui.icon.AddCircleOutline +import com.maxrave.simpmusic.ui.icon.ArrowBackIosNew import com.maxrave.simpmusic.ui.icon.CheckCircle import com.maxrave.simpmusic.ui.icon.CommentOutline import com.maxrave.simpmusic.ui.icon.FastForward @@ -408,11 +409,19 @@ internal fun AppleMusicCompactHeader( actions: NowPlayingContentActions, typography: AppleMusicTypography, modifier: Modifier = Modifier, + // A back button ahead of the artwork; only the SoundCloud style passes one, to leave its + // borrowed Lyrics page for its card. + onBack: (() -> Unit)? = null, ) { Row( modifier = modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 12.dp), verticalAlignment = Alignment.CenterVertically, ) { + if (onBack != null) { + // On the circle the page's floating buttons sit on. + AppleMusicFloatingCircleButton(icon = SimpIcons.ArrowBackIosNew, onClick = onBack) + Spacer(modifier = Modifier.width(12.dp)) + } AsyncImage( model = ImageRequest @@ -453,7 +462,12 @@ internal fun AppleMusicCompactHeader( } } Spacer(modifier = Modifier.width(12.dp)) - AppleMusicHeaderActions(state = state, actions = actions) + if (onBack != null) { + // The SoundCloud style keeps like and add-to-liked on its card, so only more stays here. + AppleMusicGlyphButton(icon = SimpIcons.MoreVert, onClick = { actions.onShowMoreSheet() }) + } else { + AppleMusicHeaderActions(state = state, actions = actions) + } } } From 87f38a498b43e24b7c5cc8eac04aeac686451eb6 Mon Sep 17 00:00:00 2001 From: maxrave-dev Date: Sat, 7 Nov 2026 01:21:14 +0700 Subject: [PATCH 17/29] feat(automix): place crossfades by the loudness-labelled parts of each track --- CLAUDE.md | 13 ++++++++++++- core | 2 +- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 527a389bae..f63c3e3130 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1124,10 +1124,21 @@ if (getPlatform() == Platform.Android) { - **The cover stays composed under a video.** Its `onSuccess` is the only thing that hands the artwork to the shell (`setBitmap`, reset to null on every track change), and `NowPlayingExpressiveTheme` falls back to the app `seed` (`#8ECAE6`) without it. The first version skipped the cover while a video played, so every video track drew the waveform and the rest of the style cyan. M3 Expressive keeps its cover under video for the same reason. - **Waveform** (`content/soundcloud/SoundCloudWaveform.kt`): bars slide past a playhead fixed at the centre, so dragging LEFT goes forward — the opposite of a slider; while dragging, the labels and controls give way to the time in large type. The step and the bar width are whole pixels while the origin stays fractional. A 3.8px step put each bar on a different fraction of a pixel, sharp beside smeared, and the owner saw that pattern crawl "like an old TV"; with whole-pixel steps every bar shares one fraction and the waveform glides as one. Do not snap the origin as well: that made it tick along in one-pixel steps ("giật quá"). A waveform that arrives (seconds after the track, once decoded) rises out of the flat line over 350ms from the playhead outward, each bar on smoothstep and a little after its neighbour nearer the playhead; a track change sinks the old one back over 150ms first (700/250ms read as slow). It used to swap from flat to bars in one frame (`bars ?: FLAT_LEVEL`), and the owner asked where the animation was. - **The waveform has a playhead of its own, `rememberSteadyPlayhead`.** On Desktop the reported position runs, pauses and runs again: mpv moves `time-pos` a few times a second and the handler's smoothing holds rather than step back. `rememberSweepPlayhead` (the Apple Music lyric strip's) leans toward each report within 150ms and passed that on: measured frame by frame on a screen recording, the bars scrolled fast for ~0.2s and nearly stopped for the next ~0.2s, about 2.5 times a second. The steady one runs on the frame clock and eases toward the last report carried forward at 1x (at most 1s) over 3s, so the end of a hold slows it by a few percent and never throws it back; it jumps only across a gap wider than 2s (a seek, a new track), and while a scrub settles (`pendingSeekMs`) it is not running and follows the reports. A first version also jumped whenever a report broke 400ms from the run: that fired at the end of every handler hold and threw the bars back ("giật đùng đùng"). It assumes 1x between reports (at another speed it trails by about (speed − 1) × 3s). The position is read where it is drawn (the canvas, a `derivedStateOf` for the elapsed text and the timed comment), so the card does not recompose every frame, and the artwork's modifier (glass source, paused blur, dim and scrim) is remembered so the shell's per-report recompositions do not redraw the blur and the glass. The time label stands ON the baseline with its divider on the playhead, the time played to its left and the length to its right, as SoundCloud sets it (it was centred across the baseline, half into the reflection). Paused, the time label loses its strip and the folded line is lit where the track has played and a 35% hairline ahead. Position comes from `rememberSweepPlayhead` (now `internal`), and a scrub holds its value until the player reports the new spot, so the bars do not spring back. - - **Waveform data**: `MediaPlayerInterface.loadWaveform(mediaId)`, default null, which draws the same bars as a flat line. Android: `WaveformReader` (`core/media/media3/.../waveform/`) reads the audio through the player's own resolving, cache-backed data source chain — no second download — one resolver chunk at a time up to the format's `contentLength` (it never opens at the end of the file, where HTTP answers 416), decodes it with MediaExtractor + MediaCodec, and keeps one RMS byte per 0.8 s (`WAVEFORM_BARS_PER_SECOND` = 1.25) under `cacheDir/waveforms/`. Desktop: `MpvWaveformReader` (`media-jvm/.../mpv/`) plays the audio once more through a second, silent mpv handle — mpv shares no cache between handles — with `ao=null` + `ao-null-untimed` (decodes as fast as the stream arrives) and the lavfi chain `aresample=8000,aformat=mono,asetnsamples,astats,ametadata` printing one RMS line per bar to a file that is read back; the result is stored under `~/.simpmusic/waveforms/` in the same one-byte-per-bar format. The source is a download first, then the format's own audio URL, with no fallback extraction. Linux: `asetnsamples`, `astats` and `ametadata` were added to the slice's whitelist (`scripts/mpv-linux/Dockerfile`) and the slice rebuilt, republished on `abc` and re-pinned (`ab9957e8…1d05`, 2026-11-06); the macOS and Windows slices carry every filter already. Checked by running the exact graph on the new libmpv against a WAV of known loudness (10 s decoded in 0.02 s, bars as expected); the previous slice ends that file with an error and writes nothing, which is the flat-line fallback any slice without the filters gets. + - **Waveform data**: `MediaPlayerInterface.loadWaveform(mediaId)`, default null, which draws the same bars as a flat line. Android: `WaveformReader` (`core/media/media3/.../waveform/`) reads the audio through the player's own resolving, cache-backed data source chain — no second download — one resolver chunk at a time up to the format's `contentLength` (it never opens at the end of the file, where HTTP answers 416), decodes it with MediaExtractor + MediaCodec, and keeps one RMS byte per 0.8 s (`WAVEFORM_BARS_PER_SECOND` = 1.25) under `cacheDir/waveforms/`. Desktop: `MpvWaveformReader` (`media-jvm/.../mpv/`) plays the audio once more through a second, silent mpv handle — mpv shares no cache between handles — with `ao=pcm` (writes the chain's output raw to a file as fast as it decodes; since 2026-11-06, for AutoMix, replacing `ao=null` + `ao-null-untimed`) and the lavfi chain `aresample=8000,aformat=sample_fmts=s16:channel_layouts=mono,asetnsamples,astats,ametadata` printing one RMS line per bar to a file that is read back; the result is stored under `~/.simpmusic/waveforms/` in the same one-byte-per-bar format. The source is a download first, then the format's own audio URL, with no fallback extraction. Linux: `asetnsamples`, `astats` and `ametadata` were added to the slice's whitelist (`scripts/mpv-linux/Dockerfile`) and the slice rebuilt, republished on `abc` and re-pinned (`ab9957e8…1d05`, 2026-11-06); the macOS and Windows slices carry every filter already. Checked by running the exact graph on the new libmpv against a WAV of known loudness (10 s decoded in 0.02 s, bars as expected); the previous slice ends that file with an error and writes nothing, which is the flat-line fallback any slice without the filters gets. - **Timed comments**: YouTube comments carry no moment of their own, so only the ones whose text names one float over the waveform, at the first "m:ss" or "h:mm:ss" in them — read with `TIMESTAMP_REGEX`, the regex `DescriptionView` uses for its seek links, so both read a moment by one rule. They come from the first comments page of the track; the comment count beside the icon comes from the same page. - The landscape fullscreen-lyrics page has no SoundCloud rows; its `when` falls to `else` and borrows Classic's. +- **AutoMix places the transition by each track's structure (2026-11-06)**: in Auto crossfade mode the waveform decides only WHERE the fade sits: the second the outgoing track starts and ends it, and the second the incoming track plays from. The fade's length is still `resolveAutoCrossfadeDurationMs`. Tempo and key still come from Tidal alone. Everything the fade does (LPF/HPF sweeps, cos/sin volume, BPM speed ratio, Camelot pitch, 60% smoothstep ramp) is unchanged on both platforms. A first version also cut the length to the incoming intro and matched tempo/key from the waveform when Tidal had none. The owner heard it as far too abrupt (short intros gave fades of a few seconds), and both were removed: the waveform must not change how a fade sounds, only where it is. + - **Measured on the waveform's own decode.** `core/domain/.../mediaservice/automix/TrackStructureAnalyzer` takes 8 kHz mono PCM and returns a `TrackStructure`: BPM (beat-grid comb; autocorrelation locks onto trap hi-hat rolls), downbeats (Ellis DP tracker, bar phase from bass hits plus bar-to-bar loudness jumps), section changes (four-bar means more than 3 dB apart), first/last sound (−60 dBFS) and `musicEndMs`. Android's `WaveformReader` averages the decoded audio down to 8 kHz in the same pass that draws the bars. Desktop's `MpvWaveformReader` gets it from `ao=pcm`, which every bundled slice carries (a 238 s track decodes in 0.69 s). The result is kept as `.mix` beside `.wf`; an empty file means "measured, nothing usable". A `Mutex` in each reader serialises decodes, because the SoundCloud waveform and AutoMix ask for the same tracks. + - **The plan** (`TransitionPlanner`) works from parts labelled by loudness alone. The analyzer splits the song into parts at its section changes, up to the music's end. A chorus is any part within 2 dB of the loudest. The intro is a first part, not a chorus, at least 3 dB quieter than both parts after it, and ending within 45 s. The last chorus has an end only when a quieter outro of at most 30 s follows it. These are stored as `introEndMs` / `lastChorusEndMs` (`TrackStructure.VERSION` 2; a `.mix` from an older version is deleted and measured again). + - The window ends on the outgoing `lastChorusEndMs`, else on its `musicEndMs`. + - The window starts `length × (1 + 0.7 × (speed ratio − 1))` earlier, because the outgoing track's speed ramps during the fade. + - The incoming track plays from `introEndMs − length`. It plays from 0 when that is negative, or when loudness did not set an intro apart. The owner's rule: anything loudness cannot separate falls back to 0. + - The plan is null only when the outgoing song is too short for the window; the old fade then runs. + - Labelling by loudness merges a verse and a chorus of equal loudness into one block. Telling those apart needs a repetition (chroma self-similarity) step, which is not built. + - **`musicEndMs` is the bar line closing the last bar within 10 dB of the median bar, not a phrase counted from section changes.** On Nonstop, counting 8-bar phrases from section changes landed 2 bars off, because its 2-bar breaks blur four-bar means. The loudness rule lands on 235.36 s, where the last phrase really ends (bar 151 at −7 dB, bar 152 at −33 dB). Eye 2 Eye's intro ends at 13.15 s (−33 → −3.6 dB within 50 ms). + - **Trigger**: both adapters measure the current and next track in the background from the position poll, in Auto mode only, one job at a time, three attempts at 30 s spacing. Tidal metadata is loaded first, so the plan uses the same length and ratio the fade will. With a plan, the poll fires when the outgoing position reaches the window start, with no 3 s preparation lead, since the incoming track must not start early. The start block re-derives the plan with `startingAt(position)`, which shifts a late start (the incoming track starts that much later, the fade is that much shorter, the drop stays put) and returns null on the end-of-file path or after a seek past the window. That keeps both trigger paths on one rule. The incoming track starts there by seeking a precached player (`seekTo`) or by passing a start position to a fresh one (`setMediaItem(item, ms)`; mpv's `start` option through `MpvPlayer.loadFile(startMs)`, since `time-pos` cannot be set before a file loads). + ## 🔄 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/core b/core index c1bc55d022..514216c42b 160000 --- a/core +++ b/core @@ -1 +1 @@ -Subproject commit c1bc55d0225489f24820db1cd688dc64fc247283 +Subproject commit 514216c42be9850c557897477b554fb3221df560 From 91ec84b3990f0afd81e3bfd50a2a8442885d59a4 Mon Sep 17 00:00:00 2001 From: maxrave-dev Date: Sun, 8 Nov 2026 15:31:13 +0700 Subject: [PATCH 18/29] chore(core): bump for the precache retry and leak fix merge into multiplatform --- core | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core b/core index 514216c42b..1cdb95dd13 160000 --- a/core +++ b/core @@ -1 +1 @@ -Subproject commit 514216c42be9850c557897477b554fb3221df560 +Subproject commit 1cdb95dd1350a5865f19af860298b4416ef030c0 From 51104c1c4d972ce047709a9a6c64b4453e9a0a01 Mon Sep 17 00:00:00 2001 From: maxrave-dev Date: Sun, 8 Nov 2026 22:43:45 +0700 Subject: [PATCH 19/29] feat(login): import YouTube and Spotify sign-ins from browsers --- CLAUDE.md | 7 +- .../composeResources/values/strings.xml | 14 + .../maxrave/simpmusic/di/ViewModelModule.kt | 4 +- .../simpmusic/ui/screen/login/LogInScreen.kt | 290 +++++++++++++++--- .../ui/screen/login/SpotifyLoginScreen.kt | 182 ++++++----- .../viewModel/BrowserLoginViewModel.kt | 105 +++++++ .../simpmusic/viewModel/LogInViewModel.kt | 6 +- .../viewModel/BrowserLoginPermissionTest.kt | 46 +++ core | 2 +- 9 files changed, 530 insertions(+), 126 deletions(-) create mode 100644 composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/BrowserLoginViewModel.kt create mode 100644 composeApp/src/jvmTest/kotlin/com/maxrave/simpmusic/viewModel/BrowserLoginPermissionTest.kt diff --git a/CLAUDE.md b/CLAUDE.md index f63c3e3130..aae8ce91ce 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1139,6 +1139,11 @@ if (getPlatform() == Platform.Android) { - **`musicEndMs` is the bar line closing the last bar within 10 dB of the median bar, not a phrase counted from section changes.** On Nonstop, counting 8-bar phrases from section changes landed 2 bars off, because its 2-bar breaks blur four-bar means. The loudness rule lands on 235.36 s, where the last phrase really ends (bar 151 at −7 dB, bar 152 at −33 dB). Eye 2 Eye's intro ends at 13.15 s (−33 → −3.6 dB within 50 ms). - **Trigger**: both adapters measure the current and next track in the background from the position poll, in Auto mode only, one job at a time, three attempts at 30 s spacing. Tidal metadata is loaded first, so the plan uses the same length and ratio the fade will. With a plan, the poll fires when the outgoing position reaches the window start, with no 3 s preparation lead, since the incoming track must not start early. The start block re-derives the plan with `startingAt(position)`, which shifts a late start (the incoming track starts that much later, the fade is that much shorter, the drop stays put) and returns null on the end-of-file path or after a seek past the window. That keeps both trigger paths on one rule. The incoming track starts there by seeking a precached player (`seekTo`) or by passing a start position to a fresh one (`setMediaItem(item, ms)`; mpv's `start` option through `MpvPlayer.loadFile(startMs)`, since `time-pos` cannot be set before a file loads). +- **Browser sign-in import on Desktop (2026-11-08)**: Settings → Log in to YouTube and Log in to Spotify share `BrowserLoginPanel`, built from the existing `SettingGroup`/`SettingItem` and final `EndOfPage()` components. `BrowserLoginRepository` in domain is bound only by the JVM loader; its implementation and Chromium/Gecko/Safari readers live in `core/data`'s `browserlogin` package. `BrowserLoginTarget` is a two-service allowlist, not an arbitrary domain parameter. The app resolves `BrowserLoginViewModel` only on Desktop. Discovery checks unexpired authentication-cookie metadata for the selected service without requesting a storage key; "cookies found" is not a verified session. YouTube passes its header and Netscape text to the existing `SettingsViewModel.addAccount(cookie, netscapeCookie)`. Spotify reads only `sp_dc` from spotify.com scopes (the SQL readers filter its name before loading/decrypting values), then awaits the existing `LogInViewModel.saveSpotifySpdc()` job and uses the screen's existing stored-status/toast/navigation flow. Changing service clears stale profile results and imports require an explicit matching target. No browser found retains the existing guide; manual developer/cookie overlays are hosted independently of each Desktop panel. Android WebView callbacks and phone Login Sync are unchanged; the Spotify setter only gained a returned Job so import can await storage. + - macOS Chromium keys are requested directly with `SecItemCopyMatching` through the existing JNA dependency; Linux uses libsecret (label search without loading unrelated secrets), then KWallet as applicable, with no backend retry after authorization denial. Linux `v10` uses Chromium's fixed legacy derivation; `v11` requires the selected browser's storage key. Windows exposes Gecko browsers only. Unknown encryption is reported as unsupported, not guessed as plaintext. Chromium schema ≥24 verifies the domain SHA-256 prefix; Gecko schema ≥16 converts millisecond expiry and excludes nondefault containers/third-party partitions. Safari parses BinaryCookies. Denied file access on macOS offers an explicit Open System Settings button to Full Disk Access, with a refresh on return; it is distinct from denial of Keychain authorization, which must not be presented as a disk-access issue. Every Mac browser family must first have a confirmed app bundle in the application directories: a denied path or leftover data directory is NOT installation evidence. Only confirmed browsers can retain Local State/default profiles without a discoverable Cookies file. Header matching and Netscape serialization preserve cookie scope independently. + - `BrowserCookieSnapshot` uses the already bundled AndroidX SQLite driver on disposable copies, never a writable source connection. DB/WAL/SHM copies get bounded retries and `quick_check`; this is best-effort live copying, not an atomic backup. The private `simpmusic-browser-login` directory under the system temporary directory has Unix mode0700, copies mode0600, and a file lock guards active imports and cleanup. Copies are removed on normal/error paths; the next import removes abandoned UUID import directories after a crash. Only the empty lock file/directory may remain. Keys are import-local byte arrays cleared after use; decoded credentials are not put in UI state or new logs. YouTube persistence remains the existing DataStore/GoogleAccountEntity/ytdlp-cookie.txt path; Spotify keeps its existing sp_dc DataStore setting and writes no new cookie file. + - Synthetic JVM tests cover decryption/hash/prefix errors, expiry/containers, header/Netscape scope, BinaryCookies bounds, authorization-denial injection, copied SQLite/WAL/cleanup/permissions, Chrome discovery without a cookie file, per-profile permission actions and Spotify/YouTube isolation in all three readers. They are **not executed yet** under the no-auto-build rule. Compilation, native settings/return behavior, the packaged macOS Keychain prompt identity, native GNOME/KWallet authorization, Flatpak/Zen discovery and real imports remain unverified; do not describe source checks as end-to-end verification. Koin singleton/ViewModel/contract changes require a fresh Stop/Run, not only Hot Reload; the owner controls the running app. No new module, dependency or build configuration was added. + ## 🔄 CLAUDE.md Auto-Update Rule (MANDATORY) After completing any of the following types of changes, the AI agent **MUST** update this CLAUDE.md file: @@ -1163,6 +1168,6 @@ After completing any of the following types of changes, the AI agent **MUST** up *This document helps AI Agents quickly understand the SimpMusic project. Update regularly when there are major changes to architecture or structure.* -**Last updated**: 2026-11-06 +**Last updated**: 2026-11-08 **Project version**: Check latest release on GitHub **Maintained by**: maxrave-dev and contributors diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index fdf61d1400..f07f235c96 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -1074,4 +1074,18 @@ Microphone access needed SimpMusic listens for a few seconds to find the song playing near you Allow microphone + YouTube + Choose a browser profile to import its %1$s sign-in. Only %1$s cookies are imported; your browser is not changed. + %1$s sign-in cookies found + No %1$s sign-in cookies found. Sign in in this browser profile, then refresh. + Permission is required to read this profile. Allow access, then try again. + Allow SimpMusic in Privacy & Security → Full Disk Access. Use + to add the app if it is not listed, then return here. + Open System Settings + This profile could not be read. Try again, or close the browser and refresh. + This profile uses unsupported cookie encryption. Use manual sign-in or send sign-ins from your phone. + Importing sign-in… Approve browser storage access if your system asks. + The browser storage key is unavailable. Unlock your keyring and try again, or use manual sign-in. + The browser data changed while it was being read. Close the browser and try again. + Sign-in could not be verified. Check your connection, or sign in again in this browser profile and refresh. + Refresh browser profiles diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/di/ViewModelModule.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/di/ViewModelModule.kt index 9291b439f7..b9ae65a8c3 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/di/ViewModelModule.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/di/ViewModelModule.kt @@ -7,6 +7,7 @@ import com.maxrave.simpmusic.viewModel.ListenTogetherSettingsViewModel import com.maxrave.simpmusic.viewModel.ListenTogetherViewModel import com.maxrave.simpmusic.viewModel.ArtistViewModel import com.maxrave.simpmusic.viewModel.BrowseViewModel +import com.maxrave.simpmusic.viewModel.BrowserLoginViewModel import com.maxrave.simpmusic.viewModel.CommentsViewModel import com.maxrave.simpmusic.viewModel.SoundCloudPlayerViewModel import com.maxrave.simpmusic.viewModel.HomeViewModel @@ -67,6 +68,7 @@ val viewModelModule = // sender. Koin resolves dependencies when a ViewModel is created, not when it is declared. viewModel { LoginSyncHostViewModel(get()) } viewModel { LoginSyncSenderViewModel(get()) } + viewModel { BrowserLoginViewModel(get()) } viewModel { CommentsViewModel(get(), get()) } viewModel { SoundCloudPlayerViewModel(get()) } viewModel { @@ -235,4 +237,4 @@ val viewModelModule = ) } - } \ No newline at end of file + } diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/login/LogInScreen.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/login/LogInScreen.kt index eba9821700..4b4ae944d2 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/login/LogInScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/login/LogInScreen.kt @@ -2,16 +2,24 @@ package com.maxrave.simpmusic.ui.screen.login import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Icon import androidx.compose.material3.IconButton +import androidx.compose.material3.LocalContentColor import androidx.compose.material3.Text +import androidx.compose.material3.TextButton import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable @@ -27,22 +35,38 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.compose.LifecycleEventEffect import androidx.navigation.NavController import com.maxrave.common.Config +import com.maxrave.domain.repository.BrowserLoginFailure +import com.maxrave.domain.repository.BrowserLoginTarget +import com.maxrave.domain.repository.BrowserProfile +import com.maxrave.domain.repository.BrowserProfileStatus import com.maxrave.logger.Logger +import com.maxrave.simpmusic.Platform +import com.maxrave.simpmusic.getPlatform +import com.maxrave.simpmusic.expect.openUrl import com.maxrave.simpmusic.expect.ui.PlatformWebView import com.maxrave.simpmusic.expect.ui.createWebViewCookieManager import com.maxrave.simpmusic.expect.ui.rememberWebViewState import com.maxrave.simpmusic.extension.ultraThinBarStyle import com.maxrave.simpmusic.ui.component.DevLogInBottomSheet import com.maxrave.simpmusic.ui.component.DevLogInType +import com.maxrave.simpmusic.ui.component.EndOfPage import com.maxrave.simpmusic.ui.component.RippleIconButton +import com.maxrave.simpmusic.ui.component.SettingGroup +import com.maxrave.simpmusic.ui.component.SettingItem import com.maxrave.simpmusic.ui.icon.ArrowBackIosNew import com.maxrave.simpmusic.ui.icon.LogoDev import com.maxrave.simpmusic.ui.icon.SimpIcons import com.maxrave.simpmusic.ui.theme.typo import com.maxrave.simpmusic.viewModel.LogInViewModel import com.maxrave.simpmusic.viewModel.SettingsViewModel +import com.maxrave.simpmusic.viewModel.BrowserLoginViewModel +import com.maxrave.simpmusic.viewModel.BrowserLoginUiState +import com.maxrave.simpmusic.viewModel.requiresFileAccess import dev.chrisbanes.haze.HazeInput import dev.chrisbanes.haze.blur.hazeBlur import dev.chrisbanes.haze.hazeSource @@ -52,6 +76,22 @@ import org.jetbrains.compose.resources.getString import org.jetbrains.compose.resources.stringResource import org.koin.compose.viewmodel.koinViewModel import simpmusic.composeapp.generated.resources.Res +import simpmusic.composeapp.generated.resources.browser_login_busy +import simpmusic.composeapp.generated.resources.browser_login_description +import simpmusic.composeapp.generated.resources.browser_login_found +import simpmusic.composeapp.generated.resources.browser_login_full_disk_access +import simpmusic.composeapp.generated.resources.browser_login_importing +import simpmusic.composeapp.generated.resources.browser_login_key_unavailable +import simpmusic.composeapp.generated.resources.browser_login_missing +import simpmusic.composeapp.generated.resources.browser_login_permission +import simpmusic.composeapp.generated.resources.browser_login_open_settings +import simpmusic.composeapp.generated.resources.browser_login_refresh +import simpmusic.composeapp.generated.resources.browser_login_rejected +import simpmusic.composeapp.generated.resources.browser_login_unreadable +import simpmusic.composeapp.generated.resources.browser_login_unsupported +import simpmusic.composeapp.generated.resources.browser_login_youtube +import simpmusic.composeapp.generated.resources.spotify +import simpmusic.composeapp.generated.resources.loading import simpmusic.composeapp.generated.resources.log_in import simpmusic.composeapp.generated.resources.login_failed import simpmusic.composeapp.generated.resources.login_success @@ -73,6 +113,48 @@ fun LoginScreen( } val state = rememberWebViewState() + // Resolve the Desktop-only dependency only on Desktop. Android keeps its existing WebView. + val browserViewModel = if (getPlatform() == Platform.Desktop) koinViewModel() else null + val browserState = browserViewModel?.state?.collectAsStateWithLifecycle()?.value + val isMacOS = browserViewModel != null && getPlatform().osName().lowercase().let { "mac" in it || "darwin" in it } + + if (browserViewModel != null && isMacOS) { + LifecycleEventEffect(Lifecycle.Event.ON_RESUME) { + browserViewModel.onResumeAfterFileAccess() + } + } + + LaunchedEffect(browserViewModel) { + browserViewModel?.refresh(BrowserLoginTarget.YOUTUBE) + } + LaunchedEffect(browserState?.completed) { + if (browserState?.completed == true) { + viewModel.makeToast(getString(Res.string.login_success)) + navController.navigateUp() + } + } + + // Android still hosts this in aboveContent (above its WebView). Desktop hosts it outside the + // browser panel, so replacing PlatformWebView does not strand the existing developer button. + val manualLogin: @Composable () -> Unit = { + if (devLoginSheet) { + DevLogInBottomSheet( + onDismiss = { devLoginSheet = false }, + onDone = { cookie -> + coroutineScope.launch { + val success = settingsViewModel.addAccount(cookie) + if (success) { + viewModel.makeToast(getString(Res.string.login_success)) + navController.navigateUp() + } else { + viewModel.makeToast(getString(Res.string.login_failed)) + } + } + }, + type = DevLogInType.YouTube, + ) + } + } LaunchedEffect(state) { snapshotFlow { state.value }.collect { @@ -101,65 +183,74 @@ fun LoginScreen( } Box(modifier = Modifier.fillMaxSize().hazeSource(state = hazeState)) { - Column { + Column(if (browserViewModel != null) Modifier.fillMaxSize() else Modifier) { Spacer( Modifier .size( innerPadding.calculateTopPadding() + 64.dp, ), ) - // WebView for YouTube Music login - PlatformWebView( - state, - Config.LOG_IN_URL, - aboveContent = { - if (devLoginSheet) { - DevLogInBottomSheet( - onDismiss = { - devLoginSheet = false - }, - onDone = { cookie -> - coroutineScope.launch { - val success = settingsViewModel.addAccount(cookie) - if (success) { - viewModel.makeToast(getString(Res.string.login_success)) - navController.navigateUp() - } else { - viewModel.makeToast(getString(Res.string.login_failed)) - } - } - }, - type = DevLogInType.YouTube, - ) - } - }, - clearCookies = true, - ) { url -> - Logger.d("LogInScreen", "Current URL: $url") - if (url == Config.YOUTUBE_MUSIC_MAIN_URL) { - coroutineScope.launch { - val success = - createWebViewCookieManager() - .getCookie(url) - .takeIf { - it.isNotEmpty() - }?.let { - settingsViewModel.addAccount(it) - } ?: false + val desktopState = browserState + if (browserViewModel != null && desktopState != null) { + if (!desktopState.loading && desktopState.profiles.isEmpty() && desktopState.error == null) { + // No browser found: retain the exact existing guide text and blog button. + PlatformWebView(state, Config.LOG_IN_URL, aboveContent = {}, clearCookies = false, onPageFinished = {}) + } else { + BrowserLoginPanel( + state = desktopState, + target = BrowserLoginTarget.YOUTUBE, + bottomPadding = innerPadding.calculateBottomPadding(), + isMacOS = isMacOS, + onRefresh = browserViewModel::refresh, + onOpenFileAccess = { + browserViewModel.onFileAccessRequested() + openUrl("x-apple.systempreferences:com.apple.preference.security?Privacy_AllFiles") + }, + onSelect = { profile -> + browserViewModel.importProfile(profile, BrowserLoginTarget.YOUTUBE) { cookies -> + settingsViewModel.addAccount(cookies.cookie, cookies.netscapeCookie) + } + }, + ) + } + } else { + // WebView for YouTube Music login, unchanged on Android. + PlatformWebView( + state, + Config.LOG_IN_URL, + aboveContent = { + manualLogin() + }, + clearCookies = true, + ) { url -> + Logger.d("LogInScreen", "Current URL: $url") + if (url == Config.YOUTUBE_MUSIC_MAIN_URL) { + coroutineScope.launch { + val success = + createWebViewCookieManager() + .getCookie(url) + .takeIf { + it.isNotEmpty() + }?.let { + settingsViewModel.addAccount(it) + } ?: false - createWebViewCookieManager().removeAllCookies() + createWebViewCookieManager().removeAllCookies() - if (success) { - viewModel.makeToast(getString(Res.string.login_success)) - navController.navigateUp() - } else { - viewModel.makeToast(getString(Res.string.login_failed)) + if (success) { + viewModel.makeToast(getString(Res.string.login_success)) + navController.navigateUp() + } else { + viewModel.makeToast(getString(Res.string.login_failed)) + } } } } } } + if (browserViewModel != null) manualLogin() + // Top App Bar with haze effect TopAppBar( modifier = @@ -186,6 +277,7 @@ fun LoginScreen( }, actions = { IconButton( + enabled = browserState?.importingId == null, onClick = { devLoginSheet = true }, @@ -202,4 +294,110 @@ fun LoginScreen( ), ) } -} \ No newline at end of file +} + +@Composable +internal fun BrowserLoginPanel( + state: BrowserLoginUiState, + target: BrowserLoginTarget, + bottomPadding: androidx.compose.ui.unit.Dp, + isMacOS: Boolean, + onRefresh: () -> Unit, + onOpenFileAccess: () -> Unit, + onSelect: (BrowserProfile) -> Unit, +) { + val busy = state.loading || state.importingId != null + val serviceName = stringResource(if (target == BrowserLoginTarget.YOUTUBE) Res.string.browser_login_youtube else Res.string.spotify) + LazyColumn( + modifier = Modifier.fillMaxSize().padding(horizontal = 16.dp), + contentPadding = PaddingValues(top = 16.dp, bottom = bottomPadding + 24.dp), + ) { + item(key = "description") { + Text( + stringResource(Res.string.browser_login_description, serviceName), + style = typo().bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + if (busy) { + item(key = "progress") { + Row( + Modifier.fillMaxWidth().padding(vertical = 16.dp), + horizontalArrangement = Arrangement.spacedBy(12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + CircularProgressIndicator(Modifier.size(24.dp)) + Text( + stringResource(if (state.loading) Res.string.loading else Res.string.browser_login_importing), + style = typo().bodyMedium, + color = MaterialTheme.colorScheme.onSurface, + ) + } + } + } + state.profiles.groupBy { it.browser }.forEach { (browser, profiles) -> + item(key = "browser:$browser") { + SettingGroup(title = browser) { + profiles.forEach { profile -> + val needsFileAccess = state.requiresFileAccess(profile, isMacOS) + val subtitle = when (profile.status) { + BrowserProfileStatus.COOKIES_FOUND -> Res.string.browser_login_found + BrowserProfileStatus.NO_COOKIES -> Res.string.browser_login_missing + BrowserProfileStatus.PERMISSION_REQUIRED -> if (isMacOS) Res.string.browser_login_full_disk_access else Res.string.browser_login_permission + BrowserProfileStatus.UNREADABLE -> Res.string.browser_login_unreadable + BrowserProfileStatus.UNSUPPORTED -> Res.string.browser_login_unsupported + } + SettingItem( + title = profile.name, + subtitle = if (profile.status == BrowserProfileStatus.COOKIES_FOUND || profile.status == BrowserProfileStatus.NO_COOKIES) { + stringResource(subtitle, serviceName) + } else { + stringResource(subtitle) + }, + isEnable = !busy && profile.status != BrowserProfileStatus.UNSUPPORTED, + onClick = { if (needsFileAccess) onOpenFileAccess() else onSelect(profile) }, + otherView = if (needsFileAccess) { + { + TextButton(onClick = onOpenFileAccess, enabled = !busy) { + Text(stringResource(Res.string.browser_login_open_settings), color = LocalContentColor.current) + } + } + } else { + null + }, + ) + } + } + } + } + val error = state.error + if (error != null || state.rejectedSession) { + item(key = "error") { + val message = when { + state.rejectedSession -> Res.string.browser_login_rejected + error == BrowserLoginFailure.FILE_ACCESS_DENIED -> if (isMacOS) Res.string.browser_login_full_disk_access else Res.string.browser_login_permission + error == BrowserLoginFailure.ACCESS_DENIED -> Res.string.browser_login_permission + error == BrowserLoginFailure.KEY_UNAVAILABLE -> Res.string.browser_login_key_unavailable + error == BrowserLoginFailure.UNSUPPORTED_ENCRYPTION -> Res.string.browser_login_unsupported + error == BrowserLoginFailure.DATABASE_BUSY -> Res.string.browser_login_busy + error == BrowserLoginFailure.NO_COOKIES -> Res.string.browser_login_missing + else -> Res.string.browser_login_unreadable + } + Spacer(Modifier.height(16.dp)) + Text( + if (error == BrowserLoginFailure.NO_COOKIES) stringResource(message, serviceName) else stringResource(message), + style = typo().bodyMedium, + color = MaterialTheme.colorScheme.error, + ) + } + } + item(key = "refresh") { + TextButton(onClick = onRefresh, enabled = !busy) { + Text(stringResource(Res.string.browser_login_refresh), color = LocalContentColor.current) + } + } + item(key = "end_of_list") { + EndOfPage() + } + } +} diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/login/SpotifyLoginScreen.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/login/SpotifyLoginScreen.kt index 23ddeaca53..006b1a8bfb 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/login/SpotifyLoginScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/login/SpotifyLoginScreen.kt @@ -1,6 +1,7 @@ package com.maxrave.simpmusic.ui.screen.login import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxScope import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Spacer @@ -27,8 +28,14 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.compose.LifecycleEventEffect import androidx.navigation.NavController import com.maxrave.common.Config +import com.maxrave.domain.repository.BrowserLoginTarget +import com.maxrave.simpmusic.Platform +import com.maxrave.simpmusic.getPlatform +import com.maxrave.simpmusic.expect.openUrl import com.maxrave.simpmusic.expect.ui.PlatformWebView import com.maxrave.simpmusic.expect.ui.createWebViewCookieManager import com.maxrave.simpmusic.expect.ui.rememberWebViewState @@ -45,6 +52,7 @@ import com.maxrave.simpmusic.ui.icon.SimpIcons import com.maxrave.simpmusic.ui.theme.typo import com.maxrave.simpmusic.viewModel.LogInViewModel import com.maxrave.simpmusic.viewModel.SettingsViewModel +import com.maxrave.simpmusic.viewModel.BrowserLoginViewModel import dev.chrisbanes.haze.HazeInput import dev.chrisbanes.haze.blur.hazeBlur import dev.chrisbanes.haze.hazeSource @@ -102,94 +110,119 @@ fun SpotifyLoginScreen( val state = rememberWebViewState() val cookieManager = createWebViewCookieManager() + val browserViewModel = if (getPlatform() == Platform.Desktop) koinViewModel() else null + val browserState = browserViewModel?.state?.collectAsStateWithLifecycle()?.value + val isMacOS = browserViewModel != null && getPlatform().osName().lowercase().let { "mac" in it || "darwin" in it } + + LaunchedEffect(browserViewModel) { + browserViewModel?.refresh(BrowserLoginTarget.SPOTIFY) + } + if (browserViewModel != null && isMacOS) { + LifecycleEventEffect(Lifecycle.Event.ON_RESUME) { + browserViewModel.onResumeAfterFileAccess() + } + } + + val loginOverlays: @Composable BoxScope.() -> Unit = { + FloatingActionButton( + onClick = { showCookiesBottomSheet = true }, + containerColor = Color(0xFF40D96A), + modifier = Modifier.align(Alignment.BottomStart).padding(innerPadding).padding(25.dp), + ) { + Icon(SimpIcons.Cookie, "Cookies") + } + if (devLoginSheet) { + DevLogInBottomSheet( + onDismiss = { devLoginSheet = false }, + onDone = { spdc -> + devLoginSheet = false + val spdcText = "sp_dc=$spdc" + viewModel.saveSpotifySpdc(spdcText) + viewModel.makeToast(getStringBlocking(Res.string.login_success)) + navController.navigateUp() + }, + type = DevLogInType.Spotify, + ) + } + if (showCookiesBottomSheet) { + DevCookieLogInBottomSheet( + onDismiss = { showCookiesBottomSheet = false }, + type = DevLogInType.Spotify, + cookies = fullSpotifyCookies, + ) + } + } Box(modifier = Modifier.fillMaxSize().hazeSource(state = hazeState)) { - Column { + Column(if (browserViewModel != null) Modifier.fillMaxSize() else Modifier) { Spacer( Modifier .size( innerPadding.calculateTopPadding() + 64.dp, ), ) - // WebView for Spotify login - PlatformWebView( - state, - Config.SPOTIFY_LOG_IN_URL, - aboveContent = { - FloatingActionButton( - onClick = { - showCookiesBottomSheet = true + val desktopState = browserState + if (browserViewModel != null && desktopState != null) { + if (!desktopState.loading && desktopState.profiles.isEmpty() && desktopState.error == null) { + PlatformWebView(state, Config.SPOTIFY_LOG_IN_URL, aboveContent = {}, clearCookies = false, onPageFinished = {}) + } else { + BrowserLoginPanel( + state = desktopState, + target = BrowserLoginTarget.SPOTIFY, + bottomPadding = innerPadding.calculateBottomPadding(), + isMacOS = isMacOS, + onRefresh = browserViewModel::refresh, + onOpenFileAccess = { + browserViewModel.onFileAccessRequested() + openUrl("x-apple.systempreferences:com.apple.preference.security?Privacy_AllFiles") }, - containerColor = Color(0xFF40D96A), - modifier = - Modifier - .align( - Alignment.BottomStart, - ).padding(innerPadding) - .padding( - 25.dp, - ), - ) { - Icon( - SimpIcons.Cookie, - "Cookies", - ) - } - if (devLoginSheet) { - DevLogInBottomSheet( - onDismiss = { - devLoginSheet = false - }, - onDone = { spdc -> - devLoginSheet = false - val spdcText = "sp_dc=$spdc" - viewModel.saveSpotifySpdc(spdcText) - viewModel.makeToast(getStringBlocking(Res.string.login_success)) - navController.navigateUp() - }, - type = DevLogInType.Spotify, - ) + onSelect = { profile -> + browserViewModel.importProfile(profile, BrowserLoginTarget.SPOTIFY) { cookies -> + val save = viewModel.saveSpotifySpdc(cookies.cookie) + save.join() + !save.isCancelled && viewModel.spotifyStatus.value + } + }, + ) + } + } else { + // Android keeps the original WebView and its sign-in callback. + PlatformWebView( + state, + Config.SPOTIFY_LOG_IN_URL, + aboveContent = loginOverlays, + ) { url -> + val cookie = cookieManager.getCookie(url) + cookie.takeIf { + it.isNotEmpty() + }?.let { cookie -> + val cookies = + cookie.split("; ").map { + val (key, value) = it.split("=") + key to value + } + viewModel.setFullSpotifyCookies(cookies) } - - if (showCookiesBottomSheet) { - DevCookieLogInBottomSheet( - onDismiss = { - showCookiesBottomSheet = false - }, - type = DevLogInType.Spotify, - cookies = fullSpotifyCookies, - ) + // Some login flows land on the status page with a query string appended + // (e.g. /en/status?flow_ctx=...). Anchoring right after `status` made those + // URLs fail the match silently, so sp_dc was never saved and auto-login + // appeared to do nothing. + val statusUrl = Regex("^https://accounts\\.spotify\\.com/(?:[^/]+/)?status(?:\\?.*)?$") + if (statusUrl.matches(url)) { + cookie + .takeIf { + it.isNotEmpty() + }?.let { + viewModel.saveSpotifySpdc(it) + } + cookieManager.removeAllCookies() } - }, - ) { url -> - val cookie = cookieManager.getCookie(url) - cookie.takeIf { - it.isNotEmpty() - }?.let { cookie -> - val cookies = - cookie.split("; ").map { - val (key, value) = it.split("=") - key to value - } - viewModel.setFullSpotifyCookies(cookies) - } - // Some login flows land on the status page with a query string appended - // (e.g. /en/status?flow_ctx=...). Anchoring right after `status` made those - // URLs fail the match silently, so sp_dc was never saved and auto-login - // appeared to do nothing. - val statusUrl = Regex("^https://accounts\\.spotify\\.com/(?:[^/]+/)?status(?:\\?.*)?$") - if (statusUrl.matches(url)) { - cookie - .takeIf { - it.isNotEmpty() - }?.let { - viewModel.saveSpotifySpdc(it) - } - cookieManager.removeAllCookies() } } } + if (browserViewModel != null) loginOverlays() + // Top App Bar with haze effect TopAppBar( modifier = @@ -216,6 +249,7 @@ fun SpotifyLoginScreen( }, actions = { IconButton( + enabled = browserState?.importingId == null, onClick = { devLoginSheet = true }, @@ -232,4 +266,4 @@ fun SpotifyLoginScreen( ), ) } -} \ No newline at end of file +} diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/BrowserLoginViewModel.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/BrowserLoginViewModel.kt new file mode 100644 index 0000000000..ad2d3b6065 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/BrowserLoginViewModel.kt @@ -0,0 +1,105 @@ +package com.maxrave.simpmusic.viewModel + +import androidx.lifecycle.viewModelScope +import com.maxrave.domain.repository.BrowserCookies +import com.maxrave.domain.repository.BrowserLoginException +import com.maxrave.domain.repository.BrowserLoginFailure +import com.maxrave.domain.repository.BrowserLoginRepository +import com.maxrave.domain.repository.BrowserLoginTarget +import com.maxrave.domain.repository.BrowserProfile +import com.maxrave.domain.repository.BrowserProfileStatus +import com.maxrave.logger.LogLevel +import com.maxrave.simpmusic.viewModel.base.BaseViewModel +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.Job +import kotlinx.coroutines.ensureActive +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch + +class BrowserLoginViewModel( + private val repository: BrowserLoginRepository, +) : BaseViewModel() { + private val _state = MutableStateFlow(BrowserLoginUiState()) + val state = _state.asStateFlow() + private var operation: Job? = null + + fun refresh() = refresh(_state.value.target) + + fun refresh(target: BrowserLoginTarget) { + if (_state.value.importingId != null || _state.value.completed && _state.value.target == target) return + operation?.cancel() + _state.value = _state.value.copy( + loading = true, + error = null, + rejectedSession = false, + failedProfileId = null, + awaitingFileAccess = false, + profiles = if (_state.value.target == target) _state.value.profiles else emptyList(), + target = target, + completed = false, + ) + operation = viewModelScope.launch { + try { + val profiles = repository.profiles(target) + ensureActive() + _state.value = _state.value.copy(loading = false, profiles = profiles) + } catch (error: CancellationException) { + throw error + } catch (error: Exception) { + val site = error.stackTrace.firstOrNull { it.className.startsWith("com.maxrave.data.browserlogin.") } + val location = site?.let { "${it.className}.${it.methodName}:${it.lineNumber}" } ?: "unknown" + // Never pass the throwable/message: native file errors can contain private paths. + log("Browser discovery failed: ${error::class.simpleName} at $location", LogLevel.WARN) + _state.value = _state.value.copy(loading = false, error = BrowserLoginFailure.INVALID_DATA) + } + } + } + + fun importProfile(profile: BrowserProfile, target: BrowserLoginTarget, addAccount: suspend (BrowserCookies) -> Boolean) { + if (_state.value.target != target || _state.value.loading || _state.value.importingId != null || _state.value.completed) return + _state.value = _state.value.copy(importingId = profile.id, error = null, rejectedSession = false, failedProfileId = null) + operation = viewModelScope.launch { + try { + val cookies = repository.cookies(profile, target) + ensureActive() + // Keep credentials local to this call, never in StateFlow, SavedState or a log. + val accepted = addAccount(cookies) + ensureActive() + _state.value = _state.value.copy(completed = accepted, rejectedSession = !accepted) + } catch (error: CancellationException) { + throw error + } catch (error: BrowserLoginException) { + _state.value = _state.value.copy(error = error.reason, failedProfileId = profile.id) + } catch (_: Exception) { + _state.value = _state.value.copy(error = BrowserLoginFailure.INVALID_DATA, failedProfileId = profile.id) + } finally { + _state.value = _state.value.copy(importingId = null) + } + } + } + + fun onFileAccessRequested() { + _state.value = _state.value.copy(awaitingFileAccess = true) + } + + fun onResumeAfterFileAccess() { + if (_state.value.awaitingFileAccess) refresh() + } +} + +data class BrowserLoginUiState( + val loading: Boolean = true, + val profiles: List = emptyList(), + val importingId: String? = null, + val error: BrowserLoginFailure? = null, + val rejectedSession: Boolean = false, + val completed: Boolean = false, + val failedProfileId: String? = null, + val awaitingFileAccess: Boolean = false, + val target: BrowserLoginTarget = BrowserLoginTarget.YOUTUBE, +) + +internal fun BrowserLoginUiState.requiresFileAccess(profile: BrowserProfile, isMacOS: Boolean): Boolean = + isMacOS && (profile.status == BrowserProfileStatus.PERMISSION_REQUIRED || + error == BrowserLoginFailure.FILE_ACCESS_DENIED && failedProfileId == profile.id) diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/LogInViewModel.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/LogInViewModel.kt index aea7a0026e..1143a041f1 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/LogInViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/LogInViewModel.kt @@ -12,6 +12,7 @@ import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch +import kotlinx.coroutines.Job import org.simpmusic.lastfm.authorizeUrl import org.simpmusic.lastfm.completeLogin @@ -28,7 +29,7 @@ class LogInViewModel( private val _fullYouTubeCookies: MutableStateFlow>> = MutableStateFlow(emptyList()) val fullYouTubeCookies: StateFlow>> get() = _fullYouTubeCookies.asStateFlow() - fun saveSpotifySpdc(cookie: String) { + fun saveSpotifySpdc(cookie: String): Job = viewModelScope.launch { cookie .split("; ") @@ -42,7 +43,6 @@ class LogInViewModel( _spotifyStatus.value = true } } - } fun setVisitorData(visitorData: String) { viewModelScope.launch { @@ -225,4 +225,4 @@ sealed interface LastfmLoginState { ) : LastfmLoginState data object Failed : LastfmLoginState -} \ No newline at end of file +} diff --git a/composeApp/src/jvmTest/kotlin/com/maxrave/simpmusic/viewModel/BrowserLoginPermissionTest.kt b/composeApp/src/jvmTest/kotlin/com/maxrave/simpmusic/viewModel/BrowserLoginPermissionTest.kt new file mode 100644 index 0000000000..bd3f394103 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/maxrave/simpmusic/viewModel/BrowserLoginPermissionTest.kt @@ -0,0 +1,46 @@ +package com.maxrave.simpmusic.viewModel + +import com.maxrave.domain.repository.BrowserLoginFailure +import com.maxrave.domain.repository.BrowserProfile +import com.maxrave.domain.repository.BrowserProfileStatus +import kotlin.test.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class BrowserLoginPermissionTest { + @Test + fun safariPermissionRowOpensFileAccessSettingsInsteadOfImportingAgain() { + val safari = profile("safari", "Safari", BrowserProfileStatus.PERMISSION_REQUIRED) + assertTrue(BrowserLoginUiState().requiresFileAccess(safari, isMacOS = true)) + } + + @Test + fun chromePermissionRowAlsoOpensFileAccessSettings() { + val chrome = profile("chrome", "Chrome", BrowserProfileStatus.PERMISSION_REQUIRED) + assertTrue(BrowserLoginUiState().requiresFileAccess(chrome, isMacOS = true)) + } + + @Test + fun fileDenialAfterDiscoveryOffersSettingsForTheAffectedProfileOnly() { + val chrome = profile("chrome", "Chrome", BrowserProfileStatus.COOKIES_FOUND) + val zen = profile("zen", "Zen", BrowserProfileStatus.COOKIES_FOUND) + val state = BrowserLoginUiState(error = BrowserLoginFailure.FILE_ACCESS_DENIED, failedProfileId = chrome.id) + assertTrue(state.requiresFileAccess(chrome, isMacOS = true)) + assertFalse(state.requiresFileAccess(zen, isMacOS = true)) + } + + @Test + fun keychainDenialDoesNotPretendToRequireFullDiskAccess() { + val chrome = profile("chrome", "Chrome", BrowserProfileStatus.COOKIES_FOUND) + val state = BrowserLoginUiState(error = BrowserLoginFailure.ACCESS_DENIED, failedProfileId = chrome.id) + assertFalse(state.requiresFileAccess(chrome, isMacOS = true)) + } + + @Test + fun otherPlatformsDoNotOpenMacSystemSettings() { + val firefox = profile("firefox", "Firefox", BrowserProfileStatus.PERMISSION_REQUIRED) + assertFalse(BrowserLoginUiState().requiresFileAccess(firefox, isMacOS = false)) + } + + private fun profile(id: String, browser: String, status: BrowserProfileStatus) = BrowserProfile(id, browser, "Default", status) +} diff --git a/core b/core index 1cdb95dd13..920a610c54 160000 --- a/core +++ b/core @@ -1 +1 @@ -Subproject commit 1cdb95dd1350a5865f19af860298b4416ef030c0 +Subproject commit 920a610c54910b42416a731b52f384e328830035 From 092575eba548a57a27436d3710bf514c870e15be Mon Sep 17 00:00:00 2001 From: maxrave-dev Date: Mon, 9 Nov 2026 16:07:43 +0700 Subject: [PATCH 20/29] fix(artist): scale desktop logos with the content panel --- .../simpmusic/ui/screen/other/ArtistScreen.kt | 42 +++++++++++++++++-- 1 file changed, 38 insertions(+), 4 deletions(-) diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/ArtistScreen.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/ArtistScreen.kt index 48b09e6408..d13ce6a2da 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/ArtistScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/ArtistScreen.kt @@ -74,6 +74,7 @@ import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.graphics.luminance import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.layout.layout import androidx.compose.ui.platform.LocalUriHandler import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow @@ -93,6 +94,8 @@ import com.maxrave.domain.data.model.searchResult.songs.Artist import com.maxrave.domain.mediaservice.handler.PlaylistType import com.maxrave.domain.mediaservice.handler.QueueData import com.maxrave.domain.utils.toSongEntity +import com.maxrave.simpmusic.Platform +import com.maxrave.simpmusic.getPlatform import com.maxrave.simpmusic.expect.shareUrl import com.maxrave.simpmusic.expect.ui.MediaPlayerView import com.maxrave.simpmusic.expect.ui.layerBackdrop @@ -150,6 +153,7 @@ import dev.chrisbanes.haze.hazeSource import dev.chrisbanes.haze.rememberHazeState import kotlinx.coroutines.flow.map import kotlinx.coroutines.runBlocking +import kotlin.math.roundToInt import org.jetbrains.compose.resources.getString import org.jetbrains.compose.resources.painterResource import org.jetbrains.compose.resources.pluralStringResource @@ -461,6 +465,7 @@ fun ArtistScreen( .background(artworkScrimBrush(mutedPaletteBg)), ) // Artist name (TEXT for now — logo image is roadmap) + subscriber · view + val nameHorizontalPadding = 20.dp Column( modifier = Modifier @@ -468,14 +473,14 @@ fun ArtistScreen( // Lift the name + subtitle together with the action row. .offset(y = (-36).dp) .fillMaxWidth() - .padding(horizontal = 20.dp) + .padding(horizontal = nameHorizontalPadding) .padding(bottom = 16.dp), horizontalAlignment = Alignment.CenterHorizontally, ) { val logo = artistLogo // The name stays as text until the logo image has actually - // loaded, then the two cross-fade and the box eases to the - // logo's height. Swapping on the logo's url alone blanked the + // loaded, then the two cross-fade. Android also eases the + // box to the logo's height. Swapping on the logo's url alone blanked the // line until the image arrived and then popped it in. Saveable, // so coming back to the page shows the logo straight away. var logoLoaded by rememberSaveable(logo?.logoUrl) { mutableStateOf(false) } @@ -485,7 +490,13 @@ fun ArtistScreen( label = "artistNameLogo", ) Box( - modifier = Modifier.fillMaxWidth().animateContentSize(), + modifier = + Modifier.fillMaxWidth().then( + // Desktop already receives animated widths from the + // Now Playing panel. A second size animation lags + // behind the image and makes it slide down. + if (getPlatform() == Platform.Desktop) Modifier else Modifier.animateContentSize(), + ), contentAlignment = Alignment.Center, ) { if (logoAlpha < 1f) { @@ -508,6 +519,29 @@ fun ArtistScreen( onSuccess = { logoLoaded = true }, modifier = Modifier + .then( + if (getPlatform() == Platform.Desktop) { + // Follow the panel's animated width in measure only; + // do not recompose the video/blur/glass header. + Modifier.layout { measurable, constraints -> + val panelWidth = constraints.maxWidth + (nameHorizontalPadding * 2).roundToPx() + val scale = (panelWidth.toFloat() / screenInfo.wPX.coerceAtLeast(1)).coerceIn(0f, 1f) + val maxHeight = minOf(constraints.maxHeight, (84.dp.toPx() * scale).roundToInt()) + val placeable = + measurable.measure( + constraints.copy( + minHeight = constraints.minHeight.coerceAtMost(maxHeight), + maxHeight = maxHeight, + ), + ) + layout(placeable.width, placeable.height) { + placeable.placeRelative(0, 0) + } + } + } else { + Modifier + }, + ) .fillMaxWidth(0.7f) .heightIn(max = 84.dp) .graphicsLayer { alpha = logoAlpha }, From fbdba0daa447c93f43a81201a1063d42941665d5 Mon Sep 17 00:00:00 2001 From: maxrave-dev Date: Mon, 9 Nov 2026 16:11:42 +0700 Subject: [PATCH 21/29] feat(lyrics): enable LRCLIB word-synced lyrics --- CLAUDE.md | 6 +++++- core | 2 +- gradle/libs.versions.toml | 2 ++ 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index aae8ce91ce..af80023bf5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1144,6 +1144,10 @@ if (getPlatform() == Platform.Android) { - `BrowserCookieSnapshot` uses the already bundled AndroidX SQLite driver on disposable copies, never a writable source connection. DB/WAL/SHM copies get bounded retries and `quick_check`; this is best-effort live copying, not an atomic backup. The private `simpmusic-browser-login` directory under the system temporary directory has Unix mode0700, copies mode0600, and a file lock guards active imports and cleanup. Copies are removed on normal/error paths; the next import removes abandoned UUID import directories after a crash. Only the empty lock file/directory may remain. Keys are import-local byte arrays cleared after use; decoded credentials are not put in UI state or new logs. YouTube persistence remains the existing DataStore/GoogleAccountEntity/ytdlp-cookie.txt path; Spotify keeps its existing sp_dc DataStore setting and writes no new cookie file. - Synthetic JVM tests cover decryption/hash/prefix errors, expiry/containers, header/Netscape scope, BinaryCookies bounds, authorization-denial injection, copied SQLite/WAL/cleanup/permissions, Chrome discovery without a cookie file, per-profile permission actions and Spotify/YouTube isolation in all three readers. They are **not executed yet** under the no-auto-build rule. Compilation, native settings/return behavior, the packaged macOS Keychain prompt identity, native GNOME/KWallet authorization, Flatpak/Zen discovery and real imports remain unverified; do not describe source checks as end-to-end verification. Koin singleton/ViewModel/contract changes require a fresh Stop/Run, not only Hot Reload; the owner controls the running app. No new module, dependency or build configuration was added. +- **LRCLIB Lyricsfile support (2026-11-09)**: `lyricsService` now prefers the selected record's `lyricsfile` YAML over `syncedLyrics` and `plainLyrics`. `parser/LyricsfileParser.kt` uses Kotaml **0.113.0** (`io.heapy.kotaml:kotaml`, commonMain; backed by SnakeYAML Engine KMP), matching the project's Kotlin 2.4.21 and serialization 1.12.0. Its private serializable models decode Lyricsfile version `1.0`; valid `words` become the existing `RICH_SYNCED` marker string with three millisecond digits, timed lines become `LINE_SYNCED`, and `plain` becomes `UNSYNCED`. Word text is concatenated without adding or removing whitespace; inconsistent or invalid word timing falls back to that line's complete text. Mixed word/line-synced documents retain both kinds of lines. Explicit line ends are preserved; missing or invalid ends use the existing `0` sentinel, not the next line's start. The existing renderer still uses word starts rather than individual word ends and does not gain simultaneous-line rendering. + - The YAML reader rejects anchors/aliases and duplicate keys, caps nesting at 12 and input at 1,000,000 UTF-16 code units (with the same code-point budget in the engine), ignores unrelated fields, and rejects unsupported document versions. Missing, malformed, empty or unusable Lyricsfile data falls back to the old fields; instrumental YAML does not invent lyrics. Parser exception messages are not logged because they may include the input text. The raw YAML is not written to a separate store: the normalized `Lyrics` still uses the existing cache, contribution and display paths. + - The request remains `/api/search?q= `. Record selection first applies the existing inclusive 10-second duration tolerance (all results are eligible when duration is unknown), then prefers the first candidate with `hasWordSync = true`; if none has that flag, it keeps the first eligible result. The optional flag defaults to false for older responses. Response order within either group is retained; no new album/name scoring or duration-threshold change was added. The selected record still goes through YAML validation and legacy-field fallback. No database migration, UI change or extra HTTP request was added. Common tests cover YAML formats, timing/whitespace, mixed lines, limits, record priority and legacy fallbacks; these have **not been compiled or executed** under the no-auto-build rule. + ## 🔄 CLAUDE.md Auto-Update Rule (MANDATORY) After completing any of the following types of changes, the AI agent **MUST** update this CLAUDE.md file: @@ -1168,6 +1172,6 @@ After completing any of the following types of changes, the AI agent **MUST** up *This document helps AI Agents quickly understand the SimpMusic project. Update regularly when there are major changes to architecture or structure.* -**Last updated**: 2026-11-08 +**Last updated**: 2026-11-09 **Project version**: Check latest release on GitHub **Maintained by**: maxrave-dev and contributors diff --git a/core b/core index 920a610c54..164e89e0d0 160000 --- a/core +++ b/core @@ -1 +1 @@ -Subproject commit 920a610c54910b42416a731b52f384e328830035 +Subproject commit 164e89e0d093492d6f1c9be3f745201b7b4574bb diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 9722d6a557..acc58e9c26 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -54,6 +54,7 @@ haze = "2.0.1" onetimepassword = "3.0.0" common = "1.23.0" json = "1.12.0" +kotaml = "0.113.0" gemini-kotlin = "4.0.2" slf4j = "1.7.36" sentry-android = "8.61.1" @@ -184,6 +185,7 @@ ktor-serialization-kotlinx-xml = { group = "io.ktor", name = "ktor-serialization ktor-serialization-kotlinx-protobuf = { group = "io.ktor", name = "ktor-serialization-kotlinx-protobuf", version.ref = "ktor" } kotlinx-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "json" } kotlinx-serialization-protobuf = { module = "org.jetbrains.kotlinx:kotlinx-serialization-protobuf", version.ref = "json" } +kotaml = { module = "io.heapy.kotaml:kotaml", version.ref = "kotaml" } brotli-dec = { group = "org.brotli", name = "dec", version.ref = "brotli" } kotlin-reflect = { module = "org.jetbrains.kotlin:kotlin-reflect" } kotlin-stdlib = { module = "org.jetbrains.kotlin:kotlin-stdlib" } From b7dd4d66405e9fc79ed3bc20ceb580e7164f2a55 Mon Sep 17 00:00:00 2001 From: maxrave-dev Date: Tue, 10 Nov 2026 22:58:26 +0700 Subject: [PATCH 22/29] fix(player): complete SoundCloud controls and waveform previews --- CLAUDE.md | 5 +- build.gradle.kts | 13 +- .../composeResources/values/strings.xml | 1 + .../content/NowPlayingContentSoundCloud.kt | 242 +++++++++++++----- .../content/soundcloud/SoundCloudWaveform.kt | 29 ++- .../viewModel/SoundCloudPlayerViewModel.kt | 27 +- .../content/SoundCloudCommentTimestampTest.kt | 28 ++ core | 2 +- 8 files changed, 268 insertions(+), 79 deletions(-) create mode 100644 composeApp/src/jvmTest/kotlin/com/maxrave/simpmusic/ui/screen/player/content/SoundCloudCommentTimestampTest.kt diff --git a/CLAUDE.md b/CLAUDE.md index af80023bf5..280a5719ec 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1125,6 +1125,7 @@ if (getPlatform() == Platform.Android) { - **Waveform** (`content/soundcloud/SoundCloudWaveform.kt`): bars slide past a playhead fixed at the centre, so dragging LEFT goes forward — the opposite of a slider; while dragging, the labels and controls give way to the time in large type. The step and the bar width are whole pixels while the origin stays fractional. A 3.8px step put each bar on a different fraction of a pixel, sharp beside smeared, and the owner saw that pattern crawl "like an old TV"; with whole-pixel steps every bar shares one fraction and the waveform glides as one. Do not snap the origin as well: that made it tick along in one-pixel steps ("giật quá"). A waveform that arrives (seconds after the track, once decoded) rises out of the flat line over 350ms from the playhead outward, each bar on smoothstep and a little after its neighbour nearer the playhead; a track change sinks the old one back over 150ms first (700/250ms read as slow). It used to swap from flat to bars in one frame (`bars ?: FLAT_LEVEL`), and the owner asked where the animation was. - **The waveform has a playhead of its own, `rememberSteadyPlayhead`.** On Desktop the reported position runs, pauses and runs again: mpv moves `time-pos` a few times a second and the handler's smoothing holds rather than step back. `rememberSweepPlayhead` (the Apple Music lyric strip's) leans toward each report within 150ms and passed that on: measured frame by frame on a screen recording, the bars scrolled fast for ~0.2s and nearly stopped for the next ~0.2s, about 2.5 times a second. The steady one runs on the frame clock and eases toward the last report carried forward at 1x (at most 1s) over 3s, so the end of a hold slows it by a few percent and never throws it back; it jumps only across a gap wider than 2s (a seek, a new track), and while a scrub settles (`pendingSeekMs`) it is not running and follows the reports. A first version also jumped whenever a report broke 400ms from the run: that fired at the end of every handler hold and threw the bars back ("giật đùng đùng"). It assumes 1x between reports (at another speed it trails by about (speed − 1) × 3s). The position is read where it is drawn (the canvas, a `derivedStateOf` for the elapsed text and the timed comment), so the card does not recompose every frame, and the artwork's modifier (glass source, paused blur, dim and scrim) is remembered so the shell's per-report recompositions do not redraw the blur and the glass. The time label stands ON the baseline with its divider on the playhead, the time played to its left and the length to its right, as SoundCloud sets it (it was centred across the baseline, half into the reflection). Paused, the time label loses its strip and the folded line is lit where the track has played and a 35% hairline ahead. Position comes from `rememberSweepPlayhead` (now `internal`), and a scrub holds its value until the player reports the new spot, so the bars do not spring back. - **Waveform data**: `MediaPlayerInterface.loadWaveform(mediaId)`, default null, which draws the same bars as a flat line. Android: `WaveformReader` (`core/media/media3/.../waveform/`) reads the audio through the player's own resolving, cache-backed data source chain — no second download — one resolver chunk at a time up to the format's `contentLength` (it never opens at the end of the file, where HTTP answers 416), decodes it with MediaExtractor + MediaCodec, and keeps one RMS byte per 0.8 s (`WAVEFORM_BARS_PER_SECOND` = 1.25) under `cacheDir/waveforms/`. Desktop: `MpvWaveformReader` (`media-jvm/.../mpv/`) plays the audio once more through a second, silent mpv handle — mpv shares no cache between handles — with `ao=pcm` (writes the chain's output raw to a file as fast as it decodes; since 2026-11-06, for AutoMix, replacing `ao=null` + `ao-null-untimed`) and the lavfi chain `aresample=8000,aformat=sample_fmts=s16:channel_layouts=mono,asetnsamples,astats,ametadata` printing one RMS line per bar to a file that is read back; the result is stored under `~/.simpmusic/waveforms/` in the same one-byte-per-bar format. The source is a download first, then the format's own audio URL, with no fallback extraction. Linux: `asetnsamples`, `astats` and `ametadata` were added to the slice's whitelist (`scripts/mpv-linux/Dockerfile`) and the slice rebuilt, republished on `abc` and re-pinned (`ab9957e8…1d05`, 2026-11-06); the macOS and Windows slices carry every filter already. Checked by running the exact graph on the new libmpv against a WAV of known loudness (10 s decoded in 0.02 s, bars as expected); the previous slice ends that file with an error and writes nothing, which is the flat-line fallback any slice without the filters gets. + - **Playback-buffer waveform (2026-11-10, supersedes the separate-reader implementation)**: Android `loadWaveform(mediaId, onProgress)` returns a completed `.wf` cache or observes `PlaybackWaveforms`; it never calls `measure`, creates a decoder, downloads a song or waits for the AutoMix mutex. `WaveformAudioSink` wraps the existing `DefaultAudioSink` in the sole ExoPlayer factory, with the media id bound before preparation for normal, crossfade and precache players. It measures only bytes actually consumed by the delegate, retaining original buffer bytes/positions, handling partial-buffer retries without duplication and subtracting the renderer's stream offset from PCM timestamps. The wrapper requires decoded PCM rather than compressed passthrough/offload; codec selection, the existing effects chain and audio focus remain delegated. The bounded in-memory store retains recent previews (8 unobserved tracks, active subscribers retained; at most six hours per preview), publishes from the first decoded buffer and keeps missing seek ranges as zero/flat slots. Opening the player late receives the latest preview immediately. Partial live previews are not written to `.wf` or treated as complete; the existing AutoMix offline analysis/PCM/downsampling and `.wf`/`.mix` formats are retained. Desktop keeps its mpv progress reader. No dependency/native rebuild is introduced. Added buffer/RMS/seek/identity tests have not been compiled or executed, and Android audio/UI behavior remains unverified under the no-auto-build rule; do not use a standalone FFmpeg result as native verification. - **Timed comments**: YouTube comments carry no moment of their own, so only the ones whose text names one float over the waveform, at the first "m:ss" or "h:mm:ss" in them — read with `TIMESTAMP_REGEX`, the regex `DescriptionView` uses for its seek links, so both read a moment by one rule. They come from the first comments page of the track; the comment count beside the icon comes from the same page. - The landscape fullscreen-lyrics page has no SoundCloud rows; its `when` falls to `else` and borrows Classic's. @@ -1148,6 +1149,8 @@ if (getPlatform() == Platform.Android) { - The YAML reader rejects anchors/aliases and duplicate keys, caps nesting at 12 and input at 1,000,000 UTF-16 code units (with the same code-point budget in the engine), ignores unrelated fields, and rejects unsupported document versions. Missing, malformed, empty or unusable Lyricsfile data falls back to the old fields; instrumental YAML does not invent lyrics. Parser exception messages are not logged because they may include the input text. The raw YAML is not written to a separate store: the normalized `Lyrics` still uses the existing cache, contribution and display paths. - The request remains `/api/search?q= `. Record selection first applies the existing inclusive 10-second duration tolerance (all results are eligible when duration is unknown), then prefers the first candidate with `hasWordSync = true`; if none has that flag, it keeps the first eligible result. The optional flag defaults to false for older responses. Response order within either group is retained; no new album/name scoring or duration-threshold change was added. The selected record still goes through YAML validation and legacy-field fallback. No database migration, UI change or extra HTTP request was added. Common tests cover YAML formats, timing/whitespace, mixed lines, limits, record priority and legacy fallbacks; these have **not been compiled or executed** under the no-auto-build rule. + - **Kaml/Kotaml collision (2026-11-10)**: Kotaml retains Kaml's `com.charleskorn.kaml` package, so their different Maven coordinates otherwise allow duplicate classes into Android and Desktop. The root `build.gradle.kts` resolution rule redirects `com.charleskorn.kaml:kaml` and its `kaml-*` platform modules to the corresponding `io.heapy.kotaml:kotaml*` at `libs.versions.kotaml`. Keep one implementation rather than excluding packaged classes or downgrading the parser, which uses Kotaml's `maxNestingDepth`. Cached Ktor OpenAPI and Wire consumers' referenced JVM members were checked against the replacement; Gradle resolution/build and runtime remain unverified until the owner builds. + ## 🔄 CLAUDE.md Auto-Update Rule (MANDATORY) After completing any of the following types of changes, the AI agent **MUST** update this CLAUDE.md file: @@ -1172,6 +1175,6 @@ After completing any of the following types of changes, the AI agent **MUST** up *This document helps AI Agents quickly understand the SimpMusic project. Update regularly when there are major changes to architecture or structure.* -**Last updated**: 2026-11-09 +**Last updated**: 2026-11-10 **Project version**: Check latest release on GitHub **Maintained by**: maxrave-dev and contributors diff --git a/build.gradle.kts b/build.gradle.kts index f7ee8c8fed..5369d9ac95 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -51,6 +51,17 @@ subprojects { configurations.all { resolutionStrategy { force("com.github.TeamNewPipe:nanojson:c7a6c1c08d16b6d5ecded34758e6415e07be2166") + + // Kotaml retains Kaml's com.charleskorn.kaml package. Different Maven coordinates + // otherwise let both copies reach DEX. Align root and platform-specific modules. + eachDependency { + if (requested.group == "com.charleskorn.kaml" && + (requested.name == "kaml" || requested.name.startsWith("kaml-")) + ) { + useTarget("io.heapy.kotaml:${requested.name.replaceFirst("kaml", "kotaml")}:${libs.versions.kotaml.get()}") + because("Kotaml and Kaml provide the same classes; use one YAML implementation") + } + } } } -} \ No newline at end of file +} diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index f07f235c96..f3413e0ba7 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -1088,4 +1088,5 @@ The browser data changed while it was being read. Close the browser and try again. Sign-in could not be verified. Check your connection, or sign in again in this browser profile and refresh. Refresh browser profiles + %1$s - song info diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentSoundCloud.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentSoundCloud.kt index 51650ea255..5c86a42774 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentSoundCloud.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentSoundCloud.kt @@ -2,7 +2,12 @@ package com.maxrave.simpmusic.ui.screen.player.content import androidx.compose.animation.AnimatedContent import androidx.compose.animation.Crossfade +import androidx.compose.animation.core.LinearEasing +import androidx.compose.animation.core.RepeatMode +import androidx.compose.animation.core.animateFloat import androidx.compose.animation.core.animateFloatAsState +import androidx.compose.animation.core.infiniteRepeatable +import androidx.compose.animation.core.rememberInfiniteTransition import androidx.compose.animation.core.tween import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut @@ -26,12 +31,11 @@ import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.statusBars import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.windowInsetsPadding +import androidx.compose.foundation.pager.HorizontalPager import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.FilledIconButton import androidx.compose.material3.Icon import androidx.compose.material3.IconButton -import androidx.compose.material3.IconButtonDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable @@ -39,6 +43,7 @@ import androidx.compose.runtime.IntState import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue +import androidx.compose.runtime.key import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableLongStateOf import androidx.compose.runtime.mutableStateOf @@ -52,12 +57,14 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.blur import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.clipToBounds import androidx.compose.ui.draw.drawBehind import androidx.compose.ui.draw.drawWithContent import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.BlendMode import androidx.compose.ui.graphics.BlurEffect +import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.CompositingStrategy import androidx.compose.ui.graphics.TileMode @@ -100,6 +107,7 @@ import com.maxrave.simpmusic.extension.lengthLabel import com.maxrave.simpmusic.extension.smoothScrimBrush import com.maxrave.simpmusic.getPlatform import com.maxrave.simpmusic.ui.component.LiquidGlassContainer +import com.maxrave.simpmusic.ui.component.LiquidGlassIconButton import com.maxrave.simpmusic.ui.component.RippleIconButton import com.maxrave.simpmusic.ui.component.TIMESTAMP_REGEX import com.maxrave.simpmusic.ui.component.liquidGlass @@ -145,6 +153,8 @@ import org.jetbrains.compose.resources.stringResource import org.koin.compose.viewmodel.koinViewModel import simpmusic.composeapp.generated.resources.Res import simpmusic.composeapp.generated.resources.comment_placeholder +import simpmusic.composeapp.generated.resources.crossfading +import simpmusic.composeapp.generated.resources.soundcloud_play_count_info import kotlin.math.abs import kotlin.math.roundToInt @@ -395,14 +405,40 @@ private fun NowPlayingSoundCloudLayout( .background(colors.surfaceContainer) .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null, onClick = togglePlayPause), ) { - SoundCloudArtwork( - state = state, - actions = actions, - showVideo = showVideo, - showSubtitle = showSubtitle, - lowerBlockHeight = lowerBlockHeight, - modifier = artworkModifier, - ) + if (getPlatform() == Platform.Android) { + LeftToRight { + HorizontalPager( + state = state.artworkPagerState, + // Record the visible pager once, not each neighboring page, for the glass. + modifier = artworkModifier.fillMaxSize(), + beyondViewportPageCount = 1, + userScrollEnabled = state.controllerState.repeatState !is RepeatState.One && state.artworkQueue.isNotEmpty(), + key = { page -> + val id = state.artworkQueue.getOrNull(page)?.videoId.orEmpty() + "soundCloudArtwork_${id}_$page" + }, + ) { page -> + SoundCloudArtwork( + state = state, + actions = actions, + showVideo = showVideo, + showSubtitle = showSubtitle, + lowerBlockHeight = lowerBlockHeight, + modifier = Modifier.clipToBounds(), + page = page, + ) + } + } + } else { + SoundCloudArtwork( + state = state, + actions = actions, + showVideo = showVideo, + showSubtitle = showSubtitle, + lowerBlockHeight = lowerBlockHeight, + modifier = artworkModifier, + ) + } androidx.compose.animation.AnimatedVisibility( visible = !scrubbing, @@ -457,7 +493,17 @@ private fun NowPlayingSoundCloudLayout( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(10.dp), ) { - RoundButton(backdrop = backdrop, icon = state.dismissIcon, size = 40.dp, iconSize = 24.dp, onClick = actions.onDismiss) + LiquidGlassIconButton( + backdrop = backdrop, + imageVector = state.dismissIcon, + modifier = Modifier.size(40.dp), + tint = colors.onSurface, + // Closing already animates the whole sheet; do not animate refraction and + // press-scale on this button at the same time. + interactive = false, + highlight = Highlight(width = 1.dp), + onClick = actions.onDismiss, + ) // The output button Classic and M3 Expressive use, opening the same sheet. CornerIconButton( backdrop = backdrop, @@ -606,7 +652,8 @@ private fun NowPlayingSoundCloudLayout( // Time runs left to right in every language: the waveform's drag, its playhead and its label. LeftToRight { SoundCloudWaveform( - bars = waveform?.takeIf { it.videoId == videoId }?.bars, + mediaId = videoId, + bars = waveform?.takeIf { it.videoId == videoId }?.bars?.takeIf { it.isNotEmpty() }, position = position, durationMs = durationMs, playedColor = waveformColor, @@ -627,11 +674,12 @@ private fun NowPlayingSoundCloudLayout( ) } } + SoundCloudPlaybackStatus(state = state) Spacer(modifier = Modifier.height(12.dp)) CommentBox( backdrop = backdrop, - onOpen = actions.onShowComments, - onReaction = actions.onWriteComment, + position = position, + onWriteComment = actions.onWriteComment, modifier = Modifier.padding(horizontal = CARD_PADDING), ) } @@ -682,6 +730,60 @@ private fun NowPlayingSoundCloudLayout( } } +/** One stable slot by the waveform: crossfade status takes the stream-quality line's place. */ +@Composable +private fun SoundCloudPlaybackStatus(state: NowPlayingContentState) = LeftToRight { + val colors = MaterialTheme.colorScheme + val transition = rememberInfiniteTransition(label = "soundCloudCrossfadeSweep") + val sweep by transition.animateFloat( + initialValue = 0f, + targetValue = 1f, + animationSpec = infiniteRepeatable(animation = tween(3200, easing = LinearEasing), repeatMode = RepeatMode.Restart), + label = "soundCloudSweepHead", + ) + Crossfade( + targetState = state.timelineState.isCrossfading to state.audioQualityLabel, + animationSpec = tween(300), + label = "soundCloudPlaybackStatus", + // Reserve the line even before format metadata arrives, so the waveform never jumps. + modifier = Modifier.fillMaxWidth().height(24.dp), + ) { (crossfading, quality) -> + Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + if (crossfading) { + val span = 140f + val head = sweep * (span * 3f) - span + Text( + text = stringResource(Res.string.crossfading), + style = + typo().labelSmall.copy( + brush = + Brush.horizontalGradient( + 0f to colors.onSurface.copy(alpha = 0.45f), + 0.5f to Color.White, + 1f to colors.onSurface.copy(alpha = 0.45f), + startX = head, + endX = head + span, + tileMode = TileMode.Clamp, + ), + ), + maxLines = 1, + ) + } else if (quality != null) { + Row(modifier = Modifier.padding(vertical = 2.dp), verticalAlignment = Alignment.CenterVertically) { + Icon( + imageVector = SimpIcons.Headphones, + contentDescription = null, + tint = colors.onSurfaceVariant, + modifier = Modifier.size(13.dp), + ) + Spacer(modifier = Modifier.width(4.dp)) + Text(text = quality, style = typo().labelSmall.copy(fontSize = 13.sp), color = colors.onSurfaceVariant, maxLines = 1) + } + } + } + } +} + /** * The artwork filling the card, or what plays in its place: a canvas (Spotify's, or Apple Music's * animated cover) cropped to the card, or the music video at its own shape on black. A video surface @@ -700,8 +802,19 @@ private fun SoundCloudArtwork( showSubtitle: Boolean, lowerBlockHeight: IntState, modifier: Modifier = Modifier, + page: Int? = null, ) { - val canvas = state.screenData.canvasData + // Only the playing page may attach video/canvas or feed the shell's artwork palette. + // Neighboring pages preview their own queue covers; Desktop keeps its existing single page. + val isCurrentPage = page == null || state.artworkQueue.isEmpty() || page == state.currentOrderIndex + val canvas = state.screenData.canvasData.takeIf { isCurrentPage } + val showCurrentVideo = showVideo && isCurrentPage + val thumbnailUrl = + if (isCurrentPage) { + state.screenData.thumbnailURL + } else { + page?.let { state.artworkQueue.getOrNull(it) }?.thumbnails?.maxByOrNull { it.width * it.height }?.url + } Box(modifier = modifier.fillMaxSize()) { var canvasReady by remember(canvas?.url) { mutableStateOf(false) } if (canvas != null) { @@ -713,11 +826,11 @@ private fun SoundCloudArtwork( ) } val coverAlpha by animateFloatAsState( - targetValue = if (showVideo || (canvas != null && canvasReady)) 0f else 1f, + targetValue = if (showCurrentVideo || (canvas != null && canvasReady)) 0f else 1f, animationSpec = tween(COVER_FADE_MS), label = "soundCloudCover", ) - var artworkUrl by remember(state.screenData.thumbnailURL) { mutableStateOf(state.screenData.thumbnailURL) } + var artworkUrl by remember(thumbnailUrl) { mutableStateOf(thumbnailUrl) } val request = ImageRequest .Builder(LocalPlatformContext.current) @@ -726,19 +839,23 @@ private fun SoundCloudArtwork( .diskCacheKey(artworkUrl + "BIGGER") .crossfade(550) .build() - AsyncImage( - model = request, - contentDescription = null, - onSuccess = { actions.onArtworkBitmap(it.result.image.toImageBitmap()) }, - onError = { - val fallback = artworkUrl?.replace("maxresdefault", "hqdefault") - if (fallback != null && fallback != artworkUrl) artworkUrl = fallback - }, - contentScale = ContentScale.Crop, - placeholder = rememberHolderPainter(), - error = rememberHolderPainter(), - modifier = Modifier.fillMaxSize().alpha(coverAlpha), - ) + // Re-enter when a prefetched cover becomes current, even if its URL is unchanged, so the + // memory-cache success still hands the new track's bitmap to the shell. + key(isCurrentPage) { + AsyncImage( + model = request, + contentDescription = null, + onSuccess = { if (isCurrentPage) actions.onArtworkBitmap(it.result.image.toImageBitmap()) }, + onError = { + val fallback = artworkUrl?.replace("maxresdefault", "hqdefault") + if (fallback != null && fallback != artworkUrl) artworkUrl = fallback + }, + contentScale = ContentScale.Crop, + placeholder = rememberHolderPainter(), + error = rememberHolderPainter(), + modifier = Modifier.fillMaxSize().alpha(coverAlpha), + ) + } // From the bottom up to the line of lyrics the cover melts into a blurred copy of itself, faded // in by a DstIn mask on the smoothstep curve the scrim over it uses. At the top of the ramp the // copy is fully transparent, so it leaves no seam (ArtistScreen's header does the same). It fades @@ -764,7 +881,7 @@ private fun SoundCloudArtwork( contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize().alpha(coverAlpha).then(lowerBlur), ) - if (showVideo) { + if (showCurrentVideo) { BoxWithConstraints(modifier = Modifier.fillMaxSize().background(MaterialTheme.colorScheme.surfaceContainerLowest)) { // A frame of the video's own shape, as M3 Expressive and the Apple Music style give // theirs. Without it the view grows to the whole card (its subtitle layer fills its @@ -877,7 +994,7 @@ private fun PlayCountChip( Icon(imageVector = SimpIcons.PlayArrow, contentDescription = null, tint = colors.onSurface, modifier = Modifier.size(14.dp)) Spacer(modifier = Modifier.width(4.dp)) Text( - text = count, + text = stringResource(Res.string.soundcloud_play_count_info, count), style = typo().bodyMedium.copy(fontSize = 12.sp), color = colors.onSurface, maxLines = 1, @@ -886,8 +1003,7 @@ private fun PlayCountChip( } /** - * A round button: liquid glass over the artwork while the app's glass is on, otherwise the black - * circle SoundCloud gives its dismiss control and its paused transport. + * Shared glass surface with its built-in fallback, retaining each control's icon size and state. */ @Composable private fun RoundButton( @@ -899,23 +1015,6 @@ private fun RoundButton( tint: Color = MaterialTheme.colorScheme.onSurface, onClick: () -> Unit, ) { - if (!LocalLiquidGlassEnabled.current) { - FilledIconButton( - onClick = onClick, - enabled = enabled, - modifier = Modifier.size(size), - colors = - IconButtonDefaults.filledIconButtonColors( - containerColor = MaterialTheme.colorScheme.surfaceContainerLowest, - contentColor = tint, - disabledContainerColor = MaterialTheme.colorScheme.surfaceContainerLowest.copy(alpha = 0.6f), - disabledContentColor = tint.copy(alpha = 0.38f), - ), - ) { - Icon(imageVector = icon, contentDescription = null, modifier = Modifier.size(iconSize)) - } - return - } // A 1dp highlight, as on the other small round glass buttons: a circle this size catches only a // short arc of the default directional rim and reads as rimless. LiquidGlassContainer(backdrop = backdrop, modifier = Modifier.size(size), highlight = Highlight(width = 1.dp)) { @@ -931,8 +1030,7 @@ private fun RoundButton( } /** - * Follow and output in the card's corner: plain icons on the artwork as SoundCloud draws them, or - * glass circles matching the dismiss button above them while the app's glass is on. + * Corner controls share the dismiss button's glass circle and solid fallback. */ @Composable private fun CornerIconButton( @@ -941,25 +1039,24 @@ private fun CornerIconButton( tint: Color, onClick: () -> Unit, ) { - if (LocalLiquidGlassEnabled.current) { - RoundButton(backdrop = backdrop, icon = icon, size = 40.dp, iconSize = 24.dp, tint = tint, onClick = onClick) - } else { - RippleIconButton(imageVector = icon, tint = tint, onClick = onClick) - } + RoundButton(backdrop = backdrop, icon = icon, size = 40.dp, iconSize = 24.dp, tint = tint, onClick = onClick) } /** - * SoundCloud's comment box under the waveform: a tap opens the comments sheet, an emoji opens it - * with that emoji already typed. + * The current time leads the placeholder; opening the draft captures that time, including emoji. */ @Composable private fun CommentBox( backdrop: PlatformBackdrop, - onOpen: () -> Unit, - onReaction: (String) -> Unit, + position: () -> Long, + onWriteComment: (String) -> Unit, modifier: Modifier = Modifier, -) { +) = LeftToRight { val colors = MaterialTheme.colorScheme + val latestPosition by rememberUpdatedState(position) + // Refresh just this label once a second, not the whole card on every playhead frame. + val elapsedSecond by remember { derivedStateOf { latestPosition().coerceAtLeast(0L) / 1000L } } + val timestamp = soundCloudCommentTimestamp(elapsedSecond * 1000L) Row( modifier = modifier @@ -974,15 +1071,18 @@ private fun CommentBox( Modifier.clip(CircleShape).background(colors.surfaceContainerLowest.copy(alpha = 0.6f)) }, ).clip(CircleShape) - .clickable(onClick = onOpen) + .clickable { onWriteComment("${soundCloudCommentTimestamp(latestPosition())} ") } .padding(start = 16.dp, end = 6.dp), verticalAlignment = Alignment.CenterVertically, ) { + Text(text = timestamp, style = typo().bodyMedium, color = colors.onSurfaceVariant, maxLines = 1) + Spacer(modifier = Modifier.width(8.dp)) Text( text = stringResource(Res.string.comment_placeholder), style = typo().bodyMedium, color = colors.onSurfaceVariant, maxLines = 1, + overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f), ) QUICK_REACTIONS.forEach { emoji -> @@ -992,13 +1092,25 @@ private fun CommentBox( modifier = Modifier .clip(CircleShape) - .clickable { onReaction(emoji) } + .clickable { onWriteComment("${soundCloudCommentTimestamp(latestPosition())} $emoji") } .padding(horizontal = 8.dp, vertical = 4.dp), ) } } } +/** YouTube-compatible timestamps, including hour-long tracks; captured again at the actual tap. */ +internal fun soundCloudCommentTimestamp(positionMs: Long): String { + val totalSeconds = positionMs.coerceAtLeast(0L) / 1000L + val seconds = (totalSeconds % 60L).toString().padStart(2, '0') + val minutes = totalSeconds / 60L + return if (minutes < 60L) { + "${minutes.toString().padStart(2, '0')}:$seconds" + } else { + "${minutes / 60L}:${(minutes % 60L).toString().padStart(2, '0')}:$seconds" + } +} + @Composable private fun TimedCommentBubble(comment: TimedComment) { Row( diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/soundcloud/SoundCloudWaveform.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/soundcloud/SoundCloudWaveform.kt index 274557e079..d085dc7f61 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/soundcloud/SoundCloudWaveform.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/soundcloud/SoundCloudWaveform.kt @@ -45,6 +45,7 @@ import androidx.compose.ui.unit.dp import com.maxrave.domain.mediaservice.player.WAVEFORM_BARS_PER_SECOND import com.maxrave.simpmusic.extension.formatDuration import com.maxrave.simpmusic.ui.theme.typo +import kotlinx.coroutines.launch import kotlin.math.abs import kotlin.math.ceil import kotlin.math.floor @@ -65,6 +66,7 @@ import kotlin.math.roundToLong */ @Composable internal fun SoundCloudWaveform( + mediaId: String, bars: FloatArray?, position: () -> Long, durationMs: Long, @@ -104,12 +106,22 @@ internal fun SoundCloudWaveform( // waveform arrives a few seconds after the track, once it is decoded: it rises out of the line // instead of popping in, and on a track change the old one sinks back into the line first. var shownBars by remember { mutableStateOf(null) } + var shownMediaId by remember { mutableStateOf(mediaId) } val rise = remember { Animatable(0f) } - LaunchedEffect(bars) { - if (bars === shownBars) return@LaunchedEffect - if (shownBars != null) rise.animateTo(0f, tween(SINK_MS, easing = LinearEasing)) + val revealedBars = remember { Animatable(0f) } + LaunchedEffect(mediaId, bars) { + if (mediaId == shownMediaId && bars === shownBars) return@LaunchedEffect + if (mediaId != shownMediaId || bars == null) { + if (shownBars != null) rise.animateTo(0f, tween(SINK_MS, easing = LinearEasing)) + revealedBars.snapTo(0f) + shownMediaId = mediaId + } shownBars = bars - if (bars != null) rise.animateTo(1f, tween(RISE_MS, easing = LinearEasing)) + if (bars != null) { + // Appending data must not sink/restart the whole waveform. Only newly loaded bars rise. + launch { rise.animateTo(1f, tween(RISE_MS, easing = LinearEasing)) } + revealedBars.animateTo(bars.size.toFloat(), tween(RISE_MS, easing = LinearEasing)) + } } BoxWithConstraints( @@ -138,7 +150,8 @@ internal fun SoundCloudWaveform( Canvas(modifier = Modifier.fillMaxWidth().height(WAVEFORM_HEIGHT)) { val positionMs = currentPosition() val shown = shownBars - val barCount = shown?.size ?: (durationMs / 1000f * WAVEFORM_BARS_PER_SECOND).toInt() + // Keep the complete timeline; time not decoded yet is a flat line, not stretched data. + val barCount = maxOf(shown?.size ?: 0, (durationMs / 1000.0 * WAVEFORM_BARS_PER_SECOND).toInt()) if (barCount <= 0) return@Canvas val step = stepPx.toFloat() val barWidth = BAR_WIDTH.roundToPx().coerceIn(1, stepPx - 1).toFloat() @@ -158,11 +171,13 @@ internal fun SoundCloudWaveform( val risen = rise.value val playheadBar = (playheadX - origin) / step val reach = (size.width / 2f / step).coerceAtLeast(1f) + val loaded = revealedBars.value fun levelAt(i: Int): Float { - val target = shown?.getOrNull(i) ?: return FLAT_LEVEL + val target = shown?.getOrNull(i)?.takeIf { it > 0f } ?: return FLAT_LEVEL val t = (risen * (1f + RISE_STAGGER) - abs(i - playheadBar) / reach * RISE_STAGGER).coerceIn(0f, 1f) - return FLAT_LEVEL + (target - FLAT_LEVEL) * t * t * (3f - 2f * t) + val available = (loaded - i).coerceIn(0f, 1f) + return FLAT_LEVEL + (target - FLAT_LEVEL) * t * t * (3f - 2f * t) * available } fun DrawScope.drawBars( diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/SoundCloudPlayerViewModel.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/SoundCloudPlayerViewModel.kt index aced8ffeb9..d0ce71f789 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/SoundCloudPlayerViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/SoundCloudPlayerViewModel.kt @@ -9,11 +9,14 @@ import com.maxrave.simpmusic.viewModel.base.BaseViewModel import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job +import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.firstOrNull +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.withContext @@ -21,6 +24,7 @@ import kotlinx.coroutines.withContext class TrackWaveform( val videoId: String, val bars: FloatArray, + val isComplete: Boolean = false, ) /** The first page of a track's YouTube comments, as the SoundCloud style reads it. */ @@ -65,18 +69,33 @@ class SoundCloudPlayerViewModel( * still on screen, and a track came back to without a waveform is tried afresh. */ private fun loadWaveform(videoId: String) { - if (_waveform.value?.videoId == videoId) return + if (_waveform.value?.let { it.videoId == videoId && it.isComplete } == true) return if (videoId == waveformVideoId && waveformJob?.isActive == true) return waveformVideoId = videoId waveformJob?.cancel() - _waveform.value = null + if (_waveform.value?.videoId != videoId) _waveform.value = TrackWaveform(videoId, floatArrayOf()) waveformJob = viewModelScope.launch { WAVEFORM_ATTEMPT_DELAYS_MS.forEachIndexed { attempt, wait -> delay(wait) val bars = try { - withContext(Dispatchers.IO) { mediaPlayerHandler.player.loadWaveform(videoId) } + withContext(Dispatchers.IO) { + val loadingContext = currentCoroutineContext() + mediaPlayerHandler.player.loadWaveform(videoId) { partial -> + if (partial.isNotEmpty()) { + // A retry restarts decoding at zero; retain the longer prefix + // already visible until the new pass catches up. + _waveform.update { previous -> + if (!loadingContext.isActive || previous == null || previous.videoId != videoId || partial.size < previous.bars.size) { + previous + } else { + TrackWaveform(videoId, partial) + } + } + } + } + } } catch (e: CancellationException) { throw e } catch (e: Exception) { @@ -84,7 +103,7 @@ class SoundCloudPlayerViewModel( null } if (bars != null && bars.isNotEmpty()) { - _waveform.value = TrackWaveform(videoId, bars) + _waveform.value = TrackWaveform(videoId, bars, isComplete = true) return@launch } Logger.d(tag, "No waveform for $videoId yet, attempt ${attempt + 1} of ${WAVEFORM_ATTEMPT_DELAYS_MS.size}") diff --git a/composeApp/src/jvmTest/kotlin/com/maxrave/simpmusic/ui/screen/player/content/SoundCloudCommentTimestampTest.kt b/composeApp/src/jvmTest/kotlin/com/maxrave/simpmusic/ui/screen/player/content/SoundCloudCommentTimestampTest.kt new file mode 100644 index 0000000000..f34cc572b9 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/maxrave/simpmusic/ui/screen/player/content/SoundCloudCommentTimestampTest.kt @@ -0,0 +1,28 @@ +package com.maxrave.simpmusic.ui.screen.player.content + +import kotlin.test.Test +import kotlin.test.assertEquals + +class SoundCloudCommentTimestampTest { + @Test + fun formatsMinuteAndHourBoundaries() { + listOf( + 0L to "00:00", + 999L to "00:00", + 59_999L to "00:59", + 60_000L to "01:00", + 83_000L to "01:23", + 3_599_999L to "59:59", + 3_600_000L to "1:00:00", + 3_661_000L to "1:01:01", + ).forEach { (position, expected) -> + assertEquals(expected, soundCloudCommentTimestamp(position)) + } + } + + @Test + fun unknownNegativePositionStartsAtZero() { + assertEquals("00:00", soundCloudCommentTimestamp(-1L)) + assertEquals("00:00", soundCloudCommentTimestamp(Long.MIN_VALUE)) + } +} diff --git a/core b/core index 164e89e0d0..a2b0213014 160000 --- a/core +++ b/core @@ -1 +1 @@ -Subproject commit 164e89e0d093492d6f1c9be3f745201b7b4574bb +Subproject commit a2b0213014b5c43e831ee0df25e4399784bbb241 From e2be20e0cc6d4901c37297849bb2b558f8173cc1 Mon Sep 17 00:00:00 2001 From: maxrave-dev Date: Wed, 11 Nov 2026 15:10:42 +0700 Subject: [PATCH 23/29] feat(audio): add 8D audio effect --- CLAUDE.md | 13 +++- composeApp/build.gradle.kts | 2 +- .../composeResources/values/strings.xml | 8 +++ .../ui/screen/home/AudioEffectsSection.kt | 69 ++++++++++++++++++- .../simpmusic/ui/screen/home/SettingScreen.kt | 23 ++++++- .../simpmusic/viewModel/SettingsViewModel.kt | 25 +++++++ core | 2 +- scripts/mpv-linux/Dockerfile | 2 +- 8 files changed, 138 insertions(+), 6 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 280a5719ec..9173d68d15 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1151,6 +1151,17 @@ if (getPlatform() == Platform.Android) { - **Kaml/Kotaml collision (2026-11-10)**: Kotaml retains Kaml's `com.charleskorn.kaml` package, so their different Maven coordinates otherwise allow duplicate classes into Android and Desktop. The root `build.gradle.kts` resolution rule redirects `com.charleskorn.kaml:kaml` and its `kaml-*` platform modules to the corresponding `io.heapy.kotaml:kotaml*` at `libs.versions.kotaml`. Keep one implementation rather than excluding packaged classes or downgrading the parser, which uses Kotaml's `maxNestingDepth`. Cached Ktor OpenAPI and Wire consumers' referenced JVM members were checked against the replacement; Gradle resolution/build and runtime remain unverified until the owner builds. +- **8D audio (2026-11-11, Android + Desktop)**: Settings → Playback, under Reverb: a switch (off by default), a rotation direction (left → right / right → left) and a seconds-per-revolution slider, 3–30 s in 0.5 s steps, default 10 s. Those numbers are SonicLab's own 8D tool (`soniclab.io/tools/8d-audio`, read from its served JS bundle), chosen by the owner after a made-up range was rejected; `EightDEffect` in `core/domain` holds them and `normalizePeriod` clamps and snaps any stored value. Three DataStore keys (`eight_d_enabled`, `eight_d_direction`, `eight_d_period_seconds`), turned into one nullable `EightDEffect` by an identical collector in both handlers and handed to `MediaPlayerInterface.setEightD` — a separate line from `setAudioEffects`, so EQ/Delay/Reverb are untouched. The row is disabled while casting and when the engine refused the filter (`MediaPlayerInterface.eightDAvailable`); a saved on-state can still be switched off then. + - **One orbit for the whole playback, not one per player.** `EightDOrbit` stores the phase plus the wall-clock moment it was taken and evaluates the angle on demand, so changing direction or period keeps the current position, pause freezes it, and the incoming crossfade player, a precached handle and the next track all join the same angle instead of restarting at zero. **The rotation is a head model, not a pan law** (replaced the same day). The first version used Web Audio's equal-power panner at depth 0.95: the far ear lost 22-28 dB at every frequency, and a one-sided recording dropped to silence (-180 dB measured), which the owner found painful. A published 8D track he pointed to measured differently: the far ear 1.8 dB down at the median and 9 dB at worst, bands under 500 Hz within a few dB, bands above 4 kHz up to 17.8 dB apart, and the far ear 0.67-0.77 ms late. `EightDHead` is Brown & Duda's spherical-head model (IEEE TSAP 6(5), 1998, p. 477, eq. 2-5; a = 8.75 cm, c = 343 m/s, α_min = 0.1, θ_min = 150°, read off the paper itself): each ear renders its OWN channel from its angle of incidence, with Woodworth's delay (0.656 ms side to side) and the one-pole-one-zero head-shadow filter `EightDHeadShadow`. It predicts 0 dB lows, 17 dB apart at the highs and 0.656 ms, matching the track. **At every angle the paper's shadow is divided by the brighter ear's response** (`H(α)/H(α_b)` with `α_b = max(α(θ), α(π − θ))`: pole `EightDHead.shadowPole` = β/α_b, high-frequency gain `shadowGain` = α/α_b; bilinear with K = 2·fs, not prewarped, since the pole moves). Equation (3) as written lifts the near ear's highs up to 6 dB, and through the new libmpv a master peaking at −0.0 dBFS came out at +4.7 dBFS with 4335 clipped samples in 40 s — the owner heard it as "vỡ tùm lum". Dividing by the near ear alone (α/2) fixed the clipping but left both ears 8 dB darker facing front: −1.38 LU on average and −1.81 LU at front/back (BS.1770 over 400 ms blocks), "giảm nhỏ tiếng khó chịu". Divided by the brighter ear, that ear is an exact identity and the other keeps the paper's ratio; the impulse response is non-negative and sums to 1, so no sample grows (same master: peak 0.973, none clipped; −0.74 LU on average, −0.5 front/back, −0.95 at the sides — what is left is the far ear's shaded highs, i.e. the effect). **The song is not folded to mono** (first head-model version did `(L+R)/2`): the whole mix became one small point and its wide parts combed hollow ("ở trong 1 cái Stadium hình cầu mà nó nhỏ"). The linked track keeps its stereo: side-to-mid energy facing front 0.088 under 300 Hz against the original's 0.116, and above the original's from 300 Hz to 3 kHz. A one-sided recording therefore stays one-sided; centred content reaches both ears at full level at every angle. Toggling fades over 50 ms (SonicLab's ramp). A stalled player stops the orbit with it (Android `onIsLoadingChanged`, Desktop's `buffering` callback), since the PLAYING state survives a stall. + - **Audio rendered before a player starts must stay dry, on both platforms.** ExoPlayer renders while paused (`ExoPlayerImplInternal.doSomeWork` calls `render()` in READY and BUFFERING alike), and mpv fills its output before PLAYBACK_RESTART, so a precache has processed its first fraction of a second long before anyone knows when it will be heard; joining the orbit then put each precached track at a random angle. That audio is left dry, and the track joins the live orbit with the 50 ms fade when it starts: Android through a `Player.Listener.onPlayWhenReadyChanged` added in `createExoPlayerInstance` (every way a player starts passes through it, so the processor is not threaded through `PlayerWithFilter`), Desktop in `MpvPlayer.play()` on the handle's first play. A player started before it renders anything joins at full depth. + - **Android** renders the full model: each channel's history read by 4-point Catmull-Rom for its ear's fractional delay (linear interpolation low-passes half-sample delays by up to 6 dB at 16 kHz, varying with the angle; both ears read one sample late so the newer neighbour exists; the price is an overshoot of at most 1.25× on full-scale edges — a Python port of the kernel kept the same −0.0 dBFS master at 0.974, none clipped, −0.74 LU like Desktop), then each ear's head-shadow filter. It appends `EightDAudioProcessor` AFTER Sonic, by subclassing `DefaultAudioSink.DefaultAudioProcessorChain` and overriding `getAudioProcessors()` (Media3 1.11.1 builds the pipeline from it, `DefaultAudioSink.java:759`); the chain's own Sonic/silence-skip timing methods stay as they are. After Sonic, one turn lasts the chosen wall-clock time whatever the playback speed or DJ tempo. Stereo PCM 16-bit and float only; anything else passes through. **A flush keeps the kernel's own phase**: Media3 flushes the pipeline on a seek AND on every speed/pitch change (`applyAudioProcessorPlaybackParametersAndSkipSilence` → `setupAudioProcessors`), and only the seek empties the AudioTrack, so rejoining the orbit on flush threw the angle back by everything the AudioTrack still held — on every AutoMix speed step. + - **Desktop** writes a fourth `af` tier: `aeval` computing the same per-channel head-shadow filter per sample from `phase + ω·n/s`, with the live orbit phase written into the expression. aeval keeps a separate variable set per channel that survives between samples (measured with ffmpeg 8.0.1: a counter reached n on both channels, not 2n), which holds each ear's filter state in `ld(6)`/`ld(7)`; ffmpeg's `mod()` floors like Kotlin's `floor`, so the angle wrap matches. aeval keeps no sample history, so **Desktop has no interaural delay** — the one difference from Android, accepted by the owner. Measured through the rebuilt libmpv with `ao=pcm` on the first (mono-fold, unnormalized) graph: a 200 Hz tone stayed within 0.4 dB between the ears through the whole turn and an 8 kHz tone swung +5.9/-14.8 dB (deepest at θ_min, as the paper's α_min predicts); the current graph was re-measured only for peaks and width (above). A user `scaletempo2` goes in front of it, because mpv hands `SET_SPEED` to the last user filter that accepts it before its own post-chain speed filter (`f_output_chain.c` `set_speed_any`), which puts 8D after the speed change; it is left out while rubberband (AutoMix/pitch) is in the chain, since rubberband already takes the speed there. + - **mpv rebuilds every lavfi graph on reset** (`f_lavfi.c` `lavfi_reset` → `free_graph`), so after a seek or a `loop-file` wrap `n` restarts at 0 and the graph would replay the phase it was installed with, then jump once the refilled output drained. `MpvPlayer.seekTo` writes the live phase BEFORE seeking, so the rebuild starts on it; for `loop-file` wraps the new `MPV_EVENT_SEEK` callback (`seeking`, sent right after the reset in `playloop.c` `mp_seek`, before the refill) does it. Both that and `restarted` (every `PLAYBACK_RESTART`, where the first install happens — never before, so a missing filter cannot fail a track's load) go through `MpvPlayer.syncEightD()` via the adapter's `EightDSyncListener`, which the current handle's listener and the crossfade's incoming handle's listener both extend. A 500 ms guard stops a loop: rewriting `af` while audio plays can itself issue a refresh seek (`audio.c` `reinit_audio_filters`, when ≥0.2 s of buffered audio is dropped). A plain resume rewrites nothing: graph and orbit both stood still. + - A refused `aeval` drops only the 8D tier and only on that handle; `applyAudioFilters` handles it for every writer (EQ, effects, crossfade), blaming 8D only when the chain is accepted without it. The adapter then sets `eightDAvailable` false for the session and clears 8D on every live handle, so a precache that was given 8D earlier cannot take the effects tier down with it. + - **Setting the `af` PROPERTY never reports a filter that fails to build.** The option change runs through `mp_option_change_callback`, which ignores `set_filters`' result: mpv logs "Audio filter initialized failed!", keeps the old live chain, and `mpv_set_property_string` returns 0. Measured with ctypes on the bundled Linux libmpv (no `aeval`): property → rc 0; the `af set ` COMMAND (`edit_filters`) → rc -12 with the previous chain restored. So `MpvPlayer.writeAf()` uses the command. Before that, every write carrying the 8D tier was silently dropped on Linux — EQ, reverb and the DJ sweep stopped updating (`af-command simpDjSweep … failed` on every step of a crossfade), and 8D still showed as available. The same false success had made every earlier "did mpv accept it" check on `af` (reverb's tiered fallback, the rubberband pitch check) unable to fire. + - **Linux slice rebuilt with `aeval` (2026-11-11).** `aeval` joined the FFmpeg `--enable-filter` list in `scripts/mpv-linux/Dockerfile`; the slice was rebuilt natively on ubuntu-work (38 libs, every object x86-64 ET_DYN, no glib, every other filter unchanged), republished on `abc` and pinned in `mpvNativesChecksums` (`f2f56dc6…45b0`, 16,035,411 B; the public URL served it at once). Checked by playing a left-only tone through that libmpv with `ao=pcm` and the app's 8D tier written by `af set`: the tone moved between the ears at the chosen period, while the previous slice answered `af set` with -12 and stayed left-only. The staged macOS (arm64, x64) and Windows (arm64, x64) slices carry `aeval` already. + - Tests: `EightDEffectTest` (domain commonTest), `EightDKernelTest` (media3), `EightDGraphsTest` (media-jvm, which gained `testImplementation(libs.junit)`). Written, not run; nothing was built or listened to. aeval parses its expression only when the output is configured, so `EightDGraphsTest` cannot catch a broken one: the graph string was run through ffmpeg 8.0.1 and through the rebuilt libmpv instead (the measurements above; `1.0E-4` phases parse). The kernel's expected numbers were checked against a line-for-line Python port first: ILD 0.41 dB at 200 Hz, 16.3 dB at 8 kHz, 17.8 dB at 12 kHz with the source at the right ear, far ear 30-31 samples late at 48 kHz, 0.5/0.5 on both ears for a left-only DC input at every azimuth. + ## 🔄 CLAUDE.md Auto-Update Rule (MANDATORY) After completing any of the following types of changes, the AI agent **MUST** update this CLAUDE.md file: @@ -1175,6 +1186,6 @@ After completing any of the following types of changes, the AI agent **MUST** up *This document helps AI Agents quickly understand the SimpMusic project. Update regularly when there are major changes to architecture or structure.* -**Last updated**: 2026-11-10 +**Last updated**: 2026-11-11 **Project version**: Check latest release on GitHub **Maintained by**: maxrave-dev and contributors diff --git a/composeApp/build.gradle.kts b/composeApp/build.gradle.kts index 8d4a3f2d56..a912548aaf 100644 --- a/composeApp/build.gradle.kts +++ b/composeApp/build.gradle.kts @@ -764,7 +764,7 @@ val mpvBundleAll by tasks.registering { */ val mpvNativesChecksums = mapOf( - "linux-x64" to "ab9957e812f6b27ef28d24b13d38a00b428a6529c87876c1c80d0427d8251d05", + "linux-x64" to "f2f56dc629b2b6f4a7face7361eb749b26416df4ea5fabe0cb50aaf3506745b0", "macos-arm64" to "e527daac8f6cc196324ea6f0ce54d119d04450af9795ff2856c1891806c1d5e0", "macos-x64" to "95170ea54e1f637fdee148a9efd97993c305a92e233b8478d3764fbecce3eb02", "windows-x64" to "256f17cf402c7583b8684d5a7cf585ad1b59695469219671f4887b9d8d272a99", diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index f3413e0ba7..56789955c6 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -357,6 +357,14 @@ Echo the sound with a repeating delay Reverb Place the music in a room, hall or plate + 8D audio + Rotating stereo sound. Best with headphones. + Rotation direction + Left → Right + Right → Left + Time per revolution + s + 8D is unavailable in this audio engine Time Feedback Mix diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/AudioEffectsSection.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/AudioEffectsSection.kt index 5d0767790f..d22240fc40 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/AudioEffectsSection.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/AudioEffectsSection.kt @@ -27,10 +27,15 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextDirection +import androidx.compose.ui.text.TextStyle import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.maxrave.domain.data.player.DelayEffect +import com.maxrave.domain.data.player.EightDDirection +import com.maxrave.domain.data.player.EightDEffect import com.maxrave.domain.data.player.ReverbPreset +import com.maxrave.simpmusic.extension.LeftToRight import com.maxrave.simpmusic.ui.component.Chip import com.maxrave.simpmusic.ui.component.RippleIconButton import com.maxrave.simpmusic.ui.icon.Help @@ -47,6 +52,11 @@ import simpmusic.composeapp.generated.resources.delay_preset_slapback import simpmusic.composeapp.generated.resources.effect_feedback import simpmusic.composeapp.generated.resources.effect_mix import simpmusic.composeapp.generated.resources.effect_time +import simpmusic.composeapp.generated.resources.eight_d_direction +import simpmusic.composeapp.generated.resources.eight_d_left_to_right +import simpmusic.composeapp.generated.resources.eight_d_right_to_left +import simpmusic.composeapp.generated.resources.eight_d_period +import simpmusic.composeapp.generated.resources.eight_d_seconds_unit import simpmusic.composeapp.generated.resources.ok import simpmusic.composeapp.generated.resources.reverb_help_cathedral import simpmusic.composeapp.generated.resources.reverb_help_damping @@ -261,6 +271,62 @@ fun ReverbSection(viewModel: SettingsViewModel = koinViewModel()) { } } +/** Direction and explicit seconds per turn, not a combined intensity level. */ +@Composable +fun EightDSection(viewModel: SettingsViewModel = koinViewModel()) { + val direction by viewModel.eightDDirection.collectAsStateWithLifecycle() + val period by viewModel.eightDPeriodSeconds.collectAsStateWithLifecycle() + val secondsUnit = stringResource(Res.string.eight_d_seconds_unit) + val periodLabel = stringResource(Res.string.eight_d_period) + val periodLabelStyle = typo().bodySmall.copy(textDirection = TextDirection.Content) + EffectCard { + Text( + text = stringResource(Res.string.eight_d_direction), + style = typo().bodySmall, + modifier = Modifier.padding(bottom = 8.dp), + ) + LeftToRight { + EffectPresetRow { + Chip( + isSelected = direction == EightDDirection.LEFT_TO_RIGHT, + text = stringResource(Res.string.eight_d_left_to_right), + onClick = { viewModel.setEightDDirection(EightDDirection.LEFT_TO_RIGHT) }, + ) + Chip( + isSelected = direction == EightDDirection.RIGHT_TO_LEFT, + text = stringResource(Res.string.eight_d_right_to_left), + onClick = { viewModel.setEightDDirection(EightDDirection.RIGHT_TO_LEFT) }, + ) + } + } + LeftToRight { + Column { + EffectSlider( + label = periodLabel, + labelStyle = periodLabelStyle, + value = period, + valueRange = EightDEffect.MIN_PERIOD_SECONDS..EightDEffect.MAX_PERIOD_SECONDS, + snap = EightDEffect::normalizePeriod, + readout = { + val seconds = EightDEffect.normalizePeriod(it) + "${if (seconds % 1f == 0f) seconds.toInt().toString() else seconds.toString()} $secondsUnit" + }, + onCommit = viewModel::setEightDPeriodSeconds, + modifier = Modifier.padding(top = 12.dp), + ) + // Match the Slider's weighted width, excluding its existing 60dp value + 12dp gap. + Row( + modifier = Modifier.fillMaxWidth().padding(end = EFFECT_READOUT_WIDTH + 12.dp), + horizontalArrangement = Arrangement.SpaceBetween, + ) { + Text("${EightDEffect.MIN_PERIOD_SECONDS.toInt()} $secondsUnit", style = typo().bodySmall) + Text("${EightDEffect.MAX_PERIOD_SECONDS.toInt()} $secondsUnit", style = typo().bodySmall) + } + } + } + } +} + /** * What the four rooms and the mix slider actually do, in the user's language. * @@ -402,6 +468,7 @@ private fun EffectSlider( onCommit: (Float) -> Unit, modifier: Modifier = Modifier, snap: (Float) -> Float = { it }, + labelStyle: TextStyle? = null, ) { var draft by remember { mutableStateOf(null) } LaunchedEffect(value) { draft = null } @@ -410,7 +477,7 @@ private fun EffectSlider( Column(modifier = modifier.fillMaxWidth()) { Text( text = label, - style = typo().bodySmall, + style = labelStyle ?: typo().bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(bottom = 4.dp), ) diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/SettingScreen.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/SettingScreen.kt index f5de7582ed..2881398c48 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/SettingScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/SettingScreen.kt @@ -201,6 +201,9 @@ import simpmusic.composeapp.generated.resources.audio_delay import simpmusic.composeapp.generated.resources.audio_delay_description import simpmusic.composeapp.generated.resources.audio_reverb import simpmusic.composeapp.generated.resources.audio_reverb_description +import simpmusic.composeapp.generated.resources.audio_eight_d +import simpmusic.composeapp.generated.resources.audio_eight_d_description +import simpmusic.composeapp.generated.resources.eight_d_unavailable import simpmusic.composeapp.generated.resources.author import simpmusic.composeapp.generated.resources.auto_backup import simpmusic.composeapp.generated.resources.auto_backup_description @@ -593,6 +596,8 @@ fun SettingScreen( val equalizerType by viewModel.equalizerType.collectAsStateWithLifecycle() val delayEnabled by viewModel.delayEnabled.collectAsStateWithLifecycle() val reverbEnabled by viewModel.reverbEnabled.collectAsStateWithLifecycle() + val eightDEnabled by viewModel.eightDEnabled.collectAsStateWithLifecycle() + val eightDAvailable by viewModel.eightDAvailable.collectAsStateWithLifecycle() val lastfmLoggedIn by viewModel.lastfmLoggedIn.collectAsStateWithLifecycle() val lastfmUsername by viewModel.lastfmUsername.collectAsStateWithLifecycle() val lastfmScrobbleEnabled by viewModel.lastfmScrobbleEnabled.collectAsStateWithLifecycle() @@ -1525,6 +1530,22 @@ fun SettingScreen( AnimatedVisibility(visible = reverbEnabled) { ReverbSection() } + SettingItem( + title = stringResource(Res.string.audio_eight_d), + subtitle = + when { + castState.isRemote -> stringResource(Res.string.not_available_while_casting) + !eightDAvailable -> stringResource(Res.string.eight_d_unavailable) + else -> stringResource(Res.string.audio_eight_d_description) + }, + smallSubtitle = true, + switch = (eightDEnabled to viewModel::setEightDEnabled), + // A saved on-state may still be switched off when the native filter is absent. + isEnable = !castState.isRemote && (eightDAvailable || eightDEnabled), + ) + AnimatedVisibility(visible = eightDEnabled && eightDAvailable && !castState.isRemote) { + EightDSection() + } SettingItem( title = stringResource(Res.string.save_playback_state), subtitle = stringResource(Res.string.save_shuffle_and_repeat_mode), @@ -3581,4 +3602,4 @@ private fun ImportProgressDialog( } }, ) -} \ No newline at end of file +} diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/SettingsViewModel.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/SettingsViewModel.kt index f1c67be76b..6baa36a245 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/SettingsViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/SettingsViewModel.kt @@ -13,6 +13,8 @@ import com.maxrave.domain.data.entities.DownloadState import com.maxrave.domain.data.entities.GoogleAccountEntity import com.maxrave.domain.data.model.lyrics.RomanizationDictionaryState import com.maxrave.domain.data.player.GenericCastState +import com.maxrave.domain.data.player.EightDDirection +import com.maxrave.domain.data.player.EightDEffect import com.maxrave.domain.data.player.ReverbPreset import com.maxrave.domain.extension.toNetScapeString import com.maxrave.domain.manager.DataStoreManager @@ -86,6 +88,7 @@ class SettingsViewModel( private val downloadUtils: DownloadHandler by inject() val castState: StateFlow get() = mediaPlayerHandler.castState + val eightDAvailable: StateFlow get() = mediaPlayerHandler.player.eightDAvailable /** READY everywhere the dictionary is bundled (Desktop), so only Android ever leaves it. */ val japaneseDictionaryState: StateFlow = @@ -1870,6 +1873,12 @@ class SettingsViewModel( } private var _delayEnabled: MutableStateFlow = MutableStateFlow(false) + private val _eightDEnabled = MutableStateFlow(false) + val eightDEnabled: StateFlow = _eightDEnabled + private val _eightDDirection = MutableStateFlow(EightDDirection.LEFT_TO_RIGHT) + val eightDDirection: StateFlow = _eightDDirection + private val _eightDPeriodSeconds = MutableStateFlow(EightDEffect.DEFAULT_PERIOD_SECONDS) + val eightDPeriodSeconds: StateFlow = _eightDPeriodSeconds val delayEnabled: StateFlow = _delayEnabled private var _delayTimeMs: MutableStateFlow = MutableStateFlow(DEFAULT_DELAY_TIME_MS) @@ -1918,9 +1927,25 @@ class SettingsViewModel( } } launch { dataStoreManager.reverbMix.collect { _reverbMix.emit(it) } } + launch { dataStoreManager.eightDEnabled.collect { _eightDEnabled.value = it == DataStoreManager.TRUE } } + launch { dataStoreManager.eightDDirection.collect { _eightDDirection.value = EightDDirection.fromStored(it) } } + launch { dataStoreManager.eightDPeriodSeconds.collect { _eightDPeriodSeconds.value = EightDEffect.normalizePeriod(it) } } } } + fun setEightDEnabled(enabled: Boolean) { + if (enabled && !eightDAvailable.value) return + viewModelScope.launch { dataStoreManager.setEightDEnabled(enabled) } + } + + fun setEightDDirection(direction: EightDDirection) { + viewModelScope.launch { dataStoreManager.setEightDDirection(direction) } + } + + fun setEightDPeriodSeconds(seconds: Float) { + viewModelScope.launch { dataStoreManager.setEightDPeriodSeconds(seconds) } + } + fun setDelayEnabled(enabled: Boolean) { viewModelScope.launch { dataStoreManager.setDelayEnabled(enabled) } } diff --git a/core b/core index a2b0213014..a4e6231015 160000 --- a/core +++ b/core @@ -1 +1 @@ -Subproject commit a2b0213014b5c43e831ee0df25e4399784bbb241 +Subproject commit a4e62310154c6dc37846237cd7a4ed83708313ed diff --git a/scripts/mpv-linux/Dockerfile b/scripts/mpv-linux/Dockerfile index 8080999fa7..f6d8723bc5 100644 --- a/scripts/mpv-linux/Dockerfile +++ b/scripts/mpv-linux/Dockerfile @@ -83,7 +83,7 @@ RUN git clone --depth 1 --branch n7.1.1 https://github.com/FFmpeg/FFmpeg.git ffm --enable-shared --disable-static \ --disable-programs --disable-doc --disable-debug \ --disable-encoders --disable-muxers --disable-devices \ - --disable-filters --enable-filter=aresample,atempo,rubberband,scale,format,aformat,anull,null,volume,lavfi,acompressor,firequalizer,equalizer,highpass,lowpass,dynaudnorm,loudnorm,aecho,afir,amovie,asplit,amix,asetnsamples,astats,ametadata \ + --disable-filters --enable-filter=aresample,atempo,rubberband,scale,format,aformat,anull,null,volume,lavfi,acompressor,firequalizer,equalizer,highpass,lowpass,dynaudnorm,loudnorm,aecho,afir,amovie,asplit,amix,asetnsamples,astats,ametadata,aeval \ --enable-openssl --enable-protocol=https,http,tls,file,pipe,crypto,hls,data \ --enable-libdav1d \ --enable-version3 \ From c11ee6a38102b6065dd27b71cb12b0afef61f54a Mon Sep 17 00:00:00 2001 From: maxrave-dev Date: Wed, 11 Nov 2026 15:10:42 +0700 Subject: [PATCH 24/29] fix(player): show the comment time only once the SoundCloud draft opens --- .../screen/player/content/NowPlayingContentSoundCloud.kt | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentSoundCloud.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentSoundCloud.kt index 5c86a42774..9790681f5c 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentSoundCloud.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentSoundCloud.kt @@ -1043,7 +1043,8 @@ private fun CornerIconButton( } /** - * The current time leads the placeholder; opening the draft captures that time, including emoji. + * No running time on the box itself (owner's call): the time appears only once the draft opens, + * captured at the tap, emoji included. */ @Composable private fun CommentBox( @@ -1054,9 +1055,6 @@ private fun CommentBox( ) = LeftToRight { val colors = MaterialTheme.colorScheme val latestPosition by rememberUpdatedState(position) - // Refresh just this label once a second, not the whole card on every playhead frame. - val elapsedSecond by remember { derivedStateOf { latestPosition().coerceAtLeast(0L) / 1000L } } - val timestamp = soundCloudCommentTimestamp(elapsedSecond * 1000L) Row( modifier = modifier @@ -1075,8 +1073,6 @@ private fun CommentBox( .padding(start = 16.dp, end = 6.dp), verticalAlignment = Alignment.CenterVertically, ) { - Text(text = timestamp, style = typo().bodyMedium, color = colors.onSurfaceVariant, maxLines = 1) - Spacer(modifier = Modifier.width(8.dp)) Text( text = stringResource(Res.string.comment_placeholder), style = typo().bodyMedium, From 357c521b52d3368897e3a7b20c8db5fa4d1d1ca4 Mon Sep 17 00:00:00 2001 From: maxrave-dev Date: Thu, 12 Nov 2026 16:34:12 +0700 Subject: [PATCH 25/29] feat(sync): add library sync between phone and desktop --- CLAUDE.md | 15 +- .../com/maxrave/simpmusic/MainActivity.kt | 16 + .../maxrave/simpmusic/SimpMusicApplication.kt | 8 + .../service/sync/LibrarySyncScheduler.kt | 54 +++ .../service/sync/LibrarySyncWorker.kt | 22 + .../expect/ui/LibrarySync.android.kt | 390 ++++++++++++++++++ .../simpmusic/expect/ui/LoginSync.android.kt | 27 +- .../composeResources/values/strings.xml | 54 +++ .../maxrave/simpmusic/di/ViewModelModule.kt | 7 +- .../simpmusic/expect/ui/LibrarySync.kt | 108 +++++ .../simpmusic/ui/screen/home/SettingScreen.kt | 63 ++- .../viewModel/LibrarySyncViewModels.kt | 197 +++++++++ .../viewModel/LoginSyncSenderViewModel.kt | 54 ++- .../simpmusic/viewModel/SettingsViewModel.kt | 22 +- .../com/maxrave/simpmusic/DesktopApp.kt | 10 + .../simpmusic/expect/ui/LibrarySync.jvm.kt | 278 +++++++++++++ .../simpmusic/expect/ui/LoginSync.jvm.kt | 2 +- core | 2 +- 18 files changed, 1307 insertions(+), 22 deletions(-) create mode 100644 androidApp/src/main/java/com/maxrave/simpmusic/service/sync/LibrarySyncScheduler.kt create mode 100644 androidApp/src/main/java/com/maxrave/simpmusic/service/sync/LibrarySyncWorker.kt create mode 100644 composeApp/src/androidMain/kotlin/com/maxrave/simpmusic/expect/ui/LibrarySync.android.kt create mode 100644 composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/expect/ui/LibrarySync.kt create mode 100644 composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/LibrarySyncViewModels.kt create mode 100644 composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/expect/ui/LibrarySync.jvm.kt diff --git a/CLAUDE.md b/CLAUDE.md index 9173d68d15..01d11a8021 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -110,7 +110,7 @@ Service modules: - **autoEqService/**: AutoEq headphone correction profiles (index + fixed-band curves) - **lyricsService/**: Lyrics fetching (LRCLIB, SimpMusic Lyrics, BetterLyrics) - **listenTogether/**: shared listening rooms, wire-compatible with Metrolist (`MetrolistGroup/metroproto`) -- **loginSync/**: the QR-paired transport that moves sign-ins from the Android app to the Desktop app (Ktor client on the phone, one-shot Ktor CIO server on the Desktop, AES-256-GCM). Android + JVM targets only; carries opaque bytes — the data layer decides what they mean +- **loginSync/**: the QR-paired transport that moves sign-ins from the Android app to the Desktop app (Ktor client on the phone, one-shot Ktor CIO server on the Desktop, AES-256-GCM). Android + JVM targets only; carries opaque bytes — the data layer decides what they mean. Also carries library sync's long-lived paired channel (`PairedSyncWire`/`PairedSyncClient`/`PairedSyncServer`, fixed port 48517) - **kizzy/**: Discord Rich Presence for FOSS builds (the user's own token, from a WebView login on Android or pasted on Desktop). Left untouched by the OAuth work below - **discord/**: Discord Rich Presence over OAuth for Full builds (package `org.simpmusic.discord`): PKCE login, a Ktor gateway client that identifies with a Bearer token, and the presence itself. Used instead of kizzy whenever the build carries a Discord application id - **ktorExt/**: Ktor extensions for networking @@ -1162,6 +1162,17 @@ if (getPlatform() == Platform.Android) { - **Linux slice rebuilt with `aeval` (2026-11-11).** `aeval` joined the FFmpeg `--enable-filter` list in `scripts/mpv-linux/Dockerfile`; the slice was rebuilt natively on ubuntu-work (38 libs, every object x86-64 ET_DYN, no glib, every other filter unchanged), republished on `abc` and pinned in `mpvNativesChecksums` (`f2f56dc6…45b0`, 16,035,411 B; the public URL served it at once). Checked by playing a left-only tone through that libmpv with `ao=pcm` and the app's 8D tier written by `af set`: the tone moved between the ears at the chosen period, while the previous slice answered `af set` with -12 and stayed left-only. The staged macOS (arm64, x64) and Windows (arm64, x64) slices carry `aeval` already. - Tests: `EightDEffectTest` (domain commonTest), `EightDKernelTest` (media3), `EightDGraphsTest` (media-jvm, which gained `testImplementation(libs.junit)`). Written, not run; nothing was built or listened to. aeval parses its expression only when the output is configured, so `EightDGraphsTest` cannot catch a broken one: the graph string was run through ffmpeg 8.0.1 and through the rebuilt libmpv instead (the measurements above; `1.0E-4` phases parse). The kernel's expected numbers were checked against a line-for-line Python port first: ILD 0.41 dB at 200 Hz, 16.3 dB at 8 kHz, 17.8 dB at 12 kHz with the source at the right ear, far ear 30-31 samples late at 48 kHz, 0.5/0.5 on both ears for a left-only DC input at every azimuth. +- **Library sync between a phone and its paired computer (2026-11-12, issue #2663, branch `feat/data_sync`, NOT BUILT OR TESTED YET)**: the Desktop app is the server and keeps the log; the Android app drives every round — on app open (at most every 5 min, `MainActivity.syncLibraryIfDue`), every 15 min through WorkManager (`androidApp/.../service/sync/`, scheduled only while paired) and on "Sync now". Not realtime, never touches the queue or the player. Synced: liked songs, followed artists, hearted albums / YouTube playlists / podcasts, local playlists (title, cover, songs, order) and listening history (a phone gets the year before it was paired and everything after, on every batch). Not synced: queue, recents, caches, downloads, Smart downloads, device-bound settings and secrets. Downloads stay each device's own: Smart downloads scores only the plays made on that device (`getSongPlaysSince` reads `deviceId IS NULL`), and a like arriving by sync never triggers "download songs you like", which runs only on the like action itself. A device with local tracking off neither sends nor takes plays (the computer then relays none either). UI: Settings → Devices → **Library sync** opens `LibrarySyncDialog` (`expect/ui/LibrarySync*.kt`, state in `LibrarySyncHostViewModel` / `LibrarySyncPhoneViewModel`). Desktop: QR with the address picker, then the paired phones with per-phone sync time and Remove; Windows Public and port-in-use warnings. Android: scan → "Pair with this computer?" → status with Sync now / Unpair. The settings prompt names each differing key (`PendingSettings.keys`, labelled from the key name, English only). Paired, "Send sign-ins to desktop" skips the QR and goes over the paired channel; the computer asks with `LibrarySyncLoginPrompt`, drawn over the whole Desktop window. "Apply & restart" exits on Desktop (as a restored backup does) and relaunches on Android. + - **Layers**: transport in `core/service/loginSync` (above); domain `LibrarySyncRepository` + `LibrarySyncHostRepository` (Desktop) / `LibrarySyncPhoneRepository` (Android) and `model/librarysync`; data `librarysync/` — `SyncChangeRecorder` (write hooks in `LocalDataSource`/`AnalyticsDatasource`), `SyncEngine` (one round, both ends), `SyncApplier`, `SyncSnapshot`, `SyncedSettings`, `SyncPrefs`, platform repos in `jvmMain`/`androidMain`, bound in `Loader.*.kt`. iOS binds nothing. + - **Database v28** (AutoMigration from 25/26/27): new `sync_change` table; `syncId` (unique, nullable) on `local_playlist` and `playback_event`; `deviceId` on `playback_event` (null = played on this device). "Recently played" reads `deviceId IS NULL` only, so another device's plays never show up there. `27.json` was overwritten once by an IDE build mid-edit and restored from git: **the `from` schema of an AutoMigration must stay the shipped one**. + - **`sync_change` is two things.** On the phone it is the outbox (`serverSeq` null = not taken yet), so changes made while the computer is away go out later. On the computer it is the log phones pull from by `serverSeq`, keeping only the newest row per (entity, key) except history. It exists because an unlike writes `favoriteAt` back to null, so without it the moment of an "off" is lost and two devices cannot tell which came last. + - **Merge**: last change wins (`supersedes`: `changedAt`, then "on" beats "off", then `changeId`), compared against the log on the computer and against the phone's own pending rows on the phone, one change at a time right before it is applied. The computer logs a change only once it holds there (`SyncApplier.applyOne` returns whether it did), and when a phone's change loses it sends the winning row back. A playlist's name, cover and order are read when sent, not when changed. Writes made while applying run under the `SyncApplying` context element so the hooks do not record them again. Referenced rows (songs, albums, artists…) travel along and are inserted IGNORE with `inLibrary = 2000-01-01`, so they never surface as "recently added". + - **Local playlists are the hard part** (found by an independent review on 2026-11-12). A rename logs a new playlist row at the end of the log while its songs keep their old places, so a phone pulling from scratch can get the songs several batches before the playlist: every song and order row therefore carries the playlist's `meta`, and the receiver creates the playlist from it unless it deleted it later itself. A deletion loses to a later edit; the side that keeps the playlist then sends it again whole (`SyncSnapshot.playlistChanges`) instead of logging the deletion, since other phones would otherwise delete it too. When the computer brings back a playlist it had deleted from an edit alone, it asks that phone to send it again whole (`SyncResponse.resend`). + - **The YouTube link travels too** (owner's call, 2026-11-12): `PlaylistMeta.youtubePlaylistId`, and each song row of a linked playlist carries its `setVideoId` (the YouTube entry id `LocalPlaylistRepositoryImpl.findSetVideoId` needs to remove a song there). Only the device where the user made an edit pushes it to YouTube; applying a synced edit never does. Linking (`updateLocalPlaylistYouTubePlaylistId`) sends the playlist whole so every song carries its entry id, and an entry id stored after its song (`insertSetVideoId`) sends that song again. **A playlist imported from the same YouTube playlist on both devices is one playlist**: the side that receives a syncId it lacks, while holding a playlist with that link, gives its own the incoming syncId, drops what it recorded under the old one and sends it again whole. Both sides adopt what they receive, so they agree whichever row arrives first. + - **Sign-ins sent over the paired channel wait for the computer's user** (`LibrarySyncHostRepository.pendingLogins` / `answerLogins`): holding the paired key is not enough, so a lost phone cannot switch the computer's accounts. The phone's request waits up to 100 s for the answer (its client gives up at 120 s) and gets back only what was accepted; one prompt at a time. + - **Identity is the key, not the IP.** Pairing hands the phone a long-lived key under the QR's one-time key; every later knock carries a nonce the computer must echo with its id, and every sync reply echoes the request's nonce. A 403 alone never unpairs a phone: only the computer's own sealed "removed" knock reply does, and the computer keeps answering it for the 30 days a removed phone is remembered. The server refuses a body with no Content-Length before reading it. The phone looks for the computer at the address picked when pairing (LAN, Tailscale, anything listed), then every address it last reported, then a sealed UDP probe (multicast 239.255.48.17 + broadcast), then a sweep of its /24. + - **Deletion never propagates by accident.** Clearing listening history unpairs first (Desktop: every phone), and so does restoring a backup. A removed phone is told under its own key the next time it knocks. Settings travel every round but are applied only after the user agrees (allowlist in `SyncedSettings.KEYS`). A database copy is taken before the first merge of a pairing and before a merge that removes something, at most one an hour, three kept (`~/.simpmusic/sync-backups`, `filesDir/sync-backups`). Pairing state lives in its own `library_sync.preferences_pb`, outside the settings file, so a backup cannot carry a pairing key to another device. + ## 🔄 CLAUDE.md Auto-Update Rule (MANDATORY) After completing any of the following types of changes, the AI agent **MUST** update this CLAUDE.md file: @@ -1186,6 +1197,6 @@ After completing any of the following types of changes, the AI agent **MUST** up *This document helps AI Agents quickly understand the SimpMusic project. Update regularly when there are major changes to architecture or structure.* -**Last updated**: 2026-11-11 +**Last updated**: 2026-11-12 **Project version**: Check latest release on GitHub **Maintained by**: maxrave-dev and contributors diff --git a/androidApp/src/main/java/com/maxrave/simpmusic/MainActivity.kt b/androidApp/src/main/java/com/maxrave/simpmusic/MainActivity.kt index 61c9203bf8..1fbeae79d9 100644 --- a/androidApp/src/main/java/com/maxrave/simpmusic/MainActivity.kt +++ b/androidApp/src/main/java/com/maxrave/simpmusic/MainActivity.kt @@ -8,6 +8,7 @@ import android.content.res.Configuration import android.os.Build import android.os.Bundle import android.os.IBinder +import android.os.SystemClock import androidx.activity.SystemBarStyle import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge @@ -34,6 +35,7 @@ import com.maxrave.domain.data.model.intent.GenericIntent import com.maxrave.domain.manager.DataStoreManager import com.maxrave.domain.mediaservice.handler.MediaPlayerHandler import com.maxrave.domain.mediaservice.handler.ToastType +import com.maxrave.domain.repository.LibrarySyncPhoneRepository import com.maxrave.logger.Logger import com.maxrave.media3.di.setServiceActivitySession import com.maxrave.simpmusic.di.viewModelModule @@ -53,11 +55,15 @@ import pub.devrel.easypermissions.EasyPermissions import java.util.Locale import java.util.concurrent.TimeUnit +// Process-wide, so a recreated activity (rotation, theme change) does not count as opening the app. +private var lastLibrarySyncAt = 0L + @Suppress("DEPRECATION") class MainActivity : AppCompatActivity() { val viewModel: SharedViewModel by inject() val mediaPlayerHandler by inject() val dataStoreManager: DataStoreManager by inject() + private val librarySync: LibrarySyncPhoneRepository by inject() private var mBound = false private var shouldUnbind = false @@ -84,6 +90,16 @@ class MainActivity : AppCompatActivity() { startMusicService() // Every return to the screen asks; the pass itself runs at most once a day. viewModel.runSmartDownloadsIfDue() + syncLibraryIfDue() + } + + // ponytail: a fixed 5-minute gap between app-open rounds, since a computer that is off costs a + // LAN sweep each time; WorkManager covers the rest every 15 minutes, and "Sync now" ignores it. + private fun syncLibraryIfDue() { + val now = SystemClock.elapsedRealtime() + if (lastLibrarySyncAt != 0L && now - lastLibrarySyncAt < 5 * 60_000L) return + lastLibrarySyncAt = now + lifecycleScope.launch { librarySync.syncNow() } } override fun onStop() { diff --git a/androidApp/src/main/java/com/maxrave/simpmusic/SimpMusicApplication.kt b/androidApp/src/main/java/com/maxrave/simpmusic/SimpMusicApplication.kt index 00b831b514..a50d16cc3b 100644 --- a/androidApp/src/main/java/com/maxrave/simpmusic/SimpMusicApplication.kt +++ b/androidApp/src/main/java/com/maxrave/simpmusic/SimpMusicApplication.kt @@ -20,9 +20,11 @@ import coil3.request.crossfade import com.maxrave.common.AppIdentity import com.maxrave.data.di.loader.loadAllModules import com.maxrave.domain.manager.DataStoreManager +import com.maxrave.domain.repository.LibrarySyncPhoneRepository import com.maxrave.logger.Logger import com.maxrave.simpmusic.di.viewModelModule import com.maxrave.simpmusic.service.backup.AutoBackupScheduler +import com.maxrave.simpmusic.service.sync.LibrarySyncScheduler import com.maxrave.simpmusic.utils.NetworkFirstInterceptor import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers @@ -34,6 +36,7 @@ import okio.FileSystem import org.koin.android.ext.koin.androidContext import org.koin.android.ext.koin.androidLogger import org.koin.core.component.KoinComponent +import org.koin.core.component.get import org.koin.core.component.inject import org.koin.core.context.loadKoinModules import org.koin.core.context.startKoin @@ -90,6 +93,11 @@ class SimpMusicApplication : autoBackupScheduler.observeAndSchedule() } + val librarySyncScheduler = LibrarySyncScheduler(this, get()) + applicationScope.launch { + librarySyncScheduler.observeAndSchedule() + } + CaocConfig.Builder .create() .backgroundMode(CaocConfig.BACKGROUND_MODE_SILENT) // default: CaocConfig.BACKGROUND_MODE_SHOW_CUSTOM diff --git a/androidApp/src/main/java/com/maxrave/simpmusic/service/sync/LibrarySyncScheduler.kt b/androidApp/src/main/java/com/maxrave/simpmusic/service/sync/LibrarySyncScheduler.kt new file mode 100644 index 0000000000..0f14f5ac6c --- /dev/null +++ b/androidApp/src/main/java/com/maxrave/simpmusic/service/sync/LibrarySyncScheduler.kt @@ -0,0 +1,54 @@ +package com.maxrave.simpmusic.service.sync + +import android.content.Context +import androidx.work.Constraints +import androidx.work.ExistingPeriodicWorkPolicy +import androidx.work.NetworkType +import androidx.work.PeriodicWorkRequestBuilder +import androidx.work.WorkManager +import com.maxrave.domain.repository.LibrarySyncPhoneRepository +import com.maxrave.logger.Logger +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.map +import java.util.concurrent.TimeUnit + +/** + * Runs a library sync round in the background while this phone is paired with a computer (#2663). + * Fifteen minutes is the shortest interval WorkManager allows; opening the app and "Sync now" fill in + * between. + */ +class LibrarySyncScheduler( + private val context: Context, + private val repository: LibrarySyncPhoneRepository, +) { + /** Call from a scope that lives as long as the application. */ + suspend fun observeAndSchedule() { + var wasPaired = false + repository.state + .map { it.isPaired } + .distinctUntilChanged() + .collect { paired -> + val workManager = WorkManager.getInstance(context) + if (paired) { + val request = + PeriodicWorkRequestBuilder(15, TimeUnit.MINUTES) + .setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()) + .build() + // KEEP: a launch must not restart the period, or cancel the job that woke the process. + workManager.enqueueUniquePeriodicWork(WORK_NAME, ExistingPeriodicWorkPolicy.KEEP, request) + Logger.i(TAG, "background sync scheduled") + } else if (wasPaired) { + // Only a real unpairing cancels it. The first value is "not paired" until the + // pairing file has been read, and acting on it would cancel a job that is running. + workManager.cancelUniqueWork(WORK_NAME) + Logger.i(TAG, "background sync cancelled") + } + wasPaired = paired + } + } + + private companion object { + const val TAG = "LibrarySync" + const val WORK_NAME = "LibrarySyncWorker" + } +} diff --git a/androidApp/src/main/java/com/maxrave/simpmusic/service/sync/LibrarySyncWorker.kt b/androidApp/src/main/java/com/maxrave/simpmusic/service/sync/LibrarySyncWorker.kt new file mode 100644 index 0000000000..b65637bd58 --- /dev/null +++ b/androidApp/src/main/java/com/maxrave/simpmusic/service/sync/LibrarySyncWorker.kt @@ -0,0 +1,22 @@ +package com.maxrave.simpmusic.service.sync + +import android.content.Context +import androidx.work.CoroutineWorker +import androidx.work.WorkerParameters +import com.maxrave.domain.repository.LibrarySyncPhoneRepository +import org.koin.core.component.KoinComponent +import org.koin.core.component.inject + +/** One round; a computer that is away is simply tried again on the next run. */ +class LibrarySyncWorker( + context: Context, + params: WorkerParameters, +) : CoroutineWorker(context, params), + KoinComponent { + private val repository: LibrarySyncPhoneRepository by inject() + + override suspend fun doWork(): Result { + repository.syncNow() + return Result.success() + } +} diff --git a/composeApp/src/androidMain/kotlin/com/maxrave/simpmusic/expect/ui/LibrarySync.android.kt b/composeApp/src/androidMain/kotlin/com/maxrave/simpmusic/expect/ui/LibrarySync.android.kt new file mode 100644 index 0000000000..0291855440 --- /dev/null +++ b/composeApp/src/androidMain/kotlin/com/maxrave/simpmusic/expect/ui/LibrarySync.android.kt @@ -0,0 +1,390 @@ +package com.maxrave.simpmusic.expect.ui + +import android.Manifest +import android.content.Intent +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.Arrangement +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.AlertDialog +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.LocalContentColor +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.rememberModalBottomSheetState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +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 androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.maxrave.domain.data.model.librarysync.LibrarySyncProblem +import com.maxrave.domain.data.model.librarysync.LibrarySyncState +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.viewModel.LibrarySyncPhoneViewModel +import com.maxrave.simpmusic.viewModel.LibrarySyncPhoneViewModel.Step +import kotlinx.coroutines.launch +import org.jetbrains.compose.resources.stringResource +import org.koin.compose.viewmodel.koinViewModel +import org.koin.mp.KoinPlatform.getKoin +import simpmusic.composeapp.generated.resources.Res +import simpmusic.composeapp.generated.resources.cancel +import simpmusic.composeapp.generated.resources.library_sync_allow +import simpmusic.composeapp.generated.resources.library_sync_computer +import simpmusic.composeapp.generated.resources.library_sync_failed +import simpmusic.composeapp.generated.resources.library_sync_first_sync_phone +import simpmusic.composeapp.generated.resources.library_sync_last_synced +import simpmusic.composeapp.generated.resources.library_sync_needs_nearby +import simpmusic.composeapp.generated.resources.library_sync_pair +import simpmusic.composeapp.generated.resources.library_sync_pair_again +import simpmusic.composeapp.generated.resources.library_sync_pair_message +import simpmusic.composeapp.generated.resources.library_sync_pair_title +import simpmusic.composeapp.generated.resources.library_sync_pairing +import simpmusic.composeapp.generated.resources.library_sync_revoked +import simpmusic.composeapp.generated.resources.library_sync_scan_hint +import simpmusic.composeapp.generated.resources.library_sync_settings_differ_android +import simpmusic.composeapp.generated.resources.library_sync_sync_now +import simpmusic.composeapp.generated.resources.library_sync_syncing +import simpmusic.composeapp.generated.resources.library_sync_syncs +import simpmusic.composeapp.generated.resources.library_sync_syncs_value +import simpmusic.composeapp.generated.resources.library_sync_title +import simpmusic.composeapp.generated.resources.library_sync_unpair +import simpmusic.composeapp.generated.resources.library_sync_unpair_message +import simpmusic.composeapp.generated.resources.library_sync_unpair_title +import simpmusic.composeapp.generated.resources.library_sync_unreachable +import simpmusic.composeapp.generated.resources.login_sync_allow_camera +import simpmusic.composeapp.generated.resources.login_sync_camera_blocked +import simpmusic.composeapp.generated.resources.login_sync_camera_needed +import simpmusic.composeapp.generated.resources.login_sync_connecting +import simpmusic.composeapp.generated.resources.login_sync_no_camera +import simpmusic.composeapp.generated.resources.login_sync_open_settings +import simpmusic.composeapp.generated.resources.retry + +private const val ACCESS_LOCAL_NETWORK = "android.permission.ACCESS_LOCAL_NETWORK" + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +actual fun LibrarySyncDialog(onDismiss: () -> Unit) { + val context = LocalContext.current + val viewModel: LibrarySyncPhoneViewModel = koinViewModel() + val state by viewModel.state.collectAsStateWithLifecycle() + val step by viewModel.step.collectAsStateWithLifecycle() + val pending by viewModel.pendingSettings.collectAsStateWithLifecycle() + val scope = rememberCoroutineScope() + val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true) + val colors = rememberSurfaceDarkColors() + var confirmUnpair by remember { mutableStateOf(false) } + + // Camera, plus Nearby devices on Android 17+, asked together as Login Sync does. + val permissions = remember { loginSyncPermissions() } + + fun hasPermissions() = permissions.all { ContextCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_GRANTED } + + val permissionLauncher = + rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { result -> + val granted = result.isNotEmpty() && result.values.all { it } + val blocked = !granted && !context.findActivity().shouldShowRequestPermissionRationale(Manifest.permission.CAMERA) + viewModel.onPermission(granted, blocked) + } + // Paired and only Nearby devices missing: ask for it alone, then run the round it was blocking. + val nearbyLauncher = + rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted -> + if (granted) viewModel.syncNow() else context.openAppSettings() + } + + fun close() { + scope.launch { sheetState.hide() }.invokeOnCompletion { onDismiss() } + } + + LaunchedEffect(viewModel) { viewModel.open(hasPermissions()) } + DisposableEffect(viewModel) { onDispose { viewModel.close() } } + LifecycleResumeEffect(step) { + if (step is Step.NeedsPermission && hasPermissions()) viewModel.onPermission(granted = true, blocked = false) + onPauseOrDispose { } + } + + 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.library_sync_title), + style = typo().titleMedium, + color = colors.content, + modifier = Modifier.weight(1f), + ) + IconButton(onClick = ::close) { + Icon(imageVector = SimpIcons.Close, contentDescription = stringResource(Res.string.cancel), tint = colors.content) + } + } + if (state.isPaired) { + PairedStatus( + state = state, + onAllowNearby = { nearbyLauncher.launch(ACCESS_LOCAL_NETWORK) }, + onSyncNow = viewModel::syncNow, + onUnpair = { confirmUnpair = true }, + ) + pending?.let { + Box(Modifier.padding(horizontal = 24.dp, vertical = 8.dp)) { + PendingSettingsCard( + pending = it, + differ = stringResource(Res.string.library_sync_settings_differ_android), + onNotNow = viewModel::dismissSettings, + onApply = { viewModel.applySettings(::restartAfterSyncedSettings) }, + ) + } + } + } else { + Text( + text = stringResource(Res.string.library_sync_scan_hint), + style = typo().bodySmall, + color = colors.subtitle, + modifier = Modifier.fillMaxWidth().padding(horizontal = 24.dp), + ) + Spacer(Modifier.height(20.dp)) + Box( + modifier = + Modifier + .padding(horizontal = 24.dp) + .widthIn(max = 340.dp) + .fillMaxWidth() + .aspectRatio(1f) + .clip(RoundedCornerShape(24.dp)) + .background(if (step == Step.Scanning) Color.Black else colors.disabled.copy(alpha = 0.15f)), + contentAlignment = Alignment.Center, + ) { + when (val s = step) { + Step.Scanning -> { + QrScanner( + onResult = viewModel::onScanned, + onCameraUnavailable = viewModel::onCameraUnavailable, + modifier = Modifier.fillMaxSize(), + ) + ViewfinderCorners(Modifier.fillMaxSize().padding(20.dp)) + } + + Step.Reaching -> { + Status(stringResource(Res.string.login_sync_connecting), progress = true) + } + + Step.Pairing -> { + Status(stringResource(Res.string.library_sync_pairing), progress = true) + } + + is Step.Confirm -> { + Status("${s.desktop.name} · ${s.desktop.os}", progress = false) + } + + is Step.NeedsPermission -> { + if (s.blocked) { + Status(stringResource(Res.string.login_sync_camera_blocked), progress = false) { + SheetButton(stringResource(Res.string.login_sync_open_settings)) { context.openAppSettings() } + } + } else { + Status(stringResource(Res.string.login_sync_camera_needed), progress = false) { + SheetButton(stringResource(Res.string.login_sync_allow_camera)) { + permissionLauncher.launch(permissions.toTypedArray()) + } + } + } + } + + Step.NoCamera -> { + Status(stringResource(Res.string.login_sync_no_camera), progress = false) + } + + Step.Revoked -> { + Status(stringResource(Res.string.library_sync_revoked), progress = false) { + SheetButton(stringResource(Res.string.library_sync_pair_again)) { viewModel.scan(hasPermissions()) } + } + } + + is Step.Failed -> { + Status(problemText(s.problem, s.detail, null), progress = false) { + SheetButton(stringResource(Res.string.retry)) { viewModel.scan(hasPermissions()) } + } + } + } + } + } + } + } + } + + (step as? Step.Confirm)?.let { confirm -> + if (!state.isPaired) { + AlertDialog( + onDismissRequest = { viewModel.cancelConfirm(hasPermissions()) }, + title = { Text(text = stringResource(Res.string.library_sync_pair_title), style = typo().titleSmall) }, + text = { Text(text = stringResource(Res.string.library_sync_pair_message, confirm.desktop.name, confirm.desktop.os)) }, + confirmButton = { + TextButton(onClick = viewModel::pair) { + Text(text = stringResource(Res.string.library_sync_pair), color = LocalContentColor.current) + } + }, + dismissButton = { + TextButton(onClick = { viewModel.cancelConfirm(hasPermissions()) }) { + Text(text = stringResource(Res.string.cancel), color = LocalContentColor.current) + } + }, + ) + } + } + + if (confirmUnpair) { + val name = state.peers.firstOrNull()?.name.orEmpty() + AlertDialog( + onDismissRequest = { confirmUnpair = false }, + title = { Text(text = stringResource(Res.string.library_sync_unpair_title, name), style = typo().titleSmall) }, + text = { Text(text = stringResource(Res.string.library_sync_unpair_message, name)) }, + confirmButton = { + TextButton(onClick = { + confirmUnpair = false + viewModel.unpair(hasPermissions()) + }) { Text(text = stringResource(Res.string.library_sync_unpair), color = LocalContentColor.current) } + }, + dismissButton = { + TextButton(onClick = { confirmUnpair = false }) { Text(text = stringResource(Res.string.cancel), color = LocalContentColor.current) } + }, + ) + } +} + +/** A4/A5: the computer, what syncs, when it last did, and what stopped it. */ +@Composable +private fun PairedStatus( + state: LibrarySyncState, + onAllowNearby: () -> Unit, + onSyncNow: () -> Unit, + onUnpair: () -> Unit, +) { + val colors = rememberSurfaceDarkColors() + val peer = state.peers.first() + Column( + modifier = Modifier.fillMaxWidth().padding(horizontal = 24.dp, vertical = 8.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + state.problem?.let { problem -> + if (problem == LibrarySyncProblem.NEEDS_LOCAL_NETWORK_PERMISSION) { + SyncProblemBox(stringResource(Res.string.library_sync_needs_nearby), stringResource(Res.string.library_sync_allow), onAllowNearby) + } else { + SyncProblemBox(problemText(problem, state.problemDetail, peer.name)) + } + } + Column { + Text(text = stringResource(Res.string.library_sync_computer), style = typo().bodySmall, color = colors.subtitle) + Text(text = "${peer.name} · ${peer.os}", style = typo().bodyMedium, color = colors.content) + } + Column { + Text(text = stringResource(Res.string.library_sync_syncs), style = typo().bodySmall, color = colors.subtitle) + Text(text = stringResource(Res.string.library_sync_syncs_value), style = typo().bodyMedium, color = colors.content) + } + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + if (state.syncing) CircularProgressIndicator(Modifier.width(16.dp).height(16.dp), strokeWidth = 2.dp) + Text( + text = + when { + state.syncing && state.lastSyncAt == null -> stringResource(Res.string.library_sync_first_sync_phone) + state.syncing -> stringResource(Res.string.library_sync_syncing) + else -> state.lastSyncAt?.let { stringResource(Res.string.library_sync_last_synced, syncedAgo(it)) }.orEmpty() + }, + style = typo().bodySmall, + color = colors.subtitle, + ) + } + SheetButton(stringResource(Res.string.library_sync_sync_now), onSyncNow) + TextButton(onClick = onUnpair, modifier = Modifier.align(Alignment.CenterHorizontally)) { + Text(text = stringResource(Res.string.library_sync_unpair), color = colors.content) + } + } +} + +@Composable +private fun problemText( + problem: LibrarySyncProblem, + detail: String?, + desktopName: String?, +): String = + when (problem) { + LibrarySyncProblem.UNREACHABLE -> stringResource(Res.string.library_sync_unreachable, desktopName ?: "your computer") + LibrarySyncProblem.NEEDS_LOCAL_NETWORK_PERMISSION -> stringResource(Res.string.library_sync_needs_nearby) + LibrarySyncProblem.REVOKED -> stringResource(Res.string.library_sync_revoked) + else -> stringResource(Res.string.library_sync_failed, detail.orEmpty()) + } + +actual fun restartAfterSyncedSettings() { + val context: android.content.Context = getKoin().get() + val launch = context.packageManager.getLaunchIntentForPackage(context.packageName) + context.startActivity(Intent.makeRestartActivityTask(launch?.component)) + Runtime.getRuntime().exit(0) +} diff --git a/composeApp/src/androidMain/kotlin/com/maxrave/simpmusic/expect/ui/LoginSync.android.kt b/composeApp/src/androidMain/kotlin/com/maxrave/simpmusic/expect/ui/LoginSync.android.kt index cf7f5bc685..180a73d344 100644 --- a/composeApp/src/androidMain/kotlin/com/maxrave/simpmusic/expect/ui/LoginSync.android.kt +++ b/composeApp/src/androidMain/kotlin/com/maxrave/simpmusic/expect/ui/LoginSync.android.kt @@ -77,6 +77,9 @@ import org.jetbrains.compose.resources.stringResource import org.koin.compose.viewmodel.koinViewModel import simpmusic.composeapp.generated.resources.Res import simpmusic.composeapp.generated.resources.cancel +import simpmusic.composeapp.generated.resources.library_sync_logins_declined +import simpmusic.composeapp.generated.resources.library_sync_logins_waiting +import simpmusic.composeapp.generated.resources.library_sync_send_logins_paired import simpmusic.composeapp.generated.resources.login_sync_allow_camera import simpmusic.composeapp.generated.resources.login_sync_android_title import simpmusic.composeapp.generated.resources.login_sync_camera_blocked @@ -182,7 +185,9 @@ actual fun LoginSyncDialog(onDismiss: () -> Unit) { } } Text( - text = stringResource(Res.string.login_sync_scan_hint), + text = + uiState.pairedTo?.let { stringResource(Res.string.library_sync_send_logins_paired, it.name) } + ?: stringResource(Res.string.login_sync_scan_hint), style = typo().bodySmall, color = colors.subtitle, modifier = Modifier.fillMaxWidth().padding(horizontal = 24.dp), @@ -248,6 +253,18 @@ actual fun LoginSyncDialog(onDismiss: () -> Unit) { Status(stringResource(Res.string.login_sync_no_camera), progress = false) } + is Step.Waiting -> { + Status(stringResource(Res.string.library_sync_logins_waiting, step.desktop.name), progress = true) { + SheetButton(stringResource(Res.string.cancel), ::close) + } + } + + is Step.Declined -> { + Status(stringResource(Res.string.library_sync_logins_declined, step.desktop.name), progress = false) { + SheetButton(stringResource(Res.string.ok), ::close) + } + } + Step.NothingSignedIn -> { Status(stringResource(Res.string.login_sync_nothing_signed_in), progress = false) } @@ -335,7 +352,7 @@ actual fun LoginSyncDialog(onDismiss: () -> Unit) { /** A message centred in the viewfinder square, with an optional spinner above and action below. */ @Composable -private fun Status( +internal fun Status( text: String, progress: Boolean, action: (@Composable () -> Unit)? = null, @@ -362,7 +379,7 @@ private fun Status( * inherits that instead of onPrimary and renders pale text on a pale fill. */ @Composable -private fun SheetButton( +internal fun SheetButton( text: String, onClick: () -> Unit, ) { @@ -383,7 +400,7 @@ private fun SheetButton( /** Four corner brackets marking where the code should sit. */ @Composable -private fun ViewfinderCorners(modifier: Modifier = Modifier) { +internal fun ViewfinderCorners(modifier: Modifier = Modifier) { Canvas(modifier) { val arm = size.minDimension * 0.14f val stroke = 4.dp.toPx() @@ -413,7 +430,7 @@ internal fun Context.openAppSettings() { * grants ACCESS_LOCAL_NETWORK implicitly with INTERNET, but only to apps that do not declare it, and * our manifest does. Without it the connection does not fail — it times out (element-x-android#7694). */ -private fun loginSyncPermissions(): List = +internal fun loginSyncPermissions(): List = buildList { add(Manifest.permission.CAMERA) if (Build.VERSION.SDK_INT >= 37) { diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 56789955c6..4ea19ff0df 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -508,6 +508,7 @@ Clear listening history Erase your local listening statistics and remove songs that nothing else in the app refers to Your listening statistics and unused resources will be cleaned. This cannot be undone — please back up first. + This device is paired for library sync. Clearing also unpairs it; your other devices keep their own history. Listening history cleared, %1$d songs removed Proxy Using Proxy to bypass country content blocking @@ -960,6 +961,59 @@ Couldn't reach the computer. Make sure your phone is on the same network or tailnet, then try again. The code on your computer has expired. Show a new one and scan again. Something went wrong. Please try again. + Library sync + Not paired · Share likes, artists, albums, podcasts, playlists and history with your phone + Not paired · Share likes, artists, albums, podcasts, playlists and history with your computer + %1$s · synced %2$s + %1$s · not synced yet + just now + %1$d min ago + On your phone, open SimpMusic → Settings → Library sync, then scan this code. + Windows is blocking your phones. This network is set to Public, so Windows refuses connections from other devices. Set it to Private. + Open network settings + Another app is using port 48517. Close it and try again. + Something went wrong: %1$s + Paired with %1$s. + The first sync is running on your phone. Keep SimpMusic open on both devices until it finishes. + Remove + Remove %1$s? + %1$s stops syncing with this computer. Changes made on it since the last sync stay on that phone only. Nothing is deleted on either device. + Settings from %1$s + These differ from this computer's: + These differ from this phone's: + Apply them? SimpMusic restarts. + Not now + Apply & restart + Your phones sync by themselves when SimpMusic opens on them and every 15 minutes, while SimpMusic is open on this computer. Downloads and device settings stay on each device. + Pair another phone + Pair a phone + Use sign-ins from %1$s? + Your phone sent its sign-ins for %1$s. Using them signs this computer in to those accounts. + Ignore + Use + Point the camera at the code under Settings → Library sync on your computer. + Pair with this computer? + This phone and %1$s (%2$s) will share likes, followed artists, saved albums and podcasts, playlists and the last year of listening history with each other. Nothing is deleted. Only continue if this is the computer in front of you. + Pair + Pairing… + Computer + Syncs + Likes, artists, albums, podcasts, playlists, history + First sync in progress. Keep SimpMusic open on both devices. + Syncing… + Last synced %1$s · syncs by itself when SimpMusic opens and every 15 minutes + Sync now + Unpair + Unpair from %1$s? + This phone stops syncing with %1$s. Changes made here since the last sync stay on this phone only. Nothing is deleted on either device. + Couldn't find %1$s. Make sure SimpMusic is open on it and both devices are on the same Wi-Fi or Tailscale. + Nearby devices is off, so this phone can't reach your computer. + Allow + Your computer removed this phone. + Pair again + Send to %1$s over the paired connection + Waiting for %1$s to accept. Confirm on the computer. + %1$s didn't accept the sign-ins. Unofficial app You are using an unofficial copy of SimpMusic that was modified or repackaged by someone else. It cannot be used. Download the official version from simpmusic.org. What's your music taste? diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/di/ViewModelModule.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/di/ViewModelModule.kt index b9ae65a8c3..494a7bc036 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/di/ViewModelModule.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/di/ViewModelModule.kt @@ -16,6 +16,8 @@ import com.maxrave.simpmusic.viewModel.LibraryDynamicPlaylistViewModel import com.maxrave.simpmusic.viewModel.LibrarySidebarViewModel import com.maxrave.simpmusic.viewModel.LibraryViewModel import com.maxrave.simpmusic.viewModel.LocalPlaylistViewModel +import com.maxrave.simpmusic.viewModel.LibrarySyncHostViewModel +import com.maxrave.simpmusic.viewModel.LibrarySyncPhoneViewModel import com.maxrave.simpmusic.viewModel.LogInViewModel import com.maxrave.simpmusic.viewModel.LoginSyncHostViewModel import com.maxrave.simpmusic.viewModel.LoginSyncSenderViewModel @@ -67,7 +69,9 @@ val viewModelModule = // Only one of these resolves on a given platform: Desktop binds the host repository, Android the // sender. Koin resolves dependencies when a ViewModel is created, not when it is declared. viewModel { LoginSyncHostViewModel(get()) } - viewModel { LoginSyncSenderViewModel(get()) } + viewModel { LoginSyncSenderViewModel(get(), get()) } + viewModel { LibrarySyncHostViewModel(get()) } + viewModel { LibrarySyncPhoneViewModel(get()) } viewModel { BrowserLoginViewModel(get()) } viewModel { CommentsViewModel(get(), get()) } viewModel { SoundCloudPlayerViewModel(get()) } @@ -133,6 +137,7 @@ val viewModelModule = get(), get(), get(), + get(), ) } viewModel { diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/expect/ui/LibrarySync.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/expect/ui/LibrarySync.kt new file mode 100644 index 0000000000..d81dcb8c64 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/expect/ui/LibrarySync.kt @@ -0,0 +1,108 @@ +package com.maxrave.simpmusic.expect.ui + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.LocalContentColor +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.unit.dp +import com.maxrave.domain.data.model.librarysync.PendingSettings +import com.maxrave.simpmusic.ui.theme.typo +import org.jetbrains.compose.resources.stringResource +import simpmusic.composeapp.generated.resources.Res +import simpmusic.composeapp.generated.resources.day_s_ago +import simpmusic.composeapp.generated.resources.hour_s_ago +import simpmusic.composeapp.generated.resources.library_sync_apply_question +import simpmusic.composeapp.generated.resources.library_sync_apply_restart +import simpmusic.composeapp.generated.resources.library_sync_just_now +import simpmusic.composeapp.generated.resources.library_sync_minutes_ago +import simpmusic.composeapp.generated.resources.library_sync_not_now +import simpmusic.composeapp.generated.resources.library_sync_settings_from +import kotlin.time.Clock +import kotlin.time.ExperimentalTime + +/** Desktop: the pairing QR and the paired phones. Android: scan, pair, then the pairing's status (#2663). */ +@Composable +expect fun LibrarySyncDialog(onDismiss: () -> Unit) + +/** Restarts the app after synced settings were written, the same way a restored backup does. */ +expect fun restartAfterSyncedSettings() + +/** "3 min ago" for an epoch-millisecond time. */ +@OptIn(ExperimentalTime::class) +@Composable +internal fun syncedAgo(millis: Long): String { + val minutes = (Clock.System.now().toEpochMilliseconds() - millis).coerceAtLeast(0) / 60_000 + return when { + minutes < 1 -> stringResource(Res.string.library_sync_just_now) + minutes < 60 -> stringResource(Res.string.library_sync_minutes_ago, minutes.toInt()) + minutes < 24 * 60 -> stringResource(Res.string.hour_s_ago, (minutes / 60).toInt()) + else -> stringResource(Res.string.day_s_ago, (minutes / (24 * 60)).toInt()) + } +} + +// ponytail: names come from the DataStore key ("lyrics_provider" → "Lyrics provider"), so they are +// English on every locale; give the 29 allowlisted keys string resources if translators ask. +internal fun settingLabel(key: String): String = key.replace('_', ' ').replaceFirstChar { it.uppercase() } + +/** A problem worded for the user, with an optional fix next to it. */ +@Composable +internal fun SyncProblemBox( + text: String, + action: String? = null, + onAction: () -> Unit = {}, +) { + Column( + modifier = + Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(12.dp)) + .background(MaterialTheme.colorScheme.errorContainer) + .padding(12.dp), + ) { + Text(text = text, style = typo().bodySmall, color = MaterialTheme.colorScheme.onErrorContainer) + if (action != null) { + TextButton(onClick = onAction, modifier = Modifier.align(Alignment.End)) { + Text(text = action, color = MaterialTheme.colorScheme.onErrorContainer) + } + } + } +} + +/** The other device's settings, named one per line, with Not now / Apply & restart. */ +@Composable +internal fun PendingSettingsCard( + pending: PendingSettings, + differ: String, + onNotNow: () -> Unit, + onApply: () -> Unit, +) { + Column( + modifier = + Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(12.dp)) + .background(MaterialTheme.colorScheme.surfaceContainerHigh) + .padding(12.dp), + verticalArrangement = Arrangement.spacedBy(4.dp), + ) { + Text(text = stringResource(Res.string.library_sync_settings_from, pending.fromName), style = typo().titleSmall) + Text(text = differ, style = typo().bodySmall) + pending.keys.forEach { Text(text = "• ${settingLabel(it)}", style = typo().bodyMedium) } + Text(text = stringResource(Res.string.library_sync_apply_question), style = typo().bodySmall) + Row(modifier = Modifier.align(Alignment.End)) { + TextButton(onClick = onNotNow) { Text(text = stringResource(Res.string.library_sync_not_now), color = LocalContentColor.current) } + TextButton(onClick = onApply) { Text(text = stringResource(Res.string.library_sync_apply_restart), color = LocalContentColor.current) } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/SettingScreen.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/SettingScreen.kt index 2881398c48..c6ea7e44fe 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/SettingScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/SettingScreen.kt @@ -104,13 +104,16 @@ import com.maxrave.common.VIDEO_QUALITY import com.maxrave.domain.extension.now import com.maxrave.domain.data.model.lyrics.RomanizationDictionaryState import com.maxrave.domain.data.model.lyrics.RomanizationLanguage +import com.maxrave.domain.data.model.librarysync.LibrarySyncProblem import com.maxrave.domain.manager.DataStoreManager import com.maxrave.domain.manager.DataStoreManager.Values.TRUE import com.maxrave.domain.repository.ImportProgress import com.maxrave.domain.utils.LocalResource import com.maxrave.logger.Logger import com.maxrave.simpmusic.Platform +import com.maxrave.simpmusic.expect.ui.LibrarySyncDialog import com.maxrave.simpmusic.expect.ui.LoginSyncDialog +import com.maxrave.simpmusic.expect.ui.syncedAgo import com.maxrave.simpmusic.expect.ui.filePickerResult import com.maxrave.simpmusic.expect.ui.fileSaverResult import com.maxrave.simpmusic.expect.ui.isLyricsBlurSupported @@ -234,6 +237,7 @@ import simpmusic.composeapp.generated.resources.clear_downloaded_cache import simpmusic.composeapp.generated.resources.clear_listening_history import simpmusic.composeapp.generated.resources.clear_listening_history_confirm import simpmusic.composeapp.generated.resources.clear_listening_history_description +import simpmusic.composeapp.generated.resources.clear_listening_history_unpairs import simpmusic.composeapp.generated.resources.clear_player_cache import simpmusic.composeapp.generated.resources.clear_thumbnail_cache import simpmusic.composeapp.generated.resources.content @@ -321,6 +325,13 @@ import simpmusic.composeapp.generated.resources.log_out_from_spotify import simpmusic.composeapp.generated.resources.log_out_warning import simpmusic.composeapp.generated.resources.logged_in import simpmusic.composeapp.generated.resources.logged_in_as +import simpmusic.composeapp.generated.resources.library_sync_not_paired_android +import simpmusic.composeapp.generated.resources.library_sync_not_paired_desktop +import simpmusic.composeapp.generated.resources.library_sync_peer_not_synced +import simpmusic.composeapp.generated.resources.library_sync_peer_synced +import simpmusic.composeapp.generated.resources.library_sync_send_logins_paired +import simpmusic.composeapp.generated.resources.library_sync_title +import simpmusic.composeapp.generated.resources.library_sync_windows_public import simpmusic.composeapp.generated.resources.login_sync_android_description import simpmusic.composeapp.generated.resources.login_sync_android_title import simpmusic.composeapp.generated.resources.login_sync_desktop_description @@ -521,6 +532,7 @@ fun SettingScreen( val language by viewModel.language.collectAsStateWithLifecycle() val location by viewModel.location.collectAsStateWithLifecycle() + val librarySyncState by viewModel.librarySyncState.collectAsStateWithLifecycle() val quality by viewModel.quality.collectAsStateWithLifecycle() val downloadQuality by viewModel.downloadQuality.collectAsStateWithLifecycle() val autoDownloadLikedSongs by viewModel.autoDownloadLikedSongs.collectAsStateWithLifecycle() @@ -638,6 +650,9 @@ fun SettingScreen( var showLoginSyncDialog by rememberSaveable { mutableStateOf(false) } + var showLibrarySyncDialog by rememberSaveable { + mutableStateOf(false) + } var showThirdPartyLibraries by rememberSaveable { mutableStateOf(false) } @@ -714,21 +729,46 @@ fun SettingScreen( title = stringResource(Res.string.login_sync_section), modifier = Modifier.onSizeChanged { devicesGroupHeightPx = it.height }, ) { + val syncPeer = librarySyncState.peers.firstOrNull() SettingItem( title = stringResource( if (getPlatform() == Platform.Android) Res.string.login_sync_android_title else Res.string.login_sync_desktop_title, ), subtitle = - stringResource( - if (getPlatform() == Platform.Android) { - Res.string.login_sync_android_description - } else { - Res.string.login_sync_desktop_description - }, - ), + when { + getPlatform() != Platform.Android -> stringResource(Res.string.login_sync_desktop_description) + syncPeer != null -> stringResource(Res.string.library_sync_send_logins_paired, syncPeer.name) + else -> stringResource(Res.string.login_sync_android_description) + }, onClick = { showLoginSyncDialog = true }, ) + SettingItem( + title = stringResource(Res.string.library_sync_title), + subtitle = + when { + librarySyncState.problem == LibrarySyncProblem.WINDOWS_PUBLIC_NETWORK -> { + stringResource(Res.string.library_sync_windows_public) + } + + syncPeer == null -> { + stringResource( + if (getPlatform() == Platform.Android) { + Res.string.library_sync_not_paired_android + } else { + Res.string.library_sync_not_paired_desktop + }, + ) + } + + else -> { + val names = librarySyncState.peers.joinToString { it.name } + librarySyncState.lastSyncAt?.let { stringResource(Res.string.library_sync_peer_synced, names, syncedAgo(it)) } + ?: stringResource(Res.string.library_sync_peer_not_synced, names) + } + }, + onClick = { showLibrarySyncDialog = true }, + ) } SettingGroup(title = stringResource(Res.string.user_interface)) { val themeModeLabels = @@ -1682,7 +1722,11 @@ fun SettingScreen( viewModel.setBasicAlertData( SettingBasicAlertState( title = runBlocking { getString(Res.string.clear_listening_history) }, - message = runBlocking { getString(Res.string.clear_listening_history_confirm) }, + message = + runBlocking { + val confirm = getString(Res.string.clear_listening_history_confirm) + if (viewModel.librarySyncPaired) "$confirm\n\n${getString(Res.string.clear_listening_history_unpairs)}" else confirm + }, confirm = runBlocking { getString(Res.string.clear) } to { viewModel.clearListeningHistory() @@ -3007,6 +3051,9 @@ fun SettingScreen( if (showLoginSyncDialog) { LoginSyncDialog(onDismiss = { showLoginSyncDialog = false }) } + if (showLibrarySyncDialog) { + LibrarySyncDialog(onDismiss = { showLibrarySyncDialog = false }) + } if (showYouTubeAccountDialog) { BasicAlertDialog( onDismissRequest = { }, diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/LibrarySyncViewModels.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/LibrarySyncViewModels.kt new file mode 100644 index 0000000000..ea26f5fd13 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/LibrarySyncViewModels.kt @@ -0,0 +1,197 @@ +package com.maxrave.simpmusic.viewModel + +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import com.maxrave.domain.data.model.librarysync.LibrarySyncException +import com.maxrave.domain.data.model.librarysync.LibrarySyncPairingState +import com.maxrave.domain.data.model.librarysync.LibrarySyncProblem +import com.maxrave.domain.data.model.librarysync.LibrarySyncState +import com.maxrave.domain.data.model.librarysync.PendingSettings +import com.maxrave.domain.data.model.loginsync.DesktopInfo +import com.maxrave.domain.data.model.loginsync.NetAddress +import com.maxrave.domain.repository.LibrarySyncHostRepository +import com.maxrave.domain.repository.LibrarySyncPhoneRepository +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch + +/** Desktop: the pairing QR, the paired phones, and settings a phone sent (#2663). */ +class LibrarySyncHostViewModel( + private val repository: LibrarySyncHostRepository, +) : ViewModel() { + val state: StateFlow = repository.state + val pairing: StateFlow = repository.pairing + val pendingSettings: StateFlow = repository.pendingSettings + + /** The dialog opened: checks the Windows network profile, and shows the QR straight away when no phone is paired. */ + fun open() { + viewModelScope.launch { + repository.checkNetworkProfile() + } + if (!repository.state.value.isPaired) startPairing() + } + + fun startPairing() { + viewModelScope.launch { repository.startPairing() } + } + + fun select(address: NetAddress) = repository.selectPairingAddress(address) + + /** Back to the list; the QR stops being valid. */ + fun stopPairing() { + viewModelScope.launch { repository.stopPairing() } + } + + fun removePhone(phoneId: String) { + viewModelScope.launch { repository.removePhone(phoneId) } + } + + fun applySettings(restart: () -> Unit) { + viewModelScope.launch { + repository.applyPendingSettings() + restart() + } + } + + fun dismissSettings() { + viewModelScope.launch { repository.dismissPendingSettings() } + } + + // The dialog can close with the ViewModel: the QR must still be withdrawn. + fun close() { + viewModelScope.launch(NonCancellable) { repository.stopPairing() } + } + + override fun onCleared() { + close() + } +} + +/** Android: scans the computer's QR, pairs, then shows the pairing's status (#2663). */ +class LibrarySyncPhoneViewModel( + private val repository: LibrarySyncPhoneRepository, +) : ViewModel() { + /** Only the unpaired side has steps; once paired the screen shows [state]. */ + sealed interface Step { + /** [blocked]: denied with "don't ask again", so only the system settings can grant it now. */ + data class NeedsPermission( + val blocked: Boolean, + ) : Step + + data object NoCamera : Step + + data object Scanning : Step + + data object Reaching : Step + + data class Confirm( + val desktop: DesktopInfo, + ) : Step + + data object Pairing : Step + + /** The computer removed this phone; the user decides when to scan again. */ + data object Revoked : Step + + data class Failed( + val problem: LibrarySyncProblem, + val detail: String?, + ) : Step + } + + val state: StateFlow = repository.state + val pendingSettings: StateFlow = repository.pendingSettings + + private val _step = MutableStateFlow(Step.Scanning) + val step: StateFlow = _step.asStateFlow() + + /** [hasPermissions]: camera (and Nearby devices on Android 17+) already granted. */ + fun open(hasPermissions: Boolean) { + val current = repository.state.value + _step.value = + when { + current.isPaired -> Step.Scanning + current.problem == LibrarySyncProblem.REVOKED -> Step.Revoked + else -> scanOrAsk(hasPermissions) + } + if (current.isPaired) syncNow() + } + + fun scan(hasPermissions: Boolean) { + _step.value = scanOrAsk(hasPermissions) + } + + fun onPermission( + granted: Boolean, + blocked: Boolean, + ) { + _step.value = if (granted) Step.Scanning else Step.NeedsPermission(blocked) + } + + fun onCameraUnavailable() { + _step.value = Step.NoCamera + } + + fun onScanned(text: String) { + // Any other QR (a Login Sync one included) is ignored and the camera keeps looking. + if (_step.value != Step.Scanning || !repository.isPairingCode(text)) return + _step.value = Step.Reaching + viewModelScope.launch { + _step.value = + try { + Step.Confirm(repository.reach(text)) + } catch (e: LibrarySyncException) { + Step.Failed(e.problem, e.detail) + } + } + } + + fun pair() { + if (_step.value !is Step.Confirm) return + _step.value = Step.Pairing + viewModelScope.launch { + try { + repository.pair() + // The paired status takes over the screen from here. + _step.value = Step.Scanning + } catch (e: LibrarySyncException) { + _step.value = Step.Failed(e.problem, e.detail) + } + } + } + + fun cancelConfirm(hasPermissions: Boolean) { + repository.cancelPairing() + _step.value = scanOrAsk(hasPermissions) + } + + fun syncNow() { + viewModelScope.launch { repository.syncNow() } + } + + fun unpair(hasPermissions: Boolean) { + viewModelScope.launch { + repository.unpairAll() + _step.value = scanOrAsk(hasPermissions) + } + } + + fun applySettings(restart: () -> Unit) { + viewModelScope.launch { + repository.applyPendingSettings() + restart() + } + } + + fun dismissSettings() { + viewModelScope.launch { repository.dismissPendingSettings() } + } + + fun close() = repository.cancelPairing() + + override fun onCleared() = close() + + private fun scanOrAsk(hasPermissions: Boolean): Step = if (hasPermissions) Step.Scanning else Step.NeedsPermission(blocked = false) +} diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/LoginSyncSenderViewModel.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/LoginSyncSenderViewModel.kt index 73a4017c0e..3cea9adab1 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/LoginSyncSenderViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/LoginSyncSenderViewModel.kt @@ -2,9 +2,12 @@ package com.maxrave.simpmusic.viewModel import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope +import com.maxrave.domain.data.model.librarysync.LibrarySyncException +import com.maxrave.domain.data.model.librarysync.LibrarySyncProblem import com.maxrave.domain.data.model.loginsync.DesktopInfo import com.maxrave.domain.data.model.loginsync.LoginSyncException import com.maxrave.domain.data.model.loginsync.LoginSyncService +import com.maxrave.domain.repository.LibrarySyncPhoneRepository import com.maxrave.domain.repository.LoginSyncSenderRepository import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow @@ -12,9 +15,13 @@ import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch -/** Android: scans the Desktop's QR, asks the user to trust it, sends the chosen sign-ins. */ +/** + * Android: scans the Desktop's QR, asks the user to trust it, sends the chosen sign-ins. Paired for + * library sync, it skips the QR and sends over the paired channel, where the computer's user decides. + */ class LoginSyncSenderViewModel( private val repository: LoginSyncSenderRepository, + private val librarySync: LibrarySyncPhoneRepository, ) : ViewModel() { sealed interface Step { data object Loading : Step @@ -42,6 +49,16 @@ class LoginSyncSenderViewModel( data object Sending : Step + /** Paired: the computer is asking its user (D4). */ + data class Waiting( + val desktop: DesktopInfo, + ) : Step + + /** Paired: the computer's user ignored the sign-ins, or did not answer in time. */ + data class Declined( + val desktop: DesktopInfo, + ) : Step + data class Done( val desktop: DesktopInfo, val services: List, @@ -57,6 +74,8 @@ class LoginSyncSenderViewModel( val step: Step = Step.Loading, val signedIn: List = emptyList(), val selected: Set = emptySet(), + /** The computer this phone is paired with for library sync, if any. */ + val pairedTo: DesktopInfo? = null, ) private val _uiState = MutableStateFlow(UiState()) @@ -66,14 +85,17 @@ class LoginSyncSenderViewModel( /** The sheet opened. [hasCamera]: the camera permission is already granted. */ fun open(hasCamera: Boolean) { - _uiState.value = UiState() + val pairedTo = librarySync.state.value.peers.firstOrNull()?.let { DesktopInfo(it.name, it.os) } + _uiState.value = UiState(pairedTo = pairedTo) viewModelScope.launch { val signedIn = repository.signedInServices() _uiState.value = UiState( + pairedTo = pairedTo, step = when { signedIn.isEmpty() -> Step.NothingSignedIn + pairedTo != null -> Step.Choose(pairedTo) hasCamera -> Step.Scanning else -> Step.NeedsCamera(blocked = false) }, @@ -117,6 +139,7 @@ class LoginSyncSenderViewModel( val choose = _uiState.value.step as? Step.Choose ?: return val services = _uiState.value.selected if (services.isEmpty()) return + if (_uiState.value.pairedTo != null) return sendPaired(choose.desktop, services) step(Step.Sending) viewModelScope.launch { step( @@ -129,9 +152,34 @@ class LoginSyncSenderViewModel( } } + private fun sendPaired( + desktop: DesktopInfo, + services: Set, + ) { + step(Step.Waiting(desktop)) + viewModelScope.launch { + step( + try { + val taken = librarySync.sendLogins(services) + if (taken.isEmpty()) Step.Declined(desktop) else Step.Done(desktop, taken) + } catch (e: LibrarySyncException) { + val reason = if (e.problem == LibrarySyncProblem.UNREACHABLE) LoginSyncException.Reason.UNREACHABLE else LoginSyncException.Reason.FAILED + Step.Failed(reason, e.detail) + }, + ) + } + } + fun retry(hasCamera: Boolean) { repository.disconnect() - step(if (hasCamera) Step.Scanning else Step.NeedsCamera(blocked = false)) + val pairedTo = _uiState.value.pairedTo + step( + when { + pairedTo != null -> Step.Choose(pairedTo) + hasCamera -> Step.Scanning + else -> Step.NeedsCamera(blocked = false) + }, + ) } /** The sheet is gone. A computer still waiting on this phone is put back on its QR. */ diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/SettingsViewModel.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/SettingsViewModel.kt index 6baa36a245..5767975dd5 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/SettingsViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/viewModel/SettingsViewModel.kt @@ -23,6 +23,8 @@ import com.maxrave.domain.repository.AccountRepository import com.maxrave.domain.repository.ArtistRepository import com.maxrave.domain.repository.CacheRepository import com.maxrave.domain.repository.DiscordRepository +import com.maxrave.domain.repository.LibrarySyncRepository +import com.maxrave.domain.data.model.librarysync.LibrarySyncState import com.maxrave.domain.repository.CommonRepository import com.maxrave.domain.repository.LyricsRomanizerRepository import com.maxrave.domain.repository.SongRepository @@ -83,6 +85,7 @@ class SettingsViewModel( private val artistRepository: ArtistRepository, private val lyricsRomanizerRepository: LyricsRomanizerRepository, private val discordRepository: DiscordRepository, + private val librarySyncRepository: LibrarySyncRepository, ) : BaseViewModel() { private val databasePath: String? = commonRepository.getDatabasePath() private val downloadUtils: DownloadHandler by inject() @@ -90,6 +93,10 @@ class SettingsViewModel( val castState: StateFlow get() = mediaPlayerHandler.castState val eightDAvailable: StateFlow get() = mediaPlayerHandler.player.eightDAvailable + /** Library sync (#2663): clearing history and restoring a backup both leave the pairing. */ + val librarySyncPaired: Boolean get() = librarySyncRepository.state.value.isPaired + val librarySyncState: StateFlow get() = librarySyncRepository.state + /** READY everywhere the dictionary is bundled (Desktop), so only Android ever leaves it. */ val japaneseDictionaryState: StateFlow = lyricsRomanizerRepository.japaneseDictionaryState @@ -1327,7 +1334,16 @@ class SettingsViewModel( // last, so a run stopped in between — the user leaving Settings is enough to do // it — has already dropped every cached playlist, album and artist and left the // songs behind. Nothing resumes it afterwards, so it has to run to the end. - withContext(NonCancellable) { songRepository.clearHistoryAndOrphanedSongs() } + withContext(NonCancellable) { + // Paired: leave the pairing first, so nothing synced lands after the wipe and + // the wipe itself never reaches the other device. The wipe goes on regardless. + try { + librarySyncRepository.unpairAll() + } catch (e: Exception) { + Logger.e(tag, "library sync: unpair before clearing history failed", e) + } + songRepository.clearHistoryAndOrphanedSongs() + } } catch (e: CancellationException) { // Not a failure, and it must not be swallowed: catching it breaks structured // concurrency, and it would put the generic error toast in front of a user whose @@ -1380,6 +1396,10 @@ class SettingsViewModel( makeToast(getString(Res.string.restore_in_progress)) withContext(Dispatchers.IO) { runCatching { + // The restored database replaces everything the sync log and the other device + // know about; pairing again starts both from it. A failure here must not stop the restore. + runCatching { librarySyncRepository.unpairAll() } + .onFailure { Logger.e(tag, "library sync: unpair before restore failed", it) } restoreNative(commonRepository, uri) { getData() } diff --git a/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/DesktopApp.kt b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/DesktopApp.kt index c3638644a2..69634ef759 100644 --- a/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/DesktopApp.kt +++ b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/DesktopApp.kt @@ -33,9 +33,11 @@ import com.maxrave.domain.manager.DataStoreManager import com.maxrave.domain.mediaservice.handler.MediaPlayerHandler import com.maxrave.domain.mediaservice.handler.ToastType import com.maxrave.domain.notification.DesktopNotificationManager +import com.maxrave.domain.repository.LibrarySyncHostRepository import com.maxrave.data.io.getHomeFolderPath import com.maxrave.logger.Logger import com.maxrave.simpmusic.di.viewModelModule +import com.maxrave.simpmusic.expect.ui.LibrarySyncLoginPrompt import com.maxrave.simpmusic.extension.DesktopWindowChrome import com.maxrave.simpmusic.ui.component.CustomTitleBar import com.maxrave.simpmusic.ui.mini_player.MiniPlayerManager @@ -53,10 +55,14 @@ import io.sentry.Sentry import io.sentry.SentryLevel import io.sentry.protocol.OperatingSystem import io.sentry.protocol.User +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.first +import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import multiplatform.network.cmptoast.ToastHost import multiplatform.network.cmptoast.showToast @@ -267,6 +273,9 @@ fun runDesktopApp(args: Array = emptyArray()) { val desktopNotificationManager = getKoin().get() desktopNotificationManager.initialize() + // Library sync (#2663): reopens the server for paired phones. Off the startup path: it binds a port. + CoroutineScope(SupervisorJob() + Dispatchers.IO).launch { getKoin().get().start() } + val sharedViewModel = getKoin().get() if (sharedViewModel.shouldCheckForUpdate()) { sharedViewModel.checkForUpdate() @@ -505,6 +514,7 @@ fun runDesktopApp(args: Array = emptyArray()) { onOpenDesktopNotificationSettings = desktopNotificationManager::openNotificationSettings, ) + LibrarySyncLoginPrompt() ToastHost() } } 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 new file mode 100644 index 0000000000..9d3608807b --- /dev/null +++ b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/expect/ui/LibrarySync.jvm.kt @@ -0,0 +1,278 @@ +package com.maxrave.simpmusic.expect.ui + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +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.verticalScroll +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.LocalContentColor +import androidx.compose.material3.RadioButton +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +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.maxrave.domain.data.model.librarysync.LibrarySyncPairingState +import com.maxrave.domain.data.model.librarysync.LibrarySyncProblem +import com.maxrave.domain.data.model.librarysync.SyncPeer +import com.maxrave.domain.repository.LibrarySyncHostRepository +import com.maxrave.simpmusic.expect.openUrl +import com.maxrave.simpmusic.ui.theme.AppTheme +import com.maxrave.simpmusic.ui.theme.typo +import com.maxrave.simpmusic.viewModel.LibrarySyncHostViewModel +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.cancel +import simpmusic.composeapp.generated.resources.library_sync_desktop_footer +import simpmusic.composeapp.generated.resources.library_sync_desktop_instructions +import simpmusic.composeapp.generated.resources.library_sync_failed +import simpmusic.composeapp.generated.resources.library_sync_first_sync_desktop +import simpmusic.composeapp.generated.resources.library_sync_ignore +import simpmusic.composeapp.generated.resources.library_sync_logins_message +import simpmusic.composeapp.generated.resources.library_sync_logins_title +import simpmusic.composeapp.generated.resources.library_sync_open_network_settings +import simpmusic.composeapp.generated.resources.library_sync_pair_another +import simpmusic.composeapp.generated.resources.library_sync_pair_phone +import simpmusic.composeapp.generated.resources.library_sync_paired_with +import simpmusic.composeapp.generated.resources.library_sync_peer_not_synced +import simpmusic.composeapp.generated.resources.library_sync_peer_synced +import simpmusic.composeapp.generated.resources.library_sync_port_in_use +import simpmusic.composeapp.generated.resources.library_sync_remove +import simpmusic.composeapp.generated.resources.library_sync_remove_message +import simpmusic.composeapp.generated.resources.library_sync_remove_title +import simpmusic.composeapp.generated.resources.library_sync_settings_differ_desktop +import simpmusic.composeapp.generated.resources.library_sync_title +import simpmusic.composeapp.generated.resources.library_sync_use +import simpmusic.composeapp.generated.resources.library_sync_windows_public +import simpmusic.composeapp.generated.resources.login_sync_new_code +import simpmusic.composeapp.generated.resources.login_sync_no_network +import simpmusic.composeapp.generated.resources.login_sync_pick_address +import simpmusic.composeapp.generated.resources.ok +import kotlin.system.exitProcess + +@Composable +actual fun LibrarySyncDialog(onDismiss: () -> Unit) { + val viewModel: LibrarySyncHostViewModel = koinViewModel() + val state by viewModel.state.collectAsStateWithLifecycle() + val pairing by viewModel.pairing.collectAsStateWithLifecycle() + val pending by viewModel.pendingSettings.collectAsStateWithLifecycle() + var removing by remember { mutableStateOf(null) } + + LaunchedEffect(viewModel) { viewModel.open() } + DisposableEffect(viewModel) { onDispose { viewModel.close() } } + + val showingQr = pairing !is LibrarySyncPairingState.Idle && pairing !is LibrarySyncPairingState.Paired + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(text = stringResource(Res.string.library_sync_title), style = typo().titleSmall) }, + text = { + Column( + modifier = Modifier.fillMaxWidth().verticalScroll(rememberScrollState()), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + when (val p = pairing) { + LibrarySyncPairingState.Starting -> { + CircularProgressIndicator() + } + + is LibrarySyncPairingState.Waiting -> { + QrCode(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()) { + p.addresses.forEach { address -> + Row( + modifier = + Modifier + .fillMaxWidth() + .selectable( + selected = address == p.selected, + role = Role.RadioButton, + onClick = { viewModel.select(address) }, + ).padding(vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + RadioButton(selected = address == p.selected, onClick = null) + Spacer(Modifier.width(8.dp)) + Text(text = address.ip, style = typo().bodyMedium) + Spacer(Modifier.width(8.dp)) + Text(text = address.interfaceName, style = typo().bodySmall, maxLines = 1) + } + } + } + WindowsPublicBox(state.problem) + } + + LibrarySyncPairingState.NoNetwork -> { + Text(text = stringResource(Res.string.login_sync_no_network)) + } + + is LibrarySyncPairingState.Failed -> { + SyncProblemBox( + if (p.problem == LibrarySyncProblem.PORT_IN_USE) { + stringResource(Res.string.library_sync_port_in_use) + } else { + stringResource(Res.string.library_sync_failed, p.detail.orEmpty()) + }, + ) + } + + is LibrarySyncPairingState.Paired -> { + Text(text = stringResource(Res.string.library_sync_paired_with, p.peer.name), style = typo().bodyMedium) + Text(text = stringResource(Res.string.library_sync_first_sync_desktop), style = typo().bodySmall) + } + + LibrarySyncPairingState.Idle -> { + state.peers.forEach { peer -> + Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + Column(Modifier.weight(1f)) { + Text(text = peer.name, style = typo().bodyMedium) + Text( + text = + peer.lastSyncAt?.let { stringResource(Res.string.library_sync_peer_synced, peer.os, syncedAgo(it)) } + ?: stringResource(Res.string.library_sync_peer_not_synced, peer.os), + style = typo().bodySmall, + ) + } + TextButton(onClick = { removing = peer }) { + Text(text = stringResource(Res.string.library_sync_remove), color = LocalContentColor.current) + } + } + } + pending?.let { + PendingSettingsCard( + pending = it, + differ = stringResource(Res.string.library_sync_settings_differ_desktop), + onNotNow = viewModel::dismissSettings, + onApply = { viewModel.applySettings(::restartAfterSyncedSettings) }, + ) + } + WindowsPublicBox(state.problem) + if (state.problem == LibrarySyncProblem.PORT_IN_USE) SyncProblemBox(stringResource(Res.string.library_sync_port_in_use)) + Text(text = stringResource(Res.string.library_sync_desktop_footer), style = typo().bodySmall) + } + } + } + }, + confirmButton = { + when { + pairing is LibrarySyncPairingState.Paired -> { + TextButton(onClick = viewModel::stopPairing) { Text(text = stringResource(Res.string.ok), color = LocalContentColor.current) } + } + + // Cancel from the QR goes back to the list when a phone is paired, else closes. + showingQr -> { + TextButton(onClick = { if (state.isPaired) viewModel.stopPairing() else onDismiss() }) { + Text(text = stringResource(Res.string.cancel), color = LocalContentColor.current) + } + } + + else -> { + TextButton(onClick = onDismiss) { Text(text = stringResource(Res.string.ok), color = LocalContentColor.current) } + } + } + }, + dismissButton = { + when { + pairing is LibrarySyncPairingState.NoNetwork || pairing is LibrarySyncPairingState.Failed -> { + TextButton(onClick = viewModel::startPairing) { + Text(text = stringResource(Res.string.login_sync_new_code), color = LocalContentColor.current) + } + } + + pairing is LibrarySyncPairingState.Idle -> { + TextButton(onClick = viewModel::startPairing) { + Text( + text = stringResource(if (state.isPaired) Res.string.library_sync_pair_another else Res.string.library_sync_pair_phone), + color = LocalContentColor.current, + ) + } + } + + else -> {} + } + }, + ) + + removing?.let { peer -> + AlertDialog( + onDismissRequest = { removing = null }, + title = { Text(text = stringResource(Res.string.library_sync_remove_title, peer.name), style = typo().titleSmall) }, + text = { Text(text = stringResource(Res.string.library_sync_remove_message, peer.name)) }, + confirmButton = { + TextButton(onClick = { + viewModel.removePhone(peer.id) + removing = null + }) { Text(text = stringResource(Res.string.library_sync_remove), color = LocalContentColor.current) } + }, + dismissButton = { + TextButton(onClick = { removing = null }) { Text(text = stringResource(Res.string.cancel), color = LocalContentColor.current) } + }, + ) + } +} + +@Composable +private fun WindowsPublicBox(problem: LibrarySyncProblem?) { + if (problem != LibrarySyncProblem.WINDOWS_PUBLIC_NETWORK) return + SyncProblemBox( + text = stringResource(Res.string.library_sync_windows_public), + action = stringResource(Res.string.library_sync_open_network_settings), + onAction = { openUrl("ms-settings:network-status") }, + ) +} + +/** + * Sign-ins a paired phone sent: nothing is used until the user here says so (D4). Lives over the + * whole window, since the phone sends them whenever its user asks. + */ +@Composable +fun LibrarySyncLoginPrompt() { + val repository: LibrarySyncHostRepository = koinInject() + val pending by repository.pendingLogins.collectAsStateWithLifecycle() + val logins = pending ?: return + // Outside App(), so it brings a theme of its own: the app's default dark one. + AppTheme { + AlertDialog( + onDismissRequest = {}, + title = { Text(text = stringResource(Res.string.library_sync_logins_title, logins.fromName), style = typo().titleSmall) }, + text = { Text(text = stringResource(Res.string.library_sync_logins_message, logins.services.joinToString { it.label })) }, + confirmButton = { + TextButton(onClick = { repository.answerLogins(true) }) { + Text(text = stringResource(Res.string.library_sync_use), color = LocalContentColor.current) + } + }, + dismissButton = { + TextButton(onClick = { repository.answerLogins(false) }) { + Text(text = stringResource(Res.string.library_sync_ignore), color = LocalContentColor.current) + } + }, + ) + } +} + +// The same exit a restored backup takes; Desktop has no relaunch of its own. +actual fun restartAfterSyncedSettings() { + exitProcess(0) +} 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 edcca8865f..939716c939 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 @@ -167,7 +167,7 @@ actual fun LoginSyncDialog(onDismiss: () -> Unit) { /** Dark modules on white whatever the theme: scanners expect that polarity. */ @Composable -private fun QrCode( +internal fun QrCode( text: String, modifier: Modifier = Modifier, ) { diff --git a/core b/core index a4e6231015..edfac2ca13 160000 --- a/core +++ b/core @@ -1 +1 @@ -Subproject commit a4e62310154c6dc37846237cd7a4ed83708313ed +Subproject commit edfac2ca13f73a047bac7698a2b543bf87f825d0 From 609369fff19698a477ec0e76d640a52e9b5eefec Mon Sep 17 00:00:00 2001 From: maxrave-dev Date: Thu, 12 Nov 2026 23:22:57 +0700 Subject: [PATCH 26/29] feat(ui): add desktop vertical scrollbars, unify artwork corners and tighten Android home --- CLAUDE.md | 6 + .../simpmusic/expect/ui/LoginSync.android.kt | 22 +- .../simpmusic/expect/ui/Scrollbar.android.kt | 22 ++ .../expect/ui/SongRecognition.android.kt | 3 +- .../maxrave/simpmusic/expect/ui/Scrollbar.kt | 29 +++ .../simpmusic/ui/component/AdapterItems.kt | 62 ++++-- .../ui/component/CommentsBottomSheet.kt | 5 + .../simpmusic/ui/component/DesktopSidebar.kt | 11 +- .../ui/component/FiveImagesComponent.kt | 4 +- .../simpmusic/ui/component/FullWidthItems.kt | 8 +- .../ui/component/FullscreenLyricsContent.kt | 5 +- .../ui/component/GridLibraryPlaylist.kt | 6 + .../ui/component/HomeSectionStyles.kt | 4 + .../simpmusic/ui/component/LibraryItem.kt | 4 +- .../ui/component/LibraryTilingBox.kt | 3 +- .../ui/component/ModalBottomSheet.kt | 189 +++++++++--------- .../ui/component/MoodCategoryCard.kt | 3 +- .../ui/component/WrappedEntryCard.kt | 5 +- .../maxrave/simpmusic/ui/screen/MiniPlayer.kt | 5 +- .../simpmusic/ui/screen/home/HomeScreen.kt | 30 ++- .../ui/screen/home/ListenTogetherScreen.kt | 75 ++++--- .../home/ListenTogetherSettingsScreen.kt | 9 +- .../simpmusic/ui/screen/home/MoodScreen.kt | 10 + .../ui/screen/home/NotificationScreen.kt | 10 +- .../simpmusic/ui/screen/home/SettingScreen.kt | 6 + .../screen/home/analytics/AnalyticsScreen.kt | 12 +- .../library/LibraryDynamicPlaylistScreen.kt | 9 + .../ui/screen/library/LibraryScreen.kt | 6 + .../ui/screen/library/LocalPlaylistScreen.kt | 9 +- .../screen/login/DiscordOAuthLoginScreen.kt | 9 +- .../ui/screen/login/LastfmLoginScreen.kt | 9 +- .../simpmusic/ui/screen/login/LogInScreen.kt | 173 ++++++++-------- .../simpmusic/ui/screen/other/AlbumScreen.kt | 9 +- .../simpmusic/ui/screen/other/AppLogScreen.kt | 12 ++ .../simpmusic/ui/screen/other/ArtistScreen.kt | 6 + .../simpmusic/ui/screen/other/BrowseScreen.kt | 6 + .../simpmusic/ui/screen/other/CreditScreen.kt | 9 +- .../ui/screen/other/MoreAlbumsScreen.kt | 9 + .../ui/screen/other/PlaylistScreen.kt | 9 +- .../ui/screen/other/PodcastsScreen.kt | 9 +- .../simpmusic/ui/screen/other/SearchScreen.kt | 21 +- .../content/NowPlayingContentAppleMusic.kt | 5 +- .../content/NowPlayingContentM3Expressive.kt | 3 +- .../content/NowPlayingContentSpotify.kt | 13 +- .../content/applemusic/AppleMusicQueueView.kt | 5 + .../content/applemusic/AppleMusicShared.kt | 3 +- .../com/maxrave/simpmusic/ui/theme/Theme.kt | 5 + .../com/maxrave/simpmusic/DesktopApp.kt | 2 +- .../simpmusic/expect/ui/LibrarySync.jvm.kt | 16 +- .../simpmusic/expect/ui/LoginSync.jvm.kt | 8 +- .../simpmusic/expect/ui/Scrollbar.jvm.kt | 42 ++++ .../ui/mini_player/MiniPlayerLayout.kt | 7 +- 52 files changed, 681 insertions(+), 281 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 01d11a8021..2f361bead7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1173,6 +1173,12 @@ if (getPlatform() == Platform.Android) { - **Identity is the key, not the IP.** Pairing hands the phone a long-lived key under the QR's one-time key; every later knock carries a nonce the computer must echo with its id, and every sync reply echoes the request's nonce. A 403 alone never unpairs a phone: only the computer's own sealed "removed" knock reply does, and the computer keeps answering it for the 30 days a removed phone is remembered. The server refuses a body with no Content-Length before reading it. The phone looks for the computer at the address picked when pairing (LAN, Tailscale, anything listed), then every address it last reported, then a sealed UDP probe (multicast 239.255.48.17 + broadcast), then a sweep of its /24. - **Deletion never propagates by accident.** Clearing listening history unpairs first (Desktop: every phone), and so does restoring a backup. A removed phone is told under its own key the next time it knocks. Settings travel every round but are applied only after the user agrees (allowlist in `SyncedSettings.KEYS`). A database copy is taken before the first merge of a pairing and before a merge that removes something, at most one an hour, three kept (`~/.simpmusic/sync-backups`, `filesDir/sync-backups`). Pairing state lives in its own `library_sync.preferences_pb`, outside the settings file, so a backup cannot carry a pairing key to another device. +- **Desktop vertical scrollbars, one artwork corner, tighter Android Home (2026-11-12)**: + - `VerticalScrollBar(scrollState, modifier)` (`expect/ui/Scrollbar*.kt`, overloads for `LazyListState`, `LazyGridState`, `ScrollState`) puts Compose Desktop's `VerticalScrollbar`, in the horizontal bars' `scrollBarStyle`, on the right edge of every scrolling page, the sidebar, both queues and the comments sheet. The Desktop gate is inside the function and the Android actual is empty. Thumb drag and press-and-hold paging (one page, then one every 100ms after 300ms) are Compose's own. Put it right after the list in a parent that stacks its children (Box, Crossfade, AnimatedContent): it fills that parent and only the bar takes input. `modifier` carries the list's top inset and `DesktopMiniPlayerClearance` (80dp: the capsule's 60dp plus its 20dp margin). A new vertical list on Desktop gets one too. + - `ArtworkShape` (`ui/theme/Theme.kt`, 4dp, measured off Spotify) is the one corner for rounded artwork; it replaced 2–14dp radii at 44 sites. It is not for circles (artists, avatars), edge-to-edge headers, or the three cards that define a style (M3 Expressive 28dp, SoundCloud 20dp, Your daily discover 28dp). + - 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`. + ## 🔄 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/src/androidMain/kotlin/com/maxrave/simpmusic/expect/ui/LoginSync.android.kt b/composeApp/src/androidMain/kotlin/com/maxrave/simpmusic/expect/ui/LoginSync.android.kt index 180a73d344..68add4c406 100644 --- a/composeApp/src/androidMain/kotlin/com/maxrave/simpmusic/expect/ui/LoginSync.android.kt +++ b/composeApp/src/androidMain/kotlin/com/maxrave/simpmusic/expect/ui/LoginSync.android.kt @@ -39,6 +39,7 @@ import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton +import androidx.compose.material3.LocalContentColor import androidx.compose.material3.ModalBottomSheet import androidx.compose.material3.Text import androidx.compose.material3.TextButton @@ -68,7 +69,6 @@ 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.seed import com.maxrave.simpmusic.ui.theme.typo import com.maxrave.simpmusic.viewModel.LoginSyncSenderViewModel import com.maxrave.simpmusic.viewModel.LoginSyncSenderViewModel.Step @@ -302,10 +302,12 @@ actual fun LoginSyncDialog(onDismiss: () -> Unit) { title = { Text(text = stringResource(Res.string.login_sync_trust_title), style = typo().titleSmall) }, text = { Text(text = stringResource(Res.string.login_sync_trust_message, step.desktop.name, step.desktop.os)) }, confirmButton = { - TextButton(onClick = viewModel::trust) { Text(text = stringResource(Res.string.login_sync_trust)) } + TextButton(onClick = viewModel::trust) { + Text(text = stringResource(Res.string.login_sync_trust), color = LocalContentColor.current) + } }, dismissButton = { - TextButton(onClick = ::close) { Text(text = stringResource(Res.string.cancel)) } + TextButton(onClick = ::close) { Text(text = stringResource(Res.string.cancel), color = LocalContentColor.current) } }, ) } @@ -337,11 +339,11 @@ actual fun LoginSyncDialog(onDismiss: () -> Unit) { }, confirmButton = { TextButton(enabled = uiState.selected.isNotEmpty(), onClick = viewModel::send) { - Text(text = stringResource(Res.string.login_sync_send)) + Text(text = stringResource(Res.string.login_sync_send), color = LocalContentColor.current) } }, dismissButton = { - TextButton(onClick = ::close) { Text(text = stringResource(Res.string.cancel)) } + TextButton(onClick = ::close) { Text(text = stringResource(Res.string.cancel), color = LocalContentColor.current) } }, ) } @@ -374,9 +376,9 @@ internal fun Status( } /** - * The app's sheet button (ModalBottomSheet.kt's sleep timer "Set"): seed fill, 12dp corners. The text - * colour is set explicitly because typo() bakes a body colour into every style — a stock M3 Button - * inherits that instead of onPrimary and renders pale text on a pale fill. + * The sheet's button: the theme's primary fill, 12dp corners, so it follows the user's theme colour. + * The text colour is set explicitly because typo() bakes a body colour into every style — a stock M3 + * Button inherits that instead of onPrimary and renders pale text on a pale fill. */ @Composable internal fun SheetButton( @@ -387,12 +389,12 @@ internal fun SheetButton( onClick = onClick, modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(12.dp), - colors = ButtonDefaults.buttonColors(containerColor = seed), + colors = ButtonDefaults.buttonColors(), ) { Text( text = text, style = typo().labelSmall, - color = rememberSurfaceDarkColors().content, + color = LocalContentColor.current, modifier = Modifier.padding(vertical = 4.dp), ) } diff --git a/composeApp/src/androidMain/kotlin/com/maxrave/simpmusic/expect/ui/Scrollbar.android.kt b/composeApp/src/androidMain/kotlin/com/maxrave/simpmusic/expect/ui/Scrollbar.android.kt index e06c9371ca..93868ec103 100644 --- a/composeApp/src/androidMain/kotlin/com/maxrave/simpmusic/expect/ui/Scrollbar.android.kt +++ b/composeApp/src/androidMain/kotlin/com/maxrave/simpmusic/expect/ui/Scrollbar.android.kt @@ -1,5 +1,6 @@ package com.maxrave.simpmusic.expect.ui +import androidx.compose.foundation.ScrollState import androidx.compose.foundation.gestures.FlingBehavior import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.lazy.grid.LazyGridState @@ -32,3 +33,24 @@ actual fun HorizontalScrollBar( itemCount: Int, ) { } + +@Composable +actual fun VerticalScrollBar( + scrollState: LazyListState, + modifier: Modifier, +) { +} + +@Composable +actual fun VerticalScrollBar( + scrollState: LazyGridState, + modifier: Modifier, +) { +} + +@Composable +actual fun VerticalScrollBar( + scrollState: ScrollState, + modifier: Modifier, +) { +} diff --git a/composeApp/src/androidMain/kotlin/com/maxrave/simpmusic/expect/ui/SongRecognition.android.kt b/composeApp/src/androidMain/kotlin/com/maxrave/simpmusic/expect/ui/SongRecognition.android.kt index ea9a689406..1d6d208941 100644 --- a/composeApp/src/androidMain/kotlin/com/maxrave/simpmusic/expect/ui/SongRecognition.android.kt +++ b/composeApp/src/androidMain/kotlin/com/maxrave/simpmusic/expect/ui/SongRecognition.android.kt @@ -78,6 +78,7 @@ import com.maxrave.simpmusic.ui.icon.Refresh import com.maxrave.simpmusic.ui.icon.Replay import com.maxrave.simpmusic.ui.icon.Search import com.maxrave.simpmusic.ui.icon.SimpIcons +import com.maxrave.simpmusic.ui.theme.ArtworkShape import com.maxrave.simpmusic.ui.theme.typo import kotlinx.coroutines.launch import org.jetbrains.compose.resources.stringResource @@ -227,7 +228,7 @@ actual fun SongRecognitionSheet( modifier = Modifier .size(OrbSize) - .clip(RoundedCornerShape(14.dp)) + .clip(ArtworkShape) .background(colors.handle), ) Column( diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/expect/ui/Scrollbar.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/expect/ui/Scrollbar.kt index 2c92131140..e1c4636c48 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/expect/ui/Scrollbar.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/expect/ui/Scrollbar.kt @@ -1,5 +1,6 @@ package com.maxrave.simpmusic.expect.ui +import androidx.compose.foundation.ScrollState import androidx.compose.foundation.gestures.FlingBehavior import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.lazy.grid.LazyGridState @@ -7,6 +8,7 @@ import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.carousel.CarouselState import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp /** [flingBehavior]: the list's own snap fling, run once the thumb is let go so a drag ends on an item. */ @Composable @@ -35,3 +37,30 @@ expect fun HorizontalScrollBar( scrollState: CarouselState, itemCount: Int, ) + +/** Space the Desktop capsule player takes at the bottom of a page (App.kt: 60dp tall, 20dp off the bottom). */ +val DesktopMiniPlayerClearance = 80.dp + +/** + * Desktop only: a bar along the right edge of a vertical list, dragged by its thumb or held on its + * track to page. Put it right after the list, in a parent that stacks its children (Box, Crossfade, + * AnimatedContent): it fills that parent and takes input only on the bar itself. [modifier] carries the + * list's top and bottom padding, so the track starts below the top bar and ends above the mini player. + */ +@Composable +expect fun VerticalScrollBar( + scrollState: LazyListState, + modifier: Modifier = Modifier, +) + +@Composable +expect fun VerticalScrollBar( + scrollState: LazyGridState, + modifier: Modifier = Modifier, +) + +@Composable +expect fun VerticalScrollBar( + scrollState: ScrollState, + modifier: Modifier = Modifier, +) diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/AdapterItems.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/AdapterItems.kt index c1ff8a43a6..2ab64cbb9e 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/AdapterItems.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/AdapterItems.kt @@ -64,7 +64,9 @@ import androidx.compose.ui.geometry.CornerRadius import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.rememberTextMeasurer import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.Dp @@ -117,6 +119,7 @@ import com.maxrave.simpmusic.ui.navigation.destination.list.PlaylistDestination import com.maxrave.simpmusic.ui.navigation.destination.list.PodcastDestination import com.maxrave.simpmusic.ui.icon.PlayArrow import com.maxrave.simpmusic.ui.icon.SimpIcons +import com.maxrave.simpmusic.ui.theme.ArtworkShape import com.maxrave.simpmusic.ui.theme.LocalForceDarkText import com.maxrave.simpmusic.ui.theme.typo import com.maxrave.simpmusic.viewModel.HomeViewModel @@ -407,6 +410,32 @@ private fun Content.hoverPlay(viewModel: BaseViewModel): (() -> Unit)? { return { viewModel.playFromEndpoint(endpoint, title) } } +// Android packs the Home-family cards tighter than Desktop: 8dp sides, so two artworks sit 16dp apart +// instead of 20. Desktop keeps the values it was tuned with. +private val compactCards = getPlatform() == Platform.Android +private val cardSidePadding = if (compactCards) 8.dp else 10.dp + +/** + * The tallest text block under a Home card's artwork — HomeItemSong's: 8dp, two title lines, and the + * subtitle row (its line plus 6dp, or the 20dp explicit badge) — measured in this device's own text. + * Android floors a card at artwork + this, so the tallest card in a row ends right under its subtitle. + * Desktop keeps its fixed 70dp, measured where Skia counts Poppins' line gap; on Android that left ~10dp spare. + */ +@Composable +private fun cardTextBlockFloor(): Dp { + val measurer = rememberTextMeasurer() + val density = LocalDensity.current + val title = typo().titleSmall + val subtitle = typo().bodySmall + return remember(measurer, density, title, subtitle) { + with(density) { + val titleLines = measurer.measure("A\nA", title).size.height.toDp() + val subtitleRow = maxOf(measurer.measure("A", subtitle).size.height.toDp() + 6.dp, 20.dp) + 8.dp + titleLines + subtitleRow + } + } +} + /** * Spotify-style hover for a Home card: while the pointer is over it, or keyboard focus is on it, * the card sits on a faint onSurface tint and [HoverPlayButton] rises onto the artwork. Touch @@ -568,13 +597,13 @@ fun HomeItemContentPlaylist( Column( modifier = Modifier - .padding(start = 10.dp, top = 10.dp, end = 10.dp, bottom = 6.dp) + .padding(start = cardSidePadding, top = 10.dp, end = cardSidePadding, bottom = 6.dp) // One floor for every home card, so a row mixing them stays one height. 70 // covers the tallest text block among them, HomeItemSong's: 69.5dp when the // text engine counts Poppins' line gap (Skia on Desktop does), 65.8dp when not. // A cell-filling card has no such row to match and its artwork is narrower than // thumbSize, so the floor would only add empty space under every tile. - .then(if (fillMaxWidth) Modifier else Modifier.heightIn(min = thumbSize + 70.dp)), + .then(if (fillMaxWidth) Modifier else Modifier.heightIn(min = thumbSize + if (compactCards) cardTextBlockFloor() else 70.dp)), ) { val thumb = when (data) { @@ -681,7 +710,7 @@ fun HomeItemContentPlaylist( (if (fillMaxWidth) Modifier.fillMaxWidth() else Modifier.size(thumbSize)) .aspectRatio(1f) .clip( - RoundedCornerShape(10.dp), + ArtworkShape, ).hoverZoom(hovered), ) if (onPlay != null) HoverPlayButton(visible = hovered, onClick = onPlay) @@ -832,7 +861,8 @@ fun QuickPicksItem( modifier = Modifier .fillMaxWidth() - .padding(10.dp), + // 44dp artwork plus this padding is the grid's cell: 64dp, or 56dp on Android. + .padding(horizontal = 10.dp, vertical = if (compactCards) 6.dp else 10.dp), ) { AsyncImage( model = @@ -851,7 +881,7 @@ fun QuickPicksItem( .align(Alignment.CenterVertically) .size(44.dp) .clip( - RoundedCornerShape(10), + ArtworkShape, ), ) Column( @@ -862,7 +892,7 @@ fun QuickPicksItem( verticalArrangement = Arrangement.SpaceEvenly, ) { // One line + marquee, NOT maxLines = 2: the parent LazyHorizontalGrid uses - // GridCells.Fixed(4) over a fixed 256.dp, so every cell is exactly 64.dp and a + // GridCells.Fixed(4) over a fixed 256.dp (224.dp on Android), so every cell is exactly 64.dp (56.dp) and a // second title line pushes the artist row out of the cell, where the grid clips it. Text( text = data.title, @@ -955,8 +985,8 @@ fun HomeItemSong( Column( modifier = Modifier - .padding(start = 10.dp, top = 10.dp, end = 10.dp, bottom = 6.dp) - .heightIn(min = 230.dp), + .padding(start = cardSidePadding, top = 10.dp, end = cardSidePadding, bottom = 6.dp) + .heightIn(min = if (compactCards) 160.dp + cardTextBlockFloor() else 230.dp), ) { val thumb = data.thumbnails.lastOrNull()?.url?.let { @@ -984,7 +1014,7 @@ fun HomeItemSong( Modifier .then(if (fillMaxWidth) Modifier.fillMaxWidth().aspectRatio(1f) else Modifier.size(160.dp)) .clip( - RoundedCornerShape(10.dp), + ArtworkShape, ).hoverZoom(hovered), ) if (onPlay != null) HoverPlayButton(visible = hovered, onClick = onPlay) @@ -1066,8 +1096,8 @@ fun HomeItemVideo( Column( modifier = Modifier - .padding(start = 10.dp, top = 10.dp, end = 10.dp, bottom = 6.dp) - .heightIn(min = 230.dp), + .padding(start = cardSidePadding, top = 10.dp, end = cardSidePadding, bottom = 6.dp) + .heightIn(min = if (compactCards) 160.dp + cardTextBlockFloor() else 230.dp), ) { val thumb = data.thumbnails.lastOrNull()?.url Box(Modifier.align(Alignment.CenterHorizontally)) { @@ -1089,7 +1119,7 @@ fun HomeItemVideo( .then(if (fillMaxWidth) Modifier.fillMaxWidth() else Modifier.height(160.dp)) .aspectRatio(16f / 9f) .clip( - RoundedCornerShape(10.dp), + ArtworkShape, ).hoverZoom(hovered), ) if (onPlay != null) HoverPlayButton(visible = hovered, onClick = onPlay) @@ -1184,8 +1214,8 @@ fun HomeItemArtist( Column( modifier = Modifier - .padding(start = 10.dp, top = 10.dp, end = 10.dp, bottom = 6.dp) - .heightIn(min = 230.dp), + .padding(start = cardSidePadding, top = 10.dp, end = cardSidePadding, bottom = 6.dp) + .heightIn(min = if (compactCards) 160.dp + cardTextBlockFloor() else 230.dp), ) { val thumb = data.thumbnails.lastOrNull()?.url AsyncImage( @@ -1325,7 +1355,7 @@ fun ItemVideoChart( .width(280.dp) .height(160.dp) .clip( - RoundedCornerShape(10), + ArtworkShape, ), ) Row { @@ -1545,7 +1575,7 @@ fun ItemTrackChart( .align(Alignment.CenterVertically) .size(50.dp) .clip( - RoundedCornerShape(10), + ArtworkShape, ), ) Column( diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/CommentsBottomSheet.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/CommentsBottomSheet.kt index d89a7cebb4..c642e0f308 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/CommentsBottomSheet.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/CommentsBottomSheet.kt @@ -72,6 +72,7 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle import coil3.compose.AsyncImage import com.maxrave.domain.data.model.comments.CommentLikeState import com.maxrave.domain.data.model.comments.YouTubeComment +import com.maxrave.simpmusic.expect.ui.VerticalScrollBar import com.maxrave.simpmusic.ui.icon.CheckCircle import com.maxrave.simpmusic.ui.icon.Close import com.maxrave.simpmusic.ui.icon.Send @@ -365,6 +366,10 @@ private fun CommentsBody( } } } + VerticalScrollBar( + scrollState = listState, + modifier = Modifier.padding(bottom = bottomPadding), + ) } } } diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/DesktopSidebar.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/DesktopSidebar.kt index 24a8f403e4..e2c653edf7 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/DesktopSidebar.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/DesktopSidebar.kt @@ -79,7 +79,9 @@ import coil3.request.CachePolicy import coil3.request.ImageRequest import com.kyant.backdrop.highlight.Highlight import com.maxrave.domain.data.model.library.LibraryCollectionPreview +import com.maxrave.simpmusic.expect.ui.DesktopMiniPlayerClearance import com.maxrave.simpmusic.expect.ui.PlatformBackdrop +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.barBlurStyle @@ -97,6 +99,7 @@ import com.maxrave.simpmusic.ui.icon.VolumeUp import com.maxrave.simpmusic.ui.navigation.destination.library.LibraryDynamicPlaylistDestination import com.maxrave.simpmusic.ui.screen.home.chipStripEdgeFades import com.maxrave.simpmusic.ui.screen.library.LibraryDynamicPlaylistType +import com.maxrave.simpmusic.ui.theme.ArtworkShape import com.maxrave.simpmusic.ui.theme.LocalLiquidGlassEnabled import com.maxrave.simpmusic.ui.theme.typo import com.maxrave.simpmusic.viewModel.LibrarySidebarItem @@ -276,7 +279,7 @@ fun DesktopSidebar( Box( Modifier .size(48.dp) - .clip(RoundedCornerShape(8.dp)) + .clip(ArtworkShape) .background(MaterialTheme.colorScheme.surfaceContainerHighest), contentAlignment = Alignment.Center, ) { collection.icon() } @@ -298,6 +301,10 @@ fun DesktopSidebar( } item { Spacer(Modifier.height(8.dp)) } } + VerticalScrollBar( + scrollState = listState, + modifier = Modifier.padding(top = with(LocalDensity.current) { headerHeightPx.toDp() }, bottom = DesktopMiniPlayerClearance), + ) Box( Modifier .fillMaxWidth() @@ -701,7 +708,7 @@ private fun SidebarLibraryRow( @Composable private fun SidebarCover(item: LibrarySidebarItem) { - val shape = if (item.kind == LibrarySidebarKind.ARTIST) CircleShape else RoundedCornerShape(8.dp) + val shape = if (item.kind == LibrarySidebarKind.ARTIST) CircleShape else ArtworkShape if (item.thumbnail.isNullOrEmpty()) { // A local playlist with no artwork: the gradient its title tile has in the Library grid, // without the title and badge, which that tile sizes for 150dp and which cannot be read at 48. diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/FiveImagesComponent.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/FiveImagesComponent.kt index b86290d1aa..4bf69637e1 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/FiveImagesComponent.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/FiveImagesComponent.kt @@ -15,7 +15,6 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.wrapContentHeight -import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment @@ -32,6 +31,7 @@ import coil3.request.CachePolicy import coil3.request.ImageRequest import coil3.request.crossfade import com.maxrave.simpmusic.extension.artworkScrimBrush +import com.maxrave.simpmusic.ui.theme.ArtworkShape import com.maxrave.simpmusic.ui.theme.typo /** @@ -51,7 +51,7 @@ fun FiveImagesComponent( modifier: Modifier, images: List, landscape: Boolean = false, - shape: Shape = RoundedCornerShape(12.dp), + shape: Shape = ArtworkShape, ) { if (images.isEmpty()) return // Rounded on the OUTSIDE of the block only. The tiles stay flush with each other on purpose — diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/FullWidthItems.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/FullWidthItems.kt index e0d3c4b071..f79e6b26ff 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/FullWidthItems.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/FullWidthItems.kt @@ -33,7 +33,6 @@ import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.shape.CircleShape -import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text @@ -87,6 +86,7 @@ import com.maxrave.simpmusic.ui.icon.PushPin import com.maxrave.simpmusic.ui.icon.QueueMusic import com.maxrave.simpmusic.ui.icon.SimpIcons import com.maxrave.simpmusic.ui.icon.SkipNext +import com.maxrave.simpmusic.ui.theme.ArtworkShape import com.maxrave.simpmusic.ui.theme.LocalForceDarkText import com.maxrave.simpmusic.ui.theme.seed import com.maxrave.simpmusic.ui.theme.typo @@ -296,7 +296,7 @@ fun SongFullWidthItems( modifier = Modifier .fillMaxSize() - .clip(RoundedCornerShape(4.dp)), + .clip(ArtworkShape), ) } else { Text( @@ -459,7 +459,7 @@ fun SuggestItems( Modifier .wrapContentHeight() .fillMaxWidth() - .clip(RoundedCornerShape(4.dp)), + .clip(ArtworkShape), ) } } @@ -616,7 +616,7 @@ fun PlaylistFullWidthItems( modifier = Modifier .fillMaxSize() - .clip(RoundedCornerShape(4.dp)), + .clip(ArtworkShape), ) } Column( diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/FullscreenLyricsContent.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/FullscreenLyricsContent.kt index 430e0d5e1f..9be0c6fa1a 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/FullscreenLyricsContent.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/FullscreenLyricsContent.kt @@ -120,6 +120,7 @@ import com.maxrave.simpmusic.ui.screen.player.content.NowPlayingTrackInfoRow import com.maxrave.simpmusic.ui.screen.player.content.SpotifyPlaybackControls import com.maxrave.simpmusic.ui.screen.player.content.applemusic.AppleMusicPlaybackControls import com.maxrave.simpmusic.ui.screen.player.content.applemusic.rememberAppleMusicTypography +import com.maxrave.simpmusic.ui.theme.ArtworkShape import com.maxrave.simpmusic.ui.theme.LocalLiquidGlassEnabled import com.maxrave.simpmusic.ui.theme.seed import com.maxrave.simpmusic.ui.theme.typo @@ -363,7 +364,7 @@ fun FullscreenLyricsContent( modifier = Modifier .size(45.dp) - .clip(RoundedCornerShape(8.dp)), + .clip(ArtworkShape), ) Spacer(modifier = Modifier.width(12.dp)) @@ -893,7 +894,7 @@ private fun FullscreenLyricsLandscape( Modifier .padding(horizontal = 20.dp) .size(artworkSize) - .clip(RoundedCornerShape(12.dp)), + .clip(ArtworkShape), ) Spacer(modifier = Modifier.height(20.dp)) when (nowPlayingStyle) { diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/GridLibraryPlaylist.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/GridLibraryPlaylist.kt index f42ee6d025..21c3dece1a 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/GridLibraryPlaylist.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/GridLibraryPlaylist.kt @@ -52,6 +52,8 @@ import com.maxrave.domain.data.type.MonthlyRecapItem import com.maxrave.domain.data.type.PlaylistType import com.maxrave.domain.utils.LocalResource import com.maxrave.logger.Logger +import com.maxrave.simpmusic.expect.ui.DesktopMiniPlayerClearance +import com.maxrave.simpmusic.expect.ui.VerticalScrollBar import com.maxrave.simpmusic.extension.angledGradientBackground import com.maxrave.simpmusic.extension.isScrollingUp import com.maxrave.simpmusic.ui.icon.Add @@ -323,6 +325,10 @@ internal inline fun GridLibraryPlaylist( EndOfPage() } } + VerticalScrollBar( + scrollState = state, + modifier = Modifier.padding(top = contentPadding.calculateTopPadding(), bottom = DesktopMiniPlayerClearance), + ) } else if (data is LocalResource.Loading) { CenterLoadingBox( Modifier.fillMaxSize(), diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/HomeSectionStyles.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/HomeSectionStyles.kt index 2e427d6fc5..82a7cd379a 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/HomeSectionStyles.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/HomeSectionStyles.kt @@ -148,6 +148,8 @@ fun HomeDiscoverSection( ), ) // The scrim is dark in either theme, so the text takes the app's force-dark styles. + // Both colours are named: force-dark typo() paints headlineMedium and bodyMedium in its + // #A8A8A8 body grey, which sinks into the scrim over a bright sleeve. ForceDarkContent { Column( Modifier @@ -158,6 +160,7 @@ fun HomeDiscoverSection( text = song.title, // The size of Home's section titles (HomeSectionHeader). style = typo().headlineMedium, + color = MaterialTheme.colorScheme.onSurface, maxLines = 2, overflow = TextOverflow.Ellipsis, ) @@ -171,6 +174,7 @@ fun HomeDiscoverSection( song.album?.name?.takeIf { it.isNotBlank() }, ).joinToString(" • "), style = typo().bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, ) diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/LibraryItem.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/LibraryItem.kt index 968c3b243d..302f608a10 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/LibraryItem.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/LibraryItem.kt @@ -20,7 +20,6 @@ import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState -import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text @@ -63,6 +62,7 @@ import com.maxrave.simpmusic.ui.navigation.destination.list.ArtistDestination import com.maxrave.simpmusic.ui.navigation.destination.list.LocalPlaylistDestination import com.maxrave.simpmusic.ui.navigation.destination.list.PlaylistDestination import com.maxrave.simpmusic.ui.navigation.destination.list.PodcastDestination +import com.maxrave.simpmusic.ui.theme.ArtworkShape import com.maxrave.simpmusic.ui.theme.typo import com.maxrave.simpmusic.viewModel.LibraryViewModel import com.maxrave.simpmusic.viewModel.SharedViewModel @@ -290,7 +290,7 @@ fun LibraryItem( Modifier .fillMaxSize() .clip( - RoundedCornerShape(8.dp), + ArtworkShape, ), ) Column( diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/LibraryTilingBox.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/LibraryTilingBox.kt index 4cb7bb179b..73dcb5e2ec 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/LibraryTilingBox.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/LibraryTilingBox.kt @@ -42,6 +42,7 @@ import com.maxrave.simpmusic.getPlatform import com.maxrave.simpmusic.ui.component.taste.libraryCardColor import com.maxrave.simpmusic.ui.navigation.destination.library.LibraryDynamicPlaylistDestination import com.maxrave.simpmusic.ui.screen.library.LibraryDynamicPlaylistType +import com.maxrave.simpmusic.ui.theme.ArtworkShape import com.maxrave.simpmusic.ui.theme.typo import org.jetbrains.compose.resources.StringResource import org.jetbrains.compose.resources.pluralStringResource @@ -257,7 +258,7 @@ private fun SleeveFan( ) { Box(modifier, contentAlignment = Alignment.Center) { if (thumbnails == null) return@Box - val shape = if (round) CircleShape else RoundedCornerShape(8.dp) + val shape = if (round) CircleShape else ArtworkShape val covers = thumbnails.take(slots) val count = if (covers.isEmpty()) slots else covers.size for (i in 0 until count) { diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/ModalBottomSheet.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/ModalBottomSheet.kt index 84c400179e..15449a0d8d 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/ModalBottomSheet.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/ModalBottomSheet.kt @@ -139,6 +139,7 @@ import com.maxrave.domain.utils.toListName import com.maxrave.logger.Logger import com.maxrave.simpmusic.expect.copyToClipboard import com.maxrave.simpmusic.expect.shareUrl +import com.maxrave.simpmusic.expect.ui.VerticalScrollBar import com.maxrave.simpmusic.expect.ui.persistPickedImage import com.maxrave.simpmusic.expect.ui.photoPickerResult import com.maxrave.simpmusic.extension.displayNameRes @@ -180,6 +181,7 @@ import com.maxrave.simpmusic.ui.icon.Tune import com.maxrave.simpmusic.ui.icon.Update import com.maxrave.simpmusic.ui.navigation.destination.list.AlbumDestination import com.maxrave.simpmusic.ui.navigation.destination.list.ArtistDestination +import com.maxrave.simpmusic.ui.theme.ArtworkShape import com.maxrave.simpmusic.ui.theme.seed import com.maxrave.simpmusic.ui.theme.typo import com.maxrave.simpmusic.viewModel.NowPlayingBottomSheetUIEvent @@ -1178,104 +1180,111 @@ fun QueueBottomSheet( "${track.videoId}#$occurrence" } } - LazyColumn( - horizontalAlignment = Alignment.Start, - state = lazyListState, - modifier = - Modifier - .pointerInput(Unit) { - detectDragGesturesAfterLongPress( - onDrag = { change, offset -> - Logger.d("QueueBottomSheet", "onDrag $offset") - change.consume() - dragDropState.onDrag(offset = offset) - - if (overscrollJob?.isActive == true) { - return@detectDragGesturesAfterLongPress - } + // Wraps the list so the Desktop scrollbar can lie over its right edge; sized by the list alone. + Box { + LazyColumn( + horizontalAlignment = Alignment.Start, + state = lazyListState, + modifier = + Modifier + .pointerInput(Unit) { + detectDragGesturesAfterLongPress( + onDrag = { change, offset -> + Logger.d("QueueBottomSheet", "onDrag $offset") + change.consume() + dragDropState.onDrag(offset = offset) + + if (overscrollJob?.isActive == true) { + return@detectDragGesturesAfterLongPress + } - dragDropState - .checkForOverScroll() - .takeIf { it != 0f } - ?.let { - overscrollJob = - coroutineScope.launch { - dragDropState.state.animateScrollBy( - it * 1.3f, - tween(easing = FastOutLinearInEasing), - ) - } + dragDropState + .checkForOverScroll() + .takeIf { it != 0f } + ?.let { + overscrollJob = + coroutineScope.launch { + dragDropState.state.animateScrollBy( + it * 1.3f, + tween(easing = FastOutLinearInEasing), + ) + } + } + ?: run { overscrollJob?.cancel() } + }, + onDragStart = { offset -> + Logger.d("QueueBottomSheet", "onDragStart $offset") + dragDropState.onDragStart(offset) + }, + onDragEnd = { + Logger.d("QueueBottomSheet", "onDragEnd") + dragDropState.onDragInterrupted(true) + overscrollJob?.cancel() + }, + onDragCancel = { + Logger.d("QueueBottomSheet", "onDragCancel") + dragDropState.onDragInterrupted() + overscrollJob?.cancel() + }, + ) + }, + ) { + itemsIndexed( + queue, + // Keyed by the track, NOT by its position: a radio queue drops played + // tracks off the front, and a position-based key changes for every row + // when that happens, so the list loses its scroll anchor and jumps under + // the user. The occurrence number keeps the key unique when a radio + // repeats a song. + key = { i, t -> queueRowKeys.getOrElse(i) { t.videoId } }, + ) { index, track -> + if (index != -1) { + DraggableItem( + dragDropState = dragDropState, + index = index, + modifier = Modifier, + ) { _ -> + SongFullWidthItems( + track = track, + isPlaying = track.videoId == songEntity?.videoId, + modifier = + Modifier + .fillMaxWidth(), + onClickListener = { videoId -> + if (videoId == track.videoId) { + musicServiceHandler.playMediaItemInMediaSource(index) } - ?: run { overscrollJob?.cancel() } - }, - onDragStart = { offset -> - Logger.d("QueueBottomSheet", "onDragStart $offset") - dragDropState.onDragStart(offset) - }, - onDragEnd = { - Logger.d("QueueBottomSheet", "onDragEnd") - dragDropState.onDragInterrupted(true) - overscrollJob?.cancel() - }, - onDragCancel = { - Logger.d("QueueBottomSheet", "onDragCancel") - dragDropState.onDragInterrupted() - overscrollJob?.cancel() - }, - ) - }, - ) { - itemsIndexed( - queue, - // Keyed by the track, NOT by its position: a radio queue drops played - // tracks off the front, and a position-based key changes for every row - // when that happens, so the list loses its scroll anchor and jumps under - // the user. The occurrence number keeps the key unique when a radio - // repeats a song. - key = { i, t -> queueRowKeys.getOrElse(i) { t.videoId } }, - ) { index, track -> - if (index != -1) { - DraggableItem( - dragDropState = dragDropState, - index = index, - modifier = Modifier, - ) { _ -> - SongFullWidthItems( - track = track, - isPlaying = track.videoId == songEntity?.videoId, + }, + onMoreClickListener = { + showQueueItemBottomSheet(index) + }, + onAddToQueue = { + sharedViewModel.addListToQueue( + arrayListOf(track), + ) + }, + ) + } + } + } + item { + if (loadMoreState == QueueData.StateSource.STATE_INITIALIZING) { + CenterLoadingBox( modifier = Modifier - .fillMaxWidth(), - onClickListener = { videoId -> - if (videoId == track.videoId) { - musicServiceHandler.playMediaItemInMediaSource(index) - } - }, - onMoreClickListener = { - showQueueItemBottomSheet(index) - }, - onAddToQueue = { - sharedViewModel.addListToQueue( - arrayListOf(track), - ) - }, + .fillMaxWidth() + .height(80.dp), ) } } - } - item { - if (loadMoreState == QueueData.StateSource.STATE_INITIALIZING) { - CenterLoadingBox( - modifier = - Modifier - .fillMaxWidth() - .height(80.dp), - ) + item { + EndOfPage() } } - item { - EndOfPage() - } + VerticalScrollBar( + scrollState = lazyListState, + modifier = Modifier.matchParentSize(), + ) } } } @@ -1654,7 +1663,7 @@ fun NowPlayingBottomSheet( Modifier .align(Alignment.CenterVertically) .size(44.dp) - .clip(RoundedCornerShape(6.dp)), + .clip(ArtworkShape), ) Spacer(modifier = Modifier.width(12.dp)) Column(verticalArrangement = Arrangement.spacedBy(1.dp)) { diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/MoodCategoryCard.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/MoodCategoryCard.kt index 4f7e8bed94..6a3f15da10 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/MoodCategoryCard.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/MoodCategoryCard.kt @@ -24,6 +24,7 @@ import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp import coil3.compose.AsyncImage import com.maxrave.simpmusic.extension.angledGradientBackground +import com.maxrave.simpmusic.ui.theme.ArtworkShape import com.maxrave.simpmusic.ui.theme.typo import org.jetbrains.compose.resources.painterResource import simpmusic.composeapp.generated.resources.Res @@ -93,7 +94,7 @@ fun MoodCategoryCard( .offset(x = 8.dp, y = 12.dp) .size(64.dp) .rotate(25f) - .clip(RoundedCornerShape(2.dp)), + .clip(ArtworkShape), ) } Text( diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/WrappedEntryCard.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/WrappedEntryCard.kt index abdd932b6c..d82092798b 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/WrappedEntryCard.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/component/WrappedEntryCard.kt @@ -33,6 +33,7 @@ import com.maxrave.simpmusic.ui.icon.PlayArrow import com.maxrave.simpmusic.ui.icon.SimpIcons import com.maxrave.simpmusic.ui.screen.home.wrapped.formatCount import com.maxrave.simpmusic.ui.screen.home.wrapped.wholeMinutes +import com.maxrave.simpmusic.ui.theme.ArtworkShape import com.maxrave.simpmusic.ui.theme.typo import com.maxrave.simpmusic.viewModel.WrappedYear import org.jetbrains.compose.resources.stringResource @@ -112,7 +113,7 @@ internal fun EntryCard( verticalAlignment = Alignment.CenterVertically, ) { Box( - modifier = Modifier.size(COVER_SIZE).clip(RoundedCornerShape(COVER_RADIUS)), + modifier = Modifier.size(COVER_SIZE).clip(ArtworkShape), content = picture, ) Spacer(Modifier.width(14.dp)) @@ -175,8 +176,6 @@ private val GUTTER = 14.dp /** Row height, not banner height — the whole card lands near 96dp with the gutter. */ private val COVER_SIZE = 68.dp -private val COVER_RADIUS = 8.dp - private val CARD_RADIUS = 12.dp private val DISC_SIZE = 44.dp diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/MiniPlayer.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/MiniPlayer.kt index 8123661417..50acc48db2 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/MiniPlayer.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/MiniPlayer.kt @@ -135,6 +135,7 @@ import com.maxrave.simpmusic.ui.icon.SimpIcons import com.maxrave.simpmusic.ui.icon.VolumeOff import com.maxrave.simpmusic.ui.icon.VolumeUp import com.maxrave.simpmusic.ui.screen.player.content.toAudioQualityLabel +import com.maxrave.simpmusic.ui.theme.ArtworkShape import com.maxrave.simpmusic.ui.theme.LocalIsDarkTheme import com.maxrave.simpmusic.ui.theme.typo import com.maxrave.simpmusic.viewModel.SharedViewModel @@ -422,7 +423,7 @@ fun MiniPlayer( modifier = Modifier .size(if (isFlat) 26.dp else 40.dp) - .clip(if (isFlat) CircleShape else RoundedCornerShape(4.dp)), + .clip(if (isFlat) CircleShape else ArtworkShape), ) } Spacer(modifier = Modifier.width(10.dp)) @@ -757,7 +758,7 @@ fun MiniPlayer( modifier = Modifier .size(32.dp) - .clip(RoundedCornerShape(6.dp)) + .clip(ArtworkShape) .hoverable(artworkInteraction), contentAlignment = Alignment.Center, ) { diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/HomeScreen.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/HomeScreen.kt index 6ed66f6042..c49d66c0b0 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/HomeScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/HomeScreen.kt @@ -120,7 +120,9 @@ import com.maxrave.domain.utils.toTrack import com.maxrave.logger.Logger import com.maxrave.simpmusic.Platform import com.maxrave.simpmusic.expect.openUrl +import com.maxrave.simpmusic.expect.ui.DesktopMiniPlayerClearance import com.maxrave.simpmusic.expect.ui.HorizontalScrollBar +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 @@ -171,6 +173,7 @@ import com.maxrave.simpmusic.ui.navigation.destination.list.PodcastDestination import com.maxrave.simpmusic.ui.navigation.destination.list.PlaylistDestination import com.maxrave.simpmusic.ui.navigation.destination.login.LoginDestination import com.maxrave.simpmusic.ui.screen.library.LibraryDynamicPlaylistType +import com.maxrave.simpmusic.ui.theme.ArtworkShape import com.maxrave.simpmusic.ui.theme.LocalLiquidGlassEnabled import com.maxrave.simpmusic.ui.theme.desktopPanelDark import com.maxrave.simpmusic.ui.theme.typo @@ -860,7 +863,9 @@ fun HomeScreen( ), ) } - Spacer(modifier = Modifier.height(8.dp)) + // Android drops the 8dp over each section's title: the list's own 8dp + // spacing already separates it from the shelf above. + if (getPlatform() != Platform.Android) Spacer(modifier = Modifier.height(8.dp)) if (item.title == stringResource(Res.string.quick_picks)) { AnimatedVisibility( visible = @@ -1022,6 +1027,14 @@ fun HomeScreen( EndOfPage() } } + VerticalScrollBar( + scrollState = scrollState, + modifier = + Modifier.padding( + top = with(LocalDensity.current) { topAppBarHeightPx.toDp() }, + bottom = DesktopMiniPlayerClearance, + ), + ) } else { Column { Spacer( @@ -1376,9 +1389,12 @@ fun QuickPicks( ) } + // Quick picks draws its own header, and its 8dp around the block and 5dp around the title are + // gaps no other shelf has: on Android they stood it 8dp further off the shelf above than the rest. + val compact = getPlatform() == Platform.Android Column( Modifier - .padding(vertical = 8.dp) + .padding(vertical = if (compact) 0.dp else 8.dp) .onGloballyPositioned { coordinates -> with(density) { widthDp = (coordinates.size.width).toDp() @@ -1399,7 +1415,7 @@ fun QuickPicks( modifier = Modifier .fillMaxWidth() - .padding(vertical = 5.dp), + .padding(vertical = if (compact) 0.dp else 5.dp), ) } if (homeItem.playAllEndpoint != null) { @@ -1411,7 +1427,11 @@ fun QuickPicks( } LazyHorizontalGrid( rows = GridCells.Fixed(4), - modifier = Modifier.height(256.dp).mouseDragScroll(lazyListState, snapperFlingBehavior), + // Four 64dp rows; 56dp on Android, where Home packs tighter (QuickPicksItem pads to match). + modifier = + Modifier + .height(if (compact) 224.dp else 256.dp) + .mouseDragScroll(lazyListState, snapperFlingBehavior), state = lazyListState, flingBehavior = snapperFlingBehavior, ) { @@ -1656,7 +1676,7 @@ fun ChartData( onClick = { navController.navigate(PodcastDestination(podcastId = data.browseId)) }, data = data, widthDp = if (isPortrait) gridWidthDp else minOf(gridWidthDp, LandscapeGridItemMaxWidth), - thumbnailShape = RoundedCornerShape(8.dp), + thumbnailShape = ArtworkShape, subtitle = data.subscribers, ) } 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 d9548f23d6..6e0c78e0f3 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 @@ -78,7 +78,9 @@ 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.expect.shareUrl +import com.maxrave.simpmusic.expect.ui.DesktopMiniPlayerClearance import com.maxrave.simpmusic.expect.ui.PlatformBackdrop +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 @@ -247,44 +249,57 @@ fun ListenTogetherScreen( Row(modifier = Modifier.fillMaxSize().padding(innerPadding)) { // The identity side scrolls separately and normally does not move at all: the room // code is what people read aloud, so it stays on screen while the list scrolls. - Column( - modifier = - Modifier - .weight(0.42f) - .fillMaxHeight() - .verticalScroll(rememberScrollState()) - .padding(start = 24.dp, end = 28.dp, top = 14.dp, bottom = 24.dp), - verticalArrangement = Arrangement.spacedBy(24.dp), - ) { - // Reserves the strip the floating back button is drawn over — it is a sibling of - // this column and takes part in no measurement, so nothing else pushes down for it. - Spacer(Modifier.height(BACK_BUTTON_STRIP)) - TitleBlock(inRoom = state.inRoom) - ConnectionLine(state.connection, viewModel::connect, viewModel::disconnect) - AnimatedVisibility(visible = state.inRoom) { - RoomCodePoster(state, copyCode, shareCode) + val identityScroll = rememberScrollState() + Box(Modifier.weight(0.42f).fillMaxHeight()) { + Column( + modifier = + Modifier + .fillMaxSize() + .verticalScroll(identityScroll) + .padding(start = 24.dp, end = 28.dp, top = 14.dp, bottom = 24.dp), + verticalArrangement = Arrangement.spacedBy(24.dp), + ) { + // Reserves the strip the floating back button is drawn over — it is a sibling of + // this column and takes part in no measurement, so nothing else pushes down for it. + Spacer(Modifier.height(BACK_BUTTON_STRIP)) + TitleBlock(inRoom = state.inRoom) + ConnectionLine(state.connection, viewModel::connect, viewModel::disconnect) + AnimatedVisibility(visible = state.inRoom) { + RoomCodePoster(state, copyCode, shareCode) + } } + VerticalScrollBar( + scrollState = identityScroll, + modifier = Modifier.padding(bottom = DesktopMiniPlayerClearance), + ) } - Column( - modifier = - Modifier - .weight(0.58f) - .fillMaxHeight() - .verticalScroll(rememberScrollState()) - .padding(start = 4.dp, end = 40.dp, top = 30.dp) - .animateContentSize(), - verticalArrangement = Arrangement.spacedBy(16.dp), - ) { - WorkArea(state, displayName, codeInput, viewModel, { managing = it }, openSettings) + val workScroll = rememberScrollState() + Box(Modifier.weight(0.58f).fillMaxHeight()) { + Column( + modifier = + Modifier + .fillMaxSize() + .verticalScroll(workScroll) + .padding(start = 4.dp, end = 40.dp, top = 30.dp) + .animateContentSize(), + verticalArrangement = Arrangement.spacedBy(16.dp), + ) { + WorkArea(state, displayName, codeInput, viewModel, { managing = it }, openSettings) + } + VerticalScrollBar( + scrollState = workScroll, + modifier = Modifier.padding(bottom = DesktopMiniPlayerClearance), + ) } } } else { + val pageScroll = rememberScrollState() Column( modifier = Modifier .fillMaxSize() - .verticalScroll(rememberScrollState()) + .verticalScroll(pageScroll) .padding(innerPadding) .padding(horizontal = 24.dp, vertical = 14.dp) .animateContentSize(), @@ -298,6 +313,10 @@ fun ListenTogetherScreen( } WorkArea(state, displayName, codeInput, viewModel, { managing = it }, openSettings) } + VerticalScrollBar( + scrollState = pageScroll, + modifier = Modifier.padding(top = innerPadding.calculateTopPadding(), bottom = DesktopMiniPlayerClearance), + ) } BackButton(backdrop) { navController.navigateUp() } diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/ListenTogetherSettingsScreen.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/ListenTogetherSettingsScreen.kt index c5a8c16364..3c1ae8a7d1 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/ListenTogetherSettingsScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/ListenTogetherSettingsScreen.kt @@ -46,6 +46,8 @@ import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavController +import com.maxrave.simpmusic.expect.ui.DesktopMiniPlayerClearance +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 @@ -134,11 +136,12 @@ fun ListenTogetherSettingsScreen( } } + val scrollState = rememberScrollState() Column( modifier = Modifier .fillMaxSize() - .verticalScroll(rememberScrollState()) + .verticalScroll(scrollState) .padding(innerPadding), horizontalAlignment = Alignment.CenterHorizontally, ) { @@ -282,6 +285,10 @@ fun ListenTogetherSettingsScreen( EndOfPage() } } + VerticalScrollBar( + scrollState = scrollState, + modifier = Modifier.padding(top = innerPadding.calculateTopPadding(), bottom = DesktopMiniPlayerClearance), + ) // Floats over the strip the header row reserves — a sibling of both the scroll column and // the backdrop source, exactly the arrangement the main Listen Together page uses. diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/MoodScreen.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/MoodScreen.kt index e719621f2c..bb1351d7c3 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/MoodScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/MoodScreen.kt @@ -3,8 +3,10 @@ package com.maxrave.simpmusic.ui.screen.home import androidx.compose.animation.AnimatedVisibility import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Text @@ -14,6 +16,8 @@ import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavController +import com.maxrave.simpmusic.expect.ui.DesktopMiniPlayerClearance +import com.maxrave.simpmusic.expect.ui.VerticalScrollBar import com.maxrave.simpmusic.ui.component.CenterLoadingBox import com.maxrave.simpmusic.ui.component.EndOfPage import com.maxrave.simpmusic.ui.component.MoodAndGenresContentItem @@ -59,7 +63,9 @@ fun MoodScreen( }, ) AnimatedVisibility(visible = !loading) { + val listState = rememberLazyListState() LazyColumn( + state = listState, modifier = Modifier.fillMaxSize(), ) { items(moodData?.items ?: emptyList()) { item -> @@ -72,6 +78,10 @@ fun MoodScreen( EndOfPage() } } + VerticalScrollBar( + scrollState = listState, + modifier = Modifier.padding(bottom = DesktopMiniPlayerClearance), + ) } AnimatedVisibility(visible = loading) { CenterLoadingBox( diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/NotificationScreen.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/NotificationScreen.kt index e40c8b4942..d42db0eb6a 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/NotificationScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/NotificationScreen.kt @@ -29,7 +29,6 @@ import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.shape.CircleShape -import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme @@ -62,6 +61,8 @@ import coil3.request.CachePolicy import coil3.request.ImageRequest import coil3.request.crossfade import com.maxrave.domain.data.entities.NotificationEntity +import com.maxrave.simpmusic.expect.ui.DesktopMiniPlayerClearance +import com.maxrave.simpmusic.expect.ui.VerticalScrollBar import com.maxrave.simpmusic.extension.barBlurStyle import com.maxrave.simpmusic.extension.formatTimeAgo import com.maxrave.simpmusic.extension.mouseDragScroll @@ -75,6 +76,7 @@ import com.maxrave.simpmusic.ui.icon.RssFeed import com.maxrave.simpmusic.ui.icon.SimpIcons import com.maxrave.simpmusic.ui.navigation.destination.list.AlbumDestination import com.maxrave.simpmusic.ui.navigation.destination.list.ArtistDestination +import com.maxrave.simpmusic.ui.theme.ArtworkShape import com.maxrave.simpmusic.ui.theme.typo import com.maxrave.simpmusic.viewModel.NotificationViewModel import dev.chrisbanes.haze.HazeInput @@ -152,6 +154,10 @@ fun NotificationScreen( EndOfPage() } } + VerticalScrollBar( + scrollState = listState, + modifier = Modifier.padding(top = topAppBarHeight, bottom = DesktopMiniPlayerClearance), + ) } else { Box( Modifier.fillMaxSize(), @@ -407,7 +413,7 @@ fun ItemAlbumNotification( .align(Alignment.CenterHorizontally) .size(150.dp) .clip( - RoundedCornerShape(10), + ArtworkShape, ), ) Text( diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/SettingScreen.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/SettingScreen.kt index c6ea7e44fe..2c17b7c0cd 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/SettingScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/SettingScreen.kt @@ -111,8 +111,10 @@ import com.maxrave.domain.repository.ImportProgress import com.maxrave.domain.utils.LocalResource import com.maxrave.logger.Logger import com.maxrave.simpmusic.Platform +import com.maxrave.simpmusic.expect.ui.DesktopMiniPlayerClearance import com.maxrave.simpmusic.expect.ui.LibrarySyncDialog import com.maxrave.simpmusic.expect.ui.LoginSyncDialog +import com.maxrave.simpmusic.expect.ui.VerticalScrollBar import com.maxrave.simpmusic.expect.ui.syncedAgo import com.maxrave.simpmusic.expect.ui.filePickerResult import com.maxrave.simpmusic.expect.ui.fileSaverResult @@ -2901,6 +2903,10 @@ fun SettingScreen( EndOfPage() } } + VerticalScrollBar( + scrollState = settingListState, + modifier = Modifier.padding(top = innerPadding.calculateTopPadding(), bottom = DesktopMiniPlayerClearance), + ) importState?.let { progress -> ImportProgressDialog( progress = progress, diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/analytics/AnalyticsScreen.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/analytics/AnalyticsScreen.kt index ba50f6c6d8..7951861dfb 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/analytics/AnalyticsScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/home/analytics/AnalyticsScreen.kt @@ -19,6 +19,7 @@ import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.windowInsetsPadding import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.DropdownMenu @@ -46,8 +47,11 @@ import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.Dp +import com.maxrave.simpmusic.expect.ui.DesktopMiniPlayerClearance +import com.maxrave.simpmusic.expect.ui.VerticalScrollBar import com.maxrave.simpmusic.extension.LeftToRight import com.maxrave.simpmusic.ui.icon.ArrowForwardIos +import com.maxrave.simpmusic.ui.theme.ArtworkShape import simpmusic.composeapp.generated.resources.analytics_avg_per_day import simpmusic.composeapp.generated.resources.analytics_busiest_day import simpmusic.composeapp.generated.resources.analytics_by_decade @@ -299,7 +303,9 @@ fun AnalyticsScreen( .fillMaxSize() .background(pageBackground), ) { + val listState = rememberLazyListState() LazyColumn( + state = listState, modifier = Modifier .fillMaxSize() @@ -433,6 +439,10 @@ fun AnalyticsScreen( item { EndOfPage() } } + VerticalScrollBar( + scrollState = listState, + modifier = Modifier.padding(bottom = DesktopMiniPlayerClearance), + ) if (selectionState.isActive) { SongSelectionTopAppBar( @@ -793,7 +803,7 @@ private fun LandscapeHeader( ArtworkImage( url = topTrack.second.thumbnails, onBitmap = onBitmap, - modifier = Modifier.size(LANDSCAPE_ARTWORK).clip(RoundedCornerShape(8.dp)), + modifier = Modifier.size(LANDSCAPE_ARTWORK).clip(ArtworkShape), ) Column(modifier = Modifier.weight(1f)) { Text( diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/library/LibraryDynamicPlaylistScreen.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/library/LibraryDynamicPlaylistScreen.kt index b572f01306..4600d0af0b 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/library/LibraryDynamicPlaylistScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/library/LibraryDynamicPlaylistScreen.kt @@ -15,6 +15,7 @@ import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.wrapContentWidth import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material3.MaterialTheme import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon @@ -49,6 +50,8 @@ import com.maxrave.domain.mediaservice.handler.QueueData import com.maxrave.domain.utils.LocalResource import com.maxrave.domain.utils.toArrayListTrack import com.maxrave.domain.utils.toTrack +import com.maxrave.simpmusic.expect.ui.DesktopMiniPlayerClearance +import com.maxrave.simpmusic.expect.ui.VerticalScrollBar import com.maxrave.simpmusic.extension.getStringBlocking import com.maxrave.simpmusic.extension.ultraThinBarStyle import com.maxrave.simpmusic.ui.component.SearchBarExit @@ -205,7 +208,9 @@ fun LibraryDynamicPlaylistScreen( ?: emptyList() } + val listState = rememberLazyListState() LazyColumn( + state = listState, modifier = Modifier.hazeSource(hazeState), contentPadding = innerPadding, ) { @@ -463,6 +468,10 @@ fun LibraryDynamicPlaylistScreen( EndOfPage() } } + VerticalScrollBar( + scrollState = listState, + modifier = Modifier.padding(top = innerPadding.calculateTopPadding(), bottom = DesktopMiniPlayerClearance), + ) if (showSelectionSheet) { val selectedIds = selectionState.selected.toList() val isDownloadedList = LibraryDynamicPlaylistType.toType(type) == LibraryDynamicPlaylistType.Downloaded diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/library/LibraryScreen.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/library/LibraryScreen.kt index 6380241e94..872df955ad 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/library/LibraryScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/library/LibraryScreen.kt @@ -59,6 +59,8 @@ import com.maxrave.domain.data.model.taste.TasteProfile import com.maxrave.domain.utils.LocalResource import com.maxrave.logger.Logger import com.maxrave.simpmusic.Platform +import com.maxrave.simpmusic.expect.ui.DesktopMiniPlayerClearance +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.copy @@ -332,6 +334,10 @@ fun LibraryScreen( EndOfPage() } } + VerticalScrollBar( + scrollState = state, + modifier = Modifier.padding(top = topAppBarHeight, bottom = DesktopMiniPlayerClearance), + ) } } diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/library/LocalPlaylistScreen.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/library/LocalPlaylistScreen.kt index 6caeb70514..dc8dd5fee6 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/library/LocalPlaylistScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/library/LocalPlaylistScreen.kt @@ -49,6 +49,8 @@ import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.AlertDialog import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.HorizontalDivider +import com.maxrave.simpmusic.expect.ui.DesktopMiniPlayerClearance +import com.maxrave.simpmusic.expect.ui.VerticalScrollBar import com.maxrave.simpmusic.extension.barBlurStyle import com.maxrave.simpmusic.ui.component.DownloadingIndicator import com.maxrave.simpmusic.ui.icon.Search @@ -160,6 +162,7 @@ import com.maxrave.simpmusic.ui.icon.Shuffle import com.maxrave.simpmusic.ui.icon.SimpIcons import com.maxrave.simpmusic.ui.icon.Sort import com.maxrave.simpmusic.ui.icon.TipsAndUpdates +import com.maxrave.simpmusic.ui.theme.ArtworkShape import com.maxrave.simpmusic.ui.theme.LocalIsDarkTheme import com.maxrave.simpmusic.ui.theme.seed import com.maxrave.simpmusic.ui.theme.typo @@ -752,7 +755,7 @@ fun LocalPlaylistScreen( modifier = Modifier .size(280.dp) - .clip(RoundedCornerShape(8.dp)), + .clip(ArtworkShape), ) Column( modifier = Modifier.weight(1f), @@ -1424,6 +1427,10 @@ fun LocalPlaylistScreen( EndOfPage() } } + VerticalScrollBar( + scrollState = lazyState, + modifier = Modifier.padding(bottom = DesktopMiniPlayerClearance), + ) AnimatedVisibility( visible = selectionState.isActive, enter = fadeIn() + slideInVertically(), diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/login/DiscordOAuthLoginScreen.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/login/DiscordOAuthLoginScreen.kt index fe5be0b5f8..f5170b064b 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/login/DiscordOAuthLoginScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/login/DiscordOAuthLoginScreen.kt @@ -38,6 +38,8 @@ import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavController +import com.maxrave.simpmusic.expect.ui.DesktopMiniPlayerClearance +import com.maxrave.simpmusic.expect.ui.VerticalScrollBar import com.maxrave.simpmusic.ui.component.RippleIconButton import com.maxrave.simpmusic.ui.icon.ArrowBackIosNew import com.maxrave.simpmusic.ui.icon.SimpIcons @@ -112,11 +114,12 @@ fun DiscordOAuthLoginScreen( val busy = state is DiscordLoginState.CompletingLogin Box(modifier = Modifier.fillMaxSize()) { + val scrollState = rememberScrollState() Column( modifier = Modifier .fillMaxSize() - .verticalScroll(rememberScrollState()) + .verticalScroll(scrollState) .padding(horizontal = 24.dp), horizontalAlignment = Alignment.CenterHorizontally, ) { @@ -215,6 +218,10 @@ fun DiscordOAuthLoginScreen( Spacer(Modifier.height(48.dp)) } + VerticalScrollBar( + scrollState = scrollState, + modifier = Modifier.padding(bottom = DesktopMiniPlayerClearance), + ) TopAppBar( modifier = Modifier.align(Alignment.TopCenter), diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/login/LastfmLoginScreen.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/login/LastfmLoginScreen.kt index e6f6d87cb1..47a6dd912d 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/login/LastfmLoginScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/login/LastfmLoginScreen.kt @@ -41,6 +41,8 @@ import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavController +import com.maxrave.simpmusic.expect.ui.DesktopMiniPlayerClearance +import com.maxrave.simpmusic.expect.ui.VerticalScrollBar import com.maxrave.simpmusic.ui.component.RippleIconButton import com.maxrave.simpmusic.ui.icon.ArrowBackIosNew import com.maxrave.simpmusic.ui.icon.SimpIcons @@ -120,11 +122,12 @@ fun LastfmLoginScreen( val busy = state is LastfmLoginState.CompletingLogin Box(modifier = Modifier.fillMaxSize()) { + val scrollState = rememberScrollState() Column( modifier = Modifier .fillMaxSize() - .verticalScroll(rememberScrollState()) + .verticalScroll(scrollState) .padding(horizontal = 24.dp), horizontalAlignment = Alignment.CenterHorizontally, ) { @@ -226,6 +229,10 @@ fun LastfmLoginScreen( Spacer(Modifier.height(48.dp)) } + VerticalScrollBar( + scrollState = scrollState, + modifier = Modifier.padding(bottom = DesktopMiniPlayerClearance), + ) TopAppBar( modifier = Modifier.align(Alignment.TopCenter), diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/login/LogInScreen.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/login/LogInScreen.kt index 4b4ae944d2..43bd5648c7 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/login/LogInScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/login/LogInScreen.kt @@ -12,6 +12,7 @@ import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme @@ -46,6 +47,8 @@ import com.maxrave.domain.repository.BrowserProfile import com.maxrave.domain.repository.BrowserProfileStatus import com.maxrave.logger.Logger import com.maxrave.simpmusic.Platform +import com.maxrave.simpmusic.expect.ui.DesktopMiniPlayerClearance +import com.maxrave.simpmusic.expect.ui.VerticalScrollBar import com.maxrave.simpmusic.getPlatform import com.maxrave.simpmusic.expect.openUrl import com.maxrave.simpmusic.expect.ui.PlatformWebView @@ -308,96 +311,104 @@ internal fun BrowserLoginPanel( ) { val busy = state.loading || state.importingId != null val serviceName = stringResource(if (target == BrowserLoginTarget.YOUTUBE) Res.string.browser_login_youtube else Res.string.spotify) - LazyColumn( - modifier = Modifier.fillMaxSize().padding(horizontal = 16.dp), - contentPadding = PaddingValues(top = 16.dp, bottom = bottomPadding + 24.dp), - ) { - item(key = "description") { - Text( - stringResource(Res.string.browser_login_description, serviceName), - style = typo().bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - if (busy) { - item(key = "progress") { - Row( - Modifier.fillMaxWidth().padding(vertical = 16.dp), - horizontalArrangement = Arrangement.spacedBy(12.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - CircularProgressIndicator(Modifier.size(24.dp)) - Text( - stringResource(if (state.loading) Res.string.loading else Res.string.browser_login_importing), - style = typo().bodyMedium, - color = MaterialTheme.colorScheme.onSurface, - ) + val listState = rememberLazyListState() + Box(Modifier.fillMaxSize()) { + LazyColumn( + state = listState, + modifier = Modifier.fillMaxSize().padding(horizontal = 16.dp), + contentPadding = PaddingValues(top = 16.dp, bottom = bottomPadding + 24.dp), + ) { + item(key = "description") { + Text( + stringResource(Res.string.browser_login_description, serviceName), + style = typo().bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + if (busy) { + item(key = "progress") { + Row( + Modifier.fillMaxWidth().padding(vertical = 16.dp), + horizontalArrangement = Arrangement.spacedBy(12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + CircularProgressIndicator(Modifier.size(24.dp)) + Text( + stringResource(if (state.loading) Res.string.loading else Res.string.browser_login_importing), + style = typo().bodyMedium, + color = MaterialTheme.colorScheme.onSurface, + ) + } } } - } - state.profiles.groupBy { it.browser }.forEach { (browser, profiles) -> - item(key = "browser:$browser") { - SettingGroup(title = browser) { - profiles.forEach { profile -> - val needsFileAccess = state.requiresFileAccess(profile, isMacOS) - val subtitle = when (profile.status) { - BrowserProfileStatus.COOKIES_FOUND -> Res.string.browser_login_found - BrowserProfileStatus.NO_COOKIES -> Res.string.browser_login_missing - BrowserProfileStatus.PERMISSION_REQUIRED -> if (isMacOS) Res.string.browser_login_full_disk_access else Res.string.browser_login_permission - BrowserProfileStatus.UNREADABLE -> Res.string.browser_login_unreadable - BrowserProfileStatus.UNSUPPORTED -> Res.string.browser_login_unsupported - } - SettingItem( - title = profile.name, - subtitle = if (profile.status == BrowserProfileStatus.COOKIES_FOUND || profile.status == BrowserProfileStatus.NO_COOKIES) { - stringResource(subtitle, serviceName) - } else { - stringResource(subtitle) - }, - isEnable = !busy && profile.status != BrowserProfileStatus.UNSUPPORTED, - onClick = { if (needsFileAccess) onOpenFileAccess() else onSelect(profile) }, - otherView = if (needsFileAccess) { - { - TextButton(onClick = onOpenFileAccess, enabled = !busy) { - Text(stringResource(Res.string.browser_login_open_settings), color = LocalContentColor.current) + state.profiles.groupBy { it.browser }.forEach { (browser, profiles) -> + item(key = "browser:$browser") { + SettingGroup(title = browser) { + profiles.forEach { profile -> + val needsFileAccess = state.requiresFileAccess(profile, isMacOS) + val subtitle = when (profile.status) { + BrowserProfileStatus.COOKIES_FOUND -> Res.string.browser_login_found + BrowserProfileStatus.NO_COOKIES -> Res.string.browser_login_missing + BrowserProfileStatus.PERMISSION_REQUIRED -> if (isMacOS) Res.string.browser_login_full_disk_access else Res.string.browser_login_permission + BrowserProfileStatus.UNREADABLE -> Res.string.browser_login_unreadable + BrowserProfileStatus.UNSUPPORTED -> Res.string.browser_login_unsupported + } + SettingItem( + title = profile.name, + subtitle = if (profile.status == BrowserProfileStatus.COOKIES_FOUND || profile.status == BrowserProfileStatus.NO_COOKIES) { + stringResource(subtitle, serviceName) + } else { + stringResource(subtitle) + }, + isEnable = !busy && profile.status != BrowserProfileStatus.UNSUPPORTED, + onClick = { if (needsFileAccess) onOpenFileAccess() else onSelect(profile) }, + otherView = if (needsFileAccess) { + { + TextButton(onClick = onOpenFileAccess, enabled = !busy) { + Text(stringResource(Res.string.browser_login_open_settings), color = LocalContentColor.current) + } } - } - } else { - null - }, - ) + } else { + null + }, + ) + } } } } - } - val error = state.error - if (error != null || state.rejectedSession) { - item(key = "error") { - val message = when { - state.rejectedSession -> Res.string.browser_login_rejected - error == BrowserLoginFailure.FILE_ACCESS_DENIED -> if (isMacOS) Res.string.browser_login_full_disk_access else Res.string.browser_login_permission - error == BrowserLoginFailure.ACCESS_DENIED -> Res.string.browser_login_permission - error == BrowserLoginFailure.KEY_UNAVAILABLE -> Res.string.browser_login_key_unavailable - error == BrowserLoginFailure.UNSUPPORTED_ENCRYPTION -> Res.string.browser_login_unsupported - error == BrowserLoginFailure.DATABASE_BUSY -> Res.string.browser_login_busy - error == BrowserLoginFailure.NO_COOKIES -> Res.string.browser_login_missing - else -> Res.string.browser_login_unreadable + val error = state.error + if (error != null || state.rejectedSession) { + item(key = "error") { + val message = when { + state.rejectedSession -> Res.string.browser_login_rejected + error == BrowserLoginFailure.FILE_ACCESS_DENIED -> if (isMacOS) Res.string.browser_login_full_disk_access else Res.string.browser_login_permission + error == BrowserLoginFailure.ACCESS_DENIED -> Res.string.browser_login_permission + error == BrowserLoginFailure.KEY_UNAVAILABLE -> Res.string.browser_login_key_unavailable + error == BrowserLoginFailure.UNSUPPORTED_ENCRYPTION -> Res.string.browser_login_unsupported + error == BrowserLoginFailure.DATABASE_BUSY -> Res.string.browser_login_busy + error == BrowserLoginFailure.NO_COOKIES -> Res.string.browser_login_missing + else -> Res.string.browser_login_unreadable + } + Spacer(Modifier.height(16.dp)) + Text( + if (error == BrowserLoginFailure.NO_COOKIES) stringResource(message, serviceName) else stringResource(message), + style = typo().bodyMedium, + color = MaterialTheme.colorScheme.error, + ) } - Spacer(Modifier.height(16.dp)) - Text( - if (error == BrowserLoginFailure.NO_COOKIES) stringResource(message, serviceName) else stringResource(message), - style = typo().bodyMedium, - color = MaterialTheme.colorScheme.error, - ) } - } - item(key = "refresh") { - TextButton(onClick = onRefresh, enabled = !busy) { - Text(stringResource(Res.string.browser_login_refresh), color = LocalContentColor.current) + item(key = "refresh") { + TextButton(onClick = onRefresh, enabled = !busy) { + Text(stringResource(Res.string.browser_login_refresh), color = LocalContentColor.current) + } + } + item(key = "end_of_list") { + EndOfPage() } } - item(key = "end_of_list") { - EndOfPage() - } + VerticalScrollBar( + scrollState = listState, + modifier = Modifier.padding(bottom = DesktopMiniPlayerClearance), + ) } } diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/AlbumScreen.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/AlbumScreen.kt index 2afb0c7ea1..9629375211 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/AlbumScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/AlbumScreen.kt @@ -68,6 +68,8 @@ import coil3.request.ImageRequest import coil3.request.crossfade import com.kmpalette.rememberPaletteState import com.kyant.backdrop.highlight.Highlight +import com.maxrave.simpmusic.expect.ui.DesktopMiniPlayerClearance +import com.maxrave.simpmusic.expect.ui.VerticalScrollBar import com.maxrave.simpmusic.extension.barBlurStyle import com.maxrave.simpmusic.ui.component.DownloadingIndicator import com.maxrave.domain.data.entities.DownloadState @@ -106,6 +108,7 @@ import com.maxrave.simpmusic.ui.icon.Shuffle import com.maxrave.simpmusic.ui.icon.SimpIcons import com.maxrave.simpmusic.ui.navigation.destination.list.AlbumDestination import com.maxrave.simpmusic.ui.navigation.destination.list.ArtistDestination +import com.maxrave.simpmusic.ui.theme.ArtworkShape import com.maxrave.simpmusic.ui.theme.seed import com.maxrave.simpmusic.ui.theme.typo import com.maxrave.simpmusic.viewModel.AlbumViewModel @@ -437,7 +440,7 @@ fun AlbumScreen( modifier = Modifier .size(280.dp) - .clip(RoundedCornerShape(8.dp)), + .clip(ArtworkShape), ) Column( modifier = Modifier.weight(1f), @@ -932,6 +935,10 @@ fun AlbumScreen( EndOfPage() } } + VerticalScrollBar( + scrollState = lazyState, + modifier = Modifier.padding(bottom = DesktopMiniPlayerClearance), + ) AnimatedVisibility( visible = shouldHideTopBar && !selectionState.isActive, enter = fadeIn() + slideInVertically(), diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/AppLogScreen.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/AppLogScreen.kt index 356e7e1817..686405bf28 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/AppLogScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/AppLogScreen.kt @@ -60,6 +60,8 @@ import androidx.navigation.NavController import com.maxrave.logger.Logger import com.maxrave.simpmusic.Platform import com.maxrave.simpmusic.expect.copyToClipboard +import com.maxrave.simpmusic.expect.ui.DesktopMiniPlayerClearance +import com.maxrave.simpmusic.expect.ui.VerticalScrollBar import com.maxrave.simpmusic.getPlatform import com.maxrave.simpmusic.ui.component.Chip import com.maxrave.simpmusic.ui.component.EndOfPage @@ -348,11 +350,17 @@ fun AppLogScreen( EndOfPage() } } + VerticalScrollBar( + scrollState = logListState, + modifier = Modifier.padding(bottom = DesktopMiniPlayerClearance), + ) } else -> { var expanded by remember { mutableStateOf(emptySet()) } + val errorListState = rememberLazyListState() LazyColumn( + state = errorListState, contentPadding = PaddingValues(top = 12.dp, bottom = bottomInset), verticalArrangement = Arrangement.spacedBy(12.dp), modifier = Modifier.padding(horizontal = if (wide) 20.dp else 16.dp), @@ -370,6 +378,10 @@ fun AppLogScreen( EndOfPage() } } + VerticalScrollBar( + scrollState = errorListState, + modifier = Modifier.padding(bottom = DesktopMiniPlayerClearance), + ) } } } diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/ArtistScreen.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/ArtistScreen.kt index d13ce6a2da..56e231262b 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/ArtistScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/ArtistScreen.kt @@ -95,6 +95,8 @@ import com.maxrave.domain.mediaservice.handler.PlaylistType import com.maxrave.domain.mediaservice.handler.QueueData import com.maxrave.domain.utils.toSongEntity import com.maxrave.simpmusic.Platform +import com.maxrave.simpmusic.expect.ui.DesktopMiniPlayerClearance +import com.maxrave.simpmusic.expect.ui.VerticalScrollBar import com.maxrave.simpmusic.getPlatform import com.maxrave.simpmusic.expect.shareUrl import com.maxrave.simpmusic.expect.ui.MediaPlayerView @@ -718,6 +720,10 @@ fun ArtistScreen( ) } } + VerticalScrollBar( + scrollState = lazyState, + modifier = Modifier.padding(bottom = DesktopMiniPlayerClearance), + ) // Haze top bar appears once the header scrolls away. AnimatedVisibility( diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/BrowseScreen.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/BrowseScreen.kt index 4b18634481..40d328dea5 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/BrowseScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/BrowseScreen.kt @@ -58,6 +58,8 @@ import com.maxrave.domain.data.model.home.Content import com.maxrave.domain.utils.toSongEntity import com.maxrave.domain.utils.toTrack import com.maxrave.simpmusic.Platform +import com.maxrave.simpmusic.expect.ui.DesktopMiniPlayerClearance +import com.maxrave.simpmusic.expect.ui.VerticalScrollBar import com.maxrave.simpmusic.extension.angledGradientBackground import com.maxrave.simpmusic.extension.artworkScrimBrush import com.maxrave.simpmusic.extension.barBlurStyle @@ -267,6 +269,10 @@ fun BrowseScreen( EndOfPage() } } + VerticalScrollBar( + scrollState = listState, + modifier = Modifier.padding(top = innerPadding.calculateTopPadding() + 64.dp, bottom = DesktopMiniPlayerClearance), + ) } } diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/CreditScreen.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/CreditScreen.kt index 5e0be04289..b3a072b4e3 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/CreditScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/CreditScreen.kt @@ -44,6 +44,8 @@ import androidx.compose.ui.unit.sp import androidx.navigation.NavController import com.maxrave.domain.extension.now import com.maxrave.simpmusic.expect.openUrl +import com.maxrave.simpmusic.expect.ui.DesktopMiniPlayerClearance +import com.maxrave.simpmusic.expect.ui.VerticalScrollBar import com.maxrave.simpmusic.extension.ultraThinBarStyle import com.maxrave.simpmusic.ui.component.RippleIconButton import com.maxrave.simpmusic.ui.icon.ArrowBackIosNew @@ -67,13 +69,14 @@ fun CreditScreen( navController: NavController, ) { val hazeState = rememberHazeState() + val scrollState = rememberScrollState() Column( modifier = Modifier .fillMaxSize() .padding(paddingValues) .padding(top = 64.dp) - .verticalScroll(rememberScrollState()) + .verticalScroll(scrollState) .hazeSource(state = hazeState), horizontalAlignment = Alignment.CenterHorizontally, ) { @@ -249,6 +252,10 @@ fun CreditScreen( // Bottom spacing Spacer(modifier = Modifier.height(200.dp)) } + VerticalScrollBar( + scrollState = scrollState, + modifier = Modifier.padding(top = paddingValues.calculateTopPadding() + 64.dp, bottom = DesktopMiniPlayerClearance), + ) TopAppBar( modifier = Modifier diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/MoreAlbumsScreen.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/MoreAlbumsScreen.kt index 85add1d4d3..9451b1f827 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/MoreAlbumsScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/MoreAlbumsScreen.kt @@ -17,6 +17,7 @@ import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.GridItemSpan import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.items +import androidx.compose.foundation.lazy.grid.rememberLazyGridState import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text @@ -32,6 +33,8 @@ import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavController import com.maxrave.logger.Logger +import com.maxrave.simpmusic.expect.ui.DesktopMiniPlayerClearance +import com.maxrave.simpmusic.expect.ui.VerticalScrollBar import com.maxrave.simpmusic.extension.ultraThinBarStyle import com.maxrave.simpmusic.ui.component.CenterLoadingBox import com.maxrave.simpmusic.ui.component.EndOfPage @@ -84,7 +87,9 @@ fun MoreAlbumsScreen( when (state) { is MoreAlbumsUIState.Success -> { val data = state.albumItems + val gridState = rememberLazyGridState() LazyVerticalGrid( + state = gridState, // As many columns as fit, not a fixed two: HomeItemContentPlaylist is a fixed // 180dp wide, so two columns on a wide window left each tile alone in a huge cell. // 170dp rather than 180 keeps two columns on a 360dp phone (2 × 170 + the 10dp @@ -126,6 +131,10 @@ fun MoreAlbumsScreen( EndOfPage() } } + VerticalScrollBar( + scrollState = gridState, + modifier = Modifier.padding(top = innerPadding.calculateTopPadding() + 64.dp, bottom = DesktopMiniPlayerClearance), + ) TopAppBar( modifier = Modifier diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/PlaylistScreen.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/PlaylistScreen.kt index 195a68c18a..b0f01b5351 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/PlaylistScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/PlaylistScreen.kt @@ -85,6 +85,8 @@ import coil3.request.crossfade import coil3.toBitmap import com.kyant.backdrop.highlight.Highlight import com.kmpalette.rememberPaletteState +import com.maxrave.simpmusic.expect.ui.DesktopMiniPlayerClearance +import com.maxrave.simpmusic.expect.ui.VerticalScrollBar import com.maxrave.simpmusic.extension.barBlurStyle import com.maxrave.simpmusic.ui.component.DownloadingIndicator import com.maxrave.domain.data.entities.DownloadState @@ -127,6 +129,7 @@ import com.maxrave.simpmusic.ui.icon.Search import com.maxrave.simpmusic.ui.icon.Shuffle import com.maxrave.simpmusic.ui.icon.SimpIcons import com.maxrave.simpmusic.ui.navigation.destination.list.ArtistDestination +import com.maxrave.simpmusic.ui.theme.ArtworkShape import com.maxrave.simpmusic.ui.theme.LocalIsDarkTheme import com.maxrave.simpmusic.ui.theme.seed import com.maxrave.simpmusic.ui.theme.typo @@ -600,7 +603,7 @@ fun PlaylistScreen( modifier = Modifier .size(280.dp) - .clip(RoundedCornerShape(8.dp)), + .clip(ArtworkShape), ) Column( modifier = Modifier.weight(1f), @@ -1163,6 +1166,10 @@ fun PlaylistScreen( } } } + VerticalScrollBar( + scrollState = lazyState, + modifier = Modifier.padding(bottom = DesktopMiniPlayerClearance), + ) AnimatedVisibility( visible = showSearchBar, diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/PodcastsScreen.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/PodcastsScreen.kt index 062d9c40b6..314e0fe062 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/PodcastsScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/PodcastsScreen.kt @@ -51,6 +51,8 @@ import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.asImageBitmap +import com.maxrave.simpmusic.expect.ui.DesktopMiniPlayerClearance +import com.maxrave.simpmusic.expect.ui.VerticalScrollBar import com.maxrave.simpmusic.ui.component.rememberHolderPainter import com.maxrave.simpmusic.expect.ui.toImageBitmap import androidx.compose.ui.layout.ContentScale @@ -86,6 +88,7 @@ import com.maxrave.simpmusic.ui.icon.Share import com.maxrave.simpmusic.ui.icon.Shuffle import com.maxrave.simpmusic.ui.icon.SimpIcons import com.maxrave.simpmusic.ui.navigation.destination.list.ArtistDestination +import com.maxrave.simpmusic.ui.theme.ArtworkShape import com.maxrave.simpmusic.ui.theme.typo import com.maxrave.simpmusic.viewModel.PodcastUIEvent import com.maxrave.simpmusic.viewModel.PodcastUIState @@ -227,7 +230,7 @@ fun PodcastScreen( .height(250.dp) .wrapContentWidth() .align(Alignment.CenterHorizontally) - .clip(RoundedCornerShape(8.dp)), + .clip(ArtworkShape), ) Box( modifier = @@ -410,6 +413,10 @@ fun PodcastScreen( EndOfPage() } } + VerticalScrollBar( + scrollState = lazyState, + modifier = Modifier.padding(bottom = DesktopMiniPlayerClearance), + ) // Animated TopAppBar when scrolling AnimatedVisibility( visible = shouldHideTopBar, diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/SearchScreen.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/SearchScreen.kt index c73e98f50a..2bd6572adb 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/SearchScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/other/SearchScreen.kt @@ -103,8 +103,10 @@ import com.maxrave.domain.utils.connectArtists import com.maxrave.domain.utils.toSongEntity import com.maxrave.domain.utils.toTrack import com.maxrave.simpmusic.Platform +import com.maxrave.simpmusic.expect.ui.DesktopMiniPlayerClearance import com.maxrave.simpmusic.expect.ui.PlatformBackHandler import com.maxrave.simpmusic.expect.ui.SongRecognitionSheet +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.getScreenSizeInfo @@ -140,6 +142,7 @@ import com.maxrave.simpmusic.ui.navigation.destination.list.ArtistDestination import com.maxrave.simpmusic.ui.navigation.destination.list.PlaylistDestination import com.maxrave.simpmusic.ui.navigation.destination.list.PodcastDestination import com.maxrave.simpmusic.ui.navigation.destination.search.SearchDestination +import com.maxrave.simpmusic.ui.theme.ArtworkShape import com.maxrave.simpmusic.ui.theme.LocalLiquidGlassEnabled import com.maxrave.simpmusic.ui.theme.typo import com.maxrave.simpmusic.viewModel.SearchScreenUIState @@ -537,6 +540,10 @@ fun SearchScreen( ) } } + VerticalScrollBar( + scrollState = suggestionsState, + modifier = Modifier.padding(top = searchBarHeight, bottom = DesktopMiniPlayerClearance), + ) } SearchUIType.SEARCH_HISTORY -> { @@ -629,6 +636,10 @@ fun SearchScreen( } } } + VerticalScrollBar( + scrollState = historyState, + modifier = Modifier.padding(top = searchBarHeight, bottom = DesktopMiniPlayerClearance), + ) } SearchUIType.EMPTY -> { @@ -726,6 +737,10 @@ fun SearchScreen( EndOfPage() } } + VerticalScrollBar( + scrollState = moodGridState, + modifier = Modifier.padding(top = searchBarHeight, bottom = DesktopMiniPlayerClearance), + ) } } } @@ -948,6 +963,10 @@ fun SearchScreen( // Space at bottom to account for bottom navigation and mini player item { Spacer(modifier = Modifier.height(150.dp)) } } + VerticalScrollBar( + scrollState = resultsState, + modifier = Modifier.padding(top = searchBarHeight, bottom = DesktopMiniPlayerClearance), + ) } else { Box( modifier = Modifier.fillMaxSize(), @@ -1292,7 +1311,7 @@ fun SuggestItemRow( if (searchResult is ArtistsResult) { CircleShape } else { - RoundedCornerShape(4.dp) + ArtworkShape }, ), ) diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentAppleMusic.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentAppleMusic.kt index 7e143538bc..580f61953b 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentAppleMusic.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentAppleMusic.kt @@ -110,6 +110,7 @@ import com.maxrave.simpmusic.ui.screen.player.content.applemusic.appleMusicVerti import com.maxrave.simpmusic.ui.screen.player.content.applemusic.displayName import com.maxrave.simpmusic.ui.screen.player.content.applemusic.rememberAppleMusicMesh import com.maxrave.simpmusic.ui.screen.player.content.applemusic.rememberAppleMusicTypography +import com.maxrave.simpmusic.ui.theme.ArtworkShape import com.maxrave.simpmusic.ui.theme.seed import com.maxrave.simpmusic.ui.theme.typo import com.maxrave.simpmusic.viewModel.NowPlayingScreenData @@ -739,7 +740,7 @@ private fun AppleMusicMainView( error = rememberHolderPainter(), contentDescription = null, contentScale = ContentScale.Crop, - modifier = Modifier.size(55.dp).clip(RoundedCornerShape(4.dp)), + modifier = Modifier.size(55.dp).clip(ArtworkShape), ) Spacer(modifier = Modifier.width(10.dp)) Column(modifier = Modifier.weight(1f)) { @@ -1052,7 +1053,7 @@ private fun AppleMusicArtworkPage( .size(width = frameWidth, height = frameHeight) // A vertical video stands clear of the screen edges, so it is rounded // like a card; wide ones run edge to edge and stay square. - .then(if (ratio < 1f) Modifier.clip(RoundedCornerShape(12.dp)) else Modifier), + .then(if (ratio < 1f) Modifier.clip(ArtworkShape) else Modifier), ) { MediaPlayerViewWithSubtitle( playerName = MAIN_PLAYER, diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentM3Expressive.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentM3Expressive.kt index 344090b4c1..d3b3eb0839 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentM3Expressive.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentM3Expressive.kt @@ -117,6 +117,7 @@ import com.maxrave.simpmusic.ui.icon.SimpIcons import com.maxrave.simpmusic.ui.screen.player.content.applemusic.AudioOutputSheetHost import com.maxrave.simpmusic.ui.screen.player.content.expressive.ExpressiveTransportRow import com.maxrave.simpmusic.ui.screen.player.content.expressive.WavySeekBar +import com.maxrave.simpmusic.ui.theme.ArtworkShape import com.maxrave.simpmusic.ui.theme.seed import com.maxrave.simpmusic.ui.theme.typo import com.maxrave.simpmusic.viewModel.UIEvent @@ -720,7 +721,7 @@ internal fun ExpressiveTrackInfoRow( .width(55.dp) .padding(end = 10.dp) .clip( - RoundedCornerShape(4.dp), + ArtworkShape, ).align(Alignment.CenterVertically), ) } diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentSpotify.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentSpotify.kt index 60b79e2a83..3207357e61 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentSpotify.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/NowPlayingContentSpotify.kt @@ -157,6 +157,7 @@ import com.maxrave.simpmusic.ui.icon.Subtitles import com.maxrave.simpmusic.ui.icon.SubtitlesOff import com.maxrave.simpmusic.ui.icon.ThumbsUpDown import com.maxrave.simpmusic.ui.screen.player.content.applemusic.AudioOutputSheetHost +import com.maxrave.simpmusic.ui.theme.ArtworkShape import com.maxrave.simpmusic.ui.theme.blackMoreOverlay import com.maxrave.simpmusic.ui.theme.overlay import com.maxrave.simpmusic.ui.theme.typo @@ -554,7 +555,7 @@ fun NowPlayingContentSpotify( .background(Color.Transparent) .shadow( elevation = 3.dp, - shape = RoundedCornerShape(8.dp), + shape = ArtworkShape, spotColor = state.spotShadowColor.copy( alpha = 0.6f, @@ -602,7 +603,7 @@ fun NowPlayingContentSpotify( }, ).background(Color.Transparent) .clip( - RoundedCornerShape(8.dp), + ArtworkShape, ).alpha( if (!state.screenData.isVideo || !state.shouldShowVideo) 1f else 0f, ), @@ -625,7 +626,7 @@ fun NowPlayingContentSpotify( modifier = Modifier .aspectRatio(state.videoAspectRatio) - .clip(RoundedCornerShape(8.dp)) + .clip(ArtworkShape) .background(Color.Black), ) { Box(Modifier.fillMaxSize()) { @@ -781,7 +782,7 @@ fun NowPlayingContentSpotify( .background(Color.Transparent) .shadow( elevation = 3.dp, - shape = RoundedCornerShape(8.dp), + shape = ArtworkShape, spotColor = Color.Black.copy(alpha = 0.4f), ambientColor = Color.Transparent, ), @@ -815,7 +816,7 @@ fun NowPlayingContentSpotify( .padding(3.dp) .fillMaxWidth() .aspectRatio(1f) - .clip(RoundedCornerShape(8.dp)), + .clip(ArtworkShape), ) } } @@ -1852,7 +1853,7 @@ internal fun NowPlayingTrackInfoRow( .width(55.dp) .padding(end = 10.dp) .clip( - RoundedCornerShape(4.dp), + ArtworkShape, ).align(Alignment.CenterVertically), ) } diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/applemusic/AppleMusicQueueView.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/applemusic/AppleMusicQueueView.kt index 7cdb222735..fd816a5206 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/applemusic/AppleMusicQueueView.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/applemusic/AppleMusicQueueView.kt @@ -57,6 +57,7 @@ import com.maxrave.domain.mediaservice.handler.MediaPlayerHandler import com.maxrave.domain.mediaservice.handler.QueueData import com.maxrave.domain.mediaservice.handler.RepeatState import com.maxrave.simpmusic.expect.ui.DeviceVolumeController +import com.maxrave.simpmusic.expect.ui.VerticalScrollBar import com.maxrave.simpmusic.ui.component.DraggableItem import com.maxrave.simpmusic.ui.component.SongFullWidthItems import com.maxrave.simpmusic.ui.component.rememberDragDropState @@ -289,6 +290,10 @@ internal fun AppleMusicQueueView( } } } + VerticalScrollBar( + scrollState = lazyListState, + modifier = Modifier.padding(top = QUEUE_TOP_FADE, bottom = QUEUE_BOTTOM_FADE), + ) } AppleMusicBottomCluster( diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/applemusic/AppleMusicShared.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/applemusic/AppleMusicShared.kt index ce80a25997..e45d14ff51 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/applemusic/AppleMusicShared.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/screen/player/content/applemusic/AppleMusicShared.kt @@ -110,6 +110,7 @@ import com.maxrave.simpmusic.ui.icon.VolumeDown import com.maxrave.simpmusic.ui.icon.VolumeUp import com.maxrave.simpmusic.ui.screen.player.content.NowPlayingContentActions import com.maxrave.simpmusic.ui.screen.player.content.NowPlayingContentState +import com.maxrave.simpmusic.ui.theme.ArtworkShape import com.maxrave.simpmusic.ui.theme.typo import com.maxrave.simpmusic.viewModel.UIEvent import org.jetbrains.compose.resources.stringResource @@ -434,7 +435,7 @@ internal fun AppleMusicCompactHeader( placeholder = rememberHolderPainter(), error = rememberHolderPainter(), contentDescription = null, - modifier = Modifier.size(55.dp).clip(RoundedCornerShape(4.dp)), + modifier = Modifier.size(55.dp).clip(ArtworkShape), ) Spacer(modifier = Modifier.width(12.dp)) Column(modifier = Modifier.weight(1f)) { diff --git a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/theme/Theme.kt b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/theme/Theme.kt index 3cc8b92fa4..9a89e937d8 100644 --- a/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/theme/Theme.kt +++ b/composeApp/src/commonMain/kotlin/com/maxrave/simpmusic/ui/theme/Theme.kt @@ -1,6 +1,7 @@ package com.maxrave.simpmusic.ui.theme import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.ColorScheme import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi import androidx.compose.material3.LocalContentColor @@ -15,6 +16,7 @@ import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.Immutable import androidx.compose.runtime.staticCompositionLocalOf import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp import com.materialkolor.PaletteStyle import com.materialkolor.rememberDynamicColorScheme import com.maxrave.domain.manager.DataStoreManager @@ -54,6 +56,9 @@ private val LightAppColors = val LocalAppColors = staticCompositionLocalOf { DarkAppColors } +/** The one corner every rounded artwork takes — covers, thumbnails, sleeves — as Spotify's 4dp. */ +val ArtworkShape = RoundedCornerShape(4.dp) + /** True in dark theme. Provided by [AppTheme] so platform glass (blur/tint) can adapt reliably. */ val LocalIsDarkTheme = staticCompositionLocalOf { true } diff --git a/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/DesktopApp.kt b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/DesktopApp.kt index 69634ef759..7e217f18ff 100644 --- a/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/DesktopApp.kt +++ b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/DesktopApp.kt @@ -514,7 +514,7 @@ fun runDesktopApp(args: Array = emptyArray()) { onOpenDesktopNotificationSettings = desktopNotificationManager::openNotificationSettings, ) - LibrarySyncLoginPrompt() + LibrarySyncLoginPrompt(sharedViewModel) ToastHost() } } 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 9d3608807b..32dee017eb 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 @@ -33,11 +33,14 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.maxrave.domain.data.model.librarysync.LibrarySyncPairingState import com.maxrave.domain.data.model.librarysync.LibrarySyncProblem 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.theme.AppTheme +import com.maxrave.simpmusic.ui.theme.parseThemeColorHex import com.maxrave.simpmusic.ui.theme.typo import com.maxrave.simpmusic.viewModel.LibrarySyncHostViewModel +import com.maxrave.simpmusic.viewModel.SharedViewModel import org.jetbrains.compose.resources.stringResource import org.koin.compose.koinInject import org.koin.compose.viewmodel.koinViewModel @@ -248,12 +251,19 @@ private fun WindowsPublicBox(problem: LibrarySyncProblem?) { * whole window, since the phone sends them whenever its user asks. */ @Composable -fun LibrarySyncLoginPrompt() { +fun LibrarySyncLoginPrompt(sharedViewModel: SharedViewModel) { val repository: LibrarySyncHostRepository = koinInject() val pending by repository.pendingLogins.collectAsStateWithLifecycle() val logins = pending ?: return - // Outside App(), so it brings a theme of its own: the app's default dark one. - AppTheme { + // Outside App(), so it applies the user's theme itself, read the way App() reads it. + val themeMode by sharedViewModel.getThemeMode().collectAsStateWithLifecycle(DataStoreManager.THEME_MODE_DARK) + val themeColorSource by sharedViewModel.getThemeColorSource().collectAsStateWithLifecycle(DataStoreManager.THEME_COLOR_DEFAULT) + val customThemeColorHex by sharedViewModel.getCustomThemeColor().collectAsStateWithLifecycle(DataStoreManager.DEFAULT_THEME_COLOR_HEX) + AppTheme( + themeMode = themeMode, + themeColorSource = themeColorSource, + customThemeColor = parseThemeColorHex(customThemeColorHex), + ) { AlertDialog( onDismissRequest = {}, title = { Text(text = stringResource(Res.string.library_sync_logins_title, logins.fromName), style = typo().titleSmall) }, 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 939716c939..184a620d9e 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 @@ -16,6 +16,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material3.AlertDialog import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.LocalContentColor import androidx.compose.material3.RadioButton import androidx.compose.material3.Text import androidx.compose.material3.TextButton @@ -149,14 +150,17 @@ actual fun LoginSyncDialog(onDismiss: () -> Unit) { }, confirmButton = { TextButton(onClick = onDismiss) { - Text(text = stringResource(if (state is LoginSyncHostState.Done) Res.string.ok else Res.string.cancel)) + Text( + text = stringResource(if (state is LoginSyncHostState.Done) Res.string.ok else Res.string.cancel), + color = LocalContentColor.current, + ) } }, dismissButton = if (canRestart) { { TextButton(onClick = viewModel::open) { - Text(text = stringResource(Res.string.login_sync_new_code)) + Text(text = stringResource(Res.string.login_sync_new_code), color = LocalContentColor.current) } } } else { diff --git a/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/expect/ui/Scrollbar.jvm.kt b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/expect/ui/Scrollbar.jvm.kt index 7c6013a85a..a3c1d4fd0e 100644 --- a/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/expect/ui/Scrollbar.jvm.kt +++ b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/expect/ui/Scrollbar.jvm.kt @@ -2,12 +2,18 @@ package com.maxrave.simpmusic.expect.ui import androidx.compose.animation.core.animateFloatAsState import androidx.compose.foundation.HorizontalScrollbar +import androidx.compose.foundation.ScrollState import androidx.compose.foundation.ScrollbarStyle +import androidx.compose.foundation.VerticalScrollbar import androidx.compose.foundation.gestures.FlingBehavior import androidx.compose.foundation.gestures.Orientation import androidx.compose.foundation.gestures.ScrollableState import androidx.compose.foundation.interaction.DragInteraction import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.lazy.grid.LazyGridState import androidx.compose.foundation.rememberScrollbarAdapter @@ -22,6 +28,7 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp @@ -165,3 +172,38 @@ actual fun HorizontalScrollBar( interactionSource = interactionSource, ) } + +/** One placement for every vertical overload: the bar on the right edge, 2dp in, over the whole height. */ +@Composable +private fun RightEdgeScrollbar( + adapter: ScrollbarAdapter, + modifier: Modifier, +) { + if (getPlatform() != Platform.Desktop) return + // A full-size Box with no pointer input of its own: presses and the wheel outside the bar fall through to the list. + Box(modifier = modifier.fillMaxSize(), contentAlignment = Alignment.TopEnd) { + VerticalScrollbar( + adapter = adapter, + modifier = Modifier.fillMaxHeight().padding(end = 2.dp), + style = scrollBarStyle, + ) + } +} + +@Composable +actual fun VerticalScrollBar( + scrollState: LazyListState, + modifier: Modifier, +) = RightEdgeScrollbar(rememberScrollbarAdapter(scrollState = scrollState), modifier) + +@Composable +actual fun VerticalScrollBar( + scrollState: LazyGridState, + modifier: Modifier, +) = RightEdgeScrollbar(rememberScrollbarAdapter(scrollState = scrollState), modifier) + +@Composable +actual fun VerticalScrollBar( + scrollState: ScrollState, + modifier: Modifier, +) = RightEdgeScrollbar(rememberScrollbarAdapter(scrollState = scrollState), modifier) diff --git a/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/ui/mini_player/MiniPlayerLayout.kt b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/ui/mini_player/MiniPlayerLayout.kt index 4a1b439008..965d7da335 100644 --- a/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/ui/mini_player/MiniPlayerLayout.kt +++ b/composeApp/src/jvmMain/kotlin/com/maxrave/simpmusic/ui/mini_player/MiniPlayerLayout.kt @@ -75,6 +75,7 @@ import com.maxrave.simpmusic.ui.icon.SkipNext import com.maxrave.simpmusic.ui.icon.SkipPrevious import com.maxrave.simpmusic.ui.icon.VolumeOff import com.maxrave.simpmusic.ui.icon.VolumeUp +import com.maxrave.simpmusic.ui.theme.ArtworkShape import com.maxrave.simpmusic.ui.theme.typo import com.maxrave.simpmusic.viewModel.NowPlayingScreenData import com.maxrave.simpmusic.viewModel.UIEvent @@ -298,7 +299,7 @@ fun MediumMiniLayout( Modifier .size(48.dp) .scale(artworkScale) - .clip(RoundedCornerShape(6.dp)) + .clip(ArtworkShape) .hoverable(artworkInteractionSource), ) @@ -521,7 +522,7 @@ fun SquareMiniLayout( .weight(1f) .fillMaxWidth(0.85f) .scale(artworkScale) - .clip(RoundedCornerShape(12.dp)) + .clip(ArtworkShape) .hoverable(artworkInteractionSource), ) @@ -786,7 +787,7 @@ fun ExpandedMiniLayout( Modifier .size(64.dp) .scale(artworkScale) - .clip(RoundedCornerShape(8.dp)) + .clip(ArtworkShape) .hoverable(artworkInteractionSource), ) From 51c883608d48f5f4a50d8dc348639b704b894cfe Mon Sep 17 00:00:00 2001 From: maxrave-dev Date: Thu, 12 Nov 2026 23:27:05 +0700 Subject: [PATCH 27/29] chore(core): bump for the library sync merge into multiplatform --- core | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core b/core index edfac2ca13..8413a257cb 160000 --- a/core +++ b/core @@ -1 +1 @@ -Subproject commit edfac2ca13f73a047bac7698a2b543bf87f825d0 +Subproject commit 8413a257cbe45d102a9f101f2760e35b549e4d9e From 44c197e12248aeaa476d94770ddf555d9f6620cb Mon Sep 17 00:00:00 2001 From: maxrave-dev Date: Sat, 14 Nov 2026 01:06:03 +0700 Subject: [PATCH 28/29] chore(release): add the 2.6.0 changelogs and bump the version and the stream extractors --- CLAUDE.md | 4 +-- changelogs/2.6.0/en-US.md | 28 +++++++++++++++++++ changelogs/2.6.0/vi-VN.md | 28 +++++++++++++++++++ .../metadata/android/en-US/changelogs/63.txt | 11 ++++++++ .../metadata/android/vi-VN/changelogs/63.txt | 11 ++++++++ gradle/libs.versions.toml | 8 +++--- 6 files changed, 84 insertions(+), 6 deletions(-) create mode 100644 changelogs/2.6.0/en-US.md create mode 100644 changelogs/2.6.0/vi-VN.md create mode 100644 fastlane/metadata/android/en-US/changelogs/63.txt create mode 100644 fastlane/metadata/android/vi-VN/changelogs/63.txt diff --git a/CLAUDE.md b/CLAUDE.md index 2f361bead7..02dbb1944a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -766,7 +766,7 @@ if (getPlatform() == Platform.Android) { - **The remote table is a locator, not a decoder.** `player_configs.json` maps a player hash to the *names* inside YouTube's own player JS (`sig: "Tl(48,5831,INPUT)"`, `nClass`, `sts`); the script is still downloaded and executed locally in QuickJS. What it buys is the step that breaks on every obfuscation reshuffle — guessing those names by regex. **Two tables, merged at lookup (2026-10-27)**: our own `raw.githubusercontent.com/maxrave-dev/simpmusic-files/main/registry/player_configs.json` (`PLAYER_CONFIG_URL`, self-hosted since 2026-09-02) is asked first, then Metrolist's `raw.githubusercontent.com/MetrolistGroup/faraday/master/registry/player_configs.json` (`METROLIST_PLAYER_CONFIG_URL`). `FaradayCipherEngine` holds one `RemotePlayerConfigStore` per URL, so each keeps its own cache, ETag and cooldowns, and one table going down or stale leaves the other working. Each is refreshed on a 6-hour TTL with an ETag, plus two failure-triggered refreshes (unknown hash, CDN rejection) that now hit both. The solver cache keys on the SUM of both stores' `configEpoch` (each only grows). Measured with aliases counted: ours covered 862 hashes, Metrolist's 1010 and every one of ours; the 8 hashes in both agreed on `sig`/`nClass`/`sts` and differed only in their alias lists, so order decides which is asked first, not the answer. - **The URL must pass two independent gates**: `configuredUrl()` wants the `/player_configs.json` suffix, `validatedSourceUrlOrNull()` wants the path under `/maxrave-dev/simpmusic-files/` or `/MetrolistGroup/faraday/`. Metrolist's own app fails the second (it points at `ZemerTeam/zemer-cipher`), so its top tier silently returns null and never runs — a whole feature disabled with no error anywhere. - **QuickJS `maxStackSize` defaults to 256 KB and YouTube's n-transform goes deeper — and QuickJS does NOT reliably raise a JS error when it overruns, the process just takes SIGSEGV.** No Kotlin frame, and no `hs_err` file either, because the crash is below the JVM: `-XX:ErrorFile` is set and still writes nothing, `dmesg` is restricted, and apport discards it because a Gradle-provisioned JDK "does not belong to a package". The only thing that located it was `Logger.w` markers around each native call — the last line printed was `callFunction.begin name=_nTransformFunc`. Fixed on both sides: `maxStackSize = 8 MB`, on a thread created with a **32 MB** stack. The soft limit must sit well under the real stack so the engine trips its own guard and throws instead of walking off the end; `newSingleThreadContext` cannot be used because it offers no way to size the stack. - - **Throwing is how a request is handed back.** `YoutubeApiDecoder.decodeBatch` tries the local decoder and falls through to the API only on an exception — a half-filled result is accepted as final and the missing URLs merely fail later. So `decodeBatch` throws unless *every* challenge is solved. `getPlayerData` is the opposite: `getPlayerMetadata` calls it with **no try/catch**, so an exception there skips the API tier entirely and lands on BravePipe; the engine returns null (rather than guessing) when either the player id or the `sts` is missing, because a wrong timestamp poisons the whole response. + - **Throwing is how a request is handed back.** `YoutubeApiDecoder.decodeBatch` tries the local decoder and falls through to the API only on an exception — a half-filled result is accepted as final and the missing URLs merely fail later. So `decodeBatch` throws unless *every* challenge is solved. `getPlayerData` is the opposite: `getPlayerMetadata` calls it with **no try/catch**, so an exception there skips the API tier entirely and lands on BravePipe; the engine returns null (rather than guessing) when either the player id or the `sts` is missing, because a wrong timestamp poisons the whole response. *(Changed 2026-11-14 with PipePipe v6.5.0, pin `bba8d84453`: `getPlayerMetadata` now catches a `ParsingException` from `getPlayerData` and takes the player metadata from the decoder API instead, logging `ejs.playerMetadata.localFailed`. `FaradayJsDecoder.getPlayerData` throws exactly that when the engine has no player info, so that case no longer ends the local extraction, and the "lands on BravePipe" statements here and in the parent entry describe pins up to `27aac1e14e`. Any other exception still propagates. `setLocalDecoder(null)` remains the way to reach the API tier.)* - **`setLocalDecoder` is the only public member of `YoutubeApiDecoder`.** `getLocalDecoder`, `decodeBatch` and `clearCache` are package-private, and `disableLocalDecoder(YoutubeJavaScriptDecoder)` — which PipePipe calls on itself the moment a decoder throws — is **private**, so it cannot be invoked from the app. Calling it anyway compiles as far as "No value passed for parameter 'decoder'", which reads like a missing argument rather than a visibility problem. Replace the decoder (`setLocalDecoder(null)` to clear it) instead. Because PipePipe drops the decoder for good the first time it throws, `Extractor.newPipePlayer` re-registers on every extraction, turning "disabled forever" into "skipped for one track". `headCheckRandomStream()` failing now also calls `invalidate()` — a CDN 403 is the only visible symptom of a stale table, since a wrong signature is still well-formed and throws nothing. - **`ExtractSource` (in-memory, last 32 videos) feeds an "Extract source" row in the info sheet** — `PipePipe · local`, `PipePipe · pipepipe.dev`, `PipePipe · cached` or `BravePipe`. Deliberately not a column on `NewFormatEntity`: a format row is cached and reused, so a persisted source would keep naming the path taken the first time. `SharedViewModel` re-reads it on **every** format emission, because the first one lands before extraction finishes. @@ -1203,6 +1203,6 @@ After completing any of the following types of changes, the AI agent **MUST** up *This document helps AI Agents quickly understand the SimpMusic project. Update regularly when there are major changes to architecture or structure.* -**Last updated**: 2026-11-12 +**Last updated**: 2026-11-14 **Project version**: Check latest release on GitHub **Maintained by**: maxrave-dev and contributors diff --git a/changelogs/2.6.0/en-US.md b/changelogs/2.6.0/en-US.md new file mode 100644 index 0000000000..b01ca7af25 --- /dev/null +++ b/changelogs/2.6.0/en-US.md @@ -0,0 +1,28 @@ +# SimpMusic 2.6.0 + +## New +- **Library sync between your phone and your computer**: pair the Android app with the Desktop app once by scanning a QR code under Settings → Library sync. Likes, followed artists, saved albums and podcasts, playlists and the last year of listening history then stay the same on both: by themselves when SimpMusic opens on the phone, every 15 minutes while it is open on the computer, and on Sync now. It runs over your own Wi-Fi or Tailscale, downloads and device settings stay on each device, and once paired the phone can send its sign-ins to the computer without scanning a code again. ([#2663](https://github.com/maxrave-dev/SimpMusic/issues/2663)) +- **SoundCloud Now Playing style**: a fourth style under Settings → Interface → Now Playing style. The artwork fills a card, the song's waveform scrolls past the playhead and is the seek bar, comments that name a moment appear over it, and a comment box with quick reactions sits underneath. ([#2847](https://github.com/maxrave-dev/SimpMusic/issues/2847)) +- **8D audio**: a switch under Settings → Playback moves the song around your head, with the rotation direction and the time per revolution (3 to 30 seconds) of your choice, on Android and Desktop. ([#2846](https://github.com/maxrave-dev/SimpMusic/issues/2846)) +- **Import sign-ins from a browser** (Desktop): Log in to YouTube and Log in to Spotify can take the sign-in from a browser profile on the same computer instead of pasting cookies by hand. Only that service's cookies are read and the browser is not changed. It reads Chromium-based and Firefox-based browsers on macOS and Linux, Safari on macOS, and Firefox-based browsers on Windows. ([#2850](https://github.com/maxrave-dev/SimpMusic/issues/2850)) +- **Word-by-word lyrics from LRCLIB**: lyrics from LRCLIB light up word by word when LRCLIB has word timing for the song. ([#2851](https://github.com/maxrave-dev/SimpMusic/issues/2851)) +- **Music app colours**: the app colour picker in Settings offers the colours of Spotify, SoundCloud, Apple Music and YouTube Music as presets. ([#2848](https://github.com/maxrave-dev/SimpMusic/issues/2848)) + +## Improved +- **AutoMix**: with crossfade on Auto, a fade now ends where the outgoing song's last chorus ends, and the next song comes in at the end of its intro. Both are read from the songs' own loudness. ([#2849](https://github.com/maxrave-dev/SimpMusic/issues/2849)) +- **Downloads**: a downloaded song's menu now says Remove download, and one still downloading says Cancel download. Several downloads can be removed at once from the Downloaded list's multi-select, and a removed or cancelled download goes back to not downloaded right away. ([#2176](https://github.com/maxrave-dev/SimpMusic/issues/2176), [#2709](https://github.com/maxrave-dev/SimpMusic/pull/2709), [core#43](https://github.com/maxrave-dev/core/pull/43)) +- **Discord login on the Full build**: you now log in on Discord's own page in your browser, and SimpMusic no longer reads your account token. If you used Discord Rich Presence before, log in again once. FOSS builds keep the token login. ([#2852](https://github.com/maxrave-dev/SimpMusic/issues/2852)) +- **Scrollbars on Desktop**: every scrolling page, the sidebar, the queues and the comments sheet have a vertical scrollbar you can drag. ([#2873](https://github.com/maxrave-dev/SimpMusic/issues/2873)) +- **Home on Android** fits more on screen, and rounded artwork uses the same corner everywhere in the app. ([#2873](https://github.com/maxrave-dev/SimpMusic/issues/2873)) +- **Artist page on Desktop**: the artist's name logo scales with the page. ([#2853](https://github.com/maxrave-dev/SimpMusic/issues/2853)) +- **Playback after YouTube updates**: both stream extractors were updated to their latest versions, with fixes for songs that failed to play when YouTube's client version could not be read or the current player could not be identified on the device. ([PipePipe bba8d844](https://github.com/maxrave-dev/PipePipeExtractor/commit/bba8d84453bb2beab4182e5d16721e25c739b777), [BravePipe 991b158f](https://github.com/maxrave-dev/BravePipeExtractor/commit/991b158fee64c95f340803d26dc5b938b4b1cd01)) +- **Skipping through a queue**: only the songs Next will play are prepared ahead, and the ones you skipped past are released. ([core ab5f1ab](https://github.com/maxrave-dev/core/commit/ab5f1abffbf693a1c12e7b27beb81ed37a3fbad8)) + +## Fixed +- Playback stopping at 00:00 / NA:NA when the next song had failed to load during a brief network drop. A failed preload is now retried with a fresh link, and dropped instead of played. This covers track changes without crossfade. ([#2239](https://github.com/maxrave-dev/SimpMusic/issues/2239), [core#12](https://github.com/maxrave-dev/core/pull/12), [core 029c420](https://github.com/maxrave-dev/core/commit/029c42060bfe7624e7c3c297b3063ff653ae60cc)) +- FOSS build: Android stopping the player about 10 minutes after a track change. ([#2233](https://github.com/maxrave-dev/SimpMusic/issues/2233)) +- macOS: the window could not be dragged to another display, and the title bar could crash the app. ([#2743](https://github.com/maxrave-dev/SimpMusic/issues/2743)) +- The keyboard staying open after picking a search suggestion. ([#2507](https://github.com/maxrave-dev/SimpMusic/issues/2507), [#2556](https://github.com/maxrave-dev/SimpMusic/pull/2556)) +- Right-to-left languages: a swiped song row moving away from your finger. It now follows it. ([683957fc](https://github.com/maxrave-dev/SimpMusic/commit/683957fc30f16b6d1cd526975360e889142e59d0)) +- The Login Sync sheet's buttons using a fixed cyan instead of your theme colour, and the title and artist on Your daily discover cards being drawn in a dim grey. ([#2873](https://github.com/maxrave-dev/SimpMusic/issues/2873)) +- A song row left pushed aside when it started or stopped playing in the middle of a swipe. ([74e691c8](https://github.com/maxrave-dev/SimpMusic/commit/74e691c88cef5bfc7bfbb99cdd6468a3889bcf05)) diff --git a/changelogs/2.6.0/vi-VN.md b/changelogs/2.6.0/vi-VN.md new file mode 100644 index 0000000000..8c59a7c4a4 --- /dev/null +++ b/changelogs/2.6.0/vi-VN.md @@ -0,0 +1,28 @@ +# SimpMusic 2.6.0 + +## Mới +- **Đồng bộ thư viện giữa điện thoại và máy tính**: bạn ghép app Android với app máy tính một lần bằng cách quét mã QR trong Cài đặt → Library sync. Sau đó bài đã thích, nghệ sĩ đang theo dõi, album và podcast đã lưu, playlist và lịch sử nghe của một năm gần nhất luôn giống nhau trên cả hai máy: tự đồng bộ khi SimpMusic mở trên điện thoại, mỗi 15 phút khi app đang mở trên máy tính, và khi bạn bấm Sync now. Việc đồng bộ chạy qua Wi-Fi hoặc Tailscale của chính bạn, bài đã tải và cài đặt riêng của thiết bị vẫn ở lại từng máy, và khi đã ghép thì điện thoại gửi được đăng nhập sang máy tính mà không cần quét mã lần nữa. ([#2663](https://github.com/maxrave-dev/SimpMusic/issues/2663)) +- **Kiểu Đang phát SoundCloud**: kiểu thứ tư trong Cài đặt → Giao diện → Kiểu Đang phát. Ảnh bìa phủ kín một thẻ, dạng sóng của bài hát chạy qua vạch phát và chính là thanh tua, bình luận có nhắc tới một thời điểm hiện ngay trên dạng sóng, và bên dưới là ô bình luận kèm vài biểu cảm bấm nhanh. ([#2847](https://github.com/maxrave-dev/SimpMusic/issues/2847)) +- **Âm thanh 8D**: một công tắc trong Cài đặt → Phát lại đưa bài hát xoay quanh đầu bạn, với chiều xoay và thời gian mỗi vòng (3 đến 30 giây) do bạn chọn, trên Android và máy tính. ([#2846](https://github.com/maxrave-dev/SimpMusic/issues/2846)) +- **Lấy đăng nhập từ trình duyệt** (máy tính): Đăng nhập vào YouTube và Đăng nhập vào Spotify lấy được đăng nhập từ một profile trình duyệt trên cùng máy, bạn không phải dán cookie bằng tay. App chỉ đọc cookie của đúng dịch vụ đó và không thay đổi gì trong trình duyệt. App đọc được các trình duyệt nhân Chromium và nhân Firefox trên macOS và Linux, Safari trên macOS, và các trình duyệt nhân Firefox trên Windows. ([#2850](https://github.com/maxrave-dev/SimpMusic/issues/2850)) +- **Lời chạy theo từng chữ từ LRCLIB**: lời lấy từ LRCLIB sáng lên theo từng chữ khi LRCLIB có mốc thời gian từng chữ cho bài đó. ([#2851](https://github.com/maxrave-dev/SimpMusic/issues/2851)) +- **Màu theo các app nhạc**: bảng chọn màu app trong Cài đặt có sẵn màu của Spotify, SoundCloud, Apple Music và YouTube Music. ([#2848](https://github.com/maxrave-dev/SimpMusic/issues/2848)) + +## Cải thiện +- **AutoMix**: khi chuyển bài mượt mà ở chế độ Auto, đoạn chuyển giờ kết thúc đúng chỗ điệp khúc cuối của bài đang phát kết thúc, và bài kế vào ở cuối đoạn dạo đầu của nó. Cả hai mốc được đọc từ chính độ lớn âm thanh của bài hát. ([#2849](https://github.com/maxrave-dev/SimpMusic/issues/2849)) +- **Bài đã tải**: menu của bài đã tải giờ ghi Remove download, còn bài đang tải ghi Cancel download. Bạn gỡ được nhiều bài cùng lúc bằng chọn nhiều trong danh sách Đã tải xuống, và bài vừa gỡ hoặc vừa huỷ tải trở về trạng thái chưa tải ngay lập tức. ([#2176](https://github.com/maxrave-dev/SimpMusic/issues/2176), [#2709](https://github.com/maxrave-dev/SimpMusic/pull/2709), [core#43](https://github.com/maxrave-dev/core/pull/43)) +- **Đăng nhập Discord trên bản Full**: giờ bạn đăng nhập trên chính trang của Discord trong trình duyệt, và SimpMusic không còn đọc token tài khoản của bạn. Nếu trước đây bạn đã dùng Discord Rich Presence, hãy đăng nhập lại một lần. Bản FOSS vẫn đăng nhập bằng token như cũ. ([#2852](https://github.com/maxrave-dev/SimpMusic/issues/2852)) +- **Thanh cuộn trên máy tính**: mọi trang cuộn được, sidebar, các hàng đợi và bảng bình luận đều có thanh cuộn dọc mà bạn kéo được. ([#2873](https://github.com/maxrave-dev/SimpMusic/issues/2873)) +- **Trang chủ trên Android** hiện được nhiều nội dung hơn trên một màn hình, và ảnh bìa bo góc dùng cùng một độ bo ở mọi nơi trong app. ([#2873](https://github.com/maxrave-dev/SimpMusic/issues/2873)) +- **Trang nghệ sĩ trên máy tính**: logo tên nghệ sĩ co giãn theo kích thước trang. ([#2853](https://github.com/maxrave-dev/SimpMusic/issues/2853)) +- **Phát nhạc sau khi YouTube cập nhật**: cả hai bộ lấy stream được cập nhật lên bản mới nhất, kèm các bản sửa cho trường hợp bài không phát được vì không đọc được phiên bản client của YouTube hoặc không xác định được trình phát hiện tại ngay trên máy. ([PipePipe bba8d844](https://github.com/maxrave-dev/PipePipeExtractor/commit/bba8d84453bb2beab4182e5d16721e25c739b777), [BravePipe 991b158f](https://github.com/maxrave-dev/BravePipeExtractor/commit/991b158fee64c95f340803d26dc5b938b4b1cd01)) +- **Bỏ qua nhiều bài trong hàng đợi**: app chỉ chuẩn bị trước những bài mà nút Tiếp sẽ phát, và giải phóng những bài bạn đã bỏ qua. ([core ab5f1ab](https://github.com/maxrave-dev/core/commit/ab5f1abffbf693a1c12e7b27beb81ed37a3fbad8)) + +## Sửa lỗi +- Nhạc dừng ở 00:00 / NA:NA khi bài kế tải hỏng vì mạng rớt trong chốc lát. Bài tải trước bị hỏng giờ được tải lại bằng link mới, và bị bỏ đi thay vì đem ra phát. Bản sửa này áp dụng cho lúc chuyển bài không có chuyển bài mượt mà. ([#2239](https://github.com/maxrave-dev/SimpMusic/issues/2239), [core#12](https://github.com/maxrave-dev/core/pull/12), [core 029c420](https://github.com/maxrave-dev/core/commit/029c42060bfe7624e7c3c297b3063ff653ae60cc)) +- Bản FOSS: Android dừng trình phát khoảng 10 phút sau một lần chuyển bài. ([#2233](https://github.com/maxrave-dev/SimpMusic/issues/2233)) +- macOS: không kéo được cửa sổ sang màn hình khác, và thanh tiêu đề có thể làm app crash. ([#2743](https://github.com/maxrave-dev/SimpMusic/issues/2743)) +- Bàn phím vẫn mở sau khi bạn chọn một gợi ý tìm kiếm. ([#2507](https://github.com/maxrave-dev/SimpMusic/issues/2507), [#2556](https://github.com/maxrave-dev/SimpMusic/pull/2556)) +- Ngôn ngữ viết từ phải sang trái: dòng bài hát chạy ngược chiều ngón tay khi bạn vuốt. Giờ nó đi theo ngón tay. ([683957fc](https://github.com/maxrave-dev/SimpMusic/commit/683957fc30f16b6d1cd526975360e889142e59d0)) +- Các nút trong bảng Login Sync dùng màu xanh cố định thay vì màu chủ đề của bạn, và tên bài cùng tên nghệ sĩ trên thẻ Your daily discover bị vẽ bằng màu xám mờ. ([#2873](https://github.com/maxrave-dev/SimpMusic/issues/2873)) +- Dòng bài hát bị kẹt lệch sang một bên khi bài đó bắt đầu hoặc ngừng phát giữa lúc bạn đang vuốt. ([74e691c8](https://github.com/maxrave-dev/SimpMusic/commit/74e691c88cef5bfc7bfbb99cdd6468a3889bcf05)) diff --git a/fastlane/metadata/android/en-US/changelogs/63.txt b/fastlane/metadata/android/en-US/changelogs/63.txt new file mode 100644 index 0000000000..02f987763a --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/63.txt @@ -0,0 +1,11 @@ +New: +- Library sync between your phone and your computer +- SoundCloud Now Playing style, 8D audio +- Word-by-word lyrics from LRCLIB, music app colours +- Desktop: import sign-ins from a browser +Improved: +- AutoMix follows each song's structure, Remove download in the song menu +- Discord login on Discord's own page (Full), Desktop scrollbars +Fixed: +- Playback stopping after a network drop, FOSS player stopping after 10 minutes +- macOS window across displays, keyboard after a search suggestion diff --git a/fastlane/metadata/android/vi-VN/changelogs/63.txt b/fastlane/metadata/android/vi-VN/changelogs/63.txt new file mode 100644 index 0000000000..8a963748d9 --- /dev/null +++ b/fastlane/metadata/android/vi-VN/changelogs/63.txt @@ -0,0 +1,11 @@ +Mới: +- Đồng bộ thư viện giữa điện thoại và máy tính +- Kiểu Đang phát SoundCloud, âm thanh 8D +- Lời chạy theo từng chữ từ LRCLIB, màu theo các app nhạc +- Máy tính: lấy đăng nhập từ trình duyệt +Cải thiện: +- AutoMix bám theo cấu trúc bài hát, Remove download trong menu bài hát +- Đăng nhập Discord trên trang của Discord (bản Full), thanh cuộn trên máy tính +Sửa lỗi: +- Nhạc dừng sau khi rớt mạng, bản FOSS dừng phát sau 10 phút +- Kéo cửa sổ macOS sang màn hình khác, bàn phím sau khi chọn gợi ý tìm kiếm diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index acc58e9c26..e9ecffa042 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -1,7 +1,7 @@ [versions] # App version -version-name = "2.5.0" -version-code = "62" +version-name = "2.6.0" +version-code = "63" android = "9.5.0" kotlin = "2.4.21" @@ -61,10 +61,10 @@ sentry-android = "8.61.1" sentry-gradle-android = "6.24.0" sentry-jvm = "8.61.1" newpipe = "v0.26.1" -brave-newpipe = "105aad96c7" +brave-newpipe = "991b158fee" # org.json ships with the Android SDK but is absent on JVM desktop; PipePipeExtractor references it. org-json = "20231013" # pin version -pipepipe = "27aac1e14e" +pipepipe = "bba8d84453" # QuickJS binding for KMP — runs YouTube's player JS to solve sig/n challenges locally. quickjs = "1.0.15" webkit = "1.18.0" From f78a4fd6da9680e5771f4763194d2895d26914fd Mon Sep 17 00:00:00 2001 From: maxrave-dev Date: Sat, 14 Nov 2026 01:10:12 +0700 Subject: [PATCH 29/29] docs(changelog): state the 2.6.0 playback fix after a network drop without a crossfade caveat --- changelogs/2.6.0/en-US.md | 2 +- changelogs/2.6.0/vi-VN.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/changelogs/2.6.0/en-US.md b/changelogs/2.6.0/en-US.md index b01ca7af25..d273d160ab 100644 --- a/changelogs/2.6.0/en-US.md +++ b/changelogs/2.6.0/en-US.md @@ -19,7 +19,7 @@ - **Skipping through a queue**: only the songs Next will play are prepared ahead, and the ones you skipped past are released. ([core ab5f1ab](https://github.com/maxrave-dev/core/commit/ab5f1abffbf693a1c12e7b27beb81ed37a3fbad8)) ## Fixed -- Playback stopping at 00:00 / NA:NA when the next song had failed to load during a brief network drop. A failed preload is now retried with a fresh link, and dropped instead of played. This covers track changes without crossfade. ([#2239](https://github.com/maxrave-dev/SimpMusic/issues/2239), [core#12](https://github.com/maxrave-dev/core/pull/12), [core 029c420](https://github.com/maxrave-dev/core/commit/029c42060bfe7624e7c3c297b3063ff653ae60cc)) +- Playback stopping at 00:00 / NA:NA when the next song had failed to load during a brief network drop. A failed preload is now retried with a fresh link, and dropped instead of played. ([#2239](https://github.com/maxrave-dev/SimpMusic/issues/2239), [core#12](https://github.com/maxrave-dev/core/pull/12), [core 029c420](https://github.com/maxrave-dev/core/commit/029c42060bfe7624e7c3c297b3063ff653ae60cc)) - FOSS build: Android stopping the player about 10 minutes after a track change. ([#2233](https://github.com/maxrave-dev/SimpMusic/issues/2233)) - macOS: the window could not be dragged to another display, and the title bar could crash the app. ([#2743](https://github.com/maxrave-dev/SimpMusic/issues/2743)) - The keyboard staying open after picking a search suggestion. ([#2507](https://github.com/maxrave-dev/SimpMusic/issues/2507), [#2556](https://github.com/maxrave-dev/SimpMusic/pull/2556)) diff --git a/changelogs/2.6.0/vi-VN.md b/changelogs/2.6.0/vi-VN.md index 8c59a7c4a4..1936012a25 100644 --- a/changelogs/2.6.0/vi-VN.md +++ b/changelogs/2.6.0/vi-VN.md @@ -19,7 +19,7 @@ - **Bỏ qua nhiều bài trong hàng đợi**: app chỉ chuẩn bị trước những bài mà nút Tiếp sẽ phát, và giải phóng những bài bạn đã bỏ qua. ([core ab5f1ab](https://github.com/maxrave-dev/core/commit/ab5f1abffbf693a1c12e7b27beb81ed37a3fbad8)) ## Sửa lỗi -- Nhạc dừng ở 00:00 / NA:NA khi bài kế tải hỏng vì mạng rớt trong chốc lát. Bài tải trước bị hỏng giờ được tải lại bằng link mới, và bị bỏ đi thay vì đem ra phát. Bản sửa này áp dụng cho lúc chuyển bài không có chuyển bài mượt mà. ([#2239](https://github.com/maxrave-dev/SimpMusic/issues/2239), [core#12](https://github.com/maxrave-dev/core/pull/12), [core 029c420](https://github.com/maxrave-dev/core/commit/029c42060bfe7624e7c3c297b3063ff653ae60cc)) +- Nhạc dừng ở 00:00 / NA:NA khi bài kế tải hỏng vì mạng rớt trong chốc lát. Bài tải trước bị hỏng giờ được tải lại bằng link mới, và bị bỏ đi thay vì đem ra phát. ([#2239](https://github.com/maxrave-dev/SimpMusic/issues/2239), [core#12](https://github.com/maxrave-dev/core/pull/12), [core 029c420](https://github.com/maxrave-dev/core/commit/029c42060bfe7624e7c3c297b3063ff653ae60cc)) - Bản FOSS: Android dừng trình phát khoảng 10 phút sau một lần chuyển bài. ([#2233](https://github.com/maxrave-dev/SimpMusic/issues/2233)) - macOS: không kéo được cửa sổ sang màn hình khác, và thanh tiêu đề có thể làm app crash. ([#2743](https://github.com/maxrave-dev/SimpMusic/issues/2743)) - Bàn phím vẫn mở sau khi bạn chọn một gợi ý tìm kiếm. ([#2507](https://github.com/maxrave-dev/SimpMusic/issues/2507), [#2556](https://github.com/maxrave-dev/SimpMusic/pull/2556))