Skip to content

Native Android client for Spotify, built with Jetpack Compose

2.0.2-beta.7: real Liquid Glass with a live blur, songs no longer chained when Spotify drops several in a row (with the reason of every song change in diagnostic reports), Immersive queue that keeps dropped songs and moves them between sections, sharp Immersive covers, accent colour in Immersive, lyrics after a skip, previous after a skip, last session restored for extension and downloaded songs, clear button in search

kota-zo7108d8243963
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0d4aefa5..49838ec6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,17 @@
Each release on GitHub shows its section below. The app shows it too when it offers the update. Every detail: [docs/CHANGELOG-full.md](docs/CHANGELOG-full.md).
+## 2.0.2-beta.7
+
+- 💎 **Real Liquid Glass** (Immersive): lens refraction, specular rim and a live blur of what scrolls behind, now also on phones with system window blurs off (Android 13+; live blur on Android 12). Softer springs and press feedback across the look.
+- ⏭️ **Songs skipping on their own**: when Spotify drops several songs in a row, the app stops and tells you instead of chaining through your queue. Diagnostic reports now say why every song changed.
+- ↕️ **Immersive queue**: dragged songs stay where you drop them, move between "Next in queue" and "Next from", and the list scrolls at the edges.
+- 🖼️ **Sharp covers in Immersive** after opening the lyrics.
+- 🎨 **Accent colour** now applies to the Immersive look; no more click sound in its full-screen player; lyrics follow the song after a skip.
+- ⏮️ **Previous** goes back a song instead of restarting it when tapped right after a skip.
+- 🔁 **Reopening the app** brings back the song from an extension or a download, its queue and position.
+- ✖️ **Clear button** in search fields.
+
## 2.0.2-beta.6
- 🔔 **Update popup fixed**: it shows as soon as the app knows about the update, a stray tap no longer closes it, and after "Later" the update stays in Settings, About.
diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyPlayer.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyPlayer.kt
index 8ad24f76..05fd42c1 100644
--- a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyPlayer.kt
+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyPlayer.kt
@@ -443,6 +443,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
val s = _state.value
preloadNextSong(s, media)
tickCrossfade(s, media, now)
+ if (localMuted && s?.item?.uri != hushedUri) { hushedUri = s?.item?.uri; applyHush() }
if (tick % VOLUME_CHECK_TICKS == 0) guardVolume(s, media)
if (_adPlaying.value) {
val ad = adState
@@ -580,7 +581,8 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
runCatching { setVolume(wanted) }
}
// A fade that never came back: the element back to the page player's own volume.
- if (media != null && media.active != false && media.own > 0.001 && media.level < media.own * 0.5) {
+ // (Not while the song is hushed on purpose.)
+ if (!clipHushed && !localMuted && media != null && media.active != false && media.own > 0.001 && media.level < media.own * 0.5) {
bridge.logger?.invoke("page player silent during a song: level ${media.level} back to ${media.own}")
runCatching { restoreLevel() }
}
@@ -875,6 +877,36 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
}
}
+ private val skipChain = TrackChanges.Chain()
+ private val _skipChained = kotlinx.coroutines.flow.MutableSharedFlow<Unit>(extraBufferCapacity = 1)
+ /**
+ * The page moved on by itself through several songs after a few seconds each (it cannot play
+ * them: licences refused, a stream failing): it was paused, the UI says so.
+ */
+ val skipChained: kotlinx.coroutines.flow.SharedFlow<Unit> = _skipChained
+
+ /**
+ * One Logbook line for each change of song with the reason (a command, an ad, the song's end,
+ * or the page on its own), so a report of songs skipping says which. The page moving on by
+ * itself again and again is stopped instead of chained through the list.
+ */
+ private fun noteTrackChange(old: PlayerState?, s: PlayerState?, adJustEnded: Boolean) {
+ val from = old?.item ?: return
+ val to = s?.item ?: return
+ if (from.uri == to.uri || from.kind == ItemKind.AD || remoteActive) return
+ val now = System.currentTimeMillis()
+ val played = old.positionAt(now)
+ val sinceCommand = now - maxOf(userMoveAt, lastPlay?.third ?: 0L)
+ val cause = TrackChanges.cause(played, from.durationMs, sinceCommand, adJustEnded, crossfadeArmed)
+ bridge.logger?.invoke("track change: ${from.name} -> ${to.name} (${cause.text}, left at ${TrackChanges.clock(played)} of ${TrackChanges.clock(from.durationMs)}${if (playbackHeld()) ", playback held" else ""})")
+ if (playbackHeld()) { skipChain.reset(); return }
+ if (skipChain.record(cause, played, now)) {
+ bridge.logger?.invoke("skip chain: the page moved on by itself three times in a row after a few seconds each (now on ${to.name}): paused")
+ _skipChained.tryEmit(Unit)
+ scope.launch { runCatching { pause() } }
+ }
+ }
+
private fun onState(s: PlayerState?) {
stateSeq++
// Another song than the one a crossfade is fading out: the ramp up, at once (the
@@ -957,6 +989,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
refusalStep = 0
if (s?.item != null) lastSong = s
else if (lastTrackState?.item != null) lastSongUntil = System.currentTimeMillis()
+ noteTrackChange(lastTrackState, s, adJustEnded)
lastTrackState = s
_state.value = s
// Reported (2.0.2-beta.3, log seen): Spotify refusing the audio licences (429), the page
@@ -1062,8 +1095,29 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
* The song unheard on this phone while it keeps playing (the music video's own sound is heard
* instead, see the app's clip sound). Sent again on each new song: the element can change.
*/
- suspend fun setHushed(on: Boolean): Int =
- runCatching { bridge.call("media.hush", buildJsonObject { put("on", on) }).toString().trim('"').toIntOrNull() ?: 0 }.getOrDefault(0)
+ suspend fun setHushed(on: Boolean): Int {
+ clipHushed = on
+ return applyHush()
+ }
+
+ /**
+ * An extension plays the song itself and only mirrors it here (to count the listen): the page
+ * keeps playing, unheard. Sent again on a new song, whose element can change.
+ */
+ override suspend fun setLocalMute(on: Boolean) {
+ localMuted = on
+ hushedUri = if (on) _state.value?.item?.uri else null
+ applyHush()
+ }
+
+ override val localMute: Boolean get() = localMuted
+
+ @Volatile private var clipHushed = false
+ @Volatile private var localMuted = false
+ @Volatile private var hushedUri: String? = null
+
+ private suspend fun applyHush(): Int =
+ runCatching { bridge.call("media.hush", buildJsonObject { put("on", clipHushed || localMuted) }).toString().trim('"').toIntOrNull() ?: 0 }.getOrDefault(0)
private suspend fun muteForAd() = runCatching {
adMuted = true
diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/TrackChanges.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/TrackChanges.kt
new file mode 100644
index 00000000..f838425f
--- /dev/null
+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/TrackChanges.kt
@@ -0,0 +1,51 @@
+package app.myspoti.spotify
+
+/**
+ * Why the song the Web Player plays changed, for the Logbook (a skip report says nothing about
+ * it otherwise), and the guard against a page that chains through songs it cannot play.
+ */
+internal object TrackChanges {
+ /** A song this close to its end that changes has ended. */
+ const val ENDED_TAIL_MS = 4_000L
+ /** A command (ours or the user's) this recent explains the change. */
+ const val COMMAND_MS = 5_000L
+
+ enum class Cause(val text: String) {
+ COMMAND("after a command"),
+ AD("after an ad break"),
+ ENDED("the song ended"),
+ /** Nothing asked for it and the song had not ended: the page moved on by itself. */
+ OWN("the page moved on by itself"),
+ }
+
+ fun cause(playedMs: Long, durationMs: Long, sinceCommandMs: Long, afterAd: Boolean, crossfading: Boolean): Cause = when {
+ sinceCommandMs in 0..COMMAND_MS -> Cause.COMMAND
+ afterAd -> Cause.AD
+ crossfading || (durationMs > 0 && durationMs - playedMs <= ENDED_TAIL_MS) -> Cause.ENDED
+ else -> Cause.OWN
+ }
+
+ fun clock(ms: Long): String = "%d:%02d".format(ms / 60_000, ms / 1000 % 60)
+
+ /**
+ * Songs the page moved on from by itself after only a few seconds, in a row: it is skipping
+ * through songs it cannot play (licences refused, a market, a stream that fails), each
+ * reported as a skip by the users. [record] says when it is time to stop it.
+ */
+ class Chain(private val limit: Int = 3, private val windowMs: Long = 30_000, private val shortMs: Long = 10_000) {
+ private val times = ArrayDeque<Long>()
+
+ /** A change of [cause] after [playedMs] of the old song at [now]; true when the chain reached [limit]. */
+ fun record(cause: Cause, playedMs: Long, now: Long): Boolean {
+ // Anything but a short song left by the page itself breaks the chain.
+ if (cause != Cause.OWN || playedMs > shortMs) { times.clear(); return false }
+ times.addLast(now)
+ while (times.isNotEmpty() && now - times.first() > windowMs) times.removeFirst()
+ if (times.size < limit) return false
+ times.clear()
+ return true
+ }
+
+ fun reset() = times.clear()
+ }
+}
diff --git a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/TrackChangesTest.kt b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/TrackChangesTest.kt
new file mode 100644
index 00000000..bcd10a97
--- /dev/null
+++ b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/TrackChangesTest.kt
@@ -0,0 +1,55 @@
+package app.myspoti.spotify
+
+import app.myspoti.spotify.TrackChanges.Cause
+import org.junit.jupiter.api.Assertions.assertEquals
+import org.junit.jupiter.api.Assertions.assertFalse
+import org.junit.jupiter.api.Assertions.assertTrue
+import org.junit.jupiter.api.Test
+
+class TrackChangesTest {
+ private fun cause(played: Long, duration: Long = 200_000, since: Long = 60_000, ad: Boolean = false, fade: Boolean = false) =
+ TrackChanges.cause(played, duration, since, ad, fade)
+
+ @Test fun `a recent command explains the change`() = assertEquals(Cause.COMMAND, cause(7_000, since = 800))
+ @Test fun `a command long ago does not`() = assertEquals(Cause.OWN, cause(7_000, since = 20_000))
+ @Test fun `the end of the song`() = assertEquals(Cause.ENDED, cause(198_000))
+ @Test fun `a crossfade ends the song early`() = assertEquals(Cause.ENDED, cause(190_000, fade = true))
+ @Test fun `an ad break`() = assertEquals(Cause.AD, cause(30_000, ad = true))
+ @Test fun `unknown duration is not an end`() = assertEquals(Cause.OWN, cause(30_000, duration = 0))
+ @Test fun `a command wins over an ad`() = assertEquals(Cause.COMMAND, cause(30_000, since = 100, ad = true))
+
+ @Test fun `three short songs left by the page in a row`() {
+ val c = TrackChanges.Chain()
+ assertFalse(c.record(Cause.OWN, 400, 1_000))
+ assertFalse(c.record(Cause.OWN, 300, 3_000))
+ assertTrue(c.record(Cause.OWN, 500, 5_000))
+ }
+
+ @Test fun `the chain starts over after it fired`() {
+ val c = TrackChanges.Chain()
+ repeat(3) { c.record(Cause.OWN, 400, it * 1_000L) }
+ assertFalse(c.record(Cause.OWN, 400, 4_000))
+ }
+
+ @Test fun `a command breaks the chain`() {
+ val c = TrackChanges.Chain()
+ c.record(Cause.OWN, 400, 1_000); c.record(Cause.OWN, 400, 2_000)
+ assertFalse(c.record(Cause.COMMAND, 400, 3_000))
+ assertFalse(c.record(Cause.OWN, 400, 4_000))
+ }
+
+ @Test fun `a song that played a while breaks the chain`() {
+ val c = TrackChanges.Chain()
+ c.record(Cause.OWN, 400, 1_000); c.record(Cause.OWN, 400, 2_000)
+ assertFalse(c.record(Cause.OWN, 60_000, 3_000))
+ assertFalse(c.record(Cause.OWN, 400, 4_000))
+ }
+
+ @Test fun `changes too far apart are not a chain`() {
+ val c = TrackChanges.Chain()
+ assertFalse(c.record(Cause.OWN, 400, 0)); assertFalse(c.record(Cause.OWN, 400, 20_000))
+ assertFalse(c.record(Cause.OWN, 400, 40_000))
+ }
+
+ @Test fun `clock`() = assertEquals("3:21", TrackChanges.clock(201_500))
+}
diff --git a/base/api/src/main/kotlin/app/myspoti/api/Api.kt b/base/api/src/main/kotlin/app/myspoti/api/Api.kt
index f7e80c7c..22ef3faf 100644
--- a/base/api/src/main/kotlin/app/myspoti/api/Api.kt
+++ b/base/api/src/main/kotlin/app/myspoti/api/Api.kt
@@ -58,6 +58,12 @@ interface Player {
suspend fun setVolume(level: Double)
/** Playback speed (podcasts): 0.5 to 3.5. */
suspend fun setSpeed(speed: Double)
+ /**
+ * Unheard on this phone while it keeps playing: an extension plays the song itself and only
+ * mirrors it here. The app then ignores this player's state ([localMute]).
+ */
+ suspend fun setLocalMute(on: Boolean) {}
+ val localMute: Boolean get() = false
}
interface Search {
diff --git a/base/app/src/main/java/com/music/spotui/data/api/SupportReminder.kt b/base/app/src/main/java/com/music/spotui/data/api/SupportReminder.kt
index ea0f3581..f2b94d38 100644
--- a/base/app/src/main/java/com/music/spotui/data/api/SupportReminder.kt
+++ b/base/app/src/main/java/com/music/spotui/data/api/SupportReminder.kt
@@ -48,6 +48,9 @@ object SupportReminder {
/** The accent chosen (applied only for supporters). */
var accent by mutableStateOf(Accent.GREEN)
private set
+ /** A colour was picked (green is also the default): the Immersive look has its own default accent until then. */
+ var accentChosen by mutableStateOf(false)
+ private set
var icon by mutableStateOf(Accent.GREEN)
private set
@@ -67,6 +70,7 @@ object SupportReminder {
val p = prefs(context)
storedLevel = runCatching { Level.valueOf(p.getString("level", "NONE")!!) }.getOrDefault(Level.NONE)
accent = Accent.entries.firstOrNull { it.key == p.getString("accent", "green") } ?: Accent.GREEN
+ accentChosen = p.contains("accent")
icon = Accent.entries.firstOrNull { it.key == p.getString("icon", "green") } ?: Accent.GREEN
}
@@ -87,6 +91,7 @@ object SupportReminder {
fun setAccent(context: Context, value: Accent) {
accent = value
+ accentChosen = true
prefs(context).edit().putString("accent", value.key).apply()
}
diff --git a/base/app/src/main/java/com/music/spotui/data/preferences/LastSession.kt b/base/app/src/main/java/com/music/spotui/data/preferences/LastSession.kt
new file mode 100644
index 00000000..30472dce
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/data/preferences/LastSession.kt
@@ -0,0 +1,35 @@
+package com.music.spotui.data.preferences
+
+import com.music.spotui.data.entity.SongsModel
+import kotlinx.serialization.builtins.ListSerializer
+import kotlinx.serialization.json.Json
+
+// The last session's queue and the rule that decides who wins at launch, kept pure so they
+// are tested without Android. The song itself lives in SongPlayer's "myspoti_last_track".
+
+object LastSession {
+ /** Where the saved session played: Spotify's own player, or the local player (an extension's stream, a download). */
+ const val SOURCE_SPOTIFY = "spotify"
+ const val SOURCE_LOCAL = "local"
+
+ private const val MAX_QUEUE = 100
+ private val json = Json { ignoreUnknownKeys = true; encodeDefaults = true }
+
+ /** The songs of the session's queue as stored; capped so the preferences stay small. */
+ fun encodeQueue(songs: List<SongsModel>): String =
+ json.encodeToString(ListSerializer(SongsModel.serializer()), songs.take(MAX_QUEUE))
+
+ /** The stored queue, empty when missing or unreadable. */
+ fun decodeQueue(raw: String?): List<SongsModel> {
+ if (raw.isNullOrBlank()) return emptyList()
+ return runCatching { json.decodeFromString(ListSerializer(SongsModel.serializer()), raw) }.getOrDefault(emptyList())
+ }
+
+ /**
+ * Spotify's state at launch is older than the session saved from the local player: it still
+ * shows the song played before and must not replace it. A state stamped after the save
+ * (another device played since) or one that plays is real and wins.
+ */
+ fun engineStateIsStale(savedSource: String, savedAtMs: Long, engineTimestampMs: Long, enginePaused: Boolean): Boolean =
+ savedSource == SOURCE_LOCAL && enginePaused && engineTimestampMs <= savedAtMs
+}
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.kt
index c816f9c4..7398a913 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
@@ -43,6 +43,7 @@ object LocalPlayer {
val contextUri: String get() = if (current()?.let { it in radioSongs } == true) "" else listUri
private var listUri: String = ""
private var exo: ExoPlayer? = null
+ private val errors = StreamErrors()
@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
private fun build(main: Boolean): ExoPlayer = ExoPlayer.Builder(Graph.app)
@@ -72,6 +73,7 @@ object LocalPlayer {
}
override fun onIsPlayingChanged(isPlaying: Boolean) {
log("isPlaying $isPlaying at ${p.currentPosition} ms")
+ if (isPlaying) errors.played()
if (isPlaying) tick.run()
}
override fun onPlaybackSuppressionReasonChanged(reason: Int) =
@@ -87,18 +89,39 @@ object LocalPlayer {
}
// A song whose audio an extension did not give or that would not play (audio-source
- // hook) is never skipped silently: Spotify plays it, where it was, and goes on.
+ // hook) is never skipped silently: asked again once if the stream itself failed,
+ // then Spotify plays it, where it was, and goes on; a queue that keeps failing stops.
override fun onPlayerError(error: androidx.media3.common.PlaybackException) {
log("error ${error.errorCodeName}: ${generic(error.cause?.toString() ?: error.message.orEmpty())}")
val item = p.currentMediaItem?.localConfiguration?.uri ?: return
if (item.scheme != com.music.spotui.extensions.ExtensionAudio.SCHEME) return
val t = current() ?: return
+ val noAudio = com.music.spotui.extensions.AudioRoute.isNoAudio(error)
+ // No extension had it (the data source already asked twice): Spotify, no new ask.
+ val again = errors.alreadyRetried(item.toString())
+ if (!noAudio && !again) {
+ log("${t.title}: the stream failed, the extensions are asked again once")
+ val at = p.currentPosition
+ prefetch.launch {
+ runCatching { com.music.spotui.extensions.ExtensionAudio.resolve(item, again = true) }
+ handler.post { if (exo === p && p.currentMediaItem?.localConfiguration?.uri == item) { p.prepare(); p.seekTo(at); p.play() } }
+ }
+ return
+ }
if (SongPlayer.playUnavailableOnSpotify(t, p.currentPosition)) return
- if (!p.hasNextMediaItem()) return
- log("skipped ${t.title}: no extension had it and Spotify cannot play it now")
- p.seekToNextMediaItem()
- p.prepare()
- p.play()
+ when (errors.failed(item.toString(), p.hasNextMediaItem())) {
+ StreamErrors.Step.SKIP -> {
+ log("skipped ${t.title}: no extension had it and Spotify cannot play it now")
+ android.widget.Toast.makeText(Graph.app, Graph.app.getString(app.myspoti.engine.R.string.song_unavailable_skipped, t.title), android.widget.Toast.LENGTH_SHORT).show()
+ p.seekToNextMediaItem()
+ p.prepare()
+ p.play()
+ }
+ else -> {
+ log("stopped on ${t.title}: it cannot be played, and the songs after it failed too or none follows")
+ android.widget.Toast.makeText(Graph.app, Graph.app.getString(app.myspoti.engine.R.string.song_unavailable, t.title), android.widget.Toast.LENGTH_LONG).show()
+ }
+ }
}
})
exo = p
@@ -182,6 +205,8 @@ object LocalPlayer {
if (!active.value) return
endFade()
active.value = false
+ // A page left muted by an extension's mirror must not stay silent once Spotify plays again.
+ SongPlayer.unmuteMirror()
forgetRadio(); continues = false
exo?.let { it.stop(); it.clearMediaItems() }
tracks.clear(); unshuffled = null
@@ -347,27 +372,19 @@ object LocalPlayer {
* queue (queued, or the list's songs), as a drag in the queue does.
*/
fun moveBeside(from: Int, target: Int, after: Boolean) {
- if (exo == null) return
- if (from !in tracks.indices || target !in tracks.indices || from == target) return
+ val p = exo ?: return
+ val (order, toQueue) = LocalQueueOrder.moveBeside(tracks.toList(), p.currentMediaItemIndex, from, target, after, isQueued) ?: return
val t = tracks[from]
- if (tracks[target] in queued) queued += t else queued -= t
- val order = tracks.toMutableList().apply { removeAt(from) }
- val at = order.indexOfFirst { it === tracks[target] }
- order.add(if (after) at + 1 else at, t)
- val playing = current()
- arrange(LocalQueueOrder.settle(order, order.indexOfFirst { it === playing }, isQueued))
+ if (toQueue) queued += t else queued -= t
+ arrange(order)
}
/** Moves the song at [from] into the queued songs: first ([target] null), else beside [target]. */
fun moveIntoQueue(from: Int, target: Int?, after: Boolean) {
val p = exo ?: return
- if (from !in tracks.indices) return
if (target != null) return moveBeside(from, target, after)
- val t = tracks[from]
- queued += t
- val cur = p.currentMediaItemIndex
- val order = tracks.toMutableList().apply { removeAt(from) }
- order.add((if (from > cur) cur + 1 else cur).coerceIn(0, order.size), t)
+ val order = LocalQueueOrder.moveToFront(tracks.toList(), p.currentMediaItemIndex, from) ?: return
+ queued += tracks[from]
arrange(order)
}
@@ -406,10 +423,14 @@ object LocalPlayer {
/** Puts the player's items in [target]'s order with moves only, so the current song keeps playing. */
private fun arrange(target: List<LocalTrack>) {
val p = exo ?: return
- for (k in target.indices) {
- val j = (k until tracks.size).firstOrNull { tracks[it] === target[k] } ?: continue
- if (j != k) { p.moveMediaItem(j, k); tracks.add(k, tracks.removeAt(j)) }
- }
+ // The player reports each single move: the queue shown would flicker through half-moved orders.
+ arranging = true
+ try {
+ for (k in target.indices) {
+ val j = (k until tracks.size).firstOrNull { tracks[it] === target[k] } ?: continue
+ if (j != k) { p.moveMediaItem(j, k); tracks.add(k, tracks.removeAt(j)) }
+ }
+ } finally { arranging = false }
publish()
}
@@ -515,8 +536,10 @@ object LocalPlayer {
/** Player.PLAY_WHEN_READY_CHANGE_REASON_*, from 1. */
private val PLAY_WHEN_READY_REASONS = listOf("asked", "audio focus lost", "audio becoming noisy", "remote", "end of item", "suppressed too long")
+ private var arranging = false
+
private fun publish() {
- if (!active.value) return
+ if (!active.value || arranging) return
val t = current() ?: return
// A queued song that started (or was skipped past) leaves the queue: it plays from there now.
if (t in queued) playingQueued = t
diff --git a/base/app/src/main/java/com/music/spotui/di/LocalQueueOrder.kt b/base/app/src/main/java/com/music/spotui/di/LocalQueueOrder.kt
index d83757fa..f3982d8b 100644
--- a/base/app/src/main/java/com/music/spotui/di/LocalQueueOrder.kt
+++ b/base/app/src/main/java/com/music/spotui/di/LocalQueueOrder.kt
@@ -50,4 +50,29 @@ internal object LocalQueueOrder {
val at = rest.indexOfFirst { it === current }
return if (at < 0) queued + rest else rest.take(at + 1) + queued + rest.drop(at + 1)
}
+
+ /**
+ * The song at [from] dropped before / [after] the one at [target], into [target]'s part (queued
+ * or the list's). The new order and whether the song is queued now; null when nothing moves.
+ * [cur] is the current song's index: it keeps playing, and the queued songs stay right after it.
+ */
+ fun <T> moveBeside(order: List<T>, cur: Int, from: Int, target: Int, after: Boolean, isQueued: (T) -> Boolean): Pair<List<T>, Boolean>? {
+ if (from !in order.indices || target !in order.indices || from == target) return null
+ val t = order[from]
+ val toQueue = isQueued(order[target])
+ val rest = order.toMutableList().apply { removeAt(from) }
+ val at = rest.indexOfFirst { it === order[target] }
+ rest.add(if (after) at + 1 else at, t)
+ val playing = order.getOrNull(cur)
+ return settle(rest, rest.indexOfFirst { it === playing }, { x -> if (x === t) toQueue else isQueued(x) }) to toQueue
+ }
+
+ /** The song at [from] queued as the first queued one, right after the current song. */
+ fun <T> moveToFront(order: List<T>, cur: Int, from: Int): List<T>? {
+ if (from !in order.indices || from == cur) return null
+ val rest = order.toMutableList().apply { removeAt(from) }
+ val playing = order[cur]
+ rest.add(rest.indexOfFirst { it === playing } + 1, order[from])
+ return rest
+ }
}
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.kt
index cd402054..e2fff048 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
@@ -119,7 +119,7 @@ object SongPlayer {
@Volatile var currentQuality: String = ""
/** Queue items of the local player (downloads, Local Files). */
- private const val LOCAL = "local"
+ const val LOCAL = "local"
/** Spotify's real queue. */
data class QueueItem(val song: SongsModel, val uri: String, val uid: String, val provider: String)
@@ -221,6 +221,11 @@ object SongPlayer {
android.widget.Toast.makeText(Graph.app, app.myspoti.engine.R.string.play_refused_all, android.widget.Toast.LENGTH_LONG).show()
}
}
+ scope.launch {
+ MyspotiRuntime.spotify.player.skipChained.collect {
+ android.widget.Toast.makeText(Graph.app, app.myspoti.engine.R.string.songs_skipped_by_spotify, android.widget.Toast.LENGTH_LONG).show()
+ }
+ }
// Said once the page has asked its WebView: a device that cannot decrypt Spotify's streams
// plays nothing (no sound, 0:00), and nothing else in the app says why.
scope.launch {
@@ -243,8 +248,8 @@ object SongPlayer {
private object Controls : app.myspoti.host.android.PlaybackControls {
override fun play() = SongPlayer.play(by = "media session")
override fun pause() = SongPlayer.pause(by = "media session")
- override fun next() = SongPlayer.next()
- override fun previous() = SongPlayer.previous()
+ override fun next() = SongPlayer.next(by = "media session")
+ override fun previous() = SongPlayer.previous(by = "media session")
override fun seekTo(ms: Long) = SongPlayer.seekTo(ms)
override fun setLiked(liked: Boolean) = SongPlayer.setLiked(liked)
override fun playFromMediaId(mediaId: String) = AutoBrowser.play(mediaId)
@@ -257,6 +262,12 @@ object SongPlayer {
private fun lastTrackPrefs() = Graph.app.getSharedPreferences("myspoti_last_track", Context.MODE_PRIVATE)
private var savedLast = ""
+ // Who played the saved session and when it was saved: Spotify's state at launch is older than a
+ // local-player (extension / download) session saved after it, and must not replace it.
+ private var savedSource = com.music.spotui.data.preferences.LastSession.SOURCE_SPOTIFY
+ private var savedAtMs = 0L
+ /** A local-player session was put back paused at launch: play restarts it there, not through Spotify. */
+ private var restoredLocal = false
@Volatile private var resumeWhenReady = false
private fun restoreLastTrack(state: CurrentSongState) {
@@ -267,6 +278,9 @@ object SongPlayer {
if (uri.isBlank() || title.isBlank()) return
val id = trackIdOf(uri)
currentTrackId = id
+ savedSource = p.getString("source", null) ?: com.music.spotui.data.preferences.LastSession.SOURCE_SPOTIFY
+ savedAtMs = p.getLong("savedAt", 0L)
+ restoredLocal = savedSource == com.music.spotui.data.preferences.LastSession.SOURCE_LOCAL
durationMs = p.getLong("duration", 0L)
positionMs = p.getLong("position", 0L)
positionAt = SystemClock.elapsedRealtime()
@@ -282,14 +296,29 @@ object SongPlayer {
album = p.getString("album", "").orEmpty(),
)
state.likeState.value = p.getBoolean("liked", false)
+ if (restoredLocal) {
+ val rest = com.music.spotui.data.preferences.LastSession.decodeQueue(p.getString("queue", null))
+ if (rest.isNotEmpty()) {
+ _queue.value = EngineQueue(
+ current = rest.first(),
+ nextUp = rest.drop(1).map { QueueItem(it, SPOTIFY_TRACK_PREFIX + it.spotifyTrackId, "", "") },
+ )
+ }
+ }
}
/** Saved on track change and on play/pause (not on every state). */
- private fun saveLastTrack(song: SongsModel, uri: String, liked: Boolean) {
- val key = "$uri|$playing|$liked"
+ private fun saveLastTrack(
+ song: SongsModel, uri: String, liked: Boolean,
+ source: String = com.music.spotui.data.preferences.LastSession.SOURCE_SPOTIFY, queue: List<SongsModel>? = null,
+ ) {
+ val key = "$uri|$playing|$liked|$source"
if (uri.isBlank() || key == savedLast) return
savedLast = key
+ savedSource = source; savedAtMs = System.currentTimeMillis(); restoredLocal = false
lastTrackPrefs().edit()
+ .putString("source", source).putLong("savedAt", savedAtMs)
+ .putString("queue", queue?.let(com.music.spotui.data.preferences.LastSession::encodeQueue).orEmpty())
.putString("uri", uri).putString("title", song.title).putString("singer", song.singer)
.putString("album", song.album).putString("cover", song.coverUri)
.putLong("duration", durationMs).putLong("position", getCurrentPosition())
@@ -315,6 +344,7 @@ object SongPlayer {
synchronized(wantedSaved) { wantedSaved.clear() }
_queue.value = EngineQueue(); apiQueue = null; _nowPlaying.value = NowPlaying()
lastTrackPrefs().edit().clear().apply(); savedLast = ""; resumeWhenReady = false
+ savedSource = com.music.spotui.data.preferences.LastSession.SOURCE_SPOTIFY; savedAtMs = 0L; restoredLocal = false
_activeDevice.value = null; _sleepEndsAt.value = null; sleepTrackId = null; spotifyFallbackId = null
_video.value = VideoState(); videoFullscreen.value = false
boundState?.let { state ->
@@ -389,6 +419,8 @@ object SongPlayer {
if (s == null) return
stateSeen = true
if (LocalPlayer.active.value && engineWhileLocal(s)) return
+ // Spotify's server still shows the song played before the local-player session saved at exit.
+ if (com.music.spotui.data.preferences.LastSession.engineStateIsStale(savedSource, savedAtMs, s.timestampMs, s.isPaused)) return
if (resumeWhenReady) {
resumeWhenReady = false
// The Web Player restored the last session paused: play what was tapped.
@@ -512,6 +544,9 @@ object SongPlayer {
}
}
+ /** Back from the local player: the page is heard again if an extension's mirror had muted it. */
+ fun unmuteMirror() { if (api.player.localMute) command { api.player.setLocalMute(false) } }
+
/** Back from the local player: the Spotify queue again. */
fun restoreEngineQueue() = main.post { _queue.value = EngineQueue(); applyQueue(apiQueue) }
@@ -901,6 +936,7 @@ object SongPlayer {
app.myspoti.host.android.Logbook.log("play asked by $by")
if (routing) return // the song asked for starts by itself
if (LocalPlayer.active.value) { Haptics.click(); LocalPlayer.resume(); return }
+ if (resumeRestoredLocal()) { Haptics.click(); return }
if (resumeThroughExtensions()) { Haptics.click(); return }
// Smart shuffle was turned off while paused: the list's order comes back as it plays on.
plainOrderDue?.let { if (restorePlainOrder(it)) return }
@@ -939,8 +975,9 @@ object SongPlayer {
}
fun stop() = pause()
- fun next() {
+ fun next(by: String = "user") {
Log.d(TAG, "next tapped")
+ app.myspoti.host.android.Logbook.log("next asked by $by")
Haptics.click()
if (LocalPlayer.active.value) { LocalPlayer.next(); return }
com.music.spotui.extensions.Extensions.skipAsked("forward")
@@ -969,6 +1006,10 @@ object SongPlayer {
burstTaps = 1
pendingSkips = 0
skipSentAt = now
+ // The next song starts at 0: a previous tapped before Spotify reports must not read
+ // the old song's position and restart instead of going back.
+ positionMs = 0L
+ positionAt = now
transport(waitReady = !stateSeen) { api.player.next() }
return
}
@@ -999,6 +1040,7 @@ object SongPlayer {
skipSentAt = SystemClock.elapsedRealtime()
// The song [burstTaps] after the one playing at the first tap.
val target = burstUpcoming.getOrNull(burstTaps - 1)
+ app.myspoti.host.android.Logbook.log("next taps merged: $burstTaps skips${if (target != null) " in one jump to ${target.name}" else ", sent as a plain next"}")
transport(waitReady = !stateSeen) { if (target == null) api.player.next() else api.player.skipTo(target) }
if (target != null) {
burstTarget = target
@@ -1035,6 +1077,7 @@ object SongPlayer {
if (tap != tapSeq || SystemClock.elapsedRealtime() - burstAt < BURST_VERIFY_MS || !playing) return@Runnable
if (lastPageUri == t.uri || burstContext.isBlank()) return@Runnable
Log.d(TAG, "skips landed on $lastPageUri, not ${t.name}: playing it (${queueTag()})")
+ app.myspoti.host.android.Logbook.log("skips landed on another song than ${t.name}: it is played by name")
// In the order it was played in (a sorted list, a smart shuffle), and a song the user
// queued is not in the list: asking for it there would restart the list.
if (t.provider == "queue") return@Runnable
@@ -1064,7 +1107,8 @@ object SongPlayer {
return "shuffle=${api.player.state.value?.shuffle} next=[$up]"
}
- fun previous() {
+ fun previous(by: String = "user") {
+ app.myspoti.host.android.Logbook.log("previous asked by $by")
Haptics.click()
if (LocalPlayer.active.value) { LocalPlayer.previous(); return }
if (getCurrentPosition() <= 3_000) com.music.spotui.extensions.Extensions.skipAsked("backward")
@@ -1088,6 +1132,10 @@ object SongPlayer {
}
cancelBurst()
skipSentAt = SystemClock.elapsedRealtime()
+ // Either way the song now starts at 0 (a restart or the one before): without this the old
+ // position stays until Spotify reports, and a quick second previous would restart again.
+ positionMs = 0L
+ positionAt = SystemClock.elapsedRealtime()
transport(waitReady = !stateSeen) { api.player.previous() }
}
@@ -1757,11 +1805,20 @@ object SongPlayer {
command { api.player.clearQueue() }
}
- /** Move [item] just before / after [target] (same section of the queue). */
+ /**
+ * The local player's list index of a queue row, found now: the row's own uid is the index it had
+ * when the queue was reported, and a row shown in a just-dragged order carries an older one.
+ */
+ private fun localIndex(item: QueueItem): Int? {
+ val up = LocalPlayer.upcoming().filter { "local:${it.second.id}" == item.uri }
+ return (up.firstOrNull { it.first.toString() == item.uid } ?: up.firstOrNull())?.first
+ }
+
+ /** Move [item] just before / after [target]; a Spotify row stays in its section (see [moveIntoQueue]), a local one goes into [target]'s. */
fun reorder(item: QueueItem, target: QueueItem, after: Boolean) {
if (item.provider == LOCAL) {
- val from = item.uid.toIntOrNull() ?: return
- val t = target.uid.toIntOrNull() ?: return
+ val from = localIndex(item) ?: return
+ val t = localIndex(target) ?: return
LocalPlayer.moveBeside(from, t, after)
return
}
@@ -1784,7 +1841,11 @@ object SongPlayer {
* other (both at once left it in both places), then placed where it was dropped.
*/
fun moveIntoQueue(item: QueueItem, target: QueueItem?, after: Boolean) {
- if (item.provider == LOCAL) { item.uid.toIntOrNull()?.let { LocalPlayer.moveIntoQueue(it, target?.uid?.toIntOrNull(), after) }; return }
+ if (item.provider == LOCAL) {
+ val from = localIndex(item) ?: return
+ LocalPlayer.moveIntoQueue(from, target?.let { localIndex(it) ?: return }, after)
+ return
+ }
queueCommand {
val a = apiItem(item) ?: return@queueCommand
val first = apiQueue?.queued?.firstOrNull()
@@ -1849,6 +1910,8 @@ object SongPlayer {
*/
private fun engineWhileLocal(s: PlayerState): Boolean {
if (s.isPaused) return true
+ // An extension mirrors its own song in the page, muted: that is not the engine taking over.
+ if (api.player.localMute) return true
// The page's last states from before the pause reached it.
if (SystemClock.elapsedRealtime() - localStartedAt < LOCAL_GRACE_MS) return true
if (s.item?.uri == engineUriBeforeLocal && !engineRepaused) {
@@ -1894,9 +1957,31 @@ object SongPlayer {
val source = if (t.uri.scheme == "file") com.music.spotui.data.local.ListenHistory.Source.DOWNLOAD
else com.music.spotui.data.local.ListenHistory.Source.LOCAL
trackListen("local:${t.id}", song, source, isPlaying)
+ // An extension's stream or a download (it has a Spotify id): kept to come back to at launch.
+ if (likeUri != null) {
+ val rest = LocalPlayer.upcoming().map { localSong(it.second) }.filter { it.spotifyTrackId.isNotBlank() }
+ saveLastTrack(song.copy(coverUri = cover), likeUri, liked, com.music.spotui.data.preferences.LastSession.SOURCE_LOCAL, listOf(song) + rest)
+ }
}
}
+ /**
+ * Play on a session put back at launch: a download plays from its file, a song an extension
+ * streamed is asked again (its saved stream address may have expired) by [resumeThroughExtensions].
+ */
+ private fun resumeRestoredLocal(): Boolean {
+ if (!restoredLocal) return false
+ restoredLocal = false
+ val q = _queue.value
+ val songs = listOfNotNull(q.current) + q.nextUp.map { it.song }
+ val store = com.music.spotui.data.offline.OfflineStore
+ val downloads = store.list().associateBy { it.trackId }
+ if (songs.firstOrNull()?.spotifyTrackId?.let(downloads::containsKey) != true) return false
+ val list = songs.mapNotNull { downloads[it.spotifyTrackId] }.map(store::toLocalTrack)
+ LocalPlayer.play(list, 0, startMs = getCurrentPosition(), context = null)
+ return true
+ }
+
/** The Spotify uri of what the local player plays: a song an extension streams or a download; null for a file of the device. */
private fun localSpotifyUri(t: com.music.spotui.data.local.LocalTrack?): String? {
t ?: return null
diff --git a/base/app/src/main/java/com/music/spotui/di/StreamErrors.kt b/base/app/src/main/java/com/music/spotui/di/StreamErrors.kt
new file mode 100644
index 00000000..484f0c37
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/di/StreamErrors.kt
@@ -0,0 +1,28 @@
+package com.music.spotui.di
+
+/**
+ * What the local player does when a song an extension streams fails: asked once more (the answer
+ * kept may be stale), then moved past, but never through more than [MAX_SKIPS] songs in a row: a
+ * source that is down would otherwise chain through the whole queue, silently.
+ */
+class StreamErrors(private val maxSkips: Int = MAX_SKIPS) {
+ enum class Step { RETRY, SKIP, STOP }
+
+ private val retried = HashSet<String>()
+ private var skips = 0
+
+ /** True the first time a stream failure of [uri] is told: it is then asked again; false when it already was. */
+ fun alreadyRetried(uri: String): Boolean = !retried.add(uri)
+
+ /** A song failed: [uri] is its address, [hasNext] whether the queue goes on after it. */
+ fun failed(uri: String, hasNext: Boolean): Step = when {
+ retried.add(uri) -> Step.RETRY
+ hasNext && skips < maxSkips -> { skips++; Step.SKIP }
+ else -> Step.STOP
+ }
+
+ /** A song played: the failures before it are forgotten. */
+ fun played() { skips = 0; retried.clear() }
+
+ companion object { const val MAX_SKIPS = 2 }
+}
diff --git a/base/app/src/main/java/com/music/spotui/ui/components/AddSongsScreen.kt b/base/app/src/main/java/com/music/spotui/ui/components/AddSongsScreen.kt
index 66d69aa4..a5ada0c4 100644
--- a/base/app/src/main/java/com/music/spotui/ui/components/AddSongsScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/components/AddSongsScreen.kt
@@ -145,8 +145,7 @@ fun AddSongsScreen(page: ContextPageModel, onClose: (added: Boolean) -> Unit) {
modifier = Modifier.fillMaxWidth().focusRequester(focus),
)
}
- if (query.isNotEmpty()) Icon(Icons.Default.Close, contentDescription = null, tint = AppText,
- modifier = Modifier.size(20.dp).clickable { query = "" })
+ if (query.isNotEmpty()) SearchClearButton(focus, AppText) { query = "" }
}
val searching = query.isNotBlank()
val list = if (searching) results else suggestions
diff --git a/base/app/src/main/java/com/music/spotui/ui/components/FindInList.kt b/base/app/src/main/java/com/music/spotui/ui/components/FindInList.kt
index 2f3d850e..9afa5c27 100644
--- a/base/app/src/main/java/com/music/spotui/ui/components/FindInList.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/components/FindInList.kt
@@ -4,11 +4,13 @@ import com.music.spotui.ui.theme.AppText
import com.music.spotui.ui.theme.AppMuted
import androidx.compose.foundation.background
+import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardOptions
@@ -18,15 +20,22 @@ import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
+import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
+import androidx.compose.ui.focus.FocusRequester
+import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
+import androidx.compose.ui.platform.LocalSoftwareKeyboardController
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
+import app.myspoti.engine.R
import java.text.Normalizer
import java.util.Locale
@@ -57,9 +66,44 @@ fun matchesFind(query: String, vararg fields: String): Boolean {
return words.all { w -> fields.any { fold(it).contains(w) } }
}
+/**
+ * The "×" at the end of a search field, shown by the caller only while there is text. A tap clears
+ * the field through [onClear] (which resets the results), then puts the cursor back in the field
+ * with the keyboard up, so the next search can be typed straight away. [focusRequester] must be
+ * attached to that field.
+ */
+@Composable
+fun SearchClearButton(
+ focusRequester: FocusRequester,
+ tint: Color,
+ modifier: Modifier = Modifier,
+ onClear: () -> Unit,
+) {
+ val keyboard = LocalSoftwareKeyboardController.current
+ Box(
+ contentAlignment = Alignment.Center,
+ modifier = modifier
+ .size(32.dp)
+ .clip(CircleShape)
+ .clickable(role = Role.Button) {
+ onClear()
+ focusRequester.requestFocus()
+ keyboard?.show()
+ },
+ ) {
+ Icon(
+ Icons.Default.Close,
+ contentDescription = stringResource(R.string.immersive_shell_search_clear),
+ tint = tint,
+ modifier = Modifier.size(18.dp),
+ )
+ }
+}
+
/** The "Find in…" field at the top of a list of songs. */
@Composable
fun FindInListField(query: String, onQuery: (String) -> Unit, hint: String, modifier: Modifier = Modifier) {
+ val focus = remember { FocusRequester() }
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(Color(0x33FFFFFF)).padding(horizontal = 12.dp),
@@ -72,7 +116,7 @@ fun FindInListField(query: String, onQuery: (String) -> Unit, hint: String, modi
textStyle = TextStyle(color = AppText, fontSize = 15.sp),
cursorBrush = SolidColor(AppText),
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
- modifier = Modifier.weight(1f).padding(8.dp, 10.dp),
+ modifier = Modifier.weight(1f).padding(8.dp, 10.dp).focusRequester(focus),
decorationBox = { inner ->
Box {
if (query.isEmpty()) Text(hint, color = AppMuted, fontSize = 15.sp, maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis)
@@ -80,10 +124,7 @@ fun FindInListField(query: String, onQuery: (String) -> Unit, hint: String, modi
}
},
)
- if (query.isNotEmpty()) Icon(
- Icons.Default.Close, contentDescription = null, tint = AppMuted,
- modifier = Modifier.size(18.dp).pressable(0.92f) { onQuery("") },
- )
+ if (query.isNotEmpty()) SearchClearButton(focus, AppMuted) { onQuery("") }
}
}
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/ImmersiveTheme.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/ImmersiveTheme.kt
index f823e03b..d087478d 100644
--- a/base/app/src/main/java/com/music/spotui/ui/immersive/ImmersiveTheme.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/ImmersiveTheme.kt
@@ -27,8 +27,9 @@ object Immersive {
val Text = Color.White
val TextSecondary = Color.White.copy(alpha = 0.60f)
val TextTertiary = Color.White.copy(alpha = 0.38f)
- /** Myspoti's own accent in this look (links, the selected tab, toggles). */
- val Accent = Color(0xFFFF4F7B)
+ /** The look's own pink until an accent colour is chosen in Settings, then that colour (links, the selected tab, toggles). */
+ val Accent: Color get() =
+ if (com.music.spotui.data.api.SupportReminder.accentChosen) com.music.spotui.ui.theme.AppAccent else Color(0xFFFF4F7B)
val GlassFill = Color(0xFF2C2C34).copy(alpha = 0.88f)
val GlassEdge = Color.White.copy(alpha = 0.12f)
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/components/ImmersiveClickable.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/components/ImmersiveClickable.kt
index ead2dfd5..33610dd6 100644
--- a/base/app/src/main/java/com/music/spotui/ui/immersive/components/ImmersiveClickable.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/components/ImmersiveClickable.kt
@@ -36,7 +36,7 @@ fun Modifier.immersiveClickable(
val pressed by interaction.collectIsPressedAsState()
val scale by animateFloatAsState(
targetValue = if (pressed) pressedScale else 1f,
- animationSpec = spring(stiffness = 900f),
+ animationSpec = com.music.spotui.ui.immersive.motion.ImmersiveMotion.pressSpring(),
label = "immersiveClickableScale",
)
val haptics = LocalHapticFeedback.current
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/lyrics/ImmersiveLyricsPanel.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/lyrics/ImmersiveLyricsPanel.kt
index 9f99dc59..f3feaaf3 100644
--- a/base/app/src/main/java/com/music/spotui/ui/immersive/lyrics/ImmersiveLyricsPanel.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/lyrics/ImmersiveLyricsPanel.kt
@@ -128,11 +128,14 @@ fun ImmersiveLyricsPanel(modifier: Modifier = Modifier, contentPadding: PaddingV
val song = Graph.currentSongState
val title = song.title.value
val artist = song.singer.value
- LaunchedEffect(title, artist, SongPlayer.currentTrackId) {
+ // currentTrackId is plain data, not Compose state: a skip whose title and artist are the same
+ // (or that reports its id after them) would never re-run this. The playing item's uri is state.
+ val playingUri = SongPlayer.nowPlaying.value.uri
+ LaunchedEffect(title, artist, playingUri, SongPlayer.currentTrackId) {
SongPlayer.currentLyricsTrack()?.let(vm::load)
}
val state by vm.state.collectAsState()
- val trackKey = "${SongPlayer.currentTrackId}|$title|$artist"
+ val trackKey = "$playingUri|${SongPlayer.currentTrackId}|$title|$artist"
when (val current = state) {
is LyricsViewModel.State.Loading -> LyricsSkeleton(
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/lyrics/ImmersiveQueuePanel.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/lyrics/ImmersiveQueuePanel.kt
index c07a92e8..c71fb3f1 100644
--- a/base/app/src/main/java/com/music/spotui/ui/immersive/lyrics/ImmersiveQueuePanel.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/lyrics/ImmersiveQueuePanel.kt
@@ -6,7 +6,7 @@
* Changes: the sections (now playing, next in queue, next from the context), placement-only
* item motion and the fading edges, over Myspoti's SongPlayer.engineQueue. A row is removed
* by swiping it away, and shuffle and repeat sit in the header as in the queue sheet.
- * A handle on each upcoming row drags it within its section (SongPlayer.reorder); history and
+ * A handle on each upcoming row drags it within its section or between them (SongPlayer.reorder, moveIntoQueue); history and
* the autoplay heading are left out for now.
*/
package com.music.spotui.ui.immersive.lyrics
@@ -17,6 +17,7 @@ import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectDragGestures
+import androidx.compose.foundation.gestures.scrollBy
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
@@ -34,6 +35,7 @@ import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyItemScope
import androidx.compose.foundation.lazy.LazyListScope
+import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.layout.Column
@@ -69,10 +71,11 @@ import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableIntStateOf
-import androidx.compose.runtime.mutableStateMapOf
-import androidx.compose.runtime.snapshots.SnapshotStateMap
+import androidx.compose.runtime.derivedStateOf
+import androidx.compose.runtime.rememberUpdatedState
+import androidx.compose.runtime.withFrameNanos
+import kotlinx.coroutines.delay
import androidx.compose.ui.zIndex
-import kotlin.math.roundToInt
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalLayoutDirection
@@ -130,11 +133,21 @@ fun ImmersiveQueuePanel(modifier: Modifier = Modifier, contentPadding: PaddingVa
// Rows swiped away, hidden at once: the queue takes a moment to report the removal.
val removed = remember { mutableStateListOf<String>() }
LaunchedEffect(queue) { removed.clear() }
- // Rows just dragged, shown in their new order until the queue reports it.
- val reordered = remember { mutableStateMapOf<String, List<String>>() }
- LaunchedEffect(queue) { reordered.clear() }
- val queued = queue.queued.dedupedKeys("q").filter { it.first !in removed }.inOrder(reordered["q"])
- val nextUp = queue.nextUp.dedupedKeys("n").filter { it.first !in removed }.inOrder(reordered["n"])
+ // Rows just dragged, shown in their new order until the queue reports exactly that order (or
+ // PENDING_ORDER_MS passes): the reports in between are of the queue before the move.
+ var pending by remember { mutableStateOf<QueueDragMath.Pending<QRow>?>(null) }
+ LaunchedEffect(queue, pending) {
+ val p = pending ?: return@LaunchedEffect
+ if (p.over(queue.queued.map { it.uri }, queue.nextUp.map { it.uri }, queue.current?.url)) pending = null
+ }
+ LaunchedEffect(pending) {
+ val p = pending ?: return@LaunchedEffect
+ delay(PENDING_ORDER_MS)
+ if (pending === p) pending = null
+ }
+ val rows = shownRows(queue, pending, removed)
+ val queued = rows.filter { it.queued }
+ val nextUp = rows.filter { !it.queued }
val drag = remember { QueueDrag() }
val listState = rememberLazyListState()
@@ -143,6 +156,33 @@ fun ImmersiveQueuePanel(modifier: Modifier = Modifier, contentPadding: PaddingVa
val current = queue.current
val hasCurrent = song.title.value.isNotBlank() || current != null
+ val rowsNow by rememberUpdatedState(rows)
+ val hover by remember { derivedStateOf { hoverOf(listState, rowsNow, drag) } }
+ val hoverNow by rememberUpdatedState(hover)
+ val onDrop: (QRow) -> Unit = drop@{ row ->
+ val (queuedNew, nextNew, call) = dropPlan(rowsNow, row, hoverNow) ?: return@drop
+ pending = QueueDragMath.Pending(
+ queuedNew, nextNew, queuedNew.map { it.item.uri }, nextNew.map { it.item.uri }, queue.current?.url,
+ )
+ call()
+ }
+
+ // The finger near the top or bottom edge scrolls the list, the row staying under it.
+ val edge = with(LocalDensity.current) { 88.dp.toPx() }
+ val maxStep = with(LocalDensity.current) { 14.dp.toPx() }
+ val dragging = drag.key != null
+ LaunchedEffect(dragging) {
+ if (!dragging) return@LaunchedEffect
+ while (true) {
+ withFrameNanos { }
+ val info = listState.layoutInfo
+ val row = info.visibleItemsInfo.firstOrNull { it.key == drag.key } ?: continue
+ val y = row.offset + row.size / 2f + drag.offset
+ val step = QueueDragMath.edgeStep(y, info.viewportSize.height.toFloat(), edge, maxStep)
+ if (step != 0f) drag.offset += listState.scrollBy(step)
+ }
+ }
+
LazyColumn(
state = listState,
modifier = modifier
@@ -202,10 +242,10 @@ fun ImmersiveQueuePanel(modifier: Modifier = Modifier, contentPadding: PaddingVa
)
}
}
- queueSection("q", queued, removed, reordered, drag)
+ queueSection(queued, rowsNow, removed, drag, { hoverNow }, onDrop)
}
if (nextUp.isNotEmpty()) {
- item(key = "heading-next") {
+ item(key = HEADING_NEXT) {
QueueHeading(
title = if (contextName.isNotBlank()) {
stringResource(R.string.next_from, contextName)
@@ -215,7 +255,7 @@ fun ImmersiveQueuePanel(modifier: Modifier = Modifier, contentPadding: PaddingVa
modifier = Modifier.padding(top = 16.dp, bottom = 6.dp).then(queueMotion()),
)
}
- queueSection("n", nextUp, removed, reordered, drag)
+ queueSection(nextUp, rowsNow, removed, drag, { hoverNow }, onDrop)
}
if (!hasCurrent && queued.isEmpty() && nextUp.isEmpty()) {
item(key = "empty") {
@@ -230,24 +270,28 @@ fun ImmersiveQueuePanel(modifier: Modifier = Modifier, contentPadding: PaddingVa
}
}
-/** Keys each item by its own id, with a suffix where two rows share one: a lazy list throws on a repeat. */
-private fun List<SongPlayer.QueueItem>.dedupedKeys(prefix: String): List<Pair<String, SongPlayer.QueueItem>> {
- val used = HashSet<String>()
- return map { item ->
- val base = "$prefix:${item.uid}|${item.uri}"
- var key = base
- var repeat = 1
- while (!used.add(key)) key = base + "~" + repeat++
- key to item
- }
-}
+/** One queue row: [index] in the flat list (queued rows, then the context's), [key] stable across moves. */
+private data class QRow(val key: String, val item: SongPlayer.QueueItem, val queued: Boolean, val index: Int)
-private fun List<Pair<String, SongPlayer.QueueItem>>.inOrder(
- keys: List<String>?,
-): List<Pair<String, SongPlayer.QueueItem>> {
- if (keys == null || keys.size != size) return this
- val byKey = associateBy { it.first }
- return keys.mapNotNull { byKey[it] }.takeIf { it.size == size } ?: this
+private const val PENDING_ORDER_MS = 3_000L
+
+/**
+ * The rows to draw: the order just dropped while the engine has not reported it (its reports in
+ * between show the queue as it was, or a song out of one part and not yet in the other), else the
+ * queue as reported. Keyed by song and occurrence, not by the row id Spotify gives: that changes
+ * with a move, and a changed key makes the row vanish and reappear.
+ */
+private fun shownRows(queue: SongPlayer.EngineQueue, pending: QueueDragMath.Pending<QRow>?, removed: List<String>): List<QRow> {
+ if (pending != null) {
+ return (pending.queued + pending.next).filter { it.key !in removed }.mapIndexed { i, r -> r.copy(index = i) }
+ }
+ val seen = HashMap<String, Int>()
+ fun key(item: SongPlayer.QueueItem): String {
+ val count = seen.merge(item.uri, 1, Int::plus)!!
+ return if (count == 1) item.uri else "${item.uri}~$count"
+ }
+ val all = queue.queued.map { Triple(key(it), it, true) } + queue.nextUp.map { Triple(key(it), it, false) }
+ return all.filter { it.first !in removed }.mapIndexed { i, (k, item, queued) -> QRow(k, item, queued, i) }
}
/** The row being dragged by its handle: which one, and how far it is from its slot. */
@@ -256,28 +300,78 @@ private class QueueDrag {
var offset by mutableFloatStateOf(0f)
}
+/** Where the dragged row hovers: its flat index, the gap among the other rows, and which side of the context heading. */
+private data class Hover(val from: Int, val slot: Int, val aboveBoundary: Boolean)
+
+private const val HEADING_NEXT = "heading-next"
+
+private fun hoverOf(listState: LazyListState, rows: List<QRow>, drag: QueueDrag): Hover? {
+ val key = drag.key ?: return null
+ val from = rows.indexOfFirst { it.key == key }
+ if (from < 0) return null
+ val visible = listState.layoutInfo.visibleItemsInfo.associateBy { it.key }
+ val me = visible[key] ?: return null
+ val center = me.offset + me.size / 2f + drag.offset
+ // A row out of sight is above the dragged one's centre if it comes before it in the list.
+ val mids = rows.filter { it.index != from }.map { r ->
+ visible[r.key]?.let { it.offset + it.size / 2f } ?: if (r.index < from) Float.NEGATIVE_INFINITY else Float.POSITIVE_INFINITY
+ }
+ val heading = visible[HEADING_NEXT]
+ val firstNext = rows.firstOrNull { !it.queued }
+ val queuedOthers = rows.count { it.queued && it.index != from }
+ // With no queued row the heading is the queue's drop target: anywhere down to its foot counts.
+ val boundary = heading?.let { if (queuedOthers == 0) (it.offset + it.size).toFloat() else it.offset + it.size / 2f }
+ ?: firstNext?.let { visible[it.key]?.offset?.toFloat() }
+ var slot = QueueDragMath.slot(center, mids)
+ val above = boundary == null || center < boundary
+ val dragged = rows[from]
+ // A Spotify queued song cannot go back into "next from": it stays at the end of the queue.
+ if (dragged.queued && dragged.item.provider != SongPlayer.LOCAL) slot = minOf(slot, queuedOthers)
+ return Hover(from, slot, above || (dragged.queued && dragged.item.provider != SongPlayer.LOCAL))
+}
+
+/** What dropping [row] at [hover] does: the new queued and next rows, and the engine call that makes it so. */
+private fun dropPlan(rows: List<QRow>, row: QRow, hover: Hover?): Triple<List<QRow>, List<QRow>, () -> Unit>? {
+ hover ?: return null
+ val oq = rows.filter { it.queued && it.key != row.key }
+ val on = rows.filter { !it.queued && it.key != row.key }
+ val local = row.item.provider == SongPlayer.LOCAL
+ val place = QueueDragMath.held(QueueDragMath.place(hover.slot, oq.size, hover.aboveBoundary), oq.size, local, row.queued)
+ val (q, n) = QueueDragMath.apply(oq, on, row.copy(queued = place.toQueue), place)
+ if (q.map { it.key } == rows.filter { it.queued }.map { it.key } && n.map { it.key } == rows.filter { !it.queued }.map { it.key }) return null
+ val into = if (place.toQueue) oq else on
+ val (ti, after) = QueueDragMath.target(into.size, place.index) ?: (null to false)
+ val target = ti?.let { into[it].item }
+ val item = row.item
+ val call: () -> Unit = when {
+ place.toQueue && !row.queued ->
+ if (target == null) ({ SongPlayer.moveToQueueFront(item) }) else ({ SongPlayer.moveIntoQueue(item, target, after) })
+ target == null -> return null
+ else -> ({ SongPlayer.reorder(item, target, after) })
+ }
+ return Triple(q, n, call)
+}
+
/** One section's rows, each swiped away to remove it or dragged by its handle to move it. */
@OptIn(ExperimentalMaterial3Api::class)
private fun LazyListScope.queueSection(
- section: String,
- rows: List<Pair<String, SongPlayer.QueueItem>>,
+ section: List<QRow>,
+ all: List<QRow>,
removed: SnapshotStateList<String>,
- reordered: SnapshotStateMap<String, List<String>>,
drag: QueueDrag,
+ hover: () -> Hover?,
+ onDrop: (QRow) -> Unit,
) {
- items(rows.size, key = { rows[it].first }) { index ->
- val (key, item) = rows[index]
+ items(section.size, key = { section[it].key }) { i ->
+ val row = section[i]
+ val key = row.key
+ val item = row.item
val rowPx = with(LocalDensity.current) { Immersive.RowHeight.toPx() }
- val from = rows.indexOfFirst { it.first == drag.key }
- val slot = if (from < 0) -1 else (from + (drag.offset / rowPx).roundToInt()).coerceIn(0, rows.lastIndex)
- // Rows the dragged one passes step aside by one slot.
- val shift = when {
- from < 0 || key == drag.key -> 0f
- index in (from + 1)..slot -> -rowPx
- index in slot until from -> rowPx
- else -> 0f
- }
val dragged = key == drag.key
+ // Rows the dragged one passes step aside by one slot.
+ val shift = hover()?.let { h -> if (dragged) 0 else QueueDragMath.step(row.index, h.from, h.slot) } ?: 0
+ val dropNow by rememberUpdatedState(onDrop)
+ val rowNow by rememberUpdatedState(row)
val dismiss = rememberSwipeToDismissBoxState(confirmValueChange = { value ->
if (value == SwipeToDismissBoxValue.EndToStart) {
removed += key
@@ -292,18 +386,22 @@ private fun LazyListScope.queueSection(
enableDismissFromStartToEnd = false,
modifier = (if (dragged) Modifier else queueMotion())
.zIndex(if (dragged) 1f else 0f)
- .graphicsLayer { translationY = if (dragged) drag.offset else shift },
+ .graphicsLayer { translationY = if (dragged) drag.offset else shift * rowPx },
backgroundContent = {
- Box(
- Modifier.fillMaxSize().padding(end = 4.dp),
- contentAlignment = Alignment.CenterEnd,
- ) {
- Icon(
- Icons.Rounded.Close,
- contentDescription = stringResource(R.string.immersive_queue_remove),
- tint = Immersive.TextSecondary,
- modifier = Modifier.size(22.dp),
- )
+ // Drawn only while swiping: the row is transparent, so at rest this × showed
+ // through behind the drag handle.
+ if (dismiss.dismissDirection != SwipeToDismissBoxValue.Settled) {
+ Box(
+ Modifier.fillMaxSize().padding(end = 4.dp),
+ contentAlignment = Alignment.CenterEnd,
+ ) {
+ Icon(
+ Icons.Rounded.Close,
+ contentDescription = stringResource(R.string.immersive_queue_remove),
+ tint = Immersive.TextSecondary,
+ modifier = Modifier.size(22.dp),
+ )
+ }
}
},
) {
@@ -326,14 +424,10 @@ private fun LazyListScope.queueSection(
detectDragGestures(
onDragStart = { drag.key = key; drag.offset = 0f },
onDragEnd = {
- val start = rows.indexOfFirst { it.first == key }
- val to = (start + (drag.offset / rowPx).roundToInt()).coerceIn(0, rows.lastIndex)
+ // Worked out while the row is still where it was dropped.
+ if (drag.key == key) dropNow(rowNow)
drag.key = null
drag.offset = 0f
- if (start >= 0 && to != start) {
- reordered[section] = rows.map { it.first }.toMutableList().apply { add(to, removeAt(start)) }
- SongPlayer.reorder(item, rows[to].second, after = to > start)
- }
},
onDragCancel = { drag.key = null; drag.offset = 0f },
onDrag = { change, amount ->
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/lyrics/QueueDragMath.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/lyrics/QueueDragMath.kt
new file mode 100644
index 00000000..829b4750
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/lyrics/QueueDragMath.kt
@@ -0,0 +1,86 @@
+package com.music.spotui.ui.immersive.lyrics
+
+/**
+ * The index arithmetic of dragging a queue row, kept free of Compose so it can be tested.
+ * Rows are one flat list (the queued rows, then the context's); "others" is that list without
+ * the dragged row, and a slot is a gap in it: 0 before the first, others.size after the last.
+ */
+internal object QueueDragMath {
+ /** The gap the dragged row's centre is in: how many of the other rows' midpoints lie above it. */
+ fun slot(center: Float, otherMidpoints: List<Float>): Int = otherMidpoints.count { it < center }
+
+ /**
+ * How far the row at flat [index] steps aside (-1 up, 1 down, 0 stays) while the row at
+ * [from] hovers over gap [slot] of the others.
+ */
+ fun step(index: Int, from: Int, slot: Int): Int = when {
+ index == from -> 0
+ index > from && index - 1 < slot -> -1
+ index < from && index >= slot -> 1
+ else -> 0
+ }
+
+ /** Where a gap lands: in the queued rows ([queueSize] others) or the context's, and at which index there. */
+ data class Place(val toQueue: Boolean, val index: Int)
+
+ /**
+ * Gap [slot] as a place. The gap between the two sections belongs to the queue when the row's
+ * centre is above the context heading's midpoint ([aboveBoundary]), else to the context.
+ */
+ fun place(slot: Int, queueSize: Int, aboveBoundary: Boolean): Place = when {
+ slot < queueSize -> Place(true, slot)
+ slot > queueSize -> Place(false, slot - queueSize)
+ aboveBoundary -> Place(true, queueSize)
+ else -> Place(false, 0)
+ }
+
+ /** [list] with the element at [from] taken out and put at [to] of the rest. */
+ fun <T> moved(list: List<T>, from: Int, to: Int): List<T> =
+ list.toMutableList().apply { add(to, removeAt(from)) }
+
+ /** Pixels to scroll this frame for a finger at [y] in a viewport of [height]: 0 outside the edge zones, growing towards the edge. */
+ fun edgeStep(y: Float, height: Float, zone: Float, maxStep: Float): Float {
+ val up = ((zone - y) / zone).coerceIn(0f, 1f)
+ val down = ((y - (height - zone)) / zone).coerceIn(0f, 1f)
+ return (down - up) * maxStep
+ }
+
+ /** Which of the section's other rows an engine call names for the drop at [index]: its position and whether to go after it; null when the section has no other row. */
+ fun target(size: Int, index: Int): Pair<Int, Boolean>? = when {
+ size == 0 -> null
+ index < size -> index to false
+ else -> size - 1 to true
+ }
+
+ /** The two sections after [dragged] (taken out of both) is dropped at [place]. */
+ fun <T> apply(queued: List<T>, next: List<T>, dragged: T, place: Place): Pair<List<T>, List<T>> {
+ val q = queued.filter { it != dragged }
+ val n = next.filter { it != dragged }
+ fun <E> List<E>.with(i: Int, e: E) = toMutableList().apply { add(i.coerceIn(0, size), e) }
+ return if (place.toQueue) q.with(place.index, dragged) to n else q to n.with(place.index, dragged)
+ }
+
+ /**
+ * Songs of the Spotify queue move between its two parts only one way: out of "next from" into
+ * the queue (a song added to it). A queued song cannot go back, so its drop is held in the queue.
+ */
+ fun held(place: Place, queueSize: Int, canLeaveQueue: Boolean, fromQueue: Boolean): Place =
+ if (fromQueue && !canLeaveQueue && !place.toQueue) Place(true, queueSize) else place
+
+ /**
+ * The order just dropped, shown until the engine reports it. [queued] / [next] are the rows,
+ * [queuedUris] / [nextUris] the songs' uris in that order, [current] what played then.
+ */
+ class Pending<T>(
+ val queued: List<T>, val next: List<T>,
+ private val queuedUris: List<String>, private val nextUris: List<String>,
+ private val current: String?,
+ ) {
+ /**
+ * The engine's report ends it when it shows the same order, or another song plays now. Reports
+ * before that (the queue as it was, or half-way: a song out of one part, not yet in the other) do not.
+ */
+ fun over(reportedQueued: List<String>, reportedNext: List<String>, reportedCurrent: String?): Boolean =
+ (reportedQueued == queuedUris && reportedNext == nextUris) || reportedCurrent != current
+ }
+}
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/motion/ImmersiveMotion.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/motion/ImmersiveMotion.kt
index 110a66a1..bc204c60 100644
--- a/base/app/src/main/java/com/music/spotui/ui/immersive/motion/ImmersiveMotion.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/motion/ImmersiveMotion.kt
@@ -31,9 +31,43 @@ object ImmersiveMotion {
* The floating chrome folding and unfolding (the tab bar minimizing to a pill, the top bar's
* controls shrinking): a soft spring with a hint of overshoot. Snaps under "reduce motion".
*/
- fun <T> chromeSpring(reduce: Boolean = false): androidx.compose.animation.core.AnimationSpec<T> =
+ fun <T> chromeSpring(reduce: Boolean = false): androidx.compose.animation.core.FiniteAnimationSpec<T> =
if (reduce) androidx.compose.animation.core.snap() else spring(dampingRatio = 0.82f, stiffness = Spring.StiffnessMediumLow)
+ /**
+ * The one set of durations and springs of the Immersive look (iOS 26 feel): everything that
+ * moves on a finger uses a spring, everything that fades uses these. Screens pick from here
+ * instead of writing their own numbers.
+ */
+ const val FADE_MS = 150
+ const val SHORT_MS = 220
+ const val MEDIUM_MS = 320
+ const val LONG_MS = 420
+ const val TINT_MS = 600
+
+ /** Press feedback (scale under the finger): stiff and fully damped, it never wobbles. */
+ fun <T> pressSpring() = spring<T>(stiffness = 900f)
+
+ /**
+ * Glass objects that travel (the tab selection pill, a lens): one soft pass beyond the mark,
+ * then settled. Damping 0.72, stiffness 320.
+ */
+ fun <T> glassSpring() = spring<T>(dampingRatio = 0.72f, stiffness = 320f)
+
+ /** Release of a glass surface after a press: a touch of overshoot. */
+ fun <T> releaseSpring() = spring<T>(dampingRatio = 0.62f, stiffness = Spring.StiffnessMedium)
+
+ /** Content that resizes inside a floating container (controls opening in a pill). */
+ fun <T> sizeSpring() = spring<T>(dampingRatio = Spring.DampingRatioNoBouncy, stiffness = Spring.StiffnessMediumLow)
+
+ /**
+ * The full player rising from the mini player and going back: critically damped with a long
+ * soft landing. Snaps under "reduce motion".
+ */
+ fun slideSpring(reduce: Boolean = false): androidx.compose.animation.core.AnimationSpec<Float> =
+ if (reduce) androidx.compose.animation.core.snap()
+ else spring(dampingRatio = Spring.DampingRatioNoBouncy, stiffness = 195f, visibilityThreshold = 0.5f)
+
/** A page pushed or popped by the nav host. */
private const val PAGE_MS = 380
@@ -44,20 +78,20 @@ object ImmersiveMotion {
*/
object Pages {
fun enter(reduce: Boolean): AnimatedContentTransitionScope<NavBackStackEntry>.() -> EnterTransition = {
- if (reduce) fadeIn(tween(150)) else slideInHorizontally(spring(stiffness = Spring.StiffnessMediumLow, visibilityThreshold = IntOffset(1, 1))) { it } +
+ if (reduce) fadeIn(tween(FADE_MS)) else slideInHorizontally(spring(stiffness = Spring.StiffnessMediumLow, visibilityThreshold = IntOffset(1, 1))) { it } +
fadeIn(tween(PAGE_MS / 2))
}
fun exit(reduce: Boolean): AnimatedContentTransitionScope<NavBackStackEntry>.() -> ExitTransition = {
- if (reduce) fadeOut(tween(150)) else slideOutHorizontally(tween(PAGE_MS)) { -it / 3 } + fadeOut(tween(PAGE_MS))
+ if (reduce) fadeOut(tween(FADE_MS)) else slideOutHorizontally(tween(PAGE_MS)) { -it / 3 } + fadeOut(tween(PAGE_MS))
}
fun popEnter(reduce: Boolean): AnimatedContentTransitionScope<NavBackStackEntry>.() -> EnterTransition = {
- if (reduce) fadeIn(tween(150)) else slideInHorizontally(tween(PAGE_MS)) { -it / 3 } + fadeIn(tween(PAGE_MS))
+ if (reduce) fadeIn(tween(FADE_MS)) else slideInHorizontally(tween(PAGE_MS)) { -it / 3 } + fadeIn(tween(PAGE_MS))
}
fun popExit(reduce: Boolean): AnimatedContentTransitionScope<NavBackStackEntry>.() -> ExitTransition = {
- if (reduce) fadeOut(tween(150)) else slideOutHorizontally(tween(PAGE_MS)) { it } + fadeOut(tween(PAGE_MS / 2))
+ if (reduce) fadeOut(tween(FADE_MS)) else slideOutHorizontally(tween(PAGE_MS)) { it } + fadeOut(tween(PAGE_MS / 2))
}
}
}
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersivePage.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersivePage.kt
index 3f8bbe74..def31d06 100644
--- a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersivePage.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersivePage.kt
@@ -275,7 +275,7 @@ internal fun ImmersiveChoiceRow(
val reduce = rememberReduceMotion()
val color by animateColorAsState(
if (selected) Immersive.Accent else Color.Transparent,
- animationSpec = if (reduce) snap() else spring(stiffness = Spring.StiffnessMediumLow),
+ animationSpec = if (reduce) snap() else com.music.spotui.ui.immersive.motion.ImmersiveMotion.placementSpring(),
label = "choice check",
)
ImmersiveGroupRow(
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveRecentlyPlayedScreen.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveRecentlyPlayedScreen.kt
index 08b08783..84568aae 100644
--- a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveRecentlyPlayedScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveRecentlyPlayedScreen.kt
@@ -244,7 +244,7 @@ private fun GroupRow(group: RecentGroup, expanded: Boolean, onToggle: () -> Unit
val reduceMotion = rememberReduceMotion()
val rotation by animateFloatAsState(
targetValue = if (expanded) 180f else 0f,
- animationSpec = if (reduceMotion) snap() else spring(stiffness = Spring.StiffnessMediumLow),
+ animationSpec = if (reduceMotion) snap() else com.music.spotui.ui.immersive.motion.ImmersiveMotion.placementSpring(),
label = "recents chevron",
)
val artist = group.context.kind == MediaKind.ARTIST
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt
index 46b7c284..17e79d26 100644
--- a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt
@@ -106,13 +106,13 @@ fun ImmersiveSettingsScreen(navController: NavController) {
targetState = page,
transitionSpec = {
when {
- reduce -> fadeIn(tween(150)) togetherWith fadeOut(tween(150))
+ reduce -> fadeIn(tween(com.music.spotui.ui.immersive.motion.ImmersiveMotion.FADE_MS)) togetherWith fadeOut(tween(com.music.spotui.ui.immersive.motion.ImmersiveMotion.FADE_MS))
!pushing ->
- (slideInHorizontally(tween(320)) { -it / 3 } + fadeIn(tween(320))) togetherWith
- (slideOutHorizontally(tween(320)) { it } + fadeOut(tween(160)))
+ (slideInHorizontally(tween(com.music.spotui.ui.immersive.motion.ImmersiveMotion.MEDIUM_MS)) { -it / 3 } + fadeIn(tween(com.music.spotui.ui.immersive.motion.ImmersiveMotion.MEDIUM_MS))) togetherWith
+ (slideOutHorizontally(tween(com.music.spotui.ui.immersive.motion.ImmersiveMotion.MEDIUM_MS)) { it } + fadeOut(tween(160)))
else ->
(slideInHorizontally(spring(stiffness = Spring.StiffnessMediumLow, visibilityThreshold = IntOffset(1, 1))) { it } + fadeIn(tween(160))) togetherWith
- (slideOutHorizontally(tween(320)) { -it / 3 } + fadeOut(tween(320)))
+ (slideOutHorizontally(tween(com.music.spotui.ui.immersive.motion.ImmersiveMotion.MEDIUM_MS)) { -it / 3 } + fadeOut(tween(com.music.spotui.ui.immersive.motion.ImmersiveMotion.MEDIUM_MS)))
}
},
label = "settings pages",
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/player/ImmersiveMiniPlayer.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/player/ImmersiveMiniPlayer.kt
index db46a727..25b0fbfb 100644
--- a/base/app/src/main/java/com/music/spotui/ui/immersive/player/ImmersiveMiniPlayer.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/player/ImmersiveMiniPlayer.kt
@@ -91,6 +91,7 @@ fun ImmersiveMiniPlayer(navController: NavController, modifier: Modifier = Modif
val adPlaying = SongPlayer.adPlaying
val buffering = SongPlayer.isBuffering
val shape = RoundedCornerShape(MINI_HEIGHT / 2)
+ val capsuleSource = remember { MutableInteractionSource() }
Row(
modifier = modifier
@@ -99,9 +100,9 @@ fun ImmersiveMiniPlayer(navController: NavController, modifier: Modifier = Modif
// Where the Classic sheet rises from; kept up to date for the pages that read it.
.onGloballyPositioned { PlayerSheet.miniTop = it.boundsInWindow().top }
.miniPlayerGestures()
- .immersiveGlassSurface(shape)
+ .immersiveGlassSurface(shape, interactionSource = capsuleSource)
.clip(shape)
- .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) { PlayerSheet.show() }
+ .clickable(interactionSource = capsuleSource, indication = null) { PlayerSheet.show() }
.padding(horizontal = 12.dp, vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/player/ImmersivePlayer.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/player/ImmersivePlayer.kt
index 4f339901..d795351f 100644
--- a/base/app/src/main/java/com/music/spotui/ui/immersive/player/ImmersivePlayer.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/player/ImmersivePlayer.kt
@@ -104,6 +104,8 @@ import com.music.spotui.ui.look.rememberPauseScale
// Sizes and gaps of the portrait layout, as the player this follows has them.
private val THUMB_SIZE = 54.dp
private val HEADER_HEIGHT = 60.dp
+// Covers.large is 640px: the cover is always decoded at that, whatever size the box has right now.
+private const val COVER_DECODE_PX = 640
private val ART_TITLE_GAP = 20.dp
private val ART_BOX_TOP_PAD = 8.dp
private val DISMISS_STRIP_HEIGHT = 32.dp
@@ -118,7 +120,7 @@ internal val PLAYER_GUTTER = 30.dp
internal val PLAYER_MAX_WIDTH = 560.dp
/** How long the sleeve takes to travel between the full player and the header. */
-private const val PANEL_TRAVEL_MS = 420
+private const val PANEL_TRAVEL_MS = com.music.spotui.ui.immersive.motion.ImmersiveMotion.LONG_MS
private val ArtCorner = RoundedCornerShape(8.dp)
@@ -192,7 +194,7 @@ fun ImmersivePlayer(
) {
val context = LocalContext.current
val palette = rememberArtworkColors(state.coverUrl.takeIf { it.isNotBlank() })
- val tint by animateColorAsState(playerTintOf(palette), tween(600), label = "playerTint")
+ val tint by animateColorAsState(playerTintOf(palette), tween(com.music.spotui.ui.immersive.motion.ImmersiveMotion.TINT_MS), label = "playerTint")
var panel by rememberSaveable { mutableIntStateOf(Panel.NONE) }
var showMenu by remember { mutableStateOf(false) }
@@ -297,6 +299,10 @@ fun ImmersivePlayer(
loading = placeholder(R.drawable.placeholder),
failure = placeholder(R.drawable.placeholder),
modifier = Modifier.fillMaxSize(),
+ // The box shrinks to the 60dp header thumbnail and grows back: Glide sizes the
+ // request from the constraints it first sees, so without a fixed size a cover
+ // first measured (or reloaded) while collapsed stays a small bitmap.
+ requestBuilderTransform = { it.override(COVER_DECODE_PX) },
)
}
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/player/ImmersivePlayerOverlay.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/player/ImmersivePlayerOverlay.kt
index 9563e0f9..82f0c437 100644
--- a/base/app/src/main/java/com/music/spotui/ui/immersive/player/ImmersivePlayerOverlay.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/player/ImmersivePlayerOverlay.kt
@@ -32,6 +32,7 @@ import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.onSizeChanged
+import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import com.music.spotui.di.SongPlayer
import com.music.spotui.ui.navigation.LocalPageSettled
@@ -50,11 +51,9 @@ private const val SLIDE_SETTLED_PX = 0.5f
/** A release faster than this (px/s) decides the sheet on its own, either way. */
private const val FLING_VELOCITY = 1_000f
-private fun slideSpec() = spring<Float>(
- dampingRatio = Spring.DampingRatioNoBouncy,
- stiffness = SLIDE_STIFFNESS,
- visibilityThreshold = SLIDE_SETTLED_PX,
-)
+private val PlayerCardShape = androidx.compose.foundation.shape.RoundedCornerShape(topStart = 28.dp, topEnd = 28.dp)
+
+private fun slideSpec(reduce: Boolean) = com.music.spotui.ui.immersive.motion.ImmersiveMotion.slideSpring(reduce)
/**
* The Immersive look's player over the pages, a drop-in for [com.music.spotui.ui.navigation.PlayerOverlay]:
@@ -70,6 +69,7 @@ fun ImmersivePlayerOverlay(navController: NavController) {
}
val open = PlayerSheet.open.value
val scope = rememberCoroutineScope()
+ val reduce = com.music.spotui.ui.look.rememberReduceMotion()
var heightPx by remember { mutableIntStateOf(0) }
// How far down the sheet is (px): 0 open, the window's height away.
val offset = remember { Animatable(0f) }
@@ -91,19 +91,27 @@ fun ImmersivePlayerOverlay(navController: NavController) {
offset.snapTo(heightPx.toFloat())
primed = true
}
- offset.animateTo(0f, slideSpec())
+ offset.animateTo(0f, slideSpec(reduce))
settled.value = true
} else if (shown) {
settled.value = false
val velocity = closeVelocity.coerceAtLeast(0f)
closeVelocity = 0f
- offset.animateTo(heightPx.toFloat(), slideSpec(), initialVelocity = velocity)
+ offset.animateTo(heightPx.toFloat(), slideSpec(reduce), initialVelocity = velocity)
shown = false
primed = false
}
}
if (!shown) return
BackHandler(enabled = open) { PlayerSheet.close() }
+ // Compose's clickable asks the view for the system "click" sound on every tap; the Classic player
+ // is silent, so the window's sound effects are off while this player is up (haptics are separate).
+ val view = androidx.compose.ui.platform.LocalView.current
+ androidx.compose.runtime.DisposableEffect(view) {
+ val was = view.isSoundEffectsEnabled
+ view.isSoundEffectsEnabled = false
+ onDispose { view.isSoundEffectsEnabled = was }
+ }
val sheetDrag = remember {
object : PlayerSheetDrag {
@@ -129,7 +137,7 @@ fun ImmersivePlayerOverlay(navController: NavController) {
closeVelocity = velocity
PlayerSheet.close()
} else {
- offset.animateTo(0f, slideSpec(), initialVelocity = velocity)
+ offset.animateTo(0f, slideSpec(reduce), initialVelocity = velocity)
}
}
}
@@ -141,7 +149,13 @@ fun ImmersivePlayerOverlay(navController: NavController) {
.fillMaxSize()
.onSizeChanged { heightPx = it.height }
.graphicsLayer {
- translationY = if (held.isNaN()) offset.value else held
+ val y = if (held.isNaN()) offset.value else held
+ translationY = y
+ // The player rises as a card with rounded top corners, square once it is home.
+ if (y > 0.5f) {
+ clip = true
+ shape = PlayerCardShape
+ }
alpha = if (primed) 1f else 0f
}
// Nothing under the player may take a touch the player leaves alone.
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/player/PlayerControls.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/player/PlayerControls.kt
index 1136f231..078753a0 100644
--- a/base/app/src/main/java/com/music/spotui/ui/immersive/player/PlayerControls.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/player/PlayerControls.kt
@@ -343,7 +343,7 @@ private val PILL_SEGMENT_WIDTH = 64.dp
private val PILL_ICON_SIZE = 24.dp
/** How long the capsule takes to cross from the middle of the row to the lyrics glyph's place as the queue opens, and back. */
-private const val PILL_SLIDE_MS = 320
+private const val PILL_SLIDE_MS = com.music.spotui.ui.immersive.motion.ImmersiveMotion.MEDIUM_MS
/** How wide a capsule of [segments] comes out, dividers included. */
private fun pillWidth(segments: Int): Dp = PILL_SEGMENT_WIDTH * segments + 1.dp * (segments - 1)
@@ -360,7 +360,7 @@ private fun Pill(content: @Composable androidx.compose.foundation.layout.RowScop
.clip(CircleShape)
.background(LocalPlayerTint.current.copy(alpha = 0.12f))
.animateContentSize(
- animationSpec = spring(dampingRatio = 0.82f, stiffness = Spring.StiffnessMediumLow),
+ animationSpec = com.music.spotui.ui.immersive.motion.ImmersiveMotion.chromeSpring(),
),
verticalAlignment = Alignment.CenterVertically,
content = content,
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/podcast/ImmersiveHeaderParts.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/podcast/ImmersiveHeaderParts.kt
index 8b2ad716..583ebd2d 100644
--- a/base/app/src/main/java/com/music/spotui/ui/immersive/podcast/ImmersiveHeaderParts.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/podcast/ImmersiveHeaderParts.kt
@@ -54,7 +54,7 @@ fun rememberHeaderCollapse(listState: LazyListState): () -> Float {
fun CoverGlow(coverUrl: String?, height: Dp, modifier: Modifier = Modifier) {
val palette = rememberArtworkColors(coverUrl?.takeIf { it.isNotBlank() })
val base = palette.colors.firstOrNull() ?: Color.DarkGray
- val tint by animateColorAsState(lerp(base, Color.Black, 0.35f), tween(600), label = "coverGlow")
+ val tint by animateColorAsState(lerp(base, Color.Black, 0.35f), tween(com.music.spotui.ui.immersive.motion.ImmersiveMotion.TINT_MS), label = "coverGlow")
Box(
modifier
.height(height)
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/FloatingTabBar.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/FloatingTabBar.kt
index 7c3a88dd..aaa527c2 100644
--- a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/FloatingTabBar.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/FloatingTabBar.kt
@@ -112,7 +112,7 @@ private val DefaultTabBarContentModifier: @Composable () -> Modifier = { Modifie
* Damping 0.72 rather than half-damped: it settles on the second approach — one soft pass
* beyond the mark and done — which is the difference between bouncy and alive.
*/
-private val GlassSpring = spring<Float>(dampingRatio = 0.72f, stiffness = 320f)
+private val GlassSpring = com.music.spotui.ui.immersive.motion.ImmersiveMotion.glassSpring<Float>()
/**
* A floating tab bar: a pill of tabs, and optionally one standalone tab in a circle of its own
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/ImmersiveChrome.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/ImmersiveChrome.kt
index 2ea47e37..2117e4a1 100644
--- a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/ImmersiveChrome.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/ImmersiveChrome.kt
@@ -240,12 +240,13 @@ fun ImmersiveBottomChrome(
@Composable
private fun MinimizedTabPill(selectedTab: String, onClick: () -> Unit) {
val item = TabItems.firstOrNull { it.route == selectedTab } ?: Routes.Home
+ val source = remember { MutableInteractionSource() }
Box(
modifier = Modifier
.size(PILL_SIZE)
- .immersiveGlassSurface(CircleShape)
+ .immersiveGlassSurface(CircleShape, interactionSource = source)
.clickable(
- interactionSource = remember { MutableInteractionSource() },
+ interactionSource = source,
indication = null,
role = Role.Button,
onClickLabel = stringResource(R.string.immersive_expand_tab_bar),
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/ImmersiveFades.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/ImmersiveFades.kt
index 1c2b8061..add2af89 100644
--- a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/ImmersiveFades.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/ImmersiveFades.kt
@@ -54,7 +54,7 @@ fun ImmersiveBottomFade(
val height by animateDpAsState(
targetValue = inset + if (withMiniPlayer) FADE_HEIGHT_WITH_MINI_PLAYER else FADE_HEIGHT,
// Matches the beat the mini player takes to appear.
- animationSpec = tween(220),
+ animationSpec = tween(com.music.spotui.ui.immersive.motion.ImmersiveMotion.SHORT_MS),
label = "immersiveBottomFadeHeight",
)
val brush = remember(pageColor) {
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/ImmersiveGlass.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/ImmersiveGlass.kt
index 51e1f508..4b99cae5 100644
--- a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/ImmersiveGlass.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/ImmersiveGlass.kt
@@ -4,22 +4,23 @@
* from EchoMusicApp/Echo-Music's GlassEffectConfig / Modifier.liquidGlass (GPL-3.0).
* Modified for Myspoti, 2026-10: the switch is LiquidGlassPref, the fallback is Myspoti's Haze
* frost, the page is recorded per page (each page's list) instead of around the whole app, and
- * a glass drawn inside the page it samples, or in another window, falls back to a plain fill.
+ * a glass drawn inside the page it samples falls back to a plain fill, one in another window (a
+ * sheet) samples the page by screen position. 2026-10 (later): the window-blur gate is gone, the
+ * blur, lens and tint follow the surface size, and a surface can react to a press.
*
* The rendering itself is Kyant0/backdrop (Apache-2.0), vendored in ./backdrop.
*/
package com.music.spotui.ui.immersive.shell
import android.os.Build
-import android.view.WindowManager
import androidx.compose.foundation.shape.CornerBasedShape
+import androidx.compose.animation.core.animateFloatAsState
+import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.runtime.Composable
-import androidx.compose.runtime.DisposableEffect
-import androidx.compose.runtime.compositionLocalOf
import androidx.compose.runtime.getValue
-import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.compositionLocalOf
import androidx.compose.runtime.remember
-import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
@@ -27,13 +28,15 @@ import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.GraphicsLayerScope
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.drawscope.DrawScope
+import androidx.compose.ui.graphics.drawscope.withTransform
+import androidx.compose.ui.graphics.layer.drawLayer
+import androidx.compose.ui.layout.positionOnScreen
import androidx.compose.ui.layout.LayoutCoordinates
-import androidx.compose.ui.platform.LocalContext
-import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.dp
import com.music.spotui.data.preferences.LiquidGlassPref
import com.music.spotui.ui.immersive.Immersive
+import com.music.spotui.ui.immersive.motion.ImmersiveMotion
import com.music.spotui.ui.immersive.shell.backdrop.Backdrop
import com.music.spotui.ui.immersive.shell.backdrop.backdrops.LayerBackdrop
import com.music.spotui.ui.immersive.shell.backdrop.backdrops.rememberLayerBackdrop
@@ -47,47 +50,65 @@ import com.music.spotui.ui.look.rememberReduceMotion
/** Whether Liquid Glass can run here, before the user's own switch is taken into account. */
enum class LiquidGlassAvailability {
- /** Android 12+ and nothing asks for less: the switch decides. */
+ /** Android 12+ and no "remove animations": the switch decides. */
AVAILABLE,
- /** The phone asks for less blur (window blurs off, battery saver) or no animation: frosted instead. */
+ /** The phone asks for no animation ("Remove animations"): frosted instead. */
REDUCED,
- /** Before Android 12 there is no RenderEffect to bend the page with: frosted, and the switch is greyed. */
+ /** Before Android 12 there is no RenderEffect to blur the page live: frosted, and the switch is greyed. */
UNSUPPORTED,
}
-/** See [LiquidGlassAvailability]. Follows the system's blur switch live. */
+/** Which glass the Immersive surfaces actually draw. */
+enum class GlassPath {
+ /** Android 13+: live blur of the page behind, lens refraction, chromatic aberration (AGSL). */
+ LENS,
+
+ /** Android 12/12L: live RenderEffect blur of the page behind, no lens (no RuntimeShader). */
+ LIVE_BLUR,
+
+ /** Haze frost: below Android 12, "Remove animations" on, or the switch off. */
+ FROST,
+}
+
+/**
+ * See [LiquidGlassAvailability]. The system's "window blurs" switch is deliberately not read: it
+ * only governs blur-behind of whole windows (a dialog's backdrop). The RenderEffect and
+ * RuntimeShader blur of a recorded layer does not depend on it, and Samsung/Xiaomi/Battery saver
+ * turn it off on phones that render the effect perfectly well.
+ */
@Composable
fun liquidGlassAvailability(): LiquidGlassAvailability {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) return LiquidGlassAvailability.UNSUPPORTED
- val reduceMotion = rememberReduceMotion()
- val blurs = rememberWindowBlursEnabled()
- return if (reduceMotion || !blurs) LiquidGlassAvailability.REDUCED else LiquidGlassAvailability.AVAILABLE
+ return if (rememberReduceMotion()) LiquidGlassAvailability.REDUCED else LiquidGlassAvailability.AVAILABLE
}
-/** True when the Immersive bars should be Liquid Glass: the switch is on and [liquidGlassAvailability] allows it. */
-@Composable
-fun rememberLiquidGlassActive(): Boolean =
- LiquidGlassPref.on && liquidGlassAvailability() == LiquidGlassAvailability.AVAILABLE
+/** The path for these inputs; [rememberLiquidGlassActive] logs it. */
+internal fun glassPathOf(switchOn: Boolean, availability: LiquidGlassAvailability, sdk: Int = Build.VERSION.SDK_INT): GlassPath = when {
+ !switchOn || availability != LiquidGlassAvailability.AVAILABLE -> GlassPath.FROST
+ sdk >= Build.VERSION_CODES.TIRAMISU -> GlassPath.LENS
+ else -> GlassPath.LIVE_BLUR
+}
-/**
- * The system's "window blurs" (off under battery saver, with the developer option, or on a device
- * whose GPU cannot afford them). The cheapest honest signal of "this phone wants less blur".
- */
+/** True when the Immersive surfaces should be Liquid Glass: the switch is on and [liquidGlassAvailability] allows it. */
@Composable
-private fun rememberWindowBlursEnabled(): Boolean {
- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) return false
- val context = LocalContext.current
- val wm = remember(context) { context.getSystemService(WindowManager::class.java) }
- var enabled by remember(wm) { mutableStateOf(wm?.isCrossWindowBlurEnabled ?: false) }
- DisposableEffect(wm) {
- if (wm == null) return@DisposableEffect onDispose { }
- val listener = java.util.function.Consumer<Boolean> { enabled = it }
- wm.addCrossWindowBlurEnabledListener(listener)
- onDispose { wm.removeCrossWindowBlurEnabledListener(listener) }
+fun rememberLiquidGlassActive(): Boolean {
+ val availability = liquidGlassAvailability()
+ val on = LiquidGlassPref.on
+ val path = glassPathOf(on, availability)
+ // One line per change, so a diagnostic report says which glass runs and why.
+ LaunchedEffect(path, availability, on) {
+ val why = when {
+ !on -> "the Liquid Glass switch is off"
+ availability == LiquidGlassAvailability.UNSUPPORTED -> "Android ${Build.VERSION.SDK_INT} is below 12, no RenderEffect"
+ availability == LiquidGlassAvailability.REDUCED -> "Remove animations is on"
+ path == GlassPath.LENS -> "Android ${Build.VERSION.SDK_INT}: RuntimeShader lens and live RenderEffect blur"
+ else -> "Android ${Build.VERSION.SDK_INT}: live RenderEffect blur, no RuntimeShader for the lens"
+ }
+ app.myspoti.host.android.Logbook.log("glass: $path ($why)")
}
- return enabled
+ return path != GlassPath.FROST
}
/**
@@ -112,19 +133,39 @@ internal val LocalGlassExport = compositionLocalOf<LayerBackdrop?> { null }
* fewer pixels through the colour matrix, the blur and the lens; the blur hides the upscale).
*/
private const val GLASS_RESOLUTION_SCALE = 0.33f
-private val GLASS_BLUR = 8.dp
-private val GLASS_LENS_HEIGHT = 24.dp
-private val GLASS_LENS_AMOUNT = 24.dp
+
+/** Surfaces up to this size (dp, smaller side) are "thin" glass: bars, pills, buttons. */
+private const val THIN_DP = 56f
+
+/** From this size on a surface is "large" glass: a sheet or a card, whose text must stay readable. */
+private const val LARGE_DP = 200f
/** The glass's own body over the refracted page: dark, so white text holds on any artwork. */
internal val GlassTint = Color(0xFF1C1C22).copy(alpha = 0.42f)
+/** Alpha of the body on large glass: more opaque, there is text on it. */
+private const val LARGE_TINT_ALPHA = 0.60f
+
private val GlassShadow = Shadow(radius = 18.dp, color = Color.Black.copy(alpha = 0.22f))
+/** A brighter, thicker specular rim than the library's default, like iOS 26's glass edge. */
+private val GlassHighlight = Highlight(width = 0.75f.dp, alpha = 0.9f)
+
+/** How much the lens bulges while the glass is pressed (fraction of its refraction). */
+private const val PRESS_BULGE = 0.35f
+
+private fun mix(a: Float, b: Float, t: Float) = a + (b - a) * t
+
/**
- * Liquid Glass over [page]: vibrancy, blur and (Android 13+, rounded shapes) lens refraction, a
- * dark [tint], a rim of light and a soft shadow. Use through [immersiveGlassSurface]; this one is
- * for surfaces that need a different tint or no lens (the top bar's strip).
+ * Liquid Glass over [page]: vibrancy, a live blur and (Android 13+, rounded shapes) lens
+ * refraction with a little chromatic aberration, a dark [tint], a rim of light and a soft shadow.
+ * The blur, the lens depth and the body's opacity follow the surface's size: a thin bar blurs
+ * little and bends hard at its edge, a sheet blurs more and is more opaque. Use through
+ * [immersiveGlassSurface]; this one is for surfaces that need a different tint or no lens (the
+ * top bar's strip).
+ *
+ * @param press 0..1, how pressed the surface is (read in the draw phase): scales it a little and
+ * bulges the lens. Null for a surface that is not touched.
*/
@Composable
internal fun Modifier.immersiveLiquidGlass(
@@ -133,36 +174,87 @@ internal fun Modifier.immersiveLiquidGlass(
tint: Color = GlassTint,
lens: Boolean = true,
rim: Boolean = true,
+ press: (() -> Float)? = null,
): Modifier {
- val density = LocalDensity.current
val export = LocalGlassExport.current
val backdrop = remember(page) { PageBackdrop(page) }
- val blurPx = with(density) { GLASS_BLUR.toPx() } * GLASS_RESOLUTION_SCALE
- val lensHeightPx = with(density) { GLASS_LENS_HEIGHT.toPx() } * GLASS_RESOLUTION_SCALE
- val lensAmountPx = with(density) { GLASS_LENS_AMOUNT.toPx() } * GLASS_RESOLUTION_SCALE
// The lens only knows rounded rectangles (it throws on anything else).
val bend = lens && shape is CornerBasedShape && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU
+ val adaptive = tint == GlassTint
+ // Stable across recompositions: a new lambda per call would rebuild the effect chain.
+ val effects = remember(bend, press) {
+ val block: com.music.spotui.ui.immersive.shell.backdrop.BackdropEffectScope.() -> Unit = {
+ val k = GLASS_RESOLUTION_SCALE
+ val minDp = size.minDimension / k / density
+ val depth = ((minDp - THIN_DP) / (LARGE_DP - THIN_DP)).coerceIn(0f, 1f)
+ // Vibrancy, and a touch darker so a bright cover behind never washes the text out.
+ colorControls(brightness = -0.03f, saturation = 1.6f)
+ blur(mix(3.5f, 14f, depth) * density * k)
+ if (bend) {
+ val bulge = 1f + PRESS_BULGE * (press?.invoke() ?: 0f)
+ val height = mix((minDp * 0.42f).coerceAtMost(22f), 30f, depth)
+ val amount = height * mix(1.7f, 1.2f, depth) * bulge
+ lens(
+ refractionHeight = height * density * k,
+ refractionAmount = amount * density * k,
+ depthEffect = true,
+ chromaticAberration = true,
+ )
+ }
+ }
+ block
+ }
+ val surface = remember(tint, adaptive) {
+ val block: DrawScope.() -> Unit = {
+ val depth = ((size.minDimension / density - THIN_DP) / (LARGE_DP - THIN_DP)).coerceIn(0f, 1f)
+ drawRect(color = if (adaptive) tint.copy(alpha = mix(tint.alpha, LARGE_TINT_ALPHA, depth)) else tint, size = size)
+ }
+ block
+ }
+ val layerBlock = remember(press) {
+ press?.let { p ->
+ val block: GraphicsLayerScope.() -> Unit = {
+ val s = 1f - 0.04f * p()
+ scaleX = s
+ scaleY = s
+ }
+ block
+ }
+ }
return drawBackdrop(
backdrop = backdrop,
shape = { shape },
- effects = {
- colorControls(saturation = 1.5f)
- blur(blurPx)
- if (bend) lens(refractionHeight = lensHeightPx, refractionAmount = lensAmountPx, depthEffect = true, chromaticAberration = true)
- },
- highlight = if (rim) ({ Highlight.Default }) else null,
+ effects = effects,
+ highlight = if (rim) ({ GlassHighlight }) else null,
shadow = if (rim) ({ GlassShadow }) else null,
- onDrawSurface = { drawRect(color = tint, size = size) },
+ layerBlock = layerBlock,
+ onDrawSurface = surface,
exportedBackdrop = export,
backdropScale = GLASS_RESOLUTION_SCALE,
)
}
+/**
+ * The 0..1 press of a glass surface for [source], on the Immersive press spring (a touch of
+ * overshoot on release). Constant 0 under "reduce motion". Read it in the draw phase.
+ */
+@Composable
+internal fun rememberGlassPress(source: androidx.compose.foundation.interaction.InteractionSource?): (() -> Float)? {
+ if (source == null || rememberReduceMotion()) return null
+ val pressed by source.collectIsPressedAsState()
+ val progress = animateFloatAsState(
+ targetValue = if (pressed) 1f else 0f,
+ animationSpec = if (pressed) ImmersiveMotion.pressSpring<Float>() else ImmersiveMotion.releaseSpring<Float>(),
+ label = "glassPress",
+ )
+ return remember(progress) { { progress.value } }
+}
+
/**
* The page under the glass, laid on the page colour so the blur never runs into transparency
* (where it does, the sharp page shows through the glass). Draws nothing but [Immersive.GlassFill]
* when it cannot sample the page: the glass is inside the recorded page itself (it would draw the
- * page into itself), or in another window (a sheet), whose position against the page means nothing.
+ * page into itself). A glass in another window (a sheet) samples the page by screen position.
*/
internal class PageBackdrop(private val page: LayerBackdrop) : Backdrop {
override val isCoordinatesDependent: Boolean = true
@@ -173,11 +265,20 @@ internal class PageBackdrop(private val page: LayerBackdrop) : Backdrop {
layerBlock: (GraphicsLayerScope.() -> Unit)?,
) {
val source = page.layerCoordinates
- val usable = coordinates != null && source != null && source.isAttached && coordinates.isAttached &&
- !source.isAncestorOf(coordinates) &&
- source.findRoot() === coordinates.findRoot()
+ val attached = coordinates != null && source != null && source.isAttached && coordinates.isAttached &&
+ !source.isAncestorOf(coordinates)
+ val sameWindow = attached && source!!.findRoot() === coordinates!!.findRoot()
+ // Another window (the sheet's dialog): the recorded layer is drawn at the surface's
+ // position on the screen, which is what both windows share.
+ val usable = attached && (sameWindow || Build.VERSION.SDK_INT >= Build.VERSION_CODES.S)
drawRect(if (usable) Immersive.Page else Immersive.GlassFill, topLeft = FAR_TOP_LEFT, size = FAR_SIZE)
- if (usable) with(page) { drawBackdrop(density, coordinates, layerBlock) }
+ if (!usable) return
+ if (sameWindow) {
+ with(page) { drawBackdrop(density, coordinates, layerBlock) }
+ } else {
+ val offset = coordinates!!.positionOnScreen() - source!!.positionOnScreen()
+ withTransform({ translate(-offset.x, -offset.y) }) { drawLayer(page.graphicsLayer) }
+ }
}
private companion object {
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/ImmersiveHaze.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/ImmersiveHaze.kt
index 826bd7fc..8ff496fd 100644
--- a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/ImmersiveHaze.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/ImmersiveHaze.kt
@@ -14,6 +14,7 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
+import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.unit.dp
import com.music.spotui.ui.immersive.Immersive
import com.music.spotui.ui.immersive.shell.backdrop.backdrops.LayerBackdrop
@@ -89,6 +90,8 @@ internal fun Modifier.immersiveFrost(
* instead: the page refracted through a lens, a rim of light and a soft shadow
* ([immersiveLiquidGlass]). A [state] of your own keeps its frost; null keeps the plain fill.
*
+ * @param interactionSource the surface's own press source: it scales a little under the finger
+ * and springs back, and the glass lens bulges (iOS 26). Null for a surface that is not tapped.
* @param liquid false keeps the frost even while Liquid Glass is on (a surface that would cost
* too much, or that must stay flat).
*/
@@ -97,13 +100,22 @@ internal fun Modifier.immersiveGlassSurface(
shape: Shape,
state: HazeState? = LocalImmersiveHaze.current,
liquid: Boolean = true,
+ interactionSource: androidx.compose.foundation.interaction.InteractionSource? = null,
): Modifier {
val page = LocalImmersiveBackdrop.current
+ val press = rememberGlassPress(interactionSource)
if (liquid && page != null && state != null && state === LocalImmersiveHaze.current) {
// Not clipped here: the glass clips itself, and its shadow falls outside the shape.
- return this.immersiveLiquidGlass(shape, page)
+ return this.immersiveLiquidGlass(shape, page, press = press)
}
return this
+ .then(
+ if (press == null) Modifier else Modifier.graphicsLayer {
+ val s = 1f - 0.04f * press()
+ scaleX = s
+ scaleY = s
+ },
+ )
.clip(shape)
.then(if (state != null) Modifier.immersiveFrost(state) else Modifier.background(Immersive.GlassFill))
.border(1.dp, Immersive.GlassEdge, shape)
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/ImmersiveTopBar.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/ImmersiveTopBar.kt
index 55048327..1756dda2 100644
--- a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/ImmersiveTopBar.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/ImmersiveTopBar.kt
@@ -197,13 +197,14 @@ fun ImmersiveTopBar(
.graphicsLayer { alpha = collapse() },
)
if (onBack != null) {
+ val backSource = remember { androidx.compose.foundation.interaction.MutableInteractionSource() }
Box(
modifier = Modifier
.align(Alignment.CenterStart)
.padding(start = Immersive.Gutter)
.size(controlSize)
- .immersiveGlassSurface(CircleShape, hazeState)
- .clickable(role = Role.Button, onClick = onBack),
+ .immersiveGlassSurface(CircleShape, hazeState, interactionSource = backSource)
+ .clickable(interactionSource = backSource, indication = null, role = Role.Button, onClick = onBack),
contentAlignment = Alignment.Center,
) {
Icon(
@@ -222,10 +223,7 @@ fun ImmersiveTopBar(
.immersiveGlassSurface(CircleShape, hazeState)
// Keep the right edge fixed while a new action opens room to its left.
.animateContentSize(
- animationSpec = spring(
- dampingRatio = Spring.DampingRatioNoBouncy,
- stiffness = Spring.StiffnessMediumLow,
- ),
+ animationSpec = ImmersiveMotion.sizeSpring(),
),
verticalAlignment = Alignment.CenterVertically,
) {
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/BackdropEffectScope.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/BackdropEffectScope.kt
index 759d8bfa..9085af99 100644
--- a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/BackdropEffectScope.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/BackdropEffectScope.kt
@@ -23,6 +23,9 @@ sealed interface BackdropEffectScope : Density, RuntimeShaderCache {
val size: Size
+ /** Vendored addition: the fraction of the surface resolution the effects run at ([size] is already scaled). */
+ val contentScale: Float
+
val layoutDirection: LayoutDirection
val shape: Shape
@@ -37,6 +40,7 @@ internal abstract class BackdropEffectScopeImpl : BackdropEffectScope, RuntimeSh
override var density: Float = 1f
override var fontScale: Float = 1f
override var size: Size = Size.Unspecified
+ override var contentScale: Float = 1f
override var layoutDirection: LayoutDirection = LayoutDirection.Ltr
override var padding: Float = 0f
override var renderEffect: RenderEffect? = null
@@ -57,11 +61,13 @@ internal abstract class BackdropEffectScopeImpl : BackdropEffectScope, RuntimeSh
val newLayoutDirection = scope.layoutDirection
val changed = newDensity != density ||
+ contentScale != this.contentScale ||
newFontScale != fontScale ||
newSize != size ||
newLayoutDirection != layoutDirection
if (changed) {
+ this.contentScale = contentScale
density = newDensity
fontScale = newFontScale
size = newSize
@@ -79,6 +85,7 @@ internal abstract class BackdropEffectScopeImpl : BackdropEffectScope, RuntimeSh
fun reset() {
density = 1f
+ contentScale = 1f
fontScale = 1f
size = Size.Unspecified
layoutDirection = LayoutDirection.Ltr
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.kt
index c52c0ff4..bc2edd93 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
@@ -90,13 +90,19 @@ private class LayerBackdropNode(
drawLayer(backdrop.graphicsLayer)
}
+ private var own: LayoutCoordinates? = null
+
override fun onGloballyPositioned(coordinates: LayoutCoordinates) {
if (coordinates.isAttached) {
+ own = coordinates
backdrop.layerCoordinates = coordinates
}
}
override fun onDetach() {
- backdrop.layerCoordinates = null
+ // Vendored change: two pages record into one backdrop while a page transition runs; the
+ // one leaving must not blank the coordinates the one staying has just reported.
+ if (backdrop.layerCoordinates === own) backdrop.layerCoordinates = null
+ own = null
}
}
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/effects/Lens.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/effects/Lens.kt
index 79925e23..7365d7ef 100644
--- a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/effects/Lens.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/effects/Lens.kt
@@ -78,10 +78,14 @@ private val BackdropEffectScope.cornerRadii: FloatArray?
is AbsoluteRoundedCornerShape -> {
val size = size
val maxRadius = size.minDimension / 2f
- val topLeft = shape.topStart.toPx(size, this)
- val topRight = shape.topEnd.toPx(size, this)
- val bottomRight = shape.bottomEnd.toPx(size, this)
- val bottomLeft = shape.bottomStart.toPx(size, this)
+ // Vendored fix: the shape is measured against the surface, the effect runs on the
+ // scaled-down layer; a radius in dp must follow the scale (a percent one already does).
+ val full = size / contentScale
+ val k = contentScale
+ val topLeft = shape.topStart.toPx(full, this) * k
+ val topRight = shape.topEnd.toPx(full, this) * k
+ val bottomRight = shape.bottomEnd.toPx(full, this) * k
+ val bottomLeft = shape.bottomStart.toPx(full, this) * k
floatArrayOf(
topLeft.fastCoerceAtMost(maxRadius),
topRight.fastCoerceAtMost(maxRadius),
@@ -94,18 +98,21 @@ private val BackdropEffectScope.cornerRadii: FloatArray?
val size = size
val maxRadius = size.minDimension / 2f
val isLtr = layoutDirection == LayoutDirection.Ltr
+ // Vendored fix: see the absolute branch above.
+ val full = size / contentScale
+ val k = contentScale
val topLeft =
- if (isLtr) shape.topStart.toPx(size, this)
- else shape.topEnd.toPx(size, this)
+ (if (isLtr) shape.topStart.toPx(full, this)
+ else shape.topEnd.toPx(full, this)) * k
val topRight =
- if (isLtr) shape.topEnd.toPx(size, this)
- else shape.topStart.toPx(size, this)
+ (if (isLtr) shape.topEnd.toPx(full, this)
+ else shape.topStart.toPx(full, this)) * k
val bottomRight =
- if (isLtr) shape.bottomEnd.toPx(size, this)
- else shape.bottomStart.toPx(size, this)
+ (if (isLtr) shape.bottomEnd.toPx(full, this)
+ else shape.bottomStart.toPx(full, this)) * k
val bottomLeft =
- if (isLtr) shape.bottomStart.toPx(size, this)
- else shape.bottomEnd.toPx(size, this)
+ (if (isLtr) shape.bottomStart.toPx(full, this)
+ else shape.bottomEnd.toPx(full, this)) * k
floatArrayOf(
topLeft.fastCoerceAtMost(maxRadius),
topRight.fastCoerceAtMost(maxRadius),
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/ExtensionsScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/ExtensionsScreen.kt
index 46ca85b0..0d0260ca 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/ExtensionsScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/ExtensionsScreen.kt
@@ -20,7 +20,6 @@ import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
-import androidx.compose.material.icons.filled.Clear
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.KeyboardArrowUp
@@ -47,6 +46,8 @@ 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.focus.FocusRequester
+import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
@@ -71,6 +72,7 @@ import app.myspoti.extensions.StoreAction
import com.music.spotui.extensions.ExtensionStore
import com.music.spotui.extensions.Extensions
import com.music.spotui.extensions.InstalledExtension
+import com.music.spotui.ui.components.SearchClearButton
import com.music.spotui.ui.navigation.Routes
import com.music.spotui.ui.theme.AppAccent
import com.music.spotui.ui.theme.AppMuted
@@ -248,6 +250,7 @@ private fun Tabs(selected: Int, updates: Int, onSelect: (Int) -> Unit) {
@Composable
private fun SearchField(query: String, onChange: (String) -> Unit) {
+ val focus = remember { FocusRequester() }
if (com.music.spotui.ui.navigation.isImmersive()) {
com.music.spotui.ui.immersive.components.ImmersiveSearchField(
query = query, onQueryChange = onChange, onSubmit = {},
@@ -260,13 +263,13 @@ private fun SearchField(query: String, onChange: (String) -> Unit) {
value = query, onValueChange = onChange, singleLine = true,
placeholder = { Text(stringResource(R.string.extensions_search), color = AppMuted) },
leadingIcon = { Icon(Icons.Default.Search, null, tint = AppMuted) },
- trailingIcon = { if (query.isNotEmpty()) IconButton(onClick = { onChange("") }) { Icon(Icons.Default.Clear, stringResource(R.string.extensions_cancel), tint = AppMuted) } },
+ trailingIcon = if (query.isEmpty()) null else { { SearchClearButton(focus, AppMuted) { onChange("") } } },
shape = RoundedCornerShape(24.dp),
colors = OutlinedTextFieldDefaults.colors(
focusedTextColor = AppText, unfocusedTextColor = AppText, focusedBorderColor = AppAccent, unfocusedBorderColor = tone(0xFF3E3E3E),
focusedContainerColor = tone(0xFF1E1E1E), unfocusedContainerColor = tone(0xFF1E1E1E), cursorColor = AppAccent,
),
- modifier = Modifier.fillMaxWidth().padding(start = 16.dp, end = 16.dp, top = 12.dp).heightIn(min = 48.dp),
+ modifier = Modifier.fillMaxWidth().padding(start = 16.dp, end = 16.dp, top = 12.dp).heightIn(min = 48.dp).focusRequester(focus),
)
}
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/LibraryScreeen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/LibraryScreeen.kt
index 6b51ecca..8558540e 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/LibraryScreeen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/LibraryScreeen.kt
@@ -6,6 +6,7 @@ import com.music.spotui.ui.theme.AppMuted
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.PushPin
+import com.music.spotui.ui.components.SearchClearButton
import com.music.spotui.ui.components.pressable
import androidx.compose.ui.res.stringResource
@@ -42,7 +43,6 @@ import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
-import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.DateRange
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.filled.Search
@@ -71,6 +71,8 @@ import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.zIndex
import androidx.compose.animation.core.VisibilityThreshold
import androidx.compose.ui.draw.clip
+import androidx.compose.ui.focus.FocusRequester
+import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.layout.ContentScale
@@ -254,6 +256,7 @@ fun LibraryScreen(navController: NavController) {
.padding(horizontal = 12.dp),
) {
Icon(Icons.Default.Search, contentDescription = null, tint = Color(0xFF888888), modifier = Modifier.size(18.dp))
+ val searchFocus = remember { FocusRequester() }
BasicTextField(
value = searchQuery,
onValueChange = { searchQuery = it },
@@ -261,7 +264,8 @@ fun LibraryScreen(navController: NavController) {
textStyle = TextStyle(color = AppText, fontSize = 15.sp),
modifier = Modifier
.weight(1f)
- .padding(8.dp, 10.dp),
+ .padding(8.dp, 10.dp)
+ .focusRequester(searchFocus),
decorationBox = { inner ->
Box {
if (searchQuery.isEmpty()) Text(stringResource(R.string.navigationbar_musicappitems_search_title), color = Color(0xFF888888), fontSize = 15.sp)
@@ -269,16 +273,7 @@ fun LibraryScreen(navController: NavController) {
}
},
)
- if (searchQuery.isNotEmpty()) {
- Icon(
- imageVector = Icons.Default.Close,
- contentDescription = stringResource(R.string.chat_content_picker_clear_recent_searches),
- tint = Color(0xFF888888),
- modifier = Modifier.pressable(0.96f) { searchQuery = "" }
- .size(18.dp)
- ,
- )
- }
+ if (searchQuery.isNotEmpty()) SearchClearButton(searchFocus, Color(0xFF888888)) { searchQuery = "" }
}
}
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/LyricsScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/LyricsScreen.kt
index 897778bb..e401ebab 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/LyricsScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/LyricsScreen.kt
@@ -212,7 +212,9 @@ private fun shareLyrics(context: Context, title: String, artist: String, line: S
@Composable
private fun rememberLyricsState(vm: LyricsViewModel, title: String, artist: String): LyricsViewModel.State {
- LaunchedEffect(title, artist, SongPlayer.currentTrackId) {
+ // currentTrackId is plain data, not Compose state: the playing item's uri re-runs the load on a skip.
+ val playingUri = SongPlayer.nowPlaying.value.uri
+ LaunchedEffect(title, artist, playingUri, SongPlayer.currentTrackId) {
SongPlayer.currentLyricsTrack()?.let { vm.load(it) }
}
return vm.state.collectAsState().value
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/SearchScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/SearchScreen.kt
index 03f6c840..9ae52a03 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/SearchScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/SearchScreen.kt
@@ -5,6 +5,7 @@ import com.music.spotui.ui.theme.AppText
import com.music.spotui.ui.theme.AppMuted
import kotlinx.coroutines.launch
+import com.music.spotui.ui.components.SearchClearButton
import com.music.spotui.ui.components.pressable
import androidx.compose.ui.res.stringResource
@@ -865,6 +866,9 @@ fun SearchStickyBar(
onTextChange: (String) -> Unit,
) {
+ // The field is always attached to a requester, so the clear button can put the cursor back in it.
+ val ownFocus = remember { androidx.compose.ui.focus.FocusRequester() }
+ val fieldFocus = focusRequester ?: ownFocus
Row(verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
@@ -882,7 +886,7 @@ fun SearchStickyBar(
TextField(
enabled = true,
modifier = Modifier
- .then(if (focusRequester != null) Modifier.focusRequester(focusRequester) else Modifier)
+ .focusRequester(fieldFocus)
.onFocusChanged { onFocusChange(it.isFocused) },
value = text,
textStyle = TextStyle.Default.copy(fontSize = 16.sp, color = Color.Black, fontWeight = FontWeight(500)),
@@ -905,7 +909,10 @@ fun SearchStickyBar(
text = stringResource(R.string.search_header_field_hint)
)
- }
+ },
+ trailingIcon = if (text.isEmpty()) null else {
+ { SearchClearButton(fieldFocus, Color.Black) { onTextChange("") } }
+ },
)
}
}
diff --git a/base/app/src/main/res/values-fr/myspoti_strings.xml b/base/app/src/main/res/values-fr/myspoti_strings.xml
index 56f3a7ad..eb1fc45a 100644
--- a/base/app/src/main/res/values-fr/myspoti_strings.xml
+++ b/base/app/src/main/res/values-fr/myspoti_strings.xml
@@ -395,6 +395,9 @@
<string name="player_forward_15">Avancer de 15 secondes</string>
<string name="player_sleep_timer">Minuteur de veille</string>
<string name="restart_player_done">Lecteur redémarré</string>
+ <string name="song_unavailable_skipped">%1$s est indisponible et a été passé.</string>
+ <string name="song_unavailable">%1$s est indisponible.</string>
+ <string name="songs_skipped_by_spotify">Spotify enchaînait des morceaux qu’il ne pouvait pas lire : la lecture a été mise en pause. Appuyez sur lecture pour réessayer, ou vérifiez votre compte et votre connexion.</string>
<string name="spotify_limited">Spotify limite la lecture pour le moment. Réessayez dans une minute.</string>
<string name="library_change_undone">Spotify a refusé la modification, votre bibliothèque est revenue comme avant</string>
<string name="blend_title">Mix à plusieurs</string>
diff --git a/base/app/src/main/res/values/myspoti_strings.xml b/base/app/src/main/res/values/myspoti_strings.xml
index c3f5e47b..bc5e7db5 100644
--- a/base/app/src/main/res/values/myspoti_strings.xml
+++ b/base/app/src/main/res/values/myspoti_strings.xml
@@ -395,6 +395,9 @@
<string name="player_forward_15">Forward 15 seconds</string>
<string name="player_sleep_timer">Sleep timer</string>
<string name="restart_player_done">Player restarted</string>
+ <string name="song_unavailable_skipped">%1$s is unavailable and was skipped.</string>
+ <string name="song_unavailable">%1$s is unavailable.</string>
+ <string name="songs_skipped_by_spotify">Spotify kept skipping songs it could not play, so playback was paused. Tap play to try again, or check your account and connection.</string>
<string name="spotify_limited">Spotify is limiting playback for a moment. Try again in a minute.</string>
<string name="library_change_undone">Spotify refused the change, your library is back as it was</string>
<string name="blend_title">Blend</string>
diff --git a/base/app/src/test/java/com/music/spotui/di/LastSessionTest.kt b/base/app/src/test/java/com/music/spotui/di/LastSessionTest.kt
new file mode 100644
index 00000000..79681a09
--- /dev/null
+++ b/base/app/src/test/java/com/music/spotui/di/LastSessionTest.kt
@@ -0,0 +1,30 @@
+package com.music.spotui.di
+
+import com.music.spotui.data.entity.SongsModel
+import com.music.spotui.data.preferences.LastSession
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class LastSessionTest {
+ private fun song(i: Int) = SongsModel(i, "t$i", "a", "s", "c", "local:u$i", spotifyTrackId = "id$i", durationMs = 1000)
+
+ @Test fun queueRoundTrips() {
+ val q = listOf(song(1), song(2))
+ assertEquals(q, LastSession.decodeQueue(LastSession.encodeQueue(q)))
+ }
+
+ @Test fun queueIsCappedAndBadInputIsEmpty() {
+ assertEquals(100, LastSession.decodeQueue(LastSession.encodeQueue((1..150).map(::song))).size)
+ assertTrue(LastSession.decodeQueue("{broken").isEmpty())
+ assertTrue(LastSession.decodeQueue(null).isEmpty())
+ }
+
+ @Test fun olderPausedEngineStateDoesNotReplaceLocalSession() {
+ assertTrue(LastSession.engineStateIsStale(LastSession.SOURCE_LOCAL, 2000, 1000, true))
+ assertFalse(LastSession.engineStateIsStale(LastSession.SOURCE_LOCAL, 2000, 3000, true))
+ assertFalse(LastSession.engineStateIsStale(LastSession.SOURCE_LOCAL, 2000, 1000, false))
+ assertFalse(LastSession.engineStateIsStale(LastSession.SOURCE_SPOTIFY, 2000, 1000, true))
+ }
+}
diff --git a/base/app/src/test/java/com/music/spotui/di/StreamErrorsTest.kt b/base/app/src/test/java/com/music/spotui/di/StreamErrorsTest.kt
new file mode 100644
index 00000000..fdd6a2bc
--- /dev/null
+++ b/base/app/src/test/java/com/music/spotui/di/StreamErrorsTest.kt
@@ -0,0 +1,41 @@
+package com.music.spotui.di
+
+import com.music.spotui.di.StreamErrors.Step
+import org.junit.Assert.assertEquals
+import org.junit.Test
+
+class StreamErrorsTest {
+ @Test fun `a failing song is asked again once`() {
+ val e = StreamErrors()
+ assertEquals(Step.RETRY, e.failed("a", true))
+ assertEquals(Step.SKIP, e.failed("a", true))
+ }
+
+ @Test fun `each song gets its own retry`() {
+ val e = StreamErrors()
+ e.failed("a", true); e.failed("a", true)
+ assertEquals(Step.RETRY, e.failed("b", true))
+ }
+
+ @Test fun `no more than two songs in a row are skipped`() {
+ val e = StreamErrors()
+ listOf("a", "b", "c").forEach { e.failed(it, true) }
+ assertEquals(Step.SKIP, e.failed("a", true))
+ assertEquals(Step.SKIP, e.failed("b", true))
+ assertEquals(Step.STOP, e.failed("c", true))
+ }
+
+ @Test fun `a song that played resets the count`() {
+ val e = StreamErrors()
+ e.failed("a", true); e.failed("a", true); e.failed("b", true); e.failed("b", true)
+ e.played()
+ e.failed("c", true)
+ assertEquals(Step.SKIP, e.failed("c", true))
+ }
+
+ @Test fun `the last song of the queue stops`() {
+ val e = StreamErrors()
+ e.failed("a", false)
+ assertEquals(Step.STOP, e.failed("a", false))
+ }
+}
diff --git a/base/app/src/test/java/com/music/spotui/ui/immersive/lyrics/QueueDragMathTest.kt b/base/app/src/test/java/com/music/spotui/ui/immersive/lyrics/QueueDragMathTest.kt
new file mode 100644
index 00000000..73c6464f
--- /dev/null
+++ b/base/app/src/test/java/com/music/spotui/ui/immersive/lyrics/QueueDragMathTest.kt
@@ -0,0 +1,135 @@
+package com.music.spotui.ui.immersive.lyrics
+
+import com.music.spotui.di.LocalQueueOrder
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class QueueDragMathTest {
+ @Test fun slotCountsMidpointsAbove() {
+ val mids = listOf(30f, 90f, 150f)
+ assertEquals(0, QueueDragMath.slot(10f, mids))
+ assertEquals(2, QueueDragMath.slot(100f, mids))
+ assertEquals(3, QueueDragMath.slot(500f, mids))
+ }
+
+ @Test fun rowsStepAsideBetweenFromAndSlot() {
+ // row 1 of 5 dragged down over gap 3 of the others: rows 2 and 3 step up
+ assertEquals(listOf(0, 0, -1, -1, 0), (0..4).map { QueueDragMath.step(it, 1, 3) })
+ // row 3 dragged up over gap 1: rows 1 and 2 step down
+ assertEquals(listOf(0, 1, 1, 0, 0), (0..4).map { QueueDragMath.step(it, 3, 1) })
+ assertEquals(listOf(0, 0, 0, 0, 0), (0..4).map { QueueDragMath.step(it, 2, 2) })
+ }
+
+ @Test fun placeSplitsAtTheSections() {
+ assertEquals(QueueDragMath.Place(true, 1), QueueDragMath.place(1, 3, false))
+ assertEquals(QueueDragMath.Place(false, 2), QueueDragMath.place(5, 3, true))
+ assertEquals(QueueDragMath.Place(true, 3), QueueDragMath.place(3, 3, true))
+ assertEquals(QueueDragMath.Place(false, 0), QueueDragMath.place(3, 3, false))
+ }
+
+ @Test fun movedKeepsTheDroppedOrder() {
+ assertEquals(listOf("b", "c", "a"), QueueDragMath.moved(listOf("a", "b", "c"), 0, 2))
+ assertEquals(listOf("c", "a", "b"), QueueDragMath.moved(listOf("a", "b", "c"), 2, 0))
+ }
+
+ @Test fun edgeStepGrowsTowardsTheEdge() {
+ assertEquals(0f, QueueDragMath.edgeStep(500f, 1000f, 100f, 20f), 0f)
+ assertEquals(-10f, QueueDragMath.edgeStep(50f, 1000f, 100f, 20f), 0.001f)
+ assertEquals(20f, QueueDragMath.edgeStep(1000f, 1000f, 100f, 20f), 0.001f)
+ assertTrue(QueueDragMath.edgeStep(20f, 1000f, 100f, 20f) < QueueDragMath.edgeStep(80f, 1000f, 100f, 20f))
+ }
+
+ // ── The panel's expected order against what the local player's move logic ends with ──
+
+ /** cur, then [nq] queued songs q0.., then [nn] list songs n0.. */
+ private fun local(nq: Int, nn: Int): Triple<List<String>, Set<String>, Int> {
+ val queued = (0 until nq).map { "q$it" }
+ return Triple(listOf("cur") + queued + (0 until nn).map { "n$it" }, queued.toSet(), 0)
+ }
+
+ @Test fun everyDropEndsInThePanelsOrderOnTheLocalPlayer() {
+ var checked = 0
+ for (nq in 0..3) for (nn in 0..3) {
+ val (order, queuedSet, cur) = local(nq, nn)
+ val rows = order.drop(1)
+ for (dragged in rows) for (above in listOf(true, false)) {
+ val oq = rows.filter { it in queuedSet && it != dragged }
+ val on = rows.filter { it !in queuedSet && it != dragged }
+ for (slot in 0..(oq.size + on.size)) {
+ val place = QueueDragMath.place(slot, oq.size, above)
+ val (eq, en) = QueueDragMath.apply(oq, on, dragged, place)
+ if (eq == rows.filter { it in queuedSet } && en == rows.filter { it !in queuedSet }) continue
+ val into = if (place.toQueue) oq else on
+ val target = QueueDragMath.target(into.size, place.index)
+ val from = order.indexOf(dragged)
+ val wasQueued = dragged in queuedSet
+ val result: Pair<List<String>, Boolean>? = when {
+ place.toQueue && !wasQueued && target == null ->
+ LocalQueueOrder.moveToFront(order, cur, from)?.let { it to true }
+ target == null -> continue
+ else -> LocalQueueOrder.moveBeside(order, cur, from, order.indexOf(into[target.first]), target.second) { it in queuedSet }
+ }
+ val (after, toQueue) = result!!
+ val nowQueued = { x: String -> if (x == dragged) toQueue else x in queuedSet }
+ val tail = after.drop(1)
+ assertEquals("cur stays", "cur", after[0])
+ assertEquals("queued part $dragged slot $slot nq=$nq nn=$nn above=$above", eq, tail.filter(nowQueued))
+ assertEquals("list part $dragged slot $slot nq=$nq nn=$nn above=$above", en, tail.filterNot(nowQueued))
+ assertEquals("queued songs come first", tail.filter(nowQueued), tail.take(eq.size))
+ checked++
+ }
+ }
+ }
+ assertTrue(checked > 100)
+ }
+
+ @Test fun targetNamesTheNeighbourToDropBesideOrNothing() {
+ assertEquals(null, QueueDragMath.target(0, 0))
+ assertEquals(0 to false, QueueDragMath.target(3, 0))
+ assertEquals(1 to false, QueueDragMath.target(3, 1))
+ assertEquals(2 to true, QueueDragMath.target(3, 3))
+ }
+
+ @Test fun aQueuedSpotifySongStaysInTheQueue() {
+ val into = QueueDragMath.Place(false, 2)
+ assertEquals(QueueDragMath.Place(true, 3), QueueDragMath.held(into, 3, canLeaveQueue = false, fromQueue = true))
+ assertEquals(into, QueueDragMath.held(into, 3, canLeaveQueue = true, fromQueue = true))
+ assertEquals(into, QueueDragMath.held(into, 3, canLeaveQueue = false, fromQueue = false))
+ }
+
+ // ── The Spotify queue's reports while a move is applied: stale, half-way, final ──
+
+ private fun pending(q: List<String>, n: List<String>) = QueueDragMath.Pending(q, n, q, n, "cur")
+
+ @Test fun noReportBeforeTheFinalOneEndsThePendingOrder() {
+ // "n1" dragged from the list into the queue, between q0 and q1.
+ val q0 = listOf("q0", "q1"); val n0 = listOf("n0", "n1", "n2")
+ val (eq, en) = QueueDragMath.apply(q0, n0, "n1", QueueDragMath.Place(true, 1))
+ val p = pending(eq, en)
+ assertEquals(listOf("q0", "n1", "q1"), eq)
+ assertEquals(listOf("n0", "n2"), en)
+ val reports = listOf(
+ q0 to n0, // stale: before the edit
+ q0 to listOf("n0", "n2"), // removed from the list, not yet queued
+ q0 + "n1" to listOf("n0", "n2"), // queued at the end
+ )
+ for ((rq, rn) in reports) assertFalse("$rq $rn", p.over(rq, rn, "cur"))
+ assertTrue(p.over(eq, en, "cur")) // final
+ assertEquals(eq, p.queued); assertEquals(en, p.next) // what is drawn all along
+ }
+
+ @Test fun aSameSectionMoveEndsOnItsFinalReportOnly() {
+ val n0 = listOf("n0", "n1", "n2", "n3")
+ val (eq, en) = QueueDragMath.apply(emptyList(), n0, "n0", QueueDragMath.Place(false, 3))
+ val p = pending(eq, en)
+ assertEquals(listOf("n1", "n2", "n3", "n0"), en)
+ assertFalse(p.over(emptyList(), n0, "cur"))
+ assertTrue(p.over(eq, en, "cur"))
+ }
+
+ @Test fun anotherSongPlayingEndsThePendingOrder() {
+ assertTrue(pending(listOf("a"), listOf("b")).over(listOf("x"), listOf("y"), "other"))
+ }
+}
diff --git a/base/extensions/src/main/kotlin/app/myspoti/extensions/SpotifyMethods.kt b/base/extensions/src/main/kotlin/app/myspoti/extensions/SpotifyMethods.kt
index 4e3c1fd1..8a8ea1d0 100644
--- a/base/extensions/src/main/kotlin/app/myspoti/extensions/SpotifyMethods.kt
+++ b/base/extensions/src/main/kotlin/app/myspoti/extensions/SpotifyMethods.kt
@@ -297,6 +297,7 @@ object SpotifyMethods {
typed("player", "moveInQueue", QUEUE, "reorder the queue") { a -> player.moveInQueue(a.queueItem(0, "item"), a.queueItem(1, "target"), a.bool(2, "after", false)) }
typed("player", "setVolume", CONTROL, "change the volume") { a -> player.setVolume(a.double(0, "level")) }
typed("player", "setSpeed", CONTROL, "change the playback speed") { a -> player.setSpeed(a.double(0, "speed")) }
+ typed("player", "setLocalMute", CONTROL, "keep playing unheard on this phone") { a -> player.setLocalMute(a.bool(0, "on")) }
// ── search ──
typed("search", "all", CATALOG) { a -> search.all(a.str(0, "query"), a.int(1, "limit", 10)) }
diff --git a/base/extensions/src/main/resources/app/myspoti/extensions/prelude.js b/base/extensions/src/main/resources/app/myspoti/extensions/prelude.js
index 6101f7f1..568caebe 100644
--- a/base/extensions/src/main/resources/app/myspoti/extensions/prelude.js
+++ b/base/extensions/src/main/resources/app/myspoti/extensions/prelude.js
@@ -122,9 +122,9 @@
/**
* What this app understands beyond the first API, for an extension to adapt to: "audio.manifest",
- * "audio.expires", "audio.quality", "audio.source", "audio.ahead", "http.all", "status", "raw.base64".
+ * "audio.expires", "audio.quality", "audio.source", "audio.ahead", "http.all", "status", "raw.base64", "player.localMute".
*/
- features: Object.freeze(['audio.manifest', 'audio.expires', 'audio.quality', 'audio.source', 'audio.ahead', 'http.all', 'status', 'raw.base64']),
+ features: Object.freeze(['audio.manifest', 'audio.expires', 'audio.quality', 'audio.source', 'audio.ahead', 'http.all', 'status', 'raw.base64', 'player.localMute']),
/**
* A sign-in page (webview.auth): open({ url, callback, hidden }) shows url in a web view of its
diff --git a/docs/extensions/API.md b/docs/extensions/API.md
index 1e7ffb41..efdb7174 100644
--- a/docs/extensions/API.md
+++ b/docs/extensions/API.md
@@ -854,6 +854,7 @@ type means optional/nullable. Returns of "—" mean `null`.
| `skipTo(item: {uri,uid?})` | — | write | |
| `moveInQueue(item: {uri,uid?}, target: {uri,uid?}, after = false)` | — | write | |
| `setVolume(level: number)` | — | write | |
+| `setLocalMute(on: boolean)` | — | write | Keeps the Web Player playing but unheard (`myspoti.features` has `player.localMute`). While on, the app ignores the Web Player's state, so an extension playing a file itself can mirror the same track there without being replaced. Cleared when the local player stops. |
| `setSpeed(speed: number)` | — | write | |
`media(trackUri)` (also `myspoti.spotify.media(trackUri)`) returns the media manifest Spotify sent the