Native Android client for Spotify, built with Jetpack Compose
Kotlin ad-freeadblockandroidjetpack-composekotlinlyricsmusic-playermusic-videomyspotispotifyspotify-adblockerspotify-clientspotify-connectspotui
Fixes from Discord: the volume bar sets a Spotify Connect device's volume, the playlist Shuffle pill turns shuffle off instead of dealing again, the glass follows a new tab's page, covers in Add to another playlist, a search in Immersive Downloads, no double skip when a song ends while a skip waits or during a crossfade
kota-zo73c5314f5b1a
diff --git a/base/app/src/main/java/com/music/spotui/data/api/EditablePlaylists.kt b/base/app/src/main/java/com/music/spotui/data/api/EditablePlaylists.ktindex e54f6d49..ddec9e91 100644--- a/base/app/src/main/java/com/music/spotui/data/api/EditablePlaylists.kt+++ b/base/app/src/main/java/com/music/spotui/data/api/EditablePlaylists.kt@@ -37,6 +37,40 @@ object EditablePlaylists {EditablePlaylist(it.uri.substringAfterLast(':'), it.name, it.trackCount, it.images.best(160)?.url)}+ /**+ * [load] for the pickers that show covers. Reported: "Add to another playlist" showed grey+ * squares. Spotify's playlist list has no cover for a playlist without one of its own (the+ * mosaic of its albums); the library has it, so those are read from there, folders walked.+ */+ suspend fun loadWithCovers(): List<EditablePlaylist> {+ val list = load()+ if (list.all { it.imageUrl != null }) return list+ val covers = libraryCovers()+ return list.map { if (it.imageUrl != null) it else it.copy(imageUrl = covers["spotify:playlist:${it.id}"]) }+ }++ /** Playlist uri → cover, as the library shows them, folders included. */+ private suspend fun libraryCovers(): Map<String, String> {+ val api = MyspotiRuntime.api+ val out = HashMap<String, String>()+ suspend fun walk(folderUri: String?, depth: Int) {+ var offset = 0+ repeat(40) {+ val page = runCatching {+ api.library.items(filter = LibraryFilter.ALL, folderUri = folderUri, offset = offset, limit = 50)+ }.getOrNull() ?: return+ for (item in page.items) when (item.kind) {+ MediaKind.FOLDER -> if (depth < 5) walk(item.uri, depth + 1)+ MediaKind.PLAYLIST -> item.images.best(160)?.url?.let { out[item.uri] = it }+ else -> Unit+ }+ offset = page.nextOffset ?: return+ }+ }+ walk(null, 0)+ return out+ }+/*** One level of the library as Spotify shows it: its folders, then the playlists the user* can change, with their covers (Spotify's playlist list has none for mosaic covers;diff --git a/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt b/base/app/src/main/java/com/music/spotui/di/LocalPlayer.ktindex 1f2a5ec3..8066bfaf 100644--- a/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt+++ b/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt@@ -345,6 +345,14 @@ object LocalPlayer {}fun pause() { exo?.pause() }fun next() {+ // In the first half of a crossfade the main player is on the next song already, while the+ // screens (and the ear) are still on the one going out: a skip there went two songs on.+ // It lands on the song coming in, at full volume.+ if (outgoing != null && fadeProgress() < 0.5f) {+ com.music.spotui.extensions.Extensions.skipAsked("forward")+ log("skip during the crossfade: the song coming in plays")+ return endFade()+ }endFade()exo?.let {if (it.hasNextMediaItem()) { com.music.spotui.extensions.Extensions.skipAsked("forward"); it.seekToNextMediaItem() }diff --git a/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt b/base/app/src/main/java/com/music/spotui/di/SongPlayer.ktindex 4a82e8a9..47ceb4ec 100644--- a/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt+++ b/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt@@ -1283,9 +1283,21 @@ object SongPlayer {positionMs = 0LpositionAt = nowval shown = showSkipTarget()+ // Reported: one skip went two songs on. A song that ends while the skip waits its turn+ // (the device check, a command still running, a slow page) is left by the page on its+ // own, and the skip then left the next song too. The skip is for the song it was+ // tapped on: gone already, it is not sent.+ val tappedOn = api.player.state.value?.item?.uri// The device check after the skip, as for a resume: before it, a slow network held// every skip for the device list's round trip (up to DEVICES_WAIT_MS).- transport(waitReady = !stateSeen, checkAfter = true, done = { ok -> skipDone(shown, ok) }) { api.player.next() }+ transport(waitReady = !stateSeen, checkAfter = true, done = { ok -> skipDone(shown, ok) }) {+ val now = api.player.state.value?.item?.uri+ if (tappedOn != null && now != null && now != tappedOn) {+ app.myspoti.host.android.Logbook.log("next not sent: the song it was tapped on had already ended")+ return@transport+ }+ api.player.next()+ }return}burstAt = now@@ -1930,7 +1942,7 @@ object SongPlayer {runCatching { api.devices.refresh() }val active = api.devices.devices.value.firstOrNull { it.active }_activeDevice.value = active?.takeIf { !it.local }?.let { ConnectDevice(it.id, it.name, it.type, false, true) }- active?.volume?.let { if (SystemClock.elapsedRealtime() > volumeHoldUntil) remoteVolume = (it * 100).toInt().coerceIn(0, 100) }+ active?.volume?.let { if (SystemClock.elapsedRealtime() > volumeHoldUntil) _remoteVolume.intValue = (it * 100).toInt().coerceIn(0, 100) }PlaybackService.setPlaybackDevice(_activeDevice.value != null, remoteVolume)}}@@ -2035,16 +2047,31 @@ object SongPlayer {command { if (device.isSelf) api.devices.pullHere() else api.devices.transfer(device.id) }}- /** Volume (0..100) of the device that plays, as last reported. */- @Volatile var remoteVolume = 100- private set+ /** Volume (0..100) of the device that plays, as last reported. State: the player's volume bar follows it. */+ private val _remoteVolume = androidx.compose.runtime.mutableIntStateOf(100)+ val remoteVolume: Int get() = _remoteVolume.intValue@Volatile private var volumeHoldUntil = 0L- /** Set the volume of the device that plays (volume keys, system slider). */+ /**+ * The newest volume asked for, sent one at a time by [volumeSender]. A drag on the player's+ * volume bar asks for dozens of levels a second: sent each in its own command they could+ * reach the device out of order and leave it on an older level.+ */+ private val volumeToSend = kotlinx.coroutines.flow.MutableStateFlow<Int?>(null)+ private val volumeSender by lazy {+ scope.launch {+ volumeToSend.collect { v ->+ if (v != null) runCatching { api.player.setVolume(v / 100.0) }.onFailure { Log.w(TAG, "volume failed: ${it.message}") }+ }+ }+ }++ /** Set the volume of the device that plays (volume keys, system slider, the player's volume bar). */fun setRemoteVolume(volume: Int) {- remoteVolume = volume.coerceIn(0, 100)+ _remoteVolume.intValue = volume.coerceIn(0, 100)volumeHoldUntil = SystemClock.elapsedRealtime() + 1500- command { api.player.setVolume(remoteVolume / 100.0) }+ volumeSender+ volumeToSend.value = remoteVolumePlaybackService.setPlaybackDevice(_activeDevice.value != null, remoteVolume)}diff --git a/base/app/src/main/java/com/music/spotui/ui/components/AddCollectionToPlaylistSheet.kt b/base/app/src/main/java/com/music/spotui/ui/components/AddCollectionToPlaylistSheet.ktindex 7f6cdb84..3d2b6ff2 100644--- a/base/app/src/main/java/com/music/spotui/ui/components/AddCollectionToPlaylistSheet.kt+++ b/base/app/src/main/java/com/music/spotui/ui/components/AddCollectionToPlaylistSheet.kt@@ -61,7 +61,7 @@ fun AddCollectionToPlaylistSheet(sourceUri: String, title: String, onDismiss: ()var query by remember { mutableStateOf("") }var reading by remember { mutableStateOf(false) }var asking by remember { mutableStateOf<Pair<EditablePlaylist, MergePlan>?>(null) }- LaunchedEffect(Unit) { playlists = EditablePlaylists.load() }+ LaunchedEffect(Unit) { playlists = EditablePlaylists.loadWithCovers() }val shown = remember(playlists, query) {playlists.orEmpty().filter { "spotify:playlist:${it.id}" != sourceUri && matchesFind(query, it.name) }}diff --git a/base/app/src/main/java/com/music/spotui/ui/components/AddToPlaylistSheet.kt b/base/app/src/main/java/com/music/spotui/ui/components/AddToPlaylistSheet.ktindex eb61c0f7..0dbf5fff 100644--- a/base/app/src/main/java/com/music/spotui/ui/components/AddToPlaylistSheet.kt+++ b/base/app/src/main/java/com/music/spotui/ui/components/AddToPlaylistSheet.kt@@ -76,7 +76,7 @@ fun AddToPlaylistSheet(var query by remember { mutableStateOf("") }LaunchedEffect(Unit) {// Folders flattened: adding to a playlist does not need the folder tree.- playlists = EditablePlaylists.load()+ playlists = EditablePlaylists.loadWithCovers()}// Filtered in one pass; accent-insensitive like the other "find" fields of the app.val shown = remember(playlists, query) {diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveDownloadsScreen.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveDownloadsScreen.ktindex 6dda6c27..dac25cec 100644--- a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveDownloadsScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveDownloadsScreen.kt@@ -86,6 +86,10 @@ fun ImmersiveDownloadsScreen(navController: NavController) {val np by SongPlayer.nowPlayingval playingHere = LocalPlayer.active.value && LocalPlayer.contextName == titlevar menuSong by remember { mutableStateOf<SongsModel?>(null) }+ // Reported: the search of the Immersive look found songs in the whole catalogue, not here.+ // The page's own find field, as Local Files has.+ var find by remember { mutableStateOf("") }+ val shown = if (find.isBlank()) tracks else tracks.filter { com.music.spotui.ui.components.matchesFind(find, it.title, it.artist, it.album) }menuSong?.let { sel ->ImmersiveSongOptionsSheet(song = sel, navController = navController, context = context, onDismiss = { menuSong = null })}@@ -150,6 +154,13 @@ fun ImmersiveDownloadsScreen(navController: NavController) {modifier = Modifier.padding(bottom = 14.dp),)}+ if (tracks.isNotEmpty()) item(key = "downloads:find") {+ com.music.spotui.ui.immersive.components.ImmersiveSearchField(+ query = find, onQueryChange = { find = it }, onSubmit = {},+ placeholder = stringResource(R.string.immersive_detail_find),+ modifier = Modifier.padding(horizontal = Immersive.Gutter, vertical = 6.dp),+ )+ }// No extension gives download files: say it where downloads would fail.if (!com.music.spotui.extensions.Extensions.hasDownloadSource()) item(key = "source") {NoticeCard(@@ -199,7 +210,10 @@ fun ImmersiveDownloadsScreen(navController: NavController) {},)}- itemsIndexed(tracks, key = { _, t -> t.trackId }) { i, t ->+ if (shown.isEmpty() && find.isNotBlank()) item(key = "downloads:find-empty") {+ com.music.spotui.ui.immersive.components.ImmersiveMessageState(stringResource(R.string.assisted_curation_search_empty_view_no_result_title, find.trim()))+ }+ itemsIndexed(shown, key = { _, t -> t.trackId }) { i, t ->val current = LocalPlayer.active.value && np.uri == "local:${OfflineStore.localIdOf(t.trackId)}"val song = OfflineStore.toSong(t)Column(Modifier.animateItem()) {@@ -215,11 +229,12 @@ fun ImmersiveDownloadsScreen(navController: NavController) {song = song,playing = current && SongPlayer.isPlaying(),current = current,- onClick = { play(i) },+ // The whole list plays from this song, even when it is filtered.+ onClick = { play(tracks.indexOf(t).coerceAtLeast(0)) },onMore = { menuSong = song },)}- if (i < tracks.lastIndex) ImmersiveRowDivider(ImmersiveRowDividerInset)+ if (i < shown.lastIndex) ImmersiveRowDivider(ImmersiveRowDividerInset)}}}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/player/PlayerState.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/player/PlayerState.ktindex 0fb645e4..43e5be2a 100644--- a/base/app/src/main/java/com/music/spotui/ui/immersive/player/PlayerState.kt+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/player/PlayerState.kt@@ -105,7 +105,11 @@ internal fun rememberPlayerScrub(trackKey: Any, position: () -> Long, durationMsreturn scrub}-/** The volume bar's state: the system music level, tweened to what the system reports, followed under a finger. */+/**+ * The volume bar's state: the system music level, tweened to what the system reports, followed+ * under a finger. While a Spotify Connect device plays, the bar is that device's volume, as the+ * volume keys are (reported: the bar only changed the phone's volume).+ */@Stableinternal class PlayerVolume(private val audio: AudioManager,@@ -118,13 +122,22 @@ internal class PlayerVolume(var dragging by mutableStateOf(false)private set- fun read(): Float = audio.getStreamVolume(AudioManager.STREAM_MUSIC).toFloat() / max+ private val remote: Boolean get() = com.music.spotui.di.SongPlayer.activeDevice.value != null++ fun read(): Float =+ if (remote) com.music.spotui.di.SongPlayer.remoteVolume / 100f+ else audio.getStreamVolume(AudioManager.STREAM_MUSIC).toFloat() / maxfun drag(to: Float) {dragging = true// Follow the finger exactly; only external changes tween.scope.launch { level.snapTo(to) }- audio.setStreamVolume(AudioManager.STREAM_MUSIC, (to * max).roundToInt().coerceIn(0, max), 0)+ if (remote) {+ val v = (to * 100).roundToInt().coerceIn(0, 100)+ if (v != com.music.spotui.di.SongPlayer.remoteVolume) com.music.spotui.di.SongPlayer.setRemoteVolume(v)+ } else {+ audio.setStreamVolume(AudioManager.STREAM_MUSIC, (to * max).roundToInt().coerceIn(0, max), 0)+ }}fun release() {@@ -150,9 +163,12 @@ internal fun rememberPlayerVolume(): PlayerVolume {androidx.core.content.ContextCompat.registerReceiver(context, receiver, IntentFilter(VOLUME_CHANGED_ACTION), androidx.core.content.ContextCompat.RECEIVER_EXPORTED)onDispose { context.unregisterReceiver(receiver) }}- // Glide to the level the system reports, but never fight the finger.- LaunchedEffect(system) {- if (!volume.dragging) volume.level.animateTo(system, tween(durationMillis = 220, easing = FastOutSlowInEasing))+ // Read here so the bar follows a Connect device appearing and its reported volume.+ val remote = com.music.spotui.di.SongPlayer.activeDevice.value != null+ val remoteLevel = com.music.spotui.di.SongPlayer.remoteVolume+ // Glide to the level the system (or the device) reports, but never fight the finger.+ LaunchedEffect(system, remote, remoteLevel) {+ if (!volume.dragging) volume.level.animateTo(volume.read(), tween(durationMillis = 220, easing = FastOutSlowInEasing))}return volume}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveContextScreen.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveContextScreen.ktindex 0641ace8..1f6c6e1c 100644--- a/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveContextScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveContextScreen.kt@@ -407,8 +407,11 @@ private fun ImmersiveContextContent(navController: NavController, vm: ContextVieif (isThisContext) vm.playSmart(p, p.tracks.firstOrNull { it.id == currentSongId })}}- // What the Shuffle pill does: start the list shuffled, or, while it plays, step through- // shuffle → smart shuffle (playlists, Liked Songs) → off, as the Classic shuffle icon does.+ // What the Shuffle pill does: start the list shuffled, or, while it plays, turn shuffle on+ // or off. Reported (3 people): a tap on the lit pill stepped to smart shuffle, which deals+ // the queue again and starts the song over, so shuffle never seemed to turn off. Smart+ // shuffle has its own button under the pill (as the Classic page's shuffle icon, off is+ // one tap away from either).fun onShuffle() {if (p.tracks.isEmpty()) returnwhen {@@ -418,7 +421,6 @@ private fun ImmersiveContextContent(navController: NavController, vm: ContextVievm.play(p, p.tracks.random(), sort)}smart -> { SmartShuffle.on.value = null; playerVm.updateShuffleState(false) }- shuffle && SmartShuffle.canPlay(p.uri) -> toggleSmart()else -> playerVm.updateShuffleState(!shuffle)}}@@ -763,7 +765,7 @@ private fun ContextHeader(text = stringResource(R.string.immersive_shell_shuffle),icon = if (shuffled && smart) Icons.Rounded.AutoAwesome else Icons.Rounded.Shuffle,onClick = onShuffle,- // Lit while this list plays shuffled: a tap then steps to smart shuffle or off.+ // Lit while this list plays shuffled (or smart-shuffled): a tap then turns it off.filled = shuffled,modifier = Modifier.weight(1f),)diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/backdrops/LayerBackdropModifier.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/backdrops/LayerBackdropModifier.ktindex 9ec3815d..b446e09a 100644--- a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/backdrops/LayerBackdropModifier.kt+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/backdrops/LayerBackdropModifier.kt@@ -24,6 +24,7 @@ import androidx.compose.ui.node.invalidateDrawimport androidx.compose.ui.node.requireGraphicsContextimport androidx.compose.ui.platform.InspectorInfoimport com.music.spotui.ui.immersive.shell.backdrop.internal.recordLayer+import kotlinx.coroutines.launchfun Modifier.layerBackdrop(backdrop: LayerBackdrop): Modifier =this then LayerBackdropElement(backdrop)@@ -107,6 +108,19 @@ private class LayerBackdropNode(source.alpha = currentValueOf(LocalBackdropSourceAlpha)backdrop.sources.add(source)backdrop.moves+++ // Reported: after a tab change the glass kept what it showed until the page was scrolled.+ // The glass draws this page's recording inside its own blurred layer, which the renderer+ // does not redraw when only the page (or a row of it) changes: the recording is drawn in+ // two places and its damage counts in one. A page that just arrived fills in over its first+ // moments (its data, its covers), so the glass is redrawn on every frame while it settles.+ // Only then: a page animating on its own (a playing row) does not keep the blur running.+ coroutineScope.launch {+ val end = android.os.SystemClock.uptimeMillis() + SETTLE_MS+ while (android.os.SystemClock.uptimeMillis() < end) {+ androidx.compose.runtime.withFrameNanos { }+ (registeredIn ?: backdrop).moves+++ }+ }}override fun onGloballyPositioned(coordinates: LayoutCoordinates) {@@ -130,3 +144,6 @@ private class LayerBackdropNode(source.layer = null}}++/** How long a page that just arrived keeps redrawing the glass as it fills in. */+private const val SETTLE_MS = 3_000Ldiff --git a/base/app/src/main/java/com/music/spotui/ui/screens/LibraryExtras.kt b/base/app/src/main/java/com/music/spotui/ui/screens/LibraryExtras.ktindex 87923bff..f9eb9c0a 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/LibraryExtras.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/LibraryExtras.kt@@ -524,7 +524,7 @@ fun AddLocalToPlaylistSheet(track: LocalTrack, onDismiss: () -> Unit) {var spotifyLists by remember { mutableStateOf<List<com.music.spotui.data.api.EditablePlaylist>?>(null) }var creating by remember { mutableStateOf(false) }LaunchedEffect(Unit) {- spotifyLists = com.music.spotui.data.api.EditablePlaylists.load()+ spotifyLists = com.music.spotui.data.api.EditablePlaylists.loadWithCovers()}fun added(name: String) {Toast.makeText(context, context.getString(R.string.local_added_to, name), Toast.LENGTH_SHORT).show()