feat: shuffle the whole library and add a sleep timer
CI / build (push) Failing after 20m30s

Library screen: an "All music" card with Shuffle all, which builds a local
queue from every cached song so playback does not need a mood session.

Player bar: a sleep timer with 15/30/45/60/90 minute presets. The shared store
shows the countdown and pauses playback; on Android the pause is also scheduled
inside the media service through a custom session command, so it still fires
when the app is backgrounded or the task is swiped away.

Playback errors from the platform player now surface in the UI instead of
failing silently (for example when no audio device is available).

Tests cover shuffle-all, the empty library, timer expiry and cancelling it.
This commit is contained in:
TapTap committed 2026-11-15 08:09:02 +00:00
1 parent f8953fb200
commit c7c1d59b70
10 files changed
+478 -42

No files matched your search

@@ -20,5 +20,13 @@ interface AudioPlayer {
val canSeek: Boolean
fun seekTo(seconds: Double)
fun release()
/**
* Pauses playback after [seconds], or cancels a pending timer with null.
* Returns true when the platform scheduled the pause itself, so it still
* fires when the UI is gone (Android background playback). Callers keep
* their own countdown for the UI either way.
*/
fun scheduleSleepTimer(seconds: Long?): Boolean = false
}
@@ -48,6 +48,7 @@ data class AppState(
val playing: Boolean = false,
val positionSeconds: Double = 0.0,
val durationSeconds: Double = 0.0,
val sleepTimerRemainingSeconds: Long? = null,
val downloads: Set<String> = emptySet(),
val downloading: Set<String> = emptySet(),
val library: List<Song> = emptyList(),
@@ -75,6 +76,7 @@ class AppStore(
val state: StateFlow<AppState> = _state.asStateFlow()
private var pollJob: Job? = null
private var sleepJob: Job? = null
private var advancing = false
private var fetching = false
private var finishing = false
@@ -471,6 +473,71 @@ class AppStore(
}
}
/**
* Builds a local queue from the whole library, so playback does not depend on
* a mood session. Shuffled by default because "play everything" is most
* useful as a mix.
*/
fun playAll(shuffled: Boolean = true) {
val state = _state.value
if (state.library.isEmpty()) {
_state.update {
it.copy(
message = "The library is empty. Scan a music folder first.",
messageIsError = true,
messageId = it.messageId + 1,
)
}
return
}
scope.launch {
state.session?.let { runCatching { api.closeSession(it.id) } }
val queue = if (shuffled) state.library.shuffled(Random.Default) else state.library
_state.update { it.copy(session = null, queue = queue) }
playNext()
}
}
/**
* Pauses playback after [minutes] so the app does not keep playing while
* falling asleep. Passing null turns the timer off.
*/
fun setSleepTimer(minutes: Int?) {
sleepJob?.cancel()
sleepJob = null
if (minutes == null || minutes <= 0) {
player.scheduleSleepTimer(null)
_state.update { it.copy(sleepTimerRemainingSeconds = null) }
return
}
// Android hands the pause to the media service so it survives the UI
// being backgrounded or swiped away; the countdown below only drives
// the display and desktop/web playback.
player.scheduleSleepTimer(minutes * 60L)
var remaining = minutes * 60L
_state.update { it.copy(sleepTimerRemainingSeconds = remaining) }
sleepJob = scope.launch {
while (isActive && remaining > 0) {
delay(1_000)
remaining -= 1
val seconds = remaining.coerceAtLeast(0)
_state.update { it.copy(sleepTimerRemainingSeconds = seconds.takeIf { value -> value > 0 }) }
}
if (!isActive) return@launch
val wasPlaying = _state.value.playing
player.pause()
_state.update {
it.copy(
playing = false,
sleepTimerRemainingSeconds = null,
message = if (wasPlaying) "Sleep timer: playback paused" else null,
messageId = if (wasPlaying) it.messageId + 1 else it.messageId,
)
}
}
}
fun togglePlayPause() {
val state = _state.value
if (state.current == null) return
@@ -635,6 +702,7 @@ class AppStore(
fun release() {
pollJob?.cancel()
sleepJob?.cancel()
player.release()
}
@@ -696,12 +764,24 @@ class AppStore(
private fun startSong(song: Song) {
val localPath = storage.downloadPath(song.id)
finishing = false
player.play(
source = localPath ?: api.streamUrl(song.id),
song = song,
local = localPath != null,
artworkUri = api.coverUrl(song.albumId),
)
try {
player.play(
source = localPath ?: api.streamUrl(song.id),
song = song,
local = localPath != null,
artworkUri = api.coverUrl(song.albumId),
)
} catch (t: Throwable) {
_state.update {
it.copy(
playing = false,
message = "Playback failed: ${t.message ?: "unknown error"}",
messageIsError = true,
messageId = it.messageId + 1,
)
}
return
}
startPolling()
}
@@ -752,8 +832,19 @@ class AppStore(
private fun stopPlayback() {
pollJob?.cancel()
sleepJob?.cancel()
sleepJob = null
player.scheduleSleepTimer(null)
player.stop()
_state.update { it.copy(current = null, playing = false, queue = emptyList(), session = null) }
_state.update {
it.copy(
current = null,
playing = false,
queue = emptyList(),
session = null,
sleepTimerRemainingSeconds = null,
)
}
}
private fun cacheDetail(detail: MoodDetail) {
@@ -4,10 +4,13 @@ import androidx.compose.foundation.layout.Arrangement
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.fillMaxSize
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.shape.RoundedCornerShape
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
@@ -16,12 +19,15 @@ import androidx.compose.material.icons.rounded.DeleteOutline
import androidx.compose.material.icons.rounded.Download
import androidx.compose.material.icons.rounded.PlayArrow
import androidx.compose.material.icons.rounded.Search
import androidx.compose.material.icons.rounded.Shuffle
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
@@ -64,6 +70,41 @@ fun LibraryScreen(state: AppState, store: AppStore) {
)
}
item {
Surface(
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.surfaceVariant,
modifier = Modifier.fillMaxWidth(),
) {
Row(
modifier = Modifier.padding(16.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
Column(Modifier.weight(1f)) {
Text("All music", style = MaterialTheme.typography.titleMedium)
Text(
if (state.library.isEmpty()) {
"Nothing in the library yet"
} else {
"${state.library.size} tracks, shuffled into a queue"
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Button(
onClick = { store.playAll() },
enabled = state.library.isNotEmpty(),
) {
Icon(Icons.Rounded.Shuffle, contentDescription = null, modifier = Modifier.size(18.dp))
Spacer(Modifier.width(6.dp))
Text("Shuffle all")
}
}
}
}
if (state.searchResults.isNotEmpty()) {
item {
SectionTitle("Search results") {
@@ -1,6 +1,7 @@
package win.taptap.musicmanager.client.ui
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
@@ -10,10 +11,14 @@ import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.AddCircleOutline
import androidx.compose.material.icons.rounded.Bedtime
import androidx.compose.material.icons.rounded.Pause
import androidx.compose.material.icons.rounded.PlayArrow
import androidx.compose.material.icons.rounded.PlaylistAdd
import androidx.compose.material.icons.rounded.SkipNext
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
@@ -36,7 +41,9 @@ import win.taptap.musicmanager.client.store.AppStore
fun PlayerBar(state: AppState, store: AppStore) {
val song = state.current ?: return
var picker by remember { mutableStateOf(false) }
var sleepMenu by remember { mutableStateOf(false) }
var dragSeconds by remember(song.id) { mutableStateOf<Float?>(null) }
val sleepRemaining = state.sleepTimerRemainingSeconds
Surface(
color = MaterialTheme.colorScheme.surfaceVariant,
@@ -48,16 +55,58 @@ fun PlayerBar(state: AppState, store: AppStore) {
} else {
0f
}
Slider(
value = dragSeconds ?: progress,
onValueChange = { dragSeconds = it },
onValueChangeFinished = {
dragSeconds?.let { store.seekTo(it * state.durationSeconds) }
dragSeconds = null
},
enabled = store.canSeek(),
modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),
)
Row(
modifier = Modifier.fillMaxWidth().padding(start = 8.dp, end = 4.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Slider(
value = dragSeconds ?: progress,
onValueChange = { dragSeconds = it },
onValueChangeFinished = {
dragSeconds?.let { store.seekTo(it * state.durationSeconds) }
dragSeconds = null
},
enabled = store.canSeek(),
modifier = Modifier.weight(1f),
)
Box {
IconButton(onClick = { sleepMenu = true }) {
Icon(
Icons.Rounded.Bedtime,
contentDescription = "Sleep timer",
tint = if (sleepRemaining != null) {
MaterialTheme.colorScheme.primary
} else {
MaterialTheme.colorScheme.onSurfaceVariant
},
)
}
DropdownMenu(
expanded = sleepMenu,
onDismissRequest = { sleepMenu = false },
) {
listOf(15, 30, 45, 60, 90).forEach { minutes ->
DropdownMenuItem(
text = { Text("$minutes minutes") },
onClick = {
sleepMenu = false
store.setSleepTimer(minutes)
},
)
}
if (sleepRemaining != null) {
HorizontalDivider()
DropdownMenuItem(
text = { Text("Turn off") },
onClick = {
sleepMenu = false
store.setSleepTimer(null)
},
)
}
}
}
}
Row(
modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 8.dp, bottom = 8.dp),
@@ -80,9 +129,19 @@ fun PlayerBar(state: AppState, store: AppStore) {
overflow = TextOverflow.Ellipsis,
)
Text(
"${formatDuration(state.positionSeconds.toInt())} / ${formatDuration(state.durationSeconds.toInt())}",
buildString {
append(formatDuration(state.positionSeconds.toInt()))
append(" / ")
append(formatDuration(state.durationSeconds.toInt()))
if (sleepRemaining != null) {
append(" · sleep ")
append(formatDuration(sleepRemaining.toInt()))
}
},
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}