diff --git a/app/src/main/java/com/lastwave/app/data/local/SettingsPreferences.kt b/app/src/main/java/com/lastwave/app/data/local/SettingsPreferences.kt index 5cbb976ea1..ab69e7c162 100644 --- a/app/src/main/java/com/lastwave/app/data/local/SettingsPreferences.kt +++ b/app/src/main/java/com/lastwave/app/data/local/SettingsPreferences.kt @@ -252,6 +252,8 @@ data class MiscSettings( val systemEffectsMode: Boolean = false, /** When true, shows floating button now playing instead of the bottom mini player card (Settings -> Experimental). */ val buttonNowPlayingEnabled: Boolean = false, + /** Opt-in: show the active synced lyric line above the progress bar on Now Playing. */ + val nowPlayingMiniLyricsEnabled: Boolean = false, /** When true, shows synced music video option in the Now Playing menu (Settings -> Experimental). On by default. */ val musicVideoEnabled: Boolean = true, val musicVideoFullBleed: Boolean = false, @@ -585,6 +587,7 @@ class SettingsPreferences @Inject constructor( val STORAGE_CACHE_LAST_CLEAR_FREED_BYTES = longPreferencesKey("lw_storage_cache_last_clear_freed_bytes") val SYSTEM_EFFECTS_MODE = booleanPreferencesKey("lw_system_effects_mode") val BUTTON_NOW_PLAYING_ENABLED = booleanPreferencesKey("lw_button_now_playing_enabled") + val NOW_PLAYING_MINI_LYRICS_ENABLED = booleanPreferencesKey("lw_now_playing_mini_lyrics_enabled") val MUSIC_VIDEO_ENABLED = booleanPreferencesKey("lw_music_video_enabled") val MUSIC_VIDEO_FULL_BLEED = booleanPreferencesKey("lw_music_video_full_bleed") val NOW_PLAYING_DESIGN = stringPreferencesKey("lw_now_playing_design") @@ -672,6 +675,7 @@ class SettingsPreferences @Inject constructor( downloadQuality = p.readSafely(Keys.DOWNLOAD_QUALITY)?.takeIf { it in DOWNLOAD_QUALITIES } ?: 27, systemEffectsMode = p.readSafely(Keys.SYSTEM_EFFECTS_MODE) ?: false, buttonNowPlayingEnabled = p.readSafely(Keys.BUTTON_NOW_PLAYING_ENABLED) ?: false, + nowPlayingMiniLyricsEnabled = p.readSafely(Keys.NOW_PLAYING_MINI_LYRICS_ENABLED) ?: false, musicVideoEnabled = p.readSafely(Keys.MUSIC_VIDEO_ENABLED) ?: true, musicVideoFullBleed = p.readSafely(Keys.MUSIC_VIDEO_FULL_BLEED) ?: false, nowPlayingDesign = NowPlayingDesign.fromId(p.readSafely(Keys.NOW_PLAYING_DESIGN)), @@ -1097,6 +1101,10 @@ class SettingsPreferences @Inject constructor( dataStore.edit { it[Keys.BUTTON_NOW_PLAYING_ENABLED] = enabled } } + suspend fun setNowPlayingMiniLyricsEnabled(enabled: Boolean) { + dataStore.edit { it[Keys.NOW_PLAYING_MINI_LYRICS_ENABLED] = enabled } + } + suspend fun setStudioMasterClarity(enabled: Boolean) { dataStore.edit { it[Keys.MUSIC_ENHANCER] = enabled } } diff --git a/app/src/main/java/com/lastwave/app/ui/player/FullPlayer.kt b/app/src/main/java/com/lastwave/app/ui/player/FullPlayer.kt index e2b86073cd..515446f837 100644 --- a/app/src/main/java/com/lastwave/app/ui/player/FullPlayer.kt +++ b/app/src/main/java/com/lastwave/app/ui/player/FullPlayer.kt @@ -378,6 +378,7 @@ internal fun FullPlayer( lyricsButtonsAutoHideSeconds: Int = 5, /** Language the lyric translate button targets; blank = app language. */ translationLanguage: String = "", + nowPlayingMiniLyricsEnabled: Boolean = false, canvas: com.lastwave.app.data.canvas.CanvasArtwork? = null, canvasEnabled: Boolean = true, canvasFullBleedEnabled: Boolean = true, @@ -1448,6 +1449,9 @@ internal fun FullPlayer( state = state, player = player, progressState = progressState, + lyricsState = lyricsState, + lyricsOffsetMs = lyricsOffsetMs, + nowPlayingMiniLyricsEnabled = nowPlayingMiniLyricsEnabled, seekbarStyle = seekbarStyle, nowPlayingDesign = nowPlayingDesign, wavySeekbarEnabled = wavySeekbarEnabled, @@ -1862,12 +1866,35 @@ internal fun FullPlayer( } } } - Spacer(Modifier.height(4.dp)) + var miniLyricsVisible by remember { mutableStateOf(false) } + val miniLyricsShowing = nowPlayingMiniLyricsEnabled && !playerLyricsActive && miniLyricsVisible + val miniLyricsLayoutDuration = if (miniLyricsShowing) 220 else 180 + val artworkBottomGap by animateDpAsState( + targetValue = if (miniLyricsShowing) 12.dp else 4.dp, + animationSpec = tween(miniLyricsLayoutDuration, easing = FastOutSlowInEasing), + label = "miniLyricsArtworkGap", + ) + val controlsTranslationY by animateDpAsState( + targetValue = if (miniLyricsShowing) 0.dp else (-14).dp, + animationSpec = tween(miniLyricsLayoutDuration, easing = FastOutSlowInEasing), + label = "miniLyricsControlsTranslationY", + ) + val miniLyricsTopGap by animateDpAsState( + targetValue = if (miniLyricsShowing) 6.dp else 10.dp, + animationSpec = tween(miniLyricsLayoutDuration, easing = FastOutSlowInEasing), + label = "miniLyricsTopGap", + ) + val utilityControlsGap by animateDpAsState( + targetValue = if (miniLyricsShowing) 18.dp else 30.dp, + animationSpec = tween(miniLyricsLayoutDuration, easing = FastOutSlowInEasing), + label = "miniLyricsUtilityGap", + ) + Spacer(Modifier.height(artworkBottomGap)) Column( modifier = Modifier .fillMaxWidth() .padding(horizontal = if (isVideoActive) 20.dp else 0.dp) - .graphicsLayer { translationY = -14.dp.toPx() }, + .graphicsLayer { translationY = controlsTranslationY.toPx() }, horizontalAlignment = Alignment.CenterHorizontally, ) { Row( @@ -2003,7 +2030,18 @@ internal fun FullPlayer( } } } - Spacer(Modifier.height(10.dp)) + Spacer(Modifier.height(miniLyricsTopGap)) + NowPlayingMiniLyrics( + enabled = nowPlayingMiniLyricsEnabled && !playerLyricsActive, + trackKey = lyricsTrackKey(track), + lyricsState = lyricsState, + progressState = progressState, + isPlaying = state.isPlaying, + lyricsOffsetMs = lyricsOffsetMs, + onOpenFullLyrics = { onTabChange(FullPlayerTab.LYRICS) }, + onVisibilityChange = { miniLyricsVisible = it }, + modifier = Modifier.fillMaxWidth().padding(horizontal = 4.dp), + ) SeekBar( progressState = progressState, isPlaying = state.isPlaying, @@ -2030,7 +2068,7 @@ internal fun FullPlayer( ) Spacer(Modifier.height(12.dp)) MainControls(state, player, isTranslucent = LocalLiquidGlass.current || showFullBleed, design = nowPlayingDesign) - Spacer(Modifier.height(30.dp)) + Spacer(Modifier.height(utilityControlsGap)) PlayerUtilityControls( state = state, player = player, diff --git a/app/src/main/java/com/lastwave/app/ui/player/FullPlayerLandscape.kt b/app/src/main/java/com/lastwave/app/ui/player/FullPlayerLandscape.kt index 5bbb01097a..26de83cc6d 100644 --- a/app/src/main/java/com/lastwave/app/ui/player/FullPlayerLandscape.kt +++ b/app/src/main/java/com/lastwave/app/ui/player/FullPlayerLandscape.kt @@ -345,6 +345,9 @@ internal fun FullPlayerLandscape( state: MusicPlayerState, player: MusicPlayer, progressState: StateFlow?, + lyricsState: LyricsUiState = LyricsUiState.Idle, + lyricsOffsetMs: Long = 0L, + nowPlayingMiniLyricsEnabled: Boolean = false, seekbarStyle: SeekbarStyle = SeekbarStyle.DEFAULT, nowPlayingDesign: com.lastwave.app.data.local.NowPlayingDesign = com.lastwave.app.data.local.NowPlayingDesign.CLASSIC, wavySeekbarEnabled: Boolean = (seekbarStyle == SeekbarStyle.WAVY), @@ -516,10 +519,26 @@ internal fun FullPlayerLandscape( } } - Spacer(Modifier.height(20.dp)) + val resolvedProgressState = progressState ?: player.progressState + val miniLyricsCandidate = nowPlayingMiniLyricsEnabled && + eligibleSyncedLines(lyricsState, lyricsTrackKey(track)) != null + Spacer(Modifier.height(if (miniLyricsCandidate) 8.dp else 20.dp)) + + NowPlayingMiniLyrics( + enabled = nowPlayingMiniLyricsEnabled, + trackKey = lyricsTrackKey(track), + lyricsState = lyricsState, + progressState = resolvedProgressState, + isPlaying = state.isPlaying, + lyricsOffsetMs = lyricsOffsetMs, + onOpenFullLyrics = { onTabChange(FullPlayerTab.LYRICS) }, + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 4.dp), + ) SeekBar( - progressState = progressState ?: player.progressState, + progressState = resolvedProgressState, isPlaying = state.isPlaying, trackKey = track.videoId ?: "${track.artist}|${track.title}", seekbarStyle = seekbarStyle, @@ -545,11 +564,11 @@ internal fun FullPlayerLandscape( onClick = onOpenSignalPath, modifier = Modifier.offset(y = (-2).dp), ) - Spacer(Modifier.height(14.dp)) + Spacer(Modifier.height(if (miniLyricsCandidate) 10.dp else 14.dp)) MainControls(state, player, isTranslucent = LocalLiquidGlass.current, design = nowPlayingDesign) - Spacer(Modifier.height(30.dp)) + Spacer(Modifier.height(if (miniLyricsCandidate) 16.dp else 30.dp)) PlayerUtilityControls( state = state, diff --git a/app/src/main/java/com/lastwave/app/ui/player/LyricsUiState.kt b/app/src/main/java/com/lastwave/app/ui/player/LyricsUiState.kt index 269c7cb1a0..5041656b25 100644 --- a/app/src/main/java/com/lastwave/app/ui/player/LyricsUiState.kt +++ b/app/src/main/java/com/lastwave/app/ui/player/LyricsUiState.kt @@ -14,6 +14,7 @@ sealed interface LyricsUiState { val plainLyrics: String? = null, val isInstrumental: Boolean = false, val source: String? = null, + val trackKey: String? = null, ) : LyricsUiState { val isRtl: Boolean get() = lines.any { it.isRtl } || isRtlText(plainLyrics) } diff --git a/app/src/main/java/com/lastwave/app/ui/player/NowPlayingMiniLyrics.kt b/app/src/main/java/com/lastwave/app/ui/player/NowPlayingMiniLyrics.kt new file mode 100644 index 0000000000..019f804e80 --- /dev/null +++ b/app/src/main/java/com/lastwave/app/ui/player/NowPlayingMiniLyrics.kt @@ -0,0 +1,259 @@ +package com.lastwave.app.ui.player + +import androidx.compose.animation.AnimatedContent +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.SizeTransform +import androidx.compose.animation.core.FastOutSlowInEasing +import androidx.compose.animation.core.animateFloatAsState +import androidx.compose.animation.core.tween +import androidx.compose.animation.expandVertically +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.shrinkVertically +import androidx.compose.animation.slideInVertically +import androidx.compose.animation.slideOutVertically +import androidx.compose.animation.togetherWith +import androidx.compose.foundation.clickable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.collectIsPressedAsState +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.defaultMinSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.Immutable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.derivedStateOf +import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +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.geometry.Offset +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Shadow +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.platform.LocalLayoutDirection +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.LayoutDirection +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.compose.LocalLifecycleOwner +import androidx.lifecycle.repeatOnLifecycle +import com.lastwave.app.R +import com.lastwave.app.data.lyrics.LyricLine +import com.lastwave.app.playback.PlaybackProgressState +import com.lastwave.app.ui.common.ExpressiveMotion +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.collectLatest + +/** Covers the 250 ms Now Playing ticker cadence plus minor frame jitter. */ +internal const val MINI_LYRICS_BOUNDARY_WAKE_WINDOW_MS = 300L + +@Immutable +internal data class MiniLyricsLine( + val stageIndex: Int, + val lineIndex: Int, + val text: String, + val isRtl: Boolean, +) + +internal fun eligibleSyncedLines( + lyricsState: LyricsUiState, + currentTrackKey: String?, +): List? { + val success = lyricsState as? LyricsUiState.Success ?: return null + if (!success.isSynced || success.isInstrumental || success.lines.isEmpty()) return null + if (success.trackKey != null && currentTrackKey != null && success.trackKey != currentTrackKey) { + return null + } + return success.lines +} + +internal fun resolveMiniLyricsLine( + stage: LyricsStage, + positionMs: Long, + lyricsOffsetMs: Long = 0L, +): MiniLyricsLine? { + if (stage.items.isEmpty()) return null + val idx = stage.activeIndex(positionMs + lyricsOffsetMs) + if (idx !in stage.items.indices) return null + val group = stage.items[idx] as? LyricLineGroup ?: return null + val vocal = group.lead?.takeIf { it.text.isNotBlank() } + ?: group.backgrounds.firstOrNull { it.text.isNotBlank() } + ?: return null + return MiniLyricsLine( + stageIndex = idx, + lineIndex = vocal.lineIndex, + text = vocal.text, + isRtl = vocal.isRtl, + ) +} + +@Composable +internal fun NowPlayingMiniLyrics( + enabled: Boolean, + trackKey: String, + lyricsState: LyricsUiState, + progressState: StateFlow, + isPlaying: Boolean, + lyricsOffsetMs: Long, + onOpenFullLyrics: () -> Unit, + modifier: Modifier = Modifier, + textColor: Color = LocalPlayerForeground.current.copy(alpha = 0.88f), + textAlign: TextAlign = TextAlign.Start, + onVisibilityChange: (Boolean) -> Unit = {}, +) { + val latestOnVisibilityChange by rememberUpdatedState(onVisibilityChange) + DisposableEffect(Unit) { + onDispose { latestOnVisibilityChange(false) } + } + // Keying by track discards the outgoing track's exit state immediately so + // stale lines from the previous song never flash over the next track. + key(trackKey) { + val lines = if (enabled) eligibleSyncedLines(lyricsState, trackKey) else null + val stage = remember(lines) { lines?.let(::buildLyricsStage) } + + val latestSample = remember { mutableLongStateOf(progressState.value.positionMs) } + val lifecycleOwner = LocalLifecycleOwner.current + LaunchedEffect(progressState, lifecycleOwner, stage != null) { + if (stage == null) return@LaunchedEffect + lifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { + progressState.collect { latestSample.longValue = it.positionMs } + } + } + + val offsetState by rememberUpdatedState(lyricsOffsetMs) + val framePositionMs = remember { mutableLongStateOf(progressState.value.positionMs) } + val clockActive = isPlaying && stage != null && rememberPlayerWindowActive() + LaunchedEffect(clockActive, stage) { + val activeStage = stage ?: return@LaunchedEffect + if (!clockActive) { + snapshotFlow { latestSample.longValue }.collect { framePositionMs.longValue = it } + return@LaunchedEffect + } + snapshotFlow { latestSample.longValue to offsetState }.collectLatest { (sample, offset) -> + val shown = framePositionMs.longValue + framePositionMs.longValue = + if (sample < shown && shown - sample <= MINI_LYRICS_BOUNDARY_WAKE_WINDOW_MS) shown else sample + val shifted = framePositionMs.longValue + offset + val nextStart = activeStage.nextStartAfter(shifted) ?: return@collectLatest + val waitMs = nextStart - shifted + if (waitMs in 1L..MINI_LYRICS_BOUNDARY_WAKE_WINDOW_MS) { + delay(waitMs) + framePositionMs.longValue = sample + waitMs + } + } + } + + val activeLine by remember(stage) { + derivedStateOf { + stage?.let { resolveMiniLyricsLine(it, framePositionMs.longValue, offsetState) } + } + } + var shownLine by remember { mutableStateOf(null) } + if (activeLine != null) shownLine = activeLine + val isVisible = activeLine != null + LaunchedEffect(isVisible) { + latestOnVisibilityChange(isVisible) + } + + AnimatedVisibility( + visible = isVisible, + enter = fadeIn(tween(220, easing = FastOutSlowInEasing)) + + expandVertically(tween(220, easing = FastOutSlowInEasing)), + exit = fadeOut(tween(180, easing = FastOutSlowInEasing)) + + shrinkVertically(tween(180, easing = FastOutSlowInEasing)), + modifier = modifier, + ) { + val displayLine = activeLine ?: shownLine ?: return@AnimatedVisibility + val interactionSource = remember { MutableInteractionSource() } + val pressed by interactionSource.collectIsPressedAsState() + val pressScale by animateFloatAsState( + targetValue = if (pressed) 0.98f else 1f, + animationSpec = ExpressiveMotion.spatialSpring(), + label = "miniLyricsPressScale", + ) + val baseStyle = MaterialTheme.typography.bodyMedium + val glowRadius = with(LocalDensity.current) { 12.dp.toPx() } + val textStyle = remember(baseStyle, glowRadius, textColor) { + baseStyle.copy( + fontSize = 15.sp, + lineHeight = 20.sp, + fontWeight = FontWeight.Bold, + letterSpacing = (-0.1).sp, + shadow = Shadow(textColor.copy(alpha = 0.55f), Offset.Zero, glowRadius), + ) + } + + Box( + modifier = Modifier + .fillMaxWidth() + .defaultMinSize(minHeight = 48.dp) + .graphicsLayer { + scaleX = pressScale + scaleY = pressScale + } + .clickable( + interactionSource = interactionSource, + indication = null, + onClickLabel = stringResource(R.string.player_mini_lyrics_open_cd), + role = Role.Button, + onClick = hapticClick(action = onOpenFullLyrics), + ) + .padding(vertical = 6.dp), + contentAlignment = if (textAlign == TextAlign.Center) Alignment.Center else Alignment.CenterStart, + ) { + AnimatedContent( + targetState = displayLine, + transitionSpec = { + val forward = targetState.stageIndex >= initialState.stageIndex + val slideOffset: (Int) -> Int = { fullHeight -> + val delta = (fullHeight / 3).coerceAtLeast(12) + if (forward) delta else -delta + } + val transform = (fadeIn(tween(240, easing = FastOutSlowInEasing)) + + slideInVertically(tween(260, easing = FastOutSlowInEasing), initialOffsetY = slideOffset)) togetherWith + (fadeOut(tween(180, easing = FastOutSlowInEasing)) + + slideOutVertically(tween(200, easing = FastOutSlowInEasing)) { fullHeight -> + val delta = (fullHeight / 3).coerceAtLeast(12) + if (forward) -delta else delta + }) + transform using SizeTransform( + clip = false, + sizeAnimationSpec = { _, _ -> tween(220, easing = FastOutSlowInEasing) }, + ) + }, + label = "nowPlayingMiniLyricsLine", + ) { line -> + CompositionLocalProvider( + LocalLayoutDirection provides if (line.isRtl) LayoutDirection.Rtl else LayoutDirection.Ltr, + ) { + Text( + text = line.text, + style = textStyle, + color = textColor, + textAlign = textAlign, + modifier = Modifier.fillMaxWidth(), + ) + } + } + } + } + } +} diff --git a/app/src/main/java/com/lastwave/app/ui/player/PlayerHost.kt b/app/src/main/java/com/lastwave/app/ui/player/PlayerHost.kt index 25c68447ba..5cc5ffdc1b 100644 --- a/app/src/main/java/com/lastwave/app/ui/player/PlayerHost.kt +++ b/app/src/main/java/com/lastwave/app/ui/player/PlayerHost.kt @@ -835,6 +835,7 @@ internal fun ExpandedPlayer( onSetLyricsCentered = viewModel::setLyricsCentered, lyricsButtonsAutoHideSeconds = settings.lyricsButtonsAutoHideSeconds, translationLanguage = settings.translationLanguage, + nowPlayingMiniLyricsEnabled = settings.nowPlayingMiniLyricsEnabled, canvas = canvas, canvasEnabled = settings.canvasEnabled, canvasFullBleedEnabled = settings.canvasFullBleed, diff --git a/app/src/main/java/com/lastwave/app/ui/player/PlayerViewModel.kt b/app/src/main/java/com/lastwave/app/ui/player/PlayerViewModel.kt index 82879130fd..cb1f8f0a99 100644 --- a/app/src/main/java/com/lastwave/app/ui/player/PlayerViewModel.kt +++ b/app/src/main/java/com/lastwave/app/ui/player/PlayerViewModel.kt @@ -491,10 +491,11 @@ class PlayerViewModel @Inject constructor( player.chromeState.map { it.current }.distinctUntilChanged(), settingsPreferences.settings.map { it.wordByWordLyrics }.distinctUntilChanged(), ) { track, wordByWord -> track to wordByWord }.collect { (track, wordByWord) -> - val key = track?.let { "${it.videoId ?: ""}|${it.artist}|${it.title}|$wordByWord" } + val songKey = track?.let(::lyricsTrackKey) + val key = songKey?.let { "$it|$wordByWord" } if (key != currentTrackLyricsKey) { // Only the last field (word-by-word) differs on a same-song refresh. - val songChanged = key?.substringBeforeLast('|') != currentTrackLyricsKey?.substringBeforeLast('|') + val songChanged = songKey != currentTrackLyricsKey?.substringBeforeLast('|') currentTrackLyricsKey = key spotLyricsOverride = Pair(null, emptySet()) probeLyricsJob?.cancel() @@ -741,8 +742,12 @@ class PlayerViewModel @Inject constructor( val same = if (!wanted.videoId.isNullOrBlank() || !current?.videoId.isNullOrBlank()) { !wanted.videoId.isNullOrBlank() && wanted.videoId == current?.videoId } else { - current != null && current.title.equals(wanted.title, ignoreCase = true) && - current.artist.equals(wanted.artist, ignoreCase = true) + val wantedLocal = com.lastwave.app.data.generate.LocalAudioFormats.importedPathOrNull(wanted.playbackUrl) + val currentLocal = com.lastwave.app.data.generate.LocalAudioFormats.importedPathOrNull(current?.playbackUrl) + current != null && + current.title.equals(wanted.title, ignoreCase = true) && + current.artist.equals(wanted.artist, ignoreCase = true) && + (wantedLocal == null || currentLocal == null || wantedLocal == currentLocal) } if (!same) return } @@ -781,9 +786,10 @@ class PlayerViewModel @Inject constructor( } else result.lines.filterNot { com.lastwave.app.data.lyrics.LyricsSanitizer.shouldSuppress(it.text) } + val resolvedTrack = wanted ?: player.state.value.current if (result.isSynced && !result.isInstrumental) { // The OriginOS music card shows the same lyrics as this screen. - (wanted ?: player.state.value.current)?.let { + resolvedTrack?.let { com.lastwave.app.playback.OriginOsMusicCard.publishPlayerLyrics(it, lines) } } @@ -794,6 +800,7 @@ class PlayerViewModel @Inject constructor( plainLyrics = com.lastwave.app.data.lyrics.LyricsSanitizer.sanitizePlain(result.plainLyrics), isInstrumental = result.isInstrumental, source = result.source, + trackKey = resolvedTrack?.let(::lyricsTrackKey), ) } is LyricsResult.Empty -> { @@ -941,3 +948,9 @@ class PlayerViewModel @Inject constructor( } } } + +internal fun lyricsTrackKey(track: PlayableTrack): String { + val base = "${track.videoId ?: ""}|${track.artist}|${track.title}" + val localPath = com.lastwave.app.data.generate.LocalAudioFormats.importedPathOrNull(track.playbackUrl) + return if (localPath != null) "$base|$localPath" else base +} diff --git a/app/src/main/java/com/lastwave/app/ui/settings/SettingsScreen.kt b/app/src/main/java/com/lastwave/app/ui/settings/SettingsScreen.kt index 25dc5d31b2..86efa4a19f 100644 --- a/app/src/main/java/com/lastwave/app/ui/settings/SettingsScreen.kt +++ b/app/src/main/java/com/lastwave/app/ui/settings/SettingsScreen.kt @@ -1791,7 +1791,7 @@ fun SettingsScreen( item { Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { SectionLabel("Controls & Layout") - SettingsGroup(rowCount = 4) { index, position -> + SettingsGroup(rowCount = 5) { index, position -> when (index) { 0 -> SettingsActionCard( icon = Icons.Rounded.AutoAwesome, @@ -1820,6 +1820,17 @@ fun SettingsScreen( isHighlighted = (highlightedSettingId == "appearance.wavy_seekbar"), ) 2 -> SettingsToggleCard( + icon = Icons.Rounded.Lyrics, + iconContainer = MaterialTheme.colorScheme.tertiaryContainer, + iconTint = MaterialTheme.colorScheme.onTertiaryContainer, + title = stringResource(R.string.settings_now_playing_mini_lyrics), + subtitle = stringResource(R.string.settings_now_playing_mini_lyrics_sub), + checked = misc.nowPlayingMiniLyricsEnabled, + onCheckedChange = viewModel::setNowPlayingMiniLyricsEnabled, + position = position, + isHighlighted = (highlightedSettingId == "appearance.now_playing_mini_lyrics"), + ) + 3 -> SettingsToggleCard( icon = Icons.Rounded.PlayCircle, iconContainer = MaterialTheme.colorScheme.secondaryContainer, iconTint = MaterialTheme.colorScheme.onSecondaryContainer, diff --git a/app/src/main/java/com/lastwave/app/ui/settings/SettingsSearchComponents.kt b/app/src/main/java/com/lastwave/app/ui/settings/SettingsSearchComponents.kt index 87a765810d..9ae6bdd86a 100644 --- a/app/src/main/java/com/lastwave/app/ui/settings/SettingsSearchComponents.kt +++ b/app/src/main/java/com/lastwave/app/ui/settings/SettingsSearchComponents.kt @@ -285,7 +285,7 @@ internal fun getTargetSectionIndex(settingId: String?): Int { else -> 0 } SettingsTab.NOW_PLAYING -> when (entry.section) { - "Seekbar" -> 1 + "Seekbar", "Controls & Layout" -> 1 "Canvas" -> 2 else -> 0 } diff --git a/app/src/main/java/com/lastwave/app/ui/settings/SettingsSearchIndex.kt b/app/src/main/java/com/lastwave/app/ui/settings/SettingsSearchIndex.kt index 0db092452f..9d7f2ad421 100644 --- a/app/src/main/java/com/lastwave/app/ui/settings/SettingsSearchIndex.kt +++ b/app/src/main/java/com/lastwave/app/ui/settings/SettingsSearchIndex.kt @@ -810,6 +810,23 @@ object SettingsSearchIndex { type = EntryType.ACTION, ) ) + add( + SettingsEntry( + id = "appearance.now_playing_mini_lyrics", + title = "Mini lyrics", + subtitle = "Show the current synced lyric line above the progress bar", + keywords = listOf( + "mini lyrics", "now playing lyrics", "synced lyric", "current line", + "lyrics above progress", "player lyrics" + ), + icon = Icons.Rounded.Lyrics, + iconContainer = { MaterialTheme.colorScheme.tertiaryContainer }, + iconTint = { MaterialTheme.colorScheme.onTertiaryContainer }, + parentTab = SettingsTab.NOW_PLAYING, + section = "Controls & Layout", + type = EntryType.TOGGLE, + ) + ) add( SettingsEntry( id = "appearance.rotating_background", diff --git a/app/src/main/java/com/lastwave/app/ui/settings/SettingsViewModel.kt b/app/src/main/java/com/lastwave/app/ui/settings/SettingsViewModel.kt index 4869c49fa9..ecca541ecb 100644 --- a/app/src/main/java/com/lastwave/app/ui/settings/SettingsViewModel.kt +++ b/app/src/main/java/com/lastwave/app/ui/settings/SettingsViewModel.kt @@ -717,6 +717,10 @@ class SettingsViewModel @Inject constructor( settingsPreferences.setButtonNowPlayingEnabled(enabled) } + fun setNowPlayingMiniLyricsEnabled(enabled: Boolean) = launchSettingsAction("update mini lyrics setting") { + settingsPreferences.setNowPlayingMiniLyricsEnabled(enabled) + } + // ── Music Haptics (Apple Music-style rhythm synchronization) ── val isHardwareHapticGeneratorAvailable: Boolean diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index a7f0d7e8e9..fce7538a2e 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -172,6 +172,8 @@ Provider, style, sync offset, text size and display Now Playing Background, Monet colors, seekbar and canvas + Mini lyrics + Show the current synced lyric line above the progress bar Tried first for every song. If it returns nothing, the app automatically falls through to the other providers. Equalizer Shape your sound across 15 frequencies @@ -987,6 +989,7 @@ Seek rewind Seek forward Show lyrics + Open full lyrics Delete Menu diff --git a/app/src/test/java/com/lastwave/app/data/local/NowPlayingMiniLyricsPreferenceTest.kt b/app/src/test/java/com/lastwave/app/data/local/NowPlayingMiniLyricsPreferenceTest.kt new file mode 100644 index 0000000000..8f7c7d1583 --- /dev/null +++ b/app/src/test/java/com/lastwave/app/data/local/NowPlayingMiniLyricsPreferenceTest.kt @@ -0,0 +1,71 @@ +package com.lastwave.app.data.local + +import android.content.Context +import androidx.datastore.preferences.core.PreferenceDataStoreFactory +import com.google.common.truth.Truth.assertThat +import com.lastwave.app.ui.settings.EntryType +import com.lastwave.app.ui.settings.SettingsSearchIndex +import com.lastwave.app.ui.settings.SettingsTab +import com.lastwave.app.ui.settings.getTargetSectionIndex +import io.mockk.mockk +import java.io.File +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder + +class NowPlayingMiniLyricsPreferenceTest { + + @get:Rule + val tmpDir = TemporaryFolder() + + @Test + fun miscSettings_defaultsMiniLyricsToOptInFalse() { + assertThat(MiscSettings().nowPlayingMiniLyricsEnabled).isFalse() + } + + @Test + fun settingsPreferences_persistsMiniLyricsToggle() = runBlocking { + val dsScope = CoroutineScope(Dispatchers.IO + SupervisorJob()) + try { + val dataStore = PreferenceDataStoreFactory.create( + scope = dsScope, + produceFile = { File(tmpDir.root, "mini_lyrics_prefs.preferences_pb") }, + ) + val prefs = SettingsPreferences(dataStore, mockk(relaxed = true)) + + assertThat(prefs.settings.first().nowPlayingMiniLyricsEnabled).isFalse() + + prefs.setNowPlayingMiniLyricsEnabled(true) + val enabled = withTimeout(5_000L) { + prefs.settings.first { it.nowPlayingMiniLyricsEnabled } + } + assertThat(enabled.nowPlayingMiniLyricsEnabled).isTrue() + + prefs.setNowPlayingMiniLyricsEnabled(false) + val disabled = withTimeout(5_000L) { + prefs.settings.first { !it.nowPlayingMiniLyricsEnabled } + } + assertThat(disabled.nowPlayingMiniLyricsEnabled).isFalse() + } finally { + dsScope.cancel() + } + } + + @Test + fun settingsSearchIndex_indexesMiniLyricsUnderNowPlayingControls() { + val entry = SettingsSearchIndex.allEntries.firstOrNull { + it.id == "appearance.now_playing_mini_lyrics" + } + assertThat(entry).isNotNull() + assertThat(entry!!.parentTab).isEqualTo(SettingsTab.NOW_PLAYING) + assertThat(entry.type).isEqualTo(EntryType.TOGGLE) + assertThat(getTargetSectionIndex(entry.id)).isEqualTo(1) + } +} diff --git a/app/src/test/java/com/lastwave/app/ui/player/NowPlayingMiniLyricsTest.kt b/app/src/test/java/com/lastwave/app/ui/player/NowPlayingMiniLyricsTest.kt new file mode 100644 index 0000000000..787849a606 --- /dev/null +++ b/app/src/test/java/com/lastwave/app/ui/player/NowPlayingMiniLyricsTest.kt @@ -0,0 +1,136 @@ +package com.lastwave.app.ui.player + +import com.google.common.truth.Truth.assertThat +import com.lastwave.app.data.lyrics.LyricLine +import com.lastwave.app.data.lyrics.LyricSyllable +import com.lastwave.app.playback.PlayableTrack +import org.junit.Test + +class NowPlayingMiniLyricsTest { + + private val sampleLines = listOf( + LyricLine(timeMs = 0L, durationMs = 0L, text = "One short line for the first verse"), + LyricLine(timeMs = 8_000L, durationMs = 0L, text = "This longer second line should wrap neatly above the progress bar"), + LyricLine(timeMs = 16_000L, durationMs = 0L, text = "The third line follows the playback position"), + ) + + @Test + fun eligibleSyncedLines_returnsLinesOnlyForSyncedMatchingTrack() { + val trackKey = "|Artist|Title|/sdcard/Music/a.flac" + val synced = LyricsUiState.Success(lines = sampleLines, isSynced = true, trackKey = trackKey) + assertThat(eligibleSyncedLines(synced, trackKey)).isEqualTo(sampleLines) + + assertThat(eligibleSyncedLines(LyricsUiState.Idle, trackKey)).isNull() + assertThat(eligibleSyncedLines(LyricsUiState.Loading, trackKey)).isNull() + assertThat(eligibleSyncedLines(LyricsUiState.Empty, trackKey)).isNull() + assertThat(eligibleSyncedLines(LyricsUiState.Error("boom"), trackKey)).isNull() + + val plain = LyricsUiState.Success(lines = emptyList(), isSynced = false, plainLyrics = "Plain", trackKey = trackKey) + assertThat(eligibleSyncedLines(plain, trackKey)).isNull() + + val instrumental = LyricsUiState.Success(lines = sampleLines, isSynced = true, isInstrumental = true, trackKey = trackKey) + assertThat(eligibleSyncedLines(instrumental, trackKey)).isNull() + } + + @Test + fun eligibleSyncedLines_rejectsStaleLyricsFromPreviousTrack() { + val oldKey = "|Artist|Song A|/sdcard/Music/a.flac" + val newKey = "|Artist|Song B|/sdcard/Music/b.flac" + val stale = LyricsUiState.Success(lines = sampleLines, isSynced = true, trackKey = oldKey) + + assertThat(eligibleSyncedLines(stale, newKey)).isNull() + } + + @Test + fun resolveMiniLyricsLine_selectsActiveLineAndHandlesSeekForwardAndBack() { + val stage = buildLyricsStage(sampleLines) + + assertThat(resolveMiniLyricsLine(stage, 0L)?.text).isEqualTo(sampleLines[0].text) + assertThat(resolveMiniLyricsLine(stage, 7_999L)?.lineIndex).isEqualTo(0) + + // Seek forward to second line + val second = resolveMiniLyricsLine(stage, 8_000L) + assertThat(second?.lineIndex).isEqualTo(1) + assertThat(second?.text).isEqualTo(sampleLines[1].text) + + // Seek forward to third line + assertThat(resolveMiniLyricsLine(stage, 16_500L)?.lineIndex).isEqualTo(2) + + // Seek back to first line + assertThat(resolveMiniLyricsLine(stage, 3_000L)?.lineIndex).isEqualTo(0) + } + + @Test + fun resolveMiniLyricsLine_respectsPositiveAndNegativeLyricsOffset() { + val stage = buildLyricsStage(sampleLines) + + // +1000ms offset advances to line 2 at 7000ms playback + assertThat(resolveMiniLyricsLine(stage, positionMs = 7_000L, lyricsOffsetMs = 1_000L)?.lineIndex).isEqualTo(1) + + // -1000ms offset holds line 1 at 8500ms playback + assertThat(resolveMiniLyricsLine(stage, positionMs = 8_500L, lyricsOffsetMs = -1_000L)?.lineIndex).isEqualTo(0) + + // Negative effective position before first line returns null + assertThat(resolveMiniLyricsLine(stage, positionMs = 200L, lyricsOffsetMs = -500L)).isNull() + } + + @Test + fun resolveMiniLyricsLine_hidesDuringIntroAndInstrumentalInterlude() { + val lines = listOf( + LyricLine(timeMs = 5_000L, durationMs = 2_000L, text = "First line"), + LyricLine(timeMs = 13_000L, durationMs = 2_000L, text = "After interlude"), + ) + val stage = buildLyricsStage(lines) + + // During LyricIntro (0..4999) + assertThat(resolveMiniLyricsLine(stage, 2_000L)).isNull() + // First line active (5000..6999) + assertThat(resolveMiniLyricsLine(stage, 5_500L)?.text).isEqualTo("First line") + // During LyricInterlude (7000..12999) + assertThat(resolveMiniLyricsLine(stage, 9_000L)).isNull() + // Line after interlude (13000+) + assertThat(resolveMiniLyricsLine(stage, 13_000L)?.text).isEqualTo("After interlude") + } + + @Test + fun resolveMiniLyricsLine_keepsLeadLineOverNestedBackingVocalAndDetectsRtl() { + val lines = listOf( + LyricLine( + timeMs = 1_000L, + durationMs = 3_000L, + text = "Hold on", + syllables = listOf( + LyricSyllable(1_000L, 500L, "Hold"), + LyricSyllable(1_500L, 500L, "on"), + ), + ), + LyricLine( + timeMs = 2_000L, + durationMs = 1_000L, + text = "(ooh)", + syllables = listOf(LyricSyllable(2_000L, 1_000L, "(ooh)", isBackground = true)), + ), + LyricLine(timeMs = 5_000L, durationMs = 2_000L, text = "שלום עולם"), + ) + val stage = buildLyricsStage(lines) + + val lead = resolveMiniLyricsLine(stage, 2_500L) + assertThat(lead?.text).isEqualTo("Hold on") + assertThat(lead?.isRtl).isFalse() + + val rtl = resolveMiniLyricsLine(stage, 5_500L) + assertThat(rtl?.text).isEqualTo("שלום עולם") + assertThat(rtl?.isRtl).isTrue() + } + + @Test + fun lyricsTrackKey_distinguishesLocalFilesAndKeepsRemoteStreamUpgradesStable() { + val localA = PlayableTrack(title = "Track", artist = "Unknown", playbackUrl = "file:///sdcard/Music/a.flac") + val localB = PlayableTrack(title = "Track", artist = "Unknown", playbackUrl = "file:///sdcard/Music/b.flac") + assertThat(lyricsTrackKey(localA)).isNotEqualTo(lyricsTrackKey(localB)) + + val remoteLow = PlayableTrack(title = "Song", artist = "Artist", videoId = "vid123", playbackUrl = "https://a.example/low") + val remoteHi = PlayableTrack(title = "Song", artist = "Artist", videoId = "vid123", playbackUrl = "https://b.example/flac") + assertThat(lyricsTrackKey(remoteLow)).isEqualTo(lyricsTrackKey(remoteHi)) + } +}