Native Android client for Spotify, built with Jetpack Compose
Kotlin ad-freeadblockandroidjetpack-composekotlinlyricsmusic-playermusic-videomyspotispotifyspotify-adblockerspotify-clientspotify-connectspotui
2.0.2-beta.5: optional Immersive look (glass tab bar and mini player that fold away on scroll, animated player and lyrics, grouped Settings, glass sheets, offered at first open), sharp player covers, background playback that keeps running, 402 refusals: browser-shaped commands, a Chromium retry and no ghost device, no songs skipping when audio licences are limited, shorter diagnostic reports with a 402 summary
kota-zo5b8754d5eeeb
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f97ff47d..ea44ff1f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,16 @@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.5++- ✨ **New Immersive look** (optional, Apple-Music-like): glass tab bar and mini player that fold away when you scroll, animated player and lyrics, grouped Settings, glass sheets (Spotify Connect, queue, quality…). Offered at the first open after the update; switch any time in Settings, Display. Classic stays the default.+- 🎤 **Lyrics** (Immersive): the new line loses its blur the moment it becomes current.+- 🖼️ **Sharp covers** in the player: the large image instead of a stretched thumbnail.+- 🎧 **Background playback**: the player keeps running when you switch apps or turn the screen off.+- 🚫 **"Spotify refused to play this" (402)**: commands sent like the browser's, a Chromium network retry after a refusal, and no more ghost copy of this phone among your devices. Still refused? Please send a diagnostic report from this version: it now opens with a short summary of the cause.+- ⏭️ **No more songs skipping on their own** when Spotify limits audio licences: the app waits instead of asking again.+- 🧹 **Lighter diagnostic reports**: a third shorter, without the repeated lines.+## 2.0.2-beta.4- 🧩 **Download sources are extensions now**: the app no longer carries any download source. Install a download-source extension (Settings, Extensions) and downloads work as before: checked, encrypted, kept in Myspoti. Without one, downloads say so.diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex 675309a3..1553ffa1 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -8,3 +8,63 @@ https://github.com/Spotui/SpotuiThe DASH-to-FLAC remux (`base/app/src/main/java/com/music/spotui/data/offline/DashFlacRemux.kt`)is ported from Spotui and stays under the GPL-3.0. The file says so in its header.++## BitChord — GPL-3.0-or-later+https://github.com/kushagrasinghx/BitChord (commit `edc1e6f`)++By the BitChord contributors. The Immersive look is ported from it. These files in+`base/app/src/main/java/com/music/spotui/ui/look/` are adapted from BitChord, stay under the+GPL-3.0-or-later, and say so in their header:++- `MeshGradient.kt`, from `sharedUi/.../ui/player/MeshGradient.kt` (the mesh backdrop and `cyclingMeshPalette`)+- `ThinSlider.kt`, from `sharedUi/.../ui/player/ThinSlider.kt` (the thin seek bar, without Automix)+- `LyricClock.kt`, from `sharedUi/.../ui/player/LyricClock.kt` (the smoothed lyric playhead)+- `SweptLyricLine.kt`, from `sharedUi/.../ui/player/PlayerLyrics.kt` (`SweptLyricLine`, its drawing+ helpers and constants) and `sharedUi/src/androidMain/.../ui/player/PlayerPlatformUi.android.kt`+- `SweptLyricModel.kt`, from `shared/.../data/lyrics/LyricLine.kt` (word timing, lift and glow)++The Immersive UI in `base/app/src/main/java/com/music/spotui/ui/immersive/` (player, lyrics, queue,+tab bar, top bars, sheets, motion, components, Home, Search, Library, Category, album/playlist, artist, profile, podcast and download pages) is+adapted from these BitChord files, each named in the header of the Myspoti file that carries it:+`sharedUi/.../ui/player/` NowPlayingScreen, PlayerControls, PlayerState, PlayerHost, PlayerLyrics,+PlayerQueue; `sharedUi/.../ui/components/` Common, SearchField, Skeletons, SongText, OptimizedHaze;+`sharedUi/.../ui/screens/` HomeScreen, SearchScreen, LibraryScreen, ExploreScreen;+`app/.../ui/components/` MiniPlayer, FrostedTopBar, GlassNavBar, BottomFadeScrim,+floatingtabbar/FloatingTabBar, floatingtabbar/GlassSelectionPill; `app/.../ui/player/PlayerSheetMotion`;+`app/.../ui/screens/` DetailScreen, LibraryPhoneParts; `app/.../ui/utils/IosOverscroll`.++No BitChord fonts, icons, images or brand are included.++Code that BitChord itself carries from other projects, kept with its own header:+- `shell/FloatingTabBar.kt`: compose-floating-tab-bar by Elyes Mansour+ (https://github.com/elyesmansour/compose-floating-tab-bar), Apache-2.0, through Echo-Music+ (https://github.com/EchoMusicApp/Echo-Music), GPL-3.0.+- `shell/GlassSelectionPill.kt`: the pill motion follows liquid_glass_easy+ (https://pub.dev/packages/liquid_glass_easy), MIT License, Copyright (c) 2025 Ahmed Gamil.+- `components/ImmersiveOverscroll.kt`: from Convx (https://github.com/cosmictaserdev-creator/Convx), GPL-3.0.+- `shell/ImmersiveGlass.kt` (Liquid Glass): adapted from BitChord's `app/.../ui/components/LiquidGlass.kt`,+ itself adapted from Echo-Music's GlassEffectConfig / `Modifier.liquidGlass`+ (https://github.com/EchoMusicApp/Echo-Music), GPL-3.0. The lens of `shell/GlassSelectionPill.kt` and+ the minimizing chrome of `shell/ImmersiveChrome.kt` follow BitChord's `floatingtabbar/` files.++## Backdrop — Apache-2.0+https://github.com/Kyant0/backdrop (v2.0.0, `io.github.kyant0:backdrop`), Copyright 2025 Kyant0.++The refraction, blur, rim highlight and shadow of the Immersive look's Liquid Glass. Vendored as+source in `base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/`, taken from+BitChord's vendored copy (which adds a backdrop resolution scale and an exported backdrop, used to+keep the GPU cost down; the published artifact has neither). Every file keeps its Apache-2.0 header;+the package is renamed. Licence text in `base/licenses/Apache-2.0.txt` (it also covers Haze and+compose-floating-tab-bar above).++## Haze — Apache-2.0+https://github.com/chrisbanes/haze++The frosted bars of the Immersive look (Gradle dependency `dev.chrisbanes.haze:haze`).++## Inter — SIL Open Font License 1.1+https://github.com/rsms/inter++The Immersive look's typeface (`base/app/src/main/res/font/inter.ttf`), Copyright 2020 The Inter+Project Authors. Cut down to Latin with its weight axis only. Licence text in+`base/licenses/Inter-OFL.txt`.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.ktindex a7d56354..8ad24f76 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@@ -27,6 +27,7 @@ import kotlinx.serialization.json.booleanOrNullimport kotlinx.serialization.json.contentOrNullimport kotlinx.serialization.json.doubleimport kotlinx.serialization.json.doubleOrNull+import kotlinx.serialization.json.intOrNullimport kotlinx.serialization.json.jsonPrimitiveimport kotlinx.serialization.json.putimport kotlinx.serialization.json.putJsonArray@@ -346,7 +347,13 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop/** What the page player itself is set to; null when the page did not say. */val playerVolume: Double?,val active: Boolean?,- )+ /** HTMLMediaElement readyState / networkState and its error, for the log only (a stall's "why"). */+ val readyState: Int = -1,+ val networkState: Int = -1,+ val error: String? = null,+ ) {+ fun describe() = "paused=$paused muted=$muted volume=$level own=$own t=${"%.1f".format(time)} ready=$readyState net=$networkState error=${error ?: "none"} active=$active"+ }private suspend fun readMedia(): Media? {val o = bridge.call("media.state", timeoutMs = MEDIA_TIMEOUT_MS, quiet = true) as? JsonObject ?: return null@@ -361,6 +368,9 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop// The device list is read at most every few seconds in the page: what it did not// answer this time is what it answered last time.active = p("active")?.booleanOrNull ?: lastMedia?.active,+ readyState = p("readyState")?.intOrNull ?: -1,+ networkState = p("networkState")?.intOrNull ?: -1,+ error = p("error")?.contentOrNull?.takeIf { it != "null" },)}@@ -525,7 +535,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopsince = nowattempts++silentSince = 0L- bridge.logger?.invoke("player stalled ($reason) on ${s.item?.name}, attempt $attempts")+ bridge.logger?.invoke("player stalled ($reason) on ${s.item?.name}, attempt $attempts; media element: ${media?.describe() ?: "none"}")// A song stuck at its end moves on; one stuck in its middle goes on where it was.val onward = reason == "past the end" || reason == "paused at the end"// A frozen page answers nothing: straight to the reload.@@ -886,6 +896,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopadSince = System.currentTimeMillis()adMuteTries = 0bridge.logger?.invoke("ad break started")+ app.myspoti.spotify.report.Refusal402.adBreak()// A song picked a moment ago and not playing yet: the ad came in its place.val p = lastPlayval came = p?.takeIf {diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/Bridge.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/Bridge.ktindex 500adc4c..2829656f 100644--- a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/Bridge.kt+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/Bridge.kt@@ -48,17 +48,64 @@ class Bridge(private val host: BridgeHost, scope: CoroutineScope) {}}+ /** The last track the page's state named, to count the songs it started. */+ private var lastTrack: String? = null+ private var lastStateLine: String? = null+ private var lastStateKey: String? = null+ private var lastStateAt = 0L++ /**+ * The page posts its state several times a second while a song buffers (a "page state" line+ * was the most frequent of every report, 755 in the Discord attachments). Logged when the song+ * or paused changes; a buffering flip of the same song at most every [STATE_EVERY_MS].+ */+ private fun stateWorthLogging(line: String, key: String): Boolean {+ val now = System.currentTimeMillis()+ if (line == lastStateLine) return false+ val changed = key != lastStateKey+ if (!changed && now - lastStateAt < STATE_EVERY_MS) return false+ lastStateLine = line; lastStateKey = key; lastStateAt = now+ return true+ }++ /**+ * The page's resource notes: only failed ones are logged (status 0 is "not readable", left+ * out too unless it is a command). Every audio licence answer goes to the 402 summary's counts+ * instead of the log (it came three times per answer: page net, http, licence answer).+ */+ private fun netWorthLogging(msg: JsonObject): Boolean {+ val url = (msg["url"] as? JsonPrimitive)?.contentOrNull ?: return true+ val status = (msg["status"] as? JsonPrimitive)?.intOrNull ?: 0+ if ("widevine-license" in url) return false+ return status >= 400 || (status == 0 && "player/command" in url)+ }++ private fun licenceNote(msg: JsonObject) {+ val url = (msg["url"] as? JsonPrimitive)?.contentOrNull ?: return+ if ("widevine-license" !in url) return+ app.myspoti.spotify.report.Refusal402.licence((msg["status"] as? JsonPrimitive)?.intOrNull ?: 0)+ }+private fun handle(raw: String) {val msg = runCatching { json.parseToJsonElement(raw) }.getOrNull() as? JsonObject ?: return// Lenient reads: a field of an unexpected type counts as missing.fun field(name: String) = msg[name] as? JsonPrimitiveval type = field("type")?.contentOrNull+ if (type == "state") {+ val track = ((msg["state"] as? JsonObject)?.get("track") as? JsonObject)?.get("name")?.toString()+ if (track != null && track != lastTrack) { lastTrack = track; app.myspoti.spotify.report.Refusal402.song() }+ }+ if (type == "ready") app.myspoti.spotify.report.Refusal402.pageReady()+ if (type == "net") licenceNote(msg)logger?.let { log ->if (type == "state") {val s = msg["state"] as? JsonObject- log("page state: " + (s?.get("track") as? JsonObject)?.get("name") + " paused=" + s?.get("isPaused") + " buffering=" + s?.get("isBuffering"))+ val line = "page state: " + (s?.get("track") as? JsonObject)?.get("name") + " paused=" + s?.get("isPaused") + " buffering=" + s?.get("isBuffering")+ if (stateWorthLogging(line, s?.get("track")?.toString() + s?.get("isPaused"))) log(line)} else if (type == "result") {// Results are logged by call(); never write their values (tokens) here.+ } else if (type == "net" && !netWorthLogging(msg)) {+ // A playback request that went through, or a licence answer (counted in the 402 summary).} else if (type != "queue") log("page $type: " + raw.take(300))}when (type) {@@ -151,6 +198,9 @@ class Bridge(private val host: BridgeHost, scope: CoroutineScope) {companion object {val json = Json { ignoreUnknownKeys = true }++ /** A buffering flip of the same song is logged at most this often (see stateWorthLogging). */+ const val STATE_EVERY_MS = 5_000L}}diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/RelayRoutes.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/RelayRoutes.ktindex f2932e6b..485e188f 100644--- a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/RelayRoutes.kt+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/RelayRoutes.kt@@ -9,14 +9,21 @@ import java.net.UnknownHostException* Which way the host sends the page's relayed requests (see the host's ControlRelay).** Some free accounts get every relayed command refused (402 COMMAND_FAILED) from the first one,- * while the same phone plays in a browser. One lead (2026-10-23 reports): the WebView reaches- * Spotify over one address family and the host's own client over the other (IPv6 against IPv4,- * 464XLAT), so Spotify sees the commands come from another place than the player — a remote- * control, which a free account may not use. A refused command is sent once more pinned to the- * other family, then through the platform's own HTTP stack; whichever is taken is kept for the- * rest of the session, for every relayed request.+ * while the same account plays in Chrome. The lead kept (402-ANALYSIS, H2): for such accounts+ * Spotify checks the shape of a genuine browser's request, down to its network stack (the TLS+ * ClientHello, the HTTP/2 settings), which OkHttp does not have. A refused command is sent again+ * through a Chromium network stack first: the platform's own (android.net.http, Android 14+), or+ * Cronet from Google Play services on older versions. The other address family comes next (an+ * older lead: the WebView and the host's client on different families, 464XLAT). Whichever is+ * answered is kept for the rest of the session, for every relayed request; a session that was+ * never refused stays on OkHttp.*/-enum class RelayRoute { DEFAULT, IPV4, IPV6, HTTP_ENGINE }+enum class RelayRoute {+ DEFAULT, IPV4, IPV6, HTTP_ENGINE, CRONET;++ /** A Chromium network stack, not OkHttp. */+ val chromium: Boolean get() = this == HTTP_ENGINE || this == CRONET+}enum class IpFamily {V4, V6;@@ -30,7 +37,17 @@ enum class IpFamily {}}-class RelayRoutes(private val engineAvailable: Boolean) {+/**+ * [chromium]: the Chromium stack this phone offers now ([RelayRoute.HTTP_ENGINE] or+ * [RelayRoute.CRONET]), null when it has none. Asked at each refusal: Cronet is there only once+ * Google Play services has installed its provider.+ */+class RelayRoutes(private val chromium: () -> RelayRoute?) {+ constructor(engineAvailable: Boolean) : this({ if (engineAvailable) RelayRoute.HTTP_ENGINE else null })++ /** The Chromium stack this phone offers now, if any. */+ fun chromiumRoute(): RelayRoute? = chromium()+/** The route every relayed request takes: [RelayRoute.DEFAULT] until another was taken after a refusal. */@Volatile var kept: RelayRoute = RelayRoute.DEFAULTprivate set@@ -44,13 +61,12 @@ class RelayRoutes(private val engineAvailable: Boolean) {val other = when {used == IpFamily.V6 -> RelayRoute.IPV4used == IpFamily.V4 -> RelayRoute.IPV6- tried.lastOrNull() == RelayRoute.IPV4 -> RelayRoute.IPV6+ RelayRoute.IPV4 in tried -> RelayRoute.IPV6else -> RelayRoute.IPV4}- // The other family is tried once: a retry pinned to it that was refused too leaves the- // platform stack only.+ // The Chromium stack first, then the other family, each once.val familyRetried = tried.drop(1).any { it == RelayRoute.IPV4 || it == RelayRoute.IPV6 }- val order = listOfNotNull(other.takeIf { !familyRetried }, RelayRoute.HTTP_ENGINE.takeIf { engineAvailable })+ val order = listOfNotNull(chromium(), other.takeIf { !familyRetried })return order.firstOrNull { it !in tried }}diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/report/Refusal402.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/report/Refusal402.ktnew file mode 100644index 00000000..36adf6d4--- /dev/null+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/report/Refusal402.kt@@ -0,0 +1,234 @@+package app.myspoti.spotify.report++/**+ * The "402 summary" at the top of a diagnostic report: what one report from an account whose+ * Connect commands Spotify refuses (402 COMMAND_FAILED, some free accounts) must settle, in one+ * screen, so nobody has to dig it out of the log again (402-ANALYSIS, 402-logger-REPORT):+ *+ * 1. per route (okhttp, HTTP_ENGINE, CRONET, the page's own fetch): the answers, their latency,+ * the headers Spotify adds on a refusal, the body's error_type, and whether a 2xx on another+ * route really started the audio within 10 s;+ * 2. the account's devices as the first cluster shows them (no ids), and the ads this session met;+ * 3. what the page's own fetch got for the same command, and the page's connect-state PUT;+ * 4. timing: page ready / registration to the first command, whether any command was accepted,+ * refusals soon after an ad break or a transfer;+ * 5. the audio licence's answers by code, its retry-after, and whether 403/429 met a 402.+ *+ * Events come from the host (relay, WebView) and the player; nothing here holds an id, a token or+ * an address. Thread-safe; [clock] is a monotonic clock in ms (replaced in tests).+ */+object Refusal402 {+ @Volatile var clock: () -> Long = { System.nanoTime() / 1_000_000 }++ /** Two events this close count as "after" one another (a refusal after an ad break or a transfer). */+ const val NEAR_MS = 60_000L+ /** A licence 403/429 this close to a 402 counts as coinciding with it. */+ const val COINCIDE_MS = 30_000L++ private class Route(var answers: MutableMap<Int, Int> = sortedMapOf(), val ms: MutableList<Long> = ArrayList())++ private val lock = Any()+ private var pageReadyAt = -1L+ private var registeredAt = -1L+ private var registration = sortedMapOf<Int, Int>()+ private var firstCommand: String? = null+ private val firstPerPage = ArrayDeque<String>()+ private var pageFirstPending = false+ private var commands = 0+ private var accepted = 0+ private var refusedCommands = 0+ private val refusedKinds = sortedMapOf<String, Int>()+ private val routes = LinkedHashMap<String, Route>()+ private val errorTypes = sortedMapOf<String, Int>()+ private val refusalHeaders = sortedMapOf<String, MutableSet<String>>()+ private val wonRetries = sortedMapOf<String, IntArray>() // route -> [2xx after a refusal, audio started]+ private val pageFetch = sortedMapOf<Int, Int>()+ private var pageKept = 0+ private var pageDropped = 0+ private val connectPut = sortedMapOf<Int, Int>()+ private var connectPutHeaders: String? = null+ private var firstCluster: String? = null+ private var lastCluster: String? = null+ private var adBreaks = 0+ private var adStatesLeftOut = 0+ private var lastAdAt = -1L+ private var lastTransferAt = -1L+ private var afterAd = 0+ private var afterTransfer = 0+ private val refusalTimes = ArrayDeque<Long>()+ private val licence = sortedMapOf<Int, Int>()+ private val licenceErrorTimes = ArrayDeque<Long>()+ private var licenceHeld = 0+ private val retryAfter = LinkedHashSet<String>()+ private var songs = 0++ fun reset() = synchronized(lock) {+ pageReadyAt = -1; registeredAt = -1; registration.clear(); firstCommand = null; firstPerPage.clear()+ pageFirstPending = false; commands = 0; accepted = 0; refusedCommands = 0; refusedKinds.clear(); routes.clear()+ errorTypes.clear(); refusalHeaders.clear(); wonRetries.clear(); pageFetch.clear(); pageKept = 0; pageDropped = 0+ connectPut.clear(); connectPutHeaders = null; firstCluster = null; lastCluster = null; adBreaks = 0+ adStatesLeftOut = 0; lastAdAt = -1; lastTransferAt = -1; afterAd = 0; afterTransfer = 0; refusalTimes.clear()+ licence.clear(); licenceErrorTimes.clear(); licenceHeld = 0; retryAfter.clear(); songs = 0+ }++ /** The page's player said "ready" (a new page: its first command is timed again). */+ fun pageReady() = synchronized(lock) { pageReadyAt = clock(); pageFirstPending = true }++ /** The playback device registration was answered. */+ fun registered(code: Int) = synchronized(lock) {+ registration.merge(code, 1, Int::plus)+ if (code in 200..299) registeredAt = clock()+ }++ /**+ * One route's answer to a relayed command ([code] null: the route failed to answer). [kind] is+ * the command's endpoint ("play", "seek_to"...) or "transfer". [headers] are the answer's own;+ * only the names a refusal can explain itself with are kept ([explaining]).+ */+ fun attempt(kind: String, route: String, code: Int?, ms: Long, headers: List<Pair<String, String>>, body: String) = synchronized(lock) {+ val r = routes.getOrPut(route) { Route() }+ r.answers.merge(code ?: 0, 1, Int::plus)+ if (code != null) r.ms += ms+ if (code != null && code >= 400) {+ errorType(body)?.let { errorTypes.merge(it, 1, Int::plus) }+ headers.filter { explaining(it.first) }.forEach { (n, v) ->+ val values = refusalHeaders.getOrPut(n.lowercase()) { LinkedHashSet() }+ if (values.size < 4) values += v.take(40)+ }+ }+ }++ /** A relayed command's final answer (after every retry route); [retried] when a route was refused before. */+ fun command(kind: String, code: Int, retried: Boolean) = synchronized(lock) {+ val now = clock()+ commands+++ val ok = code in 200..299+ if (ok) accepted+++ val timing = buildString {+ append("$code")+ if (retried) append(" after a refusal")+ if (pageReadyAt >= 0) append(", ${secs(now - pageReadyAt)} after page ready")+ if (registeredAt >= 0) append(", ${secs(now - registeredAt)} after registration")+ }+ if (firstCommand == null) firstCommand = "$kind -> $timing"+ if (pageFirstPending) {+ pageFirstPending = false+ firstPerPage.addLast("$kind ${if (ok && !retried) "ok" else if (ok) "ok after refusal" else "$code"}")+ while (firstPerPage.size > 4) firstPerPage.removeFirst()+ }+ if (retried || code == 402 || code == 403) {+ refusedCommands+++ refusedKinds.merge(kind, 1, Int::plus)+ if (lastAdAt >= 0 && now - lastAdAt <= NEAR_MS) afterAd+++ if (lastTransferAt >= 0 && now - lastTransferAt <= NEAR_MS && kind != "transfer") afterTransfer+++ refusalTimes.addLast(now)+ while (refusalTimes.size > 200) refusalTimes.removeFirst()+ }+ if (kind == "transfer") lastTransferAt = now+ }++ /** A refused command that another route answered 2xx, 10 s later: did the audio start? */+ fun audioAfterRetry(route: String, started: Boolean) = synchronized(lock) {+ val c = wonRetries.getOrPut(route) { IntArray(2) }+ c[0]+++ if (started) c[1]+++ }++ /** The page's own fetch of a command the relay saw refused. */+ fun pageFetch(code: Int) = synchronized(lock) { pageFetch.merge(code, 1, Int::plus) }++ /** 10 s after a page fetch answered 2xx: something played (kept) or nothing did. */+ fun pageKept(kept: Boolean) = synchronized(lock) { if (kept) pageKept++ else pageDropped++ }++ /** The page's connect-state device PUT (it joins the cluster): status and header names. */+ fun connectStatePut(code: Int, headerNames: String) = synchronized(lock) {+ connectPut.merge(code, 1, Int::plus)+ connectPutHeaders = headerNames.take(300)+ }++ /** A cluster, already without ids (devices, their types, player_state). */+ fun cluster(brief: String) = synchronized(lock) {+ if (firstCluster == null) firstCluster = brief+ lastCluster = brief+ }++ fun adBreak() = synchronized(lock) { adBreaks++; lastAdAt = clock() }+ fun adStateLeftOut() = synchronized(lock) { adStatesLeftOut++; lastAdAt = clock() }++ /** A song the page started (its track changed). */+ fun song() = synchronized(lock) { songs++ }++ /** An audio licence answer the page saw (0: the status was not readable). */+ fun licence(code: Int) = synchronized(lock) {+ licence.merge(code, 1, Int::plus)+ if (code == 403 || code == 429) {+ licenceErrorTimes.addLast(clock())+ while (licenceErrorTimes.size > 200) licenceErrorTimes.removeFirst()+ }+ }++ /** An audio licence request answered 429 here, never sent (the app's hold). */+ fun licenceHeld() = synchronized(lock) { licenceHeld++ }++ fun licenceRetryAfter(value: String) = synchronized(lock) { if (retryAfter.size < 4) retryAfter += value.take(20) }++ /**+ * The summary block, lines of "label : value". [account] and [installAge] come from the host+ * (the account fact, the app's install age bucket).+ */+ fun summary(account: String?, installAge: String?): List<Pair<String, String>> = synchronized(lock) {+ val out = ArrayList<Pair<String, String>>()+ val verdict = when {+ commands == 0 -> "no relayed command this session"+ refusedCommands == 0 -> "no command refused ($accepted of $commands accepted)"+ accepted == 0 && pageKept == 0 -> "every command refused ($refusedCommands of $commands), no route played"+ else -> "$refusedCommands of $commands commands refused first; $accepted accepted in the end; page fetch played $pageKept×"+ }+ out += "verdict" to verdict+ out += "account" to listOfNotNull(account ?: "unknown", installAge?.let { "app installed $it" }).joinToString(", ")+ out += "ads" to "blocked by the app; ad breaks this session=$adBreaks, ad states left out=$adStatesLeftOut"+ out += "devices" to (firstCluster?.let { first -> if (first == lastCluster) first else "$first | last: $lastCluster" } ?: "no cluster seen")+ out += "timing" to listOfNotNull(+ "first command ${firstCommand ?: "none"}",+ firstPerPage.takeIf { it.isNotEmpty() }?.joinToString(", ", "first per page: "),+ "registration ${counts(registration)}",+ ).joinToString("; ")+ if (refusedCommands > 0) {+ out += "refused" to "${counts(refusedKinds)}; within ${NEAR_MS / 1000} s after an ad: $afterAd, after a transfer: $afterTransfer"+ out += "body" to (counts(errorTypes).ifEmpty { "no error_type" })+ out += "refusal hdr" to (refusalHeaders.entries.joinToString(", ") { (n, v) -> "$n=${v.joinToString("|")}" }+ .ifEmpty { "no x-*, retry-after or www-authenticate" })+ }+ out += "routes" to (routes.entries.joinToString(" · ") { (name, r) ->+ "$name ${counts(r.answers)}" + (r.ms.takeIf { it.isNotEmpty() }?.let { " (median ${it.sorted()[it.size / 2]} ms)" } ?: "")+ }.ifEmpty { "none" })+ if (refusedCommands > 0) {+ out += "retry 2xx" to (wonRetries.entries.joinToString(", ") { (r, c) -> "$r 2xx×${c[0]}, audio in 10 s ${c[1]}/${c[0]}" }+ .ifEmpty { "no other route answered 2xx" })+ out += "page fetch" to (if (pageFetch.isEmpty()) "not tried" else "${counts(pageFetch)}; audio in 10 s $pageKept/${pageKept + pageDropped}")+ }+ out += "connect PUT" to (if (connectPut.isEmpty()) "none" else "${counts(connectPut)}; headers: ${connectPutHeaders ?: "-"}")+ val coincide = refusalTimes.count { t -> licenceErrorTimes.any { kotlin.math.abs(it - t) <= COINCIDE_MS } }+ out += "licence" to listOfNotNull(+ counts(licence).ifEmpty { "no answer seen" },+ "over $songs songs",+ licenceHeld.takeIf { it > 0 }?.let { "answered here (hold) $it" },+ retryAfter.takeIf { it.isNotEmpty() }?.joinToString("|", "retry-after=") ,+ if (refusedCommands > 0) "402 within ${COINCIDE_MS / 1000} s of a licence 403/429: $coincide of ${refusalTimes.size}" else null,+ ).joinToString("; ")+ out+ }++ /** Header names a refusal may explain itself with; never authorization or cookies. */+ internal fun explaining(name: String): Boolean {+ val n = name.lowercase()+ if ("auth" in n && n != "www-authenticate" || "cookie" in n || "token" in n) return false+ return n.startsWith("x-") || n == "retry-after" || n == "www-authenticate"+ }++ private val ERROR_TYPE = Regex(""""error_type"\s*:\s*"([A-Za-z_]{1,40})"""")+ internal fun errorType(body: String): String? = ERROR_TYPE.find(body)?.groupValues?.get(1)++ private fun counts(m: Map<*, Int>) = m.entries.joinToString(" ") { (k, v) -> "$k×$v" }+ private fun secs(ms: Long) = "%.1f s".format(java.util.Locale.US, ms / 1000.0)+}diff --git a/base/api-spotify/src/main/resources/bridge/player-bridge.js b/base/api-spotify/src/main/resources/bridge/player-bridge.jsindex 98f2eff5..44e66fcf 100644--- a/base/api-spotify/src/main/resources/bridge/player-bridge.js+++ b/base/api-spotify/src/main/resources/bridge/player-bridge.js@@ -27,6 +27,21 @@return;}+ // The page always sees itself visible: a hidden page has its timers and rendering throttled,+ // and the engine runs with the app in the background (the host already tells Chromium the view+ // is shown). Nothing in this bridge reads the page's visibility.+ try {+ Object.defineProperty(Document.prototype, 'hidden', { configurable: true, get: () => false });+ Object.defineProperty(Document.prototype, 'visibilityState', { configurable: true, get: () => 'visible' });+ Object.defineProperty(Document.prototype, 'webkitHidden', { configurable: true, get: () => false });+ Object.defineProperty(Document.prototype, 'webkitVisibilityState', { configurable: true, get: () => 'visible' });+ document.hasFocus = () => true;+ for (const t of ['visibilitychange', 'webkitvisibilitychange']) {+ document.addEventListener(t, e => e.stopImmediatePropagation(), true);+ window.addEventListener(t, e => e.stopImmediatePropagation(), true);+ }+ } catch (e) { /* keep the real values */ }+const VERSION = 1;const READY_TIMEOUT_MS = 60000;@@ -434,14 +449,14 @@// level: the element's volume (0..1), which local fades move; own: the level the page// player itself wants there. playerVolume: what the page player itself is set to, read// here too so the host's periodic volume check costs no second call.- // -> {paused, muted, volume, level, own, time, readyState, ended, playerVolume, active} | null (no element yet)+ // -> {paused, muted, volume, level, own, time, readyState, networkState, error, keys, ended, playerVolume, active} | null (no element yet)'media.state': async () => {const player = await localPlayer();const el = player && player._player;if (!(el instanceof HTMLMediaElement)) return null;let playerVolume = null;try { playerVolume = await need().playback.getVolume(); } catch (e) { /* unknown */ }- return { paused: el.paused, muted: el.muted, volume: el.volume, level: el.volume, own: ownLevel(player), time: el.currentTime, readyState: el.readyState, ended: el.ended, playerVolume, active: await activeDevice() };+ return { paused: el.paused, muted: el.muted, volume: el.volume, level: el.volume, own: ownLevel(player), time: el.currentTime, readyState: el.readyState, networkState: el.networkState, error: el.error ? el.error.code + ':' + String(el.error.message || '').slice(0, 80) : null, keys: el.mediaKeys ? 1 : 0, ended: el.ended, playerVolume, active: await activeDevice() };},// The media element's volume, on this phone only: no Spotify Connect command (refused on// some accounts, slow on a busy network) and nothing reported to Spotify, as the player'sdiff --git a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/RelayRoutesTest.kt b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/RelayRoutesTest.ktindex 7f0823ec..d7074a18 100644--- a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/RelayRoutesTest.kt+++ b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/RelayRoutesTest.kt@@ -2,6 +2,7 @@ package app.myspoti.spotify.bridgeimport org.junit.jupiter.api.Assertions.assertEqualsimport org.junit.jupiter.api.Assertions.assertNull+import org.junit.jupiter.api.Assertions.assertTrueimport org.junit.jupiter.api.Testimport org.junit.jupiter.api.assertThrowsimport java.net.InetAddress@@ -11,11 +12,21 @@ class RelayRoutesTest {private val v4 = InetAddress.getByAddress("spclient", byteArrayOf(85.toByte(), 1, 2, 3))private val v6 = InetAddress.getByAddress("spclient", ByteArray(16).also { it[0] = 0x2a; it[1] = 0x01 })- @Test fun `a refusal over IPv6 is tried over IPv4, then through the platform stack`() {+ @Test fun `a refusal goes to the platform's Chromium stack first, then the other family`() {val routes = RelayRoutes(engineAvailable = true)+ assertEquals(RelayRoute.HTTP_ENGINE, routes.next(listOf(RelayRoute.DEFAULT), IpFamily.V6))+ assertEquals(RelayRoute.IPV4, routes.next(listOf(RelayRoute.DEFAULT, RelayRoute.HTTP_ENGINE), null))+ assertNull(routes.next(listOf(RelayRoute.DEFAULT, RelayRoute.HTTP_ENGINE, RelayRoute.IPV4), IpFamily.V4))+ }++ @Test fun `before Android 14, Cronet is the first retry once it is there`() {+ var cronet: RelayRoute? = null+ val routes = RelayRoutes { cronet }assertEquals(RelayRoute.IPV4, routes.next(listOf(RelayRoute.DEFAULT), IpFamily.V6))- assertEquals(RelayRoute.HTTP_ENGINE, routes.next(listOf(RelayRoute.DEFAULT, RelayRoute.IPV4), IpFamily.V4))- assertNull(routes.next(listOf(RelayRoute.DEFAULT, RelayRoute.IPV4, RelayRoute.HTTP_ENGINE), null))+ cronet = RelayRoute.CRONET+ assertEquals(RelayRoute.CRONET, routes.next(listOf(RelayRoute.DEFAULT), IpFamily.V6))+ assertEquals(RelayRoute.IPV4, routes.next(listOf(RelayRoute.DEFAULT, RelayRoute.CRONET), null))+ assertTrue(RelayRoute.CRONET.chromium && RelayRoute.HTTP_ENGINE.chromium && !RelayRoute.IPV4.chromium)}@Test fun `a refusal over IPv4 is tried over IPv6, and nothing else without the platform stack`() {@@ -24,12 +35,15 @@ class RelayRoutesTest {assertNull(routes.next(listOf(RelayRoute.DEFAULT, RelayRoute.IPV6), IpFamily.V6))}- @Test fun `the route that won is kept, and its refusal tries the other family`() {+ @Test fun `the route that won is kept, and its refusal tries the others`() {val routes = RelayRoutes(engineAvailable = true)assertEquals(RelayRoute.DEFAULT, routes.kept)+ routes.won(RelayRoute.HTTP_ENGINE)+ assertEquals(RelayRoute.HTTP_ENGINE, routes.kept)+ assertEquals(RelayRoute.IPV4, routes.next(listOf(RelayRoute.HTTP_ENGINE), null))routes.won(RelayRoute.IPV4)- assertEquals(RelayRoute.IPV4, routes.kept)- assertEquals(RelayRoute.IPV6, routes.next(listOf(RelayRoute.IPV4), null))+ assertEquals(RelayRoute.HTTP_ENGINE, routes.next(listOf(RelayRoute.IPV4), null))+ assertEquals(RelayRoute.IPV6, routes.next(listOf(RelayRoute.IPV4, RelayRoute.HTTP_ENGINE), null))}@Test fun `pinning keeps one family, and a network without it has no address`() {diff --git a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/report/Refusal402Test.kt b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/report/Refusal402Test.ktnew file mode 100644index 00000000..a1400e0f--- /dev/null+++ b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/report/Refusal402Test.kt@@ -0,0 +1,80 @@+package app.myspoti.spotify.report++import org.junit.jupiter.api.AfterEach+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 Refusal402Test {+ private var now = 0L++ private fun fresh() { Refusal402.reset(); Refusal402.clock = { now } }++ @AfterEach fun restore() { Refusal402.reset(); Refusal402.clock = { System.nanoTime() / 1_000_000 } }++ private fun summary() = Refusal402.summary("product=FREE country=ID", "7-30 d ago").toMap()++ @Test fun `a refused session reads in one screen`() {+ fresh()+ Refusal402.pageReady()+ now = 1_200; Refusal402.registered(200)+ Refusal402.cluster("devices=2 types=COMPUTER×2 kinds=self×1,stale-own×1 active=none player_state=absent")+ Refusal402.connectStatePut(200, "content-type,date,server")+ now = 5_000+ val refusal = listOf("x-envoy-upstream-service-time" to "12", "authorization" to "Bearer secret", "set-cookie" to "sp=1", "server" to "envoy")+ Refusal402.attempt("play", "okhttp", 402, 380, refusal, """{"error_type":"COMMAND_FAILED","message":"Command failed"}""")+ Refusal402.attempt("play", "HTTP_ENGINE", 402, 210, refusal, """{"error_type":"COMMAND_FAILED"}""")+ Refusal402.command("play", 402, retried = true)+ Refusal402.pageFetch(200)+ Refusal402.pageKept(false)+ Refusal402.licence(200); Refusal402.licence(429); Refusal402.licenceRetryAfter("60"); Refusal402.song()+ now = 20_000; Refusal402.adBreak()+ now = 40_000+ Refusal402.attempt("transfer", "okhttp", 402, 90, emptyList(), "{}")+ Refusal402.command("transfer", 402, retried = true)+ val s = summary()+ assertEquals("every command refused (2 of 2), no route played", s["verdict"])+ assertEquals("product=FREE country=ID, app installed 7-30 d ago", s["account"])+ assertTrue(s.getValue("timing").startsWith("first command play -> 402 after a refusal, 5.0 s after page ready, 3.8 s after registration"), s["timing"])+ assertEquals("play×1 transfer×1; within 60 s after an ad: 1, after a transfer: 0", s["refused"])+ assertEquals("COMMAND_FAILED×2", s["body"])+ assertEquals("x-envoy-upstream-service-time=12", s["refusal hdr"])+ assertEquals("okhttp 402×2 (median 380 ms) · HTTP_ENGINE 402×1 (median 210 ms)", s["routes"])+ assertEquals("no other route answered 2xx", s["retry 2xx"])+ assertEquals("200×1; audio in 10 s 0/1", s["page fetch"])+ assertEquals("200×1; headers: content-type,date,server", s["connect PUT"])+ assertEquals("200×1 429×1; over 1 songs; retry-after=60; 402 within 30 s of a licence 403/429: 1 of 2", s["licence"])+ assertEquals("blocked by the app; ad breaks this session=1, ad states left out=0", s["ads"])+ val all = s.values.joinToString(" ")+ assertFalse("secret" in all || "sp=1" in all, all)+ }++ @Test fun `a retry on another route that plays is told apart from one that does not`() {+ fresh()+ Refusal402.attempt("play", "okhttp", 402, 300, emptyList(), "")+ Refusal402.attempt("play", "CRONET", 200, 150, emptyList(), "")+ Refusal402.command("play", 200, retried = true)+ Refusal402.audioAfterRetry("CRONET", true)+ val s = summary()+ assertEquals("1 of 1 commands refused first; 1 accepted in the end; page fetch played 0×", s["verdict"])+ assertEquals("CRONET 2xx×1, audio in 10 s 1/1", s["retry 2xx"])+ }++ @Test fun `a session never refused stays short`() {+ fresh()+ Refusal402.command("play", 200, retried = false)+ val s = summary()+ assertEquals("no command refused (1 of 1 accepted)", s["verdict"])+ assertFalse("refused" in s || "retry 2xx" in s || "page fetch" in s)+ }++ @Test fun `only headers a refusal explains itself with`() {+ assertTrue(Refusal402.explaining("Retry-After"))+ assertTrue(Refusal402.explaining("www-authenticate"))+ assertTrue(Refusal402.explaining("x-spotify-reason"))+ assertFalse(Refusal402.explaining("x-auth-token"))+ assertFalse(Refusal402.explaining("authorization"))+ assertFalse(Refusal402.explaining("server"))+ }+}diff --git a/base/app/build.gradle.kts b/base/app/build.gradle.ktsindex 6ba7e508..77d2344b 100644--- a/base/app/build.gradle.kts+++ b/base/app/build.gradle.kts@@ -135,6 +135,8 @@ dependencies {implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.9.0")implementation("com.github.bumptech.glide:compose:1.0.0-beta01")implementation("androidx.palette:palette-ktx:1.0.0")+ // Frosted (blurred) bars of the Immersive look. Apache-2.0.+ implementation("dev.chrisbanes.haze:haze:1.3.1")// MediaTransferReceiver: lets the system output switcher transfer to our Connect routesimplementation("androidx.mediarouter:mediarouter:1.8.1")implementation("androidx.compose.material:material-icons-extended:1.7.8")diff --git a/base/app/proguard-rules.pro b/base/app/proguard-rules.proindex 318e340a..dd271ba5 100644--- a/base/app/proguard-rules.pro+++ b/base/app/proguard-rules.pro@@ -82,3 +82,9 @@# (SpotifyDispatcher reads them by reflection), and the sandbox loads prelude.js from its jar.-keepclassmembers class app.myspoti.api.** { <fields>; }-keep class app.myspoti.extensions.** { *; }++# The relay's Cronet (before Android 14): CronetProvider finds the Play services provider by its+# class name, and zstd's decoder is reached from its native library by JNI.+-keep class com.google.android.gms.net.PlayServicesCronetProvider { *; }+-keep class com.google.android.gms.net.GmsCoreCronetProvider { *; }+-keep class com.squareup.zstd.** { *; }diff --git a/base/app/src/main/java/app/myspoti/MainActivity.kt b/base/app/src/main/java/app/myspoti/MainActivity.ktindex 111ce1a2..e7bdf0ee 100644--- a/base/app/src/main/java/app/myspoti/MainActivity.kt+++ b/base/app/src/main/java/app/myspoti/MainActivity.kt@@ -57,6 +57,10 @@ class MainActivity : AppCompatActivity() {private var setupNeeded by mutableStateOf(false)/** In the picture-in-picture window: only the music video is drawn. */private var inPip by mutableStateOf(false)+ /** Debug builds: `am start ... --ez showLook true` opens the look step alone, signed in or not. */+ private var showLook by mutableStateOf(false)+ /** The "new look" popup was already shown (or the onboarding look step covered it). */+ private var lookOffered by mutableStateOf(true)private val prefs get() = getSharedPreferences("myspoti_prefs", Context.MODE_PRIVATE)@@ -67,21 +71,52 @@ class MainActivity : AppCompatActivity() {requestedOrientation = com.music.spotui.data.preferences.OrientationPref.requested()signedIn = prefs.getBoolean("LoggedIn", false)setupNeeded = com.music.spotui.ui.screens.Setup.needed(this)+ lookOffered = com.music.spotui.data.preferences.LookPref.isOffered(this)root = FrameLayout(this)val compose = ComposeView(this).apply {setContent {- SpotuiTheme {+ SpotuiTheme { com.music.spotui.ui.look.ProvideLook {val orientation = com.music.spotui.data.preferences.OrientationPref.modeandroidx.compose.runtime.LaunchedEffect(orientation) {requestedOrientation = com.music.spotui.data.preferences.OrientationPref.requested()}androidx.compose.foundation.layout.Box(androidx.compose.ui.Modifier.fillMaxSize()) {when {- signedIn && setupNeeded -> com.music.spotui.ui.screens.SetupScreen(onDone = { setupNeeded = false })+ showLook -> com.music.spotui.ui.look.LookStep(onNext = {+ com.music.spotui.data.preferences.LookPref.setChosen(this@MainActivity); showLook = false+ setupNeeded = com.music.spotui.ui.screens.Setup.needed(this@MainActivity)+ })+ signedIn && setupNeeded -> com.music.spotui.ui.screens.SetupScreen(+ onDone = { setupNeeded = false },+ )signedIn -> App()connecting -> ConnectingScreen()else -> WelcomeScreen(onLogin = { showLogin() })}+ // Existing users, once, right after the update: the new look, live.+ if (signedIn && !setupNeeded && !showLook && !showingLogin && !inPip && !lookOffered) {+ if (com.music.spotui.data.preferences.LookPref.look == com.music.spotui.data.preferences.Look.IMMERSIVE) {+ androidx.compose.runtime.LaunchedEffect(Unit) {+ com.music.spotui.data.preferences.LookPref.setOffered(this@MainActivity); lookOffered = true+ }+ } else {+ val close = { look: com.music.spotui.data.preferences.Look ->+ com.music.spotui.data.preferences.LookPref.set(this@MainActivity, look)+ com.music.spotui.data.preferences.LookPref.setOffered(this@MainActivity)+ lookOffered = true+ }+ val keep = { close(com.music.spotui.data.preferences.Look.CLASSIC) }+ androidx.compose.ui.window.Dialog(+ onDismissRequest = keep,+ properties = androidx.compose.ui.window.DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false),+ ) {+ com.music.spotui.ui.look.LookStep(+ onNext = { close(com.music.spotui.data.preferences.Look.IMMERSIVE) },+ offer = com.music.spotui.ui.look.LookOffer(onKeep = keep),+ )+ }+ }+ }// "Ask each time": the download quality question, above every screen.com.music.spotui.ui.components.DownloadAskHost()// An extension about to change the Spotify account waits for the user's yes.@@ -96,7 +131,7 @@ class MainActivity : AppCompatActivity() {// so coming back finds the same screen).if (inPip) com.music.spotui.ui.components.PipVideo()}- }+ } }}}root.addView(compose, ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))@@ -106,6 +141,11 @@ class MainActivity : AppCompatActivity() {// Debug builds: `am start ... --ez showPlayer true` shows the Web Player page full screen.val debuggable = applicationInfo.flags and android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE != 0MyspotiRuntime.host.attach(root, visible = debuggable && intent.getBooleanExtra("showPlayer", false))+ showLook = debuggable && intent.getBooleanExtra("showLook", false)+ // Debug builds: `am start ... --ez resetLookOffer true` shows the new-look popup again.+ if (debuggable && intent.getBooleanExtra("resetLookOffer", false)) {+ com.music.spotui.data.preferences.LookPref.clearOffered(this); lookOffered = false+ }watchSession()watchLoginReturn()watchLogout()diff --git a/base/app/src/main/java/com/music/spotui/App.kt b/base/app/src/main/java/com/music/spotui/App.ktindex 6fd182fb..fed3f163 100644--- a/base/app/src/main/java/com/music/spotui/App.kt+++ b/base/app/src/main/java/com/music/spotui/App.kt@@ -6,6 +6,7 @@ import com.music.spotui.ui.theme.AppTextimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.verticalScrollimport androidx.compose.foundation.layout.heightIn+import androidx.compose.foundation.layout.widthInimport com.music.spotui.ui.components.pressableimport androidx.compose.ui.unit.spimport androidx.compose.ui.unit.dp@@ -108,22 +109,61 @@ fun App() {val shareTarget by com.music.spotui.ui.components.SpotifyCode.request.collectAsState()shareTarget?.let { t -> com.music.spotui.ui.components.SpotifyCodeSheet(t) { com.music.spotui.ui.components.SpotifyCode.request.value = null } }+ // The look (Settings > Display) switches the shell live. The nav host keeps one place in the+ // tree in both looks, so a switch keeps the back stack, the pages' state and the playback.+ val immersive = com.music.spotui.ui.navigation.isImmersive()+ val haze = com.music.spotui.ui.immersive.shell.rememberImmersiveHazeState()+ // Liquid Glass (Settings > Display): the pages record themselves for the glass to refract.+ // Not provided while it is off or unsupported, so nothing is recorded for no reader.+ val glassPage = com.music.spotui.ui.immersive.shell.rememberImmersiveBackdrop()+ val liquidGlass = immersive && com.music.spotui.ui.immersive.shell.rememberLiquidGlassActive()+ // The floating chrome's fold (iOS 26): pages scroll it through immersiveChromeScroll().+ val chrome = com.music.spotui.ui.immersive.shell.rememberImmersiveChromeState()+ androidx.compose.runtime.CompositionLocalProvider(+ com.music.spotui.ui.immersive.shell.LocalImmersiveHaze provides if (immersive) haze else null,+ com.music.spotui.ui.immersive.shell.LocalImmersiveBackdrop provides if (liquidGlass) glassPage else null,+ com.music.spotui.ui.immersive.shell.LocalImmersiveChrome provides if (immersive) chrome else null,+ ) {androidx.compose.foundation.layout.Box(Modifier.fillMaxSize()) {Scaffold(modifier = Modifier,bottomBar = {- MainBottomNavigation(navController = navController, bottomBarState = bottomBarState, bottomBarPlayerState)+ if (!immersive) MainBottomNavigation(navController = navController, bottomBarState = bottomBarState, bottomBarPlayerState)}) {- MyNavHost(navHostController = navController, bottomBarState = bottomBarState, bottomBarPlayerState)+ MyNavHost(+ navHostController = navController, bottomBarState = bottomBarState, bottomBarPlayerState,+ // Immersive: each page marks its own list as what the glass bars blur (a source on+ // the whole host would hold the pages' own top bars too).+ modifier = if (immersive) Modifier.background(com.music.spotui.ui.immersive.Immersive.Page) else Modifier,+ )}+ if (immersive) ImmersiveShell(navController)// Over the pages and the bottom bar: pulling it down shows them, already in place.- com.music.spotui.ui.navigation.PlayerOverlay(navController)+ else com.music.spotui.ui.navigation.PlayerOverlay(navController)+ }}}+/**+ * The Immersive look's floating chrome: the mini player capsule over the tab bar (both hidden+ * on the full-screen routes; folded into one row while a page scrolls down), and its player over+ * everything.+ */+@Composable+private fun ImmersiveShell(navController: androidx.navigation.NavHostController) {+ androidx.compose.foundation.layout.Box(Modifier.fillMaxSize()) {+ com.music.spotui.ui.immersive.shell.ImmersiveBottomChrome(+ navController,+ miniPlayer = { m -> com.music.spotui.ui.immersive.player.ImmersiveMiniPlayer(navController, m) },+ modifier = Modifier.align(androidx.compose.ui.Alignment.BottomCenter),+ )+ com.music.spotui.ui.immersive.player.ImmersivePlayerOverlay(navController)+ }+}+/** The update card is on screen: the donation reminder waits for another launch. */private val updateCardOpen = mutableStateOf(false)diff --git a/base/app/src/main/java/com/music/spotui/data/preferences/LookPref.kt b/base/app/src/main/java/com/music/spotui/data/preferences/LookPref.ktnew file mode 100644index 00000000..c2761e9b--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/data/preferences/LookPref.kt@@ -0,0 +1,46 @@+package com.music.spotui.data.preferences++/*+ * The app's look: Classic (today's) or Immersive, picked during the onboarding.+ */++import android.content.Context+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue++/** The two looks. [CLASSIC] is the default, so nothing changes for anyone who has not chosen. */+enum class Look {+ CLASSIC, IMMERSIVE;++ companion object {+ fun of(name: String?): Look = entries.firstOrNull { it.name == name } ?: CLASSIC+ }+}++object LookPref {+ private const val PREF = "settings_prefs"+ private const val KEY = "look"+ private const val KEY_CHOSEN = "look_chosen"+ private const val KEY_OFFERED = "look_offered"++ /** The chosen look, as Compose state: everything reading it redraws when it changes. */+ var look by mutableStateOf(Look.of(prefs(com.music.spotui.di.Graph.app).getString(KEY, null)))+ private set++ fun set(c: Context, value: Look) {+ look = value+ prefs(c).edit().putString(KEY, value.name).apply()+ }++ /** The look step of the onboarding was seen (new installs and updates alike). */+ fun isChosen(c: Context): Boolean = prefs(c).getBoolean(KEY_CHOSEN, false)+ fun setChosen(c: Context) = prefs(c).edit().putBoolean(KEY_CHOSEN, true).putBoolean(KEY_OFFERED, true).apply()++ /** The new-look popup was shown to an existing user (or the onboarding look step covered it). */+ fun isOffered(c: Context): Boolean = prefs(c).getBoolean(KEY_OFFERED, false)+ fun setOffered(c: Context) = prefs(c).edit().putBoolean(KEY_OFFERED, true).apply()+ fun clearOffered(c: Context) = prefs(c).edit().remove(KEY_OFFERED).apply()++ private fun prefs(c: Context) = c.getSharedPreferences(PREF, Context.MODE_PRIVATE)+}diff --git a/base/app/src/main/java/com/music/spotui/data/preferences/SettingsPref.kt b/base/app/src/main/java/com/music/spotui/data/preferences/SettingsPref.ktindex e21f4af6..30b8768a 100644--- a/base/app/src/main/java/com/music/spotui/data/preferences/SettingsPref.kt+++ b/base/app/src/main/java/com/music/spotui/data/preferences/SettingsPref.kt@@ -143,3 +143,20 @@ fun getLyricTranslateLang(c: Context): String =fun setLyricTranslateLang(c: Context, code: String) =prefs(c).edit().putString(KEY_LYRIC_TRANSLATE_LANG, code.trim()).apply()++/**+ * Liquid Glass in the Immersive look (Settings > Display, under Look): the floating bars refract+ * the page through a lens instead of only frosting it. On by default; it only takes effect on+ * Android 12+ and when the phone does not ask for less blur or motion (see+ * [com.music.spotui.ui.immersive.shell.rememberLiquidGlassActive]).+ */+object LiquidGlassPref {+ private const val KEY = "immersive_liquid_glass"+ var on by androidx.compose.runtime.mutableStateOf(prefs(com.music.spotui.di.Graph.app).getBoolean(KEY, true))+ private set++ fun set(c: Context, value: Boolean) {+ on = value+ prefs(c).edit().putBoolean(KEY, value).apply()+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/components/AddCollectionToPlaylistSheet.kt b/base/app/src/main/java/com/music/spotui/ui/components/AddCollectionToPlaylistSheet.ktindex e052ea9c..a7124893 100644--- a/base/app/src/main/java/com/music/spotui/ui/components/AddCollectionToPlaylistSheet.kt+++ b/base/app/src/main/java/com/music/spotui/ui/components/AddCollectionToPlaylistSheet.kt@@ -91,7 +91,7 @@ fun AddCollectionToPlaylistSheet(sourceUri: String, title: String, onDismiss: ()}}- ModalBottomSheet(onDismissRequest = onDismiss, sheetState = sheetState, containerColor = tone(0xFF1A1A1A)) {+ com.music.spotui.ui.components.LookSheet(onDismissRequest = onDismiss, sheetState = sheetState, containerColor = tone(0xFF1A1A1A)) {Column(modifier = Modifier.navigationBarsPadding().imePadding()) {Text(title, color = AppText, fontSize = 20.sp, fontWeight = FontWeight.Bold, maxLines = 1, overflow = TextOverflow.Ellipsis,@@ -149,7 +149,7 @@ fun AddCollectionToPlaylistSheet(sourceUri: String, title: String, onDismiss: ()fun AlbumOptionsSheet(albumUri: String, name: String, onDismiss: () -> Unit) {var adding by remember { mutableStateOf(false) }if (adding) { AddCollectionToPlaylistSheet(albumUri, name, onDismiss); return }- ModalBottomSheet(onDismissRequest = onDismiss, containerColor = tone(0xFF282828)) {+ com.music.spotui.ui.components.LookSheet(onDismissRequest = onDismiss, containerColor = tone(0xFF282828)) {Column(Modifier.navigationBarsPadding().padding(bottom = 12.dp)) {Text(name, color = AppText, fontSize = 18.sp, fontWeight = FontWeight.Bold, maxLines = 1, overflow = TextOverflow.Ellipsis,modifier = Modifier.padding(20.dp, 0.dp, 20.dp, 8.dp))diff --git a/base/app/src/main/java/com/music/spotui/ui/components/AddToPlaylistSheet.kt b/base/app/src/main/java/com/music/spotui/ui/components/AddToPlaylistSheet.ktindex 73458111..eb61c0f7 100644--- a/base/app/src/main/java/com/music/spotui/ui/components/AddToPlaylistSheet.kt+++ b/base/app/src/main/java/com/music/spotui/ui/components/AddToPlaylistSheet.kt@@ -96,7 +96,7 @@ fun AddToPlaylistSheet(}}- ModalBottomSheet(+ com.music.spotui.ui.components.LookSheet(onDismissRequest = onDismiss,sheetState = sheetState,containerColor = tone(0xFF1A1A1A),diff --git a/base/app/src/main/java/com/music/spotui/ui/components/ArtistChooser.kt b/base/app/src/main/java/com/music/spotui/ui/components/ArtistChooser.ktindex 44eda722..0c7a3e89 100644--- a/base/app/src/main/java/com/music/spotui/ui/components/ArtistChooser.kt+++ b/base/app/src/main/java/com/music/spotui/ui/components/ArtistChooser.kt@@ -98,7 +98,7 @@ fun ArtistChooserHost(navController: NavHostController) {val artists = ArtistChooser.artistsif (artists.isEmpty()) returnval dismiss = { ArtistChooser.artists = emptyList() }- ModalBottomSheet(onDismissRequest = dismiss, containerColor = tone(0xFF282828)) {+ com.music.spotui.ui.components.LookSheet(onDismissRequest = dismiss, containerColor = tone(0xFF282828)) {Column(Modifier.navigationBarsPadding().padding(bottom = 12.dp)) {Text(stringResource(R.string.choose_artist), color = AppText, fontSize = 18.sp, fontWeight = FontWeight.Bold,modifier = Modifier.padding(20.dp, 0.dp, 20.dp, 12.dp))diff --git a/base/app/src/main/java/com/music/spotui/ui/components/EpisodeSheets.kt b/base/app/src/main/java/com/music/spotui/ui/components/EpisodeSheets.ktindex f80fc312..4d63b006 100644--- a/base/app/src/main/java/com/music/spotui/ui/components/EpisodeSheets.kt+++ b/base/app/src/main/java/com/music/spotui/ui/components/EpisodeSheets.kt@@ -118,7 +118,7 @@ fun EpisodeOptionsSheet(// The + / ✓ follows Spotify's library: ask once for this episode's saved state.androidx.compose.runtime.LaunchedEffect(song.url) { SongPlayer.requestSaved(song.spotifyUri) }val saved = SongPlayer.library[song.spotifyUri] == true- ModalBottomSheet(onDismissRequest = onDismiss, containerColor = Sheet) {+ com.music.spotui.ui.components.LookSheet(onDismissRequest = onDismiss, containerColor = Sheet) {Column(Modifier.navigationBarsPadding().padding(bottom = 12.dp)) {Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(20.dp, 4.dp, 20.dp, 16.dp)) {GlideImage(@@ -246,7 +246,7 @@ fun speedLabel(speed: Double): String =@Composablefun PodcastSpeedSheet(onDismiss: () -> Unit) {val current = SongPlayer.speed.value- ModalBottomSheet(onDismissRequest = onDismiss, containerColor = Sheet) {+ com.music.spotui.ui.components.LookSheet(onDismissRequest = onDismiss, containerColor = Sheet) {Column(Modifier.fillMaxWidth().navigationBarsPadding().padding(bottom = 20.dp)) {Text(stringResource(R.string.playback_speed),diff --git a/base/app/src/main/java/com/music/spotui/ui/components/LookSheet.kt b/base/app/src/main/java/com/music/spotui/ui/components/LookSheet.ktnew file mode 100644index 00000000..838e7c56--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/components/LookSheet.kt@@ -0,0 +1,27 @@+package com.music.spotui.ui.components++import androidx.compose.foundation.layout.ColumnScope+import androidx.compose.material3.ExperimentalMaterial3Api+import androidx.compose.material3.ModalBottomSheet+import androidx.compose.material3.SheetState+import androidx.compose.material3.rememberModalBottomSheetState+import androidx.compose.runtime.Composable+import androidx.compose.ui.graphics.Color+import com.music.spotui.ui.immersive.sheets.ImmersiveGlassSheet+import com.music.spotui.ui.navigation.isImmersive++/**+ * The bottom sheet of the screens shared by both looks: Material's [ModalBottomSheet] on+ * [containerColor] in Classic (exactly as before), a glass sheet in Immersive.+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun LookSheet(+ onDismissRequest: () -> Unit,+ sheetState: SheetState = rememberModalBottomSheetState(),+ containerColor: Color,+ content: @Composable ColumnScope.() -> Unit,+) {+ if (isImmersive()) ImmersiveGlassSheet(onDismissRequest, sheetState, content)+ else ModalBottomSheet(onDismissRequest = onDismissRequest, sheetState = sheetState, containerColor = containerColor, content = content)+}diff --git a/base/app/src/main/java/com/music/spotui/ui/components/PlayerSheets.kt b/base/app/src/main/java/com/music/spotui/ui/components/PlayerSheets.ktindex 4d960f6f..fd8a9621 100644--- a/base/app/src/main/java/com/music/spotui/ui/components/PlayerSheets.kt+++ b/base/app/src/main/java/com/music/spotui/ui/components/PlayerSheets.kt@@ -171,7 +171,7 @@ fun DevicesSheet(onDismiss: () -> Unit) {val route = rememberAudioRoute()val headphones = remote == null && route.kind != AudioRoute.Kind.SPEAKERif (quality) QualitySheet(onDismiss = { quality = false })- ModalBottomSheet(onDismissRequest = onDismiss, containerColor = SheetColor) {+ com.music.spotui.ui.components.LookSheet(onDismissRequest = onDismiss, containerColor = SheetColor) {Column(modifier = Modifier.fillMaxWidth().navigationBarsPadding().padding(bottom = 16.dp)) {Text(stringResource(R.string.listen_on),@@ -296,7 +296,7 @@ fun QualitySheet(onDismiss: () -> Unit) {if (bitrate <= 0) "" else "${codecName(mime)} · ${bitrate / 1000} kbit/s"}}- ModalBottomSheet(onDismissRequest = onDismiss, containerColor = SheetColor) {+ com.music.spotui.ui.components.LookSheet(onDismissRequest = onDismiss, containerColor = SheetColor) {Column(Modifier.fillMaxWidth().navigationBarsPadding().padding(bottom = 16.dp)) {Text(stringResource(R.string.quality_sheet_title), color = AppText, fontSize = 20.sp, fontWeight = FontWeight.Bold,modifier = Modifier.padding(horizontal = 20.dp, vertical = 8.dp))@@ -416,7 +416,7 @@ private object JamLinks {@Composablefun SleepTimerSheet(onDismiss: () -> Unit) {val active = SongPlayer.sleepEndsAt.value != null- ModalBottomSheet(onDismissRequest = onDismiss, containerColor = SheetColor) {+ com.music.spotui.ui.components.LookSheet(onDismissRequest = onDismiss, containerColor = SheetColor) {Column(modifier = Modifier.fillMaxWidth().navigationBarsPadding().padding(bottom = 16.dp)) {Text(stringResource(R.string.context_menu_sleep_timer),@@ -476,7 +476,7 @@ fun QueueSheet(contextName: String, onDismiss: () -> Unit) {// through this state.val listState = rememberLazyListState()- ModalBottomSheet(+ com.music.spotui.ui.components.LookSheet(onDismissRequest = onDismiss,sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true),containerColor = SheetColor,diff --git a/base/app/src/main/java/com/music/spotui/ui/components/PlaylistOptionsSheet.kt b/base/app/src/main/java/com/music/spotui/ui/components/PlaylistOptionsSheet.ktindex 789e3897..6cee491d 100644--- a/base/app/src/main/java/com/music/spotui/ui/components/PlaylistOptionsSheet.kt+++ b/base/app/src/main/java/com/music/spotui/ui/components/PlaylistOptionsSheet.kt@@ -147,7 +147,7 @@ fun PlaylistOptionsSheet(com.music.spotui.data.api.SpotifySync.setPlaylistPublished(page.uri, on) { ok -> if (!ok) restore() }}- ModalBottomSheet(onDismissRequest = onDismiss, containerColor = tone(0xFF282828)) {+ com.music.spotui.ui.components.LookSheet(onDismissRequest = onDismiss, containerColor = tone(0xFF282828)) {Column(Modifier.navigationBarsPadding().padding(bottom = 12.dp)) {// As the official app: the playlist itself on top (cover, name, owner), then one action a row.Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(20.dp, 0.dp, 20.dp, 12.dp)) {diff --git a/base/app/src/main/java/com/music/spotui/ui/components/SavedInSheet.kt b/base/app/src/main/java/com/music/spotui/ui/components/SavedInSheet.ktindex 1fdb9e8e..6624af9c 100644--- a/base/app/src/main/java/com/music/spotui/ui/components/SavedInSheet.kt+++ b/base/app/src/main/java/com/music/spotui/ui/components/SavedInSheet.kt@@ -113,7 +113,7 @@ fun SavedInSheet(onDismiss()}- ModalBottomSheet(+ com.music.spotui.ui.components.LookSheet(onDismissRequest = onDismiss,sheetState = sheetState,containerColor = tone(0xFF1A1A1A),diff --git a/base/app/src/main/java/com/music/spotui/ui/components/SongOptionsSheet.kt b/base/app/src/main/java/com/music/spotui/ui/components/SongOptionsSheet.ktindex 10dac279..84ab7640 100644--- a/base/app/src/main/java/com/music/spotui/ui/components/SongOptionsSheet.kt+++ b/base/app/src/main/java/com/music/spotui/ui/components/SongOptionsSheet.kt@@ -371,7 +371,7 @@ private fun MenuRow(/** The track's credits (performers, writers, producers), as Spotify lists them. */@OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)@Composable-private fun CreditsSheet(song: SongsModel, onDismiss: () -> Unit) {+internal fun CreditsSheet(song: SongsModel, onDismiss: () -> Unit) {val credits by androidx.compose.runtime.produceState<app.myspoti.api.Credits?>(null, song.spotifyTrackId) {value = runCatching { app.myspoti.host.android.MyspotiRuntime.api.extras.credits("spotify:track:${song.spotifyTrackId}") }.getOrDefault(app.myspoti.api.Credits(emptyList()))@@ -406,7 +406,7 @@ private fun CreditsSheet(song: SongsModel, onDismiss: () -> Unit) {/** Podcast playback speed (Spotify refuses speed changes on music). */@OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)@Composable-private fun SpeedSheet(onDismiss: () -> Unit) {+internal fun SpeedSheet(onDismiss: () -> Unit) {ModalBottomSheet(onDismissRequest = onDismiss, containerColor = tone(0xFF282828)) {Column(Modifier.fillMaxWidth().padding(bottom = 24.dp)) {Text(stringResource(R.string.playback_speed), color = AppText, fontSize = 20.sp, fontWeight = androidx.compose.ui.text.font.FontWeight.Bold,diff --git a/base/app/src/main/java/com/music/spotui/ui/components/SpotifyCodeSheet.kt b/base/app/src/main/java/com/music/spotui/ui/components/SpotifyCodeSheet.ktindex 87c3e598..9d97f03e 100644--- a/base/app/src/main/java/com/music/spotui/ui/components/SpotifyCodeSheet.kt+++ b/base/app/src/main/java/com/music/spotui/ui/components/SpotifyCodeSheet.kt@@ -152,7 +152,7 @@ fun SpotifyCodeSheet(target: ShareTarget, onDismiss: () -> Unit) {}val bars = SpotifyCode.barsOn(background)val text = if (bars == "black") Color.Black else AppText- ModalBottomSheet(onDismissRequest = onDismiss, sheetState = sheetState, containerColor = tone(0xFF121212)) {+ com.music.spotui.ui.components.LookSheet(onDismissRequest = onDismiss, sheetState = sheetState, containerColor = tone(0xFF121212)) {Column(Modifier.fillMaxWidth().navigationBarsPadding().padding(horizontal = 24.dp), horizontalAlignment = Alignment.CenterHorizontally) {// The card: cover, name, and the code under them, all on the cover's colour.Column(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.ktnew file mode 100644index 00000000..f823e03b--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/ImmersiveTheme.kt@@ -0,0 +1,63 @@+package com.music.spotui.ui.immersive++import androidx.compose.foundation.background+import androidx.compose.foundation.border+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.Shape+import androidx.compose.ui.text.TextStyle+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import com.music.spotui.ui.look.ImmersiveDisplay+import com.music.spotui.ui.look.ImmersiveSans++/*+ * The Immersive look's tokens, shared by every Immersive screen so they read as one app:+ * a black page, Inter, large bold titles, rounded covers, translucent "glass" bars and an+ * accent taken from the playing cover where there is one.+ */+object Immersive {+ // Colours.+ val Page = Color.Black+ val Raised = Color(0xFF1C1C1E)+ val Separator = Color.White.copy(alpha = 0.10f)+ 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)+ val GlassFill = Color(0xFF2C2C34).copy(alpha = 0.88f)+ val GlassEdge = Color.White.copy(alpha = 0.12f)++ // Shapes.+ val CoverSmall: Shape = RoundedCornerShape(6.dp)+ val CoverMedium: Shape = RoundedCornerShape(10.dp)+ val CoverLarge: Shape = RoundedCornerShape(14.dp)+ val Card: Shape = RoundedCornerShape(14.dp)+ val Button: Shape = RoundedCornerShape(14.dp)++ // Type (Inter).+ private val base = TextStyle(fontFamily = ImmersiveSans, color = Text)+ private val display = TextStyle(fontFamily = ImmersiveDisplay, color = Text)+ val LargeTitle = display.copy(fontSize = 32.sp, lineHeight = 38.sp, fontWeight = FontWeight.Bold)+ val Title = display.copy(fontSize = 22.sp, lineHeight = 28.sp, fontWeight = FontWeight.Bold)+ val Headline = display.copy(fontSize = 20.sp, lineHeight = 25.sp, fontWeight = FontWeight.SemiBold)+ val Body = base.copy(fontSize = 16.sp, lineHeight = 21.sp)+ val BodyStrong = Body.copy(fontWeight = FontWeight.SemiBold)+ val Subhead = base.copy(fontSize = 14.sp, lineHeight = 19.sp, color = TextSecondary)+ val Caption = base.copy(fontSize = 12.sp, lineHeight = 16.sp, color = TextSecondary)+ val Lyric = display.copy(fontSize = 30.sp, lineHeight = 36.sp, fontWeight = FontWeight.Bold)++ // Spacing.+ val Gutter = 20.dp+ val RowHeight = 60.dp+ /** Room the floating tab bar and mini player take at the bottom of every page. */+ val BottomChrome = 170.dp+}++/** A translucent bar or capsule (tab bar, mini player, menus). */+fun Modifier.glass(shape: Shape = CircleShape): Modifier =+ this.background(Immersive.GlassFill, shape).border(1.dp, Immersive.GlassEdge, shape)diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/components/ImmersiveButtons.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/components/ImmersiveButtons.ktnew file mode 100644index 00000000..8561c486--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/components/ImmersiveButtons.kt@@ -0,0 +1,162 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * sharedUi/src/jvmSharedMain/kotlin/com/music/bitchord/ui/components/Common.kt (MessageState)+ * and sharedUi/.../ui/components/Skeletons.kt (the Play / Shuffle pair's metrics) at edc1e6f. Modified for Myspoti, 2026-10.+ */+package com.music.spotui.ui.immersive.components++import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.rounded.PlayArrow+import androidx.compose.material.icons.rounded.Shuffle+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.Shape+import androidx.compose.ui.graphics.vector.ImageVector+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import app.myspoti.engine.R+import com.music.spotui.ui.immersive.Immersive++/** The height of the page action buttons (Play / Shuffle), and what their skeleton reserves. */+val ImmersiveActionButtonHeight = 50.dp++/**+ * A button of the Immersive look: an optional [icon] and a [text] on a [Immersive.Raised] fill in+ * the accent colour; [filled] swaps it for an accent fill with white content (the primary action).+ * It shrinks a little under the finger.+ */+@Composable+fun ImmersiveButton(+ text: String,+ onClick: () -> Unit,+ modifier: Modifier = Modifier,+ icon: ImageVector? = null,+ filled: Boolean = false,+ shape: Shape = Immersive.Button,+ enabled: Boolean = true,+) {+ val content = if (filled) Color.White else Immersive.Accent+ Row(+ modifier = modifier+ .immersiveClickable(onClick = onClick, enabled = enabled)+ .height(ImmersiveActionButtonHeight)+ .clip(shape)+ .background(if (filled) Immersive.Accent else Immersive.Raised)+ .padding(horizontal = 20.dp),+ horizontalArrangement = Arrangement.Center,+ verticalAlignment = Alignment.CenterVertically,+ ) {+ if (icon != null) {+ Icon(icon, contentDescription = null, tint = content, modifier = Modifier.size(22.dp))+ Spacer(Modifier.width(8.dp))+ }+ Text(+ text = text,+ style = Immersive.BodyStrong.copy(color = content, fontWeight = FontWeight.SemiBold),+ maxLines = 1,+ )+ }+}++/** A round 44 dp icon button on [Immersive.Raised] (a download toggle, a follow, a share). */+@Composable+fun ImmersiveCircleButton(+ icon: ImageVector,+ contentDescription: String?,+ onClick: () -> Unit,+ modifier: Modifier = Modifier,+ tint: Color = Immersive.Accent,+ size: androidx.compose.ui.unit.Dp = 44.dp,+) {+ Box(+ modifier = modifier+ .immersiveClickable(onClick = onClick)+ .size(size)+ .clip(CircleShape)+ .background(Immersive.Raised),+ contentAlignment = Alignment.Center,+ ) {+ Icon(icon, contentDescription = contentDescription, tint = tint, modifier = Modifier.size(22.dp))+ }+}++/**+ * The Play / Shuffle pair under an album's or a playlist's header: two equal-width buttons, side+ * by side, inset by the page gutter. Hide it until there is something to play.+ *+ * `ImmersivePlayShuffleButtons(onPlay = { play(tracks) }, onShuffle = { play(tracks.shuffled()) })`+ */+@Composable+fun ImmersivePlayShuffleButtons(+ onPlay: () -> Unit,+ onShuffle: () -> Unit,+ modifier: Modifier = Modifier,+) {+ Row(+ modifier = modifier+ .fillMaxWidth()+ .padding(horizontal = Immersive.Gutter),+ horizontalArrangement = Arrangement.spacedBy(10.dp),+ ) {+ ImmersiveButton(+ text = stringResource(R.string.immersive_shell_play),+ icon = Icons.Rounded.PlayArrow,+ onClick = onPlay,+ modifier = Modifier.weight(1f),+ )+ ImmersiveButton(+ text = stringResource(R.string.immersive_shell_shuffle),+ icon = Icons.Rounded.Shuffle,+ onClick = onShuffle,+ modifier = Modifier.weight(1f),+ )+ }+}++/**+ * An empty or error state: a centred [message] and, with [actionLabel] and [onAction], a button+ * under it ("Try again").+ */+@Composable+fun ImmersiveMessageState(+ message: String,+ modifier: Modifier = Modifier,+ actionLabel: String? = null,+ onAction: (() -> Unit)? = null,+) {+ Column(+ modifier = modifier+ .fillMaxWidth()+ .padding(horizontal = Immersive.Gutter + 6.dp, vertical = 48.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.spacedBy(16.dp),+ ) {+ Text(+ text = message,+ style = Immersive.Body.copy(color = Immersive.TextSecondary),+ textAlign = TextAlign.Center,+ )+ if (actionLabel != null && onAction != null) {+ ImmersiveButton(text = actionLabel, onClick = onAction, filled = true)+ }+ }+}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.ktnew file mode 100644index 00000000..ead2dfd5--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/components/ImmersiveClickable.kt@@ -0,0 +1,61 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * sharedUi/src/jvmSharedMain/kotlin/com/music/bitchord/ui/components/Common.kt (SignInBanner's press spring) at edc1e6f.+ * Modified for Myspoti, 2026-10.+ */+package com.music.spotui.ui.immersive.components++import androidx.compose.animation.core.animateFloatAsState+import androidx.compose.animation.core.spring+import androidx.compose.foundation.ExperimentalFoundationApi+import androidx.compose.foundation.combinedClickable+import androidx.compose.foundation.interaction.MutableInteractionSource+import androidx.compose.foundation.interaction.collectIsPressedAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.remember+import androidx.compose.ui.Modifier+import androidx.compose.ui.composed+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.hapticfeedback.HapticFeedbackType+import androidx.compose.ui.platform.LocalHapticFeedback+import androidx.compose.ui.semantics.Role++/**+ * Tap and long-press for cards, buttons and rows of the Immersive look: no ripple, the element+ * shrinks to [pressedScale] under the finger and springs back. The long press gives a haptic tick.+ */+@OptIn(ExperimentalFoundationApi::class)+fun Modifier.immersiveClickable(+ onClick: () -> Unit,+ onLongClick: (() -> Unit)? = null,+ pressedScale: Float = 0.97f,+ enabled: Boolean = true,+ role: Role? = Role.Button,+): Modifier = composed {+ val interaction = remember { MutableInteractionSource() }+ val pressed by interaction.collectIsPressedAsState()+ val scale by animateFloatAsState(+ targetValue = if (pressed) pressedScale else 1f,+ animationSpec = spring(stiffness = 900f),+ label = "immersiveClickableScale",+ )+ val haptics = LocalHapticFeedback.current+ this+ .graphicsLayer {+ scaleX = scale+ scaleY = scale+ }+ .combinedClickable(+ interactionSource = interaction,+ indication = null,+ enabled = enabled,+ role = role,+ onClick = onClick,+ onLongClick = onLongClick?.let { long ->+ {+ haptics.performHapticFeedback(HapticFeedbackType.LongPress)+ long()+ }+ },+ )+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/components/ImmersiveCover.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/components/ImmersiveCover.ktnew file mode 100644index 00000000..d6af2e00--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/components/ImmersiveCover.kt@@ -0,0 +1,161 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * sharedUi/src/jvmSharedMain/kotlin/com/music/bitchord/ui/components/Common.kt+ * (and app/src/main/java/com/music/bitchord/ui/components/CoverPlaceholder.kt) at edc1e6f. Modified for Myspoti, 2026-10.+ */+package com.music.spotui.ui.immersive.components++import androidx.compose.animation.core.RepeatMode+import androidx.compose.animation.core.animateFloat+import androidx.compose.animation.core.infiniteRepeatable+import androidx.compose.animation.core.keyframes+import androidx.compose.animation.core.rememberInfiniteTransition+import androidx.compose.foundation.background+import androidx.compose.foundation.border+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.rounded.MusicNote+import androidx.compose.material3.Icon+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.Brush+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.Shape+import androidx.compose.ui.graphics.lerp+import androidx.compose.ui.graphics.vector.ImageVector+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.unit.dp+import com.bumptech.glide.integration.compose.CrossFade+import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi+import com.bumptech.glide.integration.compose.GlideImage+import com.music.spotui.ui.components.spotifyImageUrl+import com.music.spotui.ui.immersive.Immersive++/** The hairline every cover carries, so a cover with light edges does not dissolve into the page. */+fun Modifier.immersiveThumbnailBorder(shape: Shape): Modifier =+ this.border(width = 1.dp, color = Color.White.copy(alpha = 0.12f), shape = shape)++/**+ * A cover (album, playlist, artist, show) from [url], clipped to [shape] with the thumbnail+ * hairline and a [Immersive.Raised] fill that shows while it loads. [url] may be a+ * `spotify:image:` uri (see `spotifyImageUrl`); null or blank draws [placeholderIcon] instead.+ *+ * The size comes from [modifier]: `ImmersiveCover(url, Modifier.size(52.dp))`,+ * `Modifier.fillMaxWidth().aspectRatio(1f)`. Use `CircleShape` for artists.+ */+@OptIn(ExperimentalGlideComposeApi::class)+@Composable+fun ImmersiveCover(+ url: String?,+ modifier: Modifier = Modifier,+ shape: Shape = Immersive.CoverMedium,+ contentDescription: String? = null,+ border: Boolean = true,+ placeholderIcon: ImageVector = Icons.Rounded.MusicNote,+) {+ val model = spotifyImageUrl(url)+ Box(+ modifier = modifier+ .clip(shape)+ .background(Immersive.Raised)+ .then(if (border) Modifier.immersiveThumbnailBorder(shape) else Modifier),+ ) {+ if (model == null) {+ ImmersiveCoverPlaceholder(icon = placeholderIcon, modifier = Modifier.fillMaxSize())+ } else {+ GlideImage(+ model = model,+ contentDescription = contentDescription,+ contentScale = ContentScale.Crop,+ transition = CrossFade,+ modifier = Modifier.fillMaxSize(),+ )+ }+ }+}++/**+ * What stands in for a cover that is not there: a playlist with nothing on it yet, an album whose+ * files carry no picture. A soft diagonal gradient off [base] with a glyph for what the thing is.+ * Callers draw it behind the image, so a cover that loads late simply covers it.+ */+@Composable+fun ImmersiveCoverPlaceholder(+ icon: ImageVector,+ modifier: Modifier = Modifier,+ base: Color = Immersive.Raised,+ tint: Color = Immersive.Text,+ /** The glyph's share of the tile. */+ iconFraction: Float = 0.36f,+) {+ Box(+ modifier = modifier.background(Brush.linearGradient(listOf(lerp(base, tint, 0.16f), base))),+ contentAlignment = Alignment.Center,+ ) {+ Icon(+ imageVector = icon,+ contentDescription = null,+ tint = tint.copy(alpha = 0.6f),+ modifier = Modifier.fillMaxSize(iconFraction),+ )+ }+}++/**+ * Three bars dancing on a dark plate, laid over a cover to mark the song that is playing.+ * The plate is a fixed square so only the bars move.+ */+@Composable+fun ImmersivePlayingBars(modifier: Modifier = Modifier) {+ val heights = listOf(0.38f, 0.78f, 0.52f).mapIndexed { index, minimum ->+ val transition = rememberInfiniteTransition(label = "immersive playing bar $index")+ val height by transition.animateFloat(+ initialValue = minimum,+ targetValue = 1f - (index * 0.12f),+ animationSpec = infiniteRepeatable(+ animation = keyframes {+ durationMillis = 520 + index * 130+ minimum at 0+ 1f at (260 + index * 50)+ minimum at durationMillis+ },+ repeatMode = RepeatMode.Reverse,+ ),+ label = "immersive playing bar height $index",+ )+ height+ }+ Box(+ modifier = modifier+ .size(24.dp)+ .clip(RoundedCornerShape(6.dp))+ .background(Color.Black.copy(alpha = 0.52f)),+ contentAlignment = Alignment.Center,+ ) {+ Row(+ modifier = Modifier.height(14.dp),+ horizontalArrangement = Arrangement.spacedBy(2.dp),+ verticalAlignment = Alignment.Bottom,+ ) {+ heights.forEach { height ->+ Box(+ Modifier+ .width(3.dp)+ .height(14.dp * height)+ .clip(RoundedCornerShape(2.dp))+ .background(Color.White),+ )+ }+ }+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/components/ImmersiveOverscroll.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/components/ImmersiveOverscroll.ktnew file mode 100644index 00000000..9df5212c--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/components/ImmersiveOverscroll.kt@@ -0,0 +1,198 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * app/src/main/java/com/music/bitchord/ui/utils/IosOverscroll.kt at edc1e6f. Modified for Myspoti, 2026-10.+ */++/*+ * Adapted from Convx's IosOverscroll.kt (GPL-3.0):+ * https://github.com/cosmictaserdev-creator/Convx+ */+package com.music.spotui.ui.immersive.components++import androidx.compose.animation.core.Spring+import androidx.compose.animation.core.animate+import androidx.compose.animation.core.spring+import androidx.compose.foundation.OverscrollEffect+import androidx.compose.foundation.OverscrollFactory+import androidx.compose.runtime.Composable+import androidx.compose.runtime.MutableFloatState+import androidx.compose.runtime.mutableFloatStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.input.nestedscroll.NestedScrollSource+import androidx.compose.ui.layout.Measurable+import androidx.compose.ui.layout.MeasureResult+import androidx.compose.ui.layout.MeasureScope+import androidx.compose.ui.node.DelegatableNode+import androidx.compose.ui.node.LayoutModifierNode+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.unit.Constraints+import androidx.compose.ui.unit.Density+import androidx.compose.ui.unit.Velocity+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.coroutineScope+import kotlinx.coroutines.launch+import kotlin.math.abs+import kotlin.math.sign++private const val rubberBandConstant = 0.55f+private const val fallbackContainerPx = 2_000f+private const val maxBounceVelocity = 10_000f+private const val highVelocityThreshold = 5_000f+private const val normalBounceStiffness = 247f+private const val fastBounceStiffness = 130f++/**+ * Converts raw pull distance to UIKit's self-limiting rubber-band curve.+ */+private fun rubberBand(rawDistance: Float, containerPx: Float): Float {+ val dimension = containerPx.takeIf { it > 0f } ?: fallbackContainerPx+ val distance = abs(rawDistance)+ val banded = (1f - 1f / (distance * rubberBandConstant / dimension + 1f)) *+ dimension / rubberBandConstant+ return banded * sign(rawDistance)+}++/**+ * An iOS-style overscroll effect for Compose scroll containers.+ *+ * It replaces Android's stretch/glow with a UIScrollView-like rubber band during a+ * drag, then critically damps the content back to its resting position on release.+ */+private class IosOverscrollEffect : OverscrollEffect {+ private val rawPullX = mutableFloatStateOf(0f)+ private val rawPullY = mutableFloatStateOf(0f)+ private var containerWidthPx = 0f+ private var containerHeightPx = 0f++ override val isInProgress: Boolean+ get() = rawPullX.floatValue != 0f || rawPullY.floatValue != 0f++ override fun applyToScroll(+ delta: Offset,+ source: NestedScrollSource,+ performScroll: (Offset) -> Offset,+ ): Offset {+ // When pulling back from an existing stretch, settle the stretch before+ // allowing the list itself to scroll. This keeps the motion continuous.+ val paidX = payDown(rawPullX, delta.x)+ val paidY = payDown(rawPullY, delta.y)+ val remaining = Offset(delta.x - paidX, delta.y - paidY)+ val consumed = performScroll(remaining)+ val leftover = remaining - consumed++ // Absorb only touch deltas. Fling leftovers must be returned so Compose+ // cancels its decay and gives their velocity to applyToFling below.+ var stretchedX = 0f+ var stretchedY = 0f+ if (source == NestedScrollSource.UserInput) {+ if (leftover.x != 0f) {+ rawPullX.floatValue += leftover.x+ stretchedX = leftover.x+ }+ if (leftover.y != 0f) {+ rawPullY.floatValue += leftover.y+ stretchedY = leftover.y+ }+ }+ return Offset(consumed.x + paidX + stretchedX, consumed.y + paidY + stretchedY)+ }++ override suspend fun applyToFling(+ velocity: Velocity,+ performFling: suspend (Velocity) -> Velocity,+ ) {+ val consumed = performFling(velocity)+ val leftover = velocity - consumed+ if (!isInProgress && leftover == Velocity.Zero) return++ coroutineScope {+ launch { settle(rawPullX, leftover.x) }+ launch { settle(rawPullY, leftover.y) }+ }+ }++ private fun payDown(pull: MutableFloatState, delta: Float): Float {+ val current = pull.floatValue+ if (current == 0f || delta == 0f || sign(current) == sign(delta)) return 0f+ val target = current + delta+ val next = if (sign(target) != sign(current)) 0f else target+ pull.floatValue = next+ return next - current+ }++ private suspend fun settle(pull: MutableFloatState, leftoverVelocity: Float) {+ if (pull.floatValue == 0f && leftoverVelocity == 0f) return+ val velocity = leftoverVelocity.coerceIn(-maxBounceVelocity, maxBounceVelocity)+ animate(+ initialValue = pull.floatValue,+ targetValue = 0f,+ initialVelocity = velocity,+ animationSpec = spring(+ dampingRatio = Spring.DampingRatioNoBouncy,+ stiffness = if (abs(velocity) > highVelocityThreshold) {+ fastBounceStiffness+ } else {+ normalBounceStiffness+ },+ ),+ ) { value, _ -> pull.floatValue = value }+ }++ override val node: DelegatableNode = IosOverscrollNode(+ offsetX = { rubberBand(rawPullX.floatValue, containerWidthPx) },+ offsetY = { rubberBand(rawPullY.floatValue, containerHeightPx) },+ onMeasured = { width, height ->+ containerWidthPx = width+ containerHeightPx = height+ },+ )+}++private class IosOverscrollNode(+ private val offsetX: () -> Float,+ private val offsetY: () -> Float,+ private val onMeasured: (Float, Float) -> Unit,+) : Modifier.Node(), LayoutModifierNode {+ override fun MeasureScope.measure(+ measurable: Measurable,+ constraints: Constraints,+ ): MeasureResult {+ val placeable = measurable.measure(constraints)+ onMeasured(+ (if (constraints.hasBoundedWidth) constraints.maxWidth else placeable.width).toFloat(),+ (if (constraints.hasBoundedHeight) constraints.maxHeight else placeable.height).toFloat(),+ )+ return layout(placeable.width, placeable.height) {+ placeable.placeWithLayer(0, 0) {+ translationX = offsetX()+ translationY = offsetY()+ }+ }+ }+}++private class IosOverscrollFactory(+ private val density: Density,+ private val scope: CoroutineScope,+) : OverscrollFactory {+ override fun createOverscrollEffect(): OverscrollEffect = IosOverscrollEffect()++ override fun equals(other: Any?): Boolean =+ other is IosOverscrollFactory && other.density == density && other.scope === scope++ override fun hashCode(): Int = 31 * density.hashCode() + scope.hashCode()+}++/**+ * Provides iOS-style rubber-band overscroll to every descendant scroll container:+ * `CompositionLocalProvider(LocalOverscrollFactory provides rememberImmersiveOverscrollFactory()) { ... }`+ */+@Composable+fun rememberImmersiveOverscrollFactory(): OverscrollFactory {+ val density = LocalDensity.current+ val scope = rememberCoroutineScope()+ return remember(density, scope) { IosOverscrollFactory(density, scope) }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/components/ImmersiveRows.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/components/ImmersiveRows.ktnew file mode 100644index 00000000..55f3ac86--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/components/ImmersiveRows.kt@@ -0,0 +1,286 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * sharedUi/src/jvmSharedMain/kotlin/com/music/bitchord/ui/components/Common.kt at edc1e6f. Modified for Myspoti, 2026-10.+ */+package com.music.spotui.ui.immersive.components++import androidx.compose.animation.animateColorAsState+import androidx.compose.foundation.ExperimentalFoundationApi+import androidx.compose.foundation.clickable+import androidx.compose.foundation.combinedClickable+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.rounded.GraphicEq+import androidx.compose.material.icons.rounded.MoreVert+import androidx.compose.material.icons.rounded.PlayArrow+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.alpha+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.hapticfeedback.HapticFeedbackType+import androidx.compose.ui.layout.layout+import androidx.compose.ui.platform.LocalHapticFeedback+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.semantics.Role+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp+import app.myspoti.engine.R+import com.music.spotui.data.entity.SongsModel+import com.music.spotui.ui.immersive.Immersive++/** The cover of a row, and the height that lines the rows up (4 dp above and below it make [Immersive.RowHeight]). */+private val RowCover = 52.dp++/** A numbered row's track-number column, the number centred in it: room for three digits. */+private val TrackNumberWidth = 24.dp++/** How far a row's [ImmersiveMoreButton] reaches past the content edge into the gutter. */+private val RowMoreOutset = 14.dp++/** Where a divider under a track row starts: clear of the cover. */+val ImmersiveRowDividerInset = Immersive.Gutter + RowCover + 14.dp++private val RowTitle = Immersive.Body.copy(fontWeight = FontWeight.Medium)++/**+ * One track row for search results, album and playlist pages, the library: a 52 dp cover (or+ * [trackNumber] in its place), the title with an explicit badge, the artist, the duration and a+ * "more" button. Tap plays, long-press (or the button) calls [onMore].+ *+ * @param song the track to show (cover, title, artist, explicit, duration).+ * @param playing this song is the one playing right now: bars over its cover, title in the accent.+ * @param onMore opens the song's menu; null hides the button (and the long press).+ * @param current this song is the loaded one, playing or paused: accent title. Defaults to [playing].+ * @param trackNumber shown in place of the cover, for an album's own listing.+ * @param showDuration the length at the end of the row.+ * @param showAlbum "artist · album" as the second line instead of just the artist.+ */+@OptIn(ExperimentalFoundationApi::class)+@Composable+fun ImmersiveSongRow(+ song: SongsModel,+ playing: Boolean,+ onClick: () -> Unit,+ onMore: (() -> Unit)?,+ modifier: Modifier = Modifier,+ current: Boolean = playing,+ trackNumber: Int? = null,+ showDuration: Boolean = false,+ showAlbum: Boolean = false,+ trailing: (@Composable () -> Unit)? = null,+) {+ val titleColor by animateColorAsState(+ targetValue = if (current) Immersive.Accent else Immersive.Text,+ label = "immersive song row title",+ )+ val subtitle = if (showAlbum && song.album.isNotBlank() && song.singer.isNotBlank()) {+ "${song.singer} · ${song.album}"+ } else {+ song.singer.ifBlank { song.album }+ }+ RowScaffold(+ title = song.title,+ subtitle = subtitle,+ onClick = onClick,+ onLongClick = onMore,+ modifier = modifier.alpha(if (song.playable) 1f else 0.45f),+ titleColor = titleColor,+ explicit = song.explicit,+ leading = {+ if (trackNumber != null) {+ Box(Modifier.width(TrackNumberWidth).height(RowCover), contentAlignment = Alignment.Center) {+ if (current) {+ Icon(+ imageVector = if (playing) Icons.Rounded.GraphicEq else Icons.Rounded.PlayArrow,+ contentDescription = stringResource(R.string.immersive_shell_now_playing),+ tint = Immersive.Accent,+ modifier = Modifier.size(22.dp),+ )+ } else {+ Text(text = "$trackNumber", style = Immersive.Body.copy(color = Immersive.TextSecondary), maxLines = 1)+ }+ }+ } else {+ Box(Modifier.size(RowCover)) {+ ImmersiveCover(song.coverUri, Modifier.matchParentSize(), Immersive.CoverSmall)+ if (playing) ImmersivePlayingBars(Modifier.align(Alignment.Center))+ }+ }+ },+ gapAfterLeading = if (trackNumber == null) 14.dp else Immersive.Gutter,+ trailingText = if (showDuration && song.durationMs > 0) formatDuration(song.durationMs) else null,+ onMore = onMore,+ trailing = trailing,+ )+}++/**+ * A generic row: a 52 dp cover (a circle when [round], for artists), a title, a subtitle and an+ * optional "more" button. For playlists, albums, artists, shows and library entries.+ *+ * @param imageUrl the cover; null/blank draws the placeholder glyph.+ * @param playing bars over the cover and the title in the accent (the playing context).+ * @param onMore opens the item's menu; null hides the button (and the long press).+ * @param trailing extra content before the more button (a pin, a download badge, a chevron).+ */+@OptIn(ExperimentalFoundationApi::class)+@Composable+fun ImmersiveListRow(+ title: String,+ subtitle: String?,+ imageUrl: String?,+ round: Boolean,+ onClick: () -> Unit,+ onMore: (() -> Unit)? = null,+ modifier: Modifier = Modifier,+ playing: Boolean = false,+ trailing: (@Composable () -> Unit)? = null,+) {+ val titleColor by animateColorAsState(+ targetValue = if (playing) Immersive.Accent else Immersive.Text,+ label = "immersive list row title",+ )+ RowScaffold(+ title = title,+ subtitle = subtitle.orEmpty(),+ onClick = onClick,+ onLongClick = onMore,+ modifier = modifier,+ titleColor = titleColor,+ explicit = false,+ leading = {+ Box(Modifier.size(RowCover)) {+ ImmersiveCover(+ imageUrl,+ Modifier.matchParentSize(),+ if (round) CircleShape else Immersive.CoverSmall,+ )+ if (playing) ImmersivePlayingBars(Modifier.align(Alignment.Center))+ }+ },+ gapAfterLeading = 14.dp,+ trailingText = null,+ trailing = trailing,+ onMore = onMore,+ )+}++@OptIn(ExperimentalFoundationApi::class)+@Composable+private fun RowScaffold(+ title: String,+ subtitle: String,+ onClick: () -> Unit,+ onLongClick: (() -> Unit)?,+ modifier: Modifier,+ titleColor: Color,+ explicit: Boolean,+ leading: @Composable () -> Unit,+ gapAfterLeading: Dp,+ trailingText: String?,+ onMore: (() -> Unit)?,+ trailing: (@Composable () -> Unit)? = null,+) {+ val haptics = LocalHapticFeedback.current+ Row(+ modifier = modifier+ .fillMaxWidth()+ .combinedClickable(+ role = Role.Button,+ onClick = onClick,+ onLongClick = onLongClick?.let { long ->+ {+ haptics.performHapticFeedback(HapticFeedbackType.LongPress)+ long()+ }+ },+ )+ .padding(horizontal = Immersive.Gutter, vertical = 4.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ leading()+ Spacer(Modifier.width(gapAfterLeading))+ Column(Modifier.weight(1f)) {+ ImmersiveSongTitle(title = title, explicit = explicit, style = RowTitle, color = titleColor)+ if (subtitle.isNotBlank()) {+ Spacer(Modifier.height(2.dp))+ Text(+ text = subtitle,+ style = Immersive.Subhead,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )+ }+ }+ trailing?.invoke()+ if (trailingText != null) {+ Spacer(Modifier.width(8.dp))+ Text(text = trailingText, style = Immersive.Caption)+ }+ if (onMore != null) ImmersiveMoreButton(onClick = onMore)+ }+}++/**+ * The ⋮ at the end of a row. Its circle is a touch target nobody sees, so it hangs [RowMoreOutset]+ * into the page gutter: the dots end at the row's content edge, mirroring the cover on the left,+ * rather than a whole button's width short of it — and the row's text gets that width back.+ */+@Composable+fun ImmersiveMoreButton(+ onClick: () -> Unit,+ modifier: Modifier = Modifier,+ tint: Color = Immersive.TextSecondary,+ iconSize: Dp = 20.dp,+) {+ Box(+ modifier = modifier+ .hangIntoGutter(RowMoreOutset)+ .size(36.dp)+ .clip(CircleShape)+ .clickable(role = Role.Button, onClick = onClick),+ contentAlignment = Alignment.Center,+ ) {+ Icon(+ Icons.Rounded.MoreVert,+ contentDescription = stringResource(R.string.immersive_shell_more),+ tint = tint,+ modifier = Modifier.size(iconSize),+ )+ }+}++/**+ * Lays a trailing control out [outset] narrower than it draws, so it overhangs its row's end edge+ * by that much: for buttons whose glyph is far smaller than their touch target.+ */+fun Modifier.hangIntoGutter(outset: Dp): Modifier = layout { measurable, constraints ->+ val placeable = measurable.measure(constraints)+ val width = (placeable.width - outset.roundToPx()).coerceAtLeast(0)+ layout(width, placeable.height) { placeable.place(0, 0) }+}++/** 213000 ms -> "3:33". */+internal fun formatDuration(ms: Int): String {+ val total = ms / 1000+ val h = total / 3600+ val m = (total % 3600) / 60+ val s = total % 60+ return if (h > 0) "%d:%02d:%02d".format(h, m, s) else "%d:%02d".format(m, s)+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/components/ImmersiveSearchField.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/components/ImmersiveSearchField.ktnew file mode 100644index 00000000..e07bc795--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/components/ImmersiveSearchField.kt@@ -0,0 +1,137 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * sharedUi/src/jvmSharedMain/kotlin/com/music/bitchord/ui/components/SearchField.kt at edc1e6f. Modified for Myspoti, 2026-10.+ */+package com.music.spotui.ui.immersive.components++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.Spacer+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.text.BasicTextField+import androidx.compose.foundation.text.KeyboardActions+import androidx.compose.foundation.text.KeyboardOptions+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.rounded.Close+import androidx.compose.material.icons.rounded.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.SolidColor+import androidx.compose.ui.platform.LocalFocusManager+import androidx.compose.ui.platform.LocalSoftwareKeyboardController+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.semantics.Role+import androidx.compose.ui.text.input.ImeAction+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import app.myspoti.engine.R+import com.music.spotui.ui.immersive.Immersive++/**+ * The search field of the Immersive look: a [Immersive.Raised] capsule with a magnifier that+ * doubles as the submit button, a hint that gives way to the typed text, and a clear button once+ * there is something to clear. Stateless: keep [query] in the caller (the Search view model).+ *+ * @param onSubmit the keyboard's search key, or a tap on the magnifier with a non-blank query.+ * @param focusRequester lets the host focus it (re-tapping the Search tab).+ * @param placeholder what the empty field says it is for.+ */+@Composable+fun ImmersiveSearchField(+ query: String,+ onQueryChange: (String) -> Unit,+ onSubmit: () -> Unit,+ modifier: Modifier = Modifier,+ focusRequester: FocusRequester = remember { FocusRequester() },+ placeholder: String = stringResource(R.string.immersive_shell_search_hint),+) {+ val focusManager = LocalFocusManager.current+ val keyboardController = LocalSoftwareKeyboardController.current+ // Both ways of saying "search this" do the same two things, so they are written once here.+ val submit = {+ onSubmit()+ focusManager.clearFocus()+ }+ Row(+ modifier = modifier+ .fillMaxWidth()+ // Fixed height prevents the row from growing when text is entered.+ .height(46.dp)+ .background(Immersive.Raised, Immersive.Button)+ // Asymmetric: the magnifier is a button and wants a real touch target, so it is given+ // the room by pulling the field's own start padding in.+ .padding(start = 8.dp, end = 12.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Icon(+ Icons.Rounded.Search,+ contentDescription = stringResource(R.string.immersive_shell_search_hint),+ tint = Immersive.TextSecondary,+ modifier = Modifier+ .size(32.dp)+ .clip(CircleShape)+ .clickable(enabled = query.isNotBlank(), role = Role.Button, onClick = submit)+ .padding(6.dp),+ )+ Spacer(Modifier.width(4.dp))+ Box(Modifier.weight(1f)) {+ if (query.isEmpty()) {+ Text(+ text = placeholder,+ style = Immersive.Body.copy(color = Immersive.TextSecondary),+ // A narrow field must cut the hint short, not wrap it out of the capsule.+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )+ }+ BasicTextField(+ value = query,+ onValueChange = onQueryChange,+ singleLine = true,+ textStyle = Immersive.Body,+ cursorBrush = SolidColor(Immersive.Accent),+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),+ keyboardActions = KeyboardActions(onSearch = { submit() }),+ modifier = Modifier+ .fillMaxWidth()+ .focusRequester(focusRequester),+ )+ }+ // Emptying the field is also how the recent searches are got back to: one tap.+ if (query.isNotEmpty()) {+ Box(+ modifier = Modifier+ .size(28.dp)+ .clip(CircleShape)+ .clickable(role = Role.Button) {+ onQueryChange("")+ // Clearing is an edit, not a dismissal: leave the user ready to type.+ focusRequester.requestFocus()+ keyboardController?.show()+ },+ contentAlignment = Alignment.Center,+ ) {+ Icon(+ Icons.Rounded.Close,+ contentDescription = stringResource(R.string.immersive_shell_search_clear),+ tint = Immersive.TextSecondary,+ modifier = Modifier.size(18.dp),+ )+ }+ }+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/components/ImmersiveSections.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/components/ImmersiveSections.ktnew file mode 100644index 00000000..a61d19be--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/components/ImmersiveSections.kt@@ -0,0 +1,285 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * sharedUi/src/jvmSharedMain/kotlin/com/music/bitchord/ui/screens/HomeScreen.kt (SectionHeader, Shelf, ShelfCard, HeroCard),+ * sharedUi/src/jvmSharedMain/kotlin/com/music/bitchord/ui/components/ShelfRow.kt and+ * sharedUi/src/jvmSharedMain/kotlin/com/music/bitchord/ui/components/Common.kt at edc1e6f. Modified for Myspoti, 2026-10.+ */+package com.music.spotui.ui.immersive.components++import androidx.compose.foundation.ExperimentalFoundationApi+import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.gestures.snapping.rememberSnapFlingBehavior+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.aspectRatio+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.lazy.LazyListScope+import androidx.compose.foundation.lazy.LazyListState+import androidx.compose.foundation.lazy.LazyRow+import androidx.compose.foundation.lazy.rememberLazyListState+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.Brush+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.semantics.Role+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp+import app.myspoti.engine.R+import com.bumptech.glide.integration.compose.CrossFade+import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi+import com.bumptech.glide.integration.compose.GlideImage+import com.music.spotui.ui.components.spotifyImageUrl+import com.music.spotui.ui.immersive.Immersive++/**+ * Width of a card in the compact carousels (home shelves, library shelves, an artist's releases).+ * Sized so a phone-width row shows two cards whole with the edge of a third showing: enough to say+ * the row scrolls without a card being half a card.+ */+val ImmersiveShelfCardWidth = 150.dp++/** Share of the row a lead-shelf card takes, so the next one peeks in past it. */+private const val HERO_CARD_FRACTION = 0.70f++/** How wide a lead-shelf card is ever allowed to get: a caption over some artwork, not a poster. */+private val HERO_CARD_MAX_WIDTH = 320.dp++/** A lead-shelf card's proportions: a touch taller than it is wide. */+const val ImmersiveHeroCardRatio = 0.92f++/**+ * How wide a lead-shelf card should be in a row [available] wide — the shared answer for the real+ * shelf and for the skeleton standing in for it, which have to agree or the feed jumps when the+ * data lands. Give it the row's own width (`BoxWithConstraints.maxWidth`), not the window's.+ */+fun immersiveHeroCardWidth(available: Dp): Dp = minOf(available * HERO_CARD_FRACTION, HERO_CARD_MAX_WIDTH)++/**+ * A section's heading: [title] in the page's title type, an optional [subtitle] line and, when+ * [onSeeAll] is set, a "See all" link in the accent at the end.+ *+ * Put it above a [ImmersiveShelfRow] or a run of rows: `SectionHeader("Recently played", onSeeAll = ::open)`.+ */+@Composable+fun SectionHeader(+ title: String,+ onSeeAll: (() -> Unit)? = null,+ modifier: Modifier = Modifier,+ subtitle: String = "",+) {+ Row(+ modifier = modifier+ .padding(horizontal = Immersive.Gutter, vertical = 10.dp)+ .fillMaxWidth(),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Column(Modifier.weight(1f)) {+ Text(+ text = title,+ style = Immersive.Title,+ maxLines = 2,+ overflow = TextOverflow.Ellipsis,+ )+ if (subtitle.isNotBlank()) {+ Text(+ text = subtitle,+ style = Immersive.Subhead,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )+ }+ }+ if (onSeeAll != null) {+ Text(+ text = stringResource(R.string.immersive_shell_see_all),+ style = Immersive.Subhead.copy(color = Immersive.Accent, fontWeight = FontWeight.Medium),+ modifier = Modifier+ .clickable(role = Role.Button, onClick = onSeeAll)+ .padding(start = 12.dp, top = 4.dp, bottom = 4.dp),+ )+ }+ }+}++/**+ * A sideways-scrolling row. Snaps to each cell rather than stopping mid-card: a fling always+ * settles with a card aligned to the leading edge instead of leaving items cut in half.+ */+@OptIn(ExperimentalFoundationApi::class)+@Composable+fun ImmersiveShelfRow(+ modifier: Modifier = Modifier,+ contentPadding: PaddingValues = PaddingValues(horizontal = Immersive.Gutter),+ horizontalArrangement: Arrangement.Horizontal = Arrangement.spacedBy(14.dp),+ state: LazyListState = rememberLazyListState(),+ content: LazyListScope.() -> Unit,+) {+ LazyRow(+ modifier = modifier,+ state = state,+ contentPadding = contentPadding,+ horizontalArrangement = horizontalArrangement,+ flingBehavior = rememberSnapFlingBehavior(lazyListState = state),+ content = content,+ )+}++/**+ * A titled shelf: a [SectionHeader] over a [ImmersiveShelfRow]. Fill the row with+ * [ImmersiveShelfCard]s:+ *+ * ```+ * ImmersiveShelf("New releases", onSeeAll = ::open) {+ * items(albums, key = { it.id }) { a -> ImmersiveShelfCard(a.name, a.artist, a.imageUrl, onClick = { open(a) }) }+ * }+ * ```+ */+@Composable+fun ImmersiveShelf(+ title: String,+ modifier: Modifier = Modifier,+ onSeeAll: (() -> Unit)? = null,+ subtitle: String = "",+ state: LazyListState = rememberLazyListState(),+ content: LazyListScope.() -> Unit,+) {+ Column(modifier.padding(bottom = 26.dp)) {+ SectionHeader(title = title, onSeeAll = onSeeAll, subtitle = subtitle)+ ImmersiveShelfRow(state = state, content = content)+ }+}++/**+ * A square card for a shelf: a cover over a title and a subtitle. With [round] (artists) the cover+ * is a circle and the text is centred under it.+ *+ * @param playing bars over the cover and the title in the accent.+ * @param onLongClick the card's menu; null for none.+ */+@Composable+fun ImmersiveShelfCard(+ title: String,+ subtitle: String?,+ imageUrl: String?,+ onClick: () -> Unit,+ modifier: Modifier = Modifier.width(ImmersiveShelfCardWidth),+ round: Boolean = false,+ playing: Boolean = false,+ onLongClick: (() -> Unit)? = null,+) {+ Column(+ modifier = modifier.immersiveClickable(onClick = onClick, onLongClick = onLongClick),+ horizontalAlignment = if (round) Alignment.CenterHorizontally else Alignment.Start,+ ) {+ Box(Modifier.fillMaxWidth().aspectRatio(1f)) {+ ImmersiveCover(+ imageUrl,+ Modifier.fillMaxSize(),+ if (round) CircleShape else Immersive.CoverMedium,+ )+ if (playing) ImmersivePlayingBars(Modifier.align(Alignment.Center))+ }+ Spacer(Modifier.height(10.dp))+ Text(+ text = title,+ style = Immersive.Body.copy(+ fontWeight = FontWeight.Medium,+ color = if (playing) Immersive.Accent else Immersive.Text,+ ),+ textAlign = if (round) TextAlign.Center else TextAlign.Start,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ modifier = Modifier.fillMaxWidth(),+ )+ if (!subtitle.isNullOrBlank()) {+ Text(+ text = subtitle,+ style = Immersive.Subhead,+ textAlign = if (round) TextAlign.Center else TextAlign.Start,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ modifier = Modifier.fillMaxWidth(),+ )+ }+ }+}++/**+ * The big card of a lead shelf: the artwork with the caption laid over a scrim, as on a "Listen+ * now" row. Give it a width from [immersiveHeroCardWidth] and place several in an [ImmersiveShelfRow]+ * so the next one peeks in.+ *+ * @param playing bars over the artwork and the title in the accent.+ */+@Composable+@OptIn(ExperimentalGlideComposeApi::class)+fun ImmersiveLargeAlbumCard(+ title: String,+ subtitle: String?,+ imageUrl: String?,+ onClick: () -> Unit,+ modifier: Modifier = Modifier,+ playing: Boolean = false,+ onLongClick: (() -> Unit)? = null,+) {+ val model = spotifyImageUrl(imageUrl)+ Box(+ modifier = modifier+ .immersiveClickable(onClick = onClick, onLongClick = onLongClick, pressedScale = 0.98f)+ .aspectRatio(ImmersiveHeroCardRatio)+ .clip(Immersive.Card)+ .background(Immersive.Raised)+ .immersiveThumbnailBorder(Immersive.Card),+ ) {+ if (model != null) {+ GlideImage(+ model = model,+ contentDescription = null,+ contentScale = ContentScale.Crop,+ transition = CrossFade,+ modifier = Modifier.fillMaxSize(),+ )+ }+ if (playing) ImmersivePlayingBars(Modifier.align(Alignment.Center))+ Column(+ modifier = Modifier+ .fillMaxWidth()+ .align(Alignment.BottomStart)+ .background(Brush.verticalGradient(listOf(Color.Transparent, Color.Black.copy(alpha = 0.78f))))+ .padding(start = 16.dp, end = 16.dp, top = 34.dp, bottom = 14.dp),+ ) {+ Text(+ text = title,+ style = Immersive.Headline.copy(color = if (playing) Immersive.Accent else Color.White),+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )+ if (!subtitle.isNullOrBlank()) {+ Text(+ text = subtitle,+ style = Immersive.Subhead.copy(color = Color.White.copy(alpha = 0.72f)),+ maxLines = 2,+ overflow = TextOverflow.Ellipsis,+ )+ }+ }+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/components/ImmersiveSkeletons.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/components/ImmersiveSkeletons.ktnew file mode 100644index 00000000..83b16049--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/components/ImmersiveSkeletons.kt@@ -0,0 +1,265 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * sharedUi/src/jvmSharedMain/kotlin/com/music/bitchord/ui/components/Skeletons.kt at edc1e6f. Modified for Myspoti, 2026-10.+ */+package com.music.spotui.ui.immersive.components++import androidx.compose.animation.core.LinearEasing+import androidx.compose.animation.core.animateFloat+import androidx.compose.animation.core.infiniteRepeatable+import androidx.compose.animation.core.rememberInfiniteTransition+import androidx.compose.animation.core.tween+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxWithConstraints+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.aspectRatio+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.lazy.LazyListScope+import androidx.compose.foundation.lazy.LazyRow+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.draw.drawWithCache+import androidx.compose.ui.graphics.Brush+import androidx.compose.ui.graphics.Shape+import androidx.compose.ui.graphics.compositeOver+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp+import com.music.spotui.ui.immersive.Immersive++/*+ * Grey stand-ins for content still on the wire, laid out to the same metrics as the real rows and+ * cards so nothing jumps when the data lands.+ */++/** How long one highlight sweep takes to cross a placeholder. */+private const val SHIMMER_PERIOD_MS = 1400++private val BlockShape = RoundedCornerShape(6.dp)+private val LineShape = RoundedCornerShape(4.dp)++// Ragged widths, so a run of rows reads as text rather than as a barcode.+private val TitleWidths = listOf(0.68f, 0.46f, 0.58f, 0.74f, 0.52f)+private val SubtitleWidths = listOf(0.34f, 0.44f, 0.27f, 0.38f, 0.31f)++/**+ * One placeholder block, with a highlight sweeping across it.+ *+ * The sweep is read inside the draw block rather than the composable body: a screenful of these+ * would otherwise recompose on every animation frame, and all any of them needs per frame is a+ * fresh gradient.+ */+@Composable+fun ImmersiveShimmerBox(modifier: Modifier = Modifier, shape: Shape = BlockShape) {+ val base = Immersive.Raised+ val highlight = Immersive.Text.copy(alpha = 0.10f).compositeOver(base)+ val sweep = rememberInfiniteTransition(label = "immersive skeleton").animateFloat(+ initialValue = 0f,+ targetValue = 1f,+ animationSpec = infiniteRepeatable(tween(SHIMMER_PERIOD_MS, easing = LinearEasing)),+ label = "sweep",+ )+ Box(+ modifier+ .clip(shape)+ .drawWithCache {+ // The band travels from fully off one edge to fully off the other, which leaves a+ // beat of flat grey between passes rather than a highlight parked on the block.+ val band = size.width * 0.5f+ val startX = -band + sweep.value * (size.width + band * 2)+ val brush = Brush.horizontalGradient(+ colors = listOf(base, highlight, base),+ startX = startX,+ endX = startX + band,+ )+ onDrawBehind { drawRect(brush) }+ },+ )+}++/** A placeholder for one line of text, sized as a fraction of its parent. */+@Composable+private fun SkeletonLine(fraction: Float, height: Dp, modifier: Modifier = Modifier) {+ ImmersiveShimmerBox(+ modifier = modifier.fillMaxWidth(fraction).height(height),+ shape = LineShape,+ )+}++/** Stands in for a [SectionHeader]. Only the title line is drawn: most shelves have no subtitle. */+@Composable+fun ImmersiveSectionHeaderSkeleton(index: Int = 0) {+ Column(Modifier.padding(horizontal = Immersive.Gutter, vertical = 10.dp)) {+ SkeletonLine(fraction = TitleWidths[index % TitleWidths.size] * 0.7f, height = 20.dp)+ }+}++/**+ * Stands in for one [ImmersiveSongRow], down to the 52 dp cover and the gutter. [circular] matches+ * rows of artists, drawn as circles.+ */+@Composable+fun ImmersiveSongRowSkeleton(index: Int = 0, circular: Boolean = false, modifier: Modifier = Modifier) {+ Row(+ modifier = modifier+ .fillMaxWidth()+ .padding(horizontal = Immersive.Gutter, vertical = 4.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ ImmersiveShimmerBox(Modifier.size(52.dp), if (circular) CircleShape else Immersive.CoverSmall)+ Spacer(Modifier.width(14.dp))+ Column(Modifier.weight(1f)) {+ SkeletonLine(fraction = TitleWidths[index % TitleWidths.size], height = 14.dp)+ Spacer(Modifier.height(7.dp))+ SkeletonLine(fraction = SubtitleWidths[index % SubtitleWidths.size], height = 11.dp)+ }+ }+}++/** A run of track-row placeholders, for search hits and release track lists. */+fun LazyListScope.immersiveSongListSkeleton(+ count: Int = 8,+ keyPrefix: String = "skeleton:song",+ circular: Boolean = false,+ alpha: Float = 1f,+) {+ items(count, key = { "$keyPrefix:$it" }) { index ->+ Box(Modifier.graphicsLayer { this.alpha = alpha }) {+ ImmersiveSongRowSkeleton(index = index, circular = circular)+ }+ }+}++/**+ * The lead shelf on Home: near-page-width cards that page sideways. Built on a [LazyRow] with+ * scrolling off rather than a plain Row, so a card running past the right edge is measured and+ * clipped exactly as the real shelf's is — which is the whole point of a skeleton.+ */+@Composable+fun ImmersiveHeroShelfSkeleton() {+ Column(Modifier.padding(bottom = 26.dp)) {+ ImmersiveSectionHeaderSkeleton()+ BoxWithConstraints {+ val cardWidth = immersiveHeroCardWidth(maxWidth)+ LazyRow(+ contentPadding = PaddingValues(horizontal = Immersive.Gutter),+ horizontalArrangement = Arrangement.spacedBy(14.dp),+ userScrollEnabled = false,+ ) {+ items(2) {+ ImmersiveShimmerBox(+ modifier = Modifier.width(cardWidth).aspectRatio(ImmersiveHeroCardRatio),+ shape = Immersive.Card,+ )+ }+ }+ }+ }+}++/** The compact carousel of square cards used by every shelf below the first. */+@Composable+fun ImmersiveShelfSkeleton(+ index: Int = 0,+ cardWidth: Dp = ImmersiveShelfCardWidth,+ cardShape: Shape = Immersive.CoverMedium,+) {+ Column(Modifier.padding(bottom = 26.dp)) {+ ImmersiveSectionHeaderSkeleton(index = index)+ LazyRow(+ contentPadding = PaddingValues(horizontal = Immersive.Gutter),+ horizontalArrangement = Arrangement.spacedBy(14.dp),+ userScrollEnabled = false,+ ) {+ items(3) { card ->+ Column(Modifier.width(cardWidth)) {+ ImmersiveShimmerBox(+ modifier = Modifier.width(cardWidth).aspectRatio(1f),+ shape = cardShape,+ )+ Spacer(Modifier.height(12.dp))+ SkeletonLine(fraction = TitleWidths[card % TitleWidths.size], height = 13.dp)+ Spacer(Modifier.height(6.dp))+ SkeletonLine(fraction = SubtitleWidths[card % SubtitleWidths.size], height = 11.dp)+ }+ }+ }+ }+}++/** Home while the first page of shelves is still loading. */+fun LazyListScope.immersiveFeedSkeleton(shelves: Int = 3, firstIsHero: Boolean = true) {+ if (firstIsHero) {+ item(key = "skeleton:hero") { ImmersiveHeroShelfSkeleton() }+ items(shelves - 1, key = { "skeleton:shelf:$it" }) { index ->+ ImmersiveShelfSkeleton(index = index + 1)+ }+ } else {+ items(shelves, key = { "skeleton:shelf:$it" }) { index ->+ ImmersiveShelfSkeleton(index = index)+ }+ }+}++/** The signed-in library: saved collections, then a run of rows. */+fun LazyListScope.immersiveLibrarySkeleton() {+ item(key = "skeleton:library:shelf") { ImmersiveShelfSkeleton() }+ item(key = "skeleton:library:header") { ImmersiveSectionHeaderSkeleton(index = 1) }+ immersiveSongListSkeleton(count = 7, keyPrefix = "skeleton:library:song")+}++/** The Play / Shuffle pair, which only appears once there is something to play. */+@Composable+fun ImmersivePlayShuffleSkeleton(modifier: Modifier = Modifier) {+ Row(+ modifier = modifier+ .fillMaxWidth()+ // Matches the real pair's inset, height and corner, so the header above them does not+ // shift when the track list lands.+ .padding(horizontal = Immersive.Gutter),+ horizontalArrangement = Arrangement.spacedBy(10.dp),+ ) {+ ImmersiveShimmerBox(Modifier.weight(1f).height(ImmersiveActionButtonHeight), Immersive.Button)+ ImmersiveShimmerBox(Modifier.weight(1f).height(ImmersiveActionButtonHeight), Immersive.Button)+ }+}++/**+ * An album, playlist or artist page below its header — the header itself is drawn from what the+ * row that was tapped already knew, so it never waits.+ */+fun LazyListScope.immersiveDetailSkeleton(isArtist: Boolean) {+ item(key = "skeleton:detail:actions") {+ Column(Modifier.graphicsLayer { alpha = 0.4f }) {+ ImmersivePlayShuffleSkeleton()+ Spacer(Modifier.height(if (isArtist) 22.dp else 20.dp))+ }+ }+ if (isArtist) {+ item(key = "skeleton:detail:top") {+ Column(Modifier.graphicsLayer { alpha = 0.4f }) {+ ImmersiveSectionHeaderSkeleton()+ repeat(4) { index -> ImmersiveSongRowSkeleton(index) }+ }+ }+ item(key = "skeleton:detail:sections") {+ Box(Modifier.graphicsLayer { alpha = 0.4f }) {+ ImmersiveShelfSkeleton(index = 2)+ }+ }+ } else {+ immersiveSongListSkeleton(count = 8, keyPrefix = "skeleton:detail:song", alpha = 0.4f)+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/components/ImmersiveSongText.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/components/ImmersiveSongText.ktnew file mode 100644index 00000000..01cdd64f--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/components/ImmersiveSongText.kt@@ -0,0 +1,94 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * sharedUi/src/jvmSharedMain/kotlin/com/music/bitchord/ui/components/SongText.kt at edc1e6f. Modified for Myspoti, 2026-10.+ */+package com.music.spotui.ui.immersive.components++import androidx.compose.foundation.Canvas+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+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.geometry.CornerRadius+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.graphics.BlendMode+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.CompositingStrategy+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.text.TextStyle+import androidx.compose.ui.text.drawText+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.rememberTextMeasurer+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.DpSize+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import com.music.spotui.ui.immersive.Immersive++/**+ * A song title with the catalogue-standard explicit badge in front of it. Give it a width (it+ * fills the row it is in): `ImmersiveSongTitle(song.title, song.explicit, Immersive.Body, color)`.+ */+@Composable+fun ImmersiveSongTitle(+ title: String,+ explicit: Boolean,+ style: TextStyle,+ color: Color,+ modifier: Modifier = Modifier,+) {+ Row(modifier = modifier, verticalAlignment = Alignment.CenterVertically) {+ if (explicit) {+ ImmersiveExplicitBadge(color)+ Spacer(Modifier.width(6.dp))+ }+ Text(+ text = title,+ style = style,+ color = color,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ modifier = Modifier.weight(1f),+ )+ }+}++/**+ * The explicit mark: a filled tile with the E cut out of it, so whatever sits behind — a list+ * row, the player's artwork — shows through the letter. The cut-out is a real hole rather than+ * the letter painted in a background colour, which is why it draws into its own offscreen layer:+ * DstOut can then only erase the tile, never what is under it.+ */+@Composable+fun ImmersiveExplicitBadge(color: Color, modifier: Modifier = Modifier) {+ val measurer = rememberTextMeasurer()+ val style = remember {+ Immersive.Caption.copy(fontSize = 10.sp, lineHeight = 12.sp, fontWeight = FontWeight.Bold)+ }+ val letter = remember(measurer, style) { measurer.measure("E", style) }+ // The letter's line box plus 3dp a side.+ val size = with(LocalDensity.current) {+ DpSize(letter.size.width.toDp() + 6.dp, letter.size.height.toDp())+ }+ Canvas(+ modifier+ .size(size)+ .graphicsLayer { compositingStrategy = CompositingStrategy.Offscreen },+ ) {+ drawRoundRect(color = color, cornerRadius = CornerRadius(2.dp.toPx()))+ drawText(+ textLayoutResult = letter,+ topLeft = Offset(+ (this.size.width - letter.size.width) / 2f,+ (this.size.height - letter.size.height) / 2f,+ ),+ blendMode = BlendMode.DstOut,+ )+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/lyrics/ImmersiveListEdges.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/lyrics/ImmersiveListEdges.ktnew file mode 100644index 00000000..c98fe637--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/lyrics/ImmersiveListEdges.kt@@ -0,0 +1,62 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * sharedUi/src/jvmSharedMain/kotlin/com/music/bitchord/ui/player/PlayerQueue.kt at edc1e6f.+ * Modified for Myspoti, 2026-10.+ */+package com.music.spotui.ui.immersive.lyrics++import androidx.compose.foundation.lazy.LazyListState+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.drawWithContent+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.graphics.BlendMode+import androidx.compose.ui.graphics.Brush+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.CompositingStrategy+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.input.nestedscroll.NestedScrollConnection+import androidx.compose.ui.input.nestedscroll.NestedScrollSource+import androidx.compose.ui.unit.Velocity+import androidx.compose.ui.unit.dp++/**+ * Swallows whatever scroll the list itself didn't use, so a sheet or pager around it never+ * reads the leftover as a drag on itself. A downward fling has to be caught before they see+ * it, but only at the top of the list: otherwise the list could never fling.+ */+internal fun keepScrollInList(listState: LazyListState) = object : NestedScrollConnection {+ override fun onPostScroll(+ consumed: Offset,+ available: Offset,+ source: NestedScrollSource,+ ): Offset = available++ override suspend fun onPreFling(available: Velocity): Velocity =+ if (available.y > 0f && !listState.canScrollBackward) available else Velocity.Zero++ override suspend fun onPostFling(consumed: Velocity, available: Velocity): Velocity = available+}++/** Softens the list where it meets the header and the controls. */+internal fun Modifier.fadingEdges(): Modifier = this+ .graphicsLayer(compositingStrategy = CompositingStrategy.Offscreen)+ .drawWithContent {+ drawContent()+ val fade = 28.dp.toPx()+ drawRect(+ brush = Brush.verticalGradient(+ colors = listOf(Color.Transparent, Color.Black),+ startY = 0f,+ endY = fade,+ ),+ blendMode = BlendMode.DstIn,+ )+ drawRect(+ brush = Brush.verticalGradient(+ colors = listOf(Color.Black, Color.Transparent),+ startY = size.height - fade,+ endY = size.height,+ ),+ blendMode = BlendMode.DstIn,+ )+ }diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/lyrics/ImmersiveLyricClock.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/lyrics/ImmersiveLyricClock.ktnew file mode 100644index 00000000..64ed74a6--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/lyrics/ImmersiveLyricClock.kt@@ -0,0 +1,115 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * sharedUi/src/jvmSharedMain/kotlin/com/music/bitchord/ui/player/PlayerLyrics.kt at edc1e6f.+ * Modified for Myspoti, 2026-10.+ *+ * Changes: BitChord's LyricPlayhead / rememberLyricClock, fed by SongPlayer.getCurrentPosition()+ * (already extrapolated, read once per frame) instead of a twice-a-second stamped reading. A+ * seek is recognised from the position jumping, or announced by a tap on a line.+ */+package com.music.spotui.ui.immersive.lyrics++import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.MutableLongState+import androidx.compose.runtime.mutableLongStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.withFrameNanos+import androidx.lifecycle.Lifecycle+import androidx.lifecycle.compose.LocalLifecycleOwner+import androidx.lifecycle.repeatOnLifecycle+import com.music.spotui.di.SongPlayer+import com.music.spotui.ui.look.LyricClock+import kotlinx.coroutines.delay+import kotlinx.coroutines.isActive+import kotlin.math.abs++/**+ * The lyric playhead of one track: [clock] is the song position in milliseconds, ticking on+ * every frame while playing (read it in draw lambdas, never in composition), steered by the+ * player's own position through a [LyricClock].+ */+internal class LyricsPlayhead(startMs: Long) {+ val clock: MutableLongState = mutableLongStateOf(startMs)+ internal val engine = LyricClock(startMs)++ /** Changes whenever the lyrics are meant to jump: a seek, or a tap on a line. */+ var discontinuity: Long = 0L+ private set++ /** The panel is about to seek: the next reading is where the song landed, not a bad one. */+ fun announceJump() {+ discontinuity+++ }++ internal var lastReadMs = startMs+ internal var lastReadAtMs = Double.NaN+}++private fun nanosToMs(nanos: Long): Double = nanos / 1_000_000.0++/** A frame time this close to [System.nanoTime] is on the same clock. */+private const val SAME_CLOCK_NANOS = 250_000_000L++/** A reading this far from where the last one carried on to is a seek, not playback. */+private const val SEEK_JUMP_MS = 800L++/** How often the position is looked at while paused, for a seek made from elsewhere. */+private const val PAUSED_POLL_MS = 120L++private fun playerPosition(): Long = SongPlayer.getCurrentPosition().coerceAtLeast(0L)++/**+ * The song position, ticking every frame while [playing].+ *+ * Gated on the app being on screen: the loop asks for a frame, writes a value that+ * invalidates a drawing and is handed the next one, which is a request to render continuously+ * for as long as it runs. Every start is a fresh run from the latest reading, so neither a+ * pause nor a spell in the background is mistaken for one very long frame.+ */+@Composable+internal fun rememberLyricsPlayhead(trackKey: Any, playing: Boolean): LyricsPlayhead {+ val head = remember(trackKey) { LyricsPlayhead(playerPosition()) }+ val lifecycle = LocalLifecycleOwner.current.lifecycle+ LaunchedEffect(head, playing, lifecycle) {+ lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {+ if (!playing) {+ // Not moving: each reading is the truth, including a seek made while paused.+ while (isActive) {+ val position = playerPosition()+ head.engine.hold(position, nanosToMs(System.nanoTime()))+ head.clock.longValue = position+ head.lastReadMs = position+ head.lastReadAtMs = Double.NaN+ delay(PAUSED_POLL_MS)+ }+ } else {+ head.engine.restart()+ head.lastReadAtMs = Double.NaN+ while (isActive) {+ withFrameNanos { frameNanos ->+ // Frame time is preferred for being evenly spaced where it is on the+ // System.nanoTime clock; anywhere it is not, the real clock is used.+ val system = System.nanoTime()+ val now = nanosToMs(if (abs(system - frameNanos) < SAME_CLOCK_NANOS) frameNanos else system)+ val position = playerPosition()+ if (!head.lastReadAtMs.isNaN() &&+ abs(position - (head.lastReadMs + (now - head.lastReadAtMs))) > SEEK_JUMP_MS+ ) {+ head.announceJump()+ }+ head.lastReadMs = position+ head.lastReadAtMs = now+ head.clock.longValue = head.engine.frame(+ nowMs = now,+ reportedMs = position,+ sampledAtMs = Double.NaN,+ discontinuity = head.discontinuity,+ )+ }+ }+ }+ }+ }+ return head+}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.ktnew file mode 100644index 00000000..9f99dc59--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/lyrics/ImmersiveLyricsPanel.kt@@ -0,0 +1,783 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * sharedUi/src/jvmSharedMain/kotlin/com/music/bitchord/ui/player/PlayerLyrics.kt at edc1e6f.+ * Modified for Myspoti, 2026-10.+ *+ * Changes: LyricsPanel's list, PanelVoice, the gap dots, the loading skeleton and the+ * scroll lead / stagger, fed by Myspoti's LyricsViewModel. Myspoti's lyrics are mostly+ * line-synced, so a line lights whole (BitChord's line-level path) and the word sweep runs+ * only where a line has words. Translation, romanization, particles, duets, backing vocals,+ * line picking and the player-controls hand-off are left out for now.+ */+package com.music.spotui.ui.immersive.lyrics++import android.os.Build+import androidx.compose.animation.animateColorAsState+import androidx.compose.animation.core.LinearEasing+import androidx.compose.animation.core.animate+import androidx.compose.animation.core.animateFloat+import androidx.compose.animation.core.animateDpAsState+import androidx.compose.animation.core.animateFloatAsState+import androidx.compose.animation.core.infiniteRepeatable+import androidx.compose.animation.core.rememberInfiniteTransition+import androidx.compose.animation.core.tween+import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.gestures.animateScrollBy+import androidx.compose.foundation.interaction.DragInteraction+import androidx.compose.foundation.interaction.MutableInteractionSource+import androidx.compose.foundation.interaction.collectIsPressedAsState+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxWithConstraints+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.calculateEndPadding+import androidx.compose.foundation.layout.calculateStartPadding+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.itemsIndexed+import androidx.compose.foundation.lazy.rememberLazyListState+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.CompositionLocalProvider+import androidx.compose.runtime.FloatState+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.MutableLongState+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.derivedStateOf+import androidx.compose.runtime.getValue+import androidx.compose.runtime.key+import androidx.compose.runtime.mutableFloatStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberUpdatedState+import androidx.compose.runtime.setValue+import androidx.compose.runtime.snapshotFlow+import androidx.compose.runtime.structuralEqualityPolicy+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.BlurredEdgeTreatment+import androidx.compose.ui.draw.blur+import androidx.compose.ui.draw.clip+import androidx.compose.ui.draw.clipToBounds+import androidx.compose.ui.draw.drawBehind+import androidx.compose.ui.draw.drawWithCache+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.graphics.Brush+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.TransformOrigin+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.input.nestedscroll.nestedScroll+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.semantics.contentDescription+import androidx.compose.ui.semantics.semantics+import androidx.compose.ui.text.TextLayoutResult+import androidx.compose.ui.text.TextStyle+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.text.style.TextDirection+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.LayoutDirection+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import androidx.compose.ui.platform.LocalLayoutDirection+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import androidx.lifecycle.viewmodel.compose.viewModel+import app.myspoti.engine.R+import com.music.spotui.data.entity.Lyrics+import com.music.spotui.di.Graph+import com.music.spotui.di.SongPlayer+import com.music.spotui.ui.immersive.Immersive+import com.music.spotui.ui.look.GLOW_ALPHA+import com.music.spotui.ui.look.GLOW_ROOM+import com.music.spotui.ui.look.INACTIVE_SCALE+import com.music.spotui.ui.look.LINE_FALLOFF_ALPHA+import com.music.spotui.ui.look.LINE_FALLOFF_BLUR+import com.music.spotui.ui.look.LYRIC_EASING+import com.music.spotui.ui.look.LYRIC_SETTLE_MS+import com.music.spotui.ui.look.SweptLine+import com.music.spotui.ui.look.SweptLyricLine+import com.music.spotui.ui.look.UNSUNG_ALPHA+import com.music.spotui.ui.look.rememberReduceMotion+import com.music.spotui.ui.look.toSwept+import com.music.spotui.ui.viewmodel.LyricsViewModel+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.first+import kotlin.math.abs++/**+ * The lyrics of the playing track, inside the player: big tight type, the playing line crisp+ * and everything else falling out of focus the further it is from it. Blur needs API 31+, so+ * alpha carries the same hierarchy on older devices.+ *+ * Scrolling by hand clears the blur and suspends the auto-follow, so you can read ahead; a+ * moment after you stop it snaps back to the song. Tapping a line seeks to it.+ *+ * The list brings its own side gutter and top margin; [contentPadding] is the extra room the+ * list keeps clear of whatever the player draws over it.+ */+@Composable+fun ImmersiveLyricsPanel(modifier: Modifier = Modifier, contentPadding: PaddingValues = PaddingValues()) {+ val vm: LyricsViewModel = viewModel()+ val song = Graph.currentSongState+ val title = song.title.value+ val artist = song.singer.value+ LaunchedEffect(title, artist, SongPlayer.currentTrackId) {+ SongPlayer.currentLyricsTrack()?.let(vm::load)+ }+ val state by vm.state.collectAsState()+ val trackKey = "${SongPlayer.currentTrackId}|$title|$artist"++ when (val current = state) {+ is LyricsViewModel.State.Loading -> LyricsSkeleton(+ modifier.padding(contentPadding).padding(horizontal = Immersive.Gutter),+ )+ is LyricsViewModel.State.NotFound -> Box(+ modifier.padding(contentPadding).padding(horizontal = Immersive.Gutter),+ contentAlignment = Alignment.Center,+ ) {+ Text(+ text = stringResource(R.string.immersive_lyrics_none),+ style = Immersive.Headline,+ color = Immersive.TextSecondary,+ )+ }+ is LyricsViewModel.State.Loaded -> {+ // A new track, or new lyrics for it, starts the list over: its scroll position and+ // handover state belong to the lines they were made for.+ key(trackKey, System.identityHashCode(current.lyrics)) {+ LyricsList(current.lyrics, trackKey, modifier, contentPadding)+ }+ }+ }+}++// ─── Rows ────────────────────────────────────────────────────────────────────────────────++/**+ * One row of the panel: a line of the song, or the break counted out between two of them.+ * [swept] carries the word timings where the source has them.+ */+private class PanelLine(+ val timeMs: Long,+ val text: String,+ val isGap: Boolean,+ /** Where a break ends; unused for a sung line. */+ val untilMs: Long,+ val swept: SweptLine,+) {+ val isWordSynced: Boolean get() = !isGap && swept.isWordSynced++ /** When the line stops being sung, as far as the source says. */+ val endMs: Long get() = if (isGap) untilMs else swept.endMs+}++private fun isGapText(text: String): Boolean = text.isBlank() || text.trim() == "♪"++/** Breaks shorter than this before the first line are not worth counting out. */+private const val INTRO_GAP_MIN_MS = 3_000L++/** How long a break at the very end is counted over. */+private const val TRAILING_GAP_MS = 5_000L++private fun panelLines(lyrics: Lyrics, synced: Boolean): List<PanelLine> {+ val source = lyrics.lines+ val out = ArrayList<PanelLine>(source.size + 1)+ if (synced) {+ // An intro: the panel counts it out rather than sitting on nothing.+ val firstSung = source.firstOrNull { !isGapText(it.text) }+ if (firstSung != null && firstSung.timeMs >= INTRO_GAP_MIN_MS && source.first().timeMs > 0L) {+ out += PanelLine(0L, "", true, firstSung.timeMs, SweptLine(0L, ""))+ }+ }+ source.forEachIndexed { index, line ->+ val next = source.getOrNull(index + 1)?.timeMs+ if (synced && isGapText(line.text)) {+ out += PanelLine(line.timeMs, "", true, next ?: (line.timeMs + TRAILING_GAP_MS), SweptLine(line.timeMs, ""))+ } else {+ out += PanelLine(line.timeMs, line.text, false, 0L, line.toSwept(next))+ }+ }+ return out+}++// ─── Constants (BitChord's, at its sizes) ───────────────────────────────────────────────++/** How tall a break stands while it is playing; nothing when it is not. */+private val GAP_ROW_HEIGHT = 40.dp+private val GAP_ROW_SPACING = 16.dp++/** What a line reads at while the list is being scrolled by hand. */+private const val BROWSING_ALPHA = 0.8f++/** A line under a finger dips, the way a button does. */+private const val PRESSED_SCALE = 0.96f++/** The break between verses, counted out rather than marked. */+private const val GAP_DOTS = 3+private val GAP_DOT_SIZE = 13.dp+private val GAP_DOT_GAP = 5.dp+private const val GAP_DOT_REST = 0.25f+private const val GAP_REST_SCALE = 0.76f+private const val GAP_RUNNING = -1f++/** How long the panel takes to settle on a new line, and how far ahead it starts. */+private const val SCROLL_LEAD_MIN_MS = 350L+private const val SCROLL_LEAD_MAX_MS = 500L++/**+ * How the rows fan out as the panel moves between lines: each row after the one being+ * scrolled to sets off slightly later than the row before it, up to a few rows back.+ */+private const val STAGGER_STEPS = 3+private const val STAGGER_FRACTION = 0.06f++/** One handover: how far the panel is going, and how long it is taking. */+private class ScrollRun(val id: Int, val delta: Float, val durationMs: Int) {+ /** The last row to arrive does so this long after the panel sets off. */+ val spanMs: Float get() = durationMs * (1f + STAGGER_FRACTION * STAGGER_STEPS)+}++/**+ * How long before a line lands the panel starts moving to it — and how long the move then+ * takes, which is the same number: the silence between the last word of the line being sung+ * and the first of the next, bounded either side.+ */+private fun scrollLead(rows: List<PanelLine>, positionMs: Long): Long {+ val current = rows.indexOfLast { it.timeMs <= positionMs }+ if (current < 0) return SCROLL_LEAD_MIN_MS+ val next = rows.getOrNull(current + 1) ?: return SCROLL_LEAD_MIN_MS+ val gap = next.timeMs - rows[current].endMs+ return gap.coerceIn(SCROLL_LEAD_MIN_MS, SCROLL_LEAD_MAX_MS)+}++/** The row being sung at [positionMs], or -1 before the first one. */+private fun activeRow(rows: List<PanelLine>, positionMs: Long): Int =+ rows.indexOfLast { it.timeMs <= positionMs }++// ─── The list ────────────────────────────────────────────────────────────────────────────++@Composable+private fun LyricsList(+ lyrics: Lyrics,+ trackKey: String,+ modifier: Modifier,+ contentPadding: PaddingValues,+) {+ val isSynced = remember(lyrics) { lyrics.synced && lyrics.lines.any { it.timeMs > 0L } }+ val rows = remember(lyrics, isSynced) { panelLines(lyrics, isSynced) }+ val playing = Graph.currentSongState.playingState.value+ val head = rememberLyricsPlayhead(trackKey, playing && isSynced)+ val clock = head.clock++ val activeRow by remember(rows, isSynced) {+ derivedStateOf { if (!isSynced) -1 else activeRow(rows, clock.longValue) }+ }+ // Where the panel is heading, which is a beat ahead of where the singing is. Movement that+ // starts on the downbeat arrives after it; started during the run-up, the words are under+ // your eye when they land. Kept apart from [activeRow] on purpose: this leads, and the+ // brightness and the sweep must not.+ val leadLine by remember(rows, isSynced) {+ derivedStateOf {+ if (!isSynced) {+ -1+ } else {+ val now = clock.longValue+ activeRow(rows, now + scrollLead(rows, now))+ }+ }+ }+ // What the stack arranges itself around. The outgoing line starts dimming as the panel+ // leaves it rather than when its last word ends, so the dim, the blur and the movement+ // are one gesture.+ val focusLine = if (leadLine >= 0) leadLine else activeRow++ val listState = rememberLazyListState()+ // LayoutInfo changes on every scroll frame. Observe only height here so the entire lyrics+ // list is not recomposed for every scrolling pixel.+ val viewportHeight by remember(listState) {+ derivedStateOf { listState.layoutInfo.viewportSize.height }+ }+ val keepScroll = remember(listState) { keepScrollInList(listState) }+ var browsing by remember { mutableStateOf(false) }++ val reduceMotion = rememberReduceMotion()+ val blurOk = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && !reduceMotion++ LaunchedEffect(listState) {+ listState.interactionSource.interactions.collect { interaction ->+ // Suspends the panel's own following, and nothing more.+ if (interaction is DragInteraction.Start) browsing = true+ }+ }++ val currentLine by rememberUpdatedState(focusLine)+ val activeOnScreen by remember(listState) {+ derivedStateOf { listState.layoutInfo.visibleItemsInfo.any { it.index == currentLine } }+ }+ // Paused, there is no song to follow back to, so a hand scroll should sit wherever it was+ // left rather than snapping back on these timers.+ LaunchedEffect(browsing, activeOnScreen, listState.isScrollInProgress, playing) {+ if (playing && browsing && activeOnScreen && !listState.isScrollInProgress) {+ delay(600)+ browsing = false+ }+ }+ LaunchedEffect(browsing, listState.isScrollInProgress, playing) {+ if (playing && browsing && !listState.isScrollInProgress) {+ delay(5_000)+ browsing = false+ }+ }++ // The panel's own journey, published so each row can work out how far behind it should be+ // running. Held as a plain value plus a frame clock rather than an animation per row:+ // sixty rows each with their own Animatable is sixty animations to start and stop on every+ // handover.+ var run by remember { mutableStateOf(ScrollRun(0, 0f, LYRIC_SETTLE_MS)) }+ val since = remember { mutableFloatStateOf(0f) }+ LaunchedEffect(run.id) {+ if (run.id == 0) return@LaunchedEffect+ animate(+ initialValue = 0f,+ targetValue = run.spanMs,+ animationSpec = tween(run.spanMs.toInt(), easing = LinearEasing),+ ) { value, _ -> since.floatValue = value }+ }+ var placed by remember { mutableStateOf(false) }+ // A newer line replaces an unfinished automatic scroll. Only a user's browsing gesture+ // should suspend following, not our own animation.+ LaunchedEffect(focusLine, browsing) {+ if (isSynced && !browsing && focusLine >= 0 && focusLine in rows.indices) {+ snapshotFlow { listState.layoutInfo.viewportSize.height }.first { it > 0 }+ val visible = listState.layoutInfo.visibleItemsInfo.firstOrNull { it.index == focusLine }+ when {+ !placed -> {+ listState.scrollToItem(focusLine, scrollOffset = 0)+ placed = true+ }+ // Already on screen, which is the ordinary case of handing over to the next+ // line: its distance is known, so the move can be given the run-up's own+ // duration and curve instead of the list's default spring.+ visible != null -> {+ val span = scrollLead(rows, clock.longValue).toInt()+ run = ScrollRun(run.id + 1, visible.offset.toFloat(), span)+ listState.animateScrollBy(+ value = visible.offset.toFloat(),+ animationSpec = tween(durationMillis = span, easing = LYRIC_EASING),+ )+ }+ // Somewhere off screen — after a seek, or a long instrumental scrolled past.+ else -> listState.animateScrollToItem(focusLine, scrollOffset = 0)+ }+ }+ }++ val layoutDirection = LocalLayoutDirection.current+ val density = LocalDensity.current+ LazyColumn(+ state = listState,+ modifier = modifier+ .nestedScroll(keepScroll)+ .fadingEdges(),+ // Each row carries GLOW_ROOM of its own inset for the halo, so the list hands that+ // much back — otherwise the lines would sit a glow's width further apart and further in.+ contentPadding = PaddingValues(+ start = (Immersive.Gutter + contentPadding.calculateStartPadding(layoutDirection) - GLOW_ROOM)+ .coerceAtLeast(0.dp),+ top = contentPadding.calculateTopPadding() + 40.dp - GLOW_ROOM,+ end = (Immersive.Gutter + contentPadding.calculateEndPadding(layoutDirection) - GLOW_ROOM)+ .coerceAtLeast(0.dp),+ bottom = contentPadding.calculateBottomPadding() ++ if (isSynced) with(density) { viewportHeight.toDp() } * 0.8f else 40.dp,+ ),+ verticalArrangement = Arrangement.spacedBy(0.dp),+ ) {+ itemsIndexed(rows) { index, row ->+ PanelRow(+ index = index,+ row = row,+ synced = isSynced,+ activeRow = activeRow,+ focusLine = focusLine,+ run = run,+ since = since,+ browsing = browsing,+ blurOk = blurOk,+ glowing = blurOk,+ clock = clock,+ onSeek = { timeMs ->+ head.announceJump()+ SongPlayer.seekTo(timeMs)+ SongPlayer.play()+ },+ )+ }+ }+}++private const val BLUR_SWITCH_MS = 200++@Composable+private fun PanelRow(+ index: Int,+ row: PanelLine,+ synced: Boolean,+ activeRow: Int,+ focusLine: Int,+ run: ScrollRun,+ since: FloatState,+ browsing: Boolean,+ blurOk: Boolean,+ glowing: Boolean,+ clock: MutableLongState,+ onSeek: (Long) -> Unit,+) {+ if (!synced && row.isGap) {+ Spacer(Modifier.height(14.dp))+ return+ }++ // Off the line being sung, not off the line the panel is heading for. Brightness is what+ // says "these are the words right now", so it cannot run ahead of them.+ val offset = if (activeRow < 0) 0 else index - activeRow+ val isActive = synced && index == activeRow+ // Symmetric either side of the playing line, and shallow: the two rows around it stay+ // readable, and everything past that recedes to the same floor rather than fading to nothing.+ val step = abs(offset).coerceAtMost(LINE_FALLOFF_ALPHA.lastIndex)+ // Blur follows the line switch (focusLine), not the first word's start: the new line+ // clears and the old one blurs back in the same short tween. Reduce motion drops blur.+ val focusStep = (if (focusLine < 0) 0 else abs(index - focusLine))+ .coerceAtMost(LINE_FALLOFF_BLUR.lastIndex)+ val blur by animateDpAsState(+ targetValue = when {+ !synced || !blurOk || browsing || (focusLine >= 0 && index == focusLine) -> 0.dp+ else -> LINE_FALLOFF_BLUR[focusStep]+ },+ animationSpec = tween(BLUR_SWITCH_MS, easing = LYRIC_EASING),+ label = "lyricBlur",+ )+ val lineAlpha by animateFloatAsState(+ targetValue = when {+ !synced -> 0.95f+ isActive -> 1f+ // Reading by hand is not following along: the stack flattens to one brightness.+ browsing -> BROWSING_ALPHA+ else -> LINE_FALLOFF_ALPHA[step]+ },+ animationSpec = tween(LYRIC_SETTLE_MS, easing = LYRIC_EASING),+ label = "lyricAlpha",+ )++ if (row.isGap) {+ GapRow(row, clock, isActive, blur, lineAlpha, onSeek)+ return+ }++ val style = if (synced) {+ Immersive.Lyric+ } else {+ Immersive.Lyric.copy(fontSize = 26.sp, lineHeight = 33.sp)+ }+ // The stack sits fractionally back and the playing line comes forward to meet you. Rows+ // behind the one being scrolled to are the ones that fan out; the ones it is moving away+ // from arrive together.+ val sung = offset < 0+ val behind = if (run.delta >= 0f) index - focusLine else focusLine - index+ val staggerDelay = behind.coerceIn(0, STAGGER_STEPS) * STAGGER_FRACTION * run.durationMs+ val interaction = remember { MutableInteractionSource() }+ val pressed by interaction.collectIsPressedAsState()+ val scale by animateFloatAsState(+ targetValue = when {+ pressed -> PRESSED_SCALE+ isActive || !synced -> 1f+ else -> INACTIVE_SCALE+ },+ animationSpec = tween(+ durationMillis = if (pressed) 120 else LYRIC_SETTLE_MS,+ easing = LYRIC_EASING,+ ),+ label = "lyricScale",+ )+ // The bloom on the line being sung fades in and out with the line rather than switching.+ val glow by animateFloatAsState(+ targetValue = if (isActive && glowing) GLOW_ALPHA else 0f,+ animationSpec = tween(durationMillis = 420),+ label = "lyricGlow",+ )+ val shape = Modifier+ .fillMaxWidth()+ .graphicsLayer {+ scaleX = scale+ scaleY = scale+ // Anchored to the left edge, so the words don't slide sideways under the highlight.+ transformOrigin = TransformOrigin(0f, 0.5f)+ alpha = lineAlpha+ // Held back against the list's own movement: the list has already taken this row+ // part of the way, so giving back what it has not earned yet is what leaves it+ // trailing. Rows with nothing to catch up on never read the clock at all.+ translationY = if (staggerDelay <= 0f) {+ 0f+ } else {+ val elapsed = since.floatValue+ run.delta * (+ LYRIC_EASING.transform((elapsed / run.durationMs).coerceIn(0f, 1f)) -+ LYRIC_EASING.transform(((elapsed - staggerDelay) / run.durationMs).coerceIn(0f, 1f))+ )+ }+ }+ .blur(blur, BlurredEdgeTreatment.Unbounded)+ .clip(RoundedCornerShape(10.dp))+ .clickable(enabled = synced, interactionSource = interaction, indication = null) { onSeek(row.timeMs) }++ CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Ltr) {+ Column(modifier = shape) {+ PanelVoice(+ row = row,+ clock = clock,+ style = voiceStyle(style, row.text),+ isActive = isActive,+ sung = sung,+ synced = synced,+ browsing = browsing,+ glowAlpha = glow,+ room = GLOW_ROOM,+ modifier = Modifier.fillMaxWidth(),+ )+ }+ }+}++private fun isRtl(text: String): Boolean {+ var rtl = 0+ var ltr = 0+ for (ch in text) {+ if (ch.code in 0xFB1D..0xFB4F) return true+ when (Character.getDirectionality(ch)) {+ Character.DIRECTIONALITY_RIGHT_TO_LEFT,+ Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC -> rtl+++ Character.DIRECTIONALITY_LEFT_TO_RIGHT -> ltr+++ }+ }+ return rtl > ltr+}++/** The style with an absolute alignment taken from the line's own text direction. */+private fun voiceStyle(base: TextStyle, text: String): TextStyle {+ val rtl = isRtl(text)+ return base.copy(+ textAlign = if (rtl) TextAlign.Right else TextAlign.Left,+ textDirection = if (rtl) TextDirection.Rtl else TextDirection.Ltr,+ )+}++/**+ * One voice of a row: the whole line lit at once, or swept word by word where the source has+ * word timings.+ */+@Composable+private fun PanelVoice(+ row: PanelLine,+ clock: MutableLongState,+ style: TextStyle,+ isActive: Boolean,+ /** Whether the panel has already left this line behind. */+ sung: Boolean,+ /** Whether the source stamps its lines at all. */+ synced: Boolean,+ browsing: Boolean,+ glowAlpha: Float,+ room: Dp,+ modifier: Modifier = Modifier,+) {+ // The line being sung is white; every other one takes a quieter white. Faded across the+ // handover rather than cut, so a line warms as it is reached and cools as it is left.+ // Lyrics with no timing have no line being sung, and stay white throughout.+ val color by animateColorAsState(+ targetValue = if (isActive || !synced) Color.White else Immersive.TextSecondary.copy(alpha = 0.85f),+ label = "lyricLineColor",+ )+ if (row.isWordSynced && synced) {+ // Every word-synced line goes through the sweep, not just the playing one — a line+ // already sung is fully revealed and one still to come is not, which falls out of the+ // same arithmetic. Animating the tail lets a finished line close up as it dims away.+ val tail by animateFloatAsState(+ targetValue = if (sung) 1f else UNSUNG_ALPHA,+ label = "lyricTail",+ )+ SweptLyricLine(+ line = row.swept,+ clock = clock,+ style = style,+ dimAlpha = tail,+ modifier = modifier,+ // Browsing keeps the sweep but skips the bloom: a playback flourish, not a reading aid.+ glowAlpha = if (browsing) 0f else glowAlpha,+ glowRoom = room,+ feather = isActive,+ color = color,+ )+ } else {+ // No word timings, so there is no sweep to light the words as they are sung: the line+ // lights whole, the moment it starts, and holds itself back at the same dim a swept+ // line's unsung words sit at until then.+ val lit by animateFloatAsState(+ targetValue = if (!synced || sung || isActive) 1f else UNSUNG_ALPHA,+ label = "lyricLit",+ )+ Text(+ text = row.text,+ style = style,+ color = color.copy(alpha = lit),+ modifier = modifier.padding(room),+ )+ }+}++/**+ * A break counts itself out rather than being marked: three dots lighting in turn across the+ * interlude, so a long one reads as time running down. The row itself opens and closes with+ * the break, so the list carries no dead space through the verses either side of it.+ */+@Composable+private fun GapRow(+ row: PanelLine,+ clock: MutableLongState,+ isActive: Boolean,+ blur: Dp,+ lineAlpha: Float,+ onSeek: (Long) -> Unit,+) {+ val until = row.untilMs+ // How far through the break the song is, held at 0 before it and 1 after: the dots read+ // the clock only while it is running, so a break that is not playing never redraws.+ val gapFill = remember(row, until, clock) {+ derivedStateOf(structuralEqualityPolicy()) {+ val now = clock.longValue+ when {+ now <= row.timeMs -> 0f+ now >= until -> 1f+ else -> GAP_RUNNING+ }+ }+ }+ val swell by animateFloatAsState(+ targetValue = if (isActive) 1f else 0f,+ animationSpec = tween(durationMillis = if (isActive) 400 else 350, easing = LYRIC_EASING),+ label = "gapSwell",+ )+ val instrumental = stringResource(R.string.immersive_lyrics_instrumental)+ Box(+ contentAlignment = Alignment.CenterStart,+ modifier = Modifier+ .height((GAP_ROW_HEIGHT + GAP_ROW_SPACING) * swell)+ .clipToBounds(),+ ) {+ Box(+ modifier = Modifier+ .blur(blur, BlurredEdgeTreatment.Unbounded)+ .clip(RoundedCornerShape(10.dp))+ .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {+ onSeek(row.timeMs)+ }+ // Matches the inset every sung line carries, so the rhythm of the list doesn't+ // break at a break.+ .padding(GLOW_ROOM)+ .size(width = GAP_DOT_SIZE * 3 + GAP_DOT_GAP * 2, height = GAP_DOT_SIZE)+ .graphicsLayer {+ val grow = GAP_REST_SCALE + (1f - GAP_REST_SCALE) * swell+ scaleX = grow+ scaleY = grow+ transformOrigin = TransformOrigin(0f, 0.5f)+ alpha = lineAlpha * swell+ }+ .drawBehind {+ val span = (until - row.timeMs).coerceAtLeast(1L)+ val through = gapFill.value.takeUnless { it == GAP_RUNNING }+ ?: ((clock.longValue - row.timeMs).toFloat() / span).coerceIn(0f, 1f)+ val radius = GAP_DOT_SIZE.toPx() / 2f+ val stride = (GAP_DOT_SIZE + GAP_DOT_GAP).toPx()+ repeat(GAP_DOTS) { dot ->+ // Each dot owns its share of the break and fills across it.+ val lit = (through * GAP_DOTS - dot).coerceIn(0f, 1f)+ drawCircle(+ color = Color.White.copy(alpha = GAP_DOT_REST + (1f - GAP_DOT_REST) * lit),+ radius = radius,+ center = Offset(radius + dot * stride, size.height / 2f),+ )+ }+ }+ .semantics { contentDescription = instrumental },+ )+ }+}++// ─── Loading skeleton ────────────────────────────────────────────────────────────────────++/**+ * The shape of the page the lyrics are going to fill: one entry per line of the song, and one+ * number per row that line wraps to. Text is blocks with ragged bottoms.+ */+private val SKELETON_BLOCKS = listOf(+ floatArrayOf(0.97f, 0.54f),+ floatArrayOf(0.92f, 0.99f, 0.41f),+ floatArrayOf(0.68f),+ floatArrayOf(0.95f, 0.73f),+ floatArrayOf(0.89f, 0.96f, 0.37f),+)+private val SKELETON_BAR = 26.dp+private val SKELETON_LEADING = 15.dp+private val SKELETON_BLOCK_GAP = 35.dp+private const val SKELETON_PERIOD_MS = 1_400++@Composable+private fun LyricsSkeleton(modifier: Modifier = Modifier) {+ val sweep = rememberInfiniteTransition(label = "lyricsSkeleton").animateFloat(+ initialValue = 0f,+ targetValue = 1f,+ animationSpec = infiniteRepeatable(tween(SKELETON_PERIOD_MS, easing = LinearEasing)),+ label = "sweep",+ )+ BoxWithConstraints(modifier.padding(top = 40.dp)) {+ // Every bar sweeps against the width of the column rather than its own, so one band+ // crosses the whole page.+ val column = maxWidth+ Column(verticalArrangement = Arrangement.spacedBy(SKELETON_BLOCK_GAP)) {+ SKELETON_BLOCKS.forEach { rows ->+ Column(verticalArrangement = Arrangement.spacedBy(SKELETON_LEADING)) {+ rows.forEach { fraction ->+ Box(+ Modifier+ .fillMaxWidth(fraction)+ .height(SKELETON_BAR)+ .clip(RoundedCornerShape(4.dp))+ // Read in the draw block, not the body: all any bar needs per+ // frame is a fresh gradient.+ .drawWithCache {+ val full = column.toPx()+ val band = full * 0.45f+ val startX = -band + sweep.value * (full + band * 2)+ val brush = Brush.horizontalGradient(+ colors = listOf(+ Color.White.copy(alpha = 0.10f),+ Color.White.copy(alpha = 0.26f),+ Color.White.copy(alpha = 0.10f),+ ),+ startX = startX,+ endX = startX + band,+ )+ onDrawBehind { drawRect(brush) }+ },+ )+ }+ }+ }+ }+ }+}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.ktnew file mode 100644index 00000000..8e72bbe5--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/lyrics/ImmersiveQueuePanel.kt@@ -0,0 +1,397 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * sharedUi/src/jvmSharedMain/kotlin/com/music/bitchord/ui/player/PlayerQueue.kt at edc1e6f.+ * Modified for Myspoti, 2026-10.+ *+ * 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.+ * Drag-to-reorder, history and the autoplay heading are left out for now.+ */+package com.music.spotui.ui.immersive.lyrics++import androidx.compose.animation.core.FastOutSlowInEasing+import androidx.compose.animation.core.tween+import androidx.compose.foundation.ExperimentalFoundationApi+import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.interaction.MutableInteractionSource+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.calculateEndPadding+import androidx.compose.foundation.layout.calculateStartPadding+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.LazyItemScope+import androidx.compose.foundation.lazy.LazyListScope+import androidx.compose.foundation.lazy.rememberLazyListState+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.layout.Column+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.rounded.Close+import androidx.compose.material.icons.rounded.GraphicEq+import androidx.compose.material.icons.rounded.Repeat+import androidx.compose.material.icons.rounded.RepeatOne+import androidx.compose.material.icons.rounded.Shuffle+import androidx.compose.material3.ExperimentalMaterial3Api+import androidx.compose.material3.Icon+import androidx.compose.material3.SwipeToDismissBox+import androidx.compose.material3.SwipeToDismissBoxValue+import androidx.compose.material3.Text+import androidx.compose.material3.rememberSwipeToDismissBoxState+import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.runtime.snapshots.SnapshotStateList+import androidx.compose.runtime.mutableStateListOf+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.vector.ImageVector+import androidx.compose.ui.input.nestedscroll.nestedScroll+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.platform.LocalLayoutDirection+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.IntOffset+import androidx.compose.ui.unit.dp+import app.myspoti.engine.R+import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi+import com.bumptech.glide.integration.compose.GlideImage+import com.music.spotui.data.entity.SongsModel+import com.music.spotui.di.Graph+import com.music.spotui.di.SongPlayer+import com.music.spotui.ui.immersive.Immersive+import com.music.spotui.ui.screens.ExplicitBadge++/**+ * How a queue row moves when the running order changes under it.+ *+ * Placement only — the fades are off deliberately. A row Compose treats as removed or+ * inserted goes on being drawn at the slot it used to hold for as long as it takes to fade,+ * and a queue row's background is transparent: the fading copy and whichever row is sliding+ * through that slot both draw their title and artist into the same few pixels. Without the+ * fades a row that leaves is gone the moment it leaves, so movement is the only thing left+ * to see. Bounded rather than the default spring so a track change settles at once.+ */+private val QUEUE_ROW_MOTION = tween<IntOffset>(durationMillis = 200, easing = FastOutSlowInEasing)++/** Placement-only item motion; see [QUEUE_ROW_MOTION]. */+@OptIn(ExperimentalFoundationApi::class)+private fun LazyItemScope.queueMotion(): Modifier =+ Modifier.animateItem(fadeInSpec = null, fadeOutSpec = null, placementSpec = QUEUE_ROW_MOTION)++/**+ * The queue of the player, inside the player: what is playing, then "Next in queue" and+ * "Next from <context>". Tap a row to play it, swipe it away to remove it; shuffle and repeat+ * are in the header.+ *+ * The list brings its own side gutter; [contentPadding] is the extra room it keeps clear of+ * whatever the player draws over it.+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun ImmersiveQueuePanel(modifier: Modifier = Modifier, contentPadding: PaddingValues = PaddingValues()) {+ DisposableEffect(Unit) {+ SongPlayer.watchQueue(true)+ onDispose { SongPlayer.watchQueue(false) }+ }+ val queue by SongPlayer.engineQueue+ val song = Graph.currentSongState+ val shuffle = song.shuffle.value+ val repeatMode = SongPlayer.repeatMode.value+ val contextName = SongPlayer.nowPlaying.value.contextName++ // Rows swiped away, hidden at once: the queue takes a moment to report the removal.+ val removed = remember { mutableStateListOf<String>() }+ LaunchedEffect(queue) { removed.clear() }+ val queued = queue.queued.dedupedKeys("q").filter { it.first !in removed }+ val nextUp = queue.nextUp.dedupedKeys("n").filter { it.first !in removed }++ val listState = rememberLazyListState()+ val keepScroll = remember(listState) { keepScrollInList(listState) }+ val direction = LocalLayoutDirection.current+ val current = queue.current+ val hasCurrent = song.title.value.isNotBlank() || current != null++ LazyColumn(+ state = listState,+ modifier = modifier+ .nestedScroll(keepScroll)+ .fadingEdges(),+ contentPadding = PaddingValues(+ start = Immersive.Gutter + contentPadding.calculateStartPadding(direction),+ top = contentPadding.calculateTopPadding() + 8.dp,+ end = Immersive.Gutter + contentPadding.calculateEndPadding(direction),+ bottom = contentPadding.calculateBottomPadding() + 24.dp,+ ),+ ) {+ item(key = "header") {+ QueueHeader(+ shuffle = shuffle,+ repeatMode = repeatMode,+ onShuffle = {+ SongPlayer.setShuffle(!shuffle)+ song.shuffle.value = !shuffle+ },+ onRepeat = { SongPlayer.cycleRepeat() },+ )+ }+ if (hasCurrent) {+ item(key = "heading-now") {+ QueueHeading(+ title = stringResource(R.string.immersive_queue_now_playing),+ modifier = Modifier.padding(top = 12.dp, bottom = 6.dp).then(queueMotion()),+ )+ }+ item(key = "now-playing") {+ QueueRow(+ title = song.title.value.ifBlank { current?.title.orEmpty() },+ artist = song.singer.value.ifBlank { current?.singer.orEmpty() },+ cover = song.coverUri.value.ifBlank { current?.coverUri.orEmpty() },+ isCurrent = true,+ explicit = current?.explicit == true,+ onClick = {},+ modifier = queueMotion(),+ )+ }+ }+ if (queued.isNotEmpty()) {+ item(key = "heading-queued") {+ QueueHeading(+ title = stringResource(R.string.next_in_queue),+ modifier = Modifier.padding(top = 16.dp, bottom = 6.dp).then(queueMotion()),+ ) {+ Text(+ text = stringResource(R.string.clear_queue),+ style = Immersive.Subhead,+ color = Immersive.TextSecondary,+ modifier = Modifier+ .clip(CircleShape)+ .clickable { SongPlayer.clearQueue() }+ .padding(horizontal = 8.dp, vertical = 4.dp),+ )+ }+ }+ queueSection(queued, removed)+ }+ if (nextUp.isNotEmpty()) {+ item(key = "heading-next") {+ QueueHeading(+ title = if (contextName.isNotBlank()) {+ stringResource(R.string.next_from, contextName)+ } else {+ stringResource(R.string.next_up)+ },+ modifier = Modifier.padding(top = 16.dp, bottom = 6.dp).then(queueMotion()),+ )+ }+ queueSection(nextUp, removed)+ }+ if (!hasCurrent && queued.isEmpty() && nextUp.isEmpty()) {+ item(key = "empty") {+ Text(+ text = stringResource(R.string.immersive_queue_empty),+ style = Immersive.Body,+ color = Immersive.TextSecondary,+ modifier = Modifier.padding(top = 32.dp),+ )+ }+ }+ }+}++/** 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 section's rows, each swiped away to remove it. */+@OptIn(ExperimentalMaterial3Api::class)+private fun LazyListScope.queueSection(+ rows: List<Pair<String, SongPlayer.QueueItem>>,+ removed: SnapshotStateList<String>,+) {+ items(rows.size, key = { rows[it].first }) { index ->+ val (key, item) = rows[index]+ val dismiss = rememberSwipeToDismissBoxState(confirmValueChange = { value ->+ if (value == SwipeToDismissBoxValue.EndToStart) {+ removed += key+ SongPlayer.removeFromQueue(item)+ true+ } else {+ false+ }+ })+ SwipeToDismissBox(+ state = dismiss,+ enableDismissFromStartToEnd = false,+ modifier = queueMotion(),+ 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),+ )+ }+ },+ ) {+ QueueRow(+ title = item.song.title,+ artist = item.song.singer,+ cover = item.song.coverUri,+ isCurrent = false,+ explicit = item.song.explicit,+ onClick = { SongPlayer.skipTo(item) },+ )+ }+ }+}++@Composable+private fun QueueHeader(+ shuffle: Boolean,+ repeatMode: Int,+ onShuffle: () -> Unit,+ onRepeat: () -> Unit,+) {+ Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {+ Text(+ text = stringResource(R.string.immersive_queue_title),+ style = Immersive.Title,+ modifier = Modifier.weight(1f),+ )+ QueueToggle(Icons.Rounded.Shuffle, stringResource(R.string.immersive_queue_shuffle), shuffle, onShuffle)+ Spacer(Modifier.width(8.dp))+ QueueToggle(+ if (repeatMode == 2) Icons.Rounded.RepeatOne else Icons.Rounded.Repeat,+ stringResource(R.string.immersive_queue_repeat),+ repeatMode != 0,+ onRepeat,+ )+ }+}++/** A round toggle: lit white when on, a quiet disc when off. */+@Composable+private fun QueueToggle(icon: ImageVector, description: String, on: Boolean, onClick: () -> Unit) {+ Box(+ contentAlignment = Alignment.Center,+ modifier = Modifier+ .size(36.dp)+ .clip(CircleShape)+ .background(if (on) Color.White else Color.White.copy(alpha = 0.14f))+ .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null, onClick = onClick),+ ) {+ Icon(icon, contentDescription = description, tint = if (on) Color.Black else Color.White, modifier = Modifier.size(20.dp))+ }+}++@Composable+private fun QueueHeading(+ title: String,+ modifier: Modifier = Modifier,+ trailing: @Composable () -> Unit = {},+) {+ Row(modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {+ Text(+ text = title,+ style = Immersive.BodyStrong,+ color = Color.White.copy(alpha = 0.75f),+ modifier = Modifier.weight(1f),+ )+ trailing()+ }+}++@OptIn(ExperimentalGlideComposeApi::class)+@Composable+private fun QueueRow(+ title: String,+ artist: String,+ cover: String,+ isCurrent: Boolean,+ explicit: Boolean,+ onClick: () -> Unit,+ modifier: Modifier = Modifier,+) {+ Row(+ modifier = modifier+ .fillMaxWidth()+ .height(Immersive.RowHeight)+ .clip(Immersive.CoverMedium)+ .clickable(+ interactionSource = remember { MutableInteractionSource() },+ indication = null,+ enabled = !isCurrent,+ onClick = onClick,+ ),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ GlideImage(+ model = cover,+ contentDescription = null,+ contentScale = ContentScale.Crop,+ modifier = Modifier+ .size(48.dp)+ .clip(Immersive.CoverSmall)+ .background(Color.White.copy(alpha = 0.08f)),+ )+ Spacer(Modifier.width(12.dp))+ Column(Modifier.weight(1f), verticalArrangement = Arrangement.Center) {+ Text(+ text = title,+ style = Immersive.Body,+ color = if (isCurrent) Immersive.Accent else Immersive.Text,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )+ Row(verticalAlignment = Alignment.CenterVertically) {+ if (explicit) {+ ExplicitBadge()+ Spacer(Modifier.width(6.dp))+ }+ Text(+ text = artist,+ style = Immersive.Subhead,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )+ }+ }+ if (isCurrent) {+ Spacer(Modifier.width(10.dp))+ Icon(+ Icons.Rounded.GraphicEq,+ contentDescription = stringResource(R.string.immersive_queue_now_playing),+ tint = Immersive.Accent,+ modifier = Modifier.size(20.dp),+ )+ }+ }+}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.ktnew file mode 100644index 00000000..110a66a1--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/motion/ImmersiveMotion.kt@@ -0,0 +1,77 @@+package com.music.spotui.ui.immersive.motion++import androidx.compose.animation.AnimatedContentTransitionScope+import androidx.compose.animation.EnterTransition+import androidx.compose.animation.ExitTransition+import androidx.compose.animation.core.Spring+import androidx.compose.animation.core.spring+import androidx.compose.animation.core.tween+import androidx.compose.animation.fadeIn+import androidx.compose.animation.fadeOut+import androidx.compose.animation.slideInHorizontally+import androidx.compose.animation.slideOutHorizontally+import androidx.compose.foundation.lazy.LazyItemScope+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.IntOffset+import androidx.navigation.NavBackStackEntry+import com.music.spotui.ui.look.rememberReduceMotion++/**+ * The motion constants of the Immersive look in one place, so screens share one feel instead of+ * each picking numbers. The springs are BitChord's (medium-low stiffness for moving things,+ * high for press feedback); pages push like a navigation stack, the old page sliding a third of+ * the way as the new one covers it.+ */+object ImmersiveMotion {+ /** Placement of rows in a list (reorder, insert, filter). */+ fun <T> placementSpring() = spring<T>(stiffness = Spring.StiffnessMediumLow)++ /**+ * 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> =+ if (reduce) androidx.compose.animation.core.snap() else spring(dampingRatio = 0.82f, stiffness = Spring.StiffnessMediumLow)++ /** A page pushed or popped by the nav host. */+ private const val PAGE_MS = 380++ /**+ * Enter/exit specs for `NavHost` in the Immersive look. With "reduce motion" on they are a+ * short fade. Pass them as `enterTransition`, `exitTransition`, `popEnterTransition`,+ * `popExitTransition`.+ */+ 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 } ++ 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))+ }++ fun popEnter(reduce: Boolean): AnimatedContentTransitionScope<NavBackStackEntry>.() -> EnterTransition = {+ if (reduce) fadeIn(tween(150)) 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))+ }+ }+}++/**+ * Items of a lazy list glide to their new place (no cross-fade, the list stays readable), and+ * stay put under "reduce motion". Use on every row of an Immersive list.+ */+@Composable+fun LazyItemScope.immersiveItemPlacement(): Modifier {+ if (rememberReduceMotion()) return Modifier+ return Modifier.animateItem(+ fadeInSpec = null,+ fadeOutSpec = null,+ placementSpec = ImmersiveMotion.placementSpring(),+ )+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveActivityScreens.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveActivityScreens.ktnew file mode 100644index 00000000..40e8e854--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveActivityScreens.kt@@ -0,0 +1,414 @@+package com.music.spotui.ui.immersive.pages++import android.content.Intent+import android.net.Uri+import android.provider.Settings+import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.contract.ActivityResultContracts+import androidx.compose.animation.animateContentSize+import androidx.compose.animation.core.Spring+import androidx.compose.animation.core.spring+import androidx.compose.foundation.Image+import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.aspectRatio+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.lazy.itemsIndexed+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.rounded.Add+import androidx.compose.material.icons.rounded.Check+import androidx.compose.material.icons.rounded.Folder+import androidx.compose.material.icons.rounded.IosShare+import androidx.compose.material.icons.rounded.MoreHoriz+import androidx.compose.material.icons.rounded.Pause+import androidx.compose.material.icons.rounded.PlayArrow+import androidx.compose.material.icons.rounded.Refresh+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.painterResource+import androidx.compose.ui.res.pluralStringResource+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import androidx.lifecycle.Lifecycle+import androidx.lifecycle.compose.LifecycleEventEffect+import androidx.lifecycle.viewmodel.compose.viewModel+import androidx.navigation.NavController+import app.myspoti.api.FriendActivity+import app.myspoti.engine.R+import app.myspoti.host.android.MyspotiRuntime+import com.music.spotui.data.local.LocalMusic+import com.music.spotui.data.local.LocalTrack+import com.music.spotui.di.LocalPlayer+import com.music.spotui.di.SongPlayer+import com.music.spotui.ui.components.EpisodeDownloadButton+import com.music.spotui.ui.components.EpisodeOptionsSheet+import com.music.spotui.ui.components.episodeClock+import com.music.spotui.ui.components.episodeDateLabel+import com.music.spotui.ui.components.episodeMinutes+import com.music.spotui.ui.components.shareEpisode+import com.music.spotui.ui.components.spotifyUri+import com.music.spotui.ui.immersive.Immersive+import com.music.spotui.ui.immersive.components.ImmersiveButton+import com.music.spotui.ui.immersive.components.ImmersiveCircleButton+import com.music.spotui.ui.immersive.components.ImmersiveCover+import com.music.spotui.ui.immersive.components.ImmersiveListRow+import com.music.spotui.ui.immersive.components.ImmersiveMessageState+import com.music.spotui.ui.immersive.components.ImmersivePlayShuffleButtons+import com.music.spotui.ui.immersive.components.ImmersiveSearchField+import com.music.spotui.ui.immersive.components.ImmersiveSongRow+import com.music.spotui.ui.immersive.components.ImmersiveSongRowSkeleton+import com.music.spotui.ui.immersive.components.SectionHeader+import com.music.spotui.ui.immersive.components.immersiveClickable+import com.music.spotui.ui.immersive.components.immersiveSongListSkeleton+import com.music.spotui.ui.immersive.motion.immersiveItemPlacement+import com.music.spotui.ui.immersive.shell.ImmersiveBarAction+import com.music.spotui.ui.navigation.profileRoute+import com.music.spotui.ui.navigation.showRoute+import com.music.spotui.ui.screens.AddLocalToPlaylistSheet+import com.music.spotui.ui.screens.LocalFoldersSheet+import com.music.spotui.ui.viewmodel.EpisodeViewModel+import kotlinx.coroutines.launch++// ---------------------------------------------------------------- Friends++/**+ * Friend activity of the Immersive look: each followed person sharing their listening, with the+ * latest track and where it was played from. Tap the person for their profile, the row to play.+ */+@Composable+fun ImmersiveFriendsScreen(navController: NavController) {+ var attempt by remember { mutableIntStateOf(0) }+ var state by remember { mutableStateOf<Result<List<FriendActivity>>?>(null) }+ LaunchedEffect(attempt) { state = runCatching { MyspotiRuntime.api.users.friendActivity() } }+ val now = remember(state) { System.currentTimeMillis() }+ ImmersivePage(+ title = stringResource(R.string.friends_title),+ onBack = { navController.popBackStack() },+ actions = {+ ImmersiveBarAction(Icons.Rounded.Refresh, stringResource(R.string.friends_refresh), onClick = { state = null; attempt++ })+ },+ ) {+ val s = state+ val friends = s?.getOrNull()+ when {+ s == null -> immersiveSongListSkeleton(count = 6, circular = true)+ friends == null -> item(key = "failed") {+ ImmersiveMessageState(stringResource(R.string.friends_failed), actionLabel = stringResource(R.string.retry_button),+ onAction = { state = null; attempt++ })+ }+ friends.isEmpty() -> item(key = "empty") { ImmersiveMessageState(stringResource(R.string.friends_empty)) }+ else -> items(friends, key = { it.user.uri }) { f ->+ Column(immersiveItemPlacement()) { ImmersiveFriendRow(f, now, navController) }+ }+ }+ }+}++@Composable+private fun ImmersiveFriendRow(f: FriendActivity, now: Long, navController: NavController) {+ val track = f.track+ val openProfile = { navController.navigate(profileRoute(f.user.uri.substringAfterLast(':'), f.user.name)) }+ Row(+ verticalAlignment = Alignment.Top,+ modifier = Modifier.fillMaxWidth()+ .immersiveClickable(onClick = { if (track != null) SongPlayer.playSong(track.uri, contextUri = f.contextUri) else openProfile() }, pressedScale = 0.99f)+ .padding(horizontal = Immersive.Gutter, vertical = 10.dp),+ ) {+ Box(Modifier.clip(CircleShape).clickable(onClick = openProfile)) {+ com.music.spotui.ui.components.ProfileAvatar(url = f.user.imageUrl, name = f.user.name, size = 48.dp)+ }+ Column(Modifier.padding(start = 12.dp).weight(1f)) {+ Row(verticalAlignment = Alignment.CenterVertically) {+ Text(f.user.name, style = Immersive.BodyStrong, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))+ Spacer(Modifier.weight(1f))+ if (f.isNowPlaying(now)) {+ Box(Modifier.size(8.dp).clip(CircleShape).background(Immersive.Accent))+ Spacer(Modifier.width(6.dp))+ Text(stringResource(R.string.friends_now), style = Immersive.Caption.copy(color = Immersive.Accent), maxLines = 1)+ } else if (f.timestampMs > 0) {+ Text(+ android.text.format.DateUtils.getRelativeTimeSpanString(f.timestampMs, now,+ android.text.format.DateUtils.MINUTE_IN_MILLIS, android.text.format.DateUtils.FORMAT_ABBREV_RELATIVE).toString(),+ style = Immersive.Caption, maxLines = 1,+ )+ }+ }+ if (track != null) {+ Text(listOf(track.name, track.artists.joinToString(", ") { it.name }).filter { it.isNotBlank() }.joinToString(" • "),+ style = Immersive.Subhead.copy(color = Immersive.Text), maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(top = 2.dp))+ val where = f.contextName ?: track.album?.name+ if (!where.isNullOrBlank()) Text(where, style = Immersive.Caption, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(top = 2.dp))+ }+ }+ f.trackImageUrl?.let { cover ->+ ImmersiveCover(cover.replaceFirst("http://", "https://"), Modifier.padding(start = 10.dp).size(44.dp), Immersive.CoverSmall)+ }+ }+}++// ---------------------------------------------------------------- Local files++/** "Local Files" of the Immersive look: the device's own audio, played by [LocalPlayer]. */+@Composable+fun ImmersiveLocalFilesScreen(navController: NavController) {+ val context = LocalContext.current+ var granted by remember { mutableStateOf(LocalMusic.hasPermission(context)) }+ var askedOnce by remember { mutableStateOf(false) }+ var tracks by remember { mutableStateOf<List<LocalTrack>?>(null) }+ var find by remember { mutableStateOf("") }+ val launcher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { ok -> granted = ok; askedOnce = true }+ LifecycleEventEffect(Lifecycle.Event.ON_RESUME) { granted = LocalMusic.hasPermission(context) }+ LaunchedEffect(granted) { if (granted) tracks = LocalMusic.tracks(context, refresh = true) }++ val np by SongPlayer.nowPlaying+ val playingLocal = LocalPlayer.active.value+ var adding by remember { mutableStateOf<LocalTrack?>(null) }+ adding?.let { t -> AddLocalToPlaylistSheet(t, onDismiss = { adding = null }) }+ var choosingFolders by remember { mutableStateOf(false) }+ val scope = rememberCoroutineScope()+ if (choosingFolders) LocalFoldersSheet(+ onChanged = { scope.launch { tracks = LocalMusic.tracks(context) } },+ onDismiss = { choosingFolders = false },+ )++ val title = stringResource(R.string.local_files_title)+ val n = tracks?.size ?: 0+ ImmersivePage(+ title = title,+ subtitle = if (granted && tracks != null) pluralStringResource(R.plurals.local_files_count, n, n) else null,+ onBack = { navController.popBackStack() },+ actions = if (granted) {+ { ImmersiveBarAction(Icons.Rounded.Folder, stringResource(R.string.local_folders_button), onClick = { choosingFolders = true }) }+ } else null,+ ) {+ when {+ !granted -> item(key = "permission") {+ LocalEmpty(+ stringResource(R.string.local_files_empty_section_title),+ stringResource(R.string.local_files_empty_section_subtitle),+ stringResource(if (askedOnce) R.string.local_files_empty_section_button_go_to_settings else R.string.local_files_empty_section_dialog_permission_rationale_accept),+ ) {+ if (askedOnce) context.startActivity(Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:${context.packageName}")))+ else launcher.launch(LocalMusic.permission)+ }+ }+ tracks == null -> immersiveSongListSkeleton(count = 8)+ tracks?.isEmpty() == true -> item(key = "none") {+ LocalEmpty(stringResource(R.string.local_files_empty_section_no_files_title), stringResource(R.string.local_files_none_subtitle), null) {}+ }+ else -> {+ item(key = "buttons") {+ ImmersivePlayShuffleButtons(+ onPlay = {+ when {+ playingLocal && SongPlayer.isPlaying() -> SongPlayer.pause()+ playingLocal -> SongPlayer.play()+ else -> tracks?.let { LocalPlayer.play(it, 0) }+ }+ },+ onShuffle = { tracks?.let { if (it.isNotEmpty()) LocalPlayer.play(it, it.indices.random(), shuffle = true) } },+ modifier = Modifier.padding(bottom = 12.dp),+ )+ }+ item(key = "find") {+ ImmersiveSearchField(+ query = find, onQueryChange = { find = it }, onSubmit = {},+ placeholder = stringResource(R.string.local_files_find_hint),+ modifier = Modifier.padding(horizontal = Immersive.Gutter, vertical = 6.dp),+ )+ }+ val shown = tracks.orEmpty().filter { com.music.spotui.ui.components.matchesFind(find, it.title, it.artist, it.album) }+ if (shown.isEmpty() && find.isNotBlank()) item(key = "find-empty") {+ ImmersiveMessageState(stringResource(R.string.assisted_curation_search_empty_view_no_result_title, find.trim()))+ }+ items(shown, key = { it.id }) { t ->+ val current = playingLocal && np.uri == "local:${t.id}"+ Column(immersiveItemPlacement()) {+ ImmersiveListRow(+ title = t.title, subtitle = t.artist.ifBlank { null }, imageUrl = t.artUri.toString(), round = false,+ playing = current,+ // The whole folder plays from this song, even when the list is filtered.+ onClick = { tracks?.let { all -> LocalPlayer.play(all, all.indexOf(t).coerceAtLeast(0)) } },+ onMore = { adding = t },+ )+ }+ }+ }+ }+ }+}++@Composable+private fun LocalEmpty(title: String, subtitle: String, button: String?, onClick: () -> Unit) {+ Column(+ horizontalAlignment = Alignment.CenterHorizontally,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 32.dp, vertical = 48.dp),+ ) {+ Image(painterResource(R.drawable.local_files_cover), null, modifier = Modifier.size(120.dp).clip(Immersive.CoverMedium))+ Text(title, style = Immersive.Title, modifier = Modifier.padding(top = 24.dp))+ Text(subtitle, style = Immersive.Subhead, modifier = Modifier.padding(top = 8.dp))+ if (button != null) ImmersiveButton(button, onClick, filled = true, modifier = Modifier.padding(top = 24.dp))+ }+}++// ---------------------------------------------------------------- Episode++/** One podcast episode (or book chapter) of the Immersive look; the state and actions are the Classic page's [EpisodeViewModel]. */+@Composable+fun ImmersiveEpisodeScreen(navController: NavController, episodeId: String, fallbackName: String = "") {+ val vm: EpisodeViewModel = viewModel()+ val context = LocalContext.current+ LaunchedEffect(episodeId) { vm.load(episodeId) }++ val episode by vm.episode.collectAsState()+ val finished = vm.finished.value+ var menuOpen by remember { mutableStateOf(false) }+ var expanded by remember { mutableStateOf(false) }+ val np by SongPlayer.nowPlaying+ val uri = "spotify:episode:$episodeId"+ val playing = np.uri == uri && SongPlayer.isPlaying()+ val saved = SongPlayer.library[uri] == true++ fun play() {+ val ep = episode ?: return+ SongPlayer.playSong(ep.url, context)+ // The mini player and the notification show it before Spotify reports it.+ com.music.spotui.di.Graph.currentSongState.updateSongState(ep.coverUri, ep.title, ep.singer, true, ep.id, 0, ep.album)+ }+ episode?.let { ep ->+ if (menuOpen) EpisodeOptionsSheet(song = ep, finished = finished, onPlay = ::play, onMarkFinished = { vm.setFinished(ep, it) }, onDismiss = { menuOpen = false })+ }++ val title = episode?.title?.takeIf { it.isNotBlank() } ?: fallbackName+ ImmersivePage(title = title, onBack = { navController.popBackStack() }) {+ item(key = "hero") {+ Column(Modifier.fillMaxWidth().padding(horizontal = Immersive.Gutter), horizontalAlignment = Alignment.CenterHorizontally) {+ ImmersiveCover(episode?.coverUri, Modifier.fillMaxWidth(0.62f).aspectRatio(1f), Immersive.CoverLarge)+ val showId = episode?.showId.orEmpty()+ if (showId.isNotBlank()) {+ Text(+ episode?.singer.orEmpty(), style = Immersive.BodyStrong.copy(color = Immersive.Accent), maxLines = 1, overflow = TextOverflow.Ellipsis,+ modifier = Modifier.padding(top = 18.dp)+ .immersiveClickable(onClick = { navController.navigate(showRoute(showId, episode?.singer.orEmpty())) }),+ )+ }+ val date = episodeDateLabel(episode?.releaseDate.orEmpty())+ val minutes = episodeMinutes(episode?.durationMs ?: 0)+ Text(if (date.isBlank()) minutes else "$date • $minutes", style = Immersive.Subhead, modifier = Modifier.padding(top = 4.dp))+ // Action row: save, download, share, "...", then Play.+ Row(+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ modifier = Modifier.fillMaxWidth().padding(vertical = 16.dp),+ ) {+ ImmersiveCircleButton(+ if (saved) Icons.Rounded.Check else Icons.Rounded.Add,+ stringResource(if (saved) R.string.episode_unsave else R.string.episode_save),+ onClick = { episode?.let { SongPlayer.setSaved(it.spotifyUri, !saved) } },+ )+ episode?.let { EpisodeDownloadButton(it, size = 26.dp) }+ ImmersiveCircleButton(Icons.Rounded.IosShare, stringResource(R.string.a11y_share), onClick = { episode?.let { shareEpisode(context, it) } })+ ImmersiveCircleButton(Icons.Rounded.MoreHoriz, stringResource(R.string.episode_options), onClick = { menuOpen = true })+ Spacer(Modifier.weight(1f))+ ImmersiveButton(+ stringResource(if (playing) R.string.notif_action_pause else R.string.episode_play),+ onClick = { if (playing) SongPlayer.pause() else play() },+ icon = if (playing) Icons.Rounded.Pause else Icons.Rounded.PlayArrow,+ filled = true,+ )+ }+ }+ }+ if (vm.loading.value) immersiveSongListSkeleton(count = 2, keyPrefix = "episode:loading")+ if (vm.failed.value) item(key = "failed") { ImmersiveMessageState(stringResource(R.string.episode_not_found)) }+ episode?.let { ep ->+ if (ep.playedPositionMs > 0 && !finished) item(key = "remaining") {+ Text(+ stringResource(R.string.episode_remaining, episodeClock(ep.durationMs - ep.playedPositionMs)),+ style = Immersive.Caption.copy(color = Immersive.Accent),+ modifier = Modifier.padding(horizontal = Immersive.Gutter, vertical = 4.dp),+ )+ }+ if (ep.description.isNotBlank()) item(key = "description") {+ Column(+ Modifier.fillMaxWidth().animateContentSize(spring(stiffness = Spring.StiffnessMediumLow)).padding(Immersive.Gutter),+ ) {+ Text(+ ep.description, style = Immersive.Body.copy(color = Immersive.Text.copy(alpha = 0.8f)),+ maxLines = if (expanded) Int.MAX_VALUE else 4, overflow = TextOverflow.Ellipsis,+ )+ Text(+ stringResource(if (expanded) R.string.episode_show_less else R.string.episode_show_more),+ style = Immersive.Subhead.copy(color = Immersive.Accent),+ modifier = Modifier.padding(top = 8.dp).immersiveClickable(onClick = { expanded = !expanded }),+ )+ }+ }+ }+ }+}++// ---------------------------------------------------------------- Queue++/** The play queue route of the Immersive look: the song playing, then what is queued and what comes next. Swipe a row to remove it. */+@Composable+fun ImmersiveQueueScreen(navController: NavController) {+ // Spotify's real queue, read from the engine's PlayerAPI while this screen is open.+ DisposableEffect(Unit) {+ SongPlayer.watchQueue(true)+ onDispose { SongPlayer.watchQueue(false) }+ }+ val q by SongPlayer.engineQueue+ ImmersivePage(title = stringResource(R.string.action_queue_label), onBack = { navController.popBackStack() }) {+ q.current?.let { cur ->+ item(key = "now:header") { SectionHeader(stringResource(R.string.default_notification_channel_name)) }+ item(key = "now") { ImmersiveSongRow(song = cur, playing = true, onClick = {}, onMore = null) }+ }+ if (q.queued.isNotEmpty()) {+ item(key = "queued:header") { SectionHeader(stringResource(R.string.next_in_queue)) }+ itemsIndexed(q.queued, key = { i, it -> "q" + i + it.uid + it.uri }) { _, item ->+ Column(immersiveItemPlacement()) {+ ImmersiveSwipeToRemove(item.uid + item.uri, onRemove = { SongPlayer.removeFromQueue(item) }) {+ Box(Modifier.background(Immersive.Page)) { ImmersiveSongRow(song = item.song, playing = false, onClick = { SongPlayer.skipTo(item) }, onMore = null) }+ }+ }+ }+ }+ if (q.nextUp.isNotEmpty()) {+ item(key = "next:header") { SectionHeader(stringResource(R.string.next_up)) }+ itemsIndexed(q.nextUp, key = { i, it -> "n" + i + it.uid + it.uri }) { _, item ->+ Column(immersiveItemPlacement()) {+ ImmersiveSwipeToRemove(item.uid + item.uri, onRemove = { SongPlayer.removeFromQueue(item) }) {+ Box(Modifier.background(Immersive.Page)) { ImmersiveSongRow(song = item.song, playing = false, onClick = { SongPlayer.skipTo(item) }, onMore = null) }+ }+ }+ }+ }+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveDiscoverScreens.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveDiscoverScreens.ktnew file mode 100644index 00000000..860baead--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveDiscoverScreens.kt@@ -0,0 +1,307 @@+package com.music.spotui.ui.immersive.pages++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxHeight+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.background+import androidx.compose.foundation.lazy.LazyRow+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.lazy.itemsIndexed+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.produceState+import androidx.compose.runtime.remember+import androidx.compose.runtime.saveable.rememberSaveable+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.size+import androidx.navigation.NavController+import app.myspoti.api.TopContent+import app.myspoti.api.best+import app.myspoti.engine.R+import app.myspoti.host.android.MyspotiRuntime+import com.music.spotui.data.api.TopStats+import com.music.spotui.data.local.ListenHistory+import com.music.spotui.di.Graph+import com.music.spotui.di.SongPlayer+import com.music.spotui.ui.components.spotifyImageUrl+import com.music.spotui.ui.immersive.Immersive+import com.music.spotui.ui.immersive.components.ImmersiveListRow+import com.music.spotui.ui.immersive.components.ImmersiveMessageState+import com.music.spotui.ui.immersive.components.ImmersiveShelfCard+import com.music.spotui.ui.immersive.components.immersiveSongListSkeleton+import com.music.spotui.ui.immersive.components.ImmersiveCover+import com.music.spotui.ui.immersive.components.immersiveClickable+import com.music.spotui.ui.immersive.motion.immersiveItemPlacement+import com.music.spotui.ui.immersive.screens.ImmersiveRowDivider+import com.music.spotui.ui.immersive.components.SectionHeader+import com.music.spotui.ui.navigation.albumRoute+import com.music.spotui.ui.navigation.artistRoute+import com.music.spotui.ui.screens.ReleaseTile+import com.music.spotui.ui.screens.rangeLabels+import com.music.spotui.ui.theme.AppAccent+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext++// The pages of the Discover group in the Immersive look: new releases, saved episodes and the+// listening recap. They read the same sources as the Classic ones in DiscoverScreens.kt and+// StatsScreens.kt (the web API's what's-new, the saved episodes, ListenHistory, TopStats).++/** "New releases": what the followed artists just released, then the latest albums Spotify features. */+@Composable+fun ImmersiveNewReleasesScreen(navController: NavController) {+ val followed by produceState<List<ReleaseTile>?>(null) {+ value = runCatching {+ MyspotiRuntime.api.home.whatsNew(0, 50).items.map { a ->+ ReleaseTile(a.uri.substringAfterLast(':'), a.name, a.artists.joinToString(", ") { it.name },+ a.images.best(300)?.url.orEmpty(), listOfNotNull(a.type.lowercase().replaceFirstChar { it.uppercase() }, a.releaseDate?.take(10)).joinToString(" • "))+ }+ }.getOrDefault(emptyList())+ }+ val latest by produceState<List<ReleaseTile>?>(null) {+ value = runCatching {+ Graph.api.newReleases().map { ReleaseTile(it.spotifyId, it.name, it.artists, it.coverUri, it.artists) }+ }.getOrDefault(emptyList())+ }+ ImmersivePage(title = stringResource(R.string.browse_new_releases), onBack = { navController.popBackStack() }) {+ fun section(key: String, title: Int, list: List<ReleaseTile>?) {+ item(key = "$key:header") { SectionHeader(stringResource(title)) }+ when {+ list == null -> immersiveSongListSkeleton(count = 4, keyPrefix = "$key:skeleton")+ list.isEmpty() -> item(key = "$key:empty") {+ Text(stringResource(R.string.nothing_here), style = Immersive.Subhead, modifier = Modifier.padding(horizontal = Immersive.Gutter, vertical = 4.dp))+ }+ else -> items(list.chunked(2), key = { row -> "$key:" + row.first().id }) { pair ->+ Row(+ horizontalArrangement = Arrangement.spacedBy(14.dp),+ modifier = Modifier.fillMaxWidth().padding(horizontal = Immersive.Gutter).padding(bottom = 18.dp),+ ) {+ pair.forEach { t ->+ ImmersiveShelfCard(+ title = t.name, subtitle = t.detail.ifBlank { t.artists }, imageUrl = t.cover,+ onClick = { navController.navigate(albumRoute(t.name, t.artists, t.id)) },+ modifier = Modifier.weight(1f),+ )+ }+ if (pair.size == 1) Spacer(Modifier.weight(1f))+ }+ }+ }+ }+ section("followed", R.string.new_releases_followed, followed)+ section("latest", R.string.new_releases_latest, latest)+ }+}++/** "Your Episodes": saved podcast episodes, newest first, playable in place. */+@Composable+fun ImmersiveEpisodesScreen(navController: NavController) {+ val episodes by produceState<List<com.music.spotui.data.entity.SongsModel>?>(null) { value = Graph.api.getSavedEpisodes() }+ ImmersivePage(title = stringResource(R.string.your_episodes_title), onBack = { navController.popBackStack() }) {+ val list = episodes+ when {+ list == null -> immersiveSongListSkeleton(count = 7)+ list.isEmpty() -> item(key = "empty") { ImmersiveMessageState(stringResource(R.string.your_episodes_empty)) }+ else -> items(list, key = { it.url }) { e ->+ Column(immersiveItemPlacement()) {+ ImmersiveListRow(+ title = e.title,+ subtitle = e.singer + " • " + episodeMinutesLabel(e.durationMs / 60_000L),+ imageUrl = e.coverUri,+ round = false,+ onClick = {+ SongPlayer.registerContext(list.map { it.url }, "spotify:collection:your-episodes")+ SongPlayer.playSong(e.url)+ },+ )+ }+ }+ }+ }+}++private fun episodeMinutesLabel(min: Long) = if (min >= 60) "${min / 60} h ${min % 60} min" else "$min min"++/**+ * The in-app recap: Spotify's ranking of the account first, then what was played on this phone+ * (Spotify, downloads and local files). Same counters as the Classic `RecapScreen`.+ */+@Composable+fun ImmersiveRecapScreen(navController: NavController) {+ val periods = listOf(R.string.recap_month to 30L, R.string.recap_year to 365L, R.string.recap_all to 36_500L)+ var period by rememberSaveable { mutableIntStateOf(1) }+ var tab by rememberSaveable { mutableIntStateOf(0) }+ // Off the main thread: the history file grows with every listen.+ val loaded by produceState<ListenHistory.Recap?>(null, period) {+ value = withContext(Dispatchers.IO) { ListenHistory.recap(System.currentTimeMillis() - periods[period].second * 86_400_000L) }+ }+ val recap = loaded ?: ListenHistory.Recap(0, 0, emptyMap(), emptyList(), emptyList(), emptyList())+ ImmersivePage(title = stringResource(R.string.recap_title), onBack = { navController.popBackStack() }) {+ item(key = "tabs") {+ ImmersiveSegmentedControl(+ options = listOf(stringResource(R.string.stats_tab_spotify), stringResource(R.string.stats_tab_phone)),+ selectedIndex = tab, onSelect = { tab = it },+ modifier = Modifier.padding(horizontal = Immersive.Gutter, vertical = 6.dp),+ )+ }+ if (tab == 0) spotifyStats(navController) else phoneStats(navController, recap, periods.map { it.first }, period) { period = it }+ }+}++private fun androidx.compose.foundation.lazy.LazyListScope.spotifyStats(navController: NavController) {+ item(key = "spotify") { SpotifyStatsBlock(navController) }+}++@Composable+private fun SpotifyStatsBlock(navController: NavController) {+ var range by rememberSaveable { mutableIntStateOf(0) }+ var attempt by remember { mutableIntStateOf(0) }+ val timeRange = rangeLabels[range].first+ val state by produceState<Result<TopContent>?>(TopStats.cached(timeRange)?.let { Result.success(it) }, timeRange, attempt) {+ value = runCatching { TopStats.get(timeRange, force = attempt > 0) }+ }+ val top = state?.getOrNull()+ Column {+ ImmersiveSegmentedControl(+ options = rangeLabels.map { stringResource(it.second) },+ selectedIndex = range, onSelect = { range = it },+ modifier = Modifier.padding(horizontal = Immersive.Gutter, vertical = 6.dp),+ )+ when {+ state == null -> repeat(5) { com.music.spotui.ui.immersive.components.ImmersiveSongRowSkeleton(index = it) }+ top == null -> ImmersiveMessageState(stringResource(R.string.stats_failed), actionLabel = stringResource(R.string.retry_button), onAction = { attempt++ })+ top.artists.isEmpty() && top.tracks.isEmpty() -> ImmersiveMessageState(stringResource(R.string.stats_empty))+ else -> {+ top.artistTotal?.takeIf { it > 0 }?.let { total ->+ Text(stringResource(R.string.stats_artists_ranked, total), style = Immersive.Subhead,+ modifier = Modifier.padding(horizontal = Immersive.Gutter, vertical = 10.dp))+ }+ if (top.artists.isNotEmpty()) {+ SectionHeader(stringResource(R.string.recap_top_artists))+ LazyRow(contentPadding = PaddingValues(horizontal = Immersive.Gutter), horizontalArrangement = Arrangement.spacedBy(14.dp)) {+ itemsIndexed(top.artists, key = { _, a -> a.uri }) { i, a ->+ ImmersiveShelfCard(+ title = "${i + 1}. ${a.name}", subtitle = null,+ imageUrl = spotifyImageUrl(a.images.best(300)?.url), round = true,+ onClick = { navController.navigate(artistRoute(a.name, a.uri.substringAfterLast(':'))) },+ modifier = Modifier.width(120.dp),+ )+ }+ }+ }+ if (top.tracks.isNotEmpty()) {+ SectionHeader(stringResource(R.string.recap_top_tracks))+ top.tracks.forEachIndexed { i, t ->+ ImmersiveListRow(+ title = "${i + 1} ${t.name}",+ subtitle = t.artists.joinToString(", ") { it.name },+ imageUrl = spotifyImageUrl(t.album?.images?.best(160)?.url),+ round = false,+ onClick = { SongPlayer.playSong(t.uri) },+ )+ }+ }+ }+ }+ Text(stringResource(R.string.stats_spotify_note), style = Immersive.Caption.copy(color = Immersive.TextTertiary),+ modifier = Modifier.padding(Immersive.Gutter, 24.dp))+ }+}++private fun androidx.compose.foundation.lazy.LazyListScope.phoneStats(+ navController: NavController,+ recap: ListenHistory.Recap,+ periodLabels: List<Int>,+ period: Int,+ onPeriod: (Int) -> Unit,+) {+ item(key = "period") {+ ImmersiveSegmentedControl(+ options = periodLabels.map { stringResource(it) },+ selectedIndex = period, onSelect = onPeriod,+ modifier = Modifier.padding(horizontal = Immersive.Gutter, vertical = 6.dp),+ )+ }+ item(key = "totals") {+ Column(Modifier.padding(horizontal = Immersive.Gutter, vertical = 16.dp)) {+ Text(stringResource(R.string.recap_minutes, recap.minutes), style = Immersive.LargeTitle)+ Text(stringResource(R.string.recap_listens, recap.listens), style = Immersive.Subhead)+ val src = recap.bySource+ Text(+ stringResource(R.string.recap_sources, src[ListenHistory.Source.SPOTIFY] ?: 0, src[ListenHistory.Source.DOWNLOAD] ?: 0, src[ListenHistory.Source.LOCAL] ?: 0),+ style = Immersive.Caption, modifier = Modifier.padding(top = 8.dp),+ )+ }+ }+ item(key = "weekly") { ImmersiveWeeklyChart() }+ if (recap.listens == 0) item(key = "empty") { ImmersiveMessageState(stringResource(R.string.recap_empty)) }+ fun ranked(key: String, title: Int, list: List<ListenHistory.Ranked>) {+ if (list.isEmpty()) return+ item(key = "$key:header") { SectionHeader(stringResource(title)) }+ itemsIndexed(list, key = { i, _ -> "$key:$i" }) { i, r ->+ ImmersiveListRow(+ title = "${i + 1} ${r.name}",+ subtitle = listOf(r.subtitle, stringResource(R.string.recap_plays, r.count)).filter { it.isNotBlank() }.joinToString(" • "),+ imageUrl = r.cover, round = false, onClick = {},+ )+ }+ }+ ranked("tracks", R.string.recap_top_tracks, recap.topTracks)+ ranked("artists", R.string.recap_top_artists, recap.topArtists)+ ranked("albums", R.string.recap_top_albums, recap.topAlbums)+ item(key = "note") {+ Text(stringResource(R.string.recap_private_note), style = Immersive.Caption.copy(color = Immersive.TextTertiary),+ modifier = Modifier.padding(Immersive.Gutter, 24.dp))+ }+}++/** Minutes played per calendar week on this phone, the current week last and in the accent. */+@Composable+private fun ImmersiveWeeklyChart() {+ val weeks by produceState<List<ListenHistory.Week>?>(null) { value = withContext(Dispatchers.IO) { ListenHistory.weekly(8) } }+ val w = weeks ?: return+ if (w.all { it.minutes == 0L }) return+ val max = w.maxOf { it.minutes }.coerceAtLeast(1)+ val pattern = android.text.format.DateFormat.getBestDateTimePattern(java.util.Locale.getDefault(), "dMMM")+ val format = remember(pattern) { java.text.SimpleDateFormat(pattern, java.util.Locale.getDefault()) }+ Column(Modifier.padding(horizontal = Immersive.Gutter, vertical = 8.dp).clip(Immersive.Card).background(Immersive.Raised).padding(16.dp)) {+ Text(stringResource(R.string.stats_weekly_minutes), style = Immersive.Headline)+ Text(stringResource(R.string.stats_this_week, w.last().minutes), style = Immersive.Caption, modifier = Modifier.padding(top = 2.dp, bottom = 12.dp))+ Row(Modifier.fillMaxWidth().height(120.dp), horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.Bottom) {+ w.forEachIndexed { i, week ->+ Column(Modifier.weight(1f).fillMaxHeight(), verticalArrangement = Arrangement.Bottom, horizontalAlignment = Alignment.CenterHorizontally) {+ if (week.minutes > 0) Text("${week.minutes}", style = Immersive.Caption, maxLines = 1)+ Box(+ Modifier.fillMaxWidth()+ .height((96f * week.minutes / max).coerceAtLeast(2f).dp)+ .clip(RoundedCornerShape(topStart = 5.dp, topEnd = 5.dp))+ .background(if (i == w.lastIndex) Immersive.Accent else Immersive.Text.copy(alpha = 0.22f)),+ )+ }+ }+ }+ Row(Modifier.fillMaxWidth().padding(top = 4.dp), horizontalArrangement = Arrangement.spacedBy(6.dp)) {+ w.forEach { week ->+ Text(format.format(java.util.Date(week.startMs)), style = Immersive.Caption.copy(color = Immersive.TextTertiary), maxLines = 1,+ textAlign = TextAlign.Center, modifier = Modifier.weight(1f))+ }+ }+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveDownloadsScreen.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveDownloadsScreen.ktnew file mode 100644index 00000000..6dda6c27--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveDownloadsScreen.kt@@ -0,0 +1,254 @@+package com.music.spotui.ui.immersive.pages++import android.text.format.Formatter+import android.widget.Toast+import androidx.compose.foundation.Image+import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.lazy.itemsIndexed+import androidx.compose.foundation.lazy.rememberLazyListState+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.rounded.Close+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.painterResource+import androidx.compose.ui.res.pluralStringResource+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import androidx.navigation.NavController+import app.myspoti.engine.R+import com.music.spotui.data.entity.SongsModel+import com.music.spotui.data.offline.OfflineCollections+import com.music.spotui.data.offline.OfflineDownloader+import com.music.spotui.data.offline.OfflineStatus+import com.music.spotui.data.offline.OfflineStore+import com.music.spotui.di.Haptics+import com.music.spotui.di.LocalPlayer+import com.music.spotui.di.SongPlayer+import com.music.spotui.ui.components.DownloadBadge+import com.music.spotui.ui.components.FastScrollbar+import com.music.spotui.ui.immersive.sheets.ImmersiveSongOptionsSheet+import com.music.spotui.ui.immersive.Immersive+import com.music.spotui.ui.immersive.components.ImmersiveListRow+import com.music.spotui.ui.immersive.components.ImmersivePlayShuffleButtons+import com.music.spotui.ui.immersive.components.ImmersiveSongRow+import com.music.spotui.ui.immersive.components.ImmersiveRowDividerInset+import com.music.spotui.ui.immersive.components.immersiveClickable+import com.music.spotui.ui.immersive.screens.ImmersiveRowDivider+import com.music.spotui.ui.immersive.shell.ImmersiveLargeTitle+import com.music.spotui.ui.immersive.shell.ImmersiveTopBar+import com.music.spotui.ui.immersive.shell.immersiveHazeSource+import com.music.spotui.ui.immersive.shell.immersiveTopContentPadding+import com.music.spotui.ui.navigation.Routes++/**+ * "Downloaded" of the Immersive look, replacing the Classic `DownloadsScreen`: a large title with+ * the count and size, Play / Shuffle pills, the notice cards (SpotiFLAC verification, stop all),+ * the songs still on their way and the downloaded songs, played from the phone by [LocalPlayer].+ * A downloaded row swipes away to un-download it; its menu is the song sheet.+ */+@Composable+fun ImmersiveDownloadsScreen(navController: NavController) {+ val context = LocalContext.current+ val title = stringResource(R.string.collection_downloaded)+ // Snapshot reads: the list follows downloads as they finish.+ val tracks = OfflineStore.tracks.values.sortedByDescending { it.addedAt }+ val waiting = OfflineDownloader.requests.values.filter { !OfflineStore.isDownloaded(it.trackId) }+ // Only queued or running songs can be stopped; a failed one has nothing left to cancel.+ val stoppable = waiting.count {+ val s = OfflineStore.status[it.trackId]+ s == OfflineStatus.Queued || s is OfflineStatus.Downloading+ }+ val np by SongPlayer.nowPlaying+ val playingHere = LocalPlayer.active.value && LocalPlayer.contextName == title+ var menuSong by remember { mutableStateOf<SongsModel?>(null) }+ menuSong?.let { sel ->+ ImmersiveSongOptionsSheet(song = sel, navController = navController, context = context, onDismiss = { menuSong = null })+ }+ fun play(index: Int, shuffle: Boolean = false) {+ if (tracks.isEmpty()) return+ LocalPlayer.play(tracks.map(OfflineStore::toLocalTrack), index, shuffle = shuffle, context = title)+ }++ val listState = rememberLazyListState()+ ImmersivePageFrame {+ if (tracks.isEmpty() && waiting.isEmpty()) {+ Column(+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.Center,+ modifier = Modifier.fillMaxSize().padding(horizontal = 32.dp),+ ) {+ Image(+ painterResource(R.drawable.downloads_cover), null,+ modifier = Modifier.size(120.dp).clip(Immersive.CoverMedium),+ )+ Text(+ stringResource(R.string.downloads_empty_title),+ style = Immersive.Title, textAlign = TextAlign.Center,+ modifier = Modifier.padding(top = 24.dp),+ )+ Text(+ stringResource(R.string.downloads_empty_subtitle),+ style = Immersive.Subhead, textAlign = TextAlign.Center,+ modifier = Modifier.padding(top = 8.dp),+ )+ }+ } else {+ LazyColumn(+ state = listState,+ contentPadding = PaddingValues(top = immersiveTopContentPadding(), bottom = Immersive.BottomChrome),+ modifier = Modifier.fillMaxSize().immersiveHazeSource(),+ ) {+ item(key = "downloads:title") {+ val n = tracks.size+ val size = Formatter.formatShortFileSize(context, OfflineStore.totalBytes())+ ImmersiveLargeTitle(+ title = title,+ subtitle = pluralStringResource(R.plurals.local_files_count, n, n) + " · " ++ stringResource(R.string.downloads_size, size),+ )+ Text(+ stringResource(R.string.downloads_source),+ style = Immersive.Caption,+ modifier = Modifier.padding(horizontal = Immersive.Gutter).padding(bottom = 14.dp),+ )+ }+ if (tracks.isNotEmpty()) item(key = "downloads:buttons") {+ ImmersivePlayShuffleButtons(+ onPlay = {+ when {+ playingHere && SongPlayer.isPlaying() -> SongPlayer.pause()+ playingHere -> SongPlayer.play()+ else -> play(0)+ }+ },+ onShuffle = { play(tracks.indices.random(), shuffle = true) },+ modifier = Modifier.padding(bottom = 14.dp),+ )+ }+ // No extension gives download files: say it where downloads would fail.+ if (!com.music.spotui.extensions.Extensions.hasDownloadSource()) item(key = "source") {+ NoticeCard(+ title = stringResource(R.string.downloads_need_source),+ detail = null,+ onClick = { navController.navigate(Routes.Extensions.route) },+ )+ }+ // One tap empties the queue; the songs already downloaded stay untouched.+ if (stoppable > 0) item(key = "stop_all") {+ NoticeCard(+ title = stringResource(R.string.downloads_stop_all_title),+ detail = stringResource(R.string.downloads_stop_all_detail),+ icon = true,+ onClick = { Haptics.click(); OfflineDownloader.stopAll() },+ )+ }+ // Songs still on their way (or that could not be downloaded).+ items(waiting, key = { "w:" + it.trackId }) { r ->+ val status = OfflineStore.status[r.trackId]+ val line = when (status) {+ OfflineStatus.Unavailable -> stringResource(R.string.download_unavailable)+ OfflineStatus.Failed ->+ stringResource(R.string.download_badge_error_content_description) + " · " + stringResource(R.string.download_retry)+ else -> stringResource(R.string.download_notification_downloading)+ }+ ImmersiveListRow(+ title = r.title,+ subtitle = line,+ imageUrl = r.coverUrl,+ round = false,+ onClick = { if (status == OfflineStatus.Failed) OfflineDownloader.retry(r.trackId) },+ modifier = Modifier.animateItem(),+ trailing = {+ DownloadBadge(status, size = 20.dp)+ Spacer(Modifier.width(12.dp))+ Icon(+ Icons.Rounded.Close,+ contentDescription = stringResource(R.string.download_cancel),+ tint = Immersive.TextSecondary,+ modifier = Modifier+ .size(32.dp)+ .clip(CircleShape)+ .immersiveClickable(onClick = { Haptics.click(); OfflineDownloader.cancel(r.trackId) }, pressedScale = 0.9f)+ .padding(6.dp),+ )+ },+ )+ }+ itemsIndexed(tracks, key = { _, t -> t.trackId }) { i, t ->+ val current = LocalPlayer.active.value && np.uri == "local:${OfflineStore.localIdOf(t.trackId)}"+ val song = OfflineStore.toSong(t)+ Column(Modifier.animateItem()) {+ ImmersiveSwipeToRemove(t.trackId, onRemove = {+ val gone = OfflineCollections.removeSong(t.trackId)+ Toast.makeText(+ context,+ context.getString(if (gone) R.string.toast_undownload else R.string.download_kept_by_list),+ Toast.LENGTH_SHORT,+ ).show()+ }) {+ ImmersiveSongRow(+ song = song,+ playing = current && SongPlayer.isPlaying(),+ current = current,+ onClick = { play(i) },+ onMore = { menuSong = song },+ )+ }+ if (i < tracks.lastIndex) ImmersiveRowDivider(ImmersiveRowDividerInset)+ }+ }+ }+ FastScrollbar(listState, Modifier.align(Alignment.CenterEnd))+ }+ ImmersiveTopBar(title = title, listState = listState, onBack = { navController.navigateUp() })+ }+}++/** A rounded notice under the buttons: a title, an optional detail line and, with [icon], a cross. */+@Composable+private fun NoticeCard(title: String, detail: String?, onClick: () -> Unit, icon: Boolean = false) {+ Row(+ verticalAlignment = Alignment.CenterVertically,+ modifier = Modifier+ .padding(horizontal = Immersive.Gutter, vertical = 6.dp)+ .fillMaxWidth()+ .immersiveClickable(onClick = onClick, pressedScale = 0.98f)+ .clip(Immersive.Card)+ .background(Immersive.Raised)+ .padding(horizontal = 14.dp, vertical = 12.dp),+ ) {+ Column(Modifier.weight(1f)) {+ Text(title, style = Immersive.Body.copy(fontSize = 14.sp, lineHeight = 19.sp))+ if (detail != null) Text(detail, style = Immersive.Caption)+ }+ if (icon) {+ Spacer(Modifier.width(12.dp))+ Icon(Icons.Rounded.Close, contentDescription = title, tint = Immersive.TextSecondary, modifier = Modifier.size(20.dp))+ }+ }+}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.ktnew file mode 100644index 00000000..3f8bbe74--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersivePage.kt@@ -0,0 +1,287 @@+package com.music.spotui.ui.immersive.pages++import androidx.compose.animation.animateColorAsState+import androidx.compose.animation.core.Spring+import androidx.compose.animation.core.snap+import androidx.compose.animation.core.spring+import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.RowScope+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.heightIn+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.layout.widthIn+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.LazyListScope+import androidx.compose.foundation.lazy.LazyListState+import androidx.compose.foundation.lazy.rememberLazyListState+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.automirrored.rounded.KeyboardArrowRight+import androidx.compose.material.icons.rounded.Check+import androidx.compose.material3.Icon+import androidx.compose.material3.Switch+import androidx.compose.material3.SwitchDefaults+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.vector.ImageVector+import androidx.compose.ui.semantics.Role+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp+import com.music.spotui.ui.immersive.Immersive+import com.music.spotui.ui.immersive.components.immersiveClickable+import com.music.spotui.ui.immersive.shell.ImmersiveLargeTitle+import com.music.spotui.ui.immersive.shell.ImmersiveTopBar+import com.music.spotui.ui.immersive.shell.immersiveChromeScroll+import com.music.spotui.ui.immersive.shell.immersiveHazeSource+import com.music.spotui.ui.immersive.shell.immersiveTopContentPadding+import com.music.spotui.ui.look.rememberReduceMotion+import androidx.compose.foundation.selection.toggleable++/**+ * The shared scaffold of the Immersive pages (Settings, Extensions, Recap...): a large title that+ * collapses into the glass top bar as the list scrolls under it, the page colour and the+ * rubber-band overscroll, and a list the page fills with [content] (see [immersiveGroup] for the+ * iOS-style inset sections).+ *+ * @param modifier lands on the scrolling list; the place to attach a scroll connection (bars that+ * minimise while scrolling) or any other list-level modifier.+ * @param largeTitleTrailing the end of the title line (a count, a button).+ * @param actions trailing controls of the top bar, see `ImmersiveBarAction`.+ * @param onBack shows the back chevron when set.+ */+@Composable+internal fun ImmersivePage(+ title: String,+ onBack: (() -> Unit)?,+ modifier: Modifier = Modifier,+ subtitle: String? = null,+ listState: LazyListState = rememberLazyListState(),+ largeTitleTrailing: (@Composable RowScope.() -> Unit)? = null,+ actions: (@Composable RowScope.() -> Unit)? = null,+ bottomPadding: Dp = Immersive.BottomChrome,+ verticalArrangement: Arrangement.Vertical = Arrangement.Top,+ content: LazyListScope.() -> Unit,+) {+ ImmersivePageFrame {+ LazyColumn(+ state = listState,+ contentPadding = PaddingValues(top = immersiveTopContentPadding(), bottom = bottomPadding),+ verticalArrangement = verticalArrangement,+ modifier = modifier.fillMaxSize().immersiveHazeSource().immersiveChromeScroll(),+ ) {+ item(key = "page:title", contentType = "page:title") {+ ImmersiveLargeTitle(title = title, subtitle = subtitle, trailing = largeTitleTrailing)+ }+ content()+ }+ ImmersiveTopBar(+ title = title,+ listState = listState,+ onBack = onBack,+ actions = actions,+ )+ }+}++/** What a group collects: its rows, drawn one under the other with a separator between. */+internal class ImmersiveGroupScope {+ internal val rows = mutableListOf<@Composable () -> Unit>()++ /** One row of the card; build it with [ImmersiveGroupRow], [ImmersiveSwitchRow]... or anything else. */+ fun row(content: @Composable () -> Unit) {+ rows += content+ }+}++private val GroupSeparatorInset = 16.dp++/**+ * An inset grouped section, as in iOS Settings: a small [header] over a rounded [Immersive.Raised]+ * card whose rows are told apart by hairlines, and a [footer] note under it. Nothing is drawn+ * when [content] adds no row.+ */+internal fun LazyListScope.immersiveGroup(+ key: String,+ header: String? = null,+ footer: String? = null,+ @androidx.annotation.StringRes headerRes: Int? = null,+ @androidx.annotation.StringRes footerRes: Int? = null,+ content: ImmersiveGroupScope.() -> Unit,+) {+ item(key = "group:$key", contentType = "group") {+ val scope = ImmersiveGroupScope().apply(content)+ if (scope.rows.isEmpty()) return@item+ val header = header ?: headerRes?.let { androidx.compose.ui.res.stringResource(it) }+ val footer = footer ?: footerRes?.let { androidx.compose.ui.res.stringResource(it) }+ Column(Modifier.fillMaxWidth().padding(horizontal = Immersive.Gutter).padding(top = 14.dp)) {+ if (header != null) {+ Text(+ header.uppercase(),+ style = Immersive.Caption,+ modifier = Modifier.padding(start = GroupSeparatorInset, bottom = 6.dp),+ )+ }+ Column(Modifier.fillMaxWidth().clip(Immersive.Card).background(Immersive.Raised)) {+ scope.rows.forEachIndexed { i, row ->+ row()+ if (i < scope.rows.lastIndex) {+ Box(+ Modifier+ .padding(start = GroupSeparatorInset)+ .fillMaxWidth()+ .heightIn(min = 0.5.dp, max = 0.5.dp)+ .background(Immersive.Separator),+ )+ }+ }+ }+ if (footer != null) {+ Text(+ footer,+ style = Immersive.Caption.copy(color = Immersive.TextTertiary),+ modifier = Modifier.padding(start = GroupSeparatorInset, end = GroupSeparatorInset, top = 6.dp),+ )+ }+ }+ }+}++/** A free-standing block on the page (a message, a chart) with the page's gutters. */+internal fun LazyListScope.immersiveBlock(key: String, content: @Composable () -> Unit) {+ item(key = "block:$key", contentType = "block") {+ Box(Modifier.fillMaxWidth().padding(horizontal = Immersive.Gutter, vertical = 8.dp)) { content() }+ }+}++/**+ * One row of a group: an optional [icon], the [title] with a [detail] line, a [value] at the end+ * and a chevron when it opens something. [trailing] replaces the value and the chevron.+ */+@Composable+internal fun ImmersiveGroupRow(+ title: String,+ modifier: Modifier = Modifier,+ detail: String? = null,+ icon: ImageVector? = null,+ value: String? = null,+ chevron: Boolean = false,+ destructive: Boolean = false,+ enabled: Boolean = true,+ detailColor: Color = Immersive.TextSecondary,+ onClick: (() -> Unit)? = null,+ trailing: (@Composable () -> Unit)? = null,+) {+ val tint = if (destructive) ImmersiveDestructive else Immersive.Text+ Row(+ verticalAlignment = Alignment.CenterVertically,+ modifier = modifier+ .fillMaxWidth()+ .then(if (onClick != null) Modifier.immersiveClickable(onClick = onClick, pressedScale = 0.99f, enabled = enabled) else Modifier)+ .heightIn(min = 52.dp)+ .padding(horizontal = GroupSeparatorInset, vertical = 10.dp),+ ) {+ if (icon != null) {+ Icon(icon, null, tint = Immersive.Accent, modifier = Modifier.size(22.dp))+ Spacer(Modifier.width(12.dp))+ }+ Column(Modifier.weight(1f)) {+ Text(title, style = Immersive.Body.copy(color = tint), maxLines = 2, overflow = TextOverflow.Ellipsis)+ if (!detail.isNullOrBlank()) {+ Text(detail, style = Immersive.Caption.copy(color = detailColor), maxLines = 3, overflow = TextOverflow.Ellipsis)+ }+ }+ if (trailing != null) {+ Spacer(Modifier.width(10.dp))+ trailing()+ } else {+ if (value != null) {+ Spacer(Modifier.width(10.dp))+ Text(value, style = Immersive.Body.copy(color = Immersive.TextSecondary), maxLines = 1, overflow = TextOverflow.Ellipsis,+ modifier = Modifier.widthIn(max = 160.dp))+ }+ if (chevron) {+ Spacer(Modifier.width(4.dp))+ Icon(Icons.AutoMirrored.Rounded.KeyboardArrowRight, null, tint = Immersive.TextTertiary, modifier = Modifier.size(22.dp))+ }+ }+ }+}++/** A row with a switch at its end; the whole row toggles. */+@Composable+internal fun ImmersiveSwitchRow(+ title: String,+ checked: Boolean,+ onChecked: (Boolean) -> Unit,+ detail: String? = null,+ enabled: Boolean = true,+ detailColor: Color = Immersive.TextSecondary,+) {+ Row(+ verticalAlignment = Alignment.CenterVertically,+ modifier = Modifier+ .fillMaxWidth()+ .toggleable(checked, enabled = enabled, role = Role.Switch, onValueChange = onChecked)+ .heightIn(min = 52.dp)+ .padding(horizontal = GroupSeparatorInset, vertical = 10.dp),+ ) {+ Column(Modifier.weight(1f)) {+ Text(title, style = Immersive.Body.copy(color = if (enabled) Immersive.Text else Immersive.TextTertiary), maxLines = 2, overflow = TextOverflow.Ellipsis)+ if (!detail.isNullOrBlank()) {+ Text(detail, style = Immersive.Caption.copy(color = detailColor), maxLines = 4, overflow = TextOverflow.Ellipsis)+ }+ }+ Spacer(Modifier.width(12.dp))+ Switch(+ checked = checked,+ onCheckedChange = null,+ enabled = enabled,+ colors = SwitchDefaults.colors(+ checkedThumbColor = Color.White,+ checkedTrackColor = Immersive.Accent,+ uncheckedThumbColor = Color.White,+ uncheckedTrackColor = Color(0xFF3A3A3F),+ uncheckedBorderColor = Color.Transparent,+ disabledCheckedTrackColor = Immersive.Accent.copy(alpha = 0.4f),+ disabledUncheckedTrackColor = Color(0xFF2A2A2E),+ disabledUncheckedBorderColor = Color.Transparent,+ ),+ )+ }+}++/** One choice of a list where a single row is selected: a check in the accent at its end. */+@Composable+internal fun ImmersiveChoiceRow(+ title: String,+ selected: Boolean,+ onClick: () -> Unit,+ detail: String? = null,+) {+ val reduce = rememberReduceMotion()+ val color by animateColorAsState(+ if (selected) Immersive.Accent else Color.Transparent,+ animationSpec = if (reduce) snap() else spring(stiffness = Spring.StiffnessMediumLow),+ label = "choice check",+ )+ ImmersiveGroupRow(+ title = title,+ detail = detail,+ onClick = onClick,+ trailing = { Icon(Icons.Rounded.Check, null, tint = color, modifier = Modifier.size(22.dp)) },+ )+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersivePagesParts.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersivePagesParts.ktnew file mode 100644index 00000000..78bd3e47--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersivePagesParts.kt@@ -0,0 +1,305 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * app/src/main/java/com/music/bitchord/ui/screens/SettingsSheet.kt (SegmentedControl) at edc1e6f.+ * Modified for Myspoti, 2026-10.+ */+package com.music.spotui.ui.immersive.pages++import androidx.compose.animation.animateColorAsState+import androidx.compose.animation.core.Animatable+import androidx.compose.animation.core.snap+import androidx.compose.animation.core.spring+import androidx.compose.animation.core.tween+import androidx.compose.foundation.background+import androidx.compose.foundation.LocalOverscrollFactory+import androidx.compose.foundation.clickable+import androidx.compose.foundation.gestures.detectHorizontalDragGestures+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.BoxScope+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.ColumnScope+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.heightIn+import androidx.compose.foundation.layout.navigationBarsPadding+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.text.BasicTextField+import androidx.compose.foundation.text.KeyboardActions+import androidx.compose.foundation.text.KeyboardOptions+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.rounded.DeleteOutline+import androidx.compose.material3.AlertDialog+import androidx.compose.material3.ExperimentalMaterial3Api+import androidx.compose.material3.Icon+import androidx.compose.material3.ModalBottomSheet+import androidx.compose.material3.Text+import androidx.compose.material3.TextButton+import androidx.compose.runtime.Composable+import androidx.compose.runtime.CompositionLocalProvider+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableFloatStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.focus.focusRequester+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.SolidColor+import androidx.compose.ui.graphics.vector.ImageVector+import androidx.compose.ui.hapticfeedback.HapticFeedbackType+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.layout.onSizeChanged+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.platform.LocalHapticFeedback+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.semantics.Role+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.input.ImeAction+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.IntOffset+import androidx.compose.ui.unit.dp+import app.myspoti.engine.R+import com.music.spotui.di.Haptics+import com.music.spotui.ui.immersive.Immersive+import com.music.spotui.ui.immersive.components.immersiveClickable+import com.music.spotui.ui.immersive.components.rememberImmersiveOverscrollFactory+import com.music.spotui.ui.look.rememberReduceMotion+import kotlinx.coroutines.launch+import kotlin.math.roundToInt++/** The red of a destructive swipe or menu entry. */+internal val ImmersiveDestructive = Color(0xFFFF453A)++/**+ * Sliding pill selector for the two or three views of a page (Songs, Artists, Albums). A+ * [Immersive.Raised] track with the selected option inverted on the accent.+ */+@Composable+internal fun ImmersiveSegmentedControl(+ options: List<String>,+ selectedIndex: Int,+ onSelect: (Int) -> Unit,+ modifier: Modifier = Modifier,+) {+ val haptics = LocalHapticFeedback.current+ val reduceMotion = rememberReduceMotion()+ Row(+ modifier = modifier+ .fillMaxWidth()+ .clip(RoundedCornerShape(10.dp))+ .background(Immersive.Raised)+ // Enough of a margin for the track to read as a track: at 2 dp the selected pill sat+ // flush against the container's own edge and the two shapes merged into one.+ .padding(4.dp),+ horizontalArrangement = Arrangement.spacedBy(2.dp),+ ) {+ options.forEachIndexed { index, label ->+ val chosen = index == selectedIndex+ val pill by animateColorAsState(+ targetValue = if (chosen) Immersive.Accent else Color.Transparent,+ animationSpec = if (reduceMotion) snap() else tween(160),+ label = "segment pill",+ )+ val labelColor by animateColorAsState(+ targetValue = if (chosen) Color.White else Immersive.TextSecondary,+ animationSpec = if (reduceMotion) snap() else tween(160),+ label = "segment label",+ )+ Box(+ modifier = Modifier+ .weight(1f)+ .clip(RoundedCornerShape(8.dp))+ .background(pill)+ .clickable(role = Role.Tab) {+ if (!chosen) {+ haptics.performHapticFeedback(HapticFeedbackType.TextHandleMove)+ onSelect(index)+ }+ }+ .padding(vertical = 9.dp),+ contentAlignment = Alignment.Center,+ ) {+ Text(+ text = label,+ style = Immersive.Subhead.copy(color = labelColor, fontWeight = FontWeight.Medium),+ maxLines = 1,+ )+ }+ }+ }+}++/**+ * Swipe a row from right to left to remove it: the row follows the finger over a red strip with+ * a bin, ticks past the threshold, and slides out before [onRemove]. The Classic pages' gesture+ * on the Immersive page colour.+ */+@Composable+internal fun ImmersiveSwipeToRemove(key: Any, onRemove: () -> Unit, content: @Composable () -> Unit) {+ val haptic = LocalHapticFeedback.current+ val scope = rememberCoroutineScope()+ val reduceMotion = rememberReduceMotion()+ val threshold = with(LocalDensity.current) { 120.dp.toPx() }+ val offset = remember(key) { Animatable(0f) }+ var armed by remember(key) { mutableStateOf(false) }+ var width by remember { mutableFloatStateOf(0f) }++ Box(modifier = Modifier.fillMaxWidth().onSizeChanged { width = it.width.toFloat() }) {+ if (offset.value < 0f) {+ Box(+ contentAlignment = Alignment.CenterEnd,+ modifier = Modifier+ .matchParentSize()+ .background(if (armed) ImmersiveDestructive else ImmersiveDestructive.copy(alpha = 0.6f)),+ ) {+ Icon(+ Icons.Rounded.DeleteOutline,+ contentDescription = stringResource(R.string.context_menu_undownload),+ tint = Color.White,+ modifier = Modifier.padding(horizontal = 24.dp).size(26.dp),+ )+ }+ }+ Box(+ modifier = Modifier+ .offset { IntOffset(offset.value.roundToInt(), 0) }+ .background(Immersive.Page)+ .pointerInput(key) {+ detectHorizontalDragGestures(+ onDragEnd = {+ if (armed) scope.launch {+ offset.animateTo(-width.coerceAtLeast(threshold), if (reduceMotion) snap() else tween(180))+ onRemove()+ } else scope.launch { offset.animateTo(0f, if (reduceMotion) snap() else spring()) }+ armed = false+ },+ onDragCancel = {+ armed = false+ scope.launch { offset.animateTo(0f, if (reduceMotion) snap() else spring()) }+ },+ ) { change, dx ->+ change.consume()+ // Leftwards only (right to left).+ val next = (offset.value + dx).coerceIn(-(width.coerceAtLeast(threshold)), 0f)+ scope.launch { offset.snapTo(next) }+ val nowArmed = -next >= threshold+ if (nowArmed && !armed) haptic.performHapticFeedback(HapticFeedbackType.GestureThresholdActivate)+ armed = nowArmed+ }+ },+ ) { content() }+ }+}++/** A name prompt (new playlist, rename a folder or a playlist) in the Immersive look. */+@Composable+internal fun ImmersiveNameDialog(+ title: String,+ initial: String,+ confirm: String,+ onDismiss: () -> Unit,+ onConfirm: (String) -> Unit,+) {+ var text by remember { mutableStateOf(initial) }+ val focus = remember { FocusRequester() }+ LaunchedEffect(Unit) { runCatching { focus.requestFocus() } }+ AlertDialog(+ onDismissRequest = onDismiss,+ containerColor = Immersive.Raised,+ title = { Text(title, style = Immersive.Headline) },+ text = {+ Box(+ Modifier+ .fillMaxWidth()+ .background(Color.White.copy(alpha = 0.08f), Immersive.Button)+ .padding(horizontal = 14.dp, vertical = 12.dp),+ ) {+ if (text.isEmpty()) {+ Text(+ stringResource(R.string.immersive_pages_name_hint),+ style = Immersive.Body.copy(color = Immersive.TextSecondary),+ )+ }+ BasicTextField(+ value = text,+ onValueChange = { text = it },+ singleLine = true,+ textStyle = Immersive.Body,+ cursorBrush = SolidColor(Immersive.Accent),+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),+ keyboardActions = KeyboardActions(onDone = { if (text.isNotBlank()) onConfirm(text.trim()) }),+ modifier = Modifier.fillMaxWidth().focusRequester(focus),+ )+ }+ },+ confirmButton = {+ TextButton(enabled = text.isNotBlank(), onClick = { onConfirm(text.trim()) }) {+ Text(confirm, style = Immersive.BodyStrong.copy(color = Immersive.Accent))+ }+ },+ dismissButton = {+ TextButton(onClick = onDismiss) {+ Text(stringResource(R.string.add_to_playlist_button_cancel), style = Immersive.BodyStrong)+ }+ },+ )+}++/** A bottom sheet on the [Immersive.Raised] fill, the frame of every menu of these pages. */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+internal fun ImmersiveSheet(onDismiss: () -> Unit, content: @Composable ColumnScope.() -> Unit) {+ ModalBottomSheet(onDismissRequest = onDismiss, containerColor = Immersive.Raised) {+ Column(Modifier.navigationBarsPadding().padding(bottom = 12.dp), content = content)+ }+}++/** One entry of a sheet: a glyph, a label and, under it, an optional [detail] line. */+@Composable+internal fun ImmersiveSheetRow(+ icon: ImageVector,+ label: String,+ onClick: () -> Unit,+ detail: String? = null,+ destructive: Boolean = false,+) {+ val tint = if (destructive) ImmersiveDestructive else Immersive.Text+ Row(+ verticalAlignment = Alignment.CenterVertically,+ modifier = Modifier+ .fillMaxWidth()+ .heightIn(min = 60.dp)+ .immersiveClickable(onClick = { Haptics.click(); onClick() }, pressedScale = 0.98f)+ .padding(horizontal = Immersive.Gutter, vertical = 8.dp),+ ) {+ Icon(icon, contentDescription = null, tint = if (destructive) tint else Immersive.TextSecondary, modifier = Modifier.size(24.dp))+ Spacer(Modifier.width(16.dp))+ Column {+ Text(label, style = Immersive.Body.copy(color = tint), maxLines = 1, overflow = TextOverflow.Ellipsis)+ if (detail != null) Text(detail, style = Immersive.Caption)+ }+ }+}++/**+ * The frame of every page here: the black page with iOS-style rubber-band overscroll on all the+ * lists inside it.+ */+@Composable+internal fun ImmersivePageFrame(content: @Composable BoxScope.() -> Unit) {+ CompositionLocalProvider(LocalOverscrollFactory provides rememberImmersiveOverscrollFactory()) {+ Box(Modifier.fillMaxSize().background(Immersive.Page), content = content)+ }+}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.ktnew file mode 100644index 00000000..08b08783--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveRecentlyPlayedScreen.kt@@ -0,0 +1,408 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * app/src/main/java/com/music/bitchord/ui/screens/HistoryScreen.kt at edc1e6f.+ * Modified for Myspoti, 2026-10.+ */+package com.music.spotui.ui.immersive.pages++import androidx.compose.animation.core.Spring+import androidx.compose.animation.core.VisibilityThreshold+import androidx.compose.animation.core.animateFloatAsState+import androidx.compose.animation.core.snap+import androidx.compose.animation.core.spring+import androidx.compose.foundation.background+import androidx.compose.foundation.border+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.itemsIndexed+import androidx.compose.foundation.lazy.rememberLazyListState+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.rounded.Favorite+import androidx.compose.material.icons.rounded.KeyboardArrowDown+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.derivedStateOf+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.draw.rotate+import androidx.compose.ui.graphics.Brush+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.IntOffset+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import androidx.navigation.NavController+import app.myspoti.api.MediaKind+import app.myspoti.api.RecentEntry+import app.myspoti.api.RecentGroup+import app.myspoti.api.RecentItem+import app.myspoti.api.RecentSection+import app.myspoti.api.best+import app.myspoti.api.groupRecents+import app.myspoti.engine.R+import app.myspoti.host.android.MyspotiRuntime+import com.music.spotui.di.Haptics+import com.music.spotui.di.SongPlayer+import com.music.spotui.ui.components.FastScrollbar+import com.music.spotui.ui.immersive.Immersive+import com.music.spotui.ui.immersive.components.ImmersiveCover+import com.music.spotui.ui.immersive.components.ImmersiveMessageState+import com.music.spotui.ui.immersive.components.ImmersiveRowDividerInset+import com.music.spotui.ui.immersive.components.ImmersiveSongRowSkeleton+import com.music.spotui.ui.immersive.components.SectionHeader+import com.music.spotui.ui.immersive.components.immersiveClickable+import com.music.spotui.ui.immersive.components.immersiveSongListSkeleton+import com.music.spotui.ui.immersive.screens.ImmersiveChip+import com.music.spotui.ui.immersive.screens.ImmersiveChipRow+import com.music.spotui.ui.immersive.screens.ImmersiveRowDivider+import com.music.spotui.ui.immersive.shell.ImmersiveTopBar+import com.music.spotui.ui.immersive.shell.immersiveHazeSource+import com.music.spotui.ui.immersive.shell.immersiveLargeTitle+import com.music.spotui.ui.immersive.shell.immersiveTopContentPadding+import com.music.spotui.ui.look.rememberReduceMotion+import com.music.spotui.ui.navigation.Routes+import com.music.spotui.ui.navigation.albumRoute+import com.music.spotui.ui.navigation.artistRoute+import com.music.spotui.ui.navigation.playlistRoute+import com.music.spotui.ui.navigation.showRoute+import java.time.Instant+import java.time.LocalDate+import java.time.ZoneId+import java.time.format.DateTimeFormatter+import java.util.Locale++/** Rows per request: what the Web Player asks for its own list page. */+private const val PAGE = 50++/** The Liked Songs collection's uri, the row badged with a heart. */+private const val LIKED_URI = "spotify:collection:tracks"++/** The saved-episodes collection: a podcast context whose page is the app's own Episodes screen. */+private const val YOUR_EPISODES_URI = "spotify:collection:your-episodes"++private val ChevronRing = Color.White.copy(alpha = 0.35f)++/**+ * "Recents" of the Immersive look, replacing the Classic `RecentlyPlayedScreen`: a plain list+ * with a large title (no single cover stands for a history), a Music / Podcasts pill pair, then+ * the plays of every device grouped by context under their day. A row opens its album, playlist,+ * artist or show; its chevron unfolds the plays behind it, each of which plays with the context+ * as its queue. The next pages load as the end comes into view.+ */+@Composable+fun ImmersiveRecentlyPlayedScreen(navController: NavController) {+ var entries by remember { mutableStateOf<List<RecentEntry>?>(null) }+ var failure by remember { mutableStateOf<String?>(null) }+ // The list holds thousands of rows: the next pages load as the end comes into view.+ var nextOffset by remember { mutableStateOf<Int?>(null) }+ var loadingMore by remember { mutableStateOf(false) }+ var podcasts by remember { mutableStateOf(false) }+ var expanded by remember { mutableStateOf(emptySet<String>()) }+ var generation by remember { mutableStateOf(0) }+ val listState = rememberLazyListState()+ val reduceMotion = rememberReduceMotion()++ LaunchedEffect(generation) {+ failure = null+ runCatching { MyspotiRuntime.api.recents.recentEntries(0, PAGE) }+ .onSuccess { page ->+ entries = page.items+ nextOffset = page.nextOffset+ }+ .onFailure { failure = it.message ?: it.toString() }+ }++ val atEnd by remember {+ derivedStateOf {+ val last = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: return@derivedStateOf false+ last >= listState.layoutInfo.totalItemsCount - 5+ }+ }+ LaunchedEffect(atEnd, nextOffset) {+ val offset = nextOffset ?: return@LaunchedEffect+ if (!atEnd || loadingMore) return@LaunchedEffect+ loadingMore = true+ runCatching { MyspotiRuntime.api.recents.recentEntries(offset, PAGE) }+ .onSuccess { page ->+ entries = entries.orEmpty() + page.items+ nextOffset = page.nextOffset+ }+ loadingMore = false+ }++ // Grouping runs on the raw rows, then the pill drops what the tab does not show: a heading+ // whose rows are all gone disappears with them.+ val sections = remember(entries, podcasts) {+ groupRecents(entries.orEmpty()).mapNotNull { section ->+ val groups = section.groups.filter { it.music != podcasts }+ if (groups.isEmpty()) null else RecentSection(section.dayMs, groups)+ }+ }++ val title = stringResource(R.string.recents_title)+ ImmersivePageFrame {+ LazyColumn(+ state = listState,+ contentPadding = PaddingValues(top = immersiveTopContentPadding(), bottom = Immersive.BottomChrome),+ modifier = Modifier.fillMaxSize().immersiveHazeSource(),+ ) {+ immersiveLargeTitle(title)+ item(key = "recents:pills", contentType = "pills") {+ ImmersiveChipRow {+ ImmersiveChip(stringResource(R.string.recents_filter_music), selected = !podcasts) { podcasts = false }+ ImmersiveChip(stringResource(R.string.recents_filter_podcasts), selected = podcasts) { podcasts = true }+ }+ }+ when {+ entries == null && failure != null -> item(key = "recents:failed") {+ ImmersiveMessageState(+ message = stringResource(R.string.recently_played_failed, failure.orEmpty()),+ actionLabel = stringResource(R.string.home_retry),+ onAction = { generation++ },+ )+ }+ entries == null -> immersiveSongListSkeleton(count = 10, keyPrefix = "skeleton:recents")+ sections.isEmpty() -> item(key = "recents:empty") {+ ImmersiveMessageState(stringResource(R.string.recently_played_empty))+ }+ else -> {+ val place = if (reduceMotion) null else spring<IntOffset>(+ stiffness = Spring.StiffnessMediumLow,+ visibilityThreshold = IntOffset.VisibilityThreshold,+ )+ sections.forEach { section ->+ item(key = "day:${section.dayMs}") {+ SectionHeader(+ title = dayLabel(section.dayMs),+ modifier = Modifier.animateItem(placementSpec = place).padding(top = 8.dp),+ )+ }+ section.groups.forEachIndexed { groupIndex, group ->+ val key = group.context.uri+ item(key = "row:$key") {+ Column(Modifier.animateItem(placementSpec = place)) {+ GroupRow(+ group = group,+ expanded = key in expanded,+ onToggle = {+ Haptics.click()+ expanded = if (key in expanded) expanded - key else expanded + key+ },+ onOpen = { openContext(group.context, navController) },+ )+ if (groupIndex < section.groups.lastIndex && key !in expanded) {+ ImmersiveRowDivider(ImmersiveRowDividerInset)+ }+ }+ }+ if (key in expanded) {+ itemsIndexed(+ group.plays,+ key = { index, play -> "play:$key:$index:${play.uri}" },+ ) { _, play ->+ // Unfolded plays fade in and push the rows below down.+ PlayRow(play, Modifier.animateItem(placementSpec = place)) {+ SongPlayer.playSong(playUri(play), contextUri = group.context.uri)+ }+ }+ }+ }+ }+ if (nextOffset != null) item(key = "recents:more") { ImmersiveSongRowSkeleton(index = 1) }+ }+ }+ }+ FastScrollbar(listState, Modifier.align(Alignment.CenterEnd))+ ImmersiveTopBar(title = title, listState = listState, onBack = { navController.navigateUp() })+ }+}++/**+ * One context of the list: its cover, its count, its type and creators, and the round chevron+ * that expands it in place. The row itself opens the context.+ */+@Composable+private fun GroupRow(group: RecentGroup, expanded: Boolean, onToggle: () -> Unit, onOpen: () -> Unit) {+ val reduceMotion = rememberReduceMotion()+ val rotation by animateFloatAsState(+ targetValue = if (expanded) 180f else 0f,+ animationSpec = if (reduceMotion) snap() else spring(stiffness = Spring.StiffnessMediumLow),+ label = "recents chevron",+ )+ val artist = group.context.kind == MediaKind.ARTIST+ Row(+ verticalAlignment = Alignment.CenterVertically,+ modifier = Modifier+ .fillMaxWidth()+ .immersiveClickable(onClick = onOpen, pressedScale = 0.98f)+ .padding(horizontal = Immersive.Gutter, vertical = 4.dp),+ ) {+ RecentCover(group.context, round = artist)+ Column(Modifier.padding(start = 14.dp).weight(1f)) {+ // A context the server could not name (a withdrawn album) still reads: its count is+ // the only thing left to title the row with, and the subtitle line is then dropped+ // instead of repeating the count there.+ val count = countLabel(group.count, group.saved)+ Text(+ text = group.context.title.ifBlank { count },+ style = Immersive.Body.copy(fontWeight = FontWeight.Medium),+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )+ if (group.context.title.isNotBlank()) {+ Text(groupSubtitle(group), style = Immersive.Subhead, maxLines = 1, overflow = TextOverflow.Ellipsis)+ }+ }+ Box(+ Modifier+ .padding(start = 8.dp)+ .size(30.dp)+ .clip(CircleShape)+ .border(1.dp, ChevronRing, CircleShape)+ .immersiveClickable(onClick = onToggle, pressedScale = 0.9f),+ contentAlignment = Alignment.Center,+ ) {+ Icon(+ Icons.Rounded.KeyboardArrowDown,+ contentDescription = stringResource(if (expanded) R.string.recents_collapse else R.string.recents_expand),+ tint = Immersive.Text,+ modifier = Modifier.size(20.dp).rotate(rotation),+ )+ }+ }+}++/** A play of an expanded context: tapping it plays that track with the context as its queue. */+@Composable+private fun PlayRow(item: RecentItem, modifier: Modifier = Modifier, onClick: () -> Unit) {+ Row(+ verticalAlignment = Alignment.CenterVertically,+ modifier = modifier+ .fillMaxWidth()+ .immersiveClickable(onClick = onClick, pressedScale = 0.98f)+ .padding(start = Immersive.Gutter + 12.dp, end = Immersive.Gutter, top = 4.dp, bottom = 4.dp),+ ) {+ ImmersiveCover(item.images.best(300)?.url, Modifier.size(40.dp), Immersive.CoverSmall)+ Column(Modifier.padding(start = 12.dp).weight(1f)) {+ Text(item.title, style = Immersive.Body.copy(fontSize = 14.sp), maxLines = 1, overflow = TextOverflow.Ellipsis)+ item.subtitle?.let { Text(it, style = Immersive.Caption, maxLines = 1, overflow = TextOverflow.Ellipsis) }+ }+ }+}++/**+ * The context's artwork. Artists are round, everything else a square with the page's corners;+ * Liked Songs carries a heart badge over its cover.+ */+@Composable+private fun RecentCover(context: RecentItem, round: Boolean) {+ Box(Modifier.size(52.dp)) {+ ImmersiveCover(+ url = context.images.best(300)?.url,+ modifier = Modifier.size(52.dp),+ shape = if (round) CircleShape else Immersive.CoverSmall,+ )+ if (context.uri == LIKED_URI || context.kind == MediaKind.COLLECTION) {+ Box(+ Modifier+ .align(Alignment.BottomStart)+ .size(22.dp)+ .clip(Immersive.CoverSmall)+ .background(Brush.linearGradient(listOf(Color(0xFF8E7CFF), Color(0xFFC9B8FF)))),+ contentAlignment = Alignment.Center,+ ) {+ Icon(+ Icons.Rounded.Favorite,+ contentDescription = stringResource(R.string.collection_liked_songs_title),+ tint = Color.White,+ modifier = Modifier.size(13.dp),+ )+ }+ }+ }+}++/** "[N] tracks played • [Type] • [creators]", with its own wording for saved rows. */+@Composable+private fun groupSubtitle(group: RecentGroup): String {+ val parts = buildList {+ add(countLabel(group.count, group.saved))+ add(group.context.typeLabel?.takeIf { it.isNotBlank() } ?: kindLabel(group.context.kind))+ // Liked Songs and artists show no creator line.+ if (!group.saved && group.context.kind != MediaKind.ARTIST) group.context.subtitle?.let { add(it) }+ }+ return parts.filter { it.isNotBlank() }.joinToString(" • ")+}++@Composable+private fun countLabel(count: Int, saved: Boolean): String = when {+ saved && count == 1 -> stringResource(R.string.recents_saved_one)+ saved -> stringResource(R.string.recents_saved_many, count)+ count == 1 -> stringResource(R.string.recents_played_one)+ else -> stringResource(R.string.recents_played_many, count)+}++@Composable+private fun dayLabel(dayMs: Long?): String {+ if (dayMs == null) return ""+ val date = Instant.ofEpochMilli(dayMs).atZone(ZoneId.systemDefault()).toLocalDate()+ val today = LocalDate.now()+ return when (date) {+ today -> stringResource(R.string.recents_today)+ today.minusDays(1) -> stringResource(R.string.recents_yesterday)+ // Older days print as day and short month, in the phone's language.+ else -> date.format(DateTimeFormatter.ofPattern("d MMM", Locale.getDefault()))+ }+}++@Composable+private fun kindLabel(kind: MediaKind): String = when (kind) {+ MediaKind.PLAYLIST -> stringResource(R.string.assisted_curation_search_playlist)+ MediaKind.ALBUM -> stringResource(R.string.album_type_album)+ MediaKind.ARTIST -> stringResource(R.string.artist_subtitle)+ MediaKind.SHOW -> stringResource(R.string.ad_category_title_podcasts)+ MediaKind.EPISODE -> stringResource(R.string.your_episodes_title)+ else -> ""+}++/** The uri a play row hands the player: episodes are queued by id, tracks by their own uri. */+private fun playUri(item: RecentItem): String =+ if (item.kind == MediaKind.EPISODE) "episode:" + item.uri.substringAfterLast(':') else item.uri++/**+ * Opens the context the row stands for. Liked Songs and Your Episodes are collections with their+ * own pages, the rest go to their playlist, album, artist or show page; a lone track (a row with+ * no context) plays.+ */+private fun openContext(context: RecentItem, navController: NavController) {+ val id = context.uri.substringAfterLast(':')+ when {+ context.uri == LIKED_URI || context.kind == MediaKind.COLLECTION -> navController.navigate(Routes.Liked.route)+ context.uri == YOUR_EPISODES_URI -> navController.navigate(Routes.Episodes.route)+ context.kind == MediaKind.PLAYLIST -> navController.navigate(playlistRoute(id, context.title))+ context.kind == MediaKind.ALBUM -> navController.navigate(albumRoute(context.title, context.subtitle.orEmpty(), id))+ context.kind == MediaKind.ARTIST -> navController.navigate(artistRoute(context.title, id))+ context.kind == MediaKind.SHOW -> navController.navigate(showRoute(id, context.title))+ context.kind == MediaKind.TRACK || context.kind == MediaKind.EPISODE ->+ SongPlayer.playSong(playUri(context), contextUri = null)+ else -> Unit+ }+}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.ktnew file mode 100644index 00000000..f23dc19d--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt@@ -0,0 +1,619 @@+package com.music.spotui.ui.immersive.pages++import androidx.activity.compose.BackHandler+import androidx.compose.animation.AnimatedContent+import androidx.compose.animation.ContentTransform+import androidx.compose.animation.core.Spring+import androidx.compose.animation.core.spring+import androidx.compose.animation.core.tween+import androidx.compose.animation.fadeIn+import androidx.compose.animation.fadeOut+import androidx.compose.animation.slideInHorizontally+import androidx.compose.animation.slideOutHorizontally+import androidx.compose.animation.togetherWith+import androidx.compose.foundation.background+import androidx.compose.foundation.border+import androidx.compose.foundation.layout.Arrangement+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.material.icons.Icons+import androidx.compose.material.icons.rounded.Download+import androidx.compose.material.icons.rounded.Extension+import androidx.compose.material.icons.rounded.Palette+import androidx.compose.material.icons.rounded.PlayArrow+import androidx.compose.material.icons.rounded.SignalCellularAlt+import androidx.compose.material.icons.rounded.Info+import androidx.compose.material3.AlertDialog+import androidx.compose.material3.Text+import androidx.compose.material3.TextButton+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateListOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.saveable.rememberSaveable+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.semantics.Role+import androidx.compose.ui.semantics.contentDescription+import androidx.compose.ui.semantics.role+import androidx.compose.ui.semantics.semantics+import androidx.compose.ui.unit.IntOffset+import androidx.compose.ui.unit.dp+import androidx.compose.foundation.clickable+import androidx.compose.ui.graphics.Color+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import androidx.navigation.NavController+import app.myspoti.engine.R+import com.music.spotui.data.preferences.DownloadQuality+import com.music.spotui.data.preferences.StreamingQuality+import com.music.spotui.data.preferences.getDownloadQuality+import com.music.spotui.data.preferences.getStreamingQuality+import com.music.spotui.data.preferences.setDownloadQuality+import com.music.spotui.data.preferences.setStreamingQuality+import com.music.spotui.ui.immersive.Immersive+import com.music.spotui.ui.look.rememberReduceMotion+import com.music.spotui.ui.navigation.Routes+import com.music.spotui.ui.screens.installedRoute+import com.music.spotui.ui.screens.shareDiagnosticReport+import kotlinx.coroutines.launch++/** Where the Immersive Settings are: the list of categories, one category, or a choice inside it. */+private enum class SettingsPage { Root, Playback, StreamingWifi, StreamingCell, Crossfade, Downloads, DownloadQuality, Data, Display, Look, Rotation, Language, App }++private val StreamingChoices = listOf(+ Triple(StreamingQuality.AUTO, R.string.quality_streaming_auto, R.string.quality_streaming_auto_detail),+ Triple(StreamingQuality.LOW, R.string.quality_streaming_low, R.string.quality_streaming_low_detail),+ Triple(StreamingQuality.NORMAL, R.string.quality_streaming_normal, R.string.quality_streaming_normal_detail),+ Triple(StreamingQuality.HIGH, R.string.quality_streaming_high, R.string.quality_streaming_high_detail),+)++private val DownloadChoices = listOf(+ Triple(DownloadQuality.OFF, R.string.quality_download_off, R.string.quality_download_off_detail),+ Triple(DownloadQuality.SMALL, R.string.quality_download_small, R.string.quality_download_small_detail),+ Triple(DownloadQuality.CD, R.string.quality_download_cd, R.string.quality_download_cd_detail),+ Triple(DownloadQuality.HI_RES, R.string.quality_download_hires, R.string.quality_download_hires_detail),+ Triple(DownloadQuality.ASK, R.string.quality_download_ask, R.string.quality_download_ask_detail),+)++/**+ * Settings of the Immersive look, replacing the Classic `SettingsScreen`: the same preferences+ * and actions (every switch writes through the same stores) as iOS-style inset groups, one page+ * per category and one for each choice (quality, language, look...). A pushed page slides in on a+ * spring and back leaves it; with "reduce motion" they cross-fade.+ */+@Composable+fun ImmersiveSettingsScreen(navController: NavController) {+ // The pages pushed so far, so back pops one before it leaves Settings.+ val stack = remember { mutableStateListOf<SettingsPage>() }+ val page = stack.lastOrNull() ?: SettingsPage.Root+ val reduce = rememberReduceMotion()+ var pushing by remember { mutableStateOf(true) }+ val pop: () -> Unit = { pushing = false; stack.removeAt(stack.lastIndex) }+ BackHandler(enabled = stack.isNotEmpty(), onBack = pop)+ val open: (SettingsPage) -> Unit = { pushing = true; stack += it }+ val back: () -> Unit = { if (stack.isNotEmpty()) pop() else navController.popBackStack() }+ AnimatedContent(+ targetState = page,+ transitionSpec = {+ when {+ reduce -> fadeIn(tween(150)) togetherWith fadeOut(tween(150))+ !pushing ->+ (slideInHorizontally(tween(320)) { -it / 3 } + fadeIn(tween(320))) togetherWith+ (slideOutHorizontally(tween(320)) { 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)))+ }+ },+ label = "settings pages",+ ) { p ->+ when (p) {+ SettingsPage.Root -> SettingsRoot(navController, open, back)+ SettingsPage.Playback -> PlaybackPage(open, back)+ SettingsPage.StreamingWifi -> StreamingPage(cellular = false, back)+ SettingsPage.StreamingCell -> StreamingPage(cellular = true, back)+ SettingsPage.Crossfade -> CrossfadePage(back)+ SettingsPage.Downloads -> DownloadsPage(navController, open, back)+ SettingsPage.DownloadQuality -> DownloadQualityPage(back)+ SettingsPage.Data -> DataPage(back)+ SettingsPage.Display -> DisplayPage(open, back)+ SettingsPage.Look -> LookPage(back)+ SettingsPage.Rotation -> RotationPage(back)+ SettingsPage.Language -> LanguagePage(back)+ SettingsPage.App -> AppPage(navController, back)+ }+ }+}++@Composable+private fun SettingsRoot(navController: NavController, open: (SettingsPage) -> Unit, back: () -> Unit) {+ val registry by com.music.spotui.extensions.Extensions.registry.collectAsStateWithLifecycle()+ val withSettings = registry.extensions.mapNotNull { e ->+ com.music.spotui.extensions.Extensions.manifest(e.id)?.settings?.takeIf { it.isNotEmpty() }?.let { e to it }+ }+ ImmersivePage(title = stringResource(R.string.settings_title), onBack = back) {+ immersiveGroup("root") {+ row { ImmersiveGroupRow(stringResource(R.string.settings_section_playback), icon = Icons.Rounded.PlayArrow, chevron = true, onClick = { open(SettingsPage.Playback) }) }+ row { ImmersiveGroupRow(stringResource(R.string.settings_section_downloads), icon = Icons.Rounded.Download, chevron = true, onClick = { open(SettingsPage.Downloads) }) }+ row { ImmersiveGroupRow(stringResource(R.string.settings_section_data), icon = Icons.Rounded.SignalCellularAlt, chevron = true, onClick = { open(SettingsPage.Data) }) }+ row { ImmersiveGroupRow(stringResource(R.string.settings_section_display), icon = Icons.Rounded.Palette, chevron = true, onClick = { open(SettingsPage.Display) }) }+ row { ImmersiveGroupRow(stringResource(R.string.settings_section_app), icon = Icons.Rounded.Info, chevron = true, onClick = { open(SettingsPage.App) }) }+ }+ immersiveGroup("extensions") {+ row {+ ImmersiveGroupRow(+ stringResource(R.string.extensions_title), detail = stringResource(R.string.extensions_row_detail),+ icon = Icons.Rounded.Extension, chevron = true,+ onClick = { navController.navigate(Routes.Extensions.route) },+ )+ }+ }+ // The installed extensions that declare settings, each opening its page.+ immersiveGroup("extension-settings", headerRes = if (withSettings.isEmpty()) null else R.string.extensions_title) {+ withSettings.forEach { (e, settings) ->+ row {+ ImmersiveGroupRow(+ e.name, detail = settings.joinToString { it.label }, chevron = true,+ onClick = { navController.navigate(installedRoute(e.id)) },+ )+ }+ }+ }+ }+}++// ---------------------------------------------------------------- Playback++@Composable+private fun PlaybackPage(open: (SettingsPage) -> Unit, back: () -> Unit) {+ val ctx = LocalContext.current+ val wifi = getStreamingQuality(ctx, false)+ val cell = getStreamingQuality(ctx, true)+ val label = { q: StreamingQuality -> StreamingChoices.first { it.first == q }.second }+ var canvasWifiOnly by remember { mutableStateOf(com.music.spotui.data.preferences.isCanvasWifiOnly(ctx)) }+ var keepPlaying by remember { mutableStateOf(app.myspoti.host.android.PlaybackService.keepsPlayingOnClose(ctx)) }+ var wordSync by remember { mutableStateOf(com.music.spotui.data.preferences.isLyricsWordSync(ctx)) }+ val crossfade = com.music.spotui.data.preferences.CrossfadePref.seconds+ ImmersivePage(title = stringResource(R.string.settings_section_playback), onBack = back) {+ immersiveGroup("quality", footerRes = R.string.quality_streaming_detail) {+ row { ImmersiveGroupRow(stringResource(R.string.quality_streaming_wifi_title), value = stringResource(label(wifi)), chevron = true, onClick = { open(SettingsPage.StreamingWifi) }) }+ row { ImmersiveGroupRow(stringResource(R.string.quality_streaming_cell_title), value = stringResource(label(cell)), chevron = true, onClick = { open(SettingsPage.StreamingCell) }) }+ }+ immersiveGroup("playback") {+ row {+ ImmersiveSwitchRow(+ stringResource(R.string.settings_autoplay_title),+ checked = com.music.spotui.data.preferences.AutoplayPref.on,+ onChecked = { com.music.spotui.data.preferences.AutoplayPref.set(ctx, it) },+ detail = stringResource(R.string.settings_autoplay_detail),+ )+ }+ row {+ ImmersiveGroupRow(+ stringResource(R.string.settings_crossfade_title), detail = stringResource(R.string.settings_crossfade_detail),+ value = if (crossfade == 0) stringResource(R.string.settings_crossfade_off) else stringResource(R.string.settings_crossfade_seconds, crossfade),+ chevron = true, onClick = { open(SettingsPage.Crossfade) },+ )+ }+ row {+ ImmersiveSwitchRow(+ stringResource(R.string.settings_keep_playing_title), checked = keepPlaying,+ onChecked = { keepPlaying = it; app.myspoti.host.android.PlaybackService.setKeepsPlayingOnClose(ctx, it) },+ detail = stringResource(R.string.settings_keep_playing_detail),+ )+ }+ }+ immersiveGroup("visuals") {+ row {+ ImmersiveSwitchRow(+ stringResource(R.string.canvas_wifi_only), checked = canvasWifiOnly,+ onChecked = { canvasWifiOnly = it; com.music.spotui.data.preferences.setCanvasWifiOnly(ctx, it) },+ detail = stringResource(R.string.canvas_wifi_only_detail),+ )+ }+ // Lyrics: word by word (karaoke) first, or line by line with Spotify's first.+ row {+ ImmersiveSwitchRow(+ stringResource(R.string.lyrics_word_sync_title), checked = wordSync,+ onChecked = {+ wordSync = it+ com.music.spotui.data.preferences.setLyricsWordSync(ctx, it)+ com.music.spotui.data.api.LyricsApi.wordSync = it+ com.music.spotui.data.api.LyricsApi.forgetAll()+ },+ detail = stringResource(if (wordSync) R.string.lyrics_word_sync_on else R.string.lyrics_word_sync_off),+ )+ }+ }+ }+}++@Composable+private fun StreamingPage(cellular: Boolean, back: () -> Unit) {+ val ctx = LocalContext.current+ var current by remember(cellular) { mutableStateOf(getStreamingQuality(ctx, cellular)) }+ ImmersivePage(+ title = stringResource(if (cellular) R.string.quality_streaming_cell_title else R.string.quality_streaming_wifi_title),+ onBack = back,+ ) {+ immersiveGroup("choices", footerRes = R.string.quality_streaming_detail) {+ StreamingChoices.forEach { (value, label, detail) ->+ row {+ ImmersiveChoiceRow(stringResource(label), selected = current == value, detail = stringResource(detail),+ onClick = { current = value; setStreamingQuality(ctx, value, cellular) })+ }+ }+ }+ }+}++@Composable+private fun CrossfadePage(back: () -> Unit) {+ val ctx = LocalContext.current+ val pref = com.music.spotui.data.preferences.CrossfadePref+ ImmersivePage(title = stringResource(R.string.settings_crossfade_title), onBack = back) {+ immersiveGroup("choices", footerRes = R.string.settings_crossfade_detail) {+ for (v in listOf(0, 3, 6, 9, 12)) {+ row {+ ImmersiveChoiceRow(+ if (v == 0) stringResource(R.string.settings_crossfade_off) else stringResource(R.string.settings_crossfade_seconds, v),+ selected = pref.seconds == v, onClick = { pref.set(ctx, v) },+ )+ }+ }+ }+ }+}++// ---------------------------------------------------------------- Downloads++@Composable+private fun DownloadsPage(navController: NavController, open: (SettingsPage) -> Unit, back: () -> Unit) {+ val ctx = LocalContext.current+ val quality = getDownloadQuality(ctx)+ var ask by remember { mutableStateOf(false) }+ val size = android.text.format.Formatter.formatShortFileSize(ctx, com.music.spotui.data.offline.OfflineStore.totalBytes())+ ImmersivePage(title = stringResource(R.string.settings_section_downloads), onBack = back) {+ immersiveGroup("quality", footerRes = R.string.quality_download_detail) {+ row {+ ImmersiveGroupRow(stringResource(R.string.quality_download_title),+ value = stringResource(DownloadChoices.first { it.first == quality }.second), chevron = true,+ onClick = { open(SettingsPage.DownloadQuality) })+ }+ }+ // Where downloads come from: a download-source extension.+ immersiveGroup("source") {+ row {+ ImmersiveGroupRow(+ stringResource(R.string.downloads_source_row_title),+ detail = stringResource(+ if (com.music.spotui.extensions.Extensions.hasDownloadSource()) R.string.downloads_source_row_on+ else R.string.downloads_source_row_off,+ ),+ chevron = true, onClick = { navController.navigate(Routes.Extensions.route) },+ )+ }+ }+ if (com.music.spotui.data.offline.OfflineStore.tracks.isNotEmpty()) immersiveGroup("remove") {+ row {+ ImmersiveGroupRow(+ stringResource(R.string.settings_item_remove_downloads_title), detail = stringResource(R.string.downloads_size, size),+ destructive = true, onClick = { ask = true },+ )+ }+ }+ }+ if (ask) AlertDialog(+ onDismissRequest = { ask = false },+ containerColor = Immersive.Raised,+ title = { Text(stringResource(R.string.settings_storage_remove_downloads_dialog_title), style = Immersive.Headline) },+ text = { Text(stringResource(R.string.playlist_entity_remove_download_dialog_description), style = Immersive.Subhead) },+ confirmButton = {+ TextButton(onClick = { ask = false; com.music.spotui.data.offline.OfflineDownloader.removeAll() }) {+ Text(stringResource(R.string.playlist_entity_remove_download_dialog_positive_button), color = ImmersiveDestructive)+ }+ },+ dismissButton = {+ TextButton(onClick = { ask = false }) { Text(stringResource(R.string.add_to_playlist_button_cancel), color = Immersive.Accent) }+ },+ )+}++@Composable+private fun DownloadQualityPage(back: () -> Unit) {+ val ctx = LocalContext.current+ var current by remember { mutableStateOf(getDownloadQuality(ctx)) }+ ImmersivePage(title = stringResource(R.string.quality_download_title), onBack = back) {+ immersiveGroup("choices", footerRes = R.string.quality_download_detail) {+ DownloadChoices.forEach { (value, label, detail) ->+ row {+ ImmersiveChoiceRow(stringResource(label), selected = current == value, detail = stringResource(detail),+ onClick = { current = value; setDownloadQuality(ctx, value) })+ }+ }+ }+ }+}++// ---------------------------------------------------------------- Data and battery++@Composable+private fun DataPage(back: () -> Unit) {+ val ctx = LocalContext.current+ val energy by app.myspoti.power.EnergySettings.state.collectAsStateWithLifecycle()+ // Battery optimization off = music and Connect keep going with the screen off.+ var exempt by remember { mutableStateOf(app.myspoti.power.BatteryExemption.isExempt(ctx)) }+ androidx.lifecycle.compose.LifecycleEventEffect(androidx.lifecycle.Lifecycle.Event.ON_RESUME) {+ exempt = app.myspoti.power.BatteryExemption.isExempt(ctx)+ }+ ImmersivePage(title = stringResource(R.string.settings_section_data), onBack = back) {+ immersiveGroup("data") {+ row {+ ImmersiveSwitchRow(stringResource(R.string.energy_saver_title), checked = energy.manualSaver,+ onChecked = app.myspoti.power.EnergySettings::setSaver, detail = stringResource(R.string.energy_saver_summary))+ }+ row {+ ImmersiveSwitchRow(stringResource(R.string.data_saver_title), checked = com.music.spotui.data.DataSaver.enabled,+ onChecked = com.music.spotui.data.DataSaver::set, detail = stringResource(R.string.data_saver_summary))+ }+ row {+ ImmersiveSwitchRow(+ stringResource(R.string.background_playback_title), checked = exempt,+ onChecked = {+ if (exempt) ctx.startActivity(android.content.Intent(android.provider.Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS))+ else app.myspoti.power.BatteryExemption.request(ctx)+ },+ detail = stringResource(if (exempt) R.string.background_playback_on else R.string.background_playback_off),+ )+ }+ }+ }+}++// ---------------------------------------------------------------- Display++@Composable+private fun DisplayPage(open: (SettingsPage) -> Unit, back: () -> Unit) {+ val ctx = LocalContext.current+ val energy by app.myspoti.power.EnergySettings.state.collectAsStateWithLifecycle()+ val look = com.music.spotui.data.preferences.LookPref.look+ val rotation = com.music.spotui.data.preferences.OrientationPref.mode+ val language = remember { com.music.spotui.data.AppLanguage.current(ctx) }+ val auto = stringResource(R.string.language_auto)+ ImmersivePage(title = stringResource(R.string.settings_section_display), onBack = back) {+ immersiveGroup("look") {+ row {+ ImmersiveGroupRow(+ stringResource(R.string.settings_look_title),+ value = stringResource(if (look == com.music.spotui.data.preferences.Look.CLASSIC) R.string.look_classic else R.string.look_immersive),+ chevron = true, onClick = { open(SettingsPage.Look) },+ )+ }+ row { AccentRow() }+ }+ immersiveGroup("display") {+ if (look == com.music.spotui.data.preferences.Look.IMMERSIVE) row {+ val glass = com.music.spotui.ui.immersive.shell.liquidGlassAvailability()+ val unsupported = glass == com.music.spotui.ui.immersive.shell.LiquidGlassAvailability.UNSUPPORTED+ ImmersiveSwitchRow(+ stringResource(R.string.settings_liquid_glass_title),+ checked = com.music.spotui.data.preferences.LiquidGlassPref.on && !unsupported,+ enabled = !unsupported,+ onChecked = { com.music.spotui.data.preferences.LiquidGlassPref.set(ctx, it) },+ detail = stringResource(+ when (glass) {+ com.music.spotui.ui.immersive.shell.LiquidGlassAvailability.UNSUPPORTED -> R.string.settings_liquid_glass_unsupported+ com.music.spotui.ui.immersive.shell.LiquidGlassAvailability.REDUCED -> R.string.settings_liquid_glass_reduced+ com.music.spotui.ui.immersive.shell.LiquidGlassAvailability.AVAILABLE -> R.string.settings_liquid_glass_detail+ },+ ),+ )+ }+ row {+ ImmersiveSwitchRow(stringResource(R.string.settings_amoled_theme), checked = energy.blackPreference,+ onChecked = app.myspoti.power.EnergySettings::setBlackBackground, detail = stringResource(R.string.settings_amoled_theme_subtitle))+ }+ row {+ ImmersiveSwitchRow(+ stringResource(R.string.settings_item_canvas_title),+ checked = energy.canvasEnabled && !energy.policy.saverEnabled,+ enabled = !energy.policy.saverEnabled,+ onChecked = app.myspoti.power.EnergySettings::setCanvasEnabled,+ detail = stringResource(if (energy.policy.saverEnabled) R.string.energy_saver_summary else R.string.video_settings_canvas_subtitle),+ )+ }+ row {+ ImmersiveSwitchRow(stringResource(R.string.settings_music_video_title), checked = com.music.spotui.data.preferences.MusicVideoPref.on,+ onChecked = { com.music.spotui.data.preferences.MusicVideoPref.set(ctx, it) }, detail = stringResource(R.string.settings_music_video_detail))+ }+ row {+ ImmersiveSwitchRow(stringResource(R.string.settings_solid_nav_title), checked = com.music.spotui.data.preferences.SolidNavBar.on,+ onChecked = { com.music.spotui.data.preferences.SolidNavBar.set(ctx, it) }, detail = stringResource(R.string.settings_solid_nav_detail))+ }+ }+ immersiveGroup("layout") {+ row {+ ImmersiveGroupRow(+ stringResource(R.string.settings_rotation_title),+ value = stringResource(rotationLabel(rotation)), chevron = true, onClick = { open(SettingsPage.Rotation) },+ )+ }+ row {+ ImmersiveGroupRow(+ stringResource(R.string.settings_item_app_language_title),+ value = if (language == com.music.spotui.data.AppLanguage.SYSTEM) auto else com.music.spotui.data.AppLanguage.nativeName(language),+ chevron = true, onClick = { open(SettingsPage.Language) },+ )+ }+ }+ }+}++private fun rotationLabel(mode: String): Int = when (mode) {+ com.music.spotui.data.preferences.OrientationPref.AUTO -> R.string.settings_rotation_auto+ com.music.spotui.data.preferences.OrientationPref.LANDSCAPE -> R.string.settings_rotation_landscape+ else -> R.string.settings_rotation_portrait+}++/** The app's accent colour, for everyone (the same palette the supporter sheet uses). */+@Composable+private fun AccentRow() {+ val ctx = LocalContext.current+ androidx.compose.foundation.layout.Column(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp)) {+ Text(stringResource(R.string.supporter_accent), style = Immersive.Body)+ Row(horizontalArrangement = Arrangement.spacedBy(14.dp), modifier = Modifier.padding(top = 10.dp)) {+ for (a in com.music.spotui.data.api.SupportReminder.Accent.entries) {+ val selected = com.music.spotui.data.api.SupportReminder.accent == a+ val name = stringResource(when (a) {+ com.music.spotui.data.api.SupportReminder.Accent.GREEN -> R.string.color_green+ com.music.spotui.data.api.SupportReminder.Accent.BLUE -> R.string.color_blue+ com.music.spotui.data.api.SupportReminder.Accent.PURPLE -> R.string.color_purple+ com.music.spotui.data.api.SupportReminder.Accent.PINK -> R.string.color_pink+ com.music.spotui.data.api.SupportReminder.Accent.ORANGE -> R.string.color_orange+ })+ Box(+ Modifier.size(38.dp)+ .semantics { contentDescription = name; role = Role.RadioButton }+ .clip(CircleShape).background(a.color)+ .then(if (selected) Modifier.border(3.dp, Immersive.Text, CircleShape) else Modifier)+ .clickable { com.music.spotui.data.api.SupportReminder.setAccent(ctx, a) },+ )+ }+ }+ }+}++@Composable+private fun LookPage(back: () -> Unit) {+ val ctx = LocalContext.current+ val current = com.music.spotui.data.preferences.LookPref.look+ ImmersivePage(title = stringResource(R.string.settings_look_title), onBack = back) {+ immersiveGroup("choices") {+ for (l in com.music.spotui.data.preferences.Look.entries) {+ val classic = l == com.music.spotui.data.preferences.Look.CLASSIC+ row {+ ImmersiveChoiceRow(+ stringResource(if (classic) R.string.look_classic else R.string.look_immersive),+ selected = current == l,+ detail = stringResource(if (classic) R.string.look_classic_detail else R.string.look_immersive_detail),+ onClick = { com.music.spotui.data.preferences.LookPref.set(ctx, l) },+ )+ }+ }+ }+ }+}++@Composable+private fun RotationPage(back: () -> Unit) {+ val ctx = LocalContext.current+ val pref = com.music.spotui.data.preferences.OrientationPref+ ImmersivePage(title = stringResource(R.string.settings_rotation_title), onBack = back) {+ immersiveGroup("choices") {+ for ((value, label) in listOf(+ pref.PORTRAIT to R.string.settings_rotation_portrait,+ pref.AUTO to R.string.settings_rotation_auto,+ pref.LANDSCAPE to R.string.settings_rotation_landscape,+ )) {+ row { ImmersiveChoiceRow(stringResource(label), selected = pref.mode == value, onClick = { pref.set(ctx, value) }) }+ }+ }+ }+}++/** "App language": Automatic (French or English) or any language with Spotify's labels. */+@Composable+private fun LanguagePage(back: () -> Unit) {+ val ctx = LocalContext.current+ val current = remember { com.music.spotui.data.AppLanguage.current(ctx) }+ val auto = stringResource(R.string.language_auto)+ fun label(tag: String) = if (tag == com.music.spotui.data.AppLanguage.SYSTEM) auto else com.music.spotui.data.AppLanguage.nativeName(tag)+ ImmersivePage(title = stringResource(R.string.settings_item_app_language_title), onBack = back) {+ immersiveGroup("choices", footerRes = R.string.language_partial_note) {+ com.music.spotui.data.AppLanguage.AVAILABLE.forEach { tag ->+ row {+ ImmersiveChoiceRow(+ label(tag), selected = tag == current,+ detail = if (tag == com.music.spotui.data.AppLanguage.SYSTEM) stringResource(R.string.language_auto_detail) else null,+ onClick = {+ if (tag != current) {+ com.music.spotui.data.AppLanguage.apply(ctx, tag)+ // Screens take the new language when the activity is rebuilt.+ generateSequence(ctx) { (it as? android.content.ContextWrapper)?.baseContext }+ .filterIsInstance<android.app.Activity>().firstOrNull()?.recreate()+ }+ },+ )+ }+ }+ }+ }+}++// ---------------------------------------------------------------- App++@Composable+private fun AppPage(navController: NavController, back: () -> Unit) {+ val ctx = LocalContext.current+ val scope = rememberCoroutineScope()+ var checking by remember { mutableStateOf(false) }+ ImmersivePage(title = stringResource(R.string.settings_section_app), onBack = back) {+ immersiveGroup("updates") {+ row {+ ImmersiveSwitchRow(stringResource(R.string.settings_auto_update_title), checked = com.music.spotui.data.preferences.AutoUpdateCheckPref.on,+ onChecked = { com.music.spotui.data.preferences.AutoUpdateCheckPref.set(ctx, it) }, detail = stringResource(R.string.settings_auto_update_detail))+ }+ row {+ ImmersiveGroupRow(+ stringResource(if (checking) R.string.settings_update_checking else R.string.settings_check_update_title),+ detail = stringResource(R.string.settings_check_update_detail),+ enabled = !checking,+ onClick = {+ if (!checking) {+ checking = true+ scope.launch {+ val found = runCatching { com.music.spotui.data.api.UpdateChecker.check(ctx) }.getOrNull()+ checking = false+ // The card is the app's one update UI: fill it, it shows itself.+ if (found != null) com.music.spotui.updateRelease.value = found+ else android.widget.Toast.makeText(ctx, ctx.getString(R.string.settings_update_check_latest), android.widget.Toast.LENGTH_SHORT).show()+ }+ }+ },+ )+ }+ }+ immersiveGroup("repair") {+ // The hidden Web Player stuck or crashed: rebuild it without leaving the app.+ row {+ ImmersiveGroupRow(+ stringResource(R.string.restart_player_title), detail = stringResource(R.string.restart_player_detail),+ onClick = {+ app.myspoti.host.android.MyspotiRuntime.host.reload()+ android.widget.Toast.makeText(ctx, ctx.getString(R.string.restart_player_done), android.widget.Toast.LENGTH_SHORT).show()+ },+ )+ }+ row {+ ImmersiveGroupRow(+ stringResource(R.string.diagnostic_export_title), detail = stringResource(R.string.diagnostic_export_detail),+ onClick = {+ val file = runCatching { app.myspoti.host.android.Logbook.export(ctx) }.getOrNull()+ if (file != null) shareDiagnosticReport(ctx, file)+ else android.widget.Toast.makeText(ctx, ctx.getString(R.string.diagnostic_export_failed), android.widget.Toast.LENGTH_SHORT).show()+ },+ )+ }+ }+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/people/ImmersiveFollowListScreen.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/people/ImmersiveFollowListScreen.ktnew file mode 100644index 00000000..6e61b982--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/people/ImmersiveFollowListScreen.kt@@ -0,0 +1,78 @@+package com.music.spotui.ui.immersive.people++import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.lazy.rememberLazyListState+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.navigation.NavController+import app.myspoti.api.UserRef+import app.myspoti.engine.R+import app.myspoti.host.android.MyspotiRuntime+import com.music.spotui.ui.immersive.Immersive+import com.music.spotui.ui.immersive.components.ImmersiveListRow+import com.music.spotui.ui.immersive.components.ImmersiveMessageState+import com.music.spotui.ui.immersive.components.immersiveSongListSkeleton+import com.music.spotui.ui.immersive.podcast.ImmersiveOverscrollHost+import com.music.spotui.ui.immersive.podcast.rowPlacement+import com.music.spotui.ui.immersive.shell.ImmersiveTopBar+import com.music.spotui.ui.immersive.shell.immersiveHazeSource+import com.music.spotui.ui.immersive.shell.immersiveLargeTitle+import com.music.spotui.ui.immersive.shell.immersiveTopContentPadding+import com.music.spotui.ui.navigation.profileRoute++/**+ * The people who follow a user, or the people that user follows, in the Immersive look: a large+ * title over a list of round pictures and names; a tap opens that person's profile. Same data as+ * the Classic list.+ */+@Composable+fun ImmersiveFollowListScreen(navController: NavController, userId: String, followers: Boolean) {+ var people by remember(userId, followers) { mutableStateOf<List<UserRef>?>(null) }+ LaunchedEffect(userId, followers) {+ val uri = "spotify:user:$userId"+ people = runCatching {+ if (followers) MyspotiRuntime.api.users.followers(uri) else MyspotiRuntime.api.users.following(uri)+ }.getOrDefault(emptyList())+ }+ val list = people+ val listState = rememberLazyListState()+ val title = stringResource(if (followers) R.string.profile_followers_title else R.string.profile_following_title)++ ImmersiveOverscrollHost {+ Box(Modifier.fillMaxSize().background(Immersive.Page)) {+ LazyColumn(+ state = listState,+ contentPadding = PaddingValues(top = immersiveTopContentPadding(), bottom = Immersive.BottomChrome),+ modifier = Modifier.fillMaxSize().immersiveHazeSource(),+ ) {+ immersiveLargeTitle(title = title)+ when {+ list == null -> immersiveSongListSkeleton(count = 8, keyPrefix = "skeleton:follow", circular = true)+ list.isEmpty() -> item(key = "empty") { ImmersiveMessageState(stringResource(R.string.profile_list_empty)) }+ else -> items(list, key = { it.uri }) { u ->+ ImmersiveListRow(+ title = u.name,+ subtitle = null,+ imageUrl = u.imageUrl,+ round = true,+ onClick = { navController.navigate(profileRoute(u.uri.substringAfterLast(':'), u.name)) },+ modifier = rowPlacement(),+ )+ }+ }+ }+ ImmersiveTopBar(title = title, listState = listState, onBack = { navController.navigateUp() })+ }+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/people/ImmersiveProfileScreen.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/people/ImmersiveProfileScreen.ktnew file mode 100644index 00000000..2290a13f--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/people/ImmersiveProfileScreen.kt@@ -0,0 +1,283 @@+package com.music.spotui.ui.immersive.people++import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.widthIn+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.lazy.rememberLazyListState+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.rounded.Check+import androidx.compose.material.icons.rounded.Person+import androidx.compose.material.icons.rounded.PersonAdd+import androidx.compose.material3.Text+import androidx.compose.material3.AlertDialog+import androidx.compose.material3.DropdownMenu+import androidx.compose.material3.DropdownMenuItem+import androidx.compose.material3.TextButton+import androidx.compose.material.icons.rounded.MoreHoriz+import androidx.compose.ui.graphics.Color+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.pluralStringResource+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import androidx.navigation.NavController+import app.myspoti.api.UserProfile+import app.myspoti.api.best+import app.myspoti.engine.R+import app.myspoti.host.android.MyspotiRuntime+import com.music.spotui.di.Haptics+import com.music.spotui.ui.immersive.Immersive+import com.music.spotui.ui.immersive.components.ImmersiveButton+import com.music.spotui.ui.immersive.components.ImmersiveCover+import com.music.spotui.ui.immersive.components.ImmersiveListRow+import com.music.spotui.ui.immersive.components.ImmersiveMessageState+import com.music.spotui.ui.immersive.components.SectionHeader+import com.music.spotui.ui.immersive.components.immersiveClickable+import com.music.spotui.ui.immersive.components.immersiveSongListSkeleton+import com.music.spotui.ui.immersive.podcast.CoverGlow+import com.music.spotui.ui.immersive.podcast.ImmersiveOverscrollHost+import com.music.spotui.ui.immersive.podcast.rememberHeaderCollapse+import com.music.spotui.ui.immersive.podcast.rowPlacement+import com.music.spotui.ui.immersive.shell.ImmersiveTopBar+import com.music.spotui.ui.immersive.shell.immersiveHazeSource+import com.music.spotui.ui.immersive.shell.immersiveTopContentPadding+import com.music.spotui.ui.navigation.playlistRoute+import com.music.spotui.ui.screens.followListRoute+import kotlinx.coroutines.launch++private val AvatarSize = 168.dp++/**+ * A user's profile in the Immersive look: a large round picture on a wash of its own colour, the+ * name, followers and following (links to their lists), a Follow button (not on your own profile)+ * and the public playlists as rows. Same data and actions as the Classic profile page.+ */+@Composable+fun ImmersiveProfileScreen(navController: NavController, userId: String, userName: String = "") {+ val uri = "spotify:user:$userId"+ var profile by remember(userId) { mutableStateOf<UserProfile?>(null) }+ var failed by remember(userId) { mutableStateOf(false) }+ var following by remember(userId) { mutableStateOf<Boolean?>(null) }+ val me = com.music.spotui.data.api.ProfileCache.id == userId+ // Blocking, as on the Classic profile: null until the server has said.+ var blocked by remember(userId) { mutableStateOf<Boolean?>(null) }+ var blockAsk by remember(userId) { mutableStateOf(false) }+ var barMenu by remember { mutableStateOf(false) }+ val context = androidx.compose.ui.platform.LocalContext.current+ val scope = rememberCoroutineScope()+ var attempt by remember(userId) { mutableStateOf(0) }+ LaunchedEffect(userId, attempt) {+ failed = false+ runCatching { MyspotiRuntime.api.users.profile(uri) }+ .onSuccess { profile = it }.onFailure { failed = true }+ if (!me) following = runCatching { MyspotiRuntime.api.users.isFollowing(listOf(uri)).single() }.getOrNull()+ if (!me) blocked = runCatching { MyspotiRuntime.api.users.isBlocked(uri) }.getOrNull()+ }+ val p = profile+ val displayName = p?.name?.takeIf { it.isNotBlank() } ?: userName+ val listState = rememberLazyListState()+ val avatarUrl = p?.images?.best(300)?.url++ ImmersiveOverscrollHost {+ Box(Modifier.fillMaxSize().background(Immersive.Page)) {+ LazyColumn(+ state = listState,+ contentPadding = PaddingValues(bottom = Immersive.BottomChrome),+ modifier = Modifier.fillMaxSize().immersiveHazeSource(),+ ) {+ item(key = "header") {+ Box(Modifier.fillMaxWidth()) {+ CoverGlow(avatarUrl, height = 360.dp)+ Column(+ horizontalAlignment = Alignment.CenterHorizontally,+ modifier = Modifier.fillMaxWidth().padding(top = immersiveTopContentPadding() + 8.dp, bottom = 12.dp),+ ) {+ ImmersiveCover(+ url = avatarUrl,+ modifier = Modifier.size(AvatarSize),+ shape = CircleShape,+ placeholderIcon = Icons.Rounded.Person,+ )+ Spacer(Modifier.height(18.dp))+ Text(+ text = displayName,+ style = Immersive.LargeTitle,+ textAlign = TextAlign.Center,+ maxLines = 2,+ overflow = TextOverflow.Ellipsis,+ modifier = Modifier.padding(horizontal = Immersive.Gutter),+ )+ if (p != null) {+ Row(+ Modifier.padding(top = 6.dp),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(4.dp),+ ) {+ p.followers?.let {+ CountLink(pluralStringResource(R.plurals.profile_followers, it, it)) {+ navController.navigate(followListRoute(userId, followers = true))+ }+ }+ if (p.followers != null && p.following != null) Text("·", style = Immersive.Subhead)+ p.following?.let {+ CountLink(stringResource(R.string.profile_following_count, it)) {+ navController.navigate(followListRoute(userId, followers = false))+ }+ }+ }+ }+ // Your own profile leads to your listening stats and the extensions.+ if (me) {+ Spacer(Modifier.height(18.dp))+ ImmersiveButton(+ text = stringResource(R.string.stats_listening_stats),+ modifier = Modifier.widthIn(min = 170.dp),+ onClick = { navController.navigate(com.music.spotui.ui.navigation.Routes.Recap.route) },+ )+ Spacer(Modifier.height(10.dp))+ ImmersiveButton(+ text = stringResource(R.string.extensions_title),+ modifier = Modifier.widthIn(min = 170.dp),+ onClick = { navController.navigate(com.music.spotui.ui.navigation.Routes.Extensions.route) },+ )+ }+ if (blocked == true) {+ Spacer(Modifier.height(10.dp))+ Text(stringResource(R.string.profile_blocked), style = Immersive.Subhead)+ }+ val f = following+ if (!me && f != null && blocked != true) {+ Spacer(Modifier.height(18.dp))+ ImmersiveButton(+ text = stringResource(+ if (f) R.string.curation_button_following_state_text else R.string.curation_button_follow_state_text,+ ),+ icon = if (f) Icons.Rounded.Check else Icons.Rounded.PersonAdd,+ filled = !f,+ modifier = Modifier.widthIn(min = 170.dp),+ onClick = {+ Haptics.confirm()+ following = !f+ scope.launch {+ runCatching {+ if (f) MyspotiRuntime.api.users.unfollow(listOf(uri)) else MyspotiRuntime.api.users.follow(listOf(uri))+ }.onFailure { following = f }+ }+ },+ )+ }+ }+ }+ }+ when {+ p == null && !failed -> immersiveSongListSkeleton(count = 4, keyPrefix = "skeleton:profile", alpha = 0.5f)+ p == null -> item(key = "failed") {+ ImmersiveMessageState(+ message = stringResource(R.string.page_load_failed),+ actionLabel = stringResource(R.string.retry_button),+ onAction = { attempt++ },+ )+ }+ p.publicPlaylists.isNotEmpty() -> {+ item(key = "playlists-header") { SectionHeader(stringResource(R.string.profile_public_playlists)) }+ items(p.publicPlaylists, key = { it.uri }) { pl ->+ val followers = pl.followers?.toInt()+ ImmersiveListRow(+ title = pl.name,+ subtitle = followers?.let { pluralStringResource(R.plurals.profile_followers, it, it) },+ imageUrl = pl.images.best(160)?.url,+ round = false,+ onClick = { navController.navigate(playlistRoute(pl.uri.substringAfterLast(':'), pl.name)) },+ modifier = rowPlacement(),+ )+ }+ }+ }+ }+ ImmersiveTopBar(+ title = displayName,+ collapse = rememberHeaderCollapse(listState),+ onBack = { navController.navigateUp() },+ actions = {+ val b = blocked+ if (!me && b != null) Box {+ com.music.spotui.ui.immersive.shell.ImmersiveBarAction(+ icon = Icons.Rounded.MoreHoriz,+ contentDescription = stringResource(R.string.profile_more_options),+ onClick = { barMenu = true },+ )+ DropdownMenu(expanded = barMenu, onDismissRequest = { barMenu = false }, containerColor = Immersive.Raised) {+ DropdownMenuItem(+ text = { Text(stringResource(if (b) R.string.profile_unblock else R.string.profile_block), style = Immersive.Body) },+ onClick = {+ barMenu = false+ if (b) scope.launch {+ blocked = false+ runCatching { MyspotiRuntime.api.users.unblockUser(uri) }.onFailure {+ blocked = true+ android.widget.Toast.makeText(context, R.string.profile_block_failed, android.widget.Toast.LENGTH_SHORT).show()+ }+ } else blockAsk = true+ },+ )+ }+ }+ },+ )+ }+ }+ if (blockAsk) AlertDialog(+ onDismissRequest = { blockAsk = false },+ containerColor = Immersive.Raised,+ title = { Text(stringResource(R.string.profile_block_title, displayName.ifEmpty { userId }), style = Immersive.Headline) },+ text = { Text(stringResource(R.string.profile_block_confirm, displayName.ifEmpty { userId }), style = Immersive.Subhead) },+ confirmButton = {+ TextButton(onClick = {+ blockAsk = false+ Haptics.confirm()+ scope.launch {+ runCatching { MyspotiRuntime.api.users.blockUser(uri) }+ .onSuccess { blocked = true; following = false }+ .onFailure { android.widget.Toast.makeText(context, R.string.profile_block_failed, android.widget.Toast.LENGTH_SHORT).show() }+ }+ }) { Text(stringResource(R.string.profile_block), style = Immersive.BodyStrong.copy(color = Color(0xFFF15E6C))) }+ },+ dismissButton = {+ TextButton(onClick = { blockAsk = false }) { Text(stringResource(R.string.cancel), style = Immersive.BodyStrong.copy(color = Immersive.Accent)) }+ },+ )+}++/** "1,204 followers": an accent link to the list behind the number. */+@Composable+private fun CountLink(text: String, onClick: () -> Unit) {+ Text(+ text = text,+ style = Immersive.Subhead.copy(color = Immersive.Accent),+ modifier = Modifier+ .immersiveClickable(onClick = onClick, pressedScale = 0.95f)+ .padding(horizontal = 6.dp, vertical = 6.dp),+ )+}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.ktnew file mode 100644index 00000000..db46a727--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/player/ImmersiveMiniPlayer.kt@@ -0,0 +1,195 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * app/src/main/java/com/music/bitchord/ui/components/MiniPlayer.kt at edc1e6f.+ * Modified for Myspoti, 2026-10.+ *+ * Changes: the 56dp capsule (radius 28) with cover, credits, play/pause and next, a swipe along+ * it to change track and a pull up to open the player. The dock and the+ * loading/locked states of a shared session are left out; the capsule is the Immersive glass+ * (immersiveGlassSurface: Liquid Glass or frost).+ */+package com.music.spotui.ui.immersive.player++import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.gestures.awaitEachGesture+import androidx.compose.foundation.gestures.awaitFirstDown+import androidx.compose.foundation.gestures.awaitTouchSlopOrCancellation+import androidx.compose.foundation.gestures.drag+import androidx.compose.foundation.interaction.MutableInteractionSource+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.rounded.Pause+import androidx.compose.material.icons.rounded.PlayArrow+import androidx.compose.material.icons.rounded.SkipNext+import androidx.compose.material3.CircularProgressIndicator+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+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.graphics.Color+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.input.pointer.positionChange+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.layout.boundsInWindow+import androidx.compose.ui.layout.onGloballyPositioned+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import androidx.lifecycle.viewmodel.compose.viewModel+import androidx.navigation.NavController+import app.myspoti.engine.R+import com.bumptech.glide.integration.compose.CrossFade+import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi+import com.bumptech.glide.integration.compose.GlideImage+import com.bumptech.glide.integration.compose.placeholder+import com.music.spotui.di.Haptics+import com.music.spotui.di.SongPlayer+import com.music.spotui.ui.immersive.Immersive+import com.music.spotui.ui.immersive.shell.immersiveGlassSurface+import com.music.spotui.ui.navigation.PlayerSheet+import com.music.spotui.ui.viewmodel.PlayerViewModel+import kotlin.math.abs++private val GLYPH_SLOT = 40.dp+private val GLYPH_SIZE = 32.dp+private val ART_CORNER = 8.dp+private val MINI_HEIGHT = 56.dp++/** How far the capsule is swiped along to change track. */+private val TRACK_SWIPE_THRESHOLD = 72.dp++/**+ * The floating capsule over the pages: cover, title and artist, play/pause and next. A tap (or a+ * pull up) opens the player ([PlayerSheet.show]); a swipe along it changes track. Nothing is drawn+ * while nothing is playing. Give it the horizontal margin and the room above the tab bar through+ * [modifier]; it fills the width it is given.+ */+@OptIn(ExperimentalGlideComposeApi::class)+@Composable+fun ImmersiveMiniPlayer(navController: NavController, modifier: Modifier = Modifier) {+ val vm: PlayerViewModel = viewModel()+ val title = vm.currentSongTitle.value+ if (title.isBlank()) return+ val singer = vm.currentSongSinger.value+ val cover = vm.currentSongCoverUri.value+ val playing = vm.currentSongPlayingState.value+ val adPlaying = SongPlayer.adPlaying+ val buffering = SongPlayer.isBuffering+ val shape = RoundedCornerShape(MINI_HEIGHT / 2)++ Row(+ modifier = modifier+ .fillMaxWidth()+ .height(MINI_HEIGHT)+ // 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)+ .clip(shape)+ .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) { PlayerSheet.show() }+ .padding(horizontal = 12.dp, vertical = 8.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ GlideImage(+ model = cover.takeIf { it.isNotBlank() },+ contentDescription = null,+ contentScale = ContentScale.Crop,+ transition = CrossFade,+ loading = placeholder(R.drawable.placeholder),+ failure = placeholder(R.drawable.placeholder),+ modifier = Modifier.size(40.dp).clip(RoundedCornerShape(ART_CORNER)).background(Color.Black.copy(alpha = 0.18f)),+ )+ Spacer(Modifier.width(10.dp))+ Column(Modifier.weight(1f)) {+ Text(+ text = if (adPlaying) stringResource(R.string.immersive_player_ad) else title,+ style = Immersive.BodyStrong.copy(fontSize = 15.sp),+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )+ if (!adPlaying) {+ Text(text = singer, style = Immersive.Subhead, maxLines = 1, overflow = TextOverflow.Ellipsis)+ }+ }+ if (buffering) {+ Box(Modifier.size(GLYPH_SLOT), contentAlignment = Alignment.Center) {+ CircularProgressIndicator(color = Immersive.Text, strokeWidth = 2.dp, modifier = Modifier.size(22.dp))+ }+ } else {+ Box(+ Modifier.size(GLYPH_SLOT).clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {+ Haptics.click()+ // The same optimistic update as the Classic mini player: the glyph flips at once.+ if (playing) SongPlayer.pause() else SongPlayer.play()+ vm.updateSongState(cover, title, singer, !playing, vm.currentSongId.value, vm.currentSongIndex.value, vm.currentSongAlbum.value)+ },+ contentAlignment = Alignment.Center,+ ) {+ Icon(+ imageVector = if (playing) Icons.Rounded.Pause else Icons.Rounded.PlayArrow,+ contentDescription = stringResource(if (playing) R.string.immersive_player_pause else R.string.immersive_player_play),+ tint = Immersive.Text,+ modifier = Modifier.size(GLYPH_SIZE),+ )+ }+ }+ Box(+ Modifier.size(GLYPH_SLOT).clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {+ Haptics.click()+ SongPlayer.swipeNext()+ },+ contentAlignment = Alignment.Center,+ ) {+ Icon(+ imageVector = Icons.Rounded.SkipNext,+ contentDescription = stringResource(R.string.immersive_player_next),+ tint = Immersive.Text,+ modifier = Modifier.size(GLYPH_SIZE),+ )+ }+ }+}+++/**+ * A swipe along the capsule changes track (past [TRACK_SWIPE_THRESHOLD]); a pull up opens the+ * player. A tap is left to the capsule's own click.+ */+private fun Modifier.miniPlayerGestures(): Modifier = pointerInput(Unit) {+ val threshold = TRACK_SWIPE_THRESHOLD.toPx()+ awaitEachGesture {+ val down = awaitFirstDown(requireUnconsumed = false)+ val slopped = awaitTouchSlopOrCancellation(down.id) { change, _ -> change.consume() } ?: return@awaitEachGesture+ val moved = slopped.position - down.position+ if (abs(moved.y) > abs(moved.x)) {+ if (moved.y < 0f) PlayerSheet.show()+ drag(slopped.id) { it.consume() }+ return@awaitEachGesture+ }+ var dragged = moved.x+ val finished = drag(slopped.id) { change ->+ dragged += change.positionChange().x+ change.consume()+ }+ if (!finished) return@awaitEachGesture+ when {+ dragged <= -threshold -> SongPlayer.swipeNext()+ dragged >= threshold -> SongPlayer.previous()+ }+ }+}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.ktnew file mode 100644index 00000000..4929b481--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/player/ImmersivePlayer.kt@@ -0,0 +1,465 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * sharedUi/src/jvmSharedMain/kotlin/com/music/bitchord/ui/player/NowPlayingScreen.kt at edc1e6f.+ * Modified for Myspoti, 2026-10.+ *+ * Changes: only the portrait layout is taken: the artwork with its step back on pause, the move+ * of the artwork to a small header (title beside it) when the lyrics or the queue open, the+ * title row with its round glyphs, the scrubber, transport, volume and bottom rows, and the+ * sheet's drag to close. The full-bleed banner, Canvas clips, track-swipe on the cover, version+ * switching, landscape/tablet layouts, the lyric strip and the dock are left out.+ */+package com.music.spotui.ui.immersive.player++import androidx.activity.compose.BackHandler+import androidx.compose.animation.Crossfade+import androidx.compose.animation.animateColorAsState+import androidx.compose.animation.core.FastOutSlowInEasing+import androidx.compose.animation.core.animateFloatAsState+import androidx.compose.animation.core.tween+import androidx.compose.foundation.ExperimentalFoundationApi+import androidx.compose.foundation.background+import androidx.compose.foundation.basicMarquee+import androidx.compose.foundation.clickable+import androidx.compose.foundation.gestures.awaitEachGesture+import androidx.compose.foundation.gestures.awaitFirstDown+import androidx.compose.foundation.gestures.awaitVerticalTouchSlopOrCancellation+import androidx.compose.foundation.gestures.verticalDrag+import androidx.compose.foundation.interaction.MutableInteractionSource+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxWithConstraints+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.navigationBarsPadding+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.statusBarsPadding+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.layout.widthIn+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.rounded.MoreHoriz+import androidx.compose.material.icons.rounded.Star+import androidx.compose.material.icons.rounded.StarBorder+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.CompositionLocalProvider+import androidx.compose.runtime.derivedStateOf+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberUpdatedState+import androidx.compose.runtime.saveable.rememberSaveable+import androidx.compose.runtime.setValue+import androidx.compose.runtime.staticCompositionLocalOf+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.TransformOrigin+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.input.pointer.positionChange+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.input.pointer.util.VelocityTracker+import androidx.compose.ui.input.pointer.util.addPointerInputChange+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.layout.layout+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.Constraints+import androidx.compose.ui.unit.constrainHeight+import androidx.compose.ui.unit.constrainWidth+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.IntOffset+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.lerp+import androidx.compose.ui.unit.offset+import androidx.compose.ui.unit.sp+import androidx.navigation.NavController+import app.myspoti.engine.R+import com.bumptech.glide.integration.compose.CrossFade+import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi+import com.bumptech.glide.integration.compose.GlideImage+import com.bumptech.glide.integration.compose.placeholder+import com.music.spotui.ui.components.DevicesSheet+import com.music.spotui.ui.immersive.sheets.ImmersiveSongOptionsSheet+import com.music.spotui.ui.immersive.Immersive+import com.music.spotui.ui.immersive.lyrics.ImmersiveLyricsPanel+import com.music.spotui.ui.immersive.lyrics.ImmersiveQueuePanel+import com.music.spotui.ui.look.MeshGradientBackground+import com.music.spotui.ui.look.rememberArtworkColors+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+private val ART_TITLE_GAP = 20.dp+private val ART_BOX_TOP_PAD = 8.dp+private val DISMISS_STRIP_HEIGHT = 32.dp++/** The player's side margin. Scrollable panels reach back across it. */+internal val PLAYER_GUTTER = 30.dp++/**+ * How wide the player's content is ever allowed to get: a sleeve and a volume slider stretched+ * across a tablet aren't a bigger player, just a coarser one.+ */+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 val ArtCorner = RoundedCornerShape(8.dp)++/** What the middle of the player shows. */+private object Panel {+ const val NONE = 0+ const val LYRICS = 1+ const val QUEUE = 2+}++/**+ * The sheet the player sits in, as the player sees it: dragged down from the top of the player+ * (the handle, the artwork, the credits) it follows the finger, and lets go with its speed.+ */+internal interface PlayerSheetDrag {+ fun drag(delta: Float)+ fun release(velocity: Float)+}++internal val LocalPlayerSheetDrag = staticCompositionLocalOf<PlayerSheetDrag?> { null }++/**+ * The downward half of a vertical drag on this element, handed to the sheet. Upward is not ours:+ * the crossing of the touch slop is left alone and nothing is consumed, so a tap, a scroll or a+ * child's own gesture keeps working.+ */+@Composable+internal fun Modifier.dragToClose(): Modifier {+ val sheet = LocalPlayerSheetDrag.current ?: return this+ val current by rememberUpdatedState(sheet)+ return pointerInput(Unit) {+ awaitEachGesture {+ val down = awaitFirstDown(requireUnconsumed = false)+ var pulled = 0f+ val drag = awaitVerticalTouchSlopOrCancellation(down.id) { change, overSlop ->+ if (overSlop > 0f) {+ pulled = overSlop+ change.consume()+ }+ }+ if (drag == null || pulled <= 0f) return@awaitEachGesture+ val velocity = VelocityTracker()+ velocity.addPointerInputChange(drag)+ current.drag(pulled)+ val finished = verticalDrag(drag.id) { change ->+ velocity.addPointerInputChange(change)+ current.drag(change.positionChange().y)+ change.consume()+ }+ current.release(if (finished) velocity.calculateVelocity().y else 0f)+ }+ }+}++/**+ * The Immersive look's player: the cover's colours drifting behind a large cover, the credits,+ * a scrubber, the transport, the volume and a row of lyrics, devices and queue.+ *+ * Opening the lyrics or the queue moves the cover up into a small header with the credits beside+ * it; [ImmersiveLyricsPanel] or [ImmersiveQueuePanel] takes the middle and the controls below+ * stay where they are. [navController] is for the "more" sheet (artist, album, playlists…):+ * without it the button is not shown.+ */+@OptIn(ExperimentalGlideComposeApi::class, ExperimentalFoundationApi::class)+@Composable+fun ImmersivePlayer(+ state: ImmersivePlayerState,+ actions: ImmersivePlayerActions,+ modifier: Modifier = Modifier,+ navController: NavController? = null,+) {+ val context = LocalContext.current+ val palette = rememberArtworkColors(state.coverUrl.takeIf { it.isNotBlank() })+ val tint by animateColorAsState(playerTintOf(palette), tween(600), label = "playerTint")++ var panel by rememberSaveable { mutableIntStateOf(Panel.NONE) }+ var showMenu by remember { mutableStateOf(false) }+ var showDevices by remember { mutableStateOf(false) }+ var showQuality by remember { mutableStateOf(false) }+ val lyricsOpen = panel == Panel.LYRICS+ val queueOpen = panel == Panel.QUEUE++ // 0 with the full player, 1 with the cover in the header. Read at measure, placement and draw.+ val collapse = animateFloatAsState(+ targetValue = if (panel == Panel.NONE) 0f else 1f,+ animationSpec = tween(PANEL_TRAVEL_MS, easing = FastOutSlowInEasing),+ label = "playerCollapse",+ )+ val pauseScale = rememberPauseScale(state.playing)+ val volume = rememberPlayerVolume()++ // Back leaves the panel first; the sheet (outside) closes on the next one.+ BackHandler(enabled = panel != Panel.NONE) { panel = Panel.NONE }++ Box(modifier.fillMaxSize().background(Color.Black)) {+ MeshGradientBackground(palette = palette, trackKey = state.coverUrl)+ CompositionLocalProvider(LocalPlayerTint provides tint) {+ Column(Modifier.fillMaxSize().statusBarsPadding().navigationBarsPadding()) {+ // The handle: always hands its drags to the sheet.+ Box(+ Modifier.fillMaxWidth().height(DISMISS_STRIP_HEIGHT).dragToClose()+ .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) { actions.close() },+ contentAlignment = Alignment.Center,+ ) {+ Box(Modifier.width(36.dp).height(5.dp).clip(CircleShape).background(tint.copy(alpha = 0.35f)))+ }++ // Everything that changes between the full player and the panels lives in this+ // one weighted box, so the controls below it never move.+ BoxWithConstraints(Modifier.weight(1f).fillMaxWidth()) {+ val contentWidth = minOf(maxWidth - PLAYER_GUTTER * 2, PLAYER_MAX_WIDTH)+ val left = (maxWidth - contentWidth) / 2+ val fullArt = minOf(contentWidth, maxHeight - ART_BOX_TOP_PAD - ART_TITLE_GAP - HEADER_HEIGHT - 16.dp)+ .coerceAtLeast(THUMB_SIZE)+ // The cover and the credits sit centred as a pair while the player is whole.+ val groupTop = (maxHeight - ART_BOX_TOP_PAD - fullArt - ART_TITLE_GAP - HEADER_HEIGHT - 16.dp)+ .coerceAtLeast(0.dp) / 2+ // Functions of the collapse, called at placement and measure: composition never reads them.+ fun p() = collapse.value+ fun artSize(): Dp = lerp(fullArt, THUMB_SIZE, p())+ fun artTop(): Dp = ART_BOX_TOP_PAD + lerp(groupTop, 0.dp, p())+ fun artStart(): Dp = left + lerp((contentWidth - fullArt) / 2, 0.dp, p())+ fun titleTop(): Dp = ART_BOX_TOP_PAD + lerp(groupTop + fullArt + ART_TITLE_GAP, 0.dp, p())+ fun titleStart(): Dp = lerp(0.dp, THUMB_SIZE + 12.dp, p())+ // The credits only crawl while they are the screen: over a list they would pull the eye.+ val scrolls by remember { derivedStateOf { collapse.value < 0.01f } }++ // ---- The panel, under the header ----+ val panelAlpha = { ((p() - 0.6f) / 0.4f).coerceIn(0f, 1f) }+ Crossfade(+ targetState = panel,+ animationSpec = tween(250),+ modifier = Modifier+ .fillMaxSize()+ .padding(top = ART_BOX_TOP_PAD + HEADER_HEIGHT)+ .graphicsLayer { alpha = panelAlpha() },+ label = "playerPanel",+ ) { shown ->+ val inset = PaddingValues(start = left, end = left, top = 12.dp, bottom = 12.dp)+ when (shown) {+ Panel.LYRICS -> ImmersiveLyricsPanel(Modifier.fillMaxSize(), inset)+ Panel.QUEUE -> ImmersiveQueuePanel(Modifier.fillMaxSize(), inset)+ else -> Box(Modifier.fillMaxSize())+ }+ }++ // ---- The cover: the whole sleeve, then the header's thumbnail ----+ Box(+ modifier = Modifier+ .offset { IntOffset(artStart().roundToPx(), artTop().roundToPx()) }+ .layout { measurable, _ ->+ val side = artSize().roundToPx()+ val placeable = measurable.measure(Constraints.fixed(side, side))+ layout(side, side) { placeable.place(0, 0) }+ }+ .graphicsLayer {+ // The pause step back, let go of as the cover collapses into the header.+ val scale = pauseScale.value + (1f - pauseScale.value) * p()+ scaleX = scale+ scaleY = scale+ shadowElevation = 10.dp.toPx() * (1f - p())+ shape = ArtCorner+ clip = true+ }+ .background(Color.Black.copy(alpha = 0.18f))+ .dragToClose()+ .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {+ if (panel != Panel.NONE) panel = Panel.NONE+ },+ ) {+ GlideImage(+ model = state.coverUrl.takeIf { it.isNotBlank() },+ contentDescription = null,+ contentScale = ContentScale.Crop,+ transition = CrossFade,+ loading = placeholder(R.drawable.placeholder),+ failure = placeholder(R.drawable.placeholder),+ modifier = Modifier.fillMaxSize(),+ )+ }++ // ---- Title + round glyphs ----+ Row(+ modifier = Modifier+ .offset {+ // Collapsed, the row shares the header with the thumbnail and the two+ // are not the same height: centred on it.+ IntOffset(+ left.roundToPx(),+ (titleTop() - lerp(0.dp, (HEADER_HEIGHT - THUMB_SIZE) / 2, p())).roundToPx(),+ )+ }+ .width(contentWidth)+ .layout { measurable, constraints ->+ val start = titleStart().roundToPx()+ val placeable = measurable.measure(constraints.offset(horizontal = -start))+ layout(+ constraints.constrainWidth(placeable.width + start),+ constraints.constrainHeight(placeable.height),+ ) { placeable.placeRelative(start, 0) }+ }+ .height(HEADER_HEIGHT)+ .dragToClose(),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Column(+ Modifier+ .weight(1f)+ // Scaling the already measured type is a draw-only operation.+ .graphicsLayer {+ val scale = 1f - 0.2f * p()+ scaleX = scale+ scaleY = scale+ transformOrigin = TransformOrigin(0f, 0.5f)+ },+ ) {+ Row(verticalAlignment = Alignment.CenterVertically) {+ Text(+ text = if (state.adPlaying) stringResource(R.string.immersive_player_ad) else state.title,+ style = Immersive.Title.copy(fontSize = 20.sp, lineHeight = 24.sp),+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ modifier = Modifier+ .weight(1f, fill = false)+ .then(if (scrolls) Modifier.basicMarquee(iterations = Int.MAX_VALUE) else Modifier)+ .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) { actions.openAlbum() },+ )+ if (state.explicit && !state.adPlaying) {+ Spacer(Modifier.width(6.dp))+ Box(+ Modifier.size(16.dp).clip(RoundedCornerShape(3.dp)).background(tint.copy(alpha = 0.5f)),+ contentAlignment = Alignment.Center,+ ) {+ Text(+ text = "E",+ style = Immersive.Caption.copy(fontSize = 10.sp, lineHeight = 10.sp, fontWeight = FontWeight.Bold),+ color = Color.Black,+ )+ }+ }+ }+ if (!state.adPlaying) {+ Text(+ text = state.artist,+ style = Immersive.Title.copy(fontSize = 20.sp, lineHeight = 24.sp, fontWeight = FontWeight.W500),+ color = tint.copy(alpha = 0.55f),+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ modifier = Modifier+ .then(if (scrolls) Modifier.basicMarquee(iterations = Int.MAX_VALUE) else Modifier)+ .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) { actions.openArtist() },+ )+ }+ // What the sound is when Myspoti's own player plays it (an extension's stream, a+ // download); a tap opens what plays and its quality. Same state as the Classic player.+ val source = com.music.spotui.ui.components.playingSourceLabel()+ if (source.isNotBlank() && !state.adPlaying) Text(+ text = source,+ style = Immersive.Caption,+ color = tint.copy(alpha = 0.45f),+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ modifier = Modifier+ .padding(top = 2.dp)+ .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) { showQuality = true },+ )+ }+ Spacer(Modifier.width(10.dp))+ // Beside the credits rather than in the toggle row: liking is about this song.+ CircleGlyph(+ icon = if (state.liked) Icons.Rounded.Star else Icons.Rounded.StarBorder,+ contentDescription = stringResource(if (state.liked) R.string.immersive_player_unlike else R.string.immersive_player_like),+ onClick = actions.toggleLike,+ active = state.liked,+ )+ if (navController != null && state.song != null) {+ Spacer(Modifier.width(8.dp))+ CircleGlyph(+ icon = Icons.Rounded.MoreHoriz,+ contentDescription = stringResource(R.string.immersive_player_more),+ onClick = { showMenu = true },+ )+ }+ }+ }++ // ---- Bottom: scrubber, transport, volume, toggles ----+ // One block, measured at its natural height and pinned to the foot of the player.+ Column(+ modifier = Modifier+ .widthIn(max = PLAYER_MAX_WIDTH + PLAYER_GUTTER * 2)+ .fillMaxWidth()+ .padding(horizontal = PLAYER_GUTTER)+ .align(Alignment.CenterHorizontally),+ ) {+ PlayerScrubber(state = state, onSeek = actions.seekTo)+ Spacer(Modifier.height(8.dp))+ TransportRow(+ isPlaying = state.playing,+ isLoading = state.buffering,+ onPrevious = actions.previous,+ onPlayPause = actions.playPause,+ onNext = actions.next,+ )+ Spacer(Modifier.height(12.dp))+ VolumeRow(volume)+ // The volume slider already has room below its drawn track.+ Spacer(Modifier.height(6.dp))+ PlayerActionRow(+ lyricsOpen = lyricsOpen,+ queueOpen = queueOpen,+ shuffleEnabled = state.shuffle,+ repeatMode = state.repeatMode,+ deviceActive = state.deviceName != null,+ // Lyrics and the queue are two things to show in one place: opening one closes the other.+ onToggleLyrics = { panel = if (lyricsOpen) Panel.NONE else Panel.LYRICS },+ onToggleQueue = { panel = if (queueOpen) Panel.NONE else Panel.QUEUE },+ onToggleShuffle = actions.toggleShuffle,+ onCycleRepeat = actions.cycleRepeat,+ onOpenDevices = { showDevices = true },+ )+ // Buttons from extensions (player.buttons), under the player's own controls.+ val extTrack = remember(state.title, state.artist) { com.music.spotui.extensions.Extensions.currentTrack() }+ com.music.spotui.extensions.ExtensionPlayerButtons(extTrack)+ Spacer(Modifier.height(18.dp))+ }+ }+ }+ }++ if (showDevices) DevicesSheet { showDevices = false }+ if (showQuality) com.music.spotui.ui.components.QualitySheet { showQuality = false }+ val song = state.song+ if (showMenu && song != null && navController != null) {+ ImmersiveSongOptionsSheet(+ song = song,+ navController = navController,+ context = context,+ onDismiss = { showMenu = false },+ nowPlaying = true,+ onOpenQueue = { panel = Panel.QUEUE },+ )+ }+}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.ktnew file mode 100644index 00000000..9563e0f9--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/player/ImmersivePlayerOverlay.kt@@ -0,0 +1,160 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * app/src/main/java/com/music/bitchord/ui/player/PlayerSheetMotion.kt and+ * sharedUi/src/jvmSharedMain/kotlin/com/music/bitchord/ui/player/PlayerDock.kt at edc1e6f.+ * Modified for Myspoti, 2026-10.+ *+ * Changes: only the sheet's motion is kept: it opens and closes on one critically damped spring+ * (stiffness 195) and a pull down carries the finger's speed into it. The Material sheet window,+ * the window animations and the cover docking into the mini player are left out.+ */+package com.music.spotui.ui.immersive.player++import androidx.activity.compose.BackHandler+import androidx.compose.animation.core.Animatable+import androidx.compose.animation.core.Spring+import androidx.compose.animation.core.spring+import androidx.compose.foundation.clickable+import androidx.compose.foundation.interaction.MutableInteractionSource+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.runtime.Composable+import androidx.compose.runtime.CompositionLocalProvider+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableFloatStateOf+import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue+import androidx.compose.runtime.snapshotFlow+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.layout.onSizeChanged+import androidx.navigation.NavController+import com.music.spotui.di.SongPlayer+import com.music.spotui.ui.navigation.LocalPageSettled+import com.music.spotui.ui.navigation.PlayerSheet+import com.music.spotui.ui.screens.PodcastPlayerScreen+import kotlinx.coroutines.flow.drop+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.launch++/** The slide's spring: no bounce, a long soft landing. */+private const val SLIDE_STIFFNESS = 195f++/** The slide counts as settled within this many pixels of its target. */+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,+)++/**+ * The Immersive look's player over the pages, a drop-in for [com.music.spotui.ui.navigation.PlayerOverlay]:+ * driven by [PlayerSheet] (`open`, `show()`, `close()`), it rises on a spring when opened, follows+ * a pull down and closes with the finger's speed, closes on the back button and on any navigation.+ * A podcast episode keeps the existing podcast player.+ */+@Composable+fun ImmersivePlayerOverlay(navController: NavController) {+ // Any navigation from the player (album, artist, playlist…) lands on that page.+ LaunchedEffect(navController) {+ navController.currentBackStackEntryFlow.drop(1).collect { PlayerSheet.close() }+ }+ val open = PlayerSheet.open.value+ val scope = rememberCoroutineScope()+ 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) }+ var shown by remember { mutableStateOf(false) }+ // Invisible until it has been put below the window: no frame of it at rest before the rise.+ var primed by remember { mutableStateOf(false) }+ // The finger's hold on the sheet, or NaN when it has none.+ var held by remember { mutableFloatStateOf(Float.NaN) }+ var closeVelocity by remember { mutableFloatStateOf(0f) }+ val settled = remember { mutableStateOf(false) }++ LaunchedEffect(open) {+ if (open) {+ val wasShown = shown+ shown = true+ if (!wasShown) {+ settled.value = false+ snapshotFlow { heightPx }.first { it > 0 }+ offset.snapTo(heightPx.toFloat())+ primed = true+ }+ offset.animateTo(0f, slideSpec())+ settled.value = true+ } else if (shown) {+ settled.value = false+ val velocity = closeVelocity.coerceAtLeast(0f)+ closeVelocity = 0f+ offset.animateTo(heightPx.toFloat(), slideSpec(), initialVelocity = velocity)+ shown = false+ primed = false+ }+ }+ if (!shown) return+ BackHandler(enabled = open) { PlayerSheet.close() }++ val sheetDrag = remember {+ object : PlayerSheetDrag {+ override fun drag(delta: Float) {+ if (!PlayerSheet.open.value) return+ if (held.isNaN()) held = offset.value+ held = (held + delta).coerceIn(0f, heightPx.toFloat())+ }++ override fun release(velocity: Float) {+ if (held.isNaN()) return+ val from = held+ val close = when {+ velocity >= FLING_VELOCITY -> true+ velocity <= -FLING_VELOCITY -> false+ else -> from > heightPx / 2f+ }+ scope.launch {+ offset.snapTo(from)+ held = Float.NaN+ if (close) {+ // The finger's own speed goes into the spring: the sheet carries on as it was moving.+ closeVelocity = velocity+ PlayerSheet.close()+ } else {+ offset.animateTo(0f, slideSpec(), initialVelocity = velocity)+ }+ }+ }+ }+ }++ Box(+ Modifier+ .fillMaxSize()+ .onSizeChanged { heightPx = it.height }+ .graphicsLayer {+ translationY = if (held.isNaN()) offset.value else held+ alpha = if (primed) 1f else 0f+ }+ // Nothing under the player may take a touch the player leaves alone.+ .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {},+ ) {+ CompositionLocalProvider(LocalPageSettled provides settled, LocalPlayerSheetDrag provides sheetDrag) {+ // A podcast episode gets the podcast player; everything else the Immersive one.+ if (SongPlayer.isEpisode) {+ PodcastPlayerScreen(navController)+ } else {+ val bridge = rememberImmersivePlayer(navController)+ ImmersivePlayer(bridge.state, bridge.actions, navController = navController)+ }+ }+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/player/PlayerBridge.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/player/PlayerBridge.ktnew file mode 100644index 00000000..81e220aa--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/player/PlayerBridge.kt@@ -0,0 +1,188 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * sharedUi/src/jvmSharedMain/kotlin/com/music/bitchord/ui/player/PlayerHost.kt and PlayerState.kt at edc1e6f.+ * Modified for Myspoti, 2026-10.+ *+ * Changes: only the shape is kept (a player screen that is given plain state and a set of+ * actions, and knows nothing about the engine). The state is filled from Myspoti's+ * CurrentSongState, SongPlayer and PlayerViewModel, read-only, and every action does what the+ * Classic player's does.+ */+package com.music.spotui.ui.immersive.player++import android.widget.Toast+import androidx.compose.runtime.Composable+import androidx.compose.runtime.Immutable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.Stable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableLongStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.platform.LocalContext+import androidx.lifecycle.viewmodel.compose.viewModel+import androidx.navigation.NavController+import app.myspoti.engine.R+import com.music.spotui.data.entity.SongsModel+import com.music.spotui.di.SongPlayer+import com.music.spotui.ui.navigation.PlayerSheet+import com.music.spotui.ui.navigation.albumRoute+import com.music.spotui.ui.screens.nowPlayingSong+import com.music.spotui.ui.viewmodel.PlayerViewModel+import kotlinx.coroutines.delay++/** Repeat modes, as [SongPlayer.repeatMode] reports them. */+object ImmersiveRepeat {+ const val OFF = 0+ const val ALL = 1+ const val ONE = 2+}++/**+ * What the Immersive player draws, with no engine behind it. [positionMs] is a provider: the+ * scrubber and the time labels call it every frame, so the screen does not recompose for it.+ */+@Immutable+data class ImmersivePlayerState(+ val title: String = "",+ val artist: String = "",+ val album: String = "",+ val coverUrl: String = "",+ val playing: Boolean = false,+ val buffering: Boolean = false,+ /** The playhead in milliseconds, read per frame (SongPlayer.getCurrentPosition()). */+ val positionMs: () -> Long = { 0L },+ val durationMs: Long = 0L,+ val shuffle: Boolean = false,+ /** [ImmersiveRepeat]. */+ val repeatMode: Int = ImmersiveRepeat.OFF,+ val liked: Boolean = false,+ val isEpisode: Boolean = false,+ val explicit: Boolean = false,+ /** An ad break: the page publishes no track, a label stands in for the title. */+ val adPlaying: Boolean = false,+ /** The list the music plays from (playlist, album, Liked Songs…), or blank. */+ val contextName: String = "",+ /** The other device the sound goes to, or null for this phone. */+ val deviceName: String? = null,+ /** The track as the options sheet wants it; null while nothing is known. */+ val song: SongsModel? = null,+)++/** What the player does; nothing here touches the UI, the screen owns its sheets and panels. */+@Stable+class ImmersivePlayerActions(+ val playPause: () -> Unit = {},+ val next: () -> Unit = {},+ val previous: () -> Unit = {},+ val seekTo: (Long) -> Unit = {},+ val toggleShuffle: () -> Unit = {},+ val cycleRepeat: () -> Unit = {},+ val toggleLike: () -> Unit = {},+ /** Opens the album of the playing track. */+ val openAlbum: () -> Unit = {},+ /** Opens the artist of the playing track (a choice first when there are several). */+ val openArtist: () -> Unit = {},+ /** Closes the player (PlayerSheet.close()). */+ val close: () -> Unit = {},+)++/** The two, as [rememberImmersivePlayer] returns them. */+@Immutable+data class ImmersivePlayerBridge(val state: ImmersivePlayerState, val actions: ImmersivePlayerActions)++/**+ * Fills the player's state from Myspoti's playback (read-only) and wires its actions to the+ * same calls the Classic player makes. Needs the [navController] for the artist and album pages.+ */+@Composable+fun rememberImmersivePlayer(navController: NavController): ImmersivePlayerBridge {+ val vm: PlayerViewModel = viewModel()+ val context = LocalContext.current+ val np by SongPlayer.nowPlaying+ val title = vm.currentSongTitle.value+ val singer = vm.currentSongSinger.value+ val cover = vm.currentSongCoverUri.value+ val album = vm.currentSongAlbum.value+ val playing = vm.currentSongPlayingState.value+ val songId = vm.currentSongId.value+ val liked = vm.likeState.value+ val shuffle = vm.shuffleState.value+ val repeat = SongPlayer.repeatMode.value+ val buffering = SongPlayer.isBuffering+ val adPlaying = SongPlayer.adPlaying+ val episode = SongPlayer.isEpisode+ val device = SongPlayer.activeDevice.value?.name++ // The length is plain data in the engine, not Compose state: asked again until it changes+ // (a track still loading reports 0), then left alone.+ var duration by remember { mutableLongStateOf(SongPlayer.getDuration()) }+ LaunchedEffect(songId, np.uri) {+ while (true) {+ val d = SongPlayer.getDuration()+ if (d != duration) duration = d+ delay(if (d > 0L) 1_500L else 300L)+ }+ }++ val state = ImmersivePlayerState(+ title = title,+ artist = singer,+ album = album,+ coverUrl = app.myspoti.host.android.Covers.large(cover),+ playing = playing,+ buffering = buffering,+ positionMs = remember { { SongPlayer.getCurrentPosition() } },+ durationMs = duration,+ shuffle = shuffle,+ repeatMode = repeat,+ liked = liked,+ isEpisode = episode,+ explicit = np.explicit,+ adPlaying = adPlaying,+ contextName = np.contextName.ifBlank { SongPlayer.knownContextName(np.contextUri) }.ifBlank { album },+ deviceName = device,+ song = if (title.isBlank()) null else nowPlayingSong(vm),+ )++ // Read at the moment of the tap, not captured: the lambdas below live as long as the screen.+ val actions = remember(vm, navController) {+ ImmersivePlayerActions(+ playPause = {+ // The same optimistic update as the Classic player: the glyph flips at once.+ val nowPlaying = vm.currentSongPlayingState.value+ if (nowPlaying) SongPlayer.pause() else SongPlayer.play()+ vm.updateSongState(+ vm.currentSongCoverUri.value,+ vm.currentSongTitle.value,+ vm.currentSongSinger.value,+ !nowPlaying,+ vm.currentSongId.value,+ vm.currentSongIndex.value,+ vm.currentSongAlbum.value,+ )+ },+ next = { SongPlayer.swipeNext() },+ previous = { SongPlayer.previous() },+ seekTo = { SongPlayer.seekTo(it) },+ toggleShuffle = { vm.updateShuffleState(!vm.shuffleState.value) },+ cycleRepeat = { SongPlayer.cycleRepeat() },+ toggleLike = {+ val on = !vm.likeState.value+ vm.updateLikeState(on)+ if (on) Toast.makeText(context, context.getString(R.string.immersive_player_added_to_liked), Toast.LENGTH_SHORT).show()+ },+ openAlbum = {+ val albumId = SongPlayer.nowPlaying.value.albumUri.substringAfterLast(":")+ if (albumId.isNotBlank()) {+ navController.navigate(albumRoute(vm.currentSongAlbum.value, vm.currentSongSinger.value, albumId))+ }+ },+ openArtist = {+ vm.goToArtist(SongPlayer.currentTrackId, vm.currentSongSinger.value) { route -> navController.navigate(route) }+ },+ close = { PlayerSheet.close() },+ )+ }+ return ImmersivePlayerBridge(state, actions)+}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.ktnew file mode 100644index 00000000..1136f231--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/player/PlayerControls.kt@@ -0,0 +1,563 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * sharedUi/src/jvmSharedMain/kotlin/com/music/bitchord/ui/player/PlayerControls.kt and+ * sharedUi/src/jvmSharedMain/kotlin/com/music/bitchord/ui/theme/ArtworkPalette.kt at edc1e6f.+ * Modified for Myspoti, 2026-10.+ *+ * Changes: the scrubber, transport, volume row, round glyph discs and the bottom row. Quality+ * badges, Automix, lossless, the output/party capsule and the autoplay toggle are left out;+ * the glyphs are Material Icons Rounded; the pale player tint is read from the cover colours+ * the mesh backdrop already extracted, and the part of the palette code made of colours+ * published by a streaming service is dropped.+ */+package com.music.spotui.ui.immersive.player++import androidx.compose.animation.AnimatedContent+import androidx.compose.animation.AnimatedVisibility+import androidx.compose.animation.Crossfade+import androidx.compose.animation.SizeTransform+import androidx.compose.animation.animateContentSize+import androidx.compose.animation.core.FastOutSlowInEasing+import androidx.compose.animation.core.Spring+import androidx.compose.animation.core.animateFloatAsState+import androidx.compose.animation.core.spring+import androidx.compose.animation.core.tween+import androidx.compose.animation.fadeIn+import androidx.compose.animation.fadeOut+import androidx.compose.animation.togetherWith+import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.interaction.MutableInteractionSource+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxWithConstraints+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxHeight+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.automirrored.rounded.QueueMusic+import androidx.compose.material.icons.automirrored.rounded.VolumeDown+import androidx.compose.material.icons.automirrored.rounded.VolumeUp+import androidx.compose.material.icons.rounded.Devices+import androidx.compose.material.icons.rounded.Lyrics+import androidx.compose.material.icons.rounded.Pause+import androidx.compose.material.icons.rounded.PlayArrow+import androidx.compose.material.icons.rounded.Repeat+import androidx.compose.material.icons.rounded.RepeatOne+import androidx.compose.material.icons.rounded.Shuffle+import androidx.compose.material.icons.rounded.SkipNext+import androidx.compose.material.icons.rounded.SkipPrevious+import androidx.compose.material3.CircularProgressIndicator+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.compositionLocalOf+import androidx.compose.runtime.getValue+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.graphics.Color+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.graphics.toArgb+import androidx.compose.ui.graphics.vector.ImageVector+import androidx.compose.ui.layout.layout+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.semantics.contentDescription+import androidx.compose.ui.semantics.semantics+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp+import androidx.core.graphics.ColorUtils+import app.myspoti.engine.R+import com.music.spotui.di.Haptics+import com.music.spotui.ui.immersive.Immersive+import com.music.spotui.ui.look.MeshPalette+import com.music.spotui.ui.look.ThinSlider+import com.music.spotui.ui.components.rememberFrameClock+import kotlin.math.roundToInt++/**+ * The colour every secondary line and glyph in the player is set in: the cover's own colour+ * lifted pale rather than a translucent white. White wherever nothing provides it. The title,+ * transport, seek and volume bars stay white on purpose.+ */+internal val LocalPlayerTint = compositionLocalOf { Color.White }++private const val PLAYER_TINT_LIGHTNESS = 0.88f+private const val PLAYER_TINT_MAX_SATURATION = 0.40f++/** Below this a swatch is black, white or grey to the eye, whatever hue HSL assigns it. */+private const val TINT_MIN_CHROMA = 0.08f++/**+ * The pale tint of [palette]'s first colour that is actually visible (real chroma), or white for+ * a cover with no colour worth echoing: a near-black with a trace of red is "pink" at full+ * saturation in HSL, and lifting it pale would put a pink on the player that is nowhere on the cover.+ */+internal fun playerTintOf(palette: MeshPalette): Color {+ val source = palette.colors.firstOrNull { maxOf(it.red, it.green, it.blue) - minOf(it.red, it.green, it.blue) >= TINT_MIN_CHROMA }+ ?: return Color.White+ val hsl = FloatArray(3)+ ColorUtils.colorToHSL(source.toArgb(), hsl)+ hsl[1] = hsl[1].coerceIn(0.18f, PLAYER_TINT_MAX_SATURATION)+ hsl[2] = PLAYER_TINT_LIGHTNESS+ return Color(ColorUtils.HSLToColor(hsl))+}++/** m:ss. */+internal fun formatTime(ms: Long): String {+ val total = (ms.coerceAtLeast(0L) / 1000L).toInt()+ return "%d:%02d".format(total / 60, total % 60)+}++/**+ * The seek bar, with elapsed and remaining either side under it. The playhead is read here, per+ * tick, so the tick recomposes the bar and its two times rather than the player the bar sits in.+ */+@Composable+internal fun PlayerScrubber(+ state: ImmersivePlayerState,+ onSeek: (Long) -> Unit,+) {+ val scrub = rememberPlayerScrub(state.title, state.positionMs, state.durationMs)+ // As many ticks as the bar has pixels to move, as the Classic player's: ~5 a second on a long song.+ val frame = rememberFrameClock(state.playing && !state.buffering, fps = 15)+ frame.value+ val shown = scrub.shown(state.positionMs(), state.durationMs)+ Column(Modifier.fillMaxWidth()) {+ ThinSlider(+ value = shown,+ onValueChange = scrub::drag,+ onValueChangeFinished = { scrub.release { onSeek((it * state.durationMs).toLong()) } },+ loading = state.buffering && !scrub.scrubbing,+ )+ Row(+ modifier = Modifier+ .fillMaxWidth()+ // The slider's touch target extends well past the drawn bar: pull the labels back up under it.+ .offset(y = (-9).dp),+ horizontalArrangement = Arrangement.SpaceBetween,+ ) {+ val duration = state.durationMs.coerceAtLeast(0L)+ val elapsed = (shown * duration).toLong()+ Text(+ text = formatTime(elapsed),+ style = Immersive.Caption,+ color = LocalPlayerTint.current.copy(alpha = 0.55f),+ )+ Text(+ text = "-" + formatTime(duration - elapsed),+ style = Immersive.Caption,+ color = LocalPlayerTint.current.copy(alpha = 0.55f),+ )+ }+ }+}++/**+ * Translucent circular button used for the track menu and the like control. [active] brightens+ * the disc rather than only the glyph: it sits on artwork of any colour, and a white icon on a+ * white-ish sleeve has no tint change left to make.+ */+@Composable+internal fun CircleGlyph(+ icon: ImageVector,+ contentDescription: String,+ onClick: () -> Unit,+ active: Boolean = false,+) {+ val discAlpha by animateFloatAsState(+ targetValue = if (active) 0.34f else 0.18f,+ label = "glyphDisc",+ )+ Box(+ modifier = Modifier+ .size(34.dp)+ .clip(CircleShape)+ .background(LocalPlayerTint.current.copy(alpha = discAlpha))+ .clickable(+ interactionSource = remember { MutableInteractionSource() },+ indication = null,+ ) {+ Haptics.click()+ onClick()+ },+ contentAlignment = Alignment.Center,+ ) {+ Crossfade(+ targetState = icon,+ animationSpec = tween(durationMillis = 180),+ label = "playerMenuGlyph",+ ) { glyph ->+ Icon(+ imageVector = glyph,+ contentDescription = contentDescription,+ tint = LocalPlayerTint.current,+ modifier = Modifier.size(19.dp),+ )+ }+ }+}++/** The skip glyphs' touch box, beside the larger play button. */+private val PLAYER_SKIP_TOUCH_SIZE = 64.dp++/**+ * The skip glyphs are drawn a little flatter than they are wide, so the pair reads lower and+ * longer next to the play button without losing any width.+ */+private const val PLAYER_SKIP_HEIGHT_SCALE = 0.85f++/** Previous, play/pause, next: bare glyphs, no backgrounds. */+@Composable+internal fun TransportRow(+ isPlaying: Boolean,+ /** While the stream resolves and buffers, the play glyph would be a lie. */+ isLoading: Boolean,+ onPrevious: () -> Unit,+ onPlayPause: () -> Unit,+ onNext: () -> Unit,+) {+ val playSize = 88.dp+ val playTouch = 92.dp+ Row(+ modifier = Modifier.fillMaxWidth(),+ // SpaceAround, not SpaceEvenly: the outer margins take half a gap.+ horizontalArrangement = Arrangement.SpaceAround,+ verticalAlignment = Alignment.CenterVertically,+ ) {+ TransportGlyph(+ icon = Icons.Rounded.SkipPrevious,+ contentDescription = stringResource(R.string.immersive_player_previous),+ size = 64.dp,+ touchSize = PLAYER_SKIP_TOUCH_SIZE,+ heightScale = PLAYER_SKIP_HEIGHT_SCALE,+ onClick = onPrevious,+ )+ if (isLoading) {+ // Same footprint as the play/pause target: a smaller box would shunt everything below it.+ Box(Modifier.size(playTouch), contentAlignment = Alignment.Center) {+ CircularProgressIndicator(color = Color.White, strokeWidth = 3.dp, modifier = Modifier.size(38.dp))+ }+ } else {+ TransportGlyph(+ icon = if (isPlaying) Icons.Rounded.Pause else Icons.Rounded.PlayArrow,+ contentDescription = stringResource(if (isPlaying) R.string.immersive_player_pause else R.string.immersive_player_play),+ size = playSize,+ touchSize = playTouch,+ onClick = onPlayPause,+ )+ }+ TransportGlyph(+ icon = Icons.Rounded.SkipNext,+ contentDescription = stringResource(R.string.immersive_player_next),+ size = 64.dp,+ touchSize = PLAYER_SKIP_TOUCH_SIZE,+ heightScale = PLAYER_SKIP_HEIGHT_SCALE,+ onClick = onNext,+ )+ }+}++/**+ * Transport glyph. The circular clip belongs on the touch target, never on the [Icon]: clipping+ * the icon itself shaves the corners off wide glyphs.+ */+@Composable+private fun TransportGlyph(+ icon: ImageVector,+ contentDescription: String,+ size: Dp,+ touchSize: Dp = size,+ onClick: () -> Unit,+ heightScale: Float = 1f,+) {+ Box(+ modifier = Modifier+ .size(touchSize)+ .clickable(+ interactionSource = remember { MutableInteractionSource() },+ indication = null,+ ) {+ Haptics.click()+ onClick()+ },+ contentAlignment = Alignment.Center,+ ) {+ Icon(+ imageVector = icon,+ contentDescription = contentDescription,+ tint = Color.White,+ modifier = Modifier+ .size(size)+ .then(if (heightScale != 1f) Modifier.graphicsLayer { scaleY = heightScale } else Modifier),+ )+ }+}++/** ThinSlider's fixed touch target at the volume bar's size: 10dp + 22dp. */+internal val VOLUME_ROW_HEIGHT = 32.dp++/** The volume bar between its two speaker glyphs. */+@Composable+internal fun VolumeRow(volume: PlayerVolume) {+ Row(+ modifier = Modifier.fillMaxWidth(),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Icon(+ Icons.AutoMirrored.Rounded.VolumeDown,+ contentDescription = stringResource(R.string.immersive_player_volume_down),+ tint = LocalPlayerTint.current.copy(alpha = 0.5f),+ modifier = Modifier.size(20.dp),+ )+ Spacer(Modifier.width(10.dp))+ ThinSlider(+ value = volume.level.value,+ onValueChange = volume::drag,+ onValueChangeFinished = volume::release,+ idleHeight = 6.dp,+ activeHeight = 10.dp,+ modifier = Modifier.weight(1f),+ )+ Spacer(Modifier.width(10.dp))+ Icon(+ Icons.AutoMirrored.Rounded.VolumeUp,+ contentDescription = stringResource(R.string.immersive_player_volume_up),+ tint = LocalPlayerTint.current.copy(alpha = 0.5f),+ modifier = Modifier.size(20.dp),+ )+ }+}++private val BOTTOM_ACTION_SIZE = 44.dp+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++/** How wide a capsule of [segments] comes out, dividers included. */+private fun pillWidth(segments: Int): Dp = PILL_SEGMENT_WIDTH * segments + 1.dp * (segments - 1)++/**+ * A row of controls joined into one capsule. The join is a hairline rather than a gap, which is+ * what makes several controls read as a single object.+ */+@Composable+private fun Pill(content: @Composable androidx.compose.foundation.layout.RowScope.() -> Unit) {+ Row(+ modifier = Modifier+ .height(BOTTOM_ACTION_SIZE)+ .clip(CircleShape)+ .background(LocalPlayerTint.current.copy(alpha = 0.12f))+ .animateContentSize(+ animationSpec = spring(dampingRatio = 0.82f, stiffness = Spring.StiffnessMediumLow),+ ),+ verticalAlignment = Alignment.CenterVertically,+ content = content,+ )+}++@Composable+private fun PillDivider() {+ Box(+ Modifier+ .width(1.dp)+ .fillMaxHeight()+ .background(LocalPlayerTint.current.copy(alpha = 0.20f)),+ )+}++@Composable+private fun PillSegment(+ contentDescription: String,+ onClick: () -> Unit,+ icon: ImageVector,+ highlighted: Boolean = false,+ width: Dp = PILL_SEGMENT_WIDTH,+) {+ Box(+ modifier = Modifier+ .width(width)+ .height(BOTTOM_ACTION_SIZE)+ .background(if (highlighted) LocalPlayerTint.current.copy(alpha = 0.14f) else Color.Transparent)+ .clickable(+ interactionSource = remember { MutableInteractionSource() },+ indication = null,+ ) {+ Haptics.click()+ onClick()+ }+ .semantics { this.contentDescription = contentDescription },+ contentAlignment = Alignment.Center,+ ) {+ val tint = LocalPlayerTint.current.copy(alpha = if (highlighted) 1f else 0.75f)+ Row(verticalAlignment = Alignment.CenterVertically) {+ Crossfade(+ targetState = icon,+ animationSpec = tween(durationMillis = 200),+ label = "pillSegmentIcon",+ ) { current ->+ Icon(imageVector = current, contentDescription = null, tint = tint, modifier = Modifier.size(PILL_ICON_SIZE))+ }+ }+ }+}++/** One of the bottom row's round glyphs (lyrics, queue); lit while its panel is up. */+@Composable+private fun BottomGlyph(+ icon: ImageVector,+ contentDescription: String,+ onClick: () -> Unit,+ highlighted: Boolean = false,+) {+ Box(+ modifier = Modifier+ .size(BOTTOM_ACTION_SIZE)+ .clip(CircleShape)+ .background(if (highlighted) LocalPlayerTint.current.copy(alpha = 0.20f) else Color.Transparent)+ .clickable(+ interactionSource = remember { MutableInteractionSource() },+ indication = null,+ ) {+ Haptics.click()+ onClick()+ }+ .semantics { this.contentDescription = contentDescription },+ contentAlignment = Alignment.Center,+ ) {+ Icon(+ imageVector = icon,+ contentDescription = null,+ tint = LocalPlayerTint.current.copy(alpha = if (highlighted) 1f else 0.75f),+ modifier = Modifier.size(26.dp),+ )+ }+}++/**+ * Lyrics, the capsule, and the queue: the row the player ends on.+ *+ * The capsule swaps: the devices button normally, shuffle and repeat while the queue is up,+ * since that is when they are what you are about to reach for. With the queue up the lyrics+ * glyph steps aside and the capsule slides over into its place, leaving the queue glyph, lit,+ * as the way back.+ */+@Composable+internal fun PlayerActionRow(+ lyricsOpen: Boolean,+ queueOpen: Boolean,+ shuffleEnabled: Boolean,+ repeatMode: Int,+ deviceActive: Boolean,+ onToggleLyrics: () -> Unit,+ onToggleQueue: () -> Unit,+ onToggleShuffle: () -> Unit,+ onCycleRepeat: () -> Unit,+ onOpenDevices: () -> Unit,+) {+ BoxWithConstraints(Modifier.fillMaxWidth()) {+ // Sized for the wider of the two capsules in both states, so the lyrics and queue glyphs+ // do not slide as they swap.+ val widestRow = BOTTOM_ACTION_SIZE * 2 + pillWidth(2)+ val edgeInset = ((maxWidth - widestRow) / 4).coerceAtLeast(0.dp)+ // 0 with the capsule centred between lyrics and queue, 1 with it moved over to where the+ // lyrics glyph sits. Read only while placing, so the slide relays out the row and recomposes nothing.+ val toStart = animateFloatAsState(+ targetValue = if (queueOpen) 1f else 0f,+ animationSpec = tween(PILL_SLIDE_MS, easing = FastOutSlowInEasing),+ label = "playerBottomPillSlide",+ )+ Box(+ modifier = Modifier.fillMaxWidth().padding(horizontal = edgeInset),+ contentAlignment = Alignment.CenterStart,+ ) {+ // Gone while the queue is up: the playback modes take its place.+ AnimatedVisibility(+ visible = !queueOpen,+ enter = fadeIn(tween(180, delayMillis = 120)),+ exit = fadeOut(tween(120)),+ modifier = Modifier.align(Alignment.CenterStart),+ ) {+ BottomGlyph(+ icon = Icons.Rounded.Lyrics,+ contentDescription = stringResource(if (lyricsOpen) R.string.immersive_player_lyrics_close else R.string.immersive_player_lyrics),+ // Lyrics and the queue are two things to show in one place, so opening either+ // closes the other; lit to say which is up.+ onClick = onToggleLyrics,+ highlighted = lyricsOpen,+ )+ }+ AnimatedContent(+ // Laid out across the whole row and placed by hand: centred at 0, flush with the+ // lyrics glyph's left edge at 1.+ modifier = Modifier.layout { measurable, constraints ->+ val placeable = measurable.measure(constraints.copy(minWidth = 0))+ layout(constraints.maxWidth, placeable.height) {+ val centred = (constraints.maxWidth - placeable.width) / 2f+ placeable.place((centred * (1f - toStart.value)).roundToInt(), 0)+ }+ },+ targetState = queueOpen,+ transitionSpec = {+ (fadeIn(tween(180, delayMillis = 140)) togetherWith fadeOut(tween(140)))+ // Unclipped: the capsule's rounded ends are what the eye follows through the width change.+ .using(SizeTransform(clip = false) { _, _ -> tween(220) })+ },+ label = "playerBottomPill",+ ) { showQueueModes ->+ if (showQueueModes) {+ Pill {+ PillSegment(+ icon = Icons.Rounded.Shuffle,+ contentDescription = stringResource(+ if (shuffleEnabled) R.string.immersive_player_shuffle_on else R.string.immersive_player_shuffle_off,+ ),+ onClick = onToggleShuffle,+ highlighted = shuffleEnabled,+ )+ PillDivider()+ PillSegment(+ icon = if (repeatMode == ImmersiveRepeat.ONE) Icons.Rounded.RepeatOne else Icons.Rounded.Repeat,+ contentDescription = when (repeatMode) {+ ImmersiveRepeat.ONE -> stringResource(R.string.immersive_player_repeat_one)+ ImmersiveRepeat.ALL -> stringResource(R.string.immersive_player_repeat_all)+ else -> stringResource(R.string.immersive_player_repeat_off)+ },+ onClick = onCycleRepeat,+ highlighted = repeatMode != ImmersiveRepeat.OFF,+ )+ }+ } else {+ Pill {+ PillSegment(+ icon = Icons.Rounded.Devices,+ contentDescription = stringResource(R.string.immersive_player_devices),+ onClick = onOpenDevices,+ highlighted = deviceActive,+ width = pillWidth(2),+ )+ }+ }+ }+ Box(Modifier.align(Alignment.CenterEnd)) {+ BottomGlyph(+ icon = Icons.AutoMirrored.Rounded.QueueMusic,+ contentDescription = stringResource(if (queueOpen) R.string.immersive_player_queue_close else R.string.immersive_player_queue),+ onClick = onToggleQueue,+ highlighted = queueOpen,+ )+ }+ }+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/player/PlayerState.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/player/PlayerState.ktnew file mode 100644index 00000000..0fb645e4--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/player/PlayerState.kt@@ -0,0 +1,162 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * sharedUi/src/jvmSharedMain/kotlin/com/music/bitchord/ui/player/PlayerState.kt at edc1e6f.+ * Modified for Myspoti, 2026-10.+ *+ * Changes: the scrubber's hold-after-release and the volume bar's state, with the position from+ * Myspoti's playback and the volume from Android's AudioManager (STREAM_MUSIC).+ */+package com.music.spotui.ui.immersive.player++import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import android.content.IntentFilter+import android.media.AudioManager+import androidx.compose.animation.core.Animatable+import androidx.compose.animation.core.FastOutSlowInEasing+import androidx.compose.animation.core.tween+import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.Stable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableFloatStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue+import androidx.compose.ui.platform.LocalContext+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.delay+import kotlinx.coroutines.launch+import kotlin.math.abs+import kotlin.math.roundToInt++/**+ * How close the player's reported position has to get to a released scrub handle before the+ * handle stops being drawn where it was dropped.+ */+internal const val SEEK_SETTLE_TOLERANCE_MS = 1_500L++/** How long that handle is held at the drop point regardless: a backstop for a seek that never settles. */+internal const val SEEK_SETTLE_TIMEOUT_MS = 4_000L++/** The scrubber's finger state: where the handle is drawn while it is held, and right after. */+@Stable+internal class PlayerScrub {+ var scrubbing by mutableStateOf(false)+ private set++ var value by mutableFloatStateOf(0f)+ private set++ /**+ * After releasing the scrubber the player needs to buffer before it reports the new position.+ * Kept showing where the user dropped it so the handle doesn't snap back and then jump forward.+ */+ var pendingSeek by mutableStateOf<Float?>(null)++ /** Where the handle is drawn. */+ fun shown(positionMs: Long, durationMs: Long): Float {+ val fraction = if (durationMs > 0) positionMs.toFloat() / durationMs else 0f+ return when {+ scrubbing -> value+ pendingSeek != null -> pendingSeek!!+ else -> fraction.coerceIn(0f, 1f)+ }+ }++ fun drag(to: Float) {+ scrubbing = true+ value = to+ }++ fun release(seekTo: (Float) -> Unit) {+ pendingSeek = value+ seekTo(value)+ scrubbing = false+ }+}++/**+ * Released as soon as the player's own position agrees with where the handle was dropped, and+ * unconditionally a few seconds later whether it agrees or not (a clamped or rejected seek would+ * otherwise freeze the handle for the rest of the track).+ */+@Composable+internal fun rememberPlayerScrub(trackKey: Any, position: () -> Long, durationMs: Long): PlayerScrub {+ val scrub = remember { PlayerScrub() }+ val currentPosition by androidx.compose.runtime.rememberUpdatedState(position)+ LaunchedEffect(durationMs, scrub.pendingSeek) {+ val target = scrub.pendingSeek ?: return@LaunchedEffect+ if (durationMs <= 0) return@LaunchedEffect+ val goal = (target * durationMs).toLong()+ // The playhead is not Compose state: sampled a few times a second until it agrees.+ while (abs(currentPosition() - goal) >= SEEK_SETTLE_TOLERANCE_MS) delay(150)+ scrub.pendingSeek = null+ }+ LaunchedEffect(scrub.pendingSeek) {+ if (scrub.pendingSeek == null) return@LaunchedEffect+ delay(SEEK_SETTLE_TIMEOUT_MS)+ scrub.pendingSeek = null+ }+ LaunchedEffect(trackKey) { scrub.pendingSeek = null }+ return scrub+}++/** The volume bar's state: the system music level, tweened to what the system reports, followed under a finger. */+@Stable+internal class PlayerVolume(+ private val audio: AudioManager,+ private val scope: CoroutineScope,+) {+ private val max = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC).coerceAtLeast(1)++ /** A hardware step is a jump of 1/15th of the bar, which reads as a stutter unless tweened. */+ val level = Animatable(read())+ var dragging by mutableStateOf(false)+ private set++ fun read(): Float = audio.getStreamVolume(AudioManager.STREAM_MUSIC).toFloat() / max++ fun drag(to: Float) {+ dragging = true+ // Follow the finger exactly; only external changes tween.+ scope.launch { level.snapTo(to) }+ audio.setStreamVolume(AudioManager.STREAM_MUSIC, (to * max).roundToInt().coerceIn(0, max), 0)+ }++ fun release() {+ dragging = false+ }+}++/** The system music volume as a bar value, following the hardware keys and the system panel. */+@Composable+internal fun rememberPlayerVolume(): PlayerVolume {+ val context = LocalContext.current+ val scope = rememberCoroutineScope()+ val volume = remember(context) {+ PlayerVolume(context.getSystemService(Context.AUDIO_SERVICE) as AudioManager, scope)+ }+ var system by remember { mutableFloatStateOf(volume.read()) }+ DisposableEffect(context) {+ val receiver = object : BroadcastReceiver() {+ override fun onReceive(c: Context?, intent: Intent?) {+ if (intent?.getIntExtra(EXTRA_STREAM_TYPE, -1) == AudioManager.STREAM_MUSIC) system = volume.read()+ }+ }+ androidx.core.content.ContextCompat.registerReceiver(context, receiver, IntentFilter(VOLUME_CHANGED_ACTION), androidx.core.content.ContextCompat.RECEIVER_EXPORTED)+ onDispose { context.unregisterReceiver(receiver) }+ }+ // Glide to the level the system reports, but never fight the finger.+ LaunchedEffect(system) {+ if (!volume.dragging) volume.level.animateTo(system, tween(durationMillis = 220, easing = FastOutSlowInEasing))+ }+ return volume+}++// The system's volume broadcast has no public constant.+private const val VOLUME_CHANGED_ACTION = "android.media.VOLUME_CHANGED_ACTION"+private const val EXTRA_STREAM_TYPE = "android.media.EXTRA_VOLUME_STREAM_TYPE"diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/podcast/ImmersiveEpisodeRow.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/podcast/ImmersiveEpisodeRow.ktnew file mode 100644index 00000000..82cdc710--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/podcast/ImmersiveEpisodeRow.kt@@ -0,0 +1,152 @@+package com.music.spotui.ui.immersive.podcast++import androidx.compose.animation.Crossfade+import androidx.compose.animation.animateColorAsState+import androidx.compose.animation.core.tween+import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.rounded.MoreHoriz+import androidx.compose.material.icons.rounded.Pause+import androidx.compose.material.icons.rounded.PlayArrow+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import app.myspoti.engine.R+import com.music.spotui.data.entity.SongsModel+import com.music.spotui.di.Haptics+import com.music.spotui.ui.components.EpisodeDownloadButton+import com.music.spotui.ui.components.episodeClock+import com.music.spotui.ui.components.episodeDateLabel+import com.music.spotui.ui.components.episodeMinutes+import com.music.spotui.ui.immersive.Immersive+import com.music.spotui.ui.immersive.components.ImmersiveCover+import com.music.spotui.ui.immersive.components.immersiveClickable+import com.music.spotui.ui.immersive.screens.ImmersiveRowDivider++/**+ * One episode (or book chapter) of a show: cover, title, a snippet, "date · length" and what is+ * left of it, then its own controls (menu, download, play). A tap opens the episode, a long press+ * opens its menu; the row shrinks a little under the finger.+ */+@Composable+internal fun ImmersiveEpisodeRow(+ episode: SongsModel,+ playing: Boolean,+ finished: Boolean,+ onPlay: () -> Unit,+ onOpen: () -> Unit,+ onMenu: () -> Unit,+ modifier: Modifier = Modifier,+) {+ val date = episodeDateLabel(episode.releaseDate)+ val minutes = episodeMinutes(episode.durationMs)+ val titleColor by animateColorAsState(if (playing) Immersive.Accent else Immersive.Text, label = "episode row title")+ Column(modifier.fillMaxWidth()) {+ Column(+ Modifier+ .fillMaxWidth()+ .immersiveClickable(onClick = onOpen, onLongClick = onMenu, pressedScale = 0.98f)+ .padding(horizontal = Immersive.Gutter, vertical = 12.dp),+ ) {+ Row {+ ImmersiveCover(episode.coverUri, Modifier.size(64.dp), Immersive.CoverSmall)+ Column(Modifier.weight(1f).padding(start = 14.dp)) {+ Text(+ text = episode.title,+ style = Immersive.BodyStrong.copy(color = titleColor),+ maxLines = 2,+ overflow = TextOverflow.Ellipsis,+ )+ if (episode.description.isNotBlank()) {+ Spacer(Modifier.height(3.dp))+ Text(text = episode.description, style = Immersive.Subhead, maxLines = 2, overflow = TextOverflow.Ellipsis)+ }+ Spacer(Modifier.height(4.dp))+ val started = episode.playedPositionMs > 0 && !finished+ Row(verticalAlignment = Alignment.CenterVertically) {+ val meta = buildString {+ if (finished) append(stringResource(R.string.episode_marked_played)).append(" · ")+ append(if (date.isBlank()) minutes else "$date · $minutes")+ }+ Text(text = meta, style = Immersive.Caption, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))+ if (started) {+ Text(+ text = stringResource(R.string.episode_remaining, episodeClock(episode.durationMs - episode.playedPositionMs)),+ style = Immersive.Caption.copy(color = Immersive.Accent),+ maxLines = 1,+ modifier = Modifier.padding(start = 8.dp),+ )+ }+ }+ }+ }+ Row(+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.End,+ modifier = Modifier.fillMaxWidth().padding(top = 8.dp),+ ) {+ Box(+ Modifier+ .size(40.dp)+ .clip(CircleShape)+ .immersiveClickable(onClick = onMenu, pressedScale = 0.9f),+ contentAlignment = Alignment.Center,+ ) {+ Icon(+ Icons.Rounded.MoreHoriz,+ contentDescription = stringResource(R.string.episode_options),+ tint = Immersive.TextSecondary,+ modifier = Modifier.size(22.dp),+ )+ }+ Spacer(Modifier.weight(1f))+ EpisodeDownloadButton(episode, size = 24.dp)+ Spacer(Modifier.width(8.dp))+ PlayDisc(playing = playing, onClick = onPlay)+ }+ }+ ImmersiveRowDivider(inset = Immersive.Gutter)+ }+}++/** The episode's own play control: an accent disc with the triangle (two bars while it plays). */+@Composable+internal fun PlayDisc(playing: Boolean, onClick: () -> Unit, modifier: Modifier = Modifier) {+ Box(+ modifier+ .size(40.dp)+ .immersiveClickable(onClick = { Haptics.click(); onClick() }, pressedScale = 0.9f)+ .clip(CircleShape)+ .background(Immersive.Accent),+ contentAlignment = Alignment.Center,+ ) {+ Crossfade(targetState = playing, animationSpec = tween(150), label = "episode play glyph") { on ->+ Icon(+ imageVector = if (on) Icons.Rounded.Pause else Icons.Rounded.PlayArrow,+ contentDescription = stringResource(if (on) R.string.notif_action_pause else R.string.episode_play),+ tint = Color.White,+ modifier = Modifier.size(24.dp),+ )+ }+ }+}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.ktnew file mode 100644index 00000000..8b2ad716--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/podcast/ImmersiveHeaderParts.kt@@ -0,0 +1,76 @@+package com.music.spotui.ui.immersive.podcast++import androidx.compose.animation.animateColorAsState+import androidx.compose.animation.core.tween+import androidx.compose.foundation.LocalOverscrollFactory+import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.lazy.LazyItemScope+import com.music.spotui.ui.immersive.motion.immersiveItemPlacement+import androidx.compose.foundation.lazy.LazyListState+import androidx.compose.runtime.Composable+import androidx.compose.runtime.CompositionLocalProvider+import androidx.compose.runtime.getValue+import androidx.compose.runtime.remember+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Brush+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.lerp+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp+import com.music.spotui.ui.immersive.components.rememberImmersiveOverscrollFactory+import com.music.spotui.ui.immersive.shell.immersiveTopBarHeight+import com.music.spotui.ui.look.rememberReduceMotion+import com.music.spotui.ui.look.rememberArtworkColors++/**+ * The bar's small title takes over once a page's header (the first list item) has scrolled up+ * under it: 0 while the header's large title shows, 1 after. Read inside draw layers only.+ */+@Composable+fun rememberHeaderCollapse(listState: LazyListState): () -> Float {+ val barPx = with(LocalDensity.current) { immersiveTopBarHeight().toPx() }+ val fadePx = with(LocalDensity.current) { 40.dp.toPx() }+ return remember(listState, barPx, fadePx) {+ val fraction: () -> Float = {+ if (listState.firstVisibleItemIndex > 0) 1f+ else {+ val header = listState.layoutInfo.visibleItemsInfo.firstOrNull()?.size?.toFloat() ?: 0f+ if (header <= 0f) 0f+ else ((listState.firstVisibleItemScrollOffset - (header - barPx - fadePx)) / fadePx).coerceIn(0f, 1f)+ }+ }+ fraction+ }+}++/**+ * A wash of the cover's own colour that fades into the black page: the backdrop of a header whose+ * artwork is not full bleed. It cross-fades when the cover (and so its colour) changes.+ */+@Composable+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")+ Box(+ modifier+ .height(height)+ .background(Brush.verticalGradient(listOf(tint.copy(alpha = 0.62f), Color.Transparent))),+ )+}++/** Gives every list and page inside [content] the Immersive look's iOS-style rubber-band overscroll. */+@Composable+fun ImmersiveOverscrollHost(content: @Composable () -> Unit) {+ CompositionLocalProvider(LocalOverscrollFactory provides rememberImmersiveOverscrollFactory(), content = content)+}++/**+ * A list row's placement animation: rows slide to their new place on one soft spring when the+ * list changes (a sort, a removal) and do not fade. Nothing moves when the phone asks for no animation.+ */+@Composable+fun LazyItemScope.rowPlacement(): Modifier = immersiveItemPlacement()diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/podcast/ImmersiveShowScreen.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/podcast/ImmersiveShowScreen.ktnew file mode 100644index 00000000..77acc94b--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/podcast/ImmersiveShowScreen.kt@@ -0,0 +1,286 @@+package com.music.spotui.ui.immersive.podcast++import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.layout.widthIn+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.lazy.rememberLazyListState+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.rounded.Add+import androidx.compose.material.icons.rounded.Check+import androidx.compose.material.icons.rounded.Podcasts+import androidx.compose.material.icons.rounded.Star+import androidx.compose.material.icons.rounded.SwapVert+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import androidx.lifecycle.viewmodel.compose.viewModel+import androidx.navigation.NavController+import app.myspoti.engine.R+import com.music.spotui.data.api.Response+import com.music.spotui.data.entity.SongsModel+import com.music.spotui.di.Haptics+import com.music.spotui.di.SongPlayer+import com.music.spotui.ui.components.EpisodeOptionsSheet+import com.music.spotui.ui.immersive.Immersive+import com.music.spotui.ui.immersive.components.ImmersiveButton+import com.music.spotui.ui.immersive.components.ImmersiveCover+import com.music.spotui.ui.immersive.components.ImmersiveMessageState+import com.music.spotui.ui.immersive.components.immersiveClickable+import com.music.spotui.ui.immersive.components.immersiveSongListSkeleton+import com.music.spotui.ui.immersive.screens.ImmersiveAboutText+import com.music.spotui.ui.immersive.screens.ImmersiveChip+import com.music.spotui.ui.immersive.screens.ImmersiveChipRow+import com.music.spotui.ui.immersive.shell.ImmersiveTopBar+import com.music.spotui.ui.immersive.shell.immersiveHazeSource+import com.music.spotui.ui.immersive.shell.immersiveTopContentPadding+import com.music.spotui.ui.navigation.episodeRoute+import com.music.spotui.ui.viewmodel.ShowViewModel++private val ShowCover = 208.dp++/**+ * A show (or audiobook) page in the Immersive look: the cover on a wash of its own colour, the+ * name, who makes it, the rating and Follow; then Episodes (or Chapters) and About as pills, the+ * sort order, and the episodes with their own play, download and menu controls. Same+ * [ShowViewModel] and actions as the Classic show page.+ */+@Composable+fun ImmersiveShowScreen(navController: NavController, showId: String, showName: String = "") {+ val vm: ShowViewModel = viewModel()+ val context = LocalContext.current+ LaunchedEffect(showId) { vm.loadShow(showId) }++ val pageState by vm.page.collectAsState()+ val page = (pageState as? Response.Success)?.data+ val show = page?.show+ val audiobook = page?.audiobook == true+ val items = page?.items.orEmpty()+ val displayName = show?.name?.takeIf { it.isNotBlank() } ?: showName+ val cover = page?.coverUri.orEmpty()++ var tab by remember { mutableStateOf(0) }+ var oldestFirst by remember { mutableStateOf(false) }+ var menuSong by remember { mutableStateOf<SongsModel?>(null) }+ val np by SongPlayer.nowPlaying+ val listState = rememberLazyListState()++ fun playAt(index: Int) {+ val song = items.getOrNull(index) ?: return+ vm.updateQueue(items)+ SongPlayer.playSong(song.url, context, contextUri = "spotify:show:$showId")+ vm.updateSongState(song.coverUri, song.title, song.singer, true, song.id, index, song.album)+ }++ val rows = remember(items, oldestFirst) { if (oldestFirst) items.reversed() else items }++ menuSong?.let { sel ->+ EpisodeOptionsSheet(+ song = sel,+ finished = vm.isFinished(sel),+ onPlay = {+ val index = items.indexOfFirst { it.url == sel.url }+ if (index >= 0) playAt(index)+ },+ onMarkFinished = { vm.setFinished(sel, it) },+ onOpen = { navController.navigate(episodeRoute(sel.url.removePrefix("episode:"), sel.title)) },+ onDismiss = { menuSong = null },+ )+ }++ ImmersiveOverscrollHost {+ Box(Modifier.fillMaxSize().background(Immersive.Page)) {+ LazyColumn(+ state = listState,+ contentPadding = PaddingValues(bottom = Immersive.BottomChrome),+ modifier = Modifier.fillMaxSize().immersiveHazeSource(),+ ) {+ item(key = "header") {+ ShowHeader(+ show = show,+ name = displayName,+ cover = cover,+ following = vm.following.value,+ onFollow = { on ->+ Haptics.toggle(on)+ vm.setFollow(showId, on)+ },+ )+ }+ item(key = "tabs") {+ ImmersiveChipRow {+ ImmersiveChip(+ label = stringResource(if (audiobook) R.string.show_tab_chapters else R.string.show_tab_episodes),+ selected = tab == 0,+ onClick = { tab = 0 },+ )+ ImmersiveChip(stringResource(R.string.show_tab_about), selected = tab == 1, onClick = { tab = 1 })+ }+ }+ if (tab == 0 && rows.isNotEmpty()) item(key = "sort") {+ Row(+ verticalAlignment = Alignment.CenterVertically,+ modifier = Modifier+ .immersiveClickable(onClick = { oldestFirst = !oldestFirst }, pressedScale = 0.96f)+ .padding(horizontal = Immersive.Gutter, vertical = 12.dp),+ ) {+ Icon(Icons.Rounded.SwapVert, contentDescription = null, tint = Immersive.Accent, modifier = Modifier.size(18.dp))+ Spacer(Modifier.width(8.dp))+ Text(+ text = stringResource(+ when {+ audiobook && oldestFirst -> R.string.show_sort_chapters_oldest+ audiobook -> R.string.show_sort_chapters_newest+ oldestFirst -> R.string.show_sort_oldest+ else -> R.string.show_sort_newest+ },+ ),+ style = Immersive.Subhead.copy(color = Immersive.Accent, fontWeight = FontWeight.Medium),+ )+ }+ }+ if (pageState is Response.Loading && page == null) immersiveSongListSkeleton(count = 5, keyPrefix = "skeleton:show", alpha = 0.5f)+ if (pageState is Response.Error && items.isEmpty()) item(key = "error") {+ ImmersiveMessageState((pageState as Response.Error).error)+ }+ if (tab == 1) item(key = "about") { About(show) }+ if (tab == 0 && page != null && items.isEmpty() && pageState !is Response.Loading) item(key = "empty") {+ ImmersiveMessageState(stringResource(R.string.show_empty))+ }+ if (tab == 0) items(rows, key = { it.url }) { ep ->+ ImmersiveEpisodeRow(+ episode = ep,+ playing = np.uri == "spotify:episode:${ep.url.removePrefix("episode:")}" && SongPlayer.isPlaying(),+ finished = vm.isFinished(ep),+ onPlay = {+ val index = items.indexOfFirst { it.url == ep.url }+ if (index >= 0) playAt(index)+ },+ onOpen = { navController.navigate(episodeRoute(ep.url.removePrefix("episode:"), ep.title)) },+ onMenu = { menuSong = ep },+ modifier = rowPlacement(),+ )+ }+ }+ ImmersiveTopBar(+ title = displayName,+ collapse = rememberHeaderCollapse(listState),+ onBack = { navController.navigateUp() },+ )+ }+ }+}++@Composable+private fun ShowHeader(+ show: com.music.spotui.data.entity.PodcastModel?,+ name: String,+ cover: String,+ following: Boolean,+ onFollow: (Boolean) -> Unit,+) {+ Box(Modifier.fillMaxWidth()) {+ CoverGlow(cover, height = 420.dp)+ Column(+ horizontalAlignment = Alignment.CenterHorizontally,+ modifier = Modifier.fillMaxWidth().padding(top = immersiveTopContentPadding() + 8.dp, bottom = 8.dp),+ ) {+ ImmersiveCover(cover, Modifier.size(ShowCover), Immersive.CoverLarge, placeholderIcon = Icons.Rounded.Podcasts)+ Spacer(Modifier.height(20.dp))+ Text(+ text = name,+ style = Immersive.LargeTitle,+ textAlign = TextAlign.Center,+ maxLines = 3,+ overflow = TextOverflow.Ellipsis,+ modifier = Modifier.padding(horizontal = Immersive.Gutter),+ )+ val authors = show?.authors.orEmpty().joinToString(", ")+ val narrators = show?.narrators.orEmpty().joinToString(", ")+ val byline = when {+ authors.isNotBlank() -> stringResource(R.string.show_authors, authors)+ show != null && show.publisher.isNotBlank() -> show.publisher+ else -> ""+ }+ if (byline.isNotBlank()) {+ Text(+ text = byline,+ style = Immersive.Subhead.copy(color = Immersive.Accent),+ textAlign = TextAlign.Center,+ maxLines = 2,+ overflow = TextOverflow.Ellipsis,+ modifier = Modifier.padding(horizontal = Immersive.Gutter).padding(top = 4.dp),+ )+ }+ if (narrators.isNotBlank()) {+ Text(+ text = stringResource(R.string.show_narrators, narrators),+ style = Immersive.Caption,+ textAlign = TextAlign.Center,+ maxLines = 2,+ overflow = TextOverflow.Ellipsis,+ modifier = Modifier.padding(horizontal = Immersive.Gutter).padding(top = 2.dp),+ )+ }+ val rating = show?.rating ?: 0.0+ if (rating > 0.0) {+ Row(Modifier.padding(top = 8.dp), verticalAlignment = Alignment.CenterVertically) {+ Icon(Icons.Rounded.Star, contentDescription = null, tint = Immersive.TextSecondary, modifier = Modifier.size(16.dp))+ Spacer(Modifier.width(4.dp))+ Text(String.format(java.util.Locale.getDefault(), "%.1f", rating), style = Immersive.Subhead)+ }+ }+ Spacer(Modifier.height(16.dp))+ ImmersiveButton(+ text = stringResource(if (following) R.string.show_following else R.string.show_follow),+ icon = if (following) Icons.Rounded.Check else Icons.Rounded.Add,+ filled = !following,+ modifier = Modifier.widthIn(min = 170.dp),+ onClick = { onFollow(!following) },+ )+ }+ }+}++@Composable+private fun About(show: com.music.spotui.data.entity.PodcastModel?) {+ val authors = show?.authors.orEmpty().joinToString(", ")+ val narrators = show?.narrators.orEmpty().joinToString(", ")+ Column(Modifier.fillMaxWidth().padding(horizontal = Immersive.Gutter, vertical = 8.dp)) {+ if (!show?.description.isNullOrBlank()) ImmersiveAboutText(show?.description.orEmpty(), maxLines = 8)+ if (authors.isNotBlank()) {+ Spacer(Modifier.height(12.dp))+ Text(stringResource(R.string.show_authors, authors), style = Immersive.Subhead)+ }+ if (narrators.isNotBlank()) {+ Spacer(Modifier.height(4.dp))+ Text(stringResource(R.string.show_narrators, narrators), style = Immersive.Subhead)+ }+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveArtistReleasesScreen.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveArtistReleasesScreen.ktnew file mode 100644index 00000000..6d7174b7--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveArtistReleasesScreen.kt@@ -0,0 +1,181 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * app/src/main/java/com/music/bitchord/ui/screens/DetailScreen.kt (ArtistShelfGridPage, the+ * page's section headings) at edc1e6f. Modified for Myspoti, 2026-10.+ */+package com.music.spotui.ui.immersive.screens++import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.lazy.rememberLazyListState+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import androidx.lifecycle.viewmodel.compose.viewModel+import androidx.navigation.NavController+import app.myspoti.engine.R+import com.music.spotui.data.api.Response+import com.music.spotui.data.entity.AlbumsModel+import com.music.spotui.ui.immersive.Immersive+import com.music.spotui.ui.immersive.components.ImmersiveListRow+import com.music.spotui.ui.immersive.components.ImmersiveSongRowSkeleton+import com.music.spotui.ui.immersive.components.SectionHeader+import com.music.spotui.ui.immersive.components.immersiveClickable+import com.music.spotui.ui.immersive.shell.ImmersiveTopBar+import com.music.spotui.ui.immersive.shell.immersiveHazeSource+import com.music.spotui.ui.immersive.shell.immersiveLargeTitle+import com.music.spotui.ui.immersive.shell.immersiveTopContentPadding+import com.music.spotui.ui.navigation.albumRoute+import com.music.spotui.ui.viewmodel.ArtistViewModel++/**+ * All of an artist's releases, in the Immersive look: filter chips (albums, singles and EPs,+ * featured on) over the latest release and then the releases grouped by kind, newest first.+ * Same data as the Classic releases page.+ */+@Composable+fun ImmersiveArtistReleasesScreen(navController: NavController, artistName: String, artistId: String) {+ val artistViewModel: ArtistViewModel = viewModel()+ val overview by artistViewModel.overview.collectAsState()++ LaunchedEffect(artistName, artistId) { artistViewModel.loadArtistOverview(artistName, artistId) }++ val data = (overview as? Response.Success)?.data+ val releases = data?.popularReleases ?: emptyList()+ val featuredOn = data?.appearsOn ?: emptyList()+ // Releases grouped by kind. The catalogue names the kinds in capitals ("ALBUM", "SINGLE"…):+ // compared without case.+ val albums = releases.filter { it.type.lowercase() == "album" || it.type.lowercase() == "compilation" }+ val singles = releases.filter { it.type.lowercase() == "single" || it.type.lowercase() == "ep" }+ val untyped = releases.filter { it.type.lowercase() !in setOf("album", "compilation", "single", "ep") }+ val latest = releases.maxByOrNull { it.time }+ var filter by remember { mutableStateOf("") } // "" | "albums" | "singles" | "featured"+ val listState = rememberLazyListState()+ val releasesTitle = stringResource(R.string.releases_title)++ fun openAlbum(album: AlbumsModel) {+ navController.navigate(albumRoute(album.name, album.artists.ifBlank { artistName }, album.spotifyId))+ }++ Box(Modifier.fillMaxSize().background(Immersive.Page)) {+ LazyColumn(+ state = listState,+ contentPadding = PaddingValues(top = immersiveTopContentPadding(), bottom = Immersive.BottomChrome),+ modifier = Modifier.fillMaxSize().immersiveHazeSource(),+ ) {+ immersiveLargeTitle(title = releasesTitle, subtitle = data?.name?.ifBlank { artistName } ?: artistName)+ item(key = "chips") {+ Row(+ modifier = Modifier.padding(horizontal = Immersive.Gutter).padding(top = 4.dp, bottom = 8.dp),+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ ReleaseFilterChip(stringResource(R.string.artist_releases_albums), filter == "albums") {+ filter = if (filter == "albums") "" else "albums"+ }+ ReleaseFilterChip(stringResource(R.string.artist_releases_singles), filter == "singles") {+ filter = if (filter == "singles") "" else "singles"+ }+ if (featuredOn.isNotEmpty()) {+ ReleaseFilterChip(stringResource(R.string.immersive_detail_featured_on), filter == "featured") {+ filter = if (filter == "featured") "" else "featured"+ }+ }+ }+ }+ if (overview is Response.Loading) {+ items(6, key = { "skeleton:release:$it" }) { index -> ImmersiveSongRowSkeleton(index) }+ }+ when (filter) {+ "albums" -> releaseRows(albums, ::openAlbum)+ "singles" -> releaseRows(singles, ::openAlbum)+ "featured" -> releaseRows(featuredOn, ::openAlbum)+ else -> {+ latest?.let {+ item(key = "latest-header") { SectionHeader(stringResource(R.string.latest_release_title)) }+ releaseRows(listOf(it), ::openAlbum)+ }+ if (albums.isNotEmpty()) {+ item(key = "albums-header") { SectionHeader(stringResource(R.string.artist_releases_albums)) }+ releaseRows(albums, ::openAlbum)+ }+ if (singles.isNotEmpty()) {+ item(key = "singles-header") { SectionHeader(stringResource(R.string.artist_releases_singles)) }+ releaseRows(singles, ::openAlbum)+ }+ if (untyped.isNotEmpty()) {+ if (albums.isEmpty() && singles.isEmpty()) {+ item(key = "untyped-header") { SectionHeader(stringResource(R.string.popular_releases_section_title)) }+ }+ releaseRows(untyped, ::openAlbum)+ }+ }+ }+ }+ ImmersiveTopBar(+ title = releasesTitle,+ listState = listState,+ onBack = { navController.navigateUp() },+ )+ }+}++/** One [ImmersiveListRow] per release. */+private fun androidx.compose.foundation.lazy.LazyListScope.releaseRows(+ releases: List<AlbumsModel>,+ onOpen: (AlbumsModel) -> Unit,+) {+ items(releases) { album ->+ ReleaseRow(album) { onOpen(album) }+ }+}++@Composable+private fun ReleaseRow(album: AlbumsModel, onClick: () -> Unit) {+ ImmersiveListRow(+ title = album.name,+ subtitle = releaseDetail(album).ifBlank { album.artists },+ imageUrl = album.coverUri,+ round = false,+ onClick = onClick,+ )+}++/** A filter pill: the accent when it is on, the raised grey when it is not. */+@Composable+private fun ReleaseFilterChip(label: String, selected: Boolean, onClick: () -> Unit) {+ Box(+ modifier = Modifier+ .immersiveClickable(onClick = onClick)+ .clip(CircleShape)+ .background(if (selected) Immersive.Accent else Immersive.Raised)+ .padding(horizontal = 14.dp, vertical = 8.dp),+ contentAlignment = Alignment.Center,+ ) {+ Text(+ text = label,+ style = Immersive.Subhead.copy(+ color = if (selected) androidx.compose.ui.graphics.Color.White else Immersive.Text,+ fontWeight = FontWeight.SemiBold,+ ),+ )+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveArtistScreen.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveArtistScreen.ktnew file mode 100644index 00000000..518c41fb--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveArtistScreen.kt@@ -0,0 +1,516 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * app/src/main/java/com/music/bitchord/ui/screens/DetailScreen.kt at edc1e6f. Modified for Myspoti, 2026-10.+ */+package com.music.spotui.ui.immersive.screens++import android.annotation.SuppressLint+import androidx.compose.foundation.background+import androidx.compose.foundation.gestures.snapping.rememberSnapFlingBehavior+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxWithConstraints+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.LazyRow+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.lazy.rememberLazyListState+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.rounded.Check+import androidx.compose.material.icons.rounded.MoreHoriz+import androidx.compose.material.icons.rounded.PersonAdd+import androidx.compose.material.icons.rounded.Shuffle+import androidx.compose.material.icons.rounded.Verified+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.res.pluralStringResource+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import androidx.lifecycle.viewmodel.compose.viewModel+import androidx.navigation.NavController+import app.myspoti.engine.R+import com.music.spotui.data.api.Response+import com.music.spotui.data.entity.AlbumsModel+import com.music.spotui.data.entity.ArtistOverviewModel+import com.music.spotui.data.entity.SongsModel+import com.music.spotui.di.Graph+import com.music.spotui.di.SongPlayer+import com.music.spotui.ui.immersive.Immersive+import com.music.spotui.ui.immersive.components.ImmersiveCircleButton+import com.music.spotui.ui.immersive.components.ImmersiveCover+import com.music.spotui.ui.immersive.components.ImmersiveMessageState+import com.music.spotui.ui.immersive.components.ImmersiveShelf+import com.music.spotui.ui.immersive.components.ImmersiveShelfCard+import com.music.spotui.ui.immersive.components.SectionHeader+import com.music.spotui.ui.immersive.components.immersiveDetailSkeleton+import com.music.spotui.ui.immersive.shell.ImmersiveBarAction+import com.music.spotui.ui.immersive.shell.ImmersiveTopBar+import com.music.spotui.ui.immersive.shell.immersiveHazeSource+import com.music.spotui.ui.immersive.shell.immersiveChromeScroll+import com.music.spotui.ui.immersive.shell.immersiveTopBarHeight+import com.music.spotui.ui.navigation.Routes+import com.music.spotui.ui.navigation.albumRoute+import com.music.spotui.ui.navigation.artistRoute+import com.music.spotui.ui.navigation.likedByArtistRoute+import com.music.spotui.ui.viewmodel.ArtistViewModel++private const val MAX_ARTIST_SONGS = 10+private const val SONGS_PER_COLUMN = 4+private const val ARTIST_ROW_MAX_ITEMS = 5++/** The artist photo, very slightly taller than it is wide. */+private const val ARTIST_PHOTO_RATIO = 0.95f++/**+ * How far past the foot of the artist photo the name is allowed to hang: dropped clear of the+ * picture it sits on the faded page instead, which has nothing in it to compete.+ */+private val HeaderDrop = 44.dp++/** How far the artist name and everything under it sit above the usual [HeaderDrop]. */+private val ArtistHeaderLift = 64.dp++/** The artist action row: a large Play flanked by two smaller circles. */+private val PlayButton = 70.dp+private const val PLAY_ICON_SCALE = 0.56f+private val SideButton = 52.dp+private val ActionGap = 24.dp++/** A column of top songs is this share of the row, so the next one shows beside it. */+private const val TRACK_COLUMN_FRACTION = 0.88f+private val TrackColumnMaxWidth = 400.dp++private fun grouped(n: Long): String = "%,d".format(n)++/** "2024" or "2024-05-17" -> "2024". */+private fun releaseYear(album: AlbumsModel): String = album.time.take(4)++/** "2024 · Single": what a release card says under its name. */+@Composable+internal fun releaseDetail(album: AlbumsModel): String {+ val kind = when (album.type.uppercase()) {+ "SINGLE" -> stringResource(R.string.album_type_single)+ "EP" -> stringResource(R.string.album_type_ep)+ "COMPILATION" -> stringResource(R.string.album_type_compilation)+ "" -> ""+ else -> stringResource(R.string.album_type_album)+ }+ return listOf(releaseYear(album), kind).filter { it.isNotBlank() }.joinToString(" · ")+}++/**+ * Artist page of the Immersive look: the photo full bleed up under the bar, dissolving into the+ * page with the name over it, then Shuffle, Play and Follow, the latest release, the top songs+ * paged four at a time, the discography shelves, who the artist appears with, similar artists and+ * the biography. Same [ArtistViewModel] and actions as the Classic page.+ */+@Composable+fun ImmersiveArtistScreen(navController: NavController, artistName: String, artistId: String = "") {+ val artistViewModel: ArtistViewModel = viewModel()+ val overview by artistViewModel.overview.collectAsState()++ LaunchedEffect(artistName, artistId) { artistViewModel.loadArtistOverview(artistName, artistId) }++ BoxWithConstraints(Modifier.fillMaxSize().background(Immersive.Page)) {+ // Measured rather than read off the window, and capped against the window's own height so+ // a landscape window still shows the track list under the photo.+ val artHeight = (maxWidth / ARTIST_PHOTO_RATIO).coerceAtMost(maxHeight * 0.6f)+ when (val state = overview) {+ is Response.Loading -> ArtistLoading(navController, artistName, artHeight)+ is Response.Error -> Box(Modifier.fillMaxSize()) {+ ImmersiveMessageState(+ message = stringResource(R.string.page_load_failed),+ actionLabel = stringResource(R.string.retry_button),+ onAction = { artistViewModel.loadArtistOverview(artistName, artistId) },+ modifier = Modifier.padding(top = immersiveTopBarHeight()),+ )+ ImmersiveTopBar(title = "", collapse = { 0f }, onBack = { navController.navigateUp() })+ }+ is Response.Success -> ArtistOverviewContent(navController, artistViewModel, state.data, artistName, artHeight)+ }+ }+}++/** The name is all the row that was tapped knew; the rest stands as shimmer. */+@Composable+private fun ArtistLoading(navController: NavController, artistName: String, artHeight: Dp) {+ val listState = rememberLazyListState()+ Box(Modifier.fillMaxSize()) {+ LazyColumn(+ state = listState,+ userScrollEnabled = false,+ contentPadding = PaddingValues(bottom = Immersive.BottomChrome),+ modifier = Modifier.fillMaxSize(),+ ) {+ item(key = "header") { ArtistNameHeader(name = artistName, artHeight = artHeight) }+ immersiveDetailSkeleton(isArtist = true)+ }+ ImmersiveTopBar(title = "", collapse = { 0f }, onBack = { navController.navigateUp() })+ }+}++/** The name, hung below where the photo ends, with [extra] (verified, listeners) under it. */+@Composable+private fun ArtistNameHeader(+ name: String,+ artHeight: Dp,+ extra: (@Composable () -> Unit)? = null,+) {+ Box(Modifier.fillMaxWidth()) {+ Spacer(Modifier.fillMaxWidth().height(artHeight + HeaderDrop - ArtistHeaderLift))+ Column(+ modifier = Modifier.align(Alignment.BottomCenter),+ horizontalAlignment = Alignment.CenterHorizontally,+ ) {+ Text(+ text = name,+ style = Immersive.LargeTitle.copy(fontSize = 44.sp, lineHeight = 48.sp, fontWeight = FontWeight.ExtraBold),+ textAlign = TextAlign.Center,+ maxLines = 2,+ overflow = TextOverflow.Ellipsis,+ modifier = Modifier.padding(start = Immersive.Gutter + 8.dp, end = Immersive.Gutter + 8.dp, top = 14.dp, bottom = 7.dp),+ )+ extra?.invoke()+ }+ }+}++@SuppressLint("DefaultLocale")+@Composable+private fun ArtistOverviewContent(+ navController: NavController,+ artistViewModel: ArtistViewModel,+ overview: ArtistOverviewModel,+ artistName: String,+ artHeight: Dp,+) {+ val context = LocalContext.current+ val tracks = overview.topTracks+ val displayName = overview.name.ifBlank { artistName }++ var menuSong by remember { mutableStateOf<SongsModel?>(null) }+ menuSong?.let { sel ->+ com.music.spotui.ui.immersive.sheets.ImmersiveSongOptionsSheet(+ song = sel,+ navController = navController,+ context = context,+ onDismiss = { menuSong = null },+ )+ }+ var showArtistMenu by remember { mutableStateOf(false) }+ if (showArtistMenu) com.music.spotui.ui.components.ArtistOptionsSheet(+ artistId = overview.id,+ artistName = displayName,+ onDismiss = { showArtistMenu = false },+ )++ // Follow state straight from the user's library.+ var following by remember(overview.id) { mutableStateOf(false) }+ LaunchedEffect(overview.id) {+ val uris = tracks.map { "spotify:track:${it.song.spotifyTrackId}" } + "spotify:artist:${overview.id}"+ val res = SongPlayer.libraryContains(uris)+ following = "spotify:artist:${overview.id}" in res+ }+ // The user's liked songs by this artist: from the session cache, else loaded once in the background.+ var likedByArtist by remember(overview.id) { mutableStateOf<List<SongsModel>>(emptyList()) }+ LaunchedEffect(overview.id) {+ // Loaded once per session, shared by every artist page, after this page is shown.+ val all = com.music.spotui.data.api.Api.LikedCache.tracks+ ?: run { kotlinx.coroutines.delay(800); com.music.spotui.data.api.Api.LikedCache.loadOnce().await() }+ ?: return@LaunchedEffect+ likedByArtist = all.filter { s ->+ if (s.artistIds.isNotEmpty()) overview.id in s.artistIds+ else displayName.isNotBlank() && s.singer.split(", ").any { it.equals(displayName, ignoreCase = true) }+ }+ }+ val np by SongPlayer.nowPlaying+ val isThisArtist = np.contextUri == "spotify:artist:${overview.id}"+ val playingNow = artistViewModel.currentSongPlayingState.value+ val currentSongId = artistViewModel.currentSongId.value+ val isFollowing = SongPlayer.library["spotify:artist:${overview.id}"] ?: following+ val listState = rememberLazyListState()++ fun playTrackAt(index: Int) {+ if (index !in tracks.indices) return+ val songs = tracks.map { it.song }+ artistViewModel.updateQueue(songs)+ val s = songs[index]+ SongPlayer.playSong(s.url, context)+ artistViewModel.updateSongState(s.coverUri, s.title, s.singer, true, s.id, index)+ }++ // The bar's small title takes over once the name has scrolled up under it.+ val barPx = with(LocalDensity.current) { immersiveTopBarHeight().toPx() }+ val fadePx = with(LocalDensity.current) { 40.dp.toPx() }+ val collapse = remember(listState, barPx, fadePx) {+ val fraction: () -> Float = {+ if (listState.firstVisibleItemIndex > 0) 1f+ else {+ val header = listState.layoutInfo.visibleItemsInfo.firstOrNull()?.size?.toFloat() ?: 0f+ if (header <= 0f) 0f+ else ((listState.firstVisibleItemScrollOffset - (header - barPx - fadePx)) / fadePx).coerceIn(0f, 1f)+ }+ }+ fraction+ }++ Box(Modifier.fillMaxSize()) {+ // The photo is drawn behind the list rather than in it, so both agree on its height+ // (artHeight) without being able to ask each other.+ ArtistBackdrop(+ imageUrl = overview.headerImage.ifBlank { overview.avatarImage },+ artHeight = artHeight,+ listState = listState,+ modifier = Modifier.matchParentSize(),+ )+ LazyColumn(+ state = listState,+ contentPadding = PaddingValues(bottom = Immersive.BottomChrome),+ modifier = Modifier.fillMaxSize().immersiveHazeSource().immersiveChromeScroll(),+ ) {+ item(key = "header") {+ ArtistNameHeader(name = displayName, artHeight = artHeight) {+ if (overview.verified) Row(verticalAlignment = Alignment.CenterVertically) {+ Icon(Icons.Rounded.Verified, contentDescription = null, tint = Immersive.Accent, modifier = Modifier.size(18.dp))+ Spacer(Modifier.width(6.dp))+ Text(stringResource(R.string.verified_artist), style = Immersive.Subhead.copy(color = Immersive.Text, fontWeight = FontWeight.SemiBold))+ }+ overview.monthlyListeners?.let {+ val compact = android.icu.text.CompactDecimalFormat+ .getInstance(java.util.Locale.getDefault(), android.icu.text.CompactDecimalFormat.CompactStyle.SHORT)+ .format(it)+ Text(+ text = stringResource(R.string.monthly_listeners_text, compact),+ style = Immersive.Subhead,+ modifier = Modifier.padding(top = 4.dp),+ )+ }+ }+ }++ // "Your #3 artist of the past 4 weeks", from the account's Spotify top artists.+ item(key = "top-badge") { com.music.spotui.ui.screens.ArtistTopBadge(overview.id) }++ // Shuffle, Play, Follow: a large Play flanked by two smaller circles.+ item(key = "actions") {+ Row(+ modifier = Modifier.fillMaxWidth().padding(horizontal = Immersive.Gutter + 8.dp).padding(top = 14.dp, bottom = 22.dp),+ horizontalArrangement = Arrangement.spacedBy(ActionGap, Alignment.CenterHorizontally),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ ImmersiveCircleButton(+ icon = Icons.Rounded.Shuffle,+ contentDescription = stringResource(R.string.immersive_shell_shuffle),+ onClick = {+ if (tracks.isNotEmpty()) Graph.currentSongState.startShuffled(tracks.map { it.song })+ },+ tint = if (isThisArtist && Graph.currentSongState.shuffle.value) Immersive.Accent else Immersive.Text,+ size = SideButton,+ )+ ArtistPlayCircle(+ playing = isThisArtist && playingNow,+ onClick = {+ when {+ isThisArtist && playingNow -> SongPlayer.pause()+ isThisArtist -> SongPlayer.play()+ else -> playTrackAt(0)+ }+ },+ size = PlayButton,+ iconScale = PLAY_ICON_SCALE,+ containerColor = Color.White,+ )+ ImmersiveCircleButton(+ icon = if (isFollowing) Icons.Rounded.Check else Icons.Rounded.PersonAdd,+ contentDescription = stringResource(if (isFollowing) R.string.immersive_detail_unfollow else R.string.immersive_detail_follow),+ onClick = {+ val on = !(SongPlayer.library["spotify:artist:${overview.id}"] ?: following)+ following = on+ com.music.spotui.di.Haptics.toggle(on)+ SongPlayer.setSaved("spotify:artist:${overview.id}", on)+ },+ tint = if (isFollowing) Immersive.Accent else Immersive.Text,+ size = SideButton,+ )+ }+ }++ // Liked songs by this artist.+ if (likedByArtist.isNotEmpty()) item(key = "liked-by-artist") {+ ArtistLikedRow(+ title = stringResource(R.string.artist_liked_songs),+ subtitle = pluralStringResource(R.plurals.artist_liked_songs_count, likedByArtist.size, likedByArtist.size, displayName),+ onClick = { navController.navigate(likedByArtistRoute(overview.id, displayName)) },+ )+ }++ // The latest release, pulled out as a card of its own.+ overview.popularReleases.maxByOrNull { it.time }?.let { latest ->+ item(key = "latest-release") {+ ArtistTopReleaseCard(+ album = latest,+ label = stringResource(R.string.latest_release_title),+ detail = releaseDetail(latest),+ onClick = { navController.navigate(albumRoute(latest.name, latest.artists.ifBlank { displayName }, latest.spotifyId)) },+ )+ }+ }++ // Popular tracks: they page sideways four at a time rather than bury the shelves.+ if (tracks.isNotEmpty()) item(key = "top-songs") {+ SectionHeader(stringResource(R.string.artist_popular_tracks))+ BoxWithConstraints {+ val columnWidth = minOf(maxWidth * TRACK_COLUMN_FRACTION, TrackColumnMaxWidth)+ val topSongsState = rememberLazyListState()+ LazyRow(+ state = topSongsState,+ contentPadding = PaddingValues(horizontal = Immersive.Gutter),+ horizontalArrangement = Arrangement.spacedBy(12.dp),+ flingBehavior = rememberSnapFlingBehavior(lazyListState = topSongsState),+ ) {+ items(tracks.take(MAX_ARTIST_SONGS).withIndex().chunked(SONGS_PER_COLUMN)) { column ->+ Column(Modifier.width(columnWidth)) {+ column.forEach { (index, item) ->+ ArtistCompactSongRow(+ song = item.song,+ subtitle = item.playcount?.let { grouped(it) } ?: item.song.singer,+ current = item.song.id == currentSongId,+ playing = item.song.id == currentSongId && playingNow,+ onClick = { playTrackAt(index) },+ onMore = { menuSong = item.song },+ )+ }+ }+ }+ }+ }+ }++ // Discography: albums, then singles and EPs; a release with no kind goes under "Popular releases".+ val releases = overview.popularReleases+ val albums = releases.filter { it.type.lowercase() == "album" || it.type.lowercase() == "compilation" }+ val singles = releases.filter { it.type.lowercase() == "single" || it.type.lowercase() == "ep" }+ val untyped = releases.filter { it.type.lowercase() !in setOf("album", "compilation", "single", "ep") }+ val openReleases = {+ navController.navigate("${Routes.ArtistReleases.route}/${android.net.Uri.encode(artistName)}?id=${android.net.Uri.encode(overview.id)}")+ }+ fun openAlbum(album: AlbumsModel) {+ navController.navigate(albumRoute(album.name, album.artists.ifBlank { displayName }, album.spotifyId))+ }+ releaseShelf(R.string.artist_releases_albums, albums, "albums", ::openAlbum, openReleases)+ releaseShelf(R.string.artist_releases_singles, singles, "singles", ::openAlbum, openReleases)+ releaseShelf(R.string.popular_releases_section_title, untyped, "untyped", ::openAlbum, openReleases)++ if (overview.appearsOn.isNotEmpty()) item(key = "appears-on") {+ ImmersiveShelf(+ title = stringResource(R.string.appears_on_section_title),+ onSeeAll = if (overview.appearsOn.size > ARTIST_ROW_MAX_ITEMS) openReleases else null,+ ) {+ items(overview.appearsOn.take(ARTIST_ROW_MAX_ITEMS)) { album ->+ ImmersiveShelfCard(+ title = album.name,+ subtitle = album.artists,+ imageUrl = album.coverUri,+ onClick = { navController.navigate(albumRoute(album.name, album.artists, album.spotifyId)) },+ )+ }+ }+ }++ if (overview.relatedArtists.isNotEmpty()) item(key = "related") {+ ImmersiveShelf(title = stringResource(R.string.fans_also_like_section_title)) {+ items(overview.relatedArtists) { artist ->+ ImmersiveShelfCard(+ title = artist.name,+ subtitle = stringResource(R.string.artist_subtitle),+ imageUrl = artist.coverUri,+ round = true,+ onClick = { navController.navigate(artistRoute(artist.name, artist.id)) },+ )+ }+ }+ }++ // About closes the page, after the shelves.+ if (!overview.biography.isNullOrBlank()) item(key = "about") {+ SectionHeader(stringResource(R.string.creator_biography_section_title))+ Column(Modifier.padding(horizontal = Immersive.Gutter)) {+ if (overview.avatarImage.isNotBlank()) {+ ImmersiveCover(+ url = overview.avatarImage,+ modifier = Modifier.fillMaxWidth().height(200.dp),+ shape = Immersive.Card,+ )+ Spacer(Modifier.height(12.dp))+ }+ ImmersiveAboutText(overview.biography.orEmpty())+ }+ }+ }++ ImmersiveTopBar(+ title = displayName,+ collapse = collapse,+ onBack = { navController.navigateUp() },+ actions = {+ ImmersiveBarAction(+ icon = Icons.Rounded.MoreHoriz,+ contentDescription = stringResource(R.string.content_description_context_menu),+ onClick = { showArtistMenu = true },+ )+ },+ )+ }+}++/** A shelf of [releases] (the first few; "See all" opens the releases page), if there are any. */+private fun androidx.compose.foundation.lazy.LazyListScope.releaseShelf(+ titleRes: Int,+ releases: List<AlbumsModel>,+ key: String,+ onOpen: (AlbumsModel) -> Unit,+ onSeeAll: () -> Unit,+) {+ if (releases.isEmpty()) return+ item(key = "releases:$key") {+ ImmersiveShelf(+ title = stringResource(titleRes),+ onSeeAll = if (releases.size > ARTIST_ROW_MAX_ITEMS) onSeeAll else null,+ ) {+ items(releases.take(ARTIST_ROW_MAX_ITEMS)) { album ->+ ImmersiveShelfCard(+ title = album.name,+ subtitle = releaseDetail(album),+ imageUrl = album.coverUri,+ onClick = { onOpen(album) },+ )+ }+ }+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveArtistScreenParts.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveArtistScreenParts.ktnew file mode 100644index 00000000..25dd3f1a--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveArtistScreenParts.kt@@ -0,0 +1,334 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * app/src/main/java/com/music/bitchord/ui/screens/DetailScreen.kt (PageBackground, PlayCircle,+ * CompactSongRow, TopReleaseCard) at edc1e6f. Modified for Myspoti, 2026-10.+ */+package com.music.spotui.ui.immersive.screens++import android.os.Build+import androidx.compose.foundation.background+import androidx.compose.foundation.border+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.lazy.LazyListState+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.rounded.Favorite+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.BlurredEdgeTreatment+import androidx.compose.ui.draw.blur+import androidx.compose.ui.draw.clip+import androidx.compose.ui.draw.clipToBounds+import androidx.compose.ui.draw.drawWithContent+import androidx.compose.ui.geometry.CornerRadius+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.graphics.BlendMode+import androidx.compose.ui.graphics.Brush+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.CompositingStrategy+import androidx.compose.ui.graphics.Path+import androidx.compose.ui.graphics.StrokeCap+import androidx.compose.ui.graphics.StrokeJoin+import androidx.compose.ui.graphics.drawscope.Stroke+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.semantics.contentDescription+import androidx.compose.ui.semantics.semantics+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.IntOffset+import androidx.compose.ui.unit.dp+import app.myspoti.engine.R+import com.bumptech.glide.integration.compose.CrossFade+import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi+import com.bumptech.glide.integration.compose.GlideImage+import com.music.spotui.data.entity.AlbumsModel+import com.music.spotui.data.entity.SongsModel+import com.music.spotui.ui.components.spotifyImageUrl+import com.music.spotui.ui.immersive.Immersive+import com.music.spotui.ui.immersive.components.ImmersiveCover+import com.music.spotui.ui.immersive.components.ImmersiveMoreButton+import com.music.spotui.ui.immersive.components.ImmersivePlayingBars+import com.music.spotui.ui.immersive.components.ImmersiveSongTitle+import com.music.spotui.ui.immersive.components.immersiveClickable+import com.music.spotui.ui.immersive.components.immersiveThumbnailBorder+import kotlin.math.roundToInt++/** How far the artist photo is blurred over its foot, where it dissolves into the page. */+private val SoftFootBlur = 48.dp++/** Where the blurred copy starts to show and where it has fully taken over. */+private val SoftFootMask = Brush.verticalGradient(+ 0.35f to Color.Transparent,+ 0.75f to Color.Black,+)++/**+ * Where the top of the artwork currently is.+ *+ * The list is the one being scrolled; the background only has to agree with it. While the header+ * is item zero and on screen, how far it has been scrolled off the top is exactly the offset the+ * picture behind it needs. Once it isn't, the picture parks two artwork-heights up — far enough+ * that no part of it comes back down.+ */+private fun LazyListState.headerTop(artHeightPx: Float): Float =+ if (firstVisibleItemIndex == 0) -firstVisibleItemScrollOffset.toFloat() else -artHeightPx * 2f++/**+ * Everything on an artist page that is colour rather than words: the photo, full bleed up under+ * the bar, with its foot dissolved into the page. A layer of its own so the list can be scrolled+ * over it rather than carry it: it follows the scroll (read in the offset block, so a scroll moves+ * it without recomposing anything) instead of being scrolled.+ *+ * A blurred copy of the photo is faded in over the lower half, so the picture loses its detail+ * before it loses its colour — a merge rather than a fade to flat black. Drawn once: nothing+ * about it changes as the page moves, so it is rasterised on the first frame and composited after.+ */+@OptIn(ExperimentalGlideComposeApi::class)+@Composable+internal fun ArtistBackdrop(+ imageUrl: String?,+ artHeight: Dp,+ listState: LazyListState,+ modifier: Modifier = Modifier,+) {+ val model = spotifyImageUrl(imageUrl)+ val artHeightPx = with(androidx.compose.ui.platform.LocalDensity.current) { artHeight.toPx() }+ val softenFoot = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S+ Box(modifier.clipToBounds()) {+ Box(+ Modifier+ .fillMaxWidth()+ .height(artHeight)+ .offset { IntOffset(0, listState.headerTop(artHeightPx).roundToInt()) },+ ) {+ Box(Modifier.matchParentSize().background(Immersive.Raised))+ if (model != null) {+ GlideImage(+ model = model,+ contentDescription = null,+ contentScale = ContentScale.Crop,+ transition = CrossFade,+ modifier = Modifier.matchParentSize(),+ )+ if (softenFoot) {+ GlideImage(+ model = model,+ contentDescription = null,+ contentScale = ContentScale.Crop,+ modifier = Modifier+ .matchParentSize()+ // Offscreen so the mask cuts the blurred result rather than each draw beneath it.+ .graphicsLayer { compositingStrategy = CompositingStrategy.Offscreen }+ .drawWithContent {+ drawContent()+ drawRect(SoftFootMask, blendMode = BlendMode.DstIn)+ }+ // Rectangle keeps the edges clamped to the picture's own colour+ // rather than fading to transparent at the foot.+ .blur(SoftFootBlur, BlurredEdgeTreatment.Rectangle),+ )+ }+ }+ // Ends on the page colour at full strength, so there is no edge left where the artwork+ // stops. Eased rather than run straight: a gradient that changes slope at a stop shows+ // a line at that stop, however close the colours either side of it are. The darkening+ // at the top keeps the bar's controls legible over a bright photo.+ Box(+ Modifier+ .matchParentSize()+ .background(+ Brush.verticalGradient(+ 0.00f to Color.Black.copy(alpha = 0.35f),+ 0.22f to Color.Transparent,+ 0.45f to Color.Transparent,+ 0.65f to Immersive.Page.copy(alpha = 0.30f),+ 0.82f to Immersive.Page.copy(alpha = 0.72f),+ 0.94f to Immersive.Page.copy(alpha = 0.95f),+ 1.00f to Immersive.Page,+ ),+ ),+ )+ }+ }+}++/**+ * The artist page's Play: a filled circle with the triangle punched out of it, so the page shows+ * through (two bars while it plays).+ */+@Composable+internal fun ArtistPlayCircle(+ playing: Boolean,+ onClick: () -> Unit,+ size: Dp,+ iconScale: Float,+ containerColor: Color,+) {+ val description = stringResource(if (playing) R.string.immersive_detail_pause else R.string.immersive_shell_play)+ Box(+ modifier = Modifier+ .immersiveClickable(onClick = onClick, pressedScale = 0.94f)+ .size(size)+ .clip(CircleShape)+ // Offscreen so the clear below cuts the circle drawn under it, not whatever the page has behind.+ .graphicsLayer { compositingStrategy = CompositingStrategy.Offscreen }+ .drawWithContent {+ drawCircle(containerColor)+ val box = this.size.minDimension * iconScale+ val unit = box / 24f+ val origin = Offset((this.size.width - box) / 2f, (this.size.height - box) / 2f)+ if (playing) {+ for (x in listOf(6.5f, 14f)) {+ drawRoundRect(+ color = Color.Black,+ topLeft = Offset(origin.x + x * unit, origin.y + 4.5f * unit),+ size = Size(3.5f * unit, 15f * unit),+ cornerRadius = CornerRadius(1.2f * unit),+ blendMode = BlendMode.Clear,+ )+ }+ } else {+ val triangle = Path().apply {+ moveTo(origin.x + 6.8f * unit, origin.y + 4.8f * unit)+ lineTo(origin.x + 19.2f * unit, origin.y + 12f * unit)+ lineTo(origin.x + 6.8f * unit, origin.y + 19.2f * unit)+ close()+ }+ drawPath(triangle, Color.Black, blendMode = BlendMode.Clear)+ // The same round-joined pen the icon is drawn with.+ drawPath(+ triangle,+ Color.Black,+ style = Stroke(width = 2f * unit, cap = StrokeCap.Round, join = StrokeJoin.Round),+ blendMode = BlendMode.Clear,+ )+ }+ }+ .semantics { contentDescription = description },+ )+}++/**+ * A row of the artist's top songs: compact, no swipe, so the horizontal paging gestures stay+ * unambiguous. [subtitle] is the play count, or the artist when there is none.+ */+@Composable+internal fun ArtistCompactSongRow(+ song: SongsModel,+ subtitle: String,+ current: Boolean,+ playing: Boolean,+ onClick: () -> Unit,+ onMore: () -> Unit,+) {+ Row(+ modifier = Modifier+ .fillMaxWidth()+ .immersiveClickable(onClick = onClick, onLongClick = onMore, pressedScale = 0.98f)+ .padding(vertical = 4.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Box(Modifier.size(48.dp)) {+ ImmersiveCover(song.coverUri, Modifier.matchParentSize(), Immersive.CoverSmall)+ if (current && playing) ImmersivePlayingBars(Modifier.align(Alignment.Center))+ }+ Spacer(Modifier.width(12.dp))+ Column(Modifier.weight(1f)) {+ ImmersiveSongTitle(+ title = song.title,+ explicit = song.explicit,+ style = Immersive.Body.copy(fontWeight = androidx.compose.ui.text.font.FontWeight.Medium),+ color = if (current) Immersive.Accent else Immersive.Text,+ )+ Text(text = subtitle, style = Immersive.Subhead, maxLines = 1, overflow = TextOverflow.Ellipsis)+ }+ ImmersiveMoreButton(onClick = onMore)+ }+}++/**+ * The artist page's top-release card: sleeve, what it is and when, and its title, in a rounded+ * veil the width of the page.+ */+@Composable+internal fun ArtistTopReleaseCard(+ album: AlbumsModel,+ label: String,+ detail: String,+ onClick: () -> Unit,+) {+ val shape = RoundedCornerShape(28.dp)+ val coverShape = RoundedCornerShape(12.dp)+ Row(+ modifier = Modifier+ .fillMaxWidth()+ .padding(horizontal = Immersive.Gutter)+ .padding(bottom = 22.dp)+ .immersiveClickable(onClick = onClick, pressedScale = 0.98f)+ // A light veil rather than a dark panel, which reads as a hole in a black page.+ .clip(shape)+ .background(Color.White.copy(alpha = 0.07f), shape)+ .border(1.dp, Color.White.copy(alpha = 0.10f), shape)+ .padding(16.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ ImmersiveCover(+ url = album.coverUri,+ modifier = Modifier.size(88.dp).immersiveThumbnailBorder(coverShape),+ shape = coverShape,+ )+ Spacer(Modifier.width(14.dp))+ Column(Modifier.weight(1f)) {+ Text(text = label, style = Immersive.Subhead, maxLines = 1, overflow = TextOverflow.Ellipsis)+ Text(text = album.name, style = Immersive.Headline, maxLines = 2, overflow = TextOverflow.Ellipsis)+ if (detail.isNotBlank()) {+ Text(text = detail, style = Immersive.Subhead, maxLines = 1, overflow = TextOverflow.Ellipsis)+ }+ }+ }+}++/** The "Liked songs" row: a heart on the Liked Songs gradient, the count under it. */+@Composable+internal fun ArtistLikedRow(title: String, subtitle: String, onClick: () -> Unit) {+ Row(+ verticalAlignment = Alignment.CenterVertically,+ modifier = Modifier+ .fillMaxWidth()+ .clickable(onClick = onClick)+ .padding(horizontal = Immersive.Gutter, vertical = 8.dp),+ ) {+ Box(+ contentAlignment = Alignment.Center,+ modifier = Modifier+ .size(52.dp)+ .clip(Immersive.CoverSmall)+ .background(Brush.linearGradient(listOf(Color(0xFF450AF5), Color(0xFF8E8EE5), Color(0xFFC4EFD9)))),+ ) {+ Icon(Icons.Rounded.Favorite, contentDescription = null, tint = Color.White, modifier = Modifier.size(22.dp))+ }+ Spacer(Modifier.width(14.dp))+ Column(Modifier.weight(1f)) {+ Text(text = title, style = Immersive.Body.copy(fontWeight = androidx.compose.ui.text.font.FontWeight.Medium), maxLines = 1)+ Text(text = subtitle, style = Immersive.Subhead, maxLines = 1, overflow = TextOverflow.Ellipsis)+ }+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveCategoryScreen.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveCategoryScreen.ktnew file mode 100644index 00000000..dac2f03a--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveCategoryScreen.kt@@ -0,0 +1,114 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * sharedUi/src/jvmSharedMain/kotlin/com/music/bitchord/ui/screens/ExploreScreen.kt+ * (MoodGenrePlaylistsScreen) at edc1e6f. Modified for Myspoti, 2026-10.+ */+package com.music.spotui.ui.immersive.screens++import com.music.spotui.ui.immersive.shell.immersiveHazeSource+import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.aspectRatio+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.lazy.grid.GridCells+import androidx.compose.foundation.lazy.grid.GridItemSpan+import androidx.compose.foundation.lazy.grid.LazyVerticalGrid+import androidx.compose.foundation.lazy.grid.items+import androidx.compose.foundation.lazy.grid.rememberLazyGridState+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import androidx.lifecycle.viewmodel.compose.viewModel+import androidx.navigation.NavController+import app.myspoti.engine.R+import com.music.spotui.data.api.Response+import com.music.spotui.data.entity.LibraryEntry+import com.music.spotui.ui.components.pressHint+import com.music.spotui.ui.immersive.Immersive+import com.music.spotui.ui.immersive.components.ImmersiveMessageState+import com.music.spotui.ui.immersive.components.ImmersiveShelfCard+import com.music.spotui.ui.immersive.components.ImmersiveShimmerBox+import com.music.spotui.ui.immersive.shell.ImmersiveLargeTitle+import com.music.spotui.ui.immersive.shell.ImmersiveTopBar+import com.music.spotui.ui.immersive.shell.immersiveTopContentPadding+import com.music.spotui.ui.navigation.albumRoute+import com.music.spotui.ui.navigation.playlistRoute+import com.music.spotui.ui.screens.ContextViewModel+import com.music.spotui.ui.viewmodel.CategoryViewModel++/**+ * A browse category's page in the Immersive look: its name as the large title (with a back+ * button in the bar) over a two-column grid of the category's playlists and albums. The data,+ * routes and prefetch are those of the Classic Category screen.+ */+@Composable+fun ImmersiveCategoryScreen(navController: NavController, genre: String, title: String) {+ val viewModel: CategoryViewModel = viewModel()+ LaunchedEffect(genre) { viewModel.load(genre) }+ val playlists by viewModel.playlists.collectAsState()+ val gridState = rememberLazyGridState()+ val collapse = gridCollapse(gridState)++ Box(Modifier.fillMaxSize().background(Immersive.Page)) {+ LazyVerticalGrid(+ state = gridState,+ columns = GridCells.Fixed(2),+ contentPadding = PaddingValues(+ start = Immersive.Gutter, end = Immersive.Gutter,+ top = immersiveTopContentPadding(), bottom = Immersive.BottomChrome,+ ),+ horizontalArrangement = Arrangement.spacedBy(14.dp),+ verticalArrangement = Arrangement.spacedBy(20.dp),+ modifier = Modifier.fillMaxSize().immersiveHazeSource(),+ ) {+ item(key = "category:title", span = { GridItemSpan(maxLineSpan) }) {+ Box(Modifier.immersiveBleed(Immersive.Gutter)) { ImmersiveLargeTitle(title) }+ }+ when (val state = playlists) {+ is Response.Loading -> items(6, key = { "category:skeleton:$it" }) {+ ImmersiveShimmerBox(Modifier.fillMaxWidth().aspectRatio(1f), Immersive.CoverMedium)+ }+ is Response.Success -> {+ if (state.data.isEmpty()) {+ item(key = "category:empty", span = { GridItemSpan(maxLineSpan) }) {+ ImmersiveMessageState(stringResource(R.string.nothing_here))+ }+ } else {+ items(state.data) { entry ->+ CategoryCard(entry, navController)+ }+ }+ }+ else -> item(key = "category:error", span = { GridItemSpan(maxLineSpan) }) {+ ImmersiveMessageState(stringResource(R.string.couldnt_load, title))+ }+ }+ }+ ImmersiveTopBar(title, collapse, onBack = { navController.popBackStack() })+ }+}++@Composable+private fun CategoryCard(entry: LibraryEntry, navController: NavController) {+ ImmersiveShelfCard(+ title = entry.name,+ subtitle = entry.subtitle,+ imageUrl = entry.coverUri,+ onClick = {+ navController.navigate(+ if (entry.isPlaylist) playlistRoute(entry.spotifyId, entry.name)+ else albumRoute(entry.name, entry.subtitle, entry.spotifyId),+ )+ },+ modifier = Modifier+ .fillMaxWidth()+ .pressHint { if (entry.isPlaylist) ContextViewModel.prefetch("playlist", entry.spotifyId) },+ )+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveContextScreen.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveContextScreen.ktnew file mode 100644index 00000000..fd360efe--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveContextScreen.kt@@ -0,0 +1,993 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * app/src/main/java/com/music/bitchord/ui/screens/DetailScreen.kt at edc1e6f. Modified for Myspoti, 2026-10.+ */+package com.music.spotui.ui.immersive.screens++import android.widget.Toast+import androidx.compose.animation.animateColorAsState+import androidx.compose.animation.core.tween+import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxWithConstraints+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.material.icons.outlined.Group+import androidx.compose.material.icons.outlined.AddCircleOutline+import androidx.compose.foundation.lazy.itemsIndexed+import com.music.spotui.ui.immersive.motion.immersiveItemPlacement+import androidx.compose.foundation.lazy.rememberLazyListState+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.rounded.Album+import androidx.compose.material.icons.rounded.AutoAwesome+import androidx.compose.material.icons.rounded.Close+import androidx.compose.material.icons.rounded.DeleteOutline+import androidx.compose.material.icons.rounded.Download+import androidx.compose.material.icons.rounded.Favorite+import androidx.compose.material.icons.rounded.FavoriteBorder+import androidx.compose.material.icons.rounded.MoreHoriz+import androidx.compose.material.icons.rounded.Pause+import androidx.compose.material.icons.rounded.PlayArrow+import androidx.compose.material.icons.rounded.QueueMusic+import androidx.compose.material.icons.rounded.Search+import androidx.compose.material.icons.rounded.Shuffle+import androidx.compose.material.icons.rounded.SwapVert+import androidx.compose.material.icons.rounded.ArrowDownward+import androidx.compose.material.icons.rounded.ArrowUpward+import androidx.compose.material3.AlertDialog+import androidx.compose.material3.CircularProgressIndicator+import androidx.compose.material3.DropdownMenu+import androidx.compose.material3.DropdownMenuItem+import androidx.compose.material3.Icon+import androidx.compose.material3.Snackbar+import androidx.compose.material3.SnackbarDuration+import androidx.compose.material3.SnackbarHost+import androidx.compose.material3.SnackbarHostState+import androidx.compose.material3.SnackbarResult+import androidx.compose.material3.Text+import androidx.compose.material3.TextButton+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.derivedStateOf+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.produceState+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue+import androidx.compose.runtime.collectAsState+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.draw.shadow+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.graphics.Brush+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.lerp+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import androidx.lifecycle.viewmodel.compose.viewModel+import androidx.navigation.NavController+import app.myspoti.engine.R+import app.myspoti.host.android.MyspotiRuntime+import com.music.spotui.data.api.Response+import com.music.spotui.data.entity.ContextPageModel+import com.music.spotui.data.entity.SongsModel+import com.music.spotui.data.local.LocalPlaylists+import com.music.spotui.data.offline.OfflineCollections+import com.music.spotui.data.offline.OfflineStatus+import com.music.spotui.data.offline.OfflineStore+import com.music.spotui.di.Graph+import com.music.spotui.di.LocalPlayer+import com.music.spotui.di.Palette+import com.music.spotui.di.SongPlayer+import com.music.spotui.ui.components.DownloadAsk+import com.music.spotui.ui.components.FastScrollbar+import com.music.spotui.ui.components.matchesFind+import com.music.spotui.ui.immersive.Immersive+import com.music.spotui.ui.immersive.components.ImmersiveButton+import com.music.spotui.ui.immersive.components.ImmersiveCircleButton+import com.music.spotui.ui.immersive.components.ImmersiveCover+import com.music.spotui.ui.immersive.components.ImmersiveExplicitBadge+import com.music.spotui.ui.immersive.components.ImmersiveListRow+import com.music.spotui.ui.immersive.components.ImmersiveMessageState+import com.music.spotui.ui.immersive.components.ImmersiveRowDividerInset+import com.music.spotui.ui.immersive.components.ImmersiveSearchField+import com.music.spotui.ui.immersive.components.ImmersiveShelf+import com.music.spotui.ui.immersive.components.ImmersiveShelfCard+import com.music.spotui.ui.immersive.components.ImmersiveShimmerBox+import com.music.spotui.ui.immersive.components.ImmersiveSongRow+import com.music.spotui.ui.immersive.components.SectionHeader+import com.music.spotui.ui.immersive.components.immersiveClickable+import com.music.spotui.ui.immersive.components.immersiveDetailSkeleton+import com.music.spotui.ui.immersive.shell.ImmersiveBarAction+import com.music.spotui.ui.immersive.shell.ImmersiveTopBar+import com.music.spotui.ui.immersive.shell.immersiveHazeSource+import com.music.spotui.ui.immersive.shell.immersiveChromeScroll+import com.music.spotui.ui.immersive.shell.immersiveTopContentPadding+import com.music.spotui.ui.navigation.albumRoute+import com.music.spotui.ui.navigation.artistRoute+import com.music.spotui.ui.navigation.profileRoute+import com.music.spotui.ui.screens.ContextViewModel+import com.music.spotui.ui.screens.SmartShuffle+import com.music.spotui.ui.screens.TrackOrder+import com.music.spotui.ui.screens.TrackSort+import com.music.spotui.ui.viewmodel.PlayerViewModel+import kotlinx.coroutines.delay+import kotlinx.coroutines.launch++/** The framed sleeve on a release page, as a fraction of the page width. */+private const val SLEEVE_FRACTION = 0.76f++/** ...and of its height, so a landscape window still shows the title under it. */+private const val SLEEVE_MAX_HEIGHT = 0.5f++private val SleeveShape = RoundedCornerShape(12.dp)+private val SleeveShadow = 18.dp++/** The inset the header text shares. */+private val HeaderGutter = Immersive.Gutter + 8.dp++/** Where the divider of a numbered row starts: clear of the track number. */+private val NumberedDividerInset = Immersive.Gutter + 24.dp + Immersive.Gutter++/** Where the find field sits once open: right under the header, which is item zero. */+private const val FIND_ITEM_INDEX = 1++/**+ * Album / playlist / Liked Songs page of the Immersive look: a large centred sleeve over a wash of+ * its own colour, the title, the owner in the accent, the meta line, Play and Shuffle, a row of+ * round buttons (save, download, smart shuffle) and the track list. The data and every action are+ * the Classic page's (same [ContextViewModel], same sheets).+ *+ * @param type "album", "playlist", "liked" or "liked-artist", as for the Classic page.+ */+@Composable+fun ImmersiveContextScreen(navController: NavController, type: String, id: String) {+ val vm: ContextViewModel = viewModel(key = "$type:$id")+ // During composition, so a cached page is there for the very first frame.+ remember(type, id) { vm.load(type, id) }+ val resp by vm.page.collectAsState()+ BoxWithConstraints(Modifier.fillMaxSize().background(Immersive.Page)) {+ val sleeve = (maxWidth * SLEEVE_FRACTION).coerceAtMost(maxHeight * SLEEVE_MAX_HEIGHT)+ when (val r = resp) {+ is Response.Loading -> ContextLoading(navController, sleeve)+ is Response.Error -> {+ Box(Modifier.fillMaxSize()) {+ ImmersiveMessageState(+ message = r.error,+ actionLabel = stringResource(R.string.retry_button),+ onAction = { vm.reload() },+ modifier = Modifier.padding(top = immersiveTopContentPadding()),+ )+ ImmersiveTopBar(title = "", collapse = { 0f }, onBack = { navController.navigateUp() })+ }+ }+ is Response.Success -> ImmersiveContextContent(navController, vm, r.data, sleeve)+ }+ }+}++/** Nothing is known of the page yet: the sleeve and the track list stand as shimmer. */+@Composable+private fun ContextLoading(navController: NavController, sleeve: Dp) {+ val listState = rememberLazyListState()+ Box(Modifier.fillMaxSize()) {+ LazyColumn(+ state = listState,+ userScrollEnabled = false,+ contentPadding = PaddingValues(top = immersiveTopContentPadding(), bottom = Immersive.BottomChrome),+ modifier = Modifier.fillMaxSize(),+ ) {+ item(key = "skeleton:context:header") {+ Column(Modifier.fillMaxWidth().padding(bottom = 18.dp), horizontalAlignment = Alignment.CenterHorizontally) {+ ImmersiveShimmerBox(Modifier.size(sleeve), SleeveShape)+ Spacer(Modifier.height(20.dp))+ ImmersiveShimmerBox(Modifier.fillMaxWidth(0.55f).height(26.dp), RoundedCornerShape(6.dp))+ Spacer(Modifier.height(10.dp))+ ImmersiveShimmerBox(Modifier.fillMaxWidth(0.35f).height(16.dp), RoundedCornerShape(6.dp))+ }+ }+ immersiveDetailSkeleton(isArtist = false)+ }+ ImmersiveTopBar(title = "", listState = listState, onBack = { navController.navigateUp() })+ }+}++@Composable+private fun ImmersiveContextContent(navController: NavController, vm: ContextViewModel, p: ContextPageModel, sleeve: Dp) {+ val context = LocalContext.current+ val playerVm: PlayerViewModel = viewModel()+ val currentSongId = playerVm.currentSongId.value+ val playing = playerVm.currentSongPlayingState.value+ val shuffle = playerVm.shuffleState.value+ val np by SongPlayer.nowPlaying+ val isLiked = p.type == "liked" || p.type == "liked-artist"+ val isThisContext = np.contextUri == p.uri || (isLiked && np.contextUri.contains(":collection"))+ val contextSaved by vm.contextSaved+ val smart = SmartShuffle.on.value == p.uri+ val tapper = rememberTrackTapper()++ // The wash behind the header: the cover's second colour, the Classic page's own extraction.+ var tintTarget by remember { mutableStateOf(Palette.cachedSecond(p.coverUri) ?: Color(0xFF3A3A3A)) }+ LaunchedEffect(p.coverUri) {+ if (p.coverUri.isNotBlank()) Palette().extractSecondColorFromCoverUrl(context, p.coverUri) { tintTarget = it }+ }+ val tint by animateColorAsState(if (isLiked) LikedTint else tintTarget, tween(350), label = "context tint")++ var menuSong by remember { mutableStateOf<SongsModel?>(null) }+ // "Find in Liked Songs / in playlist", opened from the top bar.+ var find by remember { mutableStateOf("") }+ var finding by remember { mutableStateOf(false) }+ // "Sort by" for the list, kept per list (also after leaving it or restarting the app).+ var sort by remember(p.uri) { mutableStateOf(TrackOrder.load(context, p.uri)) }+ var sortMenu by remember { mutableStateOf(false) }+ var askRemoveDownloads by remember { mutableStateOf(false) }+ var playlistMenu by remember { mutableStateOf(false) }+ var addingSongs by remember { mutableStateOf(false) }+ var albumMenu by remember { mutableStateOf(false) }+ // Collaborative playlists, as on the Classic page: the people, leaving, who added what.+ var showMembers by remember { mutableStateOf(false) }+ var leaveAsk by remember { mutableStateOf(false) }+ LaunchedEffect(Unit) { com.music.spotui.data.api.ProfileCache.ensure(context) }+ val ownPlaylist = com.music.spotui.data.api.ProfileCache.let { cache ->+ cache.name+ cache.id?.let { me -> p.ownerUri == "spotify:user:$me" } == true+ }+ val crew = vm.members.value+ if (showMembers && crew.size > 1) com.music.spotui.ui.screens.MembersSheet(+ members = crew, navController = navController,+ ownPlaylist = ownPlaylist, me = com.music.spotui.data.api.ProfileCache.id, canLeave = p.canLeave,+ onChange = { m, collaborator ->+ vm.changeMember(p, m, collaborator) { ok ->+ if (!ok) android.widget.Toast.makeText(context, R.string.playlist_change_refused, android.widget.Toast.LENGTH_SHORT).show()+ }+ },+ onLeave = { showMembers = false; leaveAsk = true },+ ) { showMembers = false }+ if (leaveAsk) androidx.compose.material3.AlertDialog(+ onDismissRequest = { leaveAsk = false },+ containerColor = Immersive.Raised,+ title = { Text(stringResource(R.string.playlist_leave), color = Immersive.Text) },+ text = { Text(stringResource(R.string.playlist_leave_confirm, p.name), color = Immersive.TextSecondary) },+ confirmButton = {+ androidx.compose.material3.TextButton(onClick = {+ leaveAsk = false+ com.music.spotui.data.api.LibraryEdits.run(context, null,+ write = { app.myspoti.host.android.MyspotiRuntime.api.playlists.leave(p.uri) },+ onDone = { ok -> if (ok) com.music.spotui.data.api.LibraryEdits.reloadSoon() })+ navController.navigateUp()+ }) { Text(stringResource(R.string.playlist_leave_button), color = Color(0xFFFF453A)) }+ },+ dismissButton = {+ androidx.compose.material3.TextButton(onClick = { leaveAsk = false }) { Text(stringResource(R.string.cancel), color = Immersive.Text) }+ },+ )+ // Confirmations (and their Undo) float above the list, not inside a menu that closes.+ val snackbar = remember { SnackbarHostState() }+ val scope = rememberCoroutineScope()++ // The row goes at once, then the removal is written. The snackbar keeps the mistake+ // reversible: Undo adds the track back and the page is read again.+ fun removeFromThisPlaylist(song: SongsModel) {+ val playlistId = p.uri.substringAfterLast(':')+ vm.dropTrack(song)+ com.music.spotui.data.api.SpotifySync.removeTrackFromPlaylist(context, playlistId, song.spotifyTrackId) { ok ->+ if (!ok) {+ vm.reload()+ Toast.makeText(context, context.getString(R.string.playlist_change_refused), Toast.LENGTH_SHORT).show()+ } else scope.launch {+ val chosen = snackbar.showSnackbar(+ message = context.getString(R.string.removed_from, p.name),+ actionLabel = context.getString(R.string.undo),+ withDismissAction = false,+ // Long: the write has just gone through, the mistake deserves time to be undone.+ duration = SnackbarDuration.Long,+ )+ if (chosen == SnackbarResult.ActionPerformed) {+ com.music.spotui.data.api.SpotifySync.addTrackToPlaylist(context, playlistId, song.spotifyTrackId) { back ->+ if (back) vm.reload()+ else Toast.makeText(context, context.getString(R.string.playlist_change_refused), Toast.LENGTH_SHORT).show()+ }+ }+ }+ }+ }++ if (addingSongs) com.music.spotui.ui.components.AddSongsScreen(p) { added -> addingSongs = false; if (added) vm.reload() }+ if (albumMenu) com.music.spotui.ui.components.AlbumOptionsSheet(p.uri, p.name) { albumMenu = false }+ if (playlistMenu) com.music.spotui.ui.components.PlaylistOptionsSheet(+ page = p,+ onAddSongs = if (p.type == "playlist" && vm.editableContext.value && !p.isBlend) ({ addingSongs = true }) else null,+ onDismiss = { playlistMenu = false },+ onChanged = { vm.reload() },+ onEdited = { name, description -> vm.showDetails(name, description) },+ onDeleted = { navController.navigateUp() },+ onProfile = { navController.navigate(profileRoute(it, p.ownerName)) },+ )+ if (askRemoveDownloads) AlertDialog(+ onDismissRequest = { askRemoveDownloads = false },+ containerColor = Immersive.Raised,+ title = { Text(stringResource(R.string.playlist_entity_remove_download_dialog_title), style = Immersive.Headline) },+ text = { Text(stringResource(R.string.playlist_entity_remove_download_dialog_description), style = Immersive.Subhead) },+ confirmButton = {+ TextButton(onClick = {+ askRemoveDownloads = false+ OfflineCollections.remove(p.uri)+ Toast.makeText(context, context.getString(R.string.toast_undownload), Toast.LENGTH_SHORT).show()+ }) { Text(stringResource(R.string.playlist_entity_remove_download_dialog_positive_button), style = Immersive.BodyStrong.copy(color = Immersive.Accent)) }+ },+ dismissButton = {+ TextButton(onClick = { askRemoveDownloads = false }) {+ Text(stringResource(R.string.add_to_playlist_button_cancel), style = Immersive.BodyStrong)+ }+ },+ )+ menuSong?.let { sel ->+ val inPlaylist = p.type == "playlist"+ val canRemove = inPlaylist && vm.editableContext.value+ com.music.spotui.ui.immersive.sheets.ImmersiveSongOptionsSheet(+ song = sel,+ navController = navController,+ context = context,+ onDismiss = { menuSong = null },+ // The removal entry only exists on a playlist page the user may change: nowhere else+ // is there a list to take the track out of.+ onRemoveFromPlaylist = if (canRemove) ({ removeFromThisPlaylist(sel) }) else null,+ currentPlaylistId = if (inPlaylist) p.uri.substringAfterLast(':') else null,+ )+ }++ // Liked Songs: a track unliked anywhere leaves the list right away. Derived state:+ // recomputed when the page, the search, the sort or a like changes, while a recomposition+ // with nothing new in them re-sorts nothing (a 900-track list is real work).+ val findable = p.type == "liked" || p.type == "playlist"+ val all by remember(p) {+ derivedStateOf {+ if (isLiked) p.tracks.filter { SongPlayer.library["spotify:track:${it.spotifyTrackId}"] != false } else p.tracks+ }+ }+ val rows by remember(p, find, sort) {+ derivedStateOf {+ val found = if (findable) all.filter { matchesFind(find, it.title, it.singer, it.album) } else all+ if (findable) sort.apply(found) else found+ }+ }+ // Unique and stable for a given list: a playlist can hold the same song twice (the id alone+ // is not unique) and the index changes at every sort (which would lose every item).+ val keys = remember(rows) {+ val seen = HashMap<String, Int>()+ rows.map { s ->+ val id = s.id.toString()+ val n = (seen[id] ?: 0) + 1+ seen[id] = n+ if (n == 1) id else "$id#$n"+ }+ }++ // What the Play pill does: pause / resume this list, else start it (smart shuffle if it is on).+ fun onPlay() = when {+ isThisContext && playing -> SongPlayer.pause()+ isThisContext -> SongPlayer.play()+ p.tracks.isNotEmpty() && SmartShuffle.on.value == p.uri -> vm.playSmart(p, null)+ p.tracks.isNotEmpty() -> vm.play(p, if (shuffle) p.tracks.random() else sort.apply(p.tracks).first(), sort)+ else -> Unit+ }+ fun onShuffle() {+ if (p.tracks.isEmpty()) return+ if (SmartShuffle.on.value == p.uri) vm.playSmart(p, null)+ else {+ playerVm.updateShuffleState(true)+ vm.play(p, p.tracks.random(), sort)+ }+ }+ fun toggleSmart() {+ if (smart) {+ SmartShuffle.on.value = null+ playerVm.updateShuffleState(false)+ } else {+ SmartShuffle.on.value = p.uri+ Toast.makeText(context, context.getString(R.string.immersive_detail_smart_shuffle_on), Toast.LENGTH_SHORT).show()+ if (isThisContext) vm.playSmart(p, p.tracks.firstOrNull { it.id == currentSongId })+ }+ }++ val listState = rememberLazyListState()+ val findFocus = remember { FocusRequester() }+ val findStop = with(LocalDensity.current) { immersiveTopContentPadding().roundToPx() }+ // Opening the search carries the page up to it, so the field lands just clear of the bar with+ // the tracks under it. Done as an effect so the row it scrolls to is already in the list.+ LaunchedEffect(finding) {+ if (finding) {+ listState.animateScrollToItem(FIND_ITEM_INDEX, -findStop)+ runCatching { findFocus.requestFocus() }+ } else find = ""+ }++ val refreshing by vm.refreshing+ Box(Modifier.fillMaxSize()) {+ // Pull down to read the page again, as in the Classic look.+ androidx.compose.material3.pulltorefresh.PullToRefreshBox(+ isRefreshing = refreshing,+ onRefresh = { vm.refresh() },+ modifier = Modifier.fillMaxSize(),+ ) {+ LazyColumn(+ state = listState,+ contentPadding = PaddingValues(bottom = Immersive.BottomChrome),+ modifier = Modifier.fillMaxSize().immersiveHazeSource().immersiveChromeScroll(),+ ) {+ item(key = "header") {+ ContextHeader(+ navController = navController,+ p = p,+ tint = tint,+ sleeve = sleeve,+ isLiked = isLiked,+ isThisContext = isThisContext,+ playing = playing,+ saved = SongPlayer.library[p.uri] ?: contextSaved,+ smart = smart,+ onPlay = ::onPlay,+ onShuffle = ::onShuffle,+ onToggleSaved = { vm.toggleContextSaved(p) },+ onToggleSmart = ::toggleSmart,+ onAskRemoveDownloads = { askRemoveDownloads = true },+ members = crew,+ onMembers = { showMembers = true },+ )+ }+ // Someone else's collaborative playlist this account was never invited to.+ if (vm.collabLocked.value && !vm.editableContext.value) item(key = "collab-locked") {+ Row(+ verticalAlignment = Alignment.CenterVertically,+ modifier = Modifier.padding(horizontal = Immersive.Gutter, vertical = 6.dp).fillMaxWidth()+ .clip(RoundedCornerShape(12.dp)).background(Immersive.Raised).padding(12.dp),+ ) {+ Icon(androidx.compose.material.icons.Icons.Outlined.Group, contentDescription = null, tint = Immersive.TextSecondary, modifier = Modifier.size(20.dp))+ Text(+ stringResource(R.string.playlist_collab_locked, p.ownerName.ifBlank { stringResource(R.string.playlist_collab_owner) }),+ style = Immersive.Caption.copy(color = Immersive.TextSecondary),+ modifier = Modifier.padding(start = 10.dp),+ )+ }+ }+ if (finding && findable) item(key = "find") {+ ImmersiveSearchField(+ query = find,+ onQueryChange = { find = it },+ onSubmit = {},+ focusRequester = findFocus,+ placeholder = stringResource(+ if (p.type == "liked") R.string.find_in_context_edit_text_liked_songs_hint else R.string.find_in_context_edit_text_playlist_hint,+ ),+ modifier = Modifier.padding(horizontal = Immersive.Gutter, vertical = 8.dp),+ )+ }+ if (rows.isEmpty() && find.isNotBlank()) item(key = "find-empty") {+ ImmersiveMessageState(stringResource(R.string.assisted_curation_search_empty_view_no_result_title, find.trim()))+ }+ val numbered = p.type == "album"+ itemsIndexed(rows, key = { i, _ -> keys[i] }) { index, song ->+ Column {+ ImmersiveSwipeToQueue(song) {+ ImmersiveSongRow(+ song = song,+ playing = song.id == currentSongId && playing,+ current = song.id == currentSongId,+ onClick = {+ tapper.tap(song) { if (SmartShuffle.on.value == p.uri) vm.playSmart(p, song) else vm.play(p, song, sort) }+ },+ onMore = { menuSong = song },+ trackNumber = if (numbered) index + 1 else null,+ showDuration = numbered,+ showAlbum = !numbered,+ // Collaborative: the small face of who added the song.+ trailing = vm.adders.value.let { a -> a["row:" + song.rowUid] ?: a["song:" + song.spotifyTrackId] }?.let { m ->+ { com.music.spotui.ui.components.ProfileAvatar(m.imageUrl, m.name, 22.dp) }+ },+ )+ }+ if (index < rows.lastIndex) ImmersiveRowDivider(if (numbered) NumberedDividerInset else ImmersiveRowDividerInset)+ }+ }+ // Phone files added to this playlist on this phone (the catalogue can't hold them).+ if (p.type == "playlist") {+ val playlistId = p.uri.substringAfterLast(":")+ val additions = LocalPlaylists.additions[playlistId].orEmpty()+ if (additions.isNotEmpty()) {+ item(key = "local-header") { SectionHeader(stringResource(R.string.local_added_section), modifier = Modifier.padding(top = 14.dp)) }+ itemsIndexed(additions, key = { _, item -> "local:${item.key}" }) { index, item ->+ val track = item.toTrack()+ ImmersiveListRow(+ title = item.title,+ subtitle = item.artist,+ imageUrl = item.artUri,+ round = false,+ playing = LocalPlayer.active.value && np.uri == "local:${track.id}",+ onClick = { LocalPlayer.play(additions.map { it.toTrack() }, index, context = p.name) },+ trailing = {+ Icon(+ Icons.Rounded.Close,+ contentDescription = stringResource(R.string.immersive_detail_remove_local),+ tint = Immersive.TextSecondary,+ modifier = Modifier+ .size(36.dp)+ .clip(CircleShape)+ .immersiveClickable(onClick = { LocalPlaylists.removeFromSpotify(playlistId, item.key) })+ .padding(8.dp),+ )+ },+ )+ }+ }+ }+ // "Recommended songs", as under an own playlist in the official apps (an empty one too).+ if (p.type == "playlist" && vm.editableContext.value && find.isBlank() && !p.isBlend) immersiveRecommended(vm, p, context, currentSongId)+ // An album: "More like this", albums close to its first song.+ if (p.type == "album") item(key = "similar") {+ SimilarAlbums(navController, p.tracks.firstOrNull()?.spotifyTrackId.orEmpty(), p.uri)+ }+ }+ }+ FastScrollbar(listState, Modifier.align(Alignment.CenterEnd))++ // Search, sort and the playlist's menu live in the bar, as the header is the sleeve's.+ val hasActions = findable || p.type == "playlist"+ ImmersiveTopBar(+ title = p.name,+ listState = listState,+ onBack = { navController.navigateUp() },+ actions = if (hasActions) {+ {+ if (findable && all.isNotEmpty()) ImmersiveBarAction(+ icon = Icons.Rounded.Search,+ contentDescription = stringResource(R.string.immersive_detail_find),+ onClick = { finding = !finding },+ tint = if (finding) Immersive.Accent else Immersive.Text,+ )+ if (findable) Box {+ ImmersiveBarAction(+ icon = Icons.Rounded.SwapVert,+ contentDescription = stringResource(R.string.filter_and_sort_sort_section_title),+ onClick = { sortMenu = true },+ tint = if (sort.isCustom) Immersive.Text else Immersive.Accent,+ )+ SortMenu(+ open = sortMenu,+ sort = sort,+ onDismiss = { sortMenu = false },+ onSort = { sort = it; TrackOrder.save(context, p.uri, it) },+ )+ }+ if (p.type == "playlist" || p.type == "album") ImmersiveBarAction(+ icon = Icons.Rounded.MoreHoriz,+ contentDescription = stringResource(R.string.content_description_context_menu),+ onClick = { if (p.type == "playlist") playlistMenu = true else albumMenu = true },+ )+ }+ } else null,+ )+ // Opened from a collaborative-playlist invitation (…?pt=): the playlist is joined from here.+ InviteJoinBar(vm, p, Modifier.align(Alignment.BottomCenter).padding(start = Immersive.Gutter, end = Immersive.Gutter, bottom = Immersive.BottomChrome))+ SnackbarHost(+ hostState = snackbar,+ modifier = Modifier.align(Alignment.BottomCenter).padding(bottom = Immersive.BottomChrome),+ ) { data ->+ Snackbar(+ snackbarData = data,+ containerColor = Immersive.Raised,+ contentColor = Immersive.Text,+ actionContentColor = Immersive.Accent,+ )+ }+ }+}++/** The wash behind Liked Songs' header, as the Classic page's purple-to-blue sleeve. */+private val LikedTint = Color(0xFF4A3FA8)++/**+ * Everything above the track list: the sleeve, the title, the owner, the meta line, the Play and+ * Shuffle pair and the round buttons. The wash behind it runs up under the (transparent) top bar.+ */+@Composable+private fun ContextHeader(+ navController: NavController,+ p: ContextPageModel,+ tint: Color,+ sleeve: Dp,+ isLiked: Boolean,+ isThisContext: Boolean,+ playing: Boolean,+ saved: Boolean,+ smart: Boolean,+ onPlay: () -> Unit,+ onShuffle: () -> Unit,+ onToggleSaved: () -> Unit,+ onToggleSmart: () -> Unit,+ onAskRemoveDownloads: () -> Unit,+ members: List<app.myspoti.api.PlaylistMember> = emptyList(),+ onMembers: () -> Unit = {},+) {+ val context = LocalContext.current+ Column(+ modifier = Modifier+ .fillMaxWidth()+ .background(Brush.verticalGradient(listOf(lerp(tint, Color.Black, 0.3f), Immersive.Page)))+ .padding(top = immersiveTopContentPadding(), bottom = 18.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ ) {+ Box(Modifier.size(sleeve).shadow(SleeveShadow, SleeveShape)) {+ if (isLiked) LikedSleeve(Modifier.matchParentSize())+ else ImmersiveCover(+ url = p.coverUri,+ modifier = Modifier.matchParentSize(),+ shape = SleeveShape,+ placeholderIcon = if (p.type == "album") Icons.Rounded.Album else Icons.Rounded.QueueMusic,+ )+ }+ Spacer(Modifier.height(20.dp))+ Text(+ text = p.name,+ style = Immersive.LargeTitle.copy(fontSize = 28.sp, lineHeight = 34.sp),+ textAlign = TextAlign.Center,+ maxLines = 2,+ overflow = TextOverflow.Ellipsis,+ modifier = Modifier.padding(horizontal = HeaderGutter),+ )+ if (p.description.isNotBlank()) {+ Spacer(Modifier.height(6.dp))+ Text(+ text = p.description,+ style = Immersive.Subhead,+ textAlign = TextAlign.Center,+ maxLines = 3,+ overflow = TextOverflow.Ellipsis,+ modifier = Modifier.padding(horizontal = HeaderGutter),+ )+ }+ if (members.size > 1) {+ // Collaborative: everyone who adds to it, their faces overlapping; a tap lists them.+ Spacer(Modifier.height(8.dp))+ Row(+ verticalAlignment = Alignment.CenterVertically,+ modifier = Modifier.padding(horizontal = HeaderGutter).immersiveClickable(onClick = onMembers),+ ) {+ Box(Modifier.width((24 + 16 * (members.size.coerceAtMost(4) - 1)).dp).height(24.dp)) {+ members.take(4).forEachIndexed { n, m ->+ Box(Modifier.padding(start = (16 * n).dp).size(24.dp).clip(CircleShape).background(Immersive.Page).padding(1.dp)) {+ com.music.spotui.ui.components.ProfileAvatar(m.imageUrl, m.name, 22.dp)+ }+ }+ }+ Spacer(Modifier.width(8.dp))+ Text(+ text = if (members.size <= 2) members.joinToString(", ") { it.name }+ else stringResource(R.string.playlist_members_more, members.first().name, members.size - 1),+ style = Immersive.Headline.copy(fontSize = 17.sp, lineHeight = 22.sp, fontWeight = FontWeight.Normal, color = Immersive.Accent),+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )+ }+ } else if (p.ownerName.isNotBlank()) {+ Spacer(Modifier.height(8.dp))+ Row(+ verticalAlignment = Alignment.CenterVertically,+ modifier = Modifier+ .padding(horizontal = HeaderGutter)+ .immersiveClickable(onClick = {+ if (p.ownerUri.startsWith("spotify:artist:")) {+ navController.navigate(artistRoute(p.ownerName.substringBefore(",").trim(), p.ownerUri.substringAfterLast(":")))+ } else if (p.ownerUri.startsWith("spotify:user:")) {+ navController.navigate(profileRoute(p.ownerUri.substringAfterLast(":"), p.ownerName))+ }+ }),+ ) {+ if (p.ownerAvatar.isNotBlank()) {+ ImmersiveCover(p.ownerAvatar, Modifier.size(24.dp), CircleShape, border = false)+ Spacer(Modifier.width(8.dp))+ }+ Text(+ text = p.ownerName,+ style = Immersive.Headline.copy(fontSize = 19.sp, lineHeight = 24.sp, fontWeight = FontWeight.Normal, color = Immersive.Accent),+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )+ }+ }+ if (p.metaLine.isNotBlank() || p.explicit) {+ Spacer(Modifier.height(4.dp))+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(horizontal = HeaderGutter)) {+ if (p.explicit && p.type == "album") {+ ImmersiveExplicitBadge(Immersive.TextSecondary)+ Spacer(Modifier.width(6.dp))+ }+ Text(+ text = p.metaLine,+ style = Immersive.Caption.copy(fontWeight = FontWeight.Medium),+ textAlign = TextAlign.Center,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )+ }+ }++ if (p.tracks.isNotEmpty()) {+ val thisPlaying = isThisContext && playing+ Spacer(Modifier.height(18.dp))+ Row(+ modifier = Modifier.fillMaxWidth().padding(horizontal = Immersive.Gutter),+ horizontalArrangement = Arrangement.spacedBy(10.dp),+ ) {+ ImmersiveButton(+ text = stringResource(if (thisPlaying) R.string.immersive_detail_pause else R.string.immersive_shell_play),+ icon = if (thisPlaying) Icons.Rounded.Pause else Icons.Rounded.PlayArrow,+ onClick = onPlay,+ modifier = Modifier.weight(1f),+ )+ ImmersiveButton(+ text = stringResource(R.string.immersive_shell_shuffle),+ icon = Icons.Rounded.Shuffle,+ onClick = onShuffle,+ modifier = Modifier.weight(1f),+ )+ }+ Spacer(Modifier.height(14.dp))+ Row(horizontalArrangement = Arrangement.spacedBy(14.dp), verticalAlignment = Alignment.CenterVertically) {+ if (p.type != "liked") ImmersiveCircleButton(+ icon = if (saved) Icons.Rounded.Favorite else Icons.Rounded.FavoriteBorder,+ contentDescription = stringResource(if (saved) R.string.immersive_detail_unsave else R.string.immersive_detail_save),+ onClick = onToggleSaved,+ tint = if (saved) Immersive.Accent else Immersive.Text,+ )+ // The page's own songs, downloaded as a whole stay in step with the catalogue.+ val ids = p.tracks.map { it.spotifyTrackId }.filter { it.isNotBlank() }.distinct()+ // Songs with no matching recording count as settled: the list can still be removed.+ val downloadedCount = ids.count {+ OfflineStore.isDownloaded(it) || OfflineStore.status[it] == OfflineStatus.Unavailable+ }+ val busy = ids.any {+ val st = OfflineStore.status[it]+ st == OfflineStatus.Queued || st is OfflineStatus.Downloading+ }+ val listKept = OfflineCollections.isDownloaded(p.uri)+ LaunchedEffect(listKept, p.complete, p.tracks.size) { if (listKept && p.complete) OfflineCollections.sync(p) }+ DownloadCircle(downloadedCount, ids.size, busy, listKept) {+ if (listKept) onAskRemoveDownloads()+ else DownloadAsk.start(context) { q ->+ com.music.spotui.di.Haptics.confirm()+ OfflineCollections.download(p, q)+ Toast.makeText(context, context.getString(R.string.download_notification_downloading), Toast.LENGTH_SHORT).show()+ }+ }+ if (SmartShuffle.canPlay(p.uri)) ImmersiveCircleButton(+ icon = Icons.Rounded.AutoAwesome,+ contentDescription = stringResource(R.string.smart_shuffle_title),+ onClick = onToggleSmart,+ tint = if (smart) Immersive.Accent else Immersive.Text,+ )+ }+ }+ }+}++/** The Liked Songs artwork: purple-to-blue gradient with a white heart. */+@Composable+private fun LikedSleeve(modifier: Modifier) {+ Box(+ contentAlignment = Alignment.Center,+ modifier = modifier+ .clip(SleeveShape)+ .background(Brush.linearGradient(listOf(Color(0xFF450AF5), Color(0xFF8E8EE5), Color(0xFFC4EFD9)))),+ ) {+ Icon(Icons.Rounded.Favorite, contentDescription = null, tint = Color.White, modifier = Modifier.fillMaxSize(0.4f))+ }+}++/**+ * The download button of an album / playlist: an arrow, a progress ring while songs download, then+ * a bin once all of them are on the phone (tap = remove the downloads). The Classic button's+ * states in a round 44 dp button.+ */+@Composable+private fun DownloadCircle(downloaded: Int, total: Int, busy: Boolean, kept: Boolean, onClick: () -> Unit) {+ val all = kept && !busy+ Box(+ modifier = Modifier+ .immersiveClickable(onClick = onClick)+ .size(44.dp)+ .clip(CircleShape)+ .background(Immersive.Raised),+ contentAlignment = Alignment.Center,+ ) {+ when {+ all -> Icon(+ Icons.Rounded.DeleteOutline, stringResource(R.string.context_menu_undownload),+ tint = Immersive.Accent, modifier = Modifier.size(22.dp),+ )+ busy -> if (total > 0) CircularProgressIndicator(+ progress = { downloaded.toFloat() / total },+ color = Immersive.Accent, trackColor = Immersive.Separator,+ strokeWidth = 2.dp, modifier = Modifier.size(22.dp),+ ) else CircularProgressIndicator(color = Immersive.Accent, strokeWidth = 2.dp, modifier = Modifier.size(22.dp))+ else -> Icon(+ Icons.Rounded.Download, stringResource(R.string.context_menu_download),+ tint = Immersive.Text, modifier = Modifier.size(22.dp),+ )+ }+ }+}++/** The sort menu: picking the sort already chosen flips its direction (the arrow shows it). */+@Composable+private fun SortMenu(open: Boolean, sort: TrackOrder, onDismiss: () -> Unit, onSort: (TrackOrder) -> Unit) {+ DropdownMenu(expanded = open, onDismissRequest = onDismiss, containerColor = Immersive.Raised) {+ Text(+ stringResource(R.string.filter_and_sort_sort_section_title),+ style = Immersive.Caption,+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 6.dp),+ )+ TrackSort.entries.forEach { option ->+ DropdownMenuItem(+ text = {+ Text(+ stringResource(option.label),+ style = Immersive.Body.copy(color = if (option == sort.sort) Immersive.Accent else Immersive.Text),+ )+ },+ trailingIcon = if (option == sort.sort) {+ {+ Icon(+ if (sort.reversed) Icons.Rounded.ArrowUpward else Icons.Rounded.ArrowDownward,+ contentDescription = null, tint = Immersive.Accent, modifier = Modifier.size(18.dp),+ )+ }+ } else null,+ onClick = {+ onDismiss()+ onSort(if (option == sort.sort) sort.copy(reversed = !sort.reversed) else TrackOrder(option))+ },+ )+ }+ }+}++/** "More like this" under an album: the catalogue's similar albums, from its first song. */+@Composable+private fun SimilarAlbums(navController: NavController, firstTrackId: String, albumUri: String) {+ val albums by produceState(emptyList<app.myspoti.api.Album>(), firstTrackId) {+ if (firstTrackId.isBlank()) return@produceState+ value = runCatching { MyspotiRuntime.api.catalog.similarAlbums("spotify:track:$firstTrackId", 12) }+ .getOrDefault(emptyList()).filter { it.uri != albumUri }+ }+ if (albums.isEmpty()) return+ ImmersiveShelf(title = stringResource(R.string.more_like_this), modifier = Modifier.padding(top = 24.dp)) {+ items(albums.size, key = { albums[it].uri }) { i ->+ val a = albums[i]+ val artists = a.artists.joinToString(", ") { it.name }+ ImmersiveShelfCard(+ title = a.name,+ subtitle = artists,+ imageUrl = a.images.maxByOrNull { it.width ?: 0 }?.url,+ onClick = { navController.navigate(albumRoute(a.name, artists, a.uri.substringAfterLast(':'))) },+ )+ }+ }+}++private const val RECS_COUNT_SHOWN = 10++/** The suggestions under an own playlist: tap to listen, "+" to add, "Refresh" for others. */+private fun androidx.compose.foundation.lazy.LazyListScope.immersiveRecommended(+ vm: ContextViewModel, p: ContextPageModel, context: android.content.Context, currentSongId: Int,+) {+ item(key = "recs-title") {+ LaunchedEffect(p.uri) { vm.loadRecs(p) }+ Row(+ verticalAlignment = Alignment.CenterVertically,+ modifier = Modifier.fillMaxWidth().padding(start = Immersive.Gutter, end = 8.dp, top = 28.dp, bottom = 4.dp),+ ) {+ Column(Modifier.weight(1f)) {+ Text(stringResource(R.string.recommended_songs), style = Immersive.Headline)+ Text(+ stringResource(if (p.tracks.isEmpty()) R.string.recommended_songs_from_name else R.string.recommended_songs_from_songs),+ style = Immersive.Caption.copy(color = Immersive.TextSecondary),+ )+ }+ androidx.compose.material3.TextButton(onClick = { vm.loadRecs(p, refresh = true) }) {+ Text(stringResource(R.string.recommended_songs_refresh), color = Immersive.Accent, fontWeight = FontWeight.SemiBold)+ }+ }+ }+ val recs = vm.recs.value+ if (recs == null) item(key = "recs-loading") {+ Column(Modifier.padding(horizontal = Immersive.Gutter)) {+ repeat(3) { ImmersiveShimmerBox(Modifier.fillMaxWidth().height(52.dp).padding(vertical = 4.dp), RoundedCornerShape(8.dp)) }+ }+ }+ else items(recs.take(RECS_COUNT_SHOWN), key = { "rec-" + it.spotifyTrackId }) { song ->+ ImmersiveSongRow(+ song = song,+ playing = false,+ current = song.id == currentSongId,+ onClick = { SongPlayer.playSong(song.url, context, songs = listOf(song)) },+ onMore = null,+ modifier = immersiveItemPlacement(),+ trailing = {+ Icon(+ androidx.compose.material.icons.Icons.Outlined.AddCircleOutline,+ contentDescription = stringResource(R.string.recommended_songs_add),+ tint = Immersive.Text,+ modifier = Modifier+ .size(40.dp)+ .clip(CircleShape)+ .immersiveClickable(onClick = {+ vm.takeRec(p, song)+ com.music.spotui.data.api.SpotifySync.addTrackToPlaylist(context, p.uri.substringAfterLast(':'), song.spotifyTrackId) { ok ->+ if (ok) vm.reload()+ else android.widget.Toast.makeText(context, context.getString(R.string.playlist_change_refused), android.widget.Toast.LENGTH_SHORT).show()+ }+ })+ .padding(8.dp),+ )+ },+ )+ }+}++/** A collaborative-playlist invitation for this page: "Join" over the list, as on the Classic page. */+@Composable+private fun InviteJoinBar(vm: ContextViewModel, p: ContextPageModel, modifier: Modifier) {+ val context = LocalContext.current+ val invite by com.music.spotui.data.api.InviteLinks.pending.collectAsState()+ var joining by remember { mutableStateOf(false) }+ val offered = invite?.takeIf { p.type == "playlist" && it.uri == p.uri && !vm.editableContext.value } ?: return+ Row(+ verticalAlignment = Alignment.CenterVertically,+ modifier = modifier+ .fillMaxWidth()+ .clip(RoundedCornerShape(16.dp))+ .background(Immersive.Raised)+ .padding(start = 16.dp, end = 8.dp, top = 8.dp, bottom = 8.dp),+ ) {+ Text(stringResource(R.string.playlist_invite_banner), style = Immersive.Body, modifier = Modifier.weight(1f).padding(end = 12.dp))+ androidx.compose.material3.Button(+ enabled = !joining,+ colors = androidx.compose.material3.ButtonDefaults.buttonColors(containerColor = Immersive.Accent, contentColor = Color.White),+ onClick = {+ joining = true+ com.music.spotui.data.api.InviteLinks.join(context, offered, p) { ok ->+ joining = false+ if (ok) {+ vm.editableContext.value = true+ vm.contextSaved.value = true+ SongPlayer.library[p.uri] = true+ vm.reload()+ android.widget.Toast.makeText(context, context.getString(R.string.playlist_invite_joined), android.widget.Toast.LENGTH_SHORT).show()+ }+ }+ },+ ) { Text(stringResource(R.string.playlist_invite_join), fontWeight = FontWeight.Bold) }+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveContextScreenParts.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveContextScreenParts.ktnew file mode 100644index 00000000..3dff1f77--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveContextScreenParts.kt@@ -0,0 +1,194 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * app/src/main/java/com/music/bitchord/ui/screens/DetailScreen.kt (the header's action pills,+ * the circle buttons, the About block, the section card) at edc1e6f. Modified for Myspoti, 2026-10.+ */+package com.music.spotui.ui.immersive.screens++import android.widget.Toast+import androidx.compose.animation.animateContentSize+import androidx.compose.animation.core.Animatable+import androidx.compose.animation.core.spring+import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.gestures.detectHorizontalDragGestures+import androidx.compose.foundation.layout.Box+import androidx.compose.ui.graphics.Color+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.Column+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.automirrored.rounded.PlaylistAdd+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import kotlinx.coroutines.CoroutineScope+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.hapticfeedback.HapticFeedbackType+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.platform.LocalHapticFeedback+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.IntOffset+import androidx.compose.ui.unit.dp+import app.myspoti.engine.R+import com.music.spotui.data.entity.SongsModel+import com.music.spotui.di.SongPlayer+import com.music.spotui.ui.immersive.Immersive+import kotlinx.coroutines.delay+import kotlinx.coroutines.launch+import kotlin.math.abs+import kotlin.math.roundToInt++/** How long a greyed track is given to start before the app says why it did not. */+private const val UNAVAILABLE_CHECK_MS = 4_000L++/**+ * Taps on song rows. A greyed (unavailable) row is still tried, as on the Classic pages: the+ * catalogue's playability flag is per market and can be wrong. If the player has not moved to it+ * a few seconds later, the reason is said — a tap that appears to do nothing makes the app look broken.+ */+internal class TrackTapper(private val scope: CoroutineScope, private val context: android.content.Context) {+ fun tap(song: SongsModel, play: () -> Unit) {+ play()+ if (song.playable) return+ scope.launch {+ delay(UNAVAILABLE_CHECK_MS)+ val playing = SongPlayer.nowPlaying.value.uri+ if (song.spotifyTrackId.isNotBlank() && !playing.endsWith(song.spotifyTrackId)) {+ Toast.makeText(context, R.string.track_unavailable_region, Toast.LENGTH_LONG).show()+ }+ }+ }+}++@Composable+internal fun rememberTrackTapper(): TrackTapper {+ val scope = rememberCoroutineScope()+ val context = LocalContext.current.applicationContext+ return remember(scope, context) { TrackTapper(scope, context) }+}++/**+ * Swipe a song row sideways to add it to the queue: the row follows the finger over an accent+ * strip, ticks once past the threshold, and adds the song once on release before springing back.+ * The Classic pages' gesture, drawn in the Immersive look's colours.+ */+@Composable+internal fun ImmersiveSwipeToQueue(song: SongsModel, content: @Composable () -> Unit) {+ val context = LocalContext.current+ val haptic = LocalHapticFeedback.current+ val scope = rememberCoroutineScope()+ val threshold = with(LocalDensity.current) { 96.dp.toPx() }+ val maxDrag = threshold * 1.4f+ val offset = remember { Animatable(0f) }+ var armed by remember { mutableStateOf(false) }++ Box(modifier = Modifier.fillMaxWidth()) {+ if (offset.value != 0f) {+ Box(+ contentAlignment = if (offset.value > 0) Alignment.CenterStart else Alignment.CenterEnd,+ modifier = Modifier+ .matchParentSize()+ .background(if (armed) Immersive.Accent else Immersive.Accent.copy(alpha = 0.6f)),+ ) {+ Icon(+ Icons.AutoMirrored.Rounded.PlaylistAdd,+ contentDescription = stringResource(R.string.add_to_queue_action_content_description),+ tint = Color.White,+ modifier = Modifier.padding(horizontal = 24.dp).size(26.dp),+ )+ }+ }+ Box(+ modifier = Modifier+ .offset { IntOffset(offset.value.roundToInt(), 0) }+ .background(Immersive.Page)+ .pointerInput(song.id) {+ detectHorizontalDragGestures(+ onDragEnd = {+ if (armed && song.spotifyTrackId.isNotBlank()) {+ SongPlayer.addToQueue(song.spotifyTrackId)+ Toast.makeText(context, context.getString(R.string.snackbar_added_to_queue), Toast.LENGTH_SHORT).show()+ }+ armed = false+ scope.launch { offset.animateTo(0f, spring()) }+ },+ onDragCancel = {+ armed = false+ scope.launch { offset.animateTo(0f, spring()) }+ },+ ) { change, dx ->+ change.consume()+ val next = (offset.value + dx).coerceIn(-maxDrag, maxDrag)+ scope.launch { offset.snapTo(next) }+ val nowArmed = abs(next) >= threshold+ if (nowArmed && !armed) haptic.performHapticFeedback(HapticFeedbackType.GestureThresholdActivate)+ armed = nowArmed+ }+ },+ ) { content() }+ }+}++/**+ * "About" under an artist page: a title and a few lines of [text] that open on a tap, with a+ * More / Less link in the accent once the text has been seen to overflow. Whether there is+ * anything to expand is only known after layout at the collapsed line count, so the link waits+ * for that measurement — a two-line bio gets no toggle with nothing behind it.+ */+@Composable+internal fun ImmersiveAboutText(+ text: String,+ modifier: Modifier = Modifier,+ maxLines: Int = 3,+) {+ var expanded by remember(text) { mutableStateOf(false) }+ var clipped by remember(text) { mutableStateOf(false) }+ Column(modifier) {+ Text(+ text = text,+ style = Immersive.Body.copy(color = Immersive.TextSecondary),+ maxLines = if (expanded) Int.MAX_VALUE else maxLines,+ overflow = TextOverflow.Ellipsis,+ onTextLayout = { result -> if (!expanded) clipped = result.hasVisualOverflow },+ modifier = Modifier+ .fillMaxWidth()+ .animateContentSize()+ .let { m -> if (clipped || expanded) m.clickable { expanded = !expanded } else m },+ )+ if (clipped || expanded) {+ Text(+ text = stringResource(if (expanded) R.string.immersive_detail_less else R.string.immersive_detail_more),+ style = Immersive.Subhead.copy(color = Immersive.Accent),+ modifier = Modifier+ .clickable { expanded = !expanded }+ .padding(vertical = 6.dp),+ )+ }+ }+}++/** A hairline between two rows, starting [inset] from the edge. */+@Composable+internal fun ImmersiveRowDivider(inset: Dp) {+ Box(+ Modifier+ .padding(start = inset)+ .fillMaxWidth()+ .height(0.5.dp)+ .background(Immersive.Separator),+ )+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveHomeChips.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveHomeChips.ktnew file mode 100644index 00000000..6cb56b18--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveHomeChips.kt@@ -0,0 +1,85 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * sharedUi/src/jvmSharedMain/kotlin/com/music/bitchord/ui/screens/SearchScreen.kt (SearchFilterTabs) at edc1e6f.+ * Modified for Myspoti, 2026-10.+ */+package com.music.spotui.ui.immersive.screens++import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.horizontalScroll+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.RowScope+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.hapticfeedback.HapticFeedbackType+import androidx.compose.ui.platform.LocalHapticFeedback+import androidx.compose.ui.semantics.Role+import androidx.compose.ui.unit.dp+import com.music.spotui.ui.immersive.Immersive++/** Rounded, but well short of a capsule: the corner reads as a cut, not a curve. */+private val ChipShape = RoundedCornerShape(12.dp)++/**+ * Filter pills rather than a tab row: squarish rounded rectangles, the selected one inverted.+ * They scroll sideways so a long label set never squeezes the text, and the gutter padding sits+ * inside the scroll so it scrolls with them. Shared by the Home facets, the Search filters and+ * the Library kinds.+ */+@Composable+internal fun ImmersiveChipRow(+ modifier: Modifier = Modifier,+ content: @Composable RowScope.() -> Unit,+) {+ Row(+ modifier = modifier+ .fillMaxWidth()+ .horizontalScroll(rememberScrollState())+ .padding(PaddingValues(horizontal = Immersive.Gutter, vertical = 6.dp)),+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ verticalAlignment = Alignment.CenterVertically,+ content = content,+ )+}++/** One pill of an [ImmersiveChipRow]. */+@Composable+internal fun ImmersiveChip(+ label: String,+ selected: Boolean,+ onClick: () -> Unit,+) {+ val haptics = LocalHapticFeedback.current+ Box(+ modifier = Modifier+ .clip(ChipShape)+ .background(if (selected) Immersive.Text else Immersive.Raised)+ // Only a pill that is not already selected has anything to report: re-tapping the+ // current one changes nothing, so buzzing for it would be feedback for a no-op.+ .clickable(role = Role.Button) {+ if (!selected) haptics.performHapticFeedback(HapticFeedbackType.TextHandleMove)+ onClick()+ }+ .padding(horizontal = 12.dp, vertical = 6.dp),+ ) {+ Text(+ text = label,+ style = Immersive.Subhead.copy(+ color = if (selected) Immersive.Page else Immersive.Text,+ fontWeight = androidx.compose.ui.text.font.FontWeight.Medium,+ ),+ maxLines = 1,+ )+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveHomeProfile.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveHomeProfile.ktnew file mode 100644index 00000000..e5bb8d58--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveHomeProfile.kt@@ -0,0 +1,234 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * sharedUi/src/jvmSharedMain/kotlin/com/music/bitchord/ui/screens/HomeScreen.kt at edc1e6f.+ * The sheet's rows are those of Myspoti's Classic Home profile sheet. Modified for Myspoti, 2026-10.+ */+package com.music.spotui.ui.immersive.screens++import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.navigationBarsPadding+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.verticalScroll+import androidx.compose.material3.ExperimentalMaterial3Api+import androidx.compose.material3.HorizontalDivider+import androidx.compose.material3.ModalBottomSheet+import androidx.compose.material3.Text+import androidx.compose.material3.rememberModalBottomSheetState+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.semantics.Role+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp+import app.myspoti.engine.R+import com.music.spotui.data.api.ProfileCache+import com.music.spotui.data.api.SupportReminder+import com.music.spotui.di.Graph+import com.music.spotui.di.SessionActions+import com.music.spotui.ui.components.AboutSheet+import com.music.spotui.ui.components.SupporterBadge+import com.music.spotui.ui.components.SupporterSheet+import com.music.spotui.ui.components.SupportSheet+import com.music.spotui.ui.immersive.Immersive+import com.music.spotui.ui.immersive.components.ImmersiveCover+import com.music.spotui.ui.immersive.components.immersiveClickable+import com.music.spotui.ui.navigation.Routes+import com.music.spotui.ui.navigation.profileRoute+import com.music.spotui.ui.screens.AccountBrowser++/** The profile picture as a disc (the first letter of the name until it loads), opening [onClick]. */+@Composable+internal fun ProfileDisc(onClick: () -> Unit, modifier: Modifier = Modifier) {+ val avatar = ProfileCache.imageUrl+ val initial = ProfileCache.name?.trim()?.firstOrNull()?.uppercase() ?: "•"+ AvatarDisc(+ url = avatar,+ initial = initial,+ contentDescription = stringResource(R.string.recently_played_user_profile),+ onClick = onClick,+ modifier = modifier,+ )+}++/** A round avatar: the picture at [url], or [initial] on the accent while there is none. */+@Composable+internal fun AvatarDisc(+ url: String?,+ initial: String,+ contentDescription: String?,+ onClick: (() -> Unit)?,+ modifier: Modifier = Modifier,+ size: Dp = 36.dp,+) {+ Box(+ contentAlignment = Alignment.Center,+ modifier = modifier+ .size(size)+ .let { if (onClick != null) it.immersiveClickable(onClick = onClick) else it }+ .clip(CircleShape)+ .background(Immersive.Accent),+ ) {+ if (!url.isNullOrBlank()) {+ ImmersiveCover(+ url = url,+ modifier = Modifier.size(size),+ shape = CircleShape,+ contentDescription = contentDescription,+ border = false,+ )+ } else {+ Text(text = initial, style = Immersive.BodyStrong.copy(color = Immersive.Page, fontWeight = FontWeight.Bold))+ }+ }+}++/**+ * The profile sheet behind the avatar: account name and picture (open the public profile),+ * settings, recap, history, the account page, support, about and sign-out. The same rows and+ * actions as the Classic Home screen's sheet.+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+internal fun ImmersiveProfileSheet(onOpen: (route: String) -> Unit, onDismiss: () -> Unit) {+ val name = ProfileCache.name.orEmpty()+ val avatar = ProfileCache.imageUrl+ val myId = ProfileCache.id+ // Opened in full: half-open, the sheet and its list both moved under the finger.+ ModalBottomSheet(+ onDismissRequest = onDismiss,+ containerColor = Immersive.Raised,+ sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true),+ ) {+ Column(+ modifier = Modifier+ .fillMaxWidth()+ .navigationBarsPadding()+ .verticalScroll(rememberScrollState())+ .padding(bottom = 16.dp),+ ) {+ // Name and picture open the public profile.+ Row(+ verticalAlignment = Alignment.CenterVertically,+ modifier = Modifier+ .fillMaxWidth()+ .clickable(enabled = myId != null, role = Role.Button) { myId?.let { onOpen(profileRoute(it, name)) } }+ .padding(horizontal = Immersive.Gutter, vertical = 8.dp),+ ) {+ AvatarDisc(+ url = avatar,+ initial = name.trim().firstOrNull()?.uppercase() ?: "•",+ contentDescription = null,+ onClick = null,+ size = 48.dp,+ )+ Text(+ text = name.ifBlank { stringResource(R.string.immersive_screens_account) },+ style = Immersive.Headline,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ modifier = Modifier.padding(start = 14.dp),+ )+ if (SupportReminder.level != SupportReminder.Level.NONE) SupporterBadge(Modifier.padding(start = 10.dp))+ }+ if (myId != null) {+ Text(+ text = stringResource(R.string.view_profile),+ style = Immersive.Caption,+ modifier = Modifier.padding(start = 82.dp, bottom = 4.dp),+ )+ }+ HorizontalDivider(color = Immersive.Separator, modifier = Modifier.padding(vertical = 8.dp))+ SheetRow(stringResource(R.string.settings_title), stringResource(R.string.settings_detail)) {+ onOpen(Routes.Settings.route)+ }+ SheetRow(stringResource(R.string.recap_title), stringResource(R.string.recap_detail)) {+ onOpen(Routes.Recap.route)+ }+ SheetRow(stringResource(R.string.recents_title), stringResource(R.string.recents_detail)) {+ onOpen(Routes.Recent.route)+ }+ // What the followed people are listening to (the official Friend Activity feed).+ SheetRow(stringResource(R.string.friends_title), stringResource(R.string.friends_detail)) {+ onOpen(Routes.Friends.route)+ }+ // Third-party extensions: installed, enabled, repositories.+ val extRegistry by com.music.spotui.extensions.Extensions.registry.collectAsState()+ val installed = extRegistry.extensions+ SheetRow(+ stringResource(R.string.extensions_title),+ if (installed.isEmpty()) stringResource(R.string.extensions_row_detail)+ else stringResource(R.string.extensions_row_count, installed.size, installed.count { it.enabled }),+ ) {+ onOpen(Routes.Extensions.route)+ }+ // The account page (plan, privacy, devices), in the app's signed-in browser.+ SheetRow(+ stringResource(R.string.immersive_screens_account_page),+ stringResource(R.string.immersive_screens_account_page_detail),+ ) {+ onDismiss()+ AccountBrowser.open(Graph.app, AccountBrowser.ACCOUNT_URL)+ }+ // Donations: always here, never in the way.+ var support by remember { mutableStateOf(false) }+ if (support) SupportSheet(onDismiss = { support = false })+ SheetRow(+ stringResource(R.string.support_title),+ stringResource(R.string.support_row_detail),+ titleColor = Immersive.Accent,+ ) { support = true }+ // About: version, Discord, source code and Ko-fi.+ var about by remember { mutableStateOf(false) }+ if (about) AboutSheet(onDismiss = { about = false })+ SheetRow(stringResource(R.string.creator_biography_section_title), stringResource(R.string.about_detail)) {+ about = true+ }+ var perks by remember { mutableStateOf(false) }+ if (perks) SupporterSheet(onDismiss = { perks = false })+ if (SupportReminder.PERKS_ENABLED) {+ SheetRow(stringResource(R.string.supporter_perks_title), stringResource(R.string.supporter_perks_detail)) {+ perks = true+ }+ }+ SheetRow(stringResource(R.string.connect_device_menu_logout), null) {+ onDismiss()+ SessionActions.logout(Graph.app)+ }+ }+ }+}++@Composable+private fun SheetRow(+ title: String,+ detail: String?,+ titleColor: androidx.compose.ui.graphics.Color = Immersive.Text,+ onClick: () -> Unit,+) {+ Column(+ Modifier+ .fillMaxWidth()+ .clickable(role = Role.Button, onClick = onClick)+ .padding(horizontal = Immersive.Gutter, vertical = if (detail == null) 14.dp else 10.dp),+ ) {+ Text(title, style = Immersive.Body.copy(color = titleColor))+ if (detail != null) Text(detail, style = Immersive.Caption)+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveHomeScreen.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveHomeScreen.ktnew file mode 100644index 00000000..8eb3108a--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveHomeScreen.kt@@ -0,0 +1,338 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * sharedUi/src/jvmSharedMain/kotlin/com/music/bitchord/ui/screens/HomeScreen.kt at edc1e6f.+ * Modified for Myspoti, 2026-10.+ */+package com.music.spotui.ui.immersive.screens++import com.music.spotui.ui.immersive.shell.immersiveHazeSource+import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxWithConstraints+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.lazy.rememberLazyListState+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.draw.clip+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import androidx.lifecycle.viewmodel.compose.viewModel+import androidx.navigation.NavController+import app.myspoti.engine.R+import com.music.spotui.data.api.Features+import com.music.spotui.data.api.ProfileCache+import com.music.spotui.data.api.Response+import com.music.spotui.data.entity.HomeFeedModel+import com.music.spotui.data.entity.HomeItem+import com.music.spotui.data.entity.HomeSection+import com.music.spotui.di.Graph+import com.music.spotui.di.SongPlayer+import com.music.spotui.ui.components.pressHint+import com.music.spotui.ui.immersive.Immersive+import com.music.spotui.ui.immersive.components.ImmersiveCover+import com.music.spotui.ui.immersive.components.ImmersiveLargeAlbumCard+import com.music.spotui.ui.immersive.components.ImmersiveMessageState+import com.music.spotui.ui.immersive.components.ImmersiveShelf+import com.music.spotui.ui.immersive.components.ImmersiveShelfCard+import com.music.spotui.ui.immersive.components.ImmersiveShelfRow+import com.music.spotui.ui.immersive.components.SectionHeader+import com.music.spotui.ui.immersive.components.immersiveClickable+import com.music.spotui.ui.immersive.components.immersiveFeedSkeleton+import com.music.spotui.ui.immersive.components.immersiveHeroCardWidth+import com.music.spotui.ui.immersive.shell.ImmersiveFloatingHeader+import com.music.spotui.ui.immersive.shell.LocalBarControlSize+import com.music.spotui.ui.immersive.shell.immersiveChromeScroll+import com.music.spotui.ui.immersive.shell.immersiveHeaderContentPadding+import com.music.spotui.ui.navigation.TabReselect+import com.music.spotui.ui.navigation.albumRoute+import com.music.spotui.ui.navigation.artistRoute+import com.music.spotui.ui.navigation.playlistRoute+import com.music.spotui.ui.navigation.showRoute+import com.music.spotui.ui.screens.ContextViewModel+import com.music.spotui.ui.viewmodel.HomeViewModel++/**+ * Home in the Immersive look: the greeting as the page's large title with the profile disc at its+ * end, the facet pills, then the feed — the first carousel as big cards, the rest as shelves. The+ * data, clicks, prefetch and profile actions are those of the Classic Home screen.+ */+@Composable+fun ImmersiveHomeScreen(navController: NavController) {+ val homeViewModel: HomeViewModel = viewModel()+ val home by homeViewModel.home.collectAsState()+ val feed = (home as? Response.Success)?.data+ val facet = homeViewModel.facet.value+ val context = LocalContext.current+ LaunchedEffect(Unit) { ProfileCache.ensure(context) }++ // Re-tapping the Home tab while on Home scrolls back to the top, as in the Classic screen.+ val listState = rememberLazyListState()+ LaunchedEffect(Unit) {+ TabReselect.home.collect {+ if (listState.firstVisibleItemIndex != 0 || listState.firstVisibleItemScrollOffset != 0) {+ listState.animateScrollToItem(0)+ }+ }+ }++ val homeTitle = stringResource(R.string.navigationbar_musicappitems_home_title)+ val title = feed?.greeting?.takeIf { it.isNotBlank() } ?: homeTitle+ var showProfile by remember { mutableStateOf(false) }+ if (showProfile) {+ ImmersiveProfileSheet(+ onOpen = { route -> showProfile = false; navController.navigate(route) },+ onDismiss = { showProfile = false },+ )+ }++ // Podcasts can be off: their shows and episodes then leave the feed.+ val sections = remember(feed) { feed?.let { visibleSections(it) }.orEmpty() }+ // Only the untitled section the web home starts with is a shortcut grid; a titled lead+ // section is a carousel like any other.+ val gridSection = sections.firstOrNull()?.takeIf { it.title.isBlank() }+ val carousels = if (gridSection != null) sections.drop(1) else sections+ // The shortcuts at the top load in the background, ready before a tap.+ LaunchedEffect(gridSection?.items?.map { it.name }) {+ val top = gridSection?.items.orEmpty().take(8).mapNotNull { item ->+ when (item) {+ is HomeItem.Album -> item.id.takeIf { it.isNotBlank() }?.let { "album" to it }+ is HomeItem.Playlist -> item.id.takeIf { it.isNotBlank() }?.let { "playlist" to it }+ else -> null+ }+ }+ if (top.isNotEmpty()) ContextViewModel.prefetchSoon(top)+ }++ Box(Modifier.fillMaxSize().background(Immersive.Page)) {+ LazyColumn(+ state = listState,+ // The greeting is the floating header's own title, so the feed starts right under it+ // (it used to be a large title under an empty bar row: the gap at the top of Home).+ contentPadding = PaddingValues(top = immersiveHeaderContentPadding(), bottom = Immersive.BottomChrome),+ modifier = Modifier.fillMaxSize().immersiveHazeSource().immersiveChromeScroll(),+ ) {+ item(key = "home:facets") {+ ImmersiveChipRow {+ ImmersiveChip(stringResource(R.string.filter_chip_all_label), selected = facet.isEmpty()) {+ if (facet.isNotEmpty()) homeViewModel.selectFacet(facet)+ }+ ImmersiveChip(stringResource(R.string.recents_content_filter_music), selected = facet == "music-chip") {+ homeViewModel.selectFacet("music-chip")+ }+ if (Features.PODCASTS) {+ ImmersiveChip(stringResource(R.string.ad_category_title_podcasts), selected = facet == "podcasts-chip") {+ homeViewModel.selectFacet("podcasts-chip")+ }+ ImmersiveChip(stringResource(R.string.audiobooks_title), selected = facet == "audiobooks-chip") {+ homeViewModel.selectFacet("audiobooks-chip")+ }+ }+ }+ }+ when {+ feed != null && feed.sections.isNotEmpty() -> {+ gridSection?.let { section ->+ item(key = "home:shortcuts") {+ ShortcutGrid(navController, section.items.take(8))+ }+ }+ carousels.forEachIndexed { index, section ->+ item(key = "home:section:$index:${section.title}") {+ // The lead carousel gets the big cards, unless it is a row of artists.+ val hero = index == 0 && section.items.none { it is HomeItem.Artist }+ if (hero) HeroSection(navController, section) else ShelfSection(navController, section)+ }+ }+ // Sections from extensions (home.sections), after Spotify's own.+ item(key = "home:extensions") {+ com.music.spotui.extensions.ExtensionBlocks(app.myspoti.extensions.Hook.HOME, app.myspoti.extensions.Surface.HOME, "{}")+ }+ }+ home is Response.Loading -> immersiveFeedSkeleton(firstIsHero = true)+ else -> item(key = "home:message") {+ ImmersiveMessageState(+ message = stringResource(if (home is Response.Error) R.string.home_error else R.string.home_empty),+ actionLabel = if (home is Response.Error) stringResource(R.string.home_retry) else null,+ onAction = if (home is Response.Error) ({ homeViewModel.retry() }) else null,+ )+ }+ }+ }+ // The greeting and the profile disc on floating glass; the feed scrolls under it.+ ImmersiveFloatingHeader(title) {+ val size = LocalBarControlSize.current+ Box(+ Modifier.size(size).graphicsLayer { scaleX = size / 44.dp; scaleY = scaleX },+ contentAlignment = Alignment.Center,+ ) {+ ProfileDisc(onClick = { showProfile = true })+ }+ }+ }+}++private fun visibleSections(feed: HomeFeedModel): List<HomeSection> =+ if (Features.PODCASTS) feed.sections+ else feed.sections.map { s -> s.copy(items = s.items.filterNot { it is HomeItem.Show }) }.filter { it.items.isNotEmpty() }++/** Albums and playlists start loading under the finger. */+private fun prefetchHomeItem(item: HomeItem) {+ when (item) {+ is HomeItem.Album -> if (item.id.isNotBlank()) ContextViewModel.prefetch("album", item.id)+ is HomeItem.Playlist -> if (item.id.isNotBlank()) ContextViewModel.prefetch("playlist", item.id)+ else -> {}+ }+}++private fun onHomeItemClick(navController: NavController, item: HomeItem) {+ when (item) {+ is HomeItem.Album -> navController.navigate(albumRoute(item.name, item.artists.ifBlank { item.subtitle }, item.id))+ is HomeItem.Artist -> navController.navigate(artistRoute(item.name, item.id))+ is HomeItem.Show ->+ if (item.isEpisode) SongPlayer.playSong("episode:${item.id}")+ else navController.navigate(showRoute(item.id, item.name))+ // The real playlist content by its id (daily mixes, etc).+ is HomeItem.Playlist ->+ if (item.id.isNotBlank()) navController.navigate(playlistRoute(item.id, item.name))+ else navController.navigate(albumRoute(item.name))+ }+}++/** The uri of the thing this card opens, to tell whether it is what is playing. */+private fun HomeItem.contextUri(): String = when (this) {+ is HomeItem.Album -> if (id.isNotBlank()) "spotify:album:$id" else ""+ is HomeItem.Playlist -> if (id.isNotBlank()) "spotify:playlist:$id" else ""+ is HomeItem.Artist -> if (id.isNotBlank()) "spotify:artist:$id" else ""+ is HomeItem.Show -> if (id.isNotBlank() && !isEpisode) "spotify:show:$id" else ""+}++/** True while this card's album, playlist or artist is the playing context. */+@Composable+private fun HomeItem.isPlayingNow(): Boolean {+ val uri = contextUri()+ if (uri.isEmpty()) return false+ return SongPlayer.nowPlaying.value.contextUri == uri && Graph.currentSongState.playingState.value+}++@Composable+private fun HomeItem.cardSubtitle(): String = when (this) {+ is HomeItem.Album -> subtitle+ is HomeItem.Playlist -> subtitle+ is HomeItem.Artist -> stringResource(R.string.artist_subtitle)+ is HomeItem.Show -> subtitle+}++/** The lead carousel: big artwork cards with the caption over a scrim, the next one peeking in. */+@Composable+private fun HeroSection(navController: NavController, section: HomeSection) {+ Column(Modifier.padding(bottom = 26.dp)) {+ SectionHeader(section.title)+ BoxWithConstraints {+ // Measured: the card has a ceiling as well as a fraction, and the skeleton agrees.+ val cardWidth = immersiveHeroCardWidth(maxWidth)+ ImmersiveShelfRow {+ items(section.items.size) { i ->+ val item = section.items[i]+ ImmersiveLargeAlbumCard(+ title = item.name,+ subtitle = item.cardSubtitle(),+ imageUrl = item.imageUrl,+ onClick = { onHomeItemClick(navController, item) },+ modifier = Modifier.width(cardWidth).pressHint { prefetchHomeItem(item) },+ playing = item.isPlayingNow(),+ )+ }+ }+ }+ }+}++/** A titled row of square cards (round for artists). */+@Composable+private fun ShelfSection(navController: NavController, section: HomeSection) {+ ImmersiveShelf(title = section.title) {+ items(section.items.size) { i ->+ val item = section.items[i]+ ImmersiveShelfCard(+ title = item.name,+ subtitle = item.cardSubtitle(),+ imageUrl = item.imageUrl,+ onClick = { onHomeItemClick(navController, item) },+ modifier = Modifier.width(com.music.spotui.ui.immersive.components.ImmersiveShelfCardWidth)+ .pressHint { prefetchHomeItem(item) },+ round = item is HomeItem.Artist,+ playing = item.isPlayingNow(),+ )+ }+ }+}++/** The two-column shortcuts the web home starts with: a small cover and a name on a raised tile. */+@Composable+private fun ShortcutGrid(navController: NavController, items: List<HomeItem>) {+ Column(+ modifier = Modifier.padding(horizontal = Immersive.Gutter).padding(bottom = 22.dp),+ verticalArrangement = Arrangement.spacedBy(10.dp),+ ) {+ items.chunked(2).forEach { rowItems ->+ Row(horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth()) {+ rowItems.forEach { item ->+ val playing = item.isPlayingNow()+ Row(+ verticalAlignment = Alignment.CenterVertically,+ modifier = Modifier+ .weight(1f)+ .height(56.dp)+ .pressHint { prefetchHomeItem(item) }+ .immersiveClickable(onClick = { onHomeItemClick(navController, item) })+ .clip(Immersive.CoverMedium)+ .background(Immersive.Raised),+ ) {+ ImmersiveCover(+ url = item.imageUrl,+ modifier = Modifier.size(56.dp),+ shape = Immersive.CoverMedium,+ border = false,+ )+ Text(+ text = item.name,+ style = Immersive.Subhead.copy(+ color = if (playing) Immersive.Accent else Immersive.Text,+ fontWeight = FontWeight.SemiBold,+ lineHeight = 17.sp,+ ),+ maxLines = 2,+ overflow = TextOverflow.Ellipsis,+ modifier = Modifier.padding(horizontal = 10.dp).weight(1f),+ )+ }+ }+ if (rowItems.size == 1) Box(Modifier.weight(1f))+ }+ }+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveLibraryScreen.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveLibraryScreen.ktnew file mode 100644index 00000000..ea3d3a05--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveLibraryScreen.kt@@ -0,0 +1,846 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * sharedUi/src/jvmSharedMain/kotlin/com/music/bitchord/ui/screens/LibraryScreen.kt and+ * app/src/main/java/com/music/bitchord/ui/screens/LibraryPhoneParts.kt at edc1e6f.+ * Modified for Myspoti, 2026-10.+ */+package com.music.spotui.ui.immersive.screens++import com.music.spotui.ui.immersive.shell.immersiveHazeSource+import com.music.spotui.ui.immersive.shell.immersiveChromeScroll+import androidx.annotation.StringRes+import androidx.compose.animation.AnimatedVisibility+import androidx.compose.animation.core.Spring+import androidx.compose.animation.core.VisibilityThreshold+import androidx.compose.animation.core.spring+import androidx.compose.animation.fadeIn+import androidx.compose.animation.fadeOut+import androidx.compose.animation.expandVertically+import androidx.compose.animation.shrinkVertically+import androidx.compose.foundation.ExperimentalFoundationApi+import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.gestures.detectDragGesturesAfterLongPress+import androidx.compose.foundation.gestures.scrollBy+import androidx.compose.foundation.interaction.MutableInteractionSource+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.aspectRatio+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.LazyListState+import androidx.compose.foundation.lazy.grid.GridCells+import androidx.compose.foundation.lazy.grid.GridItemSpan+import androidx.compose.foundation.lazy.grid.LazyGridState+import androidx.compose.foundation.lazy.grid.LazyVerticalGrid+import androidx.compose.foundation.lazy.grid.itemsIndexed+import androidx.compose.foundation.lazy.grid.rememberLazyGridState+import androidx.compose.foundation.lazy.itemsIndexed+import androidx.compose.foundation.lazy.rememberLazyListState+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.rounded.Add+import androidx.compose.material.icons.rounded.PushPin+import androidx.compose.material.icons.rounded.Search+import androidx.compose.material.icons.rounded.SwapVert+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.rememberUpdatedState+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.runtime.withFrameNanos+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.hapticfeedback.HapticFeedbackType+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.layout.layout+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.platform.LocalHapticFeedback+import androidx.compose.ui.res.painterResource+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.IntOffset+import androidx.compose.ui.unit.dp+import androidx.compose.ui.zIndex+import androidx.lifecycle.viewmodel.compose.viewModel+import androidx.navigation.NavController+import app.myspoti.engine.R+import com.music.spotui.data.api.Api+import com.music.spotui.data.api.Response+import com.music.spotui.data.entity.AccountModel+import com.music.spotui.data.entity.ArtistsModel+import com.music.spotui.data.entity.LibraryEntry+import com.music.spotui.data.local.LibraryOrder+import com.music.spotui.data.preferences.isLibraryGridView+import com.music.spotui.data.preferences.setLibraryGridView+import com.music.spotui.ui.components.FastScrollbar+import com.music.spotui.ui.components.pressHint+import com.music.spotui.ui.immersive.Immersive+import com.music.spotui.ui.immersive.components.ImmersiveCover+import com.music.spotui.ui.immersive.components.ImmersiveMessageState+import com.music.spotui.ui.immersive.components.ImmersiveMoreButton+import com.music.spotui.ui.immersive.components.ImmersiveSearchField+import com.music.spotui.ui.immersive.components.SectionHeader+import com.music.spotui.ui.immersive.components.immersiveClickable+import com.music.spotui.ui.immersive.components.immersiveLibrarySkeleton+import com.music.spotui.ui.immersive.components.immersiveThumbnailBorder+import com.music.spotui.ui.immersive.shell.ImmersiveBarAction+import com.music.spotui.ui.immersive.shell.ImmersiveLargeTitle+import com.music.spotui.ui.immersive.shell.ImmersiveTopBar+import com.music.spotui.ui.immersive.shell.immersiveTopContentPadding+import com.music.spotui.ui.immersive.shell.rememberTopBarCollapse+import com.music.spotui.ui.navigation.Routes+import com.music.spotui.ui.navigation.TabReselect+import com.music.spotui.ui.navigation.albumRoute+import com.music.spotui.ui.navigation.artistRoute+import com.music.spotui.ui.navigation.folderRoute+import com.music.spotui.ui.navigation.localPlaylistRoute+import com.music.spotui.ui.navigation.playlistRoute+import com.music.spotui.ui.screens.ContextViewModel+import com.music.spotui.ui.screens.LOCAL_PLAYLIST_PREFIX+import com.music.spotui.ui.screens.LibraryCreateSheet+import com.music.spotui.ui.screens.LibraryEntryCover+import com.music.spotui.ui.screens.LibraryItemSheet+import com.music.spotui.ui.viewmodel.LibraryViewModel+import com.music.spotui.data.local.LibraryChip+import com.music.spotui.data.local.LibraryChips+import androidx.compose.runtime.saveable.rememberSaveable++/** The chips under the title, in the Classic order; their logic is the shared [LibraryChips]. */+private val LibraryChipLabels = listOf(+ LibraryChip.PLAYLISTS to R.string.library_chip_playlists,+ LibraryChip.ARTISTS to R.string.library_chip_artists,+ LibraryChip.ALBUMS to R.string.library_chip_albums,+ LibraryChip.SONGS to R.string.library_chip_songs,+)++/**+ * Your Library in the Immersive look: the page's large title, the sort and list/grid controls,+ * kind pills and an optional search, then the saved playlists and albums (Liked Songs, Local+ * Files, Downloaded and the phone's own playlists pinned on top) and the followed artists. The+ * data, ordering, drag-to-reorder, sheets and re-tap-to-top are those of the Classic screen.+ */+@Composable+fun ImmersiveLibraryScreen(navController: NavController) {+ val vm: LibraryViewModel = viewModel()+ val entries by vm.entries.collectAsState()+ val account by vm.account.collectAsState()+ val followedArtists by vm.followedArtists.collectAsState()+ val context = LocalContext.current++ // The first lists of the library load in the background, ready before a tap.+ LaunchedEffect((entries as? Response.Success)?.data?.take(8)?.map { it.spotifyId }) {+ val top = (entries as? Response.Success)?.data.orEmpty().take(8).mapNotNull { e ->+ when {+ e.isFolder || e.spotifyId.startsWith(LOCAL_PLAYLIST_PREFIX) -> null+ e.spotifyId in setOf(Api.HomeCache.LOCAL_FILES_ID, Api.HomeCache.DOWNLOADS_ID, Api.HomeCache.EPISODES_ID) -> null+ e.spotifyId == Api.HomeCache.LIKED_SONGS_ID -> "liked" to ""+ e.isPlaylist -> "playlist" to e.spotifyId+ else -> "album" to e.spotifyId+ }+ }+ if (top.isNotEmpty()) ContextViewModel.prefetchSoon(top)+ }++ var showAccount by remember { mutableStateOf(false) }+ var creating by remember { mutableStateOf(false) }+ var sorting by remember { mutableStateOf(false) }+ var itemMenu by remember { mutableStateOf<LibraryEntry?>(null) }+ // Rows or a grid of covers, persisted across runs.+ var gridView by remember { mutableStateOf(isLibraryGridView(context)) }+ var searchActive by remember { mutableStateOf(false) }+ var searchQuery by remember { mutableStateOf("") }+ var kind by rememberSaveable { mutableStateOf(LibraryChip.ALL) }++ if (showAccount) {+ ImmersiveAccountSheet(+ account = (account as? Response.Success)?.data ?: AccountModel(),+ navController = navController,+ onDismiss = { showAccount = false },+ )+ }+ if (creating) LibraryCreateSheet(navController, onDismiss = { creating = false }, onLibraryChanged = { vm.load() })+ if (sorting) ImmersiveLibrarySortSheet(onDismiss = { sorting = false })+ itemMenu?.let { LibraryItemSheet(it, onDismiss = { itemMenu = null }, onChanged = { vm.load() }) }++ val loading = entries is Response.Loading+ val (allEntries, pinned) = libraryEntries(entries)+ val (byKind, artists) = LibraryChips.apply(+ kind, allEntries, followedArtists,+ setOf(Api.HomeCache.LIKED_SONGS_ID, Api.HomeCache.LOCAL_FILES_ID, Api.HomeCache.DOWNLOADS_ID),+ )+ val shownEntries = if (searchQuery.isBlank()) byKind else byKind.filter {+ it.name.contains(searchQuery, ignoreCase = true) || it.subtitle.contains(searchQuery, ignoreCase = true)+ }+ val shownArtists = if (searchQuery.isBlank()) artists else artists.filter { it.name.contains(searchQuery, ignoreCase = true) }+ // Only the whole library, unfiltered, can be put in a new order.+ val reorderLevel = if (kind == LibraryChip.ALL && searchQuery.isBlank()) LibraryOrder.ROOT else null++ val title = stringResource(R.string.navigationbar_musicappitems_yourlibrary_title)+ val listState = rememberLazyListState()+ val gridState = rememberLazyGridState()+ val header: @Composable () -> Unit = {+ LibraryHeader(+ title = title,+ gridView = gridView,+ onToggleGrid = {+ gridView = !gridView+ setLibraryGridView(context, gridView)+ },+ onSort = { sorting = true },+ searchActive = searchActive,+ query = searchQuery,+ onQuery = { searchQuery = it },+ kind = kind,+ onKind = { kind = LibraryChips.toggle(kind, it) },+ )+ }+ val avatar = (account as? Response.Success)?.data++ val refreshing by vm.refreshing.collectAsState()+ Box(Modifier.fillMaxSize().background(Immersive.Page)) {+ // Pull down to read the library again, as in the Classic look.+ androidx.compose.material3.pulltorefresh.PullToRefreshBox(+ isRefreshing = refreshing,+ onRefresh = { vm.refresh() },+ modifier = Modifier.fillMaxSize(),+ ) {+ if (gridView && !loading) {+ LibraryGrid(+ gridState = gridState,+ header = header,+ entries = shownEntries,+ artists = shownArtists,+ loadFailed = entries !is Response.Success,+ onRetry = { vm.load() },+ navController = navController,+ reorderLevel = reorderLevel,+ pinned = pinned,+ )+ } else {+ LibraryList(+ listState = listState,+ header = header,+ loading = loading,+ entries = shownEntries,+ artists = shownArtists,+ loadFailed = !loading && entries !is Response.Success,+ onRetry = { vm.load() },+ navController = navController,+ reorderLevel = reorderLevel,+ pinned = pinned,+ onMenu = { itemMenu = it },+ )+ }+ }+ val collapse = if (gridView && !loading) gridCollapse(gridState) else rememberTopBarCollapse(listState)+ ImmersiveTopBar(title, collapse) {+ ImmersiveBarAction(+ Icons.Rounded.Add,+ stringResource(R.string.create_playlist_content_description),+ onClick = { creating = true },+ )+ ImmersiveBarAction(+ Icons.Rounded.Search,+ stringResource(R.string.library_search_text_hint),+ onClick = {+ searchActive = !searchActive+ if (!searchActive) searchQuery = ""+ },+ tint = if (searchActive) Immersive.Accent else Immersive.Text,+ )+ Box(Modifier.size(44.dp), contentAlignment = Alignment.Center) {+ AvatarDisc(+ url = avatar?.imageUrl,+ initial = avatar?.name?.trim()?.firstOrNull()?.uppercase() ?: "•",+ contentDescription = stringResource(R.string.account_title),+ onClick = { showAccount = true },+ )+ }+ }+ }++ // Re-tap on the Library tab: an animated scroll back to the top of the rows already loaded.+ LaunchedEffect(gridView, loading) {+ TabReselect.library.collect {+ if (gridView && !loading) {+ if (gridState.firstVisibleItemIndex != 0 || gridState.firstVisibleItemScrollOffset != 0) gridState.animateScrollToItem(0)+ } else if (listState.firstVisibleItemIndex != 0 || listState.firstVisibleItemScrollOffset != 0) {+ listState.animateScrollToItem(0)+ }+ }+ }+}++/** The collapse fraction (0..1) of a grid page, as [rememberTopBarCollapse] gives a list's. */+@Composable+internal fun gridCollapse(state: LazyGridState): () -> Float {+ val distancePx = with(LocalDensity.current) { 40.dp.toPx() }+ return remember(state, distancePx) {+ val fraction: () -> Float = {+ if (state.firstVisibleItemIndex > 0) 1f+ else (state.firstVisibleItemScrollOffset / distancePx).coerceIn(0f, 1f)+ }+ fraction+ }+}++/**+ * The library's entries with the app's own folders in: Liked Songs, Local Files and Downloaded+ * stay on top, then the phone's own playlists, the rest following the chosen sort. The second+ * value is how many entries at the top never move.+ */+@Composable+private fun libraryEntries(entries: Response<List<LibraryEntry>>): Pair<List<LibraryEntry>, Int> {+ val localName = stringResource(R.string.local_files_title)+ val downloadsName = stringResource(R.string.collection_downloaded)+ val localSubtitle = stringResource(R.string.assisted_curation_search_playlist) + " • " + stringResource(R.string.local_playlist_subtitle)+ val likedName = stringResource(R.string.collection_liked_songs_title)+ val packageName = LocalContext.current.packageName+ val hasDownloads = com.music.spotui.data.offline.OfflineStore.tracks.isNotEmpty() ||+ com.music.spotui.data.offline.OfflineDownloader.requests.isNotEmpty()+ val base = (entries as? Response.Success)?.data ?: emptyList()+ val rootPinned = base.indexOfFirst { it.spotifyId == Api.HomeCache.LIKED_SONGS_ID } + 2 + (if (hasDownloads) 1 else 0)+ val all = base.map {+ if (it.spotifyId == Api.HomeCache.LIKED_SONGS_ID) it.copy(name = likedName, subtitle = "") else it+ }.let { list ->+ val local = LibraryEntry(+ spotifyId = Api.HomeCache.LOCAL_FILES_ID, name = localName, subtitle = "",+ coverUri = "android.resource://$packageName/drawable/local_files_cover", isPlaylist = true,+ )+ val downloads = LibraryEntry(+ spotifyId = Api.HomeCache.DOWNLOADS_ID, name = downloadsName, subtitle = "", coverUri = "", isPlaylist = true,+ )+ val at = list.indexOfFirst { it.spotifyId == Api.HomeCache.LIKED_SONGS_ID } + 1+ // The phone's own playlists: files of this phone, not on the account.+ val localLists = com.music.spotui.data.local.LocalPlaylists.list().map { p ->+ LibraryEntry(+ spotifyId = LOCAL_PLAYLIST_PREFIX + p.id, name = p.name,+ subtitle = localSubtitle, coverUri = "", isPlaylist = true,+ )+ }+ list.take(at) + local + (if (hasDownloads) listOf(downloads) else emptyList()) + localLists + list.drop(at)+ }.let { list ->+ LibraryOrder.version+ LibraryOrder.arrange(list, LibraryOrder.sort, LibraryOrder.custom(LibraryOrder.ROOT), rootPinned)+ }+ return all to rootPinned+}++/** Title, sort and view controls, the optional search field and the kind pills: one list item. */+@Composable+private fun LibraryHeader(+ title: String,+ gridView: Boolean,+ onToggleGrid: () -> Unit,+ onSort: () -> Unit,+ searchActive: Boolean,+ query: String,+ onQuery: (String) -> Unit,+ kind: LibraryChip,+ onKind: (LibraryChip) -> Unit,+) {+ Column {+ // The title itself scrolls the list to its top.+ Box(+ Modifier.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {+ TabReselect.emit(Routes.Library.route)+ },+ ) { ImmersiveLargeTitle(title) }+ Row(+ verticalAlignment = Alignment.CenterVertically,+ modifier = Modifier.fillMaxWidth().padding(horizontal = Immersive.Gutter).padding(bottom = 2.dp),+ ) {+ Row(+ verticalAlignment = Alignment.CenterVertically,+ modifier = Modifier.immersiveClickable(onClick = onSort).padding(vertical = 6.dp),+ ) {+ Icon(Icons.Rounded.SwapVert, contentDescription = null, tint = Immersive.Text, modifier = Modifier.size(18.dp))+ Text(+ text = stringResource(libraryOrderLabel(LibraryOrder.sort)),+ style = Immersive.Subhead.copy(color = Immersive.Text, fontWeight = FontWeight.SemiBold),+ modifier = Modifier.padding(start = 6.dp),+ )+ }+ Spacer(Modifier.weight(1f))+ Icon(+ painter = painterResource(if (gridView) R.drawable.ic_view_list else R.drawable.ic_view_grid),+ contentDescription = stringResource(if (gridView) R.string.list_view else R.string.grid_view),+ tint = Immersive.Text,+ modifier = Modifier+ .size(32.dp)+ .clip(CircleShape)+ .clickable(onClick = onToggleGrid)+ .padding(7.dp),+ )+ }+ AnimatedVisibility(+ visible = searchActive,+ enter = fadeIn() + expandVertically(),+ exit = fadeOut() + shrinkVertically(),+ ) {+ ImmersiveSearchField(+ query = query,+ onQueryChange = onQuery,+ onSubmit = {},+ placeholder = stringResource(R.string.library_search_text_hint),+ modifier = Modifier.padding(horizontal = Immersive.Gutter).padding(top = 4.dp, bottom = 4.dp),+ )+ }+ ImmersiveChipRow {+ LibraryChipLabels.forEach { (k, label) ->+ ImmersiveChip(stringResource(label), selected = k == kind) { onKind(k) }+ }+ }+ }+}++/** Lays the content out [inset] wider on each side, for a full-width row inside a padded grid. */+internal fun Modifier.immersiveBleed(inset: Dp): Modifier = layout { measurable, constraints ->+ val px = inset.roundToPx()+ val width = constraints.maxWidth + 2 * px+ val placeable = measurable.measure(constraints.copy(minWidth = width, maxWidth = width))+ layout(constraints.maxWidth, placeable.height) { placeable.place(-px, 0) }+}++/** Albums, playlists and folders start loading under the finger. */+private fun prefetchLibraryEntry(entry: LibraryEntry) = when {+ entry.isFolder || entry.spotifyId.startsWith(LOCAL_PLAYLIST_PREFIX) -> Unit+ entry.spotifyId == Api.HomeCache.LOCAL_FILES_ID || entry.spotifyId == Api.HomeCache.DOWNLOADS_ID || entry.spotifyId == Api.HomeCache.EPISODES_ID -> Unit+ entry.spotifyId == Api.HomeCache.LIKED_SONGS_ID -> ContextViewModel.prefetch("liked", "")+ entry.isPlaylist -> ContextViewModel.prefetch("playlist", entry.spotifyId)+ else -> ContextViewModel.prefetch("album", entry.spotifyId)+}++private fun openLibraryEntry(entry: LibraryEntry, navController: NavController) {+ if (entry.isFolder) navController.navigate(folderRoute(entry.folderUri, entry.name))+ else if (entry.spotifyId.startsWith(LOCAL_PLAYLIST_PREFIX)) navController.navigate(localPlaylistRoute(entry.spotifyId.removePrefix(LOCAL_PLAYLIST_PREFIX)))+ else if (entry.spotifyId == Api.HomeCache.DOWNLOADS_ID) navController.navigate(Routes.Downloads.route)+ else if (entry.spotifyId == Api.HomeCache.LOCAL_FILES_ID) navController.navigate(Routes.LocalFiles.route)+ else if (entry.spotifyId == Api.HomeCache.LIKED_SONGS_ID) navController.navigate(Routes.Liked.route)+ else if (entry.spotifyId == Api.HomeCache.EPISODES_ID) navController.navigate(Routes.Episodes.route)+ else if (entry.isPlaylist) navController.navigate(playlistRoute(entry.spotifyId, entry.name))+ else navController.navigate(albumRoute(entry.name, entry.artists, entry.spotifyId))+}++/** The rows layout. */+@OptIn(ExperimentalFoundationApi::class)+@Composable+private fun LibraryList(+ listState: LazyListState,+ header: @Composable () -> Unit,+ loading: Boolean,+ entries: List<LibraryEntry>,+ artists: List<ArtistsModel>,+ loadFailed: Boolean,+ onRetry: () -> Unit,+ navController: NavController,+ reorderLevel: String?,+ pinned: Int,+ onMenu: (LibraryEntry) -> Unit,+) {+ val haptic = LocalHapticFeedback.current+ val density = LocalDensity.current+ // The rows as shown, moved live under the finger; saved when the finger lifts. One state+ // for the screen's life: the drag gestures hold on to it.+ var rows by remember { mutableStateOf(entries.distinctBy { LibraryOrder.key(it) }) }+ var dragKey by remember { mutableStateOf<String?>(null) }+ var dragOffset by remember { mutableStateOf(0f) }+ val level by rememberUpdatedState(reorderLevel)+ val fixed by rememberUpdatedState(pinned)+ LaunchedEffect(entries) {+ if (dragKey == null) rows = entries.distinctBy { LibraryOrder.key(it) }+ }++ // Moves the dragged row to the row its centre is over (pinned rows excluded).+ fun follow() {+ val key = dragKey ?: return+ val info = listState.layoutInfo.visibleItemsInfo+ val dragged = info.firstOrNull { it.key == key } ?: return+ val centre = dragged.offset + dragOffset + dragged.size / 2f+ val target = info.firstOrNull { it.key != key && it.key is String && centre.toInt() in it.offset until it.offset + it.size } ?: return+ val from = rows.indexOfFirst { LibraryOrder.key(it) == key }+ val to = rows.indexOfFirst { LibraryOrder.key(it) == target.key }+ if (from < fixed || to < fixed || from < 0 || to < 0) return+ // Keeps the list still when the first visible row is involved.+ if (listState.firstVisibleItemIndex == from || listState.firstVisibleItemIndex == to) {+ listState.requestScrollToItem(listState.firstVisibleItemIndex, listState.firstVisibleItemScrollOffset)+ }+ rows = rows.toMutableList().apply { add(to, removeAt(from)) }+ dragOffset += dragged.offset - target.offset+ }++ fun finish() {+ val at = level+ if (dragKey != null && at != null) LibraryOrder.saveCustom(at, rows.drop(fixed).map { LibraryOrder.key(it) })+ dragKey = null+ dragOffset = 0f+ }++ // Near the top or bottom edge, the list scrolls by itself while a row is dragged.+ LaunchedEffect(dragKey) {+ if (dragKey == null) return@LaunchedEffect+ val edge = with(density) { 72.dp.toPx() }+ while (dragKey != null) {+ val info = listState.layoutInfo+ val dragged = info.visibleItemsInfo.firstOrNull { it.key == dragKey }+ if (dragged != null) {+ val top = dragged.offset + dragOffset+ val bottom = top + dragged.size+ val speed = when {+ bottom > info.viewportEndOffset - edge -> 18f+ top < info.viewportStartOffset + edge -> -18f+ else -> 0f+ }+ if (speed != 0f) {+ val moved = listState.scrollBy(speed)+ dragOffset += moved+ follow()+ }+ }+ withFrameNanos { }+ }+ }++ Box(Modifier.fillMaxSize()) {+ LazyColumn(+ state = listState,+ contentPadding = PaddingValues(top = immersiveTopContentPadding(), bottom = Immersive.BottomChrome),+ modifier = Modifier.fillMaxSize().immersiveHazeSource().immersiveChromeScroll(),+ ) {+ item(key = "library:header") { header() }+ if (loading) {+ immersiveLibrarySkeleton()+ return@LazyColumn+ }+ if (entries.isEmpty() && artists.isEmpty() && !loadFailed) {+ item(key = "library:empty") { ImmersiveMessageState(stringResource(R.string.library_empty)) }+ }+ itemsIndexed(rows, key = { _, e -> LibraryOrder.key(e) }) { index, entry ->+ val key = LibraryOrder.key(entry)+ val dragged = dragKey == key+ val movable = reorderLevel != null && index >= pinned+ LibraryEntryRow(+ entry = entry,+ onMenu = { onMenu(entry) },+ modifier = Modifier+ // Same modifier chain while dragging: changing its shape would rebuild the+ // gesture detector below and cancel the drag as soon as it starts.+ .animateItem(+ fadeInSpec = null, fadeOutSpec = null,+ placementSpec = if (dragged) null else spring(+ stiffness = Spring.StiffnessMediumLow,+ visibilityThreshold = IntOffset.VisibilityThreshold,+ ),+ )+ .zIndex(if (dragged) 1f else 0f)+ .graphicsLayer {+ translationY = if (dragged) dragOffset else 0f+ if (dragged) { scaleX = 1.03f; scaleY = 1.03f }+ }+ .background(if (dragged) Immersive.Raised else androidx.compose.ui.graphics.Color.Transparent, Immersive.CoverMedium)+ .pressHint { prefetchLibraryEntry(entry) }+ .immersiveClickable(onClick = { openLibraryEntry(entry, navController) }, pressedScale = 0.98f)+ // Inside the clickable, so a long press that ends without moving opens nothing.+ .then(+ if (!movable) Modifier else Modifier.pointerInput(key) {+ try {+ detectDragGesturesAfterLongPress(+ onDragStart = {+ haptic.performHapticFeedback(HapticFeedbackType.LongPress)+ dragKey = key+ dragOffset = 0f+ },+ onDrag = { change, amount -> change.consume(); dragOffset += amount.y; follow() },+ onDragEnd = { finish() },+ onDragCancel = { finish() },+ )+ } finally {+ if (dragKey == key) finish()+ }+ },+ ),+ )+ }+ // Artists followed on the account.+ if (artists.isNotEmpty()) {+ item(key = "library:artists-header") { SectionHeader(stringResource(R.string.song_dna_search_chip_followed_artists)) }+ itemsIndexed(artists, key = { _, a -> "artist:${a.id.ifBlank { a.name }}" }) { _, artist ->+ Row(+ verticalAlignment = Alignment.CenterVertically,+ modifier = Modifier+ .fillMaxWidth()+ .immersiveClickable(onClick = { navController.navigate(artistRoute(artist.name, artist.id)) }, pressedScale = 0.98f)+ .padding(horizontal = Immersive.Gutter, vertical = 4.dp),+ ) {+ ImmersiveCover(artist.coverUri, Modifier.size(52.dp), CircleShape)+ Column(Modifier.padding(start = 14.dp)) {+ Text(+ text = artist.name,+ style = Immersive.Body.copy(fontWeight = FontWeight.Medium),+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )+ Text(text = stringResource(R.string.artist_subtitle), style = Immersive.Subhead)+ }+ }+ }+ }+ if (loadFailed) {+ item(key = "library:error") {+ ImmersiveMessageState(+ message = stringResource(R.string.library_error),+ actionLabel = stringResource(R.string.home_retry),+ onAction = onRetry,+ )+ }+ }+ }+ FastScrollbar(listState, Modifier.align(Alignment.CenterEnd))+ }+}++/** One row of the library: a cover, the name, the creator or kind, a pin mark and the menu. */+@Composable+private fun LibraryEntryRow(entry: LibraryEntry, onMenu: () -> Unit, modifier: Modifier = Modifier) {+ Row(+ verticalAlignment = Alignment.CenterVertically,+ modifier = modifier+ .fillMaxWidth()+ .padding(horizontal = Immersive.Gutter, vertical = 4.dp),+ ) {+ val shape = Immersive.CoverSmall+ LibraryEntryCover(+ entry,+ Modifier.size(52.dp).clip(shape).background(Immersive.Raised).immersiveThumbnailBorder(shape),+ )+ Column(modifier = Modifier.padding(start = 14.dp).weight(1f)) {+ Text(+ text = entry.name,+ style = Immersive.Body.copy(fontWeight = FontWeight.Medium),+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )+ Row(verticalAlignment = Alignment.CenterVertically) {+ if (entry.pinned) {+ Icon(+ Icons.Rounded.PushPin, contentDescription = null, tint = Immersive.Accent,+ modifier = Modifier.padding(end = 4.dp).size(12.dp),+ )+ }+ Text(text = entry.subtitle, style = Immersive.Subhead, maxLines = 1, overflow = TextOverflow.Ellipsis)+ }+ }+ if (entry.uri.isNotBlank()) ImmersiveMoreButton(onClick = onMenu)+ }+}++/** The grid layout: square covers with the name and creator underneath, artists as circles. */+@OptIn(ExperimentalFoundationApi::class)+@Composable+private fun LibraryGrid(+ gridState: LazyGridState,+ header: @Composable () -> Unit,+ entries: List<LibraryEntry>,+ artists: List<ArtistsModel>,+ loadFailed: Boolean,+ onRetry: () -> Unit,+ navController: NavController,+ reorderLevel: String?,+ pinned: Int,+) {+ val haptic = LocalHapticFeedback.current+ val density = LocalDensity.current+ // Same as the list view, in two dimensions: the tile follows the finger and takes the place+ // of the tile its centre is over.+ var rows by remember { mutableStateOf(entries.distinctBy { LibraryOrder.key(it) }) }+ var dragKey by remember { mutableStateOf<String?>(null) }+ var dragOffset by remember { mutableStateOf(Offset.Zero) }+ val level by rememberUpdatedState(reorderLevel)+ val fixed by rememberUpdatedState(pinned)+ LaunchedEffect(entries) {+ if (dragKey == null) rows = entries.distinctBy { LibraryOrder.key(it) }+ }++ fun follow() {+ val key = dragKey ?: return+ val info = gridState.layoutInfo.visibleItemsInfo+ val dragged = info.firstOrNull { it.key == key } ?: return+ val cx = dragged.offset.x + dragOffset.x + dragged.size.width / 2f+ val cy = dragged.offset.y + dragOffset.y + dragged.size.height / 2f+ val target = info.firstOrNull {+ it.key != key && it.key is String &&+ cx >= it.offset.x && cx < it.offset.x + it.size.width && cy >= it.offset.y && cy < it.offset.y + it.size.height+ } ?: return+ val from = rows.indexOfFirst { LibraryOrder.key(it) == key }+ val to = rows.indexOfFirst { LibraryOrder.key(it) == target.key }+ if (from < fixed || to < fixed || from < 0 || to < 0) return+ if (gridState.firstVisibleItemIndex == from || gridState.firstVisibleItemIndex == to) {+ gridState.requestScrollToItem(gridState.firstVisibleItemIndex, gridState.firstVisibleItemScrollOffset)+ }+ rows = rows.toMutableList().apply { add(to, removeAt(from)) }+ dragOffset += Offset((dragged.offset.x - target.offset.x).toFloat(), (dragged.offset.y - target.offset.y).toFloat())+ }++ fun finish() {+ val at = level+ if (dragKey != null && at != null) LibraryOrder.saveCustom(at, rows.drop(fixed).map { LibraryOrder.key(it) })+ dragKey = null+ dragOffset = Offset.Zero+ }++ LaunchedEffect(dragKey) {+ if (dragKey == null) return@LaunchedEffect+ val edge = with(density) { 72.dp.toPx() }+ while (dragKey != null) {+ val info = gridState.layoutInfo+ val dragged = info.visibleItemsInfo.firstOrNull { it.key == dragKey }+ if (dragged != null) {+ val top = dragged.offset.y + dragOffset.y+ val bottom = top + dragged.size.height+ val speed = when {+ bottom > info.viewportEndOffset - edge -> 18f+ top < info.viewportStartOffset + edge -> -18f+ else -> 0f+ }+ if (speed != 0f) {+ val moved = gridState.scrollBy(speed)+ dragOffset += Offset(0f, moved)+ follow()+ }+ }+ withFrameNanos { }+ }+ }++ LazyVerticalGrid(+ state = gridState,+ columns = GridCells.Fixed(3),+ modifier = Modifier.fillMaxSize().immersiveChromeScroll(),+ contentPadding = PaddingValues(+ start = Immersive.Gutter, end = Immersive.Gutter,+ top = immersiveTopContentPadding(), bottom = Immersive.BottomChrome,+ ),+ horizontalArrangement = Arrangement.spacedBy(12.dp),+ verticalArrangement = Arrangement.spacedBy(18.dp),+ ) {+ item(key = "library:header", span = { GridItemSpan(maxLineSpan) }) {+ Box(Modifier.immersiveBleed(Immersive.Gutter)) { header() }+ }+ if (entries.isEmpty() && artists.isEmpty() && !loadFailed) {+ item(key = "library:empty", span = { GridItemSpan(maxLineSpan) }) {+ ImmersiveMessageState(stringResource(R.string.library_empty))+ }+ }+ itemsIndexed(rows, key = { _, e -> LibraryOrder.key(e) }) { index, entry ->+ val key = LibraryOrder.key(entry)+ val dragged = dragKey == key+ val movable = reorderLevel != null && index >= pinned+ val shape = Immersive.CoverMedium+ Column(+ modifier = Modifier+ // Same modifier chain while dragging (see the list view).+ .animateItem(+ fadeInSpec = null, fadeOutSpec = null,+ placementSpec = if (dragged) null else spring(+ stiffness = Spring.StiffnessMediumLow,+ visibilityThreshold = IntOffset.VisibilityThreshold,+ ),+ )+ .zIndex(if (dragged) 1f else 0f)+ .graphicsLayer {+ translationX = if (dragged) dragOffset.x else 0f+ translationY = if (dragged) dragOffset.y else 0f+ if (dragged) { scaleX = 1.06f; scaleY = 1.06f }+ }+ .pressHint { prefetchLibraryEntry(entry) }+ .immersiveClickable(onClick = { openLibraryEntry(entry, navController) })+ .then(+ if (!movable) Modifier else Modifier.pointerInput(key) {+ try {+ detectDragGesturesAfterLongPress(+ onDragStart = {+ haptic.performHapticFeedback(HapticFeedbackType.LongPress)+ dragKey = key+ dragOffset = Offset.Zero+ },+ onDrag = { change, amount -> change.consume(); dragOffset += amount; follow() },+ onDragEnd = { finish() },+ onDragCancel = { finish() },+ )+ } finally {+ if (dragKey == key) finish()+ }+ },+ ),+ ) {+ LibraryEntryCover(+ entry,+ Modifier.fillMaxWidth().aspectRatio(1f).clip(shape).background(Immersive.Raised).immersiveThumbnailBorder(shape),+ )+ Spacer(Modifier.height(6.dp))+ Text(+ text = entry.name,+ style = Immersive.Subhead.copy(color = Immersive.Text, fontWeight = FontWeight.Medium),+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )+ if (entry.subtitle.isNotBlank()) {+ Text(text = entry.subtitle, style = Immersive.Caption, maxLines = 1, overflow = TextOverflow.Ellipsis)+ }+ }+ }+ if (artists.isNotEmpty()) {+ item(key = "library:artists-header", span = { GridItemSpan(maxLineSpan) }) {+ Box(Modifier.immersiveBleed(Immersive.Gutter)) { SectionHeader(stringResource(R.string.song_dna_search_chip_followed_artists)) }+ }+ itemsIndexed(artists, key = { _, a -> "artist:${a.id.ifBlank { a.name }}" }) { _, artist ->+ Column(+ horizontalAlignment = Alignment.CenterHorizontally,+ modifier = Modifier.immersiveClickable(onClick = { navController.navigate(artistRoute(artist.name, artist.id)) }),+ ) {+ ImmersiveCover(artist.coverUri, Modifier.fillMaxWidth().aspectRatio(1f), CircleShape)+ Spacer(Modifier.height(6.dp))+ Text(+ text = artist.name,+ style = Immersive.Subhead.copy(color = Immersive.Text, fontWeight = FontWeight.Medium),+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ textAlign = TextAlign.Center,+ )+ Text(text = stringResource(R.string.artist_subtitle), style = Immersive.Caption, textAlign = TextAlign.Center)+ }+ }+ }+ if (loadFailed) {+ item(key = "library:error", span = { GridItemSpan(maxLineSpan) }) {+ ImmersiveMessageState(+ message = stringResource(R.string.library_error),+ actionLabel = stringResource(R.string.home_retry),+ onAction = onRetry,+ )+ }+ }+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveLibrarySheets.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveLibrarySheets.ktnew file mode 100644index 00000000..2ceb79b9--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveLibrarySheets.kt@@ -0,0 +1,170 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * app/src/main/java/com/music/bitchord/ui/screens/LibraryPhoneParts.kt at edc1e6f.+ * The sheets' rows and actions are those of Myspoti's Classic Library screen. Modified for Myspoti, 2026-10.+ */+package com.music.spotui.ui.immersive.screens++import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.navigationBarsPadding+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.rounded.Check+import androidx.compose.material3.ExperimentalMaterial3Api+import androidx.compose.material3.HorizontalDivider+import androidx.compose.material3.Icon+import androidx.compose.material3.ModalBottomSheet+import androidx.compose.material3.Text+import androidx.compose.material3.rememberModalBottomSheetState+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.semantics.Role+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import androidx.navigation.NavController+import app.myspoti.engine.R+import com.music.spotui.data.api.ProfileCache+import com.music.spotui.data.entity.AccountModel+import com.music.spotui.data.local.LibraryOrder+import com.music.spotui.di.Graph+import com.music.spotui.ui.immersive.Immersive+import com.music.spotui.ui.navigation.Routes+import com.music.spotui.ui.navigation.profileRoute+import com.music.spotui.ui.screens.AccountBrowser++/** The label of a library sort order. */+internal fun libraryOrderLabel(sort: LibraryOrder.Sort): Int = when (sort) {+ LibraryOrder.Sort.CUSTOM -> R.string.your_library_sort_order_custom+ LibraryOrder.Sort.RECENTS -> R.string.library_sort_recents+ LibraryOrder.Sort.RECENTLY_ADDED -> R.string.library_sort_recently_added+ LibraryOrder.Sort.ALPHABETICAL -> R.string.your_library_sort_order_alphabetical+ LibraryOrder.Sort.CREATOR -> R.string.your_library_sort_order_creator+}++/** "Sort by": custom order (moved by hand), recents, alphabetical or by creator, and a reset. */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+internal fun ImmersiveLibrarySortSheet(onDismiss: () -> Unit) {+ ModalBottomSheet(onDismissRequest = onDismiss, containerColor = Immersive.Raised) {+ Column(Modifier.navigationBarsPadding().padding(bottom = 16.dp)) {+ Text(+ text = stringResource(R.string.filter_and_sort_sort_section_title),+ style = Immersive.Title,+ modifier = Modifier.padding(horizontal = Immersive.Gutter, vertical = 8.dp),+ )+ for (sort in LibraryOrder.Sort.entries) {+ val selected = LibraryOrder.sort == sort+ Row(+ verticalAlignment = Alignment.CenterVertically,+ modifier = Modifier+ .fillMaxWidth()+ .clickable(role = Role.Button) { LibraryOrder.choose(sort); onDismiss() }+ .padding(horizontal = Immersive.Gutter, vertical = 14.dp),+ ) {+ Text(+ text = stringResource(libraryOrderLabel(sort)),+ style = Immersive.Body.copy(color = if (selected) Immersive.Accent else Immersive.Text),+ modifier = Modifier.weight(1f),+ )+ if (selected) {+ Icon(Icons.Rounded.Check, contentDescription = null, tint = Immersive.Accent, modifier = Modifier.size(20.dp))+ }+ }+ }+ Text(+ text = stringResource(R.string.library_reorder_hint),+ style = Immersive.Caption,+ modifier = Modifier.padding(horizontal = Immersive.Gutter, vertical = 8.dp),+ )+ Text(+ text = stringResource(R.string.immersive_screens_reset_order),+ style = Immersive.BodyStrong,+ modifier = Modifier+ .fillMaxWidth()+ .clickable(role = Role.Button) { LibraryOrder.reset(); onDismiss() }+ .padding(horizontal = Immersive.Gutter, vertical = 14.dp),+ )+ }+ }+}++/** The account behind the avatar: who is signed in, the profile, settings and the account page. */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+internal fun ImmersiveAccountSheet(+ account: AccountModel,+ navController: NavController,+ onDismiss: () -> Unit,+) {+ ModalBottomSheet(+ onDismissRequest = onDismiss,+ sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true),+ containerColor = Immersive.Raised,+ ) {+ Column(modifier = Modifier.navigationBarsPadding()) {+ Row(+ verticalAlignment = Alignment.CenterVertically,+ modifier = Modifier.fillMaxWidth().padding(Immersive.Gutter, 4.dp, Immersive.Gutter, 16.dp),+ ) {+ AvatarDisc(+ url = account.imageUrl,+ initial = account.name.trim().firstOrNull()?.uppercase() ?: "•",+ contentDescription = stringResource(R.string.account_title),+ onClick = null,+ size = 56.dp,+ )+ Column(Modifier.padding(start = 14.dp)) {+ Text(+ text = account.name.ifBlank { stringResource(R.string.immersive_screens_account) },+ style = Immersive.Headline,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )+ if (account.email.isNotBlank()) {+ Text(account.email, style = Immersive.Subhead, maxLines = 1, overflow = TextOverflow.Ellipsis)+ }+ if (account.plan.isNotBlank()) {+ Text(account.plan, style = Immersive.Caption.copy(color = Immersive.Accent))+ }+ }+ }+ HorizontalDivider(color = Immersive.Separator)+ ProfileCache.id?.let { myId ->+ AccountRow(stringResource(R.string.view_profile)) {+ onDismiss()+ navController.navigate(profileRoute(myId, account.name))+ }+ }+ AccountRow(stringResource(R.string.settings_title)) {+ onDismiss()+ navController.navigate(Routes.Settings.route)+ }+ AccountRow(stringResource(R.string.immersive_screens_account_page) + " ↗") {+ onDismiss()+ AccountBrowser.open(Graph.app, AccountBrowser.ACCOUNT_URL)+ }+ HorizontalDivider(color = Immersive.Separator)+ Spacer(Modifier.height(8.dp))+ }+ }+}++@Composable+private fun AccountRow(label: String, onClick: () -> Unit) {+ Text(+ text = label,+ style = Immersive.Body,+ modifier = Modifier+ .fillMaxWidth()+ .clickable(role = Role.Button, onClick = onClick)+ .padding(Immersive.Gutter, 16.dp),+ )+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveSearchBrowse.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveSearchBrowse.ktnew file mode 100644index 00000000..3b3fa07d--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveSearchBrowse.kt@@ -0,0 +1,186 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * sharedUi/src/jvmSharedMain/kotlin/com/music/bitchord/ui/screens/ExploreScreen.kt at edc1e6f.+ * Modified for Myspoti, 2026-10.+ */+package com.music.spotui.ui.immersive.screens++import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.aspectRatio+import androidx.compose.foundation.layout.fillMaxHeight+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.produceState+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.geometry.Offset+import androidx.compose.ui.graphics.Brush+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.ColorFilter+import androidx.compose.ui.graphics.ColorMatrix+import androidx.compose.ui.graphics.Shadow+import androidx.compose.ui.graphics.lerp+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import app.myspoti.engine.R+import app.myspoti.host.android.MyspotiRuntime+import com.bumptech.glide.integration.compose.CrossFade+import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi+import com.bumptech.glide.integration.compose.GlideImage+import com.music.spotui.data.api.Features+import com.music.spotui.ui.components.spotifyImageUrl+import com.music.spotui.ui.immersive.Immersive+import com.music.spotui.ui.immersive.components.immersiveClickable++/** Genre key of the "New releases" tile, opened in its own screen (same key as the Classic screen). */+internal const val ImmersiveNewReleasesGenre = "new-releases"++/** One "Browse all" tile: a category's title, colour and artwork. */+internal data class BrowseTile(val key: String, val title: String, val color: Color, val image: String)++/** The catalogue's categories, "New releases" first. Empty until they have loaded. */+@Composable+internal fun rememberBrowseTiles(): List<BrowseTile> {+ val newReleases = stringResource(R.string.browse_new_releases)+ val tiles by produceState(initialValue = emptyList<BrowseTile>()) {+ val categories = runCatching { MyspotiRuntime.api.home.categories() }.getOrDefault(emptyList())+ value = listOf(BrowseTile(ImmersiveNewReleasesGenre, newReleases, Color(0xFFE8115B), "")) ++ categories+ .filter { Features.PODCASTS || !it.title.contains("odcast", ignoreCase = true) }+ .map { c ->+ val color = runCatching { Color(android.graphics.Color.parseColor(c.color ?: "#333333")) }+ .getOrDefault(Color(0xFF333333))+ BrowseTile(c.uri, c.title, color, c.images.firstOrNull()?.url.orEmpty())+ }+ }+ return tiles+}++/** A row of [columns] browse tiles; a short last row keeps its tiles the size of a full row's. */+@Composable+internal fun BrowseTileRow(+ row: List<BrowseTile>,+ columns: Int,+ onClick: (BrowseTile) -> Unit,+) {+ Row(+ horizontalArrangement = Arrangement.spacedBy(TileSpacing),+ modifier = Modifier.padding(horizontal = Immersive.Gutter).padding(bottom = TileSpacing),+ ) {+ row.forEach { tile ->+ BrowseTileCard(+ tile = tile,+ modifier = Modifier+ .weight(1f)+ .aspectRatio(TileAspect)+ .clip(TileShape)+ .immersiveClickable(onClick = { onClick(tile) }),+ )+ }+ repeat(columns - row.size) { Spacer(Modifier.weight(1f)) }+ }+}++/**+ * A solid stripe down the left and the category's cover filling the rest, redrawn as a duotone+ * of the stripe's colour so every card reads as one tinted sleeve rather than a photo pasted+ * onto a swatch. Only the artwork: the caller sizes, clips and makes it clickable.+ */+@OptIn(ExperimentalGlideComposeApi::class)+@Composable+internal fun BrowseTileCard(tile: BrowseTile, modifier: Modifier = Modifier) {+ val tone = remember(tile.color) { moodTone(tile.color) }+ val artwork = spotifyImageUrl(tile.image)+ Box(modifier = modifier.background(tone.stripe)) {+ Box(+ Modifier+ .align(Alignment.CenterEnd)+ .fillMaxHeight()+ .fillMaxWidth(1f - StripeFraction)+ .background(tone.placeholder),+ ) {+ if (artwork != null) {+ GlideImage(+ model = artwork,+ contentDescription = null,+ contentScale = ContentScale.Crop,+ transition = CrossFade,+ colorFilter = tone.duotone,+ modifier = Modifier.fillMaxSize(),+ )+ }+ }+ // Pale stripes would swallow white type; a soft shade under the title keeps it legible.+ Box(+ Modifier+ .matchParentSize()+ .background(Brush.verticalGradient(0f to Color.Black.copy(alpha = .24f), .62f to Color.Transparent)),+ )+ Text(+ text = tile.title,+ style = Immersive.BodyStrong.copy(+ color = Color.White,+ fontWeight = FontWeight.Bold,+ shadow = Shadow(Color.Black.copy(alpha = .35f), offset = Offset(0f, 1f), blurRadius = 6f),+ ),+ maxLines = 2,+ overflow = TextOverflow.Ellipsis,+ modifier = Modifier.align(Alignment.TopStart).padding(horizontal = 14.dp, vertical = 12.dp),+ )+ }+}++private class MoodTone(val stripe: Color, val placeholder: Color, val duotone: ColorFilter)++private fun moodTone(base: Color): MoodTone {+ // A touch of black keeps a bright palette from glowing against the black page.+ val stripe = lerp(base, Color.Black, .08f)+ val shadow = lerp(base, Color.Black, .68f)+ val highlight = lerp(base, Color.White, .32f)+ return MoodTone(+ stripe = stripe,+ placeholder = lerp(shadow, highlight, .45f),+ duotone = duotone(shadow, highlight),+ )+}++/** Maps each pixel's luminance onto the ramp [shadow] to [highlight]. */+private fun duotone(shadow: Color, highlight: Color): ColorFilter {+ fun channel(from: Float, to: Float): FloatArray {+ val span = to - from+ return floatArrayOf(span * .299f, span * .587f, span * .114f, 0f, from * 255f)+ }+ return ColorFilter.colorMatrix(+ ColorMatrix(+ channel(shadow.red, highlight.red) ++ channel(shadow.green, highlight.green) ++ channel(shadow.blue, highlight.blue) ++ floatArrayOf(0f, 0f, 0f, 1f, 0f),+ ),+ )+}++/** Gap between tiles, in both directions. */+private val TileSpacing = 12.dp++private val TileShape = RoundedCornerShape(18.dp)++/** Width over height; a two-column phone row lands at about 100 dp tall. */+private const val TileAspect = 1.72f++/** How much of the card the solid stripe covers before the artwork starts. */+private const val StripeFraction = .28fdiff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveSearchScreen.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveSearchScreen.ktnew file mode 100644index 00000000..eb1c5515--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveSearchScreen.kt@@ -0,0 +1,636 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * sharedUi/src/jvmSharedMain/kotlin/com/music/bitchord/ui/screens/SearchScreen.kt at edc1e6f.+ * Modified for Myspoti, 2026-10.+ */+package com.music.spotui.ui.immersive.screens++import com.music.spotui.ui.immersive.shell.immersiveHazeSource+import com.music.spotui.ui.immersive.shell.immersiveChromeScroll+import android.content.Context+import androidx.compose.foundation.ExperimentalFoundationApi+import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.LazyListScope+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.lazy.rememberLazyListState+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.rounded.Close+import androidx.compose.material.icons.rounded.PlayArrow+import androidx.compose.material.icons.rounded.Search+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.produceState+import androidx.compose.runtime.remember+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.onFocusChanged+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.semantics.Role+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import androidx.lifecycle.viewmodel.compose.viewModel+import androidx.navigation.NavController+import app.myspoti.api.MediaCard+import app.myspoti.engine.R+import app.myspoti.host.android.MyspotiRuntime+import com.music.spotui.data.api.Features+import com.music.spotui.data.api.Response+import com.music.spotui.data.entity.AlbumsModel+import com.music.spotui.data.entity.ArtistsModel+import com.music.spotui.data.entity.LibraryEntry+import com.music.spotui.data.entity.PodcastModel+import com.music.spotui.data.entity.SearchResults+import com.music.spotui.data.entity.SongsModel+import com.music.spotui.data.preferences.RecentItem+import com.music.spotui.data.preferences.addRecentItem+import com.music.spotui.data.preferences.clearRecentItems+import com.music.spotui.data.preferences.getRecentItems+import com.music.spotui.data.preferences.removeRecentItem+import com.music.spotui.di.Graph+import com.music.spotui.di.SongPlayer+import com.music.spotui.ui.immersive.sheets.ImmersiveSongOptionsSheet+import com.music.spotui.ui.components.SwipeToQueue+import com.music.spotui.ui.immersive.Immersive+import com.music.spotui.ui.immersive.components.ImmersiveButton+import com.music.spotui.ui.immersive.components.ImmersiveCover+import com.music.spotui.ui.immersive.components.ImmersiveListRow+import com.music.spotui.ui.immersive.components.ImmersiveMessageState+import com.music.spotui.ui.immersive.components.ImmersiveMoreButton+import com.music.spotui.ui.immersive.components.ImmersiveRowDividerInset+import com.music.spotui.ui.immersive.components.ImmersiveSearchField+import com.music.spotui.ui.immersive.components.ImmersiveSongRow+import com.music.spotui.ui.immersive.components.SectionHeader+import com.music.spotui.ui.immersive.components.immersiveClickable+import com.music.spotui.ui.immersive.components.immersiveSongListSkeleton+import com.music.spotui.ui.immersive.shell.ImmersiveTopBar+import com.music.spotui.ui.immersive.shell.immersiveLargeTitle+import com.music.spotui.ui.immersive.shell.immersiveTopContentPadding+import com.music.spotui.ui.navigation.Routes+import com.music.spotui.ui.navigation.TabReselect+import com.music.spotui.ui.navigation.albumRoute+import com.music.spotui.ui.navigation.artistRoute+import com.music.spotui.ui.navigation.categoryRoute+import com.music.spotui.ui.navigation.playlistRoute+import com.music.spotui.ui.navigation.profileRoute+import com.music.spotui.ui.navigation.showRoute+import com.music.spotui.ui.screens.SearchFilter+import com.music.spotui.ui.viewmodel.SearchViewModel+import kotlinx.coroutines.delay+import kotlinx.coroutines.launch++/**+ * Search in the Immersive look: the page's large title over a sticky search field and filter+ * pills; the category tiles and the recent searches while nothing is typed; with a query, the+ * top result then songs, artists, albums, playlists and podcasts as sections. The view model,+ * actions, recents, suggestions and sheets are those of the Classic Search screen.+ */+@OptIn(ExperimentalFoundationApi::class)+@Composable+fun ImmersiveSearchScreen(navController: NavController) {+ val vm: SearchViewModel = viewModel()+ val results by vm.results.collectAsState()+ val data = (results as? Response.Success)?.data ?: SearchResults()+ val loading = results is Response.Loading+ val failed = results is Response.Error+ val context = LocalContext.current+ val text = vm.query+ val filter = vm.filter++ // Recents are the items opened from results, not the typed queries, and show only once the+ // field is focused.+ var searchFocused by remember { mutableStateOf(false) }+ var recents by remember { mutableStateOf(loadRecents(context)) }+ var menuSong by remember { mutableStateOf<SongsModel?>(null) }+ menuSong?.let { sel ->+ ImmersiveSongOptionsSheet(song = sel, navController = navController, context = context, onDismiss = { menuSong = null })+ }+ val recordRecent: (RecentItem) -> Unit = { item ->+ addRecentItem(context, item)+ recents = loadRecents(context)+ }++ // Re-tapping the Search tab focuses the field and scrolls to the top; no query is re-run.+ val listState = rememberLazyListState()+ val fieldFocus = remember { FocusRequester() }+ LaunchedEffect(Unit) {+ TabReselect.search.collect {+ runCatching { fieldFocus.requestFocus() }+ if (listState.firstVisibleItemIndex != 0 || listState.firstVisibleItemScrollOffset != 0) {+ listState.animateScrollToItem(0)+ }+ }+ }++ val profiles by produceState(emptyList<MediaCard>(), text, filter) {+ value = emptyList()+ if (filter != SearchFilter.Profiles || text.isBlank()) return@produceState+ delay(250)+ value = runCatching { MyspotiRuntime.api.search.users(text.trim(), limit = 30).items }.getOrDefault(emptyList())+ }+ val suggestions by produceState(emptyList<String>(), text) {+ value = emptyList()+ if (text.isBlank()) return@produceState+ delay(300)+ value = runCatching { MyspotiRuntime.api.search.suggestions(text.trim(), 6) }.getOrDefault(emptyList())+ .filter { !it.equals(text.trim(), ignoreCase = true) }+ }+ val tiles = rememberBrowseTiles()++ val title = stringResource(R.string.navigationbar_musicappitems_search_title)+ val playSong: (SongsModel) -> Unit = { song ->+ // A radio from the tapped track (queue = this song + recommendations), not the list.+ vm.startRadioFromSong(song)+ SongPlayer.playSong(song.url, context)+ vm.updateSongState(song.coverUri, song.title, song.singer, true, song.id, 0, song.album)+ }++ Box(Modifier.fillMaxSize().background(Immersive.Page)) {+ LazyColumn(+ state = listState,+ contentPadding = PaddingValues(top = immersiveTopContentPadding(), bottom = Immersive.BottomChrome),+ modifier = Modifier.fillMaxSize().immersiveHazeSource().immersiveChromeScroll(),+ ) {+ immersiveLargeTitle(title)+ stickyHeader(key = "search:field") {+ Column(Modifier.fillMaxWidth().background(Immersive.Page).padding(top = 4.dp, bottom = 6.dp)) {+ ImmersiveSearchField(+ query = text,+ onQueryChange = { vm.search(it) },+ onSubmit = { vm.search(text) },+ focusRequester = fieldFocus,+ placeholder = stringResource(R.string.search_header_field_hint),+ modifier = Modifier+ .padding(horizontal = Immersive.Gutter)+ .onFocusChanged { searchFocused = it.hasFocus },+ )+ if (text.isNotBlank()) {+ ImmersiveChipRow {+ val filters = SearchFilter.entries.filter { it != SearchFilter.Podcasts || Features.PODCASTS }+ filters.forEach { f ->+ val on = f == filter+ ImmersiveChip(stringResource(f.label), selected = on) {+ vm.filter = if (on && f != SearchFilter.Top) SearchFilter.Top else f+ }+ }+ }+ }+ }+ }++ if (text.isBlank()) {+ if (searchFocused && recents.isNotEmpty()) {+ recentSearches(+ recents = recents,+ onOpen = { item -> openRecent(item, navController, vm, context) },+ onRemove = {+ removeRecentItem(context, it)+ recents = loadRecents(context)+ },+ onClear = {+ clearRecentItems(context)+ recents = emptyList()+ // The account's own list too, so other devices forget them as well.+ val runtime = MyspotiRuntime+ runtime.scope.launch { runCatching { runtime.api.search.clearRecent() } }+ },+ )+ } else {+ item(key = "search:browse-header") { SectionHeader(stringResource(R.string.browse_all)) }+ items(tiles.chunked(2), key = { row -> "browse:" + row.first().key }) { row ->+ BrowseTileRow(row = row, columns = 2) { tile ->+ // A genre opens a catalogue (a page of curated playlists), not a keyword search.+ if (tile.key == ImmersiveNewReleasesGenre) navController.navigate(Routes.NewReleases.route)+ else navController.navigate(categoryRoute(tile.key, tile.title))+ }+ }+ }+ } else {+ // The completions for what is typed: one tap searches it.+ if (suggestions.isNotEmpty()) {+ items(suggestions, key = { "suggest:$it" }) { term ->+ SuggestionRow(term) { vm.search(term) }+ }+ }+ searchResults(+ data = data,+ filter = filter,+ profiles = profiles,+ text = text,+ loading = loading,+ failed = failed,+ onRetry = { vm.retry() },+ currentSongId = vm.currentSongId.value,+ playing = Graph.currentSongState.playingState.value,+ onSong = { song -> recordRecent(song.toRecentItem()); playSong(song) },+ onSongMore = { menuSong = it },+ onArtist = { artist ->+ recordRecent(RecentItem(type = "artist", key = artist.id.ifBlank { artist.name }, name = artist.name, image = artist.coverUri))+ navController.navigate(artistRoute(artist.name, artist.id))+ },+ onAlbum = { album ->+ recordRecent(RecentItem(type = "album", key = album.spotifyId.ifBlank { album.name }, name = album.name, singer = album.artists, image = album.coverUri))+ navController.navigate(albumRoute(album.name, album.artists, album.spotifyId))+ },+ onPlaylist = { playlist ->+ recordRecent(RecentItem(type = "playlist", key = playlist.spotifyId, name = playlist.name, singer = playlist.subtitle, image = playlist.coverUri))+ navController.navigate(playlistRoute(playlist.spotifyId, playlist.name))+ },+ onShow = { show ->+ recordRecent(RecentItem(type = "show", key = show.id, name = show.name, singer = show.publisher, image = show.coverUri))+ navController.navigate(showRoute(show.id, show.name))+ },+ onProfile = { card ->+ navController.navigate(profileRoute(card.uri.substringAfterLast(':'), card.title))+ },+ )+ }+ }+ ImmersiveTopBar(title, listState)+ }+}++private fun loadRecents(context: Context): List<RecentItem> =+ getRecentItems(context).filter { Features.PODCASTS || it.type != "show" }++/** Maps a tapped search-result song to a persisted recent item. */+private fun SongsModel.toRecentItem() = RecentItem(+ type = "song",+ key = spotifyTrackId.ifBlank { url },+ name = title,+ singer = singer,+ image = coverUri,+ songId = id,+ songAlbum = album,+ songUrl = url,+ spotifyTrackId = spotifyTrackId,+ explicit = explicit,+ durationMs = durationMs,+)++/** Replays a recent song or opens its album, artist, show or playlist, as the Classic screen does. */+private fun openRecent(item: RecentItem, navController: NavController, vm: SearchViewModel, context: Context) {+ when (item.type) {+ "song" -> {+ val songUrl = item.songUrl.ifBlank {+ SongPlayer.buildSpotifyPlayQuery(item.spotifyTrackId, item.name, item.singer)+ }.let { savedUrl ->+ if (item.spotifyTrackId.isNotBlank() && !savedUrl.startsWith("spotify:track:")) {+ SongPlayer.buildSpotifyPlayQuery(item.spotifyTrackId, item.name, item.singer)+ } else {+ savedUrl+ }+ }+ val song = SongsModel(+ item.songId, item.name, item.songAlbum, item.singer,+ item.image, songUrl, item.spotifyTrackId,+ explicit = item.explicit,+ durationMs = item.durationMs,+ )+ vm.startRadioFromSong(song)+ SongPlayer.playSong(song.url, context)+ vm.updateSongState(song.coverUri, song.title, song.singer, true, song.id, 0, song.album)+ }+ "artist" -> navController.navigate(artistRoute(item.name, item.key.takeIf { it != item.name }.orEmpty()))+ "album" -> navController.navigate(albumRoute(item.name, item.singer, item.key.takeIf { it != item.name }.orEmpty()))+ "show" -> navController.navigate(showRoute(item.key, item.name))+ "playlist" -> navController.navigate(playlistRoute(item.key, item.name))+ }+}++/** The recent searches: a heading with "Clear", then a row per item opened. */+private fun LazyListScope.recentSearches(+ recents: List<RecentItem>,+ onOpen: (RecentItem) -> Unit,+ onRemove: (RecentItem) -> Unit,+ onClear: () -> Unit,+) {+ item(key = "recent:header") {+ Row(+ modifier = Modifier.fillMaxWidth().padding(horizontal = Immersive.Gutter, vertical = 10.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Text(+ text = stringResource(R.string.assisted_curation_search_search_history_title),+ style = Immersive.Title,+ modifier = Modifier.weight(1f),+ )+ Text(+ text = stringResource(R.string.chat_content_picker_clear_recent_searches),+ style = Immersive.Subhead.copy(color = Immersive.Accent, fontWeight = FontWeight.Medium),+ modifier = Modifier+ .clip(CircleShape)+ .clickable(role = Role.Button, onClick = onClear)+ .padding(horizontal = 10.dp, vertical = 4.dp),+ )+ }+ }+ items(recents.size, key = { "recent:${recents[it].type}:${recents[it].key}" }) { i ->+ val item = recents[i]+ val subtitle = when (item.type) {+ "song" -> stringResource(R.string.assisted_curation_search_song) + " • ${item.singer}"+ "artist" -> stringResource(R.string.artist_subtitle)+ "album" -> stringResource(R.string.album) + " • ${item.singer}"+ "show" -> stringResource(R.string.album_type_podcast) + (if (item.singer.isNotBlank()) " • ${item.singer}" else "")+ "playlist" -> stringResource(R.string.assisted_curation_search_playlist) + (if (item.singer.isNotBlank()) " • ${item.singer}" else "")+ else -> ""+ }+ ImmersiveListRow(+ title = item.name,+ subtitle = subtitle,+ imageUrl = item.image,+ round = item.type == "artist",+ onClick = { onOpen(item) },+ trailing = {+ Icon(+ imageVector = Icons.Rounded.Close,+ contentDescription = stringResource(R.string.aligned_curation_first_save_default_row_remove_action_description),+ tint = Immersive.TextSecondary,+ modifier = Modifier+ .size(32.dp)+ .clip(CircleShape)+ .clickable(role = Role.Button) { onRemove(item) }+ .padding(6.dp),+ )+ },+ )+ }+}++/** What the engine would complete the half-typed query to: tap to search it. */+@Composable+private fun SuggestionRow(term: String, onClick: () -> Unit) {+ Row(+ modifier = Modifier+ .fillMaxWidth()+ .clickable(role = Role.Button, onClick = onClick)+ .padding(horizontal = Immersive.Gutter, vertical = 10.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Icon(Icons.Rounded.Search, contentDescription = null, tint = Immersive.TextSecondary, modifier = Modifier.size(22.dp))+ Spacer(Modifier.width(16.dp))+ Text(text = term, style = Immersive.Body, maxLines = 1, overflow = TextOverflow.Ellipsis)+ }+}++/** A hairline between rows of a section, starting clear of the cover. */+@Composable+private fun RowDivider() {+ Box(+ Modifier+ .fillMaxWidth()+ .padding(start = ImmersiveRowDividerInset)+ .height(0.5.dp)+ .background(Immersive.Separator),+ )+}++/**+ * The results for the typed query: with Top, the top result then a section per kind; with one+ * kind picked, that kind's rows alone. Loading, nothing found and a failure each say what they+ * are (never an empty page).+ */+private fun LazyListScope.searchResults(+ data: SearchResults,+ filter: SearchFilter,+ profiles: List<MediaCard>,+ text: String,+ loading: Boolean,+ failed: Boolean,+ onRetry: () -> Unit,+ currentSongId: Int,+ playing: Boolean,+ onSong: (SongsModel) -> Unit,+ onSongMore: (SongsModel) -> Unit,+ onArtist: (ArtistsModel) -> Unit,+ onAlbum: (AlbumsModel) -> Unit,+ onPlaylist: (LibraryEntry) -> Unit,+ onShow: (PodcastModel) -> Unit,+ onProfile: (MediaCard) -> Unit,+) {+ val top = filter == SearchFilter.Top+ val songs = if (top || filter == SearchFilter.Songs) data.songs else emptyList()+ val artists = if (top || filter == SearchFilter.Artists) data.artists else emptyList()+ val albums = if (top || filter == SearchFilter.Albums) data.albums else emptyList()+ val playlists = if (top || filter == SearchFilter.Playlists) data.playlists else emptyList()+ val podcasts = Features.PODCASTS && (top || filter == SearchFilter.Podcasts)+ val shows = if (podcasts) data.shows else emptyList()+ val episodes = if (podcasts) data.episodes else emptyList()+ val sectioned = top++ if (filter != SearchFilter.Profiles &&+ songs.isEmpty() && artists.isEmpty() && albums.isEmpty() && playlists.isEmpty() && shows.isEmpty() && episodes.isEmpty()+ ) {+ when {+ loading -> immersiveSongListSkeleton(keyPrefix = "skeleton:search")+ failed -> item(key = "search:failed") {+ ImmersiveMessageState(+ message = stringResource(R.string.search_failed),+ actionLabel = stringResource(R.string.home_retry),+ onAction = onRetry,+ )+ }+ else -> item(key = "search:empty") {+ ImmersiveMessageState(stringResource(R.string.assisted_curation_search_empty_view_no_result_title, text.trim()))+ }+ }+ return+ }++ if (filter == SearchFilter.Profiles) {+ items(profiles.size, key = { "profile:${profiles[it].uri}" }) { i ->+ val card = profiles[i]+ ImmersiveListRow(+ title = card.title,+ subtitle = stringResource(R.string.recently_played_user_profile),+ imageUrl = card.images.firstOrNull()?.url,+ round = true,+ onClick = { onProfile(card) },+ )+ }+ return+ }++ // The All response carries its best song as a promoted card.+ if (top && songs.isNotEmpty()) {+ item(key = "search:top-result") {+ TopResultCard(+ song = songs.first(),+ onPlay = { onSong(songs.first()) },+ onMore = { onSongMore(songs.first()) },+ )+ }+ }+ fun title(res: Int): @Composable () -> String = { stringResource(res) }+ section("songs", sectioned, title(R.string.assisted_curation_search_filter_songs), songs.size) { range ->+ items(range.count(), key = { "song:${songs[range.first + it].id}:${range.first + it}" }) { n ->+ val song = songs[range.first + n]+ SongResultRow(song, currentSongId, playing, onClick = { onSong(song) }, onMore = { onSongMore(song) })+ if (n < range.count() - 1) RowDivider()+ }+ }+ section("artists", sectioned, title(R.string.assisted_curation_search_filter_artists), artists.size) { range ->+ items(range.count(), key = { "artist:${artists[range.first + it].id}:${range.first + it}" }) { n ->+ val artist = artists[range.first + n]+ ImmersiveListRow(+ title = artist.name,+ subtitle = stringResource(R.string.artist_subtitle),+ imageUrl = artist.coverUri,+ round = true,+ onClick = { onArtist(artist) },+ )+ if (n < range.count() - 1) RowDivider()+ }+ }+ section("albums", sectioned, title(R.string.assisted_curation_search_filter_albums), albums.size) { range ->+ items(range.count(), key = { "album:${albums[range.first + it].spotifyId}:${range.first + it}" }) { n ->+ val album = albums[range.first + n]+ ImmersiveListRow(+ title = album.name,+ subtitle = stringResource(R.string.album) + " • ${album.artists}",+ imageUrl = album.coverUri,+ round = false,+ onClick = { onAlbum(album) },+ )+ if (n < range.count() - 1) RowDivider()+ }+ }+ section("playlists", sectioned, title(R.string.assisted_curation_search_filter_playlists), playlists.size) { range ->+ items(range.count(), key = { "playlist:${playlists[range.first + it].spotifyId}:${range.first + it}" }) { n ->+ val playlist = playlists[range.first + n]+ ImmersiveListRow(+ title = playlist.name,+ subtitle = stringResource(R.string.assisted_curation_search_playlist) ++ (if (playlist.subtitle.isNotBlank()) " • ${playlist.subtitle}" else ""),+ imageUrl = playlist.coverUri,+ round = false,+ onClick = { onPlaylist(playlist) },+ )+ if (n < range.count() - 1) RowDivider()+ }+ }+ // Podcasts: shows (open their page) then individual episodes (play).+ section("shows", sectioned, title(R.string.assisted_curation_search_filter_podcasts), shows.size) { range ->+ items(range.count(), key = { "show:${shows[range.first + it].id}:${range.first + it}" }) { n ->+ val show = shows[range.first + n]+ ImmersiveListRow(+ title = show.name,+ subtitle = stringResource(R.string.album_type_podcast) + (if (show.publisher.isNotBlank()) " • ${show.publisher}" else ""),+ imageUrl = show.coverUri,+ round = false,+ onClick = { onShow(show) },+ )+ if (n < range.count() - 1) RowDivider()+ }+ }+ section("episodes", sectioned, title(R.string.assisted_curation_search_filter_episodes), episodes.size) { range ->+ items(range.count(), key = { "episode:${episodes[range.first + it].id}:${range.first + it}" }) { n ->+ val ep = episodes[range.first + n]+ SongResultRow(ep, currentSongId, playing, onClick = { onSong(ep) }, onMore = { onSongMore(ep) })+ if (n < range.count() - 1) RowDivider()+ }+ }+ // What extensions add for this search (search.provide), under Spotify's results.+ if (filter != SearchFilter.Profiles && text.isNotBlank()) item(key = "search:extensions") {+ com.music.spotui.extensions.ExtensionBlocks(+ app.myspoti.extensions.Hook.SEARCH, app.myspoti.extensions.Surface.SEARCH,+ kotlinx.serialization.json.buildJsonObject { put("query", kotlinx.serialization.json.JsonPrimitive(text.trim())) }.toString(),+ delayMs = 400,+ )+ }+}++/** A section's heading (when the page is sectioned) and its rows; nothing when it has none. */+private fun LazyListScope.section(+ id: String,+ titled: Boolean,+ title: @Composable () -> String,+ count: Int,+ rows: LazyListScope.(IntRange) -> Unit,+) {+ if (count == 0) return+ if (titled) item(key = "section:$id") { SectionHeader(title()) }+ rows(0 until count)+}++/** A song hit: the shared song row, swipe-to-queue as in the Classic list. */+@Composable+private fun SongResultRow(+ song: SongsModel,+ currentSongId: Int,+ playing: Boolean,+ onClick: () -> Unit,+ onMore: () -> Unit,+) {+ val current = song.id == currentSongId+ SwipeToQueue(song) {+ ImmersiveSongRow(+ song = song,+ playing = current && playing,+ current = current,+ onClick = onClick,+ onMore = onMore,+ modifier = Modifier.background(Immersive.Page),+ showAlbum = true,+ )+ }+}++/** The best song for the query, promoted: a big cover, the title, and Play / more. */+@Composable+private fun TopResultCard(song: SongsModel, onPlay: () -> Unit, onMore: () -> Unit) {+ Column(+ modifier = Modifier+ .fillMaxWidth()+ .padding(horizontal = Immersive.Gutter)+ .padding(top = 18.dp, bottom = 8.dp),+ ) {+ Text(text = stringResource(R.string.immersive_screens_top_result), style = Immersive.Title)+ Spacer(Modifier.height(10.dp))+ Row(+ verticalAlignment = Alignment.CenterVertically,+ modifier = Modifier.immersiveClickable(onClick = onPlay, onLongClick = onMore),+ ) {+ ImmersiveCover(song.coverUri, Modifier.size(72.dp), Immersive.CoverMedium)+ Spacer(Modifier.width(14.dp))+ Column(Modifier.weight(1f)) {+ Text(text = song.title, style = Immersive.Headline, maxLines = 2, overflow = TextOverflow.Ellipsis)+ Spacer(Modifier.height(4.dp))+ Text(text = song.singer, style = Immersive.Subhead, maxLines = 1, overflow = TextOverflow.Ellipsis)+ }+ ImmersiveMoreButton(onClick = onMore, tint = Immersive.Text, iconSize = 24.dp)+ }+ Spacer(Modifier.height(12.dp))+ Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {+ ImmersiveButton(+ text = stringResource(R.string.immersive_shell_play),+ onClick = onPlay,+ icon = Icons.Rounded.PlayArrow,+ )+ }+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/sheets/ImmersiveGlassSheet.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/sheets/ImmersiveGlassSheet.ktnew file mode 100644index 00000000..e6094391--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/sheets/ImmersiveGlassSheet.kt@@ -0,0 +1,63 @@+package com.music.spotui.ui.immersive.sheets++import androidx.compose.foundation.LocalOverscrollFactory+import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.ColumnScope+import androidx.compose.foundation.layout.WindowInsets+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.material3.ExperimentalMaterial3Api+import androidx.compose.material3.ModalBottomSheet+import androidx.compose.material3.SheetState+import androidx.compose.material3.rememberModalBottomSheetState+import androidx.compose.runtime.Composable+import androidx.compose.runtime.CompositionLocalProvider+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.unit.dp+import com.music.spotui.ui.immersive.Immersive+import com.music.spotui.ui.immersive.components.rememberImmersiveOverscrollFactory+import com.music.spotui.ui.immersive.shell.immersiveGlassSurface++/**+ * A bottom sheet on glass: [ImmersiveSheetShape] (rounded top) drawn with the shared+ * `immersiveGlassSurface`, so it takes whatever the glass looks like, with the grab handle on it.+ * The sheet opens and settles on Material's own spring-anchored drag. The content brings its own+ * rows and insets (the Classic sheets' contents work unchanged on it).+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun ImmersiveGlassSheet(+ onDismiss: () -> Unit,+ sheetState: SheetState = rememberModalBottomSheetState(),+ content: @Composable ColumnScope.() -> Unit,+) {+ ModalBottomSheet(+ onDismissRequest = onDismiss,+ sheetState = sheetState,+ containerColor = Color.Transparent,+ tonalElevation = 0.dp,+ dragHandle = null,+ contentWindowInsets = { WindowInsets(0, 0, 0, 0) },+ ) {+ CompositionLocalProvider(LocalOverscrollFactory provides rememberImmersiveOverscrollFactory()) {+ Column(Modifier.fillMaxWidth().immersiveGlassSurface(ImmersiveSheetShape)) {+ Box(Modifier.fillMaxWidth().padding(top = 8.dp, bottom = 6.dp), contentAlignment = Alignment.Center) {+ Box(+ Modifier+ .size(width = 34.dp, height = 4.dp)+ .clip(CircleShape)+ .background(Immersive.Text.copy(alpha = 0.35f)),+ )+ }+ content()+ }+ }+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/sheets/ImmersiveSheet.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/sheets/ImmersiveSheet.ktnew file mode 100644index 00000000..b494b0e1--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/sheets/ImmersiveSheet.kt@@ -0,0 +1,448 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * app/src/main/java/com/music/bitchord/ui/components/SongActionsSheet.kt (TintedSheet, ActionRow,+ * SheetTrackHeader, SheetHeading, GroupSeparator) and ArtworkBackdrop.kt at edc1e6f.+ * Modified for Myspoti, 2026-10.+ */+package com.music.spotui.ui.immersive.sheets++import android.os.Build+import androidx.compose.animation.animateColorAsState+import androidx.compose.animation.core.snap+import androidx.compose.animation.core.tween+import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.ColumnScope+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.WindowInsets+import androidx.compose.foundation.layout.fillMaxHeight+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.heightIn+import androidx.compose.foundation.layout.navigationBarsPadding+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.LocalOverscrollFactory+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.verticalScroll+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.rounded.Check+import androidx.compose.material3.CircularProgressIndicator+import androidx.compose.material3.ExperimentalMaterial3Api+import androidx.compose.material3.HorizontalDivider+import androidx.compose.material3.Icon+import androidx.compose.material3.ModalBottomSheet+import androidx.compose.material3.Text+import androidx.compose.material3.rememberModalBottomSheetState+import androidx.compose.runtime.Composable+import androidx.compose.runtime.CompositionLocalProvider+import androidx.compose.runtime.Immutable+import androidx.compose.runtime.compositionLocalOf+import androidx.compose.runtime.getValue+import androidx.compose.runtime.remember+import androidx.compose.runtime.staticCompositionLocalOf+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.BlurredEdgeTreatment+import androidx.compose.ui.draw.alpha+import androidx.compose.ui.draw.blur+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.Brush+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.graphics.toArgb+import androidx.compose.ui.graphics.vector.ImageVector+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.platform.LocalConfiguration+import androidx.compose.ui.semantics.Role+import androidx.compose.ui.text.TextStyle+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import androidx.core.graphics.ColorUtils+import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi+import com.bumptech.glide.integration.compose.GlideImage+import com.music.spotui.ui.components.spotifyImageUrl+import com.music.spotui.ui.immersive.Immersive+import com.music.spotui.ui.immersive.components.ImmersiveCover+import com.music.spotui.ui.immersive.components.ImmersiveSongTitle+import com.music.spotui.ui.immersive.components.immersiveClickable+import com.music.spotui.ui.immersive.components.rememberImmersiveOverscrollFactory+import com.music.spotui.ui.look.rememberArtworkColors+import com.music.spotui.ui.look.rememberReduceMotion++/** The sheets' top corners (BitChord's `SHEET_SHAPE`). */+val ImmersiveSheetShape = RoundedCornerShape(topStart = 28.dp, topEnd = 28.dp)++/** The ground of a sheet that is not about one cover (BitChord's player drawer, without its blur). */+private val FlatSheetColor = Color(0xFF121212)++/** How long a sheet takes to warm into its cover's colours the first time it is seen. */+private const val TINT_FADE_MS = 400++/** What a sheet is painted in: [background] under everything, [accent] for values, ticks and highlights. */+@Immutable+data class ImmersiveSheetTint(val background: Color, val accent: Color)++/** The tint of the sheet being drawn, read by the rows so they take the cover's accent. */+val LocalImmersiveSheetTint = compositionLocalOf { ImmersiveSheetTint(FlatSheetColor, Immersive.Accent) }++/** How a row is drawn: the sheet's full-width list, or the compact rows of a held item's popup. */+enum class ImmersiveRowStyle { Sheet, Menu }++/** Set by whichever surface the rows are drawn on; see [ImmersiveHeldContextMenu]. */+val LocalImmersiveRowStyle = staticCompositionLocalOf { ImmersiveRowStyle.Sheet }++/**+ * A cover's colours made into a sheet tint: a deep wash of its dominant colour for the ground+ * and a brightened version for the accent. Without a cover ([imageUrl] null) the flat ground and+ * Myspoti's own accent. The first sight of a cover warms in; a known one is right on the first+ * frame, and "reduce motion" turns the fade into a cut.+ */+@Composable+fun rememberImmersiveSheetTint(imageUrl: String?): ImmersiveSheetTint {+ val hasCover = !imageUrl.isNullOrBlank()+ val colors = rememberArtworkColors(if (hasCover) spotifyImageUrl(imageUrl) ?: imageUrl else null).colors+ val seed = colors.firstOrNull() ?: Immersive.Accent+ val target = remember(seed, hasCover) {+ if (!hasCover) return@remember ImmersiveSheetTint(FlatSheetColor, Immersive.Accent)+ val hsl = FloatArray(3)+ ColorUtils.colorToHSL(seed.toArgb(), hsl)+ val ground = floatArrayOf(hsl[0], hsl[1].coerceIn(0.25f, 0.6f), 0.14f)+ val accent = floatArrayOf(hsl[0], hsl[1].coerceIn(0.55f, 1f), 0.68f)+ ImmersiveSheetTint(+ Color(ColorUtils.HSLToColor(ground)),+ Color(ColorUtils.HSLToColor(accent)),+ )+ }+ val spec = if (rememberReduceMotion()) snap<Color>() else tween(TINT_FADE_MS)+ val background by animateColorAsState(target.background, spec, label = "sheetTintBackground")+ val accent by animateColorAsState(target.accent, spec, label = "sheetTintAccent")+ return ImmersiveSheetTint(background, accent)+}++/**+ * The bottom sheet of the Immersive look. A Material modal sheet, so it drags with the finger,+ * flings away with velocity and settles on the usual dismissal thresholds, but painted here:+ * with an [imageUrl] it wears that cover's colours (the cover blurred across the top, dissolving+ * into the tint, as BitChord's song sheet does), without one a flat dark ground.+ *+ * The rows scroll inside, capped at [maxHeightFraction] of the screen (or exactly that when+ * [expand] is set, for lists that bring their own scrolling), with the iOS rubber band.+ * [content] is a column; use [ImmersiveSheetRow] and friends for what goes in it.+ */+@OptIn(ExperimentalMaterial3Api::class, ExperimentalGlideComposeApi::class)+@Composable+fun ImmersiveSheet(+ onDismiss: () -> Unit,+ modifier: Modifier = Modifier,+ imageUrl: String? = null,+ maxHeightFraction: Float = 0.85f,+ expand: Boolean = false,+ scrollable: Boolean = true,+ content: @Composable ColumnScope.() -> Unit,+) {+ val tint = rememberImmersiveSheetTint(imageUrl)+ val maxHeight = LocalConfiguration.current.screenHeightDp.dp * maxHeightFraction+ val canBlur = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S+ ModalBottomSheet(+ onDismissRequest = onDismiss,+ sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true),+ // The sheet paints its own ground, corners and handle: a transparent container has+ // nothing to clip or to hang a handle on, which is why they are drawn below.+ containerColor = Color.Transparent,+ tonalElevation = 0.dp,+ dragHandle = null,+ contentWindowInsets = { WindowInsets(0, 0, 0, 0) },+ ) {+ CompositionLocalProvider(+ LocalImmersiveSheetTint provides tint,+ LocalOverscrollFactory provides rememberImmersiveOverscrollFactory(),+ ) {+ Box(modifier.fillMaxWidth().clip(ImmersiveSheetShape)) {+ Box(Modifier.matchParentSize().background(tint.background)) {+ if (canBlur && !imageUrl.isNullOrBlank()) {+ GlideImage(+ model = spotifyImageUrl(imageUrl) ?: imageUrl,+ contentDescription = null,+ contentScale = ContentScale.Crop,+ modifier = Modifier+ .fillMaxWidth()+ .fillMaxHeight(WASH_FRACTION)+ // Overscaled so the blur's clamped edges never reach a visible one.+ .graphicsLayer { scaleX = 1.4f; scaleY = 1.4f }+ .blur(72.dp, BlurredEdgeTreatment.Unbounded),+ )+ }+ Box(+ Modifier.fillMaxSize().background(+ Brush.verticalGradient(+ 0f to tint.background.copy(alpha = 0.40f),+ 0.20f to tint.background.copy(alpha = 0.55f),+ 0.55f to tint.background.copy(alpha = 0.85f),+ WASH_FRACTION to tint.background,+ ),+ ),+ )+ }+ Column(+ Modifier+ .fillMaxWidth()+ .then(if (expand) Modifier.height(maxHeight) else Modifier.heightIn(max = maxHeight)),+ ) {+ // Drawn rather than taken from BottomSheetDefaults, whose handle carries 22 dp of+ // padding each side. Outside the scrolling rows so it stays put as a grab target.+ Box(Modifier.fillMaxWidth().padding(top = 8.dp, bottom = 4.dp), contentAlignment = Alignment.Center) {+ Box(+ Modifier+ .size(width = 34.dp, height = 4.dp)+ .clip(CircleShape)+ .background(Immersive.Text.copy(alpha = 0.35f)),+ )+ }+ Column(+ Modifier+ .fillMaxWidth()+ .weight(1f, fill = expand)+ .then(if (scrollable) Modifier.verticalScroll(rememberScrollState()) else Modifier)+ .navigationBarsPadding(),+ content = content,+ )+ }+ }+ }+ }+}++/** How far down a tinted sheet the blurred cover reaches. */+private const val WASH_FRACTION = 0.75f++/** The sheet's heading: [title] in the page-title face, an optional quiet [subtitle] under it. */+@Composable+fun ImmersiveSheetTitle(+ title: String,+ modifier: Modifier = Modifier,+ subtitle: String? = null,+ subtitleColor: Color = Immersive.TextSecondary,+ trailing: (@Composable () -> Unit)? = null,+) {+ Row(+ modifier.fillMaxWidth().padding(horizontal = 22.dp, vertical = 10.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Column(Modifier.weight(1f)) {+ Text(title, style = Immersive.Title, maxLines = 1, overflow = TextOverflow.Ellipsis)+ if (!subtitle.isNullOrBlank()) {+ Text(subtitle, style = Immersive.Subhead.copy(color = subtitleColor), maxLines = 2, overflow = TextOverflow.Ellipsis)+ }+ }+ trailing?.invoke()+ }+}++/**+ * What a sheet is about, at its head: a 52 dp cover, the [title] (with the explicit badge) and a+ * [subtitle]. BitChord's `SheetTrackHeader`; the cover is a rounded square, or a circle for artists.+ */+@Composable+fun ImmersiveSheetHeader(+ title: String,+ subtitle: String?,+ coverUrl: String?,+ modifier: Modifier = Modifier,+ explicit: Boolean = false,+ round: Boolean = false,+) {+ Row(+ modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 10.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ ImmersiveCover(coverUrl, Modifier.size(52.dp), if (round) CircleShape else RoundedCornerShape(8.dp))+ Spacer(Modifier.width(14.dp))+ Column(Modifier.weight(1f)) {+ ImmersiveSongTitle(title, explicit, Immersive.BodyStrong, Immersive.Text)+ if (!subtitle.isNullOrBlank()) {+ Text(subtitle, style = Immersive.Subhead, maxLines = 1, overflow = TextOverflow.Ellipsis)+ }+ }+ }+}++/** The heading over a sheet's second half. */+@Composable+fun ImmersiveSheetHeading(text: String, modifier: Modifier = Modifier) {+ Text(+ text = text.uppercase(),+ style = Immersive.Caption,+ modifier = modifier.padding(start = 22.dp, end = 22.dp, top = 16.dp, bottom = 4.dp),+ )+}++/** The hairline under a header. */+@Composable+fun ImmersiveSheetDivider(modifier: Modifier = Modifier) {+ HorizontalDivider(modifier, thickness = 0.5.dp, color = Immersive.Separator)+}++/**+ * The break between groups of rows: a hairline on the sheet, and on the popup the thicker band+ * iOS-style context menus use (a hairline between rows 44 dp apart reads as a row border).+ */+@Composable+fun ImmersiveGroupSeparator() {+ if (LocalImmersiveRowStyle.current == ImmersiveRowStyle.Menu) {+ Box(Modifier.fillMaxWidth().height(6.dp).background(Immersive.Separator))+ } else {+ HorizontalDivider(Modifier.padding(vertical = 6.dp), thickness = 0.5.dp, color = Immersive.Separator)+ }+}++/**+ * One line of a sheet's menu (BitChord's `ActionRow`): glyph, [label] and an optional [value] on+ * the right in the sheet's accent. [tint] is for rows whose glyph carries state (a filled heart);+ * [leading] replaces the glyph (a download badge). In the popup of a held item the label leads and+ * the glyph sits at the far edge, as in context menus. Press shrinks it, no ripple.+ */+@Composable+fun ImmersiveSheetRow(+ icon: ImageVector?,+ label: String,+ modifier: Modifier = Modifier,+ value: String? = null,+ tint: Color? = null,+ accent: Color = LocalImmersiveSheetTint.current.accent,+ enabled: Boolean = true,+ leading: (@Composable () -> Unit)? = null,+ onClick: () -> Unit,+) {+ val menu = LocalImmersiveRowStyle.current == ImmersiveRowStyle.Menu+ val alpha = if (enabled) 1f else 0.4f+ val glyph: @Composable () -> Unit = {+ Box(Modifier.size(if (menu) 20.dp else 24.dp), contentAlignment = Alignment.Center) {+ when {+ leading != null -> leading()+ icon != null -> Icon(+ icon, contentDescription = null,+ tint = (tint ?: Immersive.Text).copy(alpha = alpha),+ modifier = Modifier.size(if (menu) 20.dp else 22.dp),+ )+ }+ }+ }+ Row(+ modifier = modifier+ .fillMaxWidth()+ .immersiveClickable(onClick = onClick, enabled = enabled, pressedScale = 0.98f)+ .then(+ if (menu) Modifier.heightIn(min = 46.dp).padding(horizontal = 18.dp, vertical = 11.dp)+ else Modifier.padding(horizontal = 22.dp, vertical = 15.dp),+ ),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ if (!menu) {+ glyph()+ Spacer(Modifier.width(18.dp))+ }+ Text(+ text = label,+ style = Immersive.Body.copy(color = Immersive.Text.copy(alpha = alpha)),+ maxLines = if (menu) 2 else Int.MAX_VALUE,+ overflow = TextOverflow.Ellipsis,+ modifier = Modifier.weight(1f),+ )+ if (value != null) {+ Spacer(Modifier.width(12.dp))+ Text(value, style = Immersive.Body.copy(color = accent.copy(alpha = alpha)), maxLines = 1)+ }+ if (menu) {+ Spacer(Modifier.width(14.dp))+ glyph()+ }+ }+}++/** Stands in for a row whose place on the sheet is not decided yet: the label dimmed, a spinner. */+@Composable+fun ImmersiveSheetLoadingRow(icon: ImageVector, label: String) {+ val menu = LocalImmersiveRowStyle.current == ImmersiveRowStyle.Menu+ Row(+ Modifier+ .fillMaxWidth()+ .then(+ if (menu) Modifier.heightIn(min = 46.dp).padding(horizontal = 18.dp, vertical = 11.dp)+ else Modifier.padding(horizontal = 22.dp, vertical = 15.dp),+ ),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Icon(icon, contentDescription = null, tint = Immersive.Text.copy(alpha = 0.4f), modifier = Modifier.size(22.dp))+ Spacer(Modifier.width(18.dp))+ Text(label, style = Immersive.Body.copy(color = Immersive.Text.copy(alpha = 0.4f)), modifier = Modifier.weight(1f))+ CircularProgressIndicator(color = Immersive.TextSecondary, strokeWidth = 2.dp, modifier = Modifier.size(16.dp))+ }+}++/**+ * A choice in a list: [label] (and an optional [detail]) with a tick in the sheet's accent when+ * [selected]. For the sleep timer, sort orders, quality pickers.+ */+@Composable+fun ImmersiveSheetOption(+ label: String,+ selected: Boolean,+ modifier: Modifier = Modifier,+ detail: String? = null,+ danger: Boolean = false,+ onClick: () -> Unit,+) {+ val accent = LocalImmersiveSheetTint.current.accent+ Row(+ modifier = modifier+ .fillMaxWidth()+ .immersiveClickable(onClick = onClick, pressedScale = 0.98f)+ .padding(horizontal = 22.dp, vertical = 15.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Column(Modifier.weight(1f)) {+ Text(label, style = Immersive.Body.copy(color = if (danger) Immersive.Accent else Immersive.Text))+ if (!detail.isNullOrBlank()) Text(detail, style = Immersive.Subhead)+ }+ if (selected) {+ Spacer(Modifier.width(12.dp))+ Icon(Icons.Rounded.Check, contentDescription = null, tint = accent, modifier = Modifier.size(22.dp))+ }+ }+}++/** The sheet's one wide action ("Done", "Add to playlist", "Create"): a filled pill, dimmed when disabled. */+@Composable+fun ImmersiveSheetButton(+ text: String,+ modifier: Modifier = Modifier,+ enabled: Boolean = true,+ onClick: () -> Unit,+) {+ Box(+ modifier = modifier+ .fillMaxWidth()+ .padding(horizontal = 22.dp)+ .alpha(if (enabled) 1f else 0.4f)+ .immersiveClickable(onClick = onClick, enabled = enabled, role = Role.Button)+ .clip(Immersive.Button)+ .background(Immersive.Text)+ .height(50.dp),+ contentAlignment = Alignment.Center,+ ) {+ Text(text, style = Immersive.BodyStrong.copy(color = Color.Black), maxLines = 1, overflow = TextOverflow.Ellipsis)+ }+}++/** A grey line of explanation or an empty state inside a sheet. */+@Composable+fun ImmersiveSheetNote(text: String, modifier: Modifier = Modifier, style: TextStyle = Immersive.Subhead) {+ Text(text, style = style, modifier = modifier.padding(horizontal = 22.dp, vertical = 14.dp))+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/sheets/ImmersiveSleepTimerSheet.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/sheets/ImmersiveSleepTimerSheet.ktnew file mode 100644index 00000000..e079daa7--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/sheets/ImmersiveSleepTimerSheet.kt@@ -0,0 +1,36 @@+package com.music.spotui.ui.immersive.sheets++import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.height+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import app.myspoti.engine.R+import com.music.spotui.di.SongPlayer++/**+ * The sleep timer of the Immersive look: the same choices and the same [SongPlayer.setSleepTimer]+ * call as the Classic [com.music.spotui.ui.components.SleepTimerSheet], in the Immersive sheet kit.+ */+@Composable+fun ImmersiveSleepTimerSheet(onDismiss: () -> Unit) {+ val active = SongPlayer.sleepEndsAt.value != null+ ImmersiveSheet(onDismiss = onDismiss) {+ ImmersiveSheetTitle(stringResource(R.string.context_menu_sleep_timer))+ val options = buildList {+ for (m in listOf(5, 10, 15, 30, 45)) add(stringResource(R.string.sleep_minutes, m) to m)+ add(stringResource(R.string.mute_chat_duration_one_hour) to 60)+ add(stringResource(R.string.context_menu_sleep_timer_end_of_track) to 0)+ }+ options.forEach { (label, minutes) ->+ ImmersiveSheetOption(label = label, selected = false) { SongPlayer.setSleepTimer(minutes); onDismiss() }+ }+ if (active) {+ ImmersiveSheetOption(+ label = stringResource(R.string.context_menu_sleep_timer_turn_off), selected = false, danger = true,+ ) { SongPlayer.setSleepTimer(null); onDismiss() }+ }+ Spacer(Modifier.height(12.dp))+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/sheets/ImmersiveSongOptionsSheet.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/sheets/ImmersiveSongOptionsSheet.ktnew file mode 100644index 00000000..20b8f488--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/sheets/ImmersiveSongOptionsSheet.kt@@ -0,0 +1,263 @@+package com.music.spotui.ui.immersive.sheets++import android.content.Context+import android.widget.Toast+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.background+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.height+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.automirrored.rounded.PlaylistAdd+import androidx.compose.material.icons.automirrored.rounded.PlaylistPlay+import androidx.compose.material.icons.automirrored.rounded.QueueMusic+import androidx.compose.material.icons.rounded.AddCircleOutline+import androidx.compose.material.icons.rounded.Album+import androidx.compose.material.icons.rounded.ArrowCircleDown+import androidx.compose.material.icons.rounded.Bedtime+import androidx.compose.material.icons.rounded.Block+import androidx.compose.material.icons.rounded.Bookmark+import androidx.compose.material.icons.rounded.Check+import androidx.compose.material.icons.rounded.DeleteOutline+import androidx.compose.material.icons.rounded.Info+import androidx.compose.material.icons.rounded.Person+import androidx.compose.material.icons.rounded.Radio+import androidx.compose.material.icons.rounded.Share+import androidx.compose.material.icons.rounded.Speed+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.produceState+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import androidx.navigation.NavController+import app.myspoti.engine.R+import com.music.spotui.data.entity.SongsModel+import com.music.spotui.di.Haptics+import com.music.spotui.di.SongPlayer+import com.music.spotui.ui.components.AddToPlaylistSheet+import com.music.spotui.ui.components.CreditsSheet+import com.music.spotui.ui.components.DownloadBadge+import com.music.spotui.ui.components.SavedInSheet+import com.music.spotui.ui.components.ShareTarget+import com.music.spotui.ui.immersive.sheets.ImmersiveSleepTimerSheet as SleepTimerSheet+import com.music.spotui.ui.components.SpeedSheet+import com.music.spotui.ui.components.SpotifyCode+import com.music.spotui.ui.immersive.Immersive+import com.music.spotui.ui.navigation.albumRoute+import kotlinx.coroutines.launch++/**+ * The track menu of the Immersive look: the same rows, order and actions as the Classic+ * [com.music.spotui.ui.components.SongOptionsSheet] (it calls the same player, offline and+ * extension code), drawn with the Immersive sheet kit and wearing the song's cover colours.+ * The pickers behind a row (playlists, sleep timer, credits, speed) are the shared sheets.+ */+@Composable+fun ImmersiveSongOptionsSheet(+ song: SongsModel,+ navController: NavController,+ context: Context,+ onDismiss: () -> Unit,+ nowPlaying: Boolean = false,+ onOpenQueue: (() -> Unit)? = null,+ onRemoveFromPlaylist: (() -> Unit)? = null,+ currentPlaylistId: String? = null,+) {+ val playerViewModel: com.music.spotui.ui.viewmodel.PlayerViewModel =+ androidx.lifecycle.viewmodel.compose.viewModel()+ val liked = com.music.spotui.di.rememberTrackSaved(song.spotifyTrackId)+ var showSavedIn by remember { mutableStateOf(false) }+ var showAddTo by remember { mutableStateOf(false) }+ var showSleep by remember { mutableStateOf(false) }+ var showCredits by remember { mutableStateOf(false) }+ var showSpeed by remember { mutableStateOf(false) }+ if (showCredits) { CreditsSheet(song = song, onDismiss = { showCredits = false; onDismiss() }); return }+ if (showSpeed) { SpeedSheet(onDismiss = { showSpeed = false; onDismiss() }); return }+ if (showSavedIn) { SavedInSheet(song = song, context = context, onDismiss = { showSavedIn = false; onDismiss() }); return }+ if (showAddTo) {+ AddToPlaylistSheet(song = song, context = context, onDismiss = { showAddTo = false; onDismiss() }, excludePlaylistId = currentPlaylistId)+ return+ }+ if (showSleep) { SleepTimerSheet(onDismiss = { showSleep = false; onDismiss() }); return }++ val hasId = song.spotifyTrackId.isNotBlank()+ val episodeKey = com.music.spotui.data.offline.episodeKeyOf(song)+ val downloadKey = episodeKey ?: song.spotifyTrackId+ fun toast(text: String) = Toast.makeText(context, text, Toast.LENGTH_SHORT).show()++ ImmersiveSheet(onDismiss = onDismiss, imageUrl = song.coverUri) {+ ImmersiveSheetHeader(title = song.title, subtitle = song.singer, coverUrl = song.coverUri)+ ImmersiveSheetDivider()++ ImmersiveSheetRow(+ icon = if (liked) null else Icons.Rounded.AddCircleOutline,+ label = stringResource(if (liked) R.string.collection_liked_songs_title else R.string.aligned_curation_context_menu_item_add_to_liked_songs),+ enabled = hasId,+ leading = if (liked) ({ LikedTick() }) else null,+ ) {+ SongPlayer.setTrackSaved(song.spotifyTrackId, !liked)+ toast(context.getString(if (liked) R.string.snackbar_removed_from_liked_songs else R.string.snackbar_added_to_liked_songs))+ onDismiss()+ }+ ImmersiveSheetRow(Icons.AutoMirrored.Rounded.PlaylistAdd, stringResource(R.string.context_menu_add_to_playlist), enabled = hasId) { showSavedIn = true }+ ImmersiveSheetRow(Icons.AutoMirrored.Rounded.PlaylistAdd, stringResource(R.string.context_menu_add_to_another_playlist), enabled = hasId) { showAddTo = true }+ if (onRemoveFromPlaylist != null) {+ ImmersiveSheetRow(Icons.Rounded.DeleteOutline, stringResource(R.string.context_menu_remove_from_playlist), enabled = hasId) {+ onDismiss()+ onRemoveFromPlaylist()+ }+ }+ if (!nowPlaying) {+ ImmersiveSheetRow(Icons.AutoMirrored.Rounded.PlaylistPlay, stringResource(R.string.context_menu_play_next), enabled = hasId) {+ playerViewModel.playNext(song)+ Haptics.confirm()+ toast(context.getString(R.string.context_menu_play_next))+ onDismiss()+ }+ ImmersiveSheetRow(Icons.AutoMirrored.Rounded.QueueMusic, stringResource(R.string.context_menu_add_to_queue), enabled = hasId) {+ playerViewModel.addToQueue(song)+ Haptics.confirm()+ toast(context.getString(R.string.snackbar_added_to_queue))+ onDismiss()+ }+ } else if (onOpenQueue != null) {+ ImmersiveSheetRow(Icons.AutoMirrored.Rounded.QueueMusic, stringResource(R.string.context_menu_go_to_queue)) {+ onDismiss()+ onOpenQueue()+ }+ }+ val offline = com.music.spotui.data.offline.OfflineStore.statusOf(downloadKey)+ when {+ offline == com.music.spotui.data.offline.OfflineStatus.Done -> ImmersiveSheetRow(+ null, stringResource(R.string.context_menu_undownload),+ leading = { DownloadBadge(offline, size = 22.dp) },+ ) {+ val gone = if (episodeKey != null) {+ com.music.spotui.data.offline.PodcastDownloader.remove(downloadKey)+ true+ } else com.music.spotui.data.offline.OfflineCollections.removeSong(downloadKey)+ toast(context.getString(if (gone) R.string.toast_undownload else R.string.download_kept_by_list))+ onDismiss()+ }+ offline == com.music.spotui.data.offline.OfflineStatus.Queued ||+ offline is com.music.spotui.data.offline.OfflineStatus.Downloading -> ImmersiveSheetRow(+ null, stringResource(R.string.download_cancel),+ leading = { DownloadBadge(offline, size = 22.dp) },+ ) {+ if (episodeKey != null) com.music.spotui.data.offline.PodcastDownloader.cancel(downloadKey)+ else com.music.spotui.data.offline.OfflineDownloader.cancel(downloadKey)+ onDismiss()+ }+ else -> ImmersiveSheetRow(+ Icons.Rounded.ArrowCircleDown, stringResource(R.string.context_menu_download),+ enabled = downloadKey.isNotBlank(),+ leading = if (offline != null) ({ DownloadBadge(offline, size = 22.dp) }) else null,+ ) {+ if (episodeKey != null) {+ com.music.spotui.data.offline.PodcastDownloader.enqueue(song)+ } else com.music.spotui.ui.components.DownloadAsk.start(context) { q ->+ com.music.spotui.data.offline.OfflineCollections.downloadSong(song, q)+ Haptics.confirm()+ toast(context.getString(R.string.download_notification_downloading))+ }+ onDismiss()+ }+ }+ ImmersiveSheetRow(Icons.Rounded.Radio, stringResource(R.string.context_menu_go_to_song_radio), enabled = hasId) {+ onDismiss()+ playerViewModel.goToSongRadio(song.spotifyTrackId, song.title,+ navigate = { route -> navController.navigate(route) },+ onFailed = { toast(context.getString(R.string.song_radio_failed)) })+ }+ ImmersiveSheetRow(Icons.Rounded.Album, stringResource(R.string.context_menu_browse_album), enabled = song.album.isNotBlank() || song.albumId.isNotBlank()) {+ onDismiss()+ navController.navigate(albumRoute(song.album, song.singer, song.albumId))+ }+ ImmersiveSheetRow(Icons.Rounded.Person, stringResource(R.string.context_menu_browse_artist), enabled = song.singer.isNotBlank()) {+ onDismiss()+ playerViewModel.goToArtist(song.spotifyTrackId, song.singer) { route -> navController.navigate(route) }+ }+ ImmersiveSheetRow(Icons.Rounded.Info, stringResource(R.string.track_credits), enabled = hasId) { showCredits = true }++ val trackUri = "spotify:track:${song.spotifyTrackId}"+ val excluded by produceState<Boolean?>(null, trackUri) {+ value = if (!hasId) null else runCatching { app.myspoti.host.android.MyspotiRuntime.api.extras.isExcludedFromTaste(listOf(trackUri)).single() }.getOrNull()+ }+ ImmersiveSheetRow(Icons.Rounded.Block, stringResource(if (excluded == true) R.string.include_taste else R.string.exclude_taste), enabled = hasId && excluded != null) {+ val exclude = excluded != true+ app.myspoti.host.android.MyspotiRuntime.scope.launch {+ runCatching { app.myspoti.host.android.MyspotiRuntime.api.extras.setExcludedFromTaste(trackUri, exclude) }+ }+ Haptics.confirm()+ onDismiss()+ }+ val artistBan by produceState<Pair<String, Boolean>?>(null, trackUri) {+ if (!hasId) return@produceState+ val api = app.myspoti.host.android.MyspotiRuntime.api+ value = runCatching {+ val artist = api.catalog.track(trackUri).artists.first().uri+ artist to api.extras.isArtistBanned(listOf(artist)).single()+ }.getOrNull()+ }+ ImmersiveSheetRow(Icons.Rounded.Block, stringResource(if (artistBan?.second == true) R.string.artist_unban else R.string.artist_ban), enabled = artistBan != null) {+ val (artist, banned) = artistBan ?: return@ImmersiveSheetRow+ app.myspoti.host.android.MyspotiRuntime.scope.launch {+ runCatching { app.myspoti.host.android.MyspotiRuntime.api.extras.setArtistBanned(artist, !banned) }+ }+ toast(context.getString(if (banned) R.string.artist_unbanned else R.string.artist_banned, song.singer.substringBefore(",").trim()))+ Haptics.confirm()+ onDismiss()+ }+ if (song.url.startsWith("episode:")) {+ val episodeUri = "spotify:episode:" + song.url.removePrefix("episode:")+ val saved by produceState<Boolean?>(null, episodeUri) {+ value = runCatching { app.myspoti.host.android.MyspotiRuntime.api.library.contains(listOf(episodeUri)).single() }.getOrNull()+ }+ ImmersiveSheetRow(Icons.Rounded.Bookmark, stringResource(if (saved == true) R.string.episode_unsave else R.string.episode_save), enabled = saved != null) {+ val save = saved != true+ app.myspoti.host.android.MyspotiRuntime.scope.launch {+ runCatching { app.myspoti.host.android.MyspotiRuntime.api.podcasts.setEpisodeSaved(episodeUri, save) }+ }+ Haptics.confirm()+ onDismiss()+ }+ }+ if (nowPlaying && song.url.startsWith("episode:")) {+ ImmersiveSheetRow(Icons.Rounded.Speed, stringResource(R.string.playback_speed)) { showSpeed = true }+ }+ ImmersiveSheetRow(Icons.Rounded.Share, stringResource(R.string.context_menu_share), enabled = hasId) {+ SpotifyCode.show(ShareTarget("spotify:track:${song.spotifyTrackId}", song.title, song.singer, song.coverUri))+ onDismiss()+ }+ if (nowPlaying) {+ ImmersiveSheetRow(+ Icons.Rounded.Bedtime,+ stringResource(R.string.context_menu_sleep_timer),+ tint = if (SongPlayer.sleepEndsAt.value != null) LocalImmersiveSheetTint.current.accent else null,+ ) { showSleep = true }+ }+ // Entries from extensions (menu.items), after the app's own; each names its extension.+ if (hasId) com.music.spotui.extensions.ExtensionMenuEntries(+ app.myspoti.extensions.Surface.TRACK_MENU, trackUri, song.title, song.singer, onDone = onDismiss,+ )+ Spacer(Modifier.height(12.dp))+ }+}++/** The filled tick of a liked song, in the sheet's accent. */+@Composable+private fun LikedTick() {+ Box(+ contentAlignment = Alignment.Center,+ modifier = Modifier.size(24.dp).background(LocalImmersiveSheetTint.current.accent, CircleShape),+ ) {+ androidx.compose.material3.Icon(Icons.Rounded.Check, contentDescription = null, tint = Color.Black, modifier = Modifier.size(16.dp))+ }+}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.ktnew file mode 100644index 00000000..7c3a88dd--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/FloatingTabBar.kt@@ -0,0 +1,586 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * app/src/main/java/com/music/bitchord/ui/components/floatingtabbar/FloatingTabBar.kt at edc1e6f.+ * Modified for Myspoti, 2026-10: only the expanded layout is kept (the tab pill and the standalone+ * tab; no inline/accessory states and no shared transitions, the mini player is stacked above the+ * bar by the host), the pill is BitChord's refracting lens while Liquid Glass is on and the plain+ * lifted pill of GlassSelectionPill.kt otherwise, haptics and "reduce animation" come from the+ * system, and the surfaces are Myspoti's glass (immersiveGlassSurface). The minimized (inline)+ * state lives in ImmersiveChrome.kt.+ */++/*+ * FloatingTabBar v1.0.1 by Elyes Mansour+ * https://github.com/elyesmansour/compose-floating-tab-bar+ * Licensed under the Apache License, Version 2.0+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Vendored from the v1.0.1 tag: the published AAR is compiled against+ * Compose 1.8 and crashes with NoSuchMethodError on+ * SharedTransitionScope.sharedElement under the Compose version this app uses.+ * Compiling the source here keeps it binary-compatible.+ *+ * Local modifications on top of v1.0.1:+ * - Package renamed.+ * - InlineBar/ExpandedBar use Row/Column instead of ConstraintLayout, and the+ * tab pill + standalone tab cluster is centered (iOS 26 style) instead of+ * being pinned to opposite screen edges.+ * - The inline/expanded AnimatedContent is center-aligned so the collapse+ * animation morphs around the center instead of the start edge.+ *+ * Taken from EchoMusicApp/Echo-Music, which carries the three modifications+ * listed above; BitChord's own use of it is in+ * [com.music.bitchord.ui.components.GlassNavBar]. One further change here:+ *+ * - `tabBarContentModifier` is a `@Composable () -> Modifier` factory rather+ * than a single Modifier value. It is applied to three surfaces of three+ * different sizes (the tab pill, the circular standalone tab, the accessory),+ * and a liquid glass Modifier carries a shape-outline cache keyed on the size+ * it last saw — so one shared instance is invalidated by whichever surface+ * drew last and re-creates all three outlines every frame. A factory gives+ * each surface its own.+ * - The expanded tab group's selection pill is a lifted glass lens in motion+ * (see [GlassSelectionPill]): a tap inflates it past the bar, carries it to+ * the tab on a spring, squashes it with its acceleration, and sheds the glass+ * back into a flat fill on landing. Horizontal drags pick it up the same way,+ * resist at the ends, tick across tab boundaries, and settle on release.+ */++package com.music.spotui.ui.immersive.shell++import androidx.compose.animation.core.AnimationSpec+import androidx.compose.animation.core.animateFloatAsState+import androidx.compose.animation.core.snap+import androidx.compose.animation.core.spring+import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.gestures.detectHorizontalDragGestures+import androidx.compose.foundation.interaction.MutableInteractionSource+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.IntrinsicSize+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.aspectRatio+import androidx.compose.foundation.layout.fillMaxHeight+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.Composable+import androidx.compose.runtime.CompositionLocalProvider+import androidx.compose.runtime.Immutable+import com.music.spotui.ui.immersive.shell.backdrop.backdrops.layerBackdrop+import com.music.spotui.ui.immersive.shell.backdrop.backdrops.rememberLayerBackdrop+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.runtime.mutableStateListOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.rememberUpdatedState+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.geometry.Offset+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.Shape+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.hapticfeedback.HapticFeedbackType+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.layout.onSizeChanged+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.platform.LocalHapticFeedback+import androidx.compose.ui.platform.LocalLayoutDirection+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.IntSize+import androidx.compose.ui.unit.LayoutDirection+import androidx.compose.ui.unit.dp+import kotlin.math.roundToInt++/** Hoisted so the default is one stable lambda rather than a new one per call. */+private val DefaultTabBarContentModifier: @Composable () -> Modifier = { Modifier }++/**+ * The spring the selection glyphs travel on.+ *+ * 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)++/**+ * A floating tab bar: a pill of tabs, and optionally one standalone tab in a circle of its own+ * beside it. The selected tab's pill is a physical object (see [GlassPillMotion]).+ *+ * @param selectedTabKey the key of the currently selected tab (a [FloatingTabBarScope.tab] or the+ * standalone one — with the standalone tab selected the pill is hidden)+ * @param modifier the modifier to be applied to the tab bar+ * @param tabBarContentModifier surface of the tab pill and of the standalone tab, applied after the+ * default styling (background, clip) but before any content padding. A factory so each surface gets+ * its own instance.+ * @param reduceMotion every move lands at once, with no lift+ * @param contentKey optional key that when changed retriggers the content lambda+ * @param content the content defining the tabs+ */+@Composable+internal fun FloatingTabBar(+ selectedTabKey: Any?,+ modifier: Modifier = Modifier,+ tabBarContentModifier: @Composable () -> Modifier = DefaultTabBarContentModifier,+ colors: FloatingTabBarColors = FloatingTabBarDefaults.colors(),+ shapes: FloatingTabBarShapes = FloatingTabBarDefaults.shapes(),+ sizes: FloatingTabBarSizes = FloatingTabBarDefaults.sizes(),+ reduceMotion: Boolean = false,+ contentKey: Any? = null,+ content: FloatingTabBarScope.() -> Unit,+) {+ val scope = remember(contentKey) { FloatingTabBarScopeImpl().apply { content() } }+ val standaloneTab = scope.standaloneTab+ val hasTabGroup = scope.tabs.isNotEmpty()++ // Full width, and the tab pill takes whatever the standalone tab leaves, so the bar measures+ // like a plain nav bar: the pill is given a width to divide rather than growing to fit labels.+ Row(+ horizontalArrangement = Arrangement.spacedBy(sizes.componentSpacing),+ verticalAlignment = Alignment.CenterVertically,+ modifier = modifier+ .fillMaxWidth()+ .height(IntrinsicSize.Max),+ ) {+ if (hasTabGroup) {+ ExpandedTabs(+ scope = scope,+ selectedTabKey = selectedTabKey,+ shapes = shapes,+ sizes = sizes,+ colors = colors,+ reduceMotion = reduceMotion,+ tabBarContentModifier = tabBarContentModifier,+ modifier = Modifier.weight(1f),+ )+ }+ if (standaloneTab != null) {+ ExpandedStandaloneTab(+ standaloneTab = standaloneTab,+ shapes = shapes,+ colors = colors,+ tabBarContentModifier = tabBarContentModifier,+ modifier = Modifier+ .fillMaxHeight()+ .aspectRatio(1f),+ )+ }+ }+}++internal interface FloatingTabBarScope {+ /**+ * Adds a regular tab to the floating tab bar.+ *+ * @param key Unique identifier for the tab+ * @param title Composable content for the tab title+ * @param icon Composable content for the tab icon+ * @param onClick Callback invoked when the tab is clicked+ */+ fun tab(+ key: Any,+ title: @Composable () -> Unit,+ icon: @Composable () -> Unit,+ onClick: () -> Unit,+ )++ /**+ * Adds a standalone tab to the floating tab bar.+ *+ * Note: Calling this method more than once will override the previous standalone tab value.+ *+ * @param key Unique identifier for the standalone tab+ * @param icon Composable content for the tab icon+ * @param onClick Callback invoked when the tab is clicked+ */+ fun standaloneTab(+ key: Any,+ icon: @Composable () -> Unit,+ onClick: () -> Unit,+ )+}++@Composable+private fun ExpandedTabs(+ scope: FloatingTabBarScopeImpl,+ selectedTabKey: Any?,+ shapes: FloatingTabBarShapes,+ sizes: FloatingTabBarSizes,+ colors: FloatingTabBarColors,+ reduceMotion: Boolean,+ modifier: Modifier,+ tabBarContentModifier: @Composable () -> Modifier,+) {+ val selectedTabIndex = scope.tabs.indexOfFirst { it.key == selectedTabKey }+ val currentSelectedTabIndex by rememberUpdatedState(selectedTabIndex)+ // The drag handler outlives the scope it was started with (a tab change builds a new one).+ val currentScope by rememberUpdatedState(scope)+ val selectionSpec: AnimationSpec<Float> = if (reduceMotion) snap() else GlassSpring+ val haptics = LocalHapticFeedback.current++ val coroutineScope = rememberCoroutineScope()+ val pill = remember { GlassPillMotion(coroutineScope, selectedTabIndex.coerceAtLeast(0)) }+ pill.reduceMotion = reduceMotion+ // With Liquid Glass on, the lifted pill is a lens refracting the bar's glass and its tabs+ // (recorded below); without it, the plain lifted pill carries the whole motion.+ val page = LocalImmersiveBackdrop.current+ val glassPill = page != null+ val barGlass = rememberLayerBackdrop()+ val tabRow = rememberLayerBackdrop()++ var rowSize by remember { mutableStateOf(IntSize.Zero) }+ var lastHapticTab by remember { mutableIntStateOf(selectedTabIndex) }+ var lastSelectedTabIndex by remember { mutableIntStateOf(selectedTabIndex) }+ val density = LocalDensity.current+ val layoutDirection = LocalLayoutDirection.current+ val isRtl = layoutDirection == LayoutDirection.Rtl+ val tabCount = scope.tabs.size+ val tabSpacingPx = with(density) { sizes.tabSpacing.toPx() }+ val tabWidthPx = if (rowSize.width > 0 && tabCount > 0) {+ (rowSize.width - tabSpacingPx * (tabCount - 1)) / tabCount+ } else {+ 0f+ }+ val tabStepPx = if (rowSize.width > 0 && tabCount > 0) {+ (rowSize.width + tabSpacingPx) / tabCount+ } else {+ 0f+ }+ pill.stepDp = tabStepPx / density.density++ // The pill rests in its tab's cell and lifts to stand [PILL_GROW_HEIGHT]+ // taller than the whole bar, keeping the cell's proportions as it grows.+ val contentPadding = sizes.tabBarContentPadding+ val padLeftPx = with(density) { contentPadding.calculateLeftPadding(layoutDirection).toPx() }+ val padTopPx = with(density) { contentPadding.calculateTopPadding().toPx() }+ val padBottomPx = with(density) { contentPadding.calculateBottomPadding().toPx() }+ val rowHeightPx = rowSize.height.toFloat()+ val restSize = Size(tabWidthPx, rowHeightPx)+ val liftedHeightPx = rowHeightPx + padTopPx + padBottomPx ++ with(density) { PILL_GROW_HEIGHT.toPx() }+ val liftedSize = if (rowHeightPx > 0f) {+ Size(liftedHeightPx * tabWidthPx / rowHeightPx, liftedHeightPx)+ } else {+ restSize+ }+ // Where the pill's centre is in the row, for a position in tab steps.+ val pillCenterInRow: (Float) -> Offset = { position ->+ val x = position * tabStepPx + tabWidthPx / 2f+ Offset(if (isRtl) rowSize.width - x else x, rowHeightPx / 2f)+ }+ val showPill = selectedTabIndex >= 0 && tabWidthPx > 0f++ LaunchedEffect(selectedTabIndex) {+ if (selectedTabIndex >= 0) {+ // Back from the standalone tab there is no tab to travel from.+ if (lastSelectedTabIndex < 0) {+ pill.snapTo(selectedTabIndex)+ } else {+ pill.animateTo(selectedTabIndex)+ }+ }+ lastSelectedTabIndex = selectedTabIndex+ lastHapticTab = selectedTabIndex+ }++ // Unclipped: the lifted pill stands past the bar's edges, so it is drawn+ // here, over the bar, rather than inside the bar's clip.+ Box(modifier = modifier) {+ // The bar's glass is exported for the lens to refract.+ CompositionLocalProvider(LocalGlassExport provides if (glassPill) barGlass else null) {+ Box(+ modifier = Modifier+ .background(colors.backgroundColor, shapes.tabBarShape)+ .clip(shapes.tabBarShape)+ .then(tabBarContentModifier())+ .padding(contentPadding),+ ) {+ if (showPill && (!glassPill || pill.isFlat)) {+ FlatSelectionPill(+ color = colors.indicatorColor,+ modifier = Modifier+ .matchParentSize()+ .pillPlacement(+ center = { pillCenterInRow(pill.position) },+ size = { pill.liveSize(restSize, liftedSize) },+ ),+ )+ }++ Row(+ horizontalArrangement = Arrangement.spacedBy(sizes.tabSpacing),+ modifier = Modifier+ .fillMaxWidth()+ .onSizeChanged { rowSize = it }+ .then(if (glassPill) Modifier.layerBackdrop(tabRow) else Modifier)+ // Keyed on whether a pill tab is selected too: the bar can be (re)composed with+ // Search selected (it has no pill), and a handler that returned then would stay+ // dead after the user came back to Home or Library.+ .pointerInput(tabStepPx, isRtl, selectedTabIndex >= 0) {+ if (currentSelectedTabIndex < 0 || tabStepPx <= 0f) return@pointerInput++ // In tab order, whichever way the row runs.+ val direction = if (isRtl) -1f else 1f+ var totalDrag = 0f+ var dragStartIndex = currentSelectedTabIndex+ detectHorizontalDragGestures(+ onDragStart = {+ totalDrag = 0f+ dragStartIndex = currentSelectedTabIndex+ pill.startDrag()+ },+ onDragCancel = { pill.release(currentSelectedTabIndex) },+ onDragEnd = {+ val absoluteIndexFloat = (dragStartIndex + totalDrag / tabStepPx)+ .coerceIn(0f, currentScope.tabs.lastIndex.toFloat())+ val newIndex = absoluteIndexFloat.roundToInt()+ pill.release(newIndex)+ if (newIndex != currentSelectedTabIndex) {+ currentScope.tabs[newIndex].onClick()+ }+ },+ onHorizontalDrag = { _, delta ->+ totalDrag += delta * direction+ val absoluteIndexFloat = (dragStartIndex + totalDrag / tabStepPx)+ .coerceIn(0f, currentScope.tabs.lastIndex.toFloat())+ pill.dragTo(absoluteIndexFloat)++ val approximateTab = absoluteIndexFloat.roundToInt()+ if (approximateTab != lastHapticTab) {+ haptics.performHapticFeedback(HapticFeedbackType.SegmentTick)+ lastHapticTab = approximateTab+ }+ },+ )+ },+ ) {+ scope.tabs.forEach { tab ->+ val isSelected = tab.key == selectedTabKey+ val iconScale by animateFloatAsState(+ targetValue = if (isSelected) 1.08f else 1f,+ animationSpec = selectionSpec,+ label = "immersiveTabScale",+ )+ Tab(+ icon = {+ Box(+ Modifier.graphicsLayer {+ scaleX = iconScale+ scaleY = iconScale+ },+ ) {+ tab.icon()+ }+ },+ title = tab.title,+ modifier = Modifier+ // An equal share of the pill each, the way the plain nav bar+ // divides its own width, rather than each tab being as wide as+ // its label happens to be.+ .weight(1f)+ .clip(shapes.tabShape)+ .clickable(+ onClick = tab.onClick,+ indication = null,+ interactionSource = remember { MutableInteractionSource() },+ )+ .padding(sizes.tabExpandedContentPadding),+ )+ }+ }+ }+ }++ if (showPill && !pill.isFlat) {+ val placement = Modifier+ .matchParentSize()+ .pillPlacement(+ center = { pillCenterInRow(pill.position) + Offset(padLeftPx, padTopPx) },+ size = { pill.liveSize(restSize, liftedSize) },+ )+ if (page != null) {+ GlassSelectionPill(+ motion = pill,+ fillColor = colors.indicatorColor,+ page = page,+ barGlass = barGlass,+ tabRow = tabRow,+ modifier = placement,+ )+ } else {+ LiftedSelectionPill(+ motion = pill,+ fillColor = colors.indicatorColor,+ modifier = placement,+ )+ }+ }+ }+}++@Composable+private fun ExpandedStandaloneTab(+ standaloneTab: FloatingTabBarTab,+ shapes: FloatingTabBarShapes,+ colors: FloatingTabBarColors,+ modifier: Modifier,+ tabBarContentModifier: @Composable () -> Modifier,+) {+ Tab(+ icon = standaloneTab.icon,+ title = standaloneTab.title,+ isStandalone = true,+ modifier = modifier+ .background(colors.backgroundColor, shapes.standaloneTabShape)+ .clip(shapes.standaloneTabShape)+ .then(tabBarContentModifier())+ .clickable(+ onClick = standaloneTab.onClick,+ indication = null,+ interactionSource = remember { MutableInteractionSource() },+ ),+ )+}++@Composable+private fun Tab(+ icon: @Composable () -> Unit,+ title: @Composable () -> Unit,+ modifier: Modifier = Modifier,+ isStandalone: Boolean = false,+) {+ Column(+ verticalArrangement = Arrangement.Center,+ horizontalAlignment = Alignment.CenterHorizontally,+ modifier = modifier,+ ) {+ icon()+ if (!isStandalone) {+ title()+ }+ }+}++private class FloatingTabBarScopeImpl : FloatingTabBarScope {+ val tabs = mutableStateListOf<FloatingTabBarTab>()+ var standaloneTab: FloatingTabBarTab? by mutableStateOf(null)+ private set++ override fun tab(+ key: Any,+ title: @Composable () -> Unit,+ icon: @Composable () -> Unit,+ onClick: () -> Unit,+ ) {+ tabs.add(FloatingTabBarTab(key = key, title = title, icon = icon, onClick = onClick))+ }++ override fun standaloneTab(+ key: Any,+ icon: @Composable () -> Unit,+ onClick: () -> Unit,+ ) {+ standaloneTab = FloatingTabBarTab(key = key, title = {}, icon = icon, onClick = onClick)+ }+}++private data class FloatingTabBarTab(+ val key: Any,+ val title: @Composable () -> Unit,+ val icon: @Composable () -> Unit,+ val onClick: () -> Unit,+)++/**+ * Represents the colors used in [FloatingTabBar].+ */+@Immutable+internal data class FloatingTabBarColors(+ val backgroundColor: Color,+ val indicatorColor: Color,+)++/**+ * Represents the shapes used in [FloatingTabBar].+ */+@Immutable+internal data class FloatingTabBarShapes(+ val tabBarShape: Shape,+ val tabShape: Shape,+ val standaloneTabShape: Shape,+)++/**+ * Represents the sizes and spacing used in [FloatingTabBar].+ */+@Immutable+internal data class FloatingTabBarSizes(+ val tabBarContentPadding: PaddingValues,+ val tabExpandedContentPadding: PaddingValues,+ val componentSpacing: Dp,+ val tabSpacing: Dp,+)++/**+ * Contains the default values used by [FloatingTabBar].+ */+internal object FloatingTabBarDefaults {+ /**+ * @param backgroundColor the color used for the tab bar background+ * @param indicatorColor the color used behind the selected tab+ */+ @Composable+ fun colors(+ backgroundColor: Color = Color.Transparent,+ indicatorColor: Color = Color.White.copy(alpha = 0.12f),+ ): FloatingTabBarColors = FloatingTabBarColors(+ backgroundColor = backgroundColor,+ indicatorColor = indicatorColor,+ )++ /**+ * @param tabBarShape the shape used to clip the tab bar+ * @param tabShape the shape used to clip individual tabs+ * @param standaloneTabShape the shape used to clip the standalone tab+ */+ @Composable+ fun shapes(+ tabBarShape: Shape = RoundedCornerShape(100),+ tabShape: Shape = RoundedCornerShape(100),+ standaloneTabShape: Shape = CircleShape,+ ): FloatingTabBarShapes = FloatingTabBarShapes(+ tabBarShape = tabBarShape,+ tabShape = tabShape,+ standaloneTabShape = standaloneTabShape,+ )++ /**+ * @param tabBarContentPadding the padding applied to the tab bar content+ * @param tabExpandedContentPadding the padding applied to each tab+ * @param componentSpacing the spacing between the pill and the standalone tab+ * @param tabSpacing the spacing between tabs+ */+ @Composable+ fun sizes(+ tabBarContentPadding: PaddingValues = PaddingValues(vertical = 4.dp, horizontal = 4.dp),+ tabExpandedContentPadding: PaddingValues = PaddingValues(vertical = 6.dp, horizontal = 20.dp),+ componentSpacing: Dp = 8.dp,+ tabSpacing: Dp = 0.dp,+ ): FloatingTabBarSizes = FloatingTabBarSizes(+ tabBarContentPadding = tabBarContentPadding,+ tabExpandedContentPadding = tabExpandedContentPadding,+ componentSpacing = componentSpacing,+ tabSpacing = tabSpacing,+ )+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/GlassSelectionPill.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/GlassSelectionPill.ktnew file mode 100644index 00000000..70a62f9a--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/GlassSelectionPill.kt@@ -0,0 +1,650 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * app/src/main/java/com/music/bitchord/ui/components/floatingtabbar/GlassSelectionPill.kt at edc1e6f.+ * Modified for Myspoti, 2026-10: the physics ([GlassPillMotion]) is unchanged; the lens that+ * refracts the recorded page ([GlassSelectionPill]) is drawn while Liquid Glass is on, and a+ * plain lifted pill ([LiftedSelectionPill]) stands in for it otherwise.+ */++/*+ * The selection pill's motion — the travel spring, the held lift, the+ * acceleration squash and the glass-to-flat hand-off, with their constants —+ * is ported from liquid_glass_easy's LiquidGlassAnimatedNavBar and+ * LiquidGlassLensMotion (pub.dev/packages/liquid_glass_easy, 4.3.4).+ * Copyright (c) 2025 Ahmed Gamil, MIT License.+ */+package com.music.spotui.ui.immersive.shell++import android.os.Build+import androidx.compose.ui.graphics.GraphicsLayerScope+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.layout.LayoutCoordinates+import androidx.compose.ui.unit.Density+import androidx.compose.ui.unit.DpOffset+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.drawBackdrop+import com.music.spotui.ui.immersive.shell.backdrop.effects.lens+import com.music.spotui.ui.immersive.shell.backdrop.highlight.Highlight+import com.music.spotui.ui.immersive.shell.backdrop.shadow.Shadow+import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.Composable+import androidx.compose.runtime.Stable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableFloatStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.runtime.withFrameNanos+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.drawBehind+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.drawscope.Stroke+import androidx.compose.ui.graphics.drawOutline+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.graphics.lerp+import androidx.compose.ui.layout.layout+import androidx.compose.ui.unit.Constraints+import androidx.compose.ui.unit.dp+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.launch+import kotlin.math.abs+import kotlin.math.exp+import kotlin.math.roundToInt+import kotlin.math.sign++/** How much taller than the bar the pill stands while it is lifted. */+internal val PILL_GROW_HEIGHT = 9.dp++/**+ * The selection pill's physics, owned by the tab bar and handed to whichever+ * pill is drawing it.+ *+ * A tap lifts the pill at once — it inflates past the bar on two+ * under-damped springs, one per axis, so it overshoots its raised size and+ * rebounds — and it stays up for the whole journey. The travel is its own+ * spring. Only once the pill has landed ([HANDOVER_START] of the way there) is+ * the lift released, so it deflates where it stands, dipping a little under+ * its resting size and coming back. A drag is the same lift held open by a+ * finger.+ *+ * Along the way the pill's drawn position is sampled every frame and+ * differentiated twice: it stretches wide and flat as it launches, squashes+ * narrow and tall as it brakes, and is undeformed at constant speed. A travel+ * keeps one sense of that deformation for the whole trip, keyed to where it is+ * going; a finger keeps the raw force.+ *+ * The glass is a third, much faster spring, so the pill reads as glass almost+ * as soon as it is touched, and sheds it ([glassPresence]) from the landing+ * while the size is still settling. Once nothing is left to see, [isFlat]+ * flips and the plain pill takes over — two identical pictures, so there is+ * nothing to cross-fade.+ *+ * Positions are in tab steps: `0` is the first tab, `1` the second.+ */+@Stable+internal class GlassPillMotion(+ private val scope: CoroutineScope,+ initialIndex: Int,+) {+ /** Where the pill is drawn, in tab steps. */+ var position by mutableFloatStateOf(initialIndex.toFloat())+ private set++ /** The width lift, `0` at rest and `1` at the raised size; overshoots both. */+ var liftX by mutableFloatStateOf(0f)+ private set++ /** The height lift; see [liftX]. */+ var liftY by mutableFloatStateOf(0f)+ private set++ /** How much of the material is on, `0`..`1`. */+ var material by mutableFloatStateOf(0f)+ private set++ /** Acceleration squash: width scales by `1 + this`, height by `1 - this`. */+ var deviation by mutableFloatStateOf(0f)+ private set++ /** How much of the pill still reads as glass, `1` lifted to `0` flat. */+ var glassPresence by mutableFloatStateOf(0f)+ private set++ /**+ * True when there is nothing left in the pill but a flat fill at rest size,+ * where the plain pill draws exactly the same picture.+ */+ var isFlat by mutableStateOf(true)+ private set++ /** The tab the pill is headed for. */+ var index: Int = initialIndex+ private set++ /** One tab step in dp, which the squash model samples the pill's travel in. */+ var stepDp: Float = 0f++ /** "Reduce animation": every move lands at once, with no lift. */+ var reduceMotion: Boolean = false++ private var travelPos = initialIndex.toDouble()+ private var travelVel = 0.0+ private var travelTarget = travelPos+ private var travelFrom = travelPos+ private var travelActive = false++ private var lifted = false+ private var liftXPos = 0.0+ private var liftXVel = 0.0+ private var liftYPos = 0.0+ private var liftYVel = 0.0+ private var liftPos = 0.0+ private var liftVel = 0.0++ private var dragging = false+ private var dragTarget = 0.0+ private var dragFollow = 0.0++ private var travelSign = 0.0+ private var travelSignEased = 0.0+ private var handover = 1.0+ private var squash = 0.0+ private val squashModel = PillSquashModel()++ private var running = false++ /** A tab was chosen: travel there, lifted. Re-choosing the current tab is a no-op. */+ fun animateTo(next: Int) {+ if (next == index) return+ if (reduceMotion) {+ snapTo(next)+ return+ }+ index = next+ travelActive = true+ lifted = true+ // Retarget from wherever the pill is; the spring keeps its velocity.+ travelFrom = travelPos+ travelTarget = next.toDouble()+ travelSign = signOfTravel(travelTarget - travelFrom)+ isFlat = false+ start()+ }++ /** Place the pill on [target] at rest, with no travel and no lift. */+ fun snapTo(target: Int) {+ index = target+ travelPos = target.toDouble()+ travelTarget = travelPos+ travelFrom = travelPos+ travelVel = 0.0+ travelActive = false+ dragging = false+ lifted = false+ liftXPos = 0.0; liftXVel = 0.0+ liftYPos = 0.0; liftYVel = 0.0+ liftPos = 0.0; liftVel = 0.0+ handover = 1.0+ squash = 0.0+ squashModel.stop()+ travelSign = 0.0+ travelSignEased = 0.0+ publish()+ isFlat = true+ }++ /** A finger has picked the pill up where it stands. */+ fun startDrag() {+ dragging = true+ travelActive = false+ lifted = !reduceMotion+ // The hand takes the deformation back off the travel.+ travelSign = 0.0+ dragFollow = travelPos+ dragTarget = travelPos+ travelVel = 0.0+ isFlat = false+ start()+ }++ /** The finger is over [position] tab steps. */+ fun dragTo(position: Float) {+ if (dragging) dragTarget = position.toDouble()+ }++ /**+ * The finger let go and the pill is to settle on [next]. It stays lifted+ * through the snap and comes down on landing, exactly as a tap's does.+ */+ fun release(next: Int) {+ if (!dragging) return+ val from = dragFollow+ dragging = false+ index = next+ if (reduceMotion) {+ snapTo(next)+ return+ }+ travelActive = true+ travelPos = from+ travelVel = 0.0+ travelFrom = from+ travelTarget = next.toDouble()+ travelSign = signOfTravel(travelTarget - travelFrom)+ start()+ }++ private fun start() {+ if (running) return+ running = true+ scope.launch {+ var last = -1L+ try {+ while (true) {+ val now = withFrameNanos { it }+ val dt = if (last < 0) 0.0 else (now - last) / 1e9+ last = now+ if (!tick(dt, now / 1e9)) break+ }+ } finally {+ running = false+ }+ }+ }++ /** One frame of everything. False once all of it has settled. */+ private fun tick(dt: Double, now: Double): Boolean {+ // 1) Travel.+ var travelSettled = true+ if (travelActive) {+ val r = springStep(travelPos, travelVel, travelTarget, dt, TRAVEL_STIFFNESS, TRAVEL_DAMPING)+ travelPos = r.first+ travelVel = r.second+ travelSettled = abs(travelPos - travelTarget) < 0.003 && abs(travelVel) < 0.05+ if (travelSettled) {+ travelPos = travelTarget+ travelVel = 0.0+ }+ }++ // 2) Under a finger, chase it smoothly.+ if (dragging) {+ dragFollow += if (reduceMotion) {+ dragTarget - dragFollow+ } else {+ (dragTarget - dragFollow) * (1 - exp(-dt / FOLLOW_TAU))+ }+ }++ // 3) The lift, held for the journey and released on landing.+ if (!dragging && (travelSettled || travelProgress() >= HANDOVER_START)) {+ lifted = false+ }+ val liftTarget = if (lifted) 1.0 else 0.0+ stepLift(liftXPos, liftXVel, liftTarget, dt, LIFT_STIFFNESS, LIFT_DAMPING_X).let {+ liftXPos = it.first; liftXVel = it.second+ }+ stepLift(liftYPos, liftYVel, liftTarget, dt, LIFT_STIFFNESS, LIFT_DAMPING_Y).let {+ liftYPos = it.first; liftYVel = it.second+ }+ stepLift(liftPos, liftVel, liftTarget, dt, MATERIAL_STIFFNESS, MATERIAL_DAMPING).let {+ liftPos = it.first; liftVel = it.second+ }+ val liftSettled = !lifted && liftXPos == 0.0 && liftYPos == 0.0 && liftPos == 0.0++ // 4) The deflation outlives the spring that carried the pill there.+ if (travelActive && travelSettled && liftSettled && !dragging) {+ travelActive = false+ }++ // 5) Sample the pill where it is drawn this frame.+ val frac = if (dragging) dragFollow else travelPos+ if (stepDp > 0f) {+ if (!squashModel.isTracking) squashModel.start()+ squash = squashModel.track(frac * stepDp, now, dt)+ if (travelSignEased == 0.0) {+ travelSignEased = travelSign+ } else if (travelSignEased != travelSign) {+ travelSignEased += (travelSign - travelSignEased) * (1 - exp(-dt / SIGN_TAU))+ if (abs(travelSign - travelSignEased) < 0.01) travelSignEased = travelSign+ }+ // Keep the force's magnitude and take its sign from the direction+ // of travel, so a trip deforms one way the whole way.+ val key = travelSignEased+ if (key != 0.0) squash = squash * (1 - abs(key)) - key * abs(squash)+ }++ // 6) The hand-off rides the same landing as the deflation.+ val handoverTarget = if (lifted) 0.0 else 1.0+ val tau = if (handoverTarget > handover) HANDOVER_TAU else GLASS_RETURN_TAU+ handover += (handoverTarget - handover) * (1 - exp(-dt / tau))+ if (abs(handoverTarget - handover) < 0.002) handover = handoverTarget++ val settled = !travelActive && !dragging && liftSettled &&+ abs(squash) < 0.0005 && handover >= 1.0+ if (settled) {+ squashModel.stop()+ squash = 0.0+ travelSign = 0.0+ travelSignEased = 0.0+ }+ publish()+ isFlat = settled+ return !settled+ }++ private fun publish() {+ position = (if (dragging) dragFollow else travelPos).toFloat()+ liftX = liftXPos.toFloat()+ liftY = liftYPos.toFloat()+ material = liftPos.coerceIn(0.0, 1.0).toFloat()+ deviation = squash.toFloat()+ glassPresence = (1 - handover).coerceIn(0.0, 1.0).toFloat()+ }++ private fun travelProgress(): Double {+ val span = abs(travelTarget - travelFrom)+ if (span < 1e-6) return 1.0+ return (1 - abs(travelTarget - travelPos) / span).coerceIn(0.0, 1.0)+ }++ private fun signOfTravel(span: Double): Double = if (abs(span) < 1e-6) 0.0 else sign(span)++ /** The size the pill is drawn at this frame, between [rest] and [lifted]. */+ fun liveSize(rest: Size, lifted: Size): Size {+ val w = rest.width + (lifted.width - rest.width) * liftX+ val h = rest.height + (lifted.height - rest.height) * liftY+ return Size(w * (1 + deviation), h * (1 - deviation))+ }++ private companion object {+ const val TRAVEL_STIFFNESS = 280.0+ const val TRAVEL_DAMPING = 31.4++ /** Damping ratio 0.6 across, 0.7 down, so width overshoots a shade further. */+ const val LIFT_STIFFNESS = 250.0+ const val LIFT_DAMPING_X = 19.0+ const val LIFT_DAMPING_Y = 22.1++ /** Critically damped and four times as stiff: the glass is on long before the size settles. */+ const val MATERIAL_STIFFNESS = 1000.0+ const val MATERIAL_DAMPING = 63.3++ const val HANDOVER_START = 0.92+ const val HANDOVER_TAU = 0.09+ const val GLASS_RETURN_TAU = 0.05+ const val FOLLOW_TAU = 0.05+ const val SIGN_TAU = 0.25++ /** Semi-implicit Euler in 1/240 s substeps, so a long frame cannot blow it up. */+ fun springStep(+ x: Double,+ vel: Double,+ target: Double,+ dt: Double,+ stiffness: Double,+ damping: Double,+ ): Pair<Double, Double> {+ var t = dt+ var px = x+ var pv = vel+ while (t > 0) {+ val step = if (t > 1 / 240.0) 1 / 240.0 else t+ val accel = -stiffness * (px - target) - damping * pv+ pv += accel * step+ px += pv * step+ t -= step+ }+ return px to pv+ }++ /** A spring step snapped to its target once it has nothing left to say. */+ fun stepLift(+ x: Double,+ vel: Double,+ target: Double,+ dt: Double,+ stiffness: Double,+ damping: Double,+ ): Pair<Double, Double> {+ val r = springStep(x, vel, target, dt, stiffness, damping)+ return if (abs(r.first - target) < 0.0008 && abs(r.second) < 0.01) target to 0.0 else r+ }+ }+}++/**+ * Acceleration to deformation: the pill's position over a short window,+ * differentiated twice and averaged, scaled and clamped, then eased so a+ * single noisy frame cannot flick it. Tuned in dp/s².+ */+private class PillSquashModel {+ private val history = ArrayList<Pair<Double, Double>>()+ var isTracking = false+ private set+ private var value = 0.0++ fun start() {+ history.clear()+ value = 0.0+ isTracking = true+ }++ fun stop() {+ isTracking = false+ history.clear()+ value = 0.0+ }++ fun track(x: Double, now: Double, dt: Double): Double {+ if (!isTracking) return value+ history.add(x to now)+ val cutoff = now - SAMPLE_WINDOW+ history.removeAll { it.second < cutoff }+ val raw = (averageAcceleration() * SENSITIVITY).coerceIn(-MAX_DEFORMATION, MAX_DEFORMATION)+ val ease = (dt / RESPONSE_TIME).coerceIn(0.0, 1.0)+ value += (raw - value) * ease+ return value+ }++ private fun averageAcceleration(): Double {+ if (history.size < 3) return 0.0+ val velocities = ArrayList<Pair<Double, Double>>(history.size)+ for (i in 1 until history.size) {+ val dt = history[i].second - history[i - 1].second+ if (dt <= 0) continue+ velocities.add(+ (history[i].first - history[i - 1].first) / dt to+ (history[i].second + history[i - 1].second) / 2,+ )+ }+ if (velocities.size < 2) return 0.0+ var total = 0.0+ var count = 0+ for (i in 1 until velocities.size) {+ val dt = velocities[i].second - velocities[i - 1].second+ if (dt <= 0) continue+ total += (velocities[i].first - velocities[i - 1].first) / dt+ count+++ }+ return if (count == 0) 0.0 else total / count+ }++ private companion object {+ const val SAMPLE_WINDOW = 0.3+ const val SENSITIVITY = 0.00007++ /** ±12 %: the pill travels inside the bar, and more would climb out of it. */+ const val MAX_DEFORMATION = 0.12+ const val RESPONSE_TIME = 0.18+ }+}++/**+ * Places a pill-sized child centred on [center] at [size], inside a parent it+ * matches the size of — so the pill can move and grow past that parent's+ * edges without ever changing its measured size. Both read on layout, not+ * composition, so a frame of motion is a relayout and nothing more.+ */+internal fun Modifier.pillPlacement(center: () -> Offset, size: () -> Size): Modifier =+ layout { measurable, constraints ->+ val s = size()+ val w = s.width.roundToInt().coerceAtLeast(1)+ val h = s.height.roundToInt().coerceAtLeast(1)+ val placeable = measurable.measure(Constraints.fixed(w, h))+ layout(constraints.minWidth, constraints.minHeight) {+ val c = center()+ placeable.place((c.x - w / 2f).roundToInt(), (c.y - h / 2f).roundToInt())+ }+ }++/** The flat pill: a fill and nothing else. */+@Composable+internal fun FlatSelectionPill(+ color: Color,+ modifier: Modifier,+) {+ val shape = remember { RoundedCornerShape(percent = 50) }+ Box(modifier.background(color, shape))+}++/**+ * The lifted pill: the selection fill gives way to a brighter body with a rim and a contact+ * shadow while the pill is picked up, drawn above the bar and free to stand past its edges.+ *+ * Stands in for BitChord's refracting lens (it needs a recorded backdrop that Myspoti does not+ * have). The rim and the shadow are the first things shed on landing, and at the end of that the+ * body is exactly the [fillColor], which is what [FlatSelectionPill] under the tabs draws.+ */+@Composable+internal fun LiftedSelectionPill(+ motion: GlassPillMotion,+ fillColor: Color,+ modifier: Modifier,+) {+ val shape = remember { RoundedCornerShape(percent = 50) }+ val liftedBody = remember(fillColor) { Color.White.copy(alpha = LIFTED_BODY_ALPHA) }+ Box(+ modifier+ .graphicsLayer {+ val rim = motion.material * rimOf(motion.glassPresence)+ shadowElevation = rim * LIFTED_SHADOW.toPx()+ this.shape = shape+ clip = false+ }+ .drawBehind {+ val outline = shape.createOutline(size, layoutDirection, this)+ val body = lerp(fillColor, liftedBody, motion.material)+ drawOutline(outline, color = body)+ val rim = motion.material * rimOf(motion.glassPresence)+ if (rim > 0f) {+ drawOutline(outline, color = Color.White.copy(alpha = LIFTED_RIM_ALPHA * rim), style = Stroke(1.dp.toPx()))+ }+ },+ )+}++/** The rim and its shadow are gone by the time the hand-off is 55% through. */+private fun rimOf(presence: Float): Float = ((presence - 0.45f) / 0.55f).coerceIn(0f, 1f)++private val LIFTED_SHADOW = 10.dp+private const val LIFTED_BODY_ALPHA = 0.20f+private const val LIFTED_RIM_ALPHA = 0.38f++/**+ * The lifted pill with Liquid Glass on (BitChord's GlassSelectionPill): a lens over the tab bar+ * that refracts the bar's own glass and its tab row, drawn above both and free to stand past the+ * bar's edges.+ *+ * Clear while it is lifted (the selection fill fades out as the material comes on and back in as+ * it goes), with a rim and a contact shadow that are the first things shed on landing, and+ * refraction that eases out behind them. At the end of that it is drawing the bar, the fill and+ * the tabs with no lens, which is exactly what [FlatSelectionPill] under the tabs draws.+ */+@Composable+internal fun GlassSelectionPill(+ motion: GlassPillMotion,+ fillColor: Color,+ page: LayerBackdrop,+ barGlass: LayerBackdrop,+ tabRow: LayerBackdrop,+ modifier: Modifier,+) {+ val shape = remember { RoundedCornerShape(percent = 50) }+ val backdrop = remember(page, barGlass, tabRow, fillColor) {+ SelectionPillBackdrop(PageBackdrop(page), barGlass, tabRow) {+ fillColor.copy(alpha = fillColor.alpha * (1f - motion.material))+ }+ }+ Box(+ modifier.drawBackdrop(+ backdrop = backdrop,+ shape = { shape },+ effects = {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+ lens(+ refractionHeight = LENS_HEIGHT.toPx() * motion.glassPresence,+ refractionAmount = LENS_AMOUNT.toPx() * motion.material,+ chromaticAberration = true,+ )+ }+ },+ highlight = {+ val alpha = motion.material * rimOf(motion.glassPresence)+ if (alpha > 0f) Highlight.Default.copy(alpha = alpha) else null+ },+ shadow = {+ val alpha = motion.material * rimOf(motion.glassPresence)+ if (alpha > 0f) PILL_SHADOW.copy(alpha = alpha) else null+ },+ ),+ )+}++private val LENS_HEIGHT = 12.dp+private val LENS_AMOUNT = 14.dp++private val PILL_SHADOW = Shadow(+ radius = 12.dp,+ offset = DpOffset(0.dp, 2.dp),+ color = Color.Black.copy(alpha = 0.3f),+)++/**+ * What the pill refracts, bottom to top: the page, the bar's glass, the selection fill, and the+ * tab row. The fill sits under the tabs here for the same reason the flat pill does: over them it+ * would grey the glyphs.+ */+private class SelectionPillBackdrop(+ private val page: Backdrop,+ private val bar: Backdrop,+ private val tabs: Backdrop,+ private val fill: () -> Color,+) : Backdrop {++ override val isCoordinatesDependent: Boolean = true++ override fun DrawScope.drawBackdrop(+ density: Density,+ coordinates: LayoutCoordinates?,+ layerBlock: (GraphicsLayerScope.() -> Unit)?,+ ) {+ with(page) { drawBackdrop(density, coordinates, layerBlock) }+ with(bar) { drawBackdrop(density, coordinates, layerBlock) }+ val color = fill()+ if (color.alpha > 0f) {+ // Past every edge: the recorded area includes the lens's padding.+ drawRect(+ color = color,+ topLeft = Offset(-size.width, -size.height),+ size = Size(size.width * 3, size.height * 3),+ )+ }+ with(tabs) { drawBackdrop(density, coordinates, layerBlock) }+ }+}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.ktnew file mode 100644index 00000000..2ea47e37--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/ImmersiveChrome.kt@@ -0,0 +1,265 @@+/*+ * The minimizing chrome follows BitChord (https://github.com/kushagrasinghx/BitChord),+ * GPL-3.0-or-later, app/src/main/java/com/music/bitchord/ui/components/floatingtabbar/FloatingTabBar.kt+ * (FloatingTabBarScrollConnection, the inline bar) and GlassNavBar.kt at edc1e6f.+ * Written anew for Myspoti, 2026-10: a scroll connection pages attach to, and one layout that+ * morphs the tab bar into a pill with the mini player beside it.+ */+package com.music.spotui.ui.immersive.shell++import androidx.compose.animation.core.Animatable+import androidx.compose.foundation.clickable+import androidx.compose.foundation.interaction.MutableInteractionSource+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.widthIn+import androidx.compose.foundation.layout.windowInsetsPadding+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.material3.Icon+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.Stable+import androidx.compose.runtime.derivedStateOf+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.runtime.staticCompositionLocalOf+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.graphics.TransformOrigin+import androidx.compose.ui.input.nestedscroll.NestedScrollConnection+import androidx.compose.ui.input.nestedscroll.NestedScrollSource+import androidx.compose.ui.input.nestedscroll.nestedScroll+import androidx.compose.ui.layout.Layout+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.res.painterResource+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.semantics.Role+import androidx.compose.ui.unit.Constraints+import androidx.compose.ui.unit.dp+import androidx.navigation.NavController+import androidx.navigation.compose.currentBackStackEntryAsState+import app.myspoti.engine.R+import com.music.spotui.ui.immersive.Immersive+import com.music.spotui.ui.immersive.motion.ImmersiveMotion+import com.music.spotui.ui.look.rememberReduceMotion+import com.music.spotui.ui.navigation.Routes+import kotlin.math.max+import kotlin.math.roundToInt+import kotlin.math.sign++/** How far a page has to scroll one way before the chrome folds or unfolds. */+private val FOLD_DISTANCE = 32.dp++/**+ * The floating chrome's fold, as iOS 26 does it: scrolling a page down minimizes the tab bar to a+ * pill (the mini player moving in beside it) and shrinks the top bar's controls; scrolling back up,+ * pulling past the top, tapping the pill or opening another page brings everything back.+ *+ * One instance for the app, provided by the host through [LocalImmersiveChrome]. Pages do not+ * talk to it: they attach its [scrollConnection] with [immersiveChromeScroll].+ */+@Stable+class ImmersiveChromeState internal constructor(private val foldDistancePx: Float) {+ /** True while the chrome is folded. */+ var minimized by mutableStateOf(false)+ private set++ private var travel = 0f++ /** Unfold now (the pill was tapped, another page opened). */+ fun expand() {+ travel = 0f+ minimized = false+ }++ /** Fold now. */+ fun minimize() {+ travel = 0f+ minimized = true+ }++ /**+ * Reads what the page actually scrolled (never consumes anything): [FOLD_DISTANCE] of it+ * downwards folds the chrome, as much upwards unfolds it, and a pull down at the very top+ * (nothing left to scroll) unfolds it at once. A page too short to scroll never folds it.+ */+ val scrollConnection: NestedScrollConnection = object : NestedScrollConnection {+ override fun onPostScroll(consumed: Offset, available: Offset, source: NestedScrollSource): Offset {+ val dy = consumed.y+ if (dy != 0f) {+ if (travel != 0f && sign(travel) != sign(dy)) travel = 0f+ travel += dy+ if (travel <= -foldDistancePx) minimize()+ else if (travel >= foldDistancePx) expand()+ } else if (available.y > 0f && minimized) {+ expand()+ }+ return Offset.Zero+ }+ }+}++/**+ * The app's [ImmersiveChromeState], or null outside the Immersive look (where+ * [immersiveChromeScroll] is then a no-op).+ */+val LocalImmersiveChrome = staticCompositionLocalOf<ImmersiveChromeState?> { null }++/** The app's chrome state, kept for the lifetime of the calling composition. Provide it with [LocalImmersiveChrome]. */+@Composable+fun rememberImmersiveChromeState(): ImmersiveChromeState {+ val px = with(LocalDensity.current) { FOLD_DISTANCE.toPx() }+ return remember { ImmersiveChromeState(px) }+}++/**+ * Lets this page's scroll fold the floating chrome (tab bar to a pill with the mini player beside+ * it, the top bar's controls shrunk) the way iOS 26 does. Put it on the page's main scrolling+ * list, next to [immersiveHazeSource]:+ *+ * ```+ * LazyColumn(+ * state = listState,+ * modifier = Modifier.fillMaxSize().immersiveHazeSource().immersiveChromeScroll(),+ * ) { ... }+ * ```+ *+ * Works the same on a `Column(Modifier.verticalScroll(...))`, a `LazyVerticalGrid` or anything+ * scrollable inside it (nested horizontal shelves are ignored: only vertical scroll counts). It+ * consumes nothing, so the page's own scroll, overscroll and top bar collapse are unchanged.+ * Classic look (no [LocalImmersiveChrome]): does nothing. Attach it once per page.+ */+@Composable+fun Modifier.immersiveChromeScroll(state: ImmersiveChromeState? = LocalImmersiveChrome.current): Modifier =+ if (state == null) this else this.nestedScroll(state.scrollConnection)++/** The minimized tab bar's pill (and the mini player's height beside it). */+private val PILL_SIZE = 56.dp++/** The gap between the mini player and the tab bar, and between the pill and the mini player. */+private val CHROME_GAP = 8.dp++/** The mini player's margin to the screen edges; the tab bar sits [TAB_INSET] further in. */+private val MINI_MARGIN = 14.dp+private val TAB_INSET = Immersive.Gutter - MINI_MARGIN++/**+ * The Immersive look's bottom chrome: the mini player over the floating tab bar, which folds into+ * a single glass pill (the current tab's glyph) with the mini player inline beside it while+ * [LocalImmersiveChrome] is minimized. Both hide on the player and queue routes.+ *+ * @param miniPlayer the mini player, given the modifier to lay out with; it may draw nothing.+ */+@Composable+fun ImmersiveBottomChrome(+ navController: NavController,+ miniPlayer: @Composable (Modifier) -> Unit,+ modifier: Modifier = Modifier,+) {+ val tabs = rememberTabNavigation(navController)+ if (tabs.fullScreen) return+ val chrome = LocalImmersiveChrome.current+ val reduceMotion = rememberReduceMotion()+ val minimized = chrome?.minimized == true++ // A new page starts at its top, with everything showing.+ val route = navController.currentBackStackEntryAsState().value?.destination?.route+ LaunchedEffect(route) { chrome?.expand() }++ val progress = remember { Animatable(if (minimized) 1f else 0f) }+ LaunchedEffect(minimized) {+ progress.animateTo(if (minimized) 1f else 0f, ImmersiveMotion.chromeSpring(reduceMotion))+ }+ val showTabs by remember { derivedStateOf { progress.value < 0.999f } }+ val showPill by remember { derivedStateOf { progress.value > 0.001f } }++ val density = LocalDensity.current+ val pillPx = with(density) { PILL_SIZE.roundToPx() }+ val gapPx = with(density) { CHROME_GAP.roundToPx() }+ val insetPx = with(density) { TAB_INSET.roundToPx() }++ Box(modifier.fillMaxWidth().windowInsetsPadding(ImmersiveBarInsets), contentAlignment = Alignment.BottomCenter) {+ Layout(+ contents = listOf<@Composable () -> Unit>(+ {+ if (showTabs) TabBarContent(selectedTab = tabs.selectedTab, onTabClick = tabs.onTabClick, modifier = Modifier)+ },+ {+ if (showPill) MinimizedTabPill(tabs.selectedTab, onClick = { chrome?.expand() })+ },+ { miniPlayer(Modifier) },+ ),+ modifier = Modifier+ .widthIn(max = ImmersiveBarMaxWidth + TAB_INSET * 2)+ .fillMaxWidth()+ .padding(horizontal = MINI_MARGIN)+ .padding(bottom = 2.dp),+ ) { (tabSlot, pillSlot, miniSlot), constraints ->+ val p = progress.value+ val width = constraints.maxWidth+ val tab = tabSlot.firstOrNull()?.measure(Constraints(maxWidth = (width - insetPx * 2).coerceAtLeast(0)))+ val pill = pillSlot.firstOrNull()?.measure(Constraints.fixed(pillPx, pillPx))+ val inlineX = insetPx + pillPx + gapPx+ val miniWidth = lerp(width.toFloat(), (width - inlineX - insetPx).toFloat(), p).roundToInt().coerceIn(0, width)+ val mini = miniSlot.firstOrNull()?.measure(Constraints(minWidth = miniWidth, maxWidth = miniWidth))++ // The tab bar's height whether or not it is still composed, so nothing jumps when it goes.+ val tabHeight = tab?.height ?: pillPx+ val miniHeight = mini?.height ?: 0+ val height = max(max(tabHeight, pillPx), if (miniHeight > 0) tabHeight + gapPx + miniHeight else 0)+ layout(width, height) {+ tab?.placeWithLayer(insetPx, height - tab.height) {+ val q = progress.value.coerceIn(0f, 1f)+ alpha = 1f - q+ // Shrinks into the pill's corner.+ transformOrigin = TransformOrigin(0f, 1f)+ scaleX = lerp(1f, pillPx / tab.width.coerceAtLeast(1).toFloat(), q)+ scaleY = lerp(1f, pillPx / tab.height.coerceAtLeast(1).toFloat(), q)+ }+ pill?.placeWithLayer(insetPx, height - pill.height) {+ val q = progress.value.coerceIn(0f, 1f)+ alpha = q+ scaleX = lerp(0.7f, 1f, q)+ scaleY = scaleX+ }+ mini?.place(+ x = lerp(0f, inlineX.toFloat(), p).roundToInt(),+ y = lerp((height - tabHeight - gapPx - miniHeight).toFloat(), (height - miniHeight).toFloat(), p).roundToInt(),+ )+ }+ }+ }+}++/** The folded tab bar: the current tab's glyph on a glass disc; a tap unfolds it. */+@Composable+private fun MinimizedTabPill(selectedTab: String, onClick: () -> Unit) {+ val item = TabItems.firstOrNull { it.route == selectedTab } ?: Routes.Home+ Box(+ modifier = Modifier+ .size(PILL_SIZE)+ .immersiveGlassSurface(CircleShape)+ .clickable(+ interactionSource = remember { MutableInteractionSource() },+ indication = null,+ role = Role.Button,+ onClickLabel = stringResource(R.string.immersive_expand_tab_bar),+ onClick = onClick,+ ),+ contentAlignment = Alignment.Center,+ ) {+ Icon(+ painter = painterResource(item.icon),+ contentDescription = stringResource(R.string.immersive_expand_tab_bar),+ tint = Immersive.Accent,+ modifier = Modifier.size(25.dp),+ )+ }+}++private fun lerp(a: Float, b: Float, t: Float): Float = a + (b - a) * tdiff --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.ktnew file mode 100644index 00000000..1c2b8061--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/ImmersiveFades.kt@@ -0,0 +1,116 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * app/src/main/java/com/music/bitchord/ui/components/BottomFadeScrim.kt at edc1e6f. Modified for Myspoti, 2026-10.+ */+package com.music.spotui.ui.immersive.shell++import androidx.compose.animation.core.EaseInCubic+import androidx.compose.animation.core.animateDpAsState+import androidx.compose.animation.core.tween+import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.asPaddingValues+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.remember+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Brush+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.layout.layout+import androidx.compose.ui.unit.Constraints+import androidx.compose.ui.unit.dp+import com.music.spotui.ui.immersive.Immersive++/** The strip the tab bar alone needs, above the gesture inset. Generous on purpose: the ramp spends most of its run at an alpha too low to see, which hides where the layer begins. */+private val FADE_HEIGHT = 180.dp++/** Taller once the mini player is stacked on top of the tab bar. */+private val FADE_HEIGHT_WITH_MINI_PLAYER = 254.dp++/** How many colour stops the ramp is cut into, so a near-flat colour does not band. */+private const val STOPS = 16++/**+ * The floor the floating bars sit on: the page colour faded in from nothing at the top to solid+ * at the very bottom, so content scrolling under the tab bar and the mini player never competes+ * with them. Flat colour, not a blur: a gradient costs one shader over a fixed rect.+ *+ * Draw it at the bottom of the app's Box, below the bars and above the page.+ *+ * @param withMiniPlayer taller when the mini player is showing above the tab bar.+ * @param pageColor the colour to fade in — whatever the page paints at the foot of the screen.+ */+@Composable+fun ImmersiveBottomFade(+ modifier: Modifier = Modifier,+ withMiniPlayer: Boolean = false,+ pageColor: Color = Immersive.Page,+) {+ // The gesture bar sits below the tab pill and wants covering too.+ val inset = ImmersiveBarInsets.asPaddingValues().calculateBottomPadding()+ 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),+ label = "immersiveBottomFadeHeight",+ )+ val brush = remember(pageColor) {+ Brush.verticalGradient(+ // A cubic ease-in: the alpha holds under a few percent for the first half of the+ // strip, which stops the eye finding the line where the layer starts.+ colorStops = Array(STOPS) { i ->+ val t = i / (STOPS - 1f)+ t to pageColor.copy(alpha = EaseInCubic.transform(t))+ },+ )+ }+ Box(+ modifier = modifier+ .fillMaxWidth()+ .height(height)+ .background(brush),+ )+}++/** How far above the floating bars the page stops taking touches. */+private val TAP_GUARD_MARGIN = 8.dp++/**+ * A dead strip across the foot of the screen, as tall as the floating bars plus a margin, so a+ * thumb that misses a tab or the mini player lands on nothing rather than on a song passing under+ * the bars. Draw it after the page and before the bars.+ *+ * @param barsHeight the bars' height in px, read in layout only (the mini player changes height+ * on every frame of its fold and this must not recompose the app root).+ */+@Composable+fun ImmersiveBarsTapGuard(+ barsHeight: () -> Int,+ modifier: Modifier = Modifier,+) {+ Box(+ modifier = modifier+ .layout { measurable, constraints ->+ val bars = barsHeight()+ val height = if (bars <= 0) 0 else (bars + TAP_GUARD_MARGIN.roundToPx())+ val placeable = measurable.measure(+ Constraints.fixed(+ width = constraints.maxWidth,+ height = height.coerceAtMost(constraints.maxHeight),+ ),+ )+ layout(placeable.width, placeable.height) { placeable.place(0, 0) }+ }+ .pointerInput(Unit) {+ // Being hit at all is what keeps the page underneath from being hit.+ awaitPointerEventScope {+ while (true) {+ awaitPointerEvent().changes.forEach { it.consume() }+ }+ }+ },+ )+}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.ktnew file mode 100644index 00000000..51e1f508--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/ImmersiveGlass.kt@@ -0,0 +1,202 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * app/src/main/java/com/music/bitchord/ui/components/LiquidGlass.kt at edc1e6f, itself adapted+ * 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.+ *+ * 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.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.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Size+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.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.shell.backdrop.Backdrop+import com.music.spotui.ui.immersive.shell.backdrop.backdrops.LayerBackdrop+import com.music.spotui.ui.immersive.shell.backdrop.backdrops.rememberLayerBackdrop+import com.music.spotui.ui.immersive.shell.backdrop.drawBackdrop+import com.music.spotui.ui.immersive.shell.backdrop.effects.blur+import com.music.spotui.ui.immersive.shell.backdrop.effects.colorControls+import com.music.spotui.ui.immersive.shell.backdrop.effects.lens+import com.music.spotui.ui.immersive.shell.backdrop.highlight.Highlight+import com.music.spotui.ui.immersive.shell.backdrop.shadow.Shadow+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. */+ AVAILABLE,++ /** The phone asks for less blur (window blurs off, battery saver) or no animation: frosted instead. */+ REDUCED,++ /** Before Android 12 there is no RenderEffect to bend the page with: frosted, and the switch is greyed. */+ UNSUPPORTED,+}++/** See [LiquidGlassAvailability]. Follows the system's blur switch live. */+@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+}++/** 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 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".+ */+@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) }+ }+ return enabled+}++/**+ * The recorded page the Liquid Glass surfaces refract. Provided by the host (App.kt) only while+ * [rememberLiquidGlassActive] is true; null means the bars fall back to Haze's frost. Pages feed+ * it through [immersiveHazeSource], which records the page here as well when it is provided.+ */+val LocalImmersiveBackdrop = compositionLocalOf<LayerBackdrop?> { null }++/** A page recording kept for the lifetime of the calling composition. */+@Composable+fun rememberImmersiveBackdrop(): LayerBackdrop = rememberLayerBackdrop()++/**+ * Where a glass surface composed under it also records the glass it draws (without rim or+ * shadow), so the tab bar's selection lens can refract the bar rather than the page behind it.+ */+internal val LocalGlassExport = compositionLocalOf<LayerBackdrop?> { null }++/**+ * Resolution the glass records and processes its backdrop at: a third, as BitChord (nine times+ * 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++/** 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)++private val GlassShadow = Shadow(radius = 18.dp, color = Color.Black.copy(alpha = 0.22f))++/**+ * 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).+ */+@Composable+internal fun Modifier.immersiveLiquidGlass(+ shape: Shape,+ page: LayerBackdrop,+ tint: Color = GlassTint,+ lens: Boolean = true,+ rim: Boolean = true,+): 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+ 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,+ shadow = if (rim) ({ GlassShadow }) else null,+ onDrawSurface = { drawRect(color = tint, size = size) },+ exportedBackdrop = export,+ backdropScale = GLASS_RESOLUTION_SCALE,+ )+}++/**+ * 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.+ */+internal class PageBackdrop(private val page: LayerBackdrop) : Backdrop {+ override val isCoordinatesDependent: Boolean = true++ override fun DrawScope.drawBackdrop(+ density: Density,+ coordinates: LayoutCoordinates?,+ layerBlock: (GraphicsLayerScope.() -> Unit)?,+ ) {+ val source = page.layerCoordinates+ val usable = coordinates != null && source != null && source.isAttached && coordinates.isAttached &&+ !source.isAncestorOf(coordinates) &&+ source.findRoot() === coordinates.findRoot()+ drawRect(if (usable) Immersive.Page else Immersive.GlassFill, topLeft = FAR_TOP_LEFT, size = FAR_SIZE)+ if (usable) with(page) { drawBackdrop(density, coordinates, layerBlock) }+ }++ private companion object {+ // Past every edge, whatever the scale and padding of the recording.+ val FAR_TOP_LEFT = Offset(-20_000f, -20_000f)+ val FAR_SIZE = Size(40_000f, 40_000f)+ }+}++private fun LayoutCoordinates.findRoot(): LayoutCoordinates {+ var c = this+ while (true) c = c.parentCoordinates ?: return c+}++private fun LayoutCoordinates.isAncestorOf(other: LayoutCoordinates): Boolean {+ var c: LayoutCoordinates? = other+ while (c != null) {+ if (c === this) return true+ c = c.parentCoordinates+ }+ return false+}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.ktnew file mode 100644index 00000000..826bd7fc--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/ImmersiveHaze.kt@@ -0,0 +1,110 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * sharedUi/src/jvmSharedMain/kotlin/com/music/bitchord/ui/components/OptimizedHaze.kt at edc1e6f.+ * Modified for Myspoti, 2026-10.+ */+package com.music.spotui.ui.immersive.shell++import androidx.compose.foundation.background+import androidx.compose.foundation.border+import androidx.compose.runtime.Composable+import androidx.compose.runtime.compositionLocalOf+import androidx.compose.runtime.remember+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.unit.dp+import com.music.spotui.ui.immersive.Immersive+import com.music.spotui.ui.immersive.shell.backdrop.backdrops.LayerBackdrop+import com.music.spotui.ui.immersive.shell.backdrop.backdrops.layerBackdrop+import dev.chrisbanes.haze.ExperimentalHazeApi+import dev.chrisbanes.haze.HazeInputScale+import dev.chrisbanes.haze.HazeState+import dev.chrisbanes.haze.HazeTint+import dev.chrisbanes.haze.hazeEffect+import dev.chrisbanes.haze.hazeSource++/**+ * The page that the frosted bars (tab bar, top bar) blur, provided once by the host:+ *+ * ```+ * val haze = rememberImmersiveHazeState()+ * CompositionLocalProvider(LocalImmersiveHaze provides haze) {+ * Box {+ * NavHost(Modifier.immersiveHazeSource()) { ... } // what scrolls under the bars+ * ImmersiveTabBar(nav, Modifier.align(Alignment.BottomCenter))+ * }+ * }+ * ```+ *+ * Null (the default) means no page is being sampled: the bars then fall back to a plain+ * translucent fill, which is also what they show before the first frame is recorded.+ */+val LocalImmersiveHaze = compositionLocalOf<HazeState?> { null }++/** A [HazeState] kept for the lifetime of the calling composition. */+@Composable+fun rememberImmersiveHazeState(): HazeState = remember { HazeState() }++/**+ * Marks this content as what the frosted bars blur. Put it on the NavHost (or the screen's+ * scrolling content), not on the bars themselves. No-op when no [LocalImmersiveHaze] is provided.+ *+ * While Liquid Glass is on ([LocalImmersiveBackdrop] provided) it also records the content for+ * the glass to refract, so a page that calls this gets both looks with nothing else to do.+ */+@Composable+fun Modifier.immersiveHazeSource(+ state: HazeState? = LocalImmersiveHaze.current,+ backdrop: LayerBackdrop? = LocalImmersiveBackdrop.current,+): Modifier {+ val hazed = if (state == null) this else this.hazeSource(state)+ return if (backdrop == null) hazed else hazed.layerBackdrop(backdrop)+}++/**+ * Keeps Haze's visual style while sampling at a third of the resolution: a blur this wide hides+ * the missing pixels, and the bars are redrawn on every frame of every scroll.+ */+@OptIn(ExperimentalHazeApi::class)+internal fun Modifier.immersiveFrost(+ state: HazeState,+ tint: Color = Immersive.GlassFill.copy(alpha = 0.55f),+ blur: Float = 24f,+): Modifier = hazeEffect(state) {+ inputScale = HazeInputScale.Fixed(0.33f)+ backgroundColor = Immersive.Page+ tints = listOf(HazeTint(tint))+ blurRadius = blur.dp+ noiseFactor = 0f+}++/**+ * The glass of the floating bars: [shape]-clipped frost over the page when one is provided,+ * the translucent [Immersive.GlassFill] when not, and the hairline edge in both cases.+ *+ * With Liquid Glass on (Settings > Display, Android 12+, see [rememberLiquidGlassActive]) and+ * [state] the app's own page ([LocalImmersiveHaze], the default), the same call draws real glass+ * 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 liquid false keeps the frost even while Liquid Glass is on (a surface that would cost+ * too much, or that must stay flat).+ */+@Composable+internal fun Modifier.immersiveGlassSurface(+ shape: Shape,+ state: HazeState? = LocalImmersiveHaze.current,+ liquid: Boolean = true,+): Modifier {+ val page = LocalImmersiveBackdrop.current+ 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+ .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/ImmersiveTabBar.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/ImmersiveTabBar.ktnew file mode 100644index 00000000..0e0696a1--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/ImmersiveTabBar.kt@@ -0,0 +1,264 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * app/src/main/java/com/music/bitchord/ui/components/GlassNavBar.kt at edc1e6f+ * (and app/src/main/java/com/music/bitchord/ui/components/FloatingBottomBar.kt). Modified for Myspoti, 2026-10.+ */+package com.music.spotui.ui.immersive.shell++import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.WindowInsets+import androidx.compose.foundation.layout.asPaddingValues+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.navigationBars+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.union+import androidx.compose.foundation.layout.widthIn+import androidx.compose.foundation.layout.windowInsetsPadding+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.saveable.rememberSaveable+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.res.painterResource+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.TextStyle+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import androidx.navigation.NavController+import androidx.navigation.NavGraph.Companion.findStartDestination+import androidx.navigation.compose.currentBackStackEntryAsState+import com.music.spotui.ui.immersive.Immersive+import com.music.spotui.ui.look.ImmersiveSans+import com.music.spotui.ui.look.rememberReduceMotion+import com.music.spotui.ui.navigation.Routes+import com.music.spotui.ui.navigation.TabReselect++/**+ * The gap between the pill's glass edge and the tabs inside it. Shared with the mini player so+ * the two floating bars measure alike.+ */+internal val PILL_INSET = 6.dp++/**+ * How far the floating bars stand off the bottom edge: the system navigation bar's inset, but+ * never less than a gesture bar's. With the gesture hint switched off that inset is zero and the+ * bar would drop onto the very edge of the screen.+ */+internal val ImmersiveBarInsets: WindowInsets+ @Composable get() = WindowInsets.navigationBars.union(WindowInsets(bottom = GESTURE_BAR_FLOOR))++/** A gesture bar's inset. */+private val GESTURE_BAR_FLOOR = 15.dp++/**+ * Each tab's own vertical padding, the counterweight to [PILL_INSET]: the pill has no height of+ * its own, so the two numbers are a pair — change one and the bar's height moves unless the other+ * moves against it.+ */+private val TAB_VERTICAL_PADDING = 9.dp++/** The gap between a tab's glyph and its label. */+private val TAB_ICON_LABEL_GAP = 2.dp++/** How wide the floating bars are ever allowed to get: on a tablet they stop growing and centre. */+val ImmersiveBarMaxWidth = 440.dp++/**+ * The room [ImmersiveTabBar] takes at the bottom of the screen (its own height, the gap under it+ * and the navigation bar inset). Stack the mini player above this.+ */+@Composable+fun immersiveTabBarHeight(): androidx.compose.ui.unit.Dp =+ TabBarContentHeight + 2.dp + ImmersiveBarInsets.asPaddingValues().calculateBottomPadding()++/** The bar's own height: a 25 dp glyph, the gap, an 11 sp label, the tab padding and the pill inset. */+private val TabBarContentHeight = (PILL_INSET + TAB_VERTICAL_PADDING) * 2 + 25.dp + TAB_ICON_LABEL_GAP + 14.dp++private val TabLabel = TextStyle(+ fontFamily = ImmersiveSans,+ fontSize = 11.sp,+ lineHeight = 14.sp,+ fontWeight = FontWeight.Medium,+)++/**+ * The Immersive look's floating tab bar: a frosted pill with Home and Library, and Search in a+ * circle of its own beside it. The selected tab's pill lifts, travels to the next tab on a spring+ * and settles; a horizontal drag across the pill picks it up the same way.+ *+ * Navigation is exactly [com.music.spotui.ui.navigation.MainBottomNavigation]'s: re-tapping the+ * tab you are on emits [TabReselect] (scroll to top, focus search); from one of its sub-pages it+ * pops back to the tab's root; otherwise it navigates with `popUpTo(start){saveState}`,+ * `launchSingleTop` and `restoreState` (Home always reopens itself). The bar hides itself on the+ * player, queue and SpotiFLAC routes.+ *+ * Usage: put it at the bottom of the app's Box, above the NavHost, and the mini player above it+ * (see [immersiveTabBarHeight]). Provide [LocalImmersiveHaze] and mark the NavHost with+ * [immersiveHazeSource] for the glass to blur the page behind; without it the glass is a plain+ * translucent fill.+ *+ * ```+ * Box(Modifier.fillMaxSize()) {+ * MyNavHost(nav, Modifier.immersiveHazeSource())+ * ImmersiveTabBar(nav, Modifier.align(Alignment.BottomCenter))+ * }+ * ```+ */+@Composable+fun ImmersiveTabBar(navController: NavController, modifier: Modifier = Modifier) {+ val tabs = rememberTabNavigation(navController)+ // No motion of its own: the bar sits above the pages, so sliding it while the player rises+ // (or collapses behind it) made one gesture look like two.+ if (tabs.fullScreen) return+ Box(modifier = modifier.fillMaxWidth(), contentAlignment = Alignment.BottomCenter) {+ TabBarContent(+ selectedTab = tabs.selectedTab,+ onTabClick = tabs.onTabClick,+ modifier = Modifier+ .windowInsetsPadding(ImmersiveBarInsets)+ .padding(horizontal = Immersive.Gutter)+ .padding(bottom = 2.dp)+ .widthIn(max = ImmersiveBarMaxWidth),+ )+ }+}++/** The tab the user is in, how to switch tabs, and whether the bar hides (player, queue). */+internal class TabNavigation(+ val selectedTab: String,+ val onTabClick: (Routes) -> Unit,+ val fullScreen: Boolean,+)++/** The tab bar's navigation, shared by [ImmersiveTabBar] and the minimizing [ImmersiveBottomChrome]. */+@Composable+internal fun rememberTabNavigation(navController: NavController): TabNavigation {+ // Visibility follows the screen actually shown, not flags each screen sets.+ val navStack by navController.currentBackStackEntryAsState()+ val currentRoute = navStack?.destination?.route+ val fullScreen = currentRoute == Routes.Player.route ||+ currentRoute == Routes.Queue.route++ // The tab the user is in, even on one of its sub-pages (album, artist...). Kept whether or+ // not the bar shows, so it survives the bar being hidden on the player.+ var selectedTab by rememberSaveable { mutableStateOf(Routes.Home.route) }+ if (currentRoute in TabRoutes) selectedTab = currentRoute!!++ val onTabClick: (Routes) -> Unit = { item ->+ // Standard bottom-tab navigation: each tab keeps its state (no reload, scroll kept).+ if (item.route == selectedTab) {+ if (currentRoute == item.route) {+ // Already on the tab's own page: nothing to reload, only the re-tap shortcut.+ TabReselect.emit(item.route)+ } else if (!navController.popBackStack(item.route, inclusive = false)) {+ // On one of its sub-pages: back to its root page first.+ navController.navigate(item.route) { launchSingleTop = true }+ }+ } else {+ selectedTab = item.route+ navController.navigate(item.route) {+ popUpTo(navController.graph.findStartDestination().id) { saveState = true }+ launchSingleTop = true+ // Home always opens Home itself (its scroll kept), not the page last left+ // open from it (a playlist, an artist...).+ restoreState = item.route != Routes.Home.route+ }+ }+ }+ return TabNavigation(selectedTab, onTabClick, fullScreen)+}++private val TabRoutes = listOf(Routes.Home.route, Routes.Search.route, Routes.Library.route)++/** The tabs the bar shows. */+internal val TabItems = listOf(Routes.Home, Routes.Library, Routes.Search)++/** The tab bar itself (pill and Search circle), filling the width [modifier] leaves it. */+@Composable+internal fun TabBarContent(+ selectedTab: String,+ onTabClick: (Routes) -> Unit,+ modifier: Modifier,+) {+ // Held for the same reason the content lambda below is keyed: it is captured once per key.+ val currentOnTabClick by androidx.compose.runtime.rememberUpdatedState(onTabClick)+ val pillShape = remember { RoundedCornerShape(percent = 50) }+ val reduceMotion = rememberReduceMotion()++ // A factory, not a value: each of the two surfaces gets its own glass modifier.+ val glassSurface: @Composable () -> Modifier = { Modifier.immersiveGlassSurface(pillShape) }++ Box(modifier = modifier, contentAlignment = Alignment.BottomCenter) {+ FloatingTabBar(+ selectedTabKey = selectedTab,+ modifier = Modifier.fillMaxWidth(),+ tabBarContentModifier = glassSurface,+ colors = FloatingTabBarDefaults.colors(+ backgroundColor = Color.Transparent,+ indicatorColor = Color.White.copy(alpha = 0.12f),+ ),+ sizes = FloatingTabBarDefaults.sizes(+ tabBarContentPadding = PaddingValues(PILL_INSET),+ tabExpandedContentPadding = PaddingValues(vertical = TAB_VERTICAL_PADDING),+ ),+ reduceMotion = reduceMotion,+ contentKey = selectedTab,+ ) {+ // Search is the odd one out: a circle of its own beside the pill.+ listOf(Routes.Home, Routes.Library).forEach { item ->+ val tint = if (selectedTab == item.route) Immersive.Accent else Immersive.Text.copy(alpha = 0.65f)+ tab(+ key = item.route,+ icon = { TabIcon(item, tint) },+ title = {+ Text(+ text = tabLabel(item),+ style = TabLabel,+ color = tint,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ modifier = Modifier.padding(top = TAB_ICON_LABEL_GAP),+ )+ },+ onClick = { currentOnTabClick(item) },+ )+ }+ standaloneTab(+ key = Routes.Search.route,+ icon = {+ TabIcon(+ Routes.Search,+ if (selectedTab == Routes.Search.route) Immersive.Accent else Immersive.Text.copy(alpha = 0.65f),+ )+ },+ onClick = { currentOnTabClick(Routes.Search) },+ )+ }+ }+}++@Composable+private fun tabLabel(item: Routes): String =+ if (item.labelRes != 0) stringResource(item.labelRes) else item.label++@Composable+private fun TabIcon(item: Routes, tint: Color) {+ Icon(+ painter = painterResource(item.icon),+ // The label right below names the tab for TalkBack; the standalone one has none.+ contentDescription = if (item == Routes.Search) tabLabel(item) else null,+ tint = tint,+ modifier = Modifier.size(25.dp),+ )+}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.ktnew file mode 100644index 00000000..55048327--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/ImmersiveTopBar.kt@@ -0,0 +1,437 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * app/src/main/java/com/music/bitchord/ui/components/FrostedTopBar.kt at edc1e6f+ * (the large page heading is from sharedUi/.../ui/screens/HomeScreen.kt). Modified for Myspoti, 2026-10.+ */+package com.music.spotui.ui.immersive.shell++import androidx.compose.animation.animateContentSize+import androidx.compose.animation.core.Spring+import androidx.compose.animation.core.spring+import androidx.compose.foundation.ScrollState+import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.RowScope+import androidx.compose.foundation.layout.WindowInsets+import androidx.compose.foundation.layout.asPaddingValues+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.statusBars+import androidx.compose.foundation.layout.statusBarsPadding+import androidx.compose.foundation.lazy.LazyListScope+import androidx.compose.foundation.lazy.LazyListState+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.automirrored.rounded.KeyboardArrowLeft+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.animation.core.animateDpAsState+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.Composable+import androidx.compose.runtime.CompositionLocalProvider+import androidx.compose.runtime.compositionLocalOf+import androidx.compose.runtime.getValue+import androidx.compose.runtime.remember+import androidx.compose.ui.graphics.RectangleShape+import com.music.spotui.ui.immersive.motion.ImmersiveMotion+import com.music.spotui.ui.look.rememberReduceMotion+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.graphics.vector.ImageVector+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.semantics.Role+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import app.myspoti.engine.R+import com.music.spotui.ui.immersive.Immersive+import dev.chrisbanes.haze.HazeState++/**+ * The bar's own height, above whatever inset it is sitting under. The single source of truth for+ * it: the bar lays itself out to this, and everything that has to clear the bar measures from+ * [immersiveTopBarHeight] rather than from a copy of the number.+ */+val ImmersiveTopBarContentHeight = 52.dp++/** The breathing room between the bar's bottom edge and the first thing under it. */+val ImmersiveTopBarContentGap = 12.dp++/** How much of each end of the bar is spoken for, so a long title truncates instead of running under it. */+private val TitleInset = 64.dp++/** The back and action targets: a 44 dp circle, as the floating controls of the official bars. */+private val BarControlSize = 44.dp++/** The same controls while the chrome is minimized ([LocalImmersiveChrome]): small glass pills. */+private val BarControlSizeMinimized = 34.dp++/**+ * The size of a top bar control right now: 44 dp, shrinking to small pills on a spring while the+ * chrome is minimized. Read by [ImmersiveBarAction]; a custom action in the bar can read it too.+ */+val LocalBarControlSize = compositionLocalOf { BarControlSize }++@Composable+private fun rememberBarControlSize(): Dp {+ val minimized = LocalImmersiveChrome.current?.minimized == true+ val size by animateDpAsState(+ targetValue = if (minimized) BarControlSizeMinimized else BarControlSize,+ animationSpec = ImmersiveMotion.chromeSpring(rememberReduceMotion()),+ label = "immersiveBarControlSize",+ )+ return size+}++/**+ * How far down the window the bar actually ends: the status bar inset it is pinned under, plus+ * its own height. Read at composition because the inset is a property of the device, not the app.+ */+@Composable+fun immersiveTopBarHeight(): Dp =+ WindowInsets.statusBars.asPaddingValues().calculateTopPadding() + ImmersiveTopBarContentHeight++/**+ * Where page content should start: clear of the bar, plus [ImmersiveTopBarContentGap]. Use it as+ * the top `contentPadding` of the page's list so its large title rests just under the bar.+ */+@Composable+fun immersiveTopContentPadding(): Dp = immersiveTopBarHeight() + ImmersiveTopBarContentGap++/**+ * The top bar of an Immersive page: a back chevron and actions on glass circles, and a small+ * centred [title] over a frosted strip — both fade in as [collapse] goes from 0 to 1. At 0 the bar+ * is transparent and the page's own [ImmersiveLargeTitle] is the heading; once the list has+ * scrolled the large title under the bar, the small one and the frost take over.+ *+ * Prefer the overloads taking the page's [LazyListState] or [ScrollState], which work [collapse]+ * out from the scroll offset. Draw it after (above) the scrolling content in a Box, and give the+ * content `immersiveTopContentPadding()` at the top:+ *+ * ```+ * val list = rememberLazyListState()+ * Box(Modifier.fillMaxSize()) {+ * LazyColumn(state = list, contentPadding = PaddingValues(top = immersiveTopContentPadding())) {+ * immersiveLargeTitle("Library")+ * ...+ * }+ * ImmersiveTopBar("Library", list, onBack = { nav.popBackStack() }) {+ * ImmersiveBarAction(Icons.Rounded.Add, "Add", onClick = ::add)+ * }+ * }+ * ```+ *+ * @param collapse 0 = large title showing (bar transparent), 1 = collapsed (small title + frost).+ * Read inside draw layers only, so a scroll does not recompose anything.+ * @param onBack shows the back chevron when set.+ * @param hazeState the page to blur, [LocalImmersiveHaze] by default; null falls back to a solid fill.+ * @param actions trailing controls, laid out in one glass pill; see [ImmersiveBarAction].+ */+@Composable+fun ImmersiveTopBar(+ title: String,+ collapse: () -> Float,+ modifier: Modifier = Modifier,+ onBack: (() -> Unit)? = null,+ hazeState: HazeState? = LocalImmersiveHaze.current,+ actions: (@Composable RowScope.() -> Unit)? = null,+) {+ val page = LocalImmersiveBackdrop.current+ val controlSize = rememberBarControlSize()+ Box(modifier = modifier.fillMaxWidth()) {+ // The frosted strip and its hairline, fading in with the collapse. Behind everything else.+ Box(+ modifier = Modifier+ .matchParentSize()+ .graphicsLayer { alpha = collapse() }+ .then(+ when {+ // Liquid Glass: the same blur, from the page the glass records (no lens on a strip).+ page != null && hazeState != null && hazeState === LocalImmersiveHaze.current ->+ Modifier.immersiveLiquidGlass(RectangleShape, page, tint = Immersive.Page.copy(alpha = 0.55f), lens = false, rim = false)+ hazeState != null -> Modifier.immersiveFrost(hazeState, tint = Immersive.Page.copy(alpha = 0.55f))+ else -> Modifier.background(Immersive.Page.copy(alpha = 0.94f))+ },+ ),+ )+ Box(+ modifier = Modifier+ .align(Alignment.BottomCenter)+ .fillMaxWidth()+ .height(0.5.dp)+ .graphicsLayer { alpha = collapse() }+ .background(Immersive.Separator),+ )++ Box(+ modifier = Modifier+ .fillMaxWidth()+ .statusBarsPadding()+ .height(ImmersiveTopBarContentHeight),+ ) {+ Text(+ text = title,+ style = Immersive.Headline.copy(fontSize = 17.sp, lineHeight = 22.sp, fontWeight = FontWeight.SemiBold),+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ textAlign = TextAlign.Center,+ modifier = Modifier+ .align(Alignment.Center)+ // The same room on both sides: the title is centred within this padded box,+ // so an inset that differs end to end would move it off the bar's centre.+ .padding(horizontal = TitleInset)+ .fillMaxWidth()+ .graphicsLayer { alpha = collapse() },+ )+ if (onBack != null) {+ Box(+ modifier = Modifier+ .align(Alignment.CenterStart)+ .padding(start = Immersive.Gutter)+ .size(controlSize)+ .immersiveGlassSurface(CircleShape, hazeState)+ .clickable(role = Role.Button, onClick = onBack),+ contentAlignment = Alignment.Center,+ ) {+ Icon(+ Icons.AutoMirrored.Rounded.KeyboardArrowLeft,+ contentDescription = stringResource(R.string.immersive_shell_back),+ tint = Immersive.Text,+ modifier = Modifier.size(controlSize * 0.64f),+ )+ }+ }+ if (actions != null) {+ Row(+ modifier = Modifier+ .align(Alignment.CenterEnd)+ .padding(end = Immersive.Gutter)+ .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,+ ),+ ),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ CompositionLocalProvider(LocalBarControlSize provides controlSize) { actions() }+ }+ }+ }+ }+}++/** [ImmersiveTopBar] collapsing as a [LazyListState] scrolls: [collapseDistance] of scroll takes it from 0 to 1. */+@Composable+fun ImmersiveTopBar(+ title: String,+ listState: LazyListState,+ modifier: Modifier = Modifier,+ onBack: (() -> Unit)? = null,+ hazeState: HazeState? = LocalImmersiveHaze.current,+ collapseDistance: Dp = 40.dp,+ actions: (@Composable RowScope.() -> Unit)? = null,+) = ImmersiveTopBar(+ title = title,+ collapse = rememberTopBarCollapse(listState, collapseDistance),+ modifier = modifier,+ onBack = onBack,+ hazeState = hazeState,+ actions = actions,+)++/** [ImmersiveTopBar] collapsing as a [ScrollState] scrolls: [collapseDistance] of scroll takes it from 0 to 1. */+@Composable+fun ImmersiveTopBar(+ title: String,+ scrollState: ScrollState,+ modifier: Modifier = Modifier,+ onBack: (() -> Unit)? = null,+ hazeState: HazeState? = LocalImmersiveHaze.current,+ collapseDistance: Dp = 40.dp,+ actions: (@Composable RowScope.() -> Unit)? = null,+) = ImmersiveTopBar(+ title = title,+ collapse = rememberTopBarCollapse(scrollState, collapseDistance),+ modifier = modifier,+ onBack = onBack,+ hazeState = hazeState,+ actions = actions,+)++/** The collapse fraction (0..1) of a [LazyListState] page: 1 once past the first item. */+@Composable+fun rememberTopBarCollapse(state: LazyListState, distance: Dp = 40.dp): () -> Float {+ val distancePx = with(LocalDensity.current) { distance.toPx() }+ return remember(state, distancePx) {+ val fraction: () -> Float = {+ if (state.firstVisibleItemIndex > 0) 1f+ else (state.firstVisibleItemScrollOffset / distancePx).coerceIn(0f, 1f)+ }+ fraction+ }+}++/** The collapse fraction (0..1) of a [ScrollState] page. */+@Composable+fun rememberTopBarCollapse(state: ScrollState, distance: Dp = 40.dp): () -> Float {+ val distancePx = with(LocalDensity.current) { distance.toPx() }+ return remember(state, distancePx) {+ val fraction: () -> Float = { (state.value / distancePx).coerceIn(0f, 1f) }+ fraction+ }+}++/**+ * One 44 dp icon button for [ImmersiveTopBar]'s `actions` (several share one glass pill).+ *+ * @param tint the glyph colour; [Immersive.Accent] for an active toggle.+ */+@Composable+fun ImmersiveBarAction(+ icon: ImageVector,+ contentDescription: String?,+ onClick: () -> Unit,+ modifier: Modifier = Modifier,+ tint: Color = Immersive.Text,+) {+ val size = LocalBarControlSize.current+ Box(+ modifier = modifier+ .size(size)+ .clip(CircleShape)+ .clickable(role = Role.Button, onClick = onClick),+ contentAlignment = Alignment.Center,+ ) {+ Icon(icon, contentDescription = contentDescription, tint = tint, modifier = Modifier.size(size * 0.5f))+ }+}++/**+ * A page's large heading (the first thing in its list), over the bar's small title that takes+ * over when it has scrolled away. [trailing] sits at the end of the line (a count, a sort button).+ *+ * In a `LazyColumn` use [immersiveLargeTitle]; in a `Column(verticalScroll(...))` put this first.+ */+@Composable+fun ImmersiveLargeTitle(+ title: String,+ modifier: Modifier = Modifier,+ subtitle: String? = null,+ trailing: (@Composable RowScope.() -> Unit)? = null,+) {+ Row(+ modifier = modifier+ .fillMaxWidth()+ .padding(horizontal = Immersive.Gutter, vertical = 8.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Column(Modifier.weight(1f)) {+ Text(+ text = title,+ style = Immersive.LargeTitle,+ maxLines = 2,+ overflow = TextOverflow.Ellipsis,+ )+ if (!subtitle.isNullOrBlank()) {+ Text(+ text = subtitle,+ style = Immersive.Subhead,+ maxLines = 2,+ overflow = TextOverflow.Ellipsis,+ )+ }+ }+ if (trailing != null) {+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.End, content = trailing)+ }+ }+}++/** [ImmersiveLargeTitle] as the next item of a lazy list. */+fun LazyListScope.immersiveLargeTitle(+ title: String,+ subtitle: String? = null,+ trailing: (@Composable RowScope.() -> Unit)? = null,+) {+ item(key = "immersive:large-title", contentType = "immersive:large-title") {+ ImmersiveLargeTitle(title = title, subtitle = subtitle, trailing = trailing)+ }+}++/** The row of [ImmersiveFloatingHeader] under the status bar. */+val ImmersiveHeaderContentHeight = 56.dp++/** The rounded bottom corners of [ImmersiveFloatingHeader]. */+private val HeaderCorner = 26.dp++/**+ * Where a page under [ImmersiveFloatingHeader] should start: just under the glass, with the gap+ * the content needs to read as below it rather than cut by it.+ */+@Composable+fun immersiveHeaderContentPadding(): Dp =+ WindowInsets.statusBars.asPaddingValues().calculateTopPadding() + ImmersiveHeaderContentHeight + 10.dp++/**+ * A tab's heading on floating glass, as Home in Apple Music: the title at the start and the+ * [trailing] controls at the end of one row, on a glass panel pinned to the top of the screen+ * (behind the status bar) with rounded bottom corners. The page scrolls under it, so give the+ * list `immersiveHeaderContentPadding()` at the top and no large title of its own:+ *+ * ```+ * Box(Modifier.fillMaxSize()) {+ * LazyColumn(contentPadding = PaddingValues(top = immersiveHeaderContentPadding()), ...) { ... }+ * ImmersiveFloatingHeader("Home") { ProfileButton() }+ * }+ * ```+ *+ * The glass is [immersiveGlassSurface] (Liquid Glass when it is on, frost otherwise). Controls in+ * [trailing] shrink with the chrome; read [LocalBarControlSize] for their size.+ */+@Composable+fun ImmersiveFloatingHeader(+ title: String,+ modifier: Modifier = Modifier,+ hazeState: HazeState? = LocalImmersiveHaze.current,+ trailing: (@Composable RowScope.() -> Unit)? = null,+) {+ val controlSize = rememberBarControlSize()+ val shape = remember { RoundedCornerShape(bottomStart = HeaderCorner, bottomEnd = HeaderCorner) }+ Box(modifier.fillMaxWidth().immersiveGlassSurface(shape, hazeState)) {+ Row(+ modifier = Modifier+ .fillMaxWidth()+ .statusBarsPadding()+ .height(ImmersiveHeaderContentHeight)+ .padding(start = Immersive.Gutter, end = Immersive.Gutter - 4.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Text(+ text = title,+ style = Immersive.Title,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ modifier = Modifier.weight(1f),+ )+ if (trailing != null) {+ CompositionLocalProvider(LocalBarControlSize provides controlSize) { trailing() }+ }+ }+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/Backdrop.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/Backdrop.ktnew file mode 100644index 00000000..6cf3f736--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/Backdrop.kt@@ -0,0 +1,29 @@+/*+ * Vendored from Kyant0/backdrop v2.0.0 (io.github.kyant0:backdrop)+ * https://github.com/Kyant0/backdrop — Copyright 2025 Kyant0, Apache License 2.0+ *+ * Vendored so the library ships as source with this app (binary AARs compiled+ * against older Compose broke at runtime) and to add a backdrop resolution+ * scale for cheaper effect rendering. KMP expect/actual declarations were+ * merged into this single Android source set. Package renamed accordingly.+ * Myspoti copy taken from BitChord's vendored tree (github.com/kushagrasinghx/BitChord,+ * app/src/main/java/com/music/bitchord/ui/components/backdrop at edc1e6f), which adds+ * backdropScale and exportedBackdrop to drawBackdrop. Package renamed again for Myspoti.+ */+package com.music.spotui.ui.immersive.shell.backdrop++import androidx.compose.ui.graphics.GraphicsLayerScope+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.layout.LayoutCoordinates+import androidx.compose.ui.unit.Density++interface Backdrop {++ val isCoordinatesDependent: Boolean++ fun DrawScope.drawBackdrop(+ density: Density,+ coordinates: LayoutCoordinates?,+ layerBlock: (GraphicsLayerScope.() -> Unit)? = null+ )+}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.ktnew file mode 100644index 00000000..759d8bfa--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/BackdropEffectScope.kt@@ -0,0 +1,89 @@+/*+ * Vendored from Kyant0/backdrop v2.0.0 (io.github.kyant0:backdrop)+ * https://github.com/Kyant0/backdrop — Copyright 2025 Kyant0, Apache License 2.0+ *+ * Vendored so the library ships as source with this app (binary AARs compiled+ * against older Compose broke at runtime) and to add a backdrop resolution+ * scale for cheaper effect rendering. KMP expect/actual declarations were+ * merged into this single Android source set. Package renamed accordingly.+ * Myspoti copy taken from BitChord's vendored tree (github.com/kushagrasinghx/BitChord,+ * app/src/main/java/com/music/bitchord/ui/components/backdrop at edc1e6f), which adds+ * backdropScale and exportedBackdrop to drawBackdrop. Package renamed again for Myspoti.+ */+package com.music.spotui.ui.immersive.shell.backdrop++import androidx.compose.ui.geometry.Size+import androidx.compose.ui.graphics.RenderEffect+import androidx.compose.ui.graphics.Shape+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.unit.Density+import androidx.compose.ui.unit.LayoutDirection++sealed interface BackdropEffectScope : Density, RuntimeShaderCache {++ val size: Size++ val layoutDirection: LayoutDirection++ val shape: Shape++ var padding: Float++ var renderEffect: RenderEffect?+}++internal abstract class BackdropEffectScopeImpl : BackdropEffectScope, RuntimeShaderCache {++ override var density: Float = 1f+ override var fontScale: Float = 1f+ override var size: Size = Size.Unspecified+ override var layoutDirection: LayoutDirection = LayoutDirection.Ltr+ override var padding: Float = 0f+ override var renderEffect: RenderEffect? = null++ private val runtimeShaderCache = RuntimeShaderCacheImpl()++ override fun obtainRuntimeShader(key: String, string: String): RuntimeShader {+ return runtimeShaderCache.obtainRuntimeShader(key, string)+ }++ // Vendored change: [contentScale] reports the size the effects actually operate+ // on when the backdrop layer is recorded at a reduced resolution, so shader+ // geometry (e.g. the lens size uniform) matches the layer's pixel grid.+ fun update(scope: DrawScope, contentScale: Float = 1f): Boolean {+ val newDensity = scope.density+ val newFontScale = scope.fontScale+ val newSize = if (contentScale != 1f) scope.size * contentScale else scope.size+ val newLayoutDirection = scope.layoutDirection++ val changed = newDensity != density ||+ newFontScale != fontScale ||+ newSize != size ||+ newLayoutDirection != layoutDirection++ if (changed) {+ density = newDensity+ fontScale = newFontScale+ size = newSize+ layoutDirection = newLayoutDirection+ }++ return changed+ }++ fun apply(effects: BackdropEffectScope.() -> Unit) {+ padding = 0f+ renderEffect = null+ effects()+ }++ fun reset() {+ density = 1f+ fontScale = 1f+ size = Size.Unspecified+ layoutDirection = LayoutDirection.Ltr+ padding = 0f+ renderEffect = null+ runtimeShaderCache.clear()+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/DrawBackdropModifier.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/DrawBackdropModifier.ktnew file mode 100644index 00000000..0fcc3d9d--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/DrawBackdropModifier.kt@@ -0,0 +1,447 @@+/*+ * Vendored from Kyant0/backdrop v2.0.0 (io.github.kyant0:backdrop)+ * https://github.com/Kyant0/backdrop — Copyright 2025 Kyant0, Apache License 2.0+ *+ * Vendored so the library ships as source with this app (binary AARs compiled+ * against older Compose broke at runtime) and to add a backdrop resolution+ * scale for cheaper effect rendering. KMP expect/actual declarations were+ * merged into this single Android source set. Package renamed accordingly.+ * Myspoti copy taken from BitChord's vendored tree (github.com/kushagrasinghx/BitChord,+ * app/src/main/java/com/music/bitchord/ui/components/backdrop at edc1e6f), which adds+ * backdropScale and exportedBackdrop to drawBackdrop. Package renamed again for Myspoti.+ */+package com.music.spotui.ui.immersive.shell.backdrop++import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableFloatStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.neverEqualPolicy+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.graphics.GraphicsLayerScope+import androidx.compose.ui.graphics.Shape+import androidx.compose.ui.graphics.drawscope.ContentDrawScope+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.graphics.drawscope.scale+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.graphics.layer.GraphicsLayer+import androidx.compose.ui.graphics.layer.drawLayer+import androidx.compose.ui.layout.LayoutCoordinates+import androidx.compose.ui.layout.Measurable+import androidx.compose.ui.layout.MeasureResult+import androidx.compose.ui.layout.MeasureScope+import androidx.compose.ui.node.DrawModifierNode+import androidx.compose.ui.node.GlobalPositionAwareModifierNode+import androidx.compose.ui.node.LayoutModifierNode+import androidx.compose.ui.node.ModifierNodeElement+import androidx.compose.ui.node.ObserverModifierNode+import androidx.compose.ui.node.observeReads+import androidx.compose.ui.node.requireGraphicsContext+import androidx.compose.ui.platform.InspectorInfo+import androidx.compose.ui.unit.Constraints+import androidx.compose.ui.unit.IntOffset+import androidx.compose.ui.unit.IntSize+import com.music.spotui.ui.immersive.shell.backdrop.backdrops.LayerBackdrop+import com.music.spotui.ui.immersive.shell.backdrop.highlight.Highlight+import com.music.spotui.ui.immersive.shell.backdrop.highlight.HighlightElement+import com.music.spotui.ui.immersive.shell.backdrop.internal.ShapeProvider+import com.music.spotui.ui.immersive.shell.backdrop.internal.recordLayer+import com.music.spotui.ui.immersive.shell.backdrop.shadow.InnerShadow+import com.music.spotui.ui.immersive.shell.backdrop.shadow.InnerShadowElement+import com.music.spotui.ui.immersive.shell.backdrop.shadow.Shadow+import com.music.spotui.ui.immersive.shell.backdrop.shadow.ShadowElement++private val DefaultHighlight = { Highlight.Default }+private val DefaultShadow = { Shadow.Default }+private val DefaultOnDrawBackdrop: DrawScope.(DrawScope.() -> Unit) -> Unit = { it() }++fun Modifier.drawPlainBackdrop(+ backdrop: Backdrop,+ shape: () -> Shape,+ effects: BackdropEffectScope.() -> Unit,+ layerBlock: (GraphicsLayerScope.() -> Unit)? = null,+ exportedBackdrop: LayerBackdrop? = null,+ onDrawBehind: (DrawScope.() -> Unit)? = null,+ onDrawBackdrop: DrawScope.(drawBackdrop: DrawScope.() -> Unit) -> Unit = DefaultOnDrawBackdrop,+ onDrawSurface: (DrawScope.() -> Unit)? = null,+ onDrawFront: (DrawScope.() -> Unit)? = null+): Modifier {+ val shapeProvider = ShapeProvider(shape)+ return this+ .then(+ if (layerBlock != null) {+ Modifier.graphicsLayer(layerBlock)+ } else {+ Modifier+ }+ )+ .then(+ DrawBackdropElement(+ backdrop = backdrop,+ shapeProvider = shapeProvider,+ effects = effects,+ layerBlock = layerBlock,+ exportedBackdrop = exportedBackdrop,+ onDrawBehind = onDrawBehind,+ onDrawBackdrop = onDrawBackdrop,+ onDrawSurface = onDrawSurface,+ onDrawFront = onDrawFront,+ backdropScale = 1f+ )+ )+}++fun Modifier.drawBackdrop(+ backdrop: Backdrop,+ shape: () -> Shape,+ effects: BackdropEffectScope.() -> Unit,+ highlight: (() -> Highlight?)? = DefaultHighlight,+ shadow: (() -> Shadow?)? = DefaultShadow,+ innerShadow: (() -> InnerShadow?)? = null,+ layerBlock: (GraphicsLayerScope.() -> Unit)? = null,+ exportedBackdrop: LayerBackdrop? = null,+ onDrawBehind: (DrawScope.() -> Unit)? = null,+ onDrawBackdrop: DrawScope.(drawBackdrop: DrawScope.() -> Unit) -> Unit = DefaultOnDrawBackdrop,+ onDrawSurface: (DrawScope.() -> Unit)? = null,+ onDrawFront: (DrawScope.() -> Unit)? = null,+ // Vendored addition: records the backdrop into a layer at this fraction of the+ // surface resolution and draws it scaled back up, so the RenderEffect chain+ // processes far fewer pixels. Pixel-sized effect parameters (blur radius, lens+ // refraction) must be pre-multiplied by the same factor by the caller; the blur+ // hides the upscaling. 1f keeps the original full resolution behavior.+ backdropScale: Float = 1f+): Modifier {+ val shapeProvider = ShapeProvider(shape)+ return this+ .then(+ if (layerBlock != null) {+ Modifier.graphicsLayer(layerBlock)+ } else {+ Modifier+ }+ )+ .then(+ if (innerShadow != null) {+ InnerShadowElement(+ shapeProvider = shapeProvider,+ shadow = innerShadow+ )+ } else {+ Modifier+ }+ )+ .then(+ if (shadow != null) {+ ShadowElement(+ shapeProvider = shapeProvider,+ shadow = shadow+ )+ } else {+ Modifier+ }+ )+ .then(+ if (highlight != null) {+ HighlightElement(+ shapeProvider = shapeProvider,+ highlight = highlight+ )+ } else {+ Modifier+ }+ )+ .then(+ DrawBackdropElement(+ backdrop = backdrop,+ shapeProvider = shapeProvider,+ effects = effects,+ layerBlock = layerBlock,+ exportedBackdrop = exportedBackdrop,+ onDrawBehind = onDrawBehind,+ onDrawBackdrop = onDrawBackdrop,+ onDrawSurface = onDrawSurface,+ onDrawFront = onDrawFront,+ backdropScale = backdropScale.coerceIn(0.05f, 1f)+ )+ )+}++private class DrawBackdropElement(+ val backdrop: Backdrop,+ val shapeProvider: ShapeProvider,+ val effects: BackdropEffectScope.() -> Unit,+ val layerBlock: (GraphicsLayerScope.() -> Unit)?,+ val exportedBackdrop: LayerBackdrop?,+ val onDrawBehind: (DrawScope.() -> Unit)?,+ val onDrawBackdrop: DrawScope.(drawBackdrop: DrawScope.() -> Unit) -> Unit,+ val onDrawSurface: (DrawScope.() -> Unit)?,+ val onDrawFront: (DrawScope.() -> Unit)?,+ val backdropScale: Float+) : ModifierNodeElement<DrawBackdropNode>() {++ override fun create(): DrawBackdropNode {+ return DrawBackdropNode(+ backdrop = backdrop,+ shapeProvider = shapeProvider,+ effects = effects,+ layerBlock = layerBlock,+ exportedBackdrop = exportedBackdrop,+ onDrawBehind = onDrawBehind,+ onDrawBackdrop = onDrawBackdrop,+ onDrawSurface = onDrawSurface,+ onDrawFront = onDrawFront,+ backdropScale = backdropScale+ )+ }++ override fun update(node: DrawBackdropNode) {+ node.backdrop = backdrop+ node.shapeProvider = shapeProvider+ node.effects = effects+ node.layerBlock = layerBlock+ if (node.exportedBackdrop != exportedBackdrop) {+ node.exportedBackdrop?.layerCoordinates = null+ node.exportedBackdrop = exportedBackdrop+ }+ node.onDrawBehind = onDrawBehind+ node.onDrawBackdrop = onDrawBackdrop+ node.onDrawSurface = onDrawSurface+ node.onDrawFront = onDrawFront+ node.backdropScale = backdropScale+ node.invalidateDrawCache()+ }++ override fun InspectorInfo.inspectableProperties() {+ name = "drawBackdrop"+ properties["backdrop"] = backdrop+ properties["shapeProvider"] = shapeProvider+ properties["effects"] = effects+ properties["layerBlock"] = layerBlock+ properties["exportedBackdrop"] = exportedBackdrop+ properties["onDrawBehind"] = onDrawBehind+ properties["onDrawBackdrop"] = onDrawBackdrop+ properties["onDrawSurface"] = onDrawSurface+ properties["onDrawFront"] = onDrawFront+ }++ override fun equals(other: Any?): Boolean {+ if (this === other) return true+ if (other !is DrawBackdropElement) return false++ if (backdrop != other.backdrop) return false+ if (shapeProvider != other.shapeProvider) return false+ if (effects != other.effects) return false+ if (layerBlock != other.layerBlock) return false+ if (exportedBackdrop != other.exportedBackdrop) return false+ if (onDrawBehind != other.onDrawBehind) return false+ if (onDrawBackdrop != other.onDrawBackdrop) return false+ if (onDrawSurface != other.onDrawSurface) return false+ if (onDrawFront != other.onDrawFront) return false+ if (backdropScale != other.backdropScale) return false++ return true+ }++ override fun hashCode(): Int {+ var result = backdrop.hashCode()+ result = 31 * result + shapeProvider.hashCode()+ result = 31 * result + effects.hashCode()+ result = 31 * result + (layerBlock?.hashCode() ?: 0)+ result = 31 * result + (exportedBackdrop?.hashCode() ?: 0)+ result = 31 * result + (onDrawBehind?.hashCode() ?: 0)+ result = 31 * result + onDrawBackdrop.hashCode()+ result = 31 * result + (onDrawSurface?.hashCode() ?: 0)+ result = 31 * result + (onDrawFront?.hashCode() ?: 0)+ result = 31 * result + backdropScale.hashCode()+ return result+ }+}++private class DrawBackdropNode(+ var backdrop: Backdrop,+ var shapeProvider: ShapeProvider,+ var effects: BackdropEffectScope.() -> Unit,+ var layerBlock: (GraphicsLayerScope.() -> Unit)?,+ var exportedBackdrop: LayerBackdrop?,+ var onDrawBehind: (DrawScope.() -> Unit)?,+ var onDrawBackdrop: DrawScope.(drawBackdrop: DrawScope.() -> Unit) -> Unit,+ var onDrawSurface: (DrawScope.() -> Unit)?,+ var onDrawFront: (DrawScope.() -> Unit)?,+ var backdropScale: Float+) : LayoutModifierNode, DrawModifierNode, GlobalPositionAwareModifierNode, ObserverModifierNode, Modifier.Node() {++ private val effectScope =+ object : BackdropEffectScopeImpl() {++ override val shape: Shape get() = shapeProvider.innerShape+ }++ private var graphicsLayer: GraphicsLayer? = null++ private val layoutLayerBlock: GraphicsLayerScope.() -> Unit = {+ clip = true+ shape = shapeProvider.shape+ compositingStrategy = androidx.compose.ui.graphics.CompositingStrategy.Offscreen+ }++ private var layoutCoordinates: LayoutCoordinates? by mutableStateOf(null, neverEqualPolicy())++ private var padding by mutableFloatStateOf(0f)++ private val recordBackdropBlock: (DrawScope.() -> Unit) = {+ val canvas = drawContext.canvas+ val padding = padding+ val scale = backdropScale++ if (padding != 0f) {+ canvas.translate(padding, padding)+ }+ // Vendored addition: draw the backdrop content downscaled so the recorded+ // layer (and therefore the RenderEffect chain) covers fewer pixels.+ if (scale != 1f) {+ canvas.scale(scale, scale)+ }+ onDrawBackdrop {+ with(backdrop) {+ drawBackdrop(+ density = effectScope,+ coordinates = layoutCoordinates,+ layerBlock = layerBlock+ )+ }+ }+ if (scale != 1f) {+ canvas.scale(1f / scale, 1f / scale)+ }+ if (padding != 0f) {+ canvas.translate(-padding, -padding)+ }+ }++ private val drawBackdropLayer: DrawScope.() -> Unit = {+ val layer = graphicsLayer+ if (layer != null) {+ val padding = padding+ val scale = backdropScale++ recordLayer(+ this@DrawBackdropNode,+ layer,+ size = IntSize(+ ((size.width * scale).toInt() + padding.toInt() * 2).coerceAtLeast(1),+ ((size.height * scale).toInt() + padding.toInt() * 2).coerceAtLeast(1)+ ),+ block = recordBackdropBlock+ )++ layer.topLeft =+ if (padding != 0f) IntOffset(-padding.toInt(), -padding.toInt())+ else IntOffset.Zero+ drawRecordedBackdrop()+ }+ }++ // Vendored change: the export below draws the layer this frame already+ // recorded, rather than recording the backdrop a second time. Upstream+ // re-runs the whole capture and effect chain for the export, which doubles+ // the surface's cost on every frame it is exported.+ private val drawRecordedBackdrop: DrawScope.() -> Unit = {+ val layer = graphicsLayer+ if (layer != null) {+ val scale = backdropScale+ if (scale != 1f) {+ // Vendored addition: stretch the low resolution layer back over the+ // full surface; the blur in the effect chain masks the upscaling.+ scale(1f / scale, pivot = Offset.Zero) {+ drawLayer(layer)+ }+ } else {+ drawLayer(layer)+ }+ }+ }++ override fun MeasureScope.measure(+ measurable: Measurable,+ constraints: Constraints+ ): MeasureResult {+ val placeable = measurable.measure(constraints)+ return layout(placeable.width, placeable.height) {+ placeable.placeWithLayer(IntOffset.Zero, layerBlock = layoutLayerBlock)+ }+ }++ override fun ContentDrawScope.draw() {+ if (effectScope.update(this, backdropScale)) {+ updateEffects()+ }++ onDrawBehind?.invoke(this)+ drawBackdropLayer()+ onDrawSurface?.invoke(this)+ drawContent()+ onDrawFront?.invoke(this)++ exportedBackdrop?.graphicsLayer?.let { layer ->+ recordLayer(this@DrawBackdropNode, layer) {+ onDrawBehind?.invoke(this)+ drawRecordedBackdrop()+ onDrawSurface?.invoke(this)+ onDrawFront?.invoke(this)+ }+ }+ }++ override fun onGloballyPositioned(coordinates: LayoutCoordinates) {+ if (coordinates.isAttached) {+ if (backdrop.isCoordinatesDependent) {+ layoutCoordinates = coordinates+ } else {+ if (layoutCoordinates != null) {+ layoutCoordinates = null+ }+ }+ exportedBackdrop?.layerCoordinates = coordinates+ }+ }++ override fun onObservedReadsChanged() {+ invalidateDrawCache()+ }++ fun invalidateDrawCache() {+ observeEffects()+ }++ private fun observeEffects() {+ observeReads { updateEffects() }+ }++ private fun updateEffects() {+ if (!isRenderEffectSupported()) return++ effectScope.apply(effects)+ graphicsLayer?.renderEffect = effectScope.renderEffect+ padding = effectScope.padding+ }++ override fun onAttach() {+ val graphicsContext = requireGraphicsContext()+ graphicsLayer = graphicsContext.createGraphicsLayer()++ observeEffects()+ }++ override fun onDetach() {+ val graphicsContext = requireGraphicsContext()+ graphicsLayer?.let { layer ->+ graphicsContext.releaseGraphicsLayer(layer)+ graphicsLayer = null+ }++ effectScope.reset()+ layoutCoordinates = null+ exportedBackdrop?.layerCoordinates = null+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/Platform.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/Platform.ktnew file mode 100644index 00000000..99ff6f82--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/Platform.kt@@ -0,0 +1,22 @@+/*+ * Vendored from Kyant0/backdrop v2.0.0 (io.github.kyant0:backdrop)+ * https://github.com/Kyant0/backdrop — Copyright 2025 Kyant0, Apache License 2.0+ *+ * Vendored so the library ships as source with this app (binary AARs compiled+ * against older Compose broke at runtime) and to add a backdrop resolution+ * scale for cheaper effect rendering. KMP expect/actual declarations were+ * merged into this single Android source set. Package renamed accordingly.+ * Myspoti copy taken from BitChord's vendored tree (github.com/kushagrasinghx/BitChord,+ * app/src/main/java/com/music/bitchord/ui/components/backdrop at edc1e6f), which adds+ * backdropScale and exportedBackdrop to drawBackdrop. Package renamed again for Myspoti.+ */+package com.music.spotui.ui.immersive.shell.backdrop++import android.os.Build+import androidx.annotation.ChecksSdkIntAtLeast++@ChecksSdkIntAtLeast(Build.VERSION_CODES.S)+fun isRenderEffectSupported(): Boolean = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S++@ChecksSdkIntAtLeast(Build.VERSION_CODES.TIRAMISU)+fun isRuntimeShaderSupported(): Boolean = Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISUdiff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/RuntimeShader.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/RuntimeShader.ktnew file mode 100644index 00000000..71fc8314--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/RuntimeShader.kt@@ -0,0 +1,99 @@+/*+ * Vendored from Kyant0/backdrop v2.0.0 (io.github.kyant0:backdrop)+ * https://github.com/Kyant0/backdrop — Copyright 2025 Kyant0, Apache License 2.0+ *+ * Vendored so the library ships as source with this app (binary AARs compiled+ * against older Compose broke at runtime) and to add a backdrop resolution+ * scale for cheaper effect rendering. KMP expect/actual declarations were+ * merged into this single Android source set. Package renamed accordingly.+ * Myspoti copy taken from BitChord's vendored tree (github.com/kushagrasinghx/BitChord,+ * app/src/main/java/com/music/bitchord/ui/components/backdrop at edc1e6f), which adds+ * backdropScale and exportedBackdrop to drawBackdrop. Package renamed again for Myspoti.+ */+package com.music.spotui.ui.immersive.shell.backdrop++import android.os.Build+import androidx.annotation.RequiresApi+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.Shader+import androidx.compose.ui.graphics.toArgb+import org.intellij.lang.annotations.Language++@RequiresApi(Build.VERSION_CODES.TIRAMISU)+fun RuntimeShader(@Language("AGSL") shaderString: String): RuntimeShader {+ val shader = android.graphics.RuntimeShader(shaderString)+ return AndroidRuntimeShader(shader)+}++fun RuntimeShader.asComposeShader(): Shader {+ return this.asAndroidRuntimeShader()+}++fun RuntimeShader.asAndroidRuntimeShader(): android.graphics.RuntimeShader {+ return (this as AndroidRuntimeShader).shader+}++@RequiresApi(Build.VERSION_CODES.TIRAMISU)+internal class AndroidRuntimeShader(val shader: android.graphics.RuntimeShader) : RuntimeShader {++ override fun setFloatUniform(name: String, value: Float) {+ shader.setFloatUniform(name, value)+ }++ override fun setFloatUniform(name: String, value1: Float, value2: Float) {+ shader.setFloatUniform(name, value1, value2)+ }++ override fun setFloatUniform(name: String, value1: Float, value2: Float, value3: Float) {+ shader.setFloatUniform(name, value1, value2, value3)+ }++ override fun setFloatUniform(name: String, value1: Float, value2: Float, value3: Float, value4: Float) {+ shader.setFloatUniform(name, value1, value2, value3, value4)+ }++ override fun setFloatUniform(name: String, values: FloatArray) {+ shader.setFloatUniform(name, values)+ }++ override fun setIntUniform(name: String, value: Int) {+ shader.setIntUniform(name, value)+ }++ override fun setIntUniform(name: String, value1: Int, value2: Int) {+ shader.setIntUniform(name, value1, value2)+ }++ override fun setIntUniform(name: String, value1: Int, value2: Int, value3: Int) {+ shader.setIntUniform(name, value1, value2, value3)+ }++ override fun setIntUniform(name: String, value1: Int, value2: Int, value3: Int, value4: Int) {+ shader.setIntUniform(name, value1, value2, value3, value4)+ }++ override fun setIntUniform(name: String, values: IntArray) {+ shader.setIntUniform(name, values)+ }++ override fun setColorUniform(name: String, color: Color) {+ shader.setColorUniform(name, color.toArgb())+ }+}++interface RuntimeShader {++ fun setFloatUniform(name: String, value: Float)+ fun setFloatUniform(name: String, value1: Float, value2: Float)+ fun setFloatUniform(name: String, value1: Float, value2: Float, value3: Float)+ fun setFloatUniform(name: String, value1: Float, value2: Float, value3: Float, value4: Float)+ fun setFloatUniform(name: String, values: FloatArray)++ fun setIntUniform(name: String, value: Int)+ fun setIntUniform(name: String, value1: Int, value2: Int)+ fun setIntUniform(name: String, value1: Int, value2: Int, value3: Int)+ fun setIntUniform(name: String, value1: Int, value2: Int, value3: Int, value4: Int)+ fun setIntUniform(name: String, values: IntArray)++ fun setColorUniform(name: String, color: Color)+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/RuntimeShaderCache.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/RuntimeShaderCache.ktnew file mode 100644index 00000000..bf9b3b55--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/RuntimeShaderCache.kt@@ -0,0 +1,33 @@+/*+ * Vendored from Kyant0/backdrop v2.0.0 (io.github.kyant0:backdrop)+ * https://github.com/Kyant0/backdrop — Copyright 2025 Kyant0, Apache License 2.0+ *+ * Vendored so the library ships as source with this app (binary AARs compiled+ * against older Compose broke at runtime) and to add a backdrop resolution+ * scale for cheaper effect rendering. KMP expect/actual declarations were+ * merged into this single Android source set. Package renamed accordingly.+ * Myspoti copy taken from BitChord's vendored tree (github.com/kushagrasinghx/BitChord,+ * app/src/main/java/com/music/bitchord/ui/components/backdrop at edc1e6f), which adds+ * backdropScale and exportedBackdrop to drawBackdrop. Package renamed again for Myspoti.+ */+package com.music.spotui.ui.immersive.shell.backdrop++import org.intellij.lang.annotations.Language++sealed interface RuntimeShaderCache {++ fun obtainRuntimeShader(key: String, @Language("AGSL") string: String): RuntimeShader+}++internal class RuntimeShaderCacheImpl : RuntimeShaderCache {++ private val runtimeShaders = mutableMapOf<String, RuntimeShader>()++ override fun obtainRuntimeShader(key: String, string: String): RuntimeShader {+ return runtimeShaders.getOrPut(key) { RuntimeShader(string) }+ }++ fun clear() {+ runtimeShaders.clear()+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/backdrops/Backdrop.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/backdrops/Backdrop.ktnew file mode 100644index 00000000..faa6296f--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/backdrops/Backdrop.kt@@ -0,0 +1,49 @@+/*+ * Vendored from Kyant0/backdrop v2.0.0 (io.github.kyant0:backdrop)+ * https://github.com/Kyant0/backdrop — Copyright 2025 Kyant0, Apache License 2.0+ *+ * Vendored so the library ships as source with this app (binary AARs compiled+ * against older Compose broke at runtime) and to add a backdrop resolution+ * scale for cheaper effect rendering. KMP expect/actual declarations were+ * merged into this single Android source set. Package renamed accordingly.+ * Myspoti copy taken from BitChord's vendored tree (github.com/kushagrasinghx/BitChord,+ * app/src/main/java/com/music/bitchord/ui/components/backdrop at edc1e6f), which adds+ * backdropScale and exportedBackdrop to drawBackdrop. Package renamed again for Myspoti.+ */+package com.music.spotui.ui.immersive.shell.backdrop.backdrops++import androidx.compose.runtime.Composable+import androidx.compose.runtime.Immutable+import androidx.compose.runtime.remember+import androidx.compose.ui.graphics.GraphicsLayerScope+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.layout.LayoutCoordinates+import androidx.compose.ui.unit.Density+import com.music.spotui.ui.immersive.shell.backdrop.Backdrop++@Composable+fun rememberBackdrop(+ backdrop: Backdrop,+ onDraw: DrawScope.(drawBackdrop: DrawScope.() -> Unit) -> Unit+): Backdrop {+ return remember(backdrop, onDraw) {+ Backdrop(backdrop, onDraw)+ }+}++@Immutable+private class Backdrop(+ val backdrop: Backdrop,+ val onDraw: DrawScope.(drawBackdrop: DrawScope.() -> Unit) -> Unit+) : Backdrop {++ override val isCoordinatesDependent: Boolean = backdrop.isCoordinatesDependent++ override fun DrawScope.drawBackdrop(+ density: Density,+ coordinates: LayoutCoordinates?,+ layerBlock: (GraphicsLayerScope.() -> Unit)?+ ) {+ onDraw { with(backdrop) { drawBackdrop(density, coordinates, layerBlock) } }+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/backdrops/CanvasBackdrop.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/backdrops/CanvasBackdrop.ktnew file mode 100644index 00000000..b2cecd84--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/backdrops/CanvasBackdrop.kt@@ -0,0 +1,47 @@+/*+ * Vendored from Kyant0/backdrop v2.0.0 (io.github.kyant0:backdrop)+ * https://github.com/Kyant0/backdrop — Copyright 2025 Kyant0, Apache License 2.0+ *+ * Vendored so the library ships as source with this app (binary AARs compiled+ * against older Compose broke at runtime) and to add a backdrop resolution+ * scale for cheaper effect rendering. KMP expect/actual declarations were+ * merged into this single Android source set. Package renamed accordingly.+ * Myspoti copy taken from BitChord's vendored tree (github.com/kushagrasinghx/BitChord,+ * app/src/main/java/com/music/bitchord/ui/components/backdrop at edc1e6f), which adds+ * backdropScale and exportedBackdrop to drawBackdrop. Package renamed again for Myspoti.+ */+package com.music.spotui.ui.immersive.shell.backdrop.backdrops++import androidx.compose.runtime.Composable+import androidx.compose.runtime.Immutable+import androidx.compose.runtime.remember+import androidx.compose.ui.graphics.GraphicsLayerScope+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.layout.LayoutCoordinates+import androidx.compose.ui.unit.Density+import com.music.spotui.ui.immersive.shell.backdrop.Backdrop++@Composable+fun rememberCanvasBackdrop(+ onDraw: DrawScope.() -> Unit+): Backdrop {+ return remember(onDraw) {+ CanvasBackdrop(onDraw)+ }+}++@Immutable+private class CanvasBackdrop(+ val onDraw: DrawScope.() -> Unit+) : Backdrop {++ override val isCoordinatesDependent: Boolean = false++ override fun DrawScope.drawBackdrop(+ density: Density,+ coordinates: LayoutCoordinates?,+ layerBlock: (GraphicsLayerScope.() -> Unit)?+ ) {+ onDraw()+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/backdrops/CombinedBackdrop.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/backdrops/CombinedBackdrop.ktnew file mode 100644index 00000000..53bb023b--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/backdrops/CombinedBackdrop.kt@@ -0,0 +1,111 @@+/*+ * Vendored from Kyant0/backdrop v2.0.0 (io.github.kyant0:backdrop)+ * https://github.com/Kyant0/backdrop — Copyright 2025 Kyant0, Apache License 2.0+ *+ * Vendored so the library ships as source with this app (binary AARs compiled+ * against older Compose broke at runtime) and to add a backdrop resolution+ * scale for cheaper effect rendering. KMP expect/actual declarations were+ * merged into this single Android source set. Package renamed accordingly.+ * Myspoti copy taken from BitChord's vendored tree (github.com/kushagrasinghx/BitChord,+ * app/src/main/java/com/music/bitchord/ui/components/backdrop at edc1e6f), which adds+ * backdropScale and exportedBackdrop to drawBackdrop. Package renamed again for Myspoti.+ */+package com.music.spotui.ui.immersive.shell.backdrop.backdrops++import androidx.compose.runtime.Composable+import androidx.compose.runtime.Immutable+import androidx.compose.runtime.remember+import androidx.compose.ui.graphics.GraphicsLayerScope+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.layout.LayoutCoordinates+import androidx.compose.ui.unit.Density+import com.music.spotui.ui.immersive.shell.backdrop.Backdrop++@Composable+fun rememberCombinedBackdrop(+ backdrop1: Backdrop,+ backdrop2: Backdrop+): Backdrop {+ return remember(backdrop1, backdrop2) {+ Combined2Backdrops(backdrop1, backdrop2)+ }+}++@Composable+fun rememberCombinedBackdrop(+ backdrop1: Backdrop,+ backdrop2: Backdrop,+ backdrop3: Backdrop+): Backdrop {+ return remember(backdrop1, backdrop2, backdrop3) {+ Combined3Backdrops(backdrop1, backdrop2, backdrop3)+ }+}++@Composable+fun rememberCombinedBackdrop(vararg backdrops: Backdrop): Backdrop {+ return remember(*backdrops) {+ CombinedBackdrops(*backdrops)+ }+}++@Immutable+private class Combined2Backdrops(+ val backdrop1: Backdrop,+ val backdrop2: Backdrop+) : Backdrop {++ override val isCoordinatesDependent: Boolean =+ backdrop1.isCoordinatesDependent || backdrop2.isCoordinatesDependent++ override fun DrawScope.drawBackdrop(+ density: Density,+ coordinates: LayoutCoordinates?,+ layerBlock: (GraphicsLayerScope.() -> Unit)?+ ) {+ with(backdrop1) { drawBackdrop(density, coordinates, layerBlock) }+ with(backdrop2) { drawBackdrop(density, coordinates, layerBlock) }+ }+}++@Immutable+private class Combined3Backdrops(+ val backdrop1: Backdrop,+ val backdrop2: Backdrop,+ val backdrop3: Backdrop+) : Backdrop {++ override val isCoordinatesDependent: Boolean =+ backdrop1.isCoordinatesDependent ||+ backdrop2.isCoordinatesDependent ||+ backdrop3.isCoordinatesDependent++ override fun DrawScope.drawBackdrop(+ density: Density,+ coordinates: LayoutCoordinates?,+ layerBlock: (GraphicsLayerScope.() -> Unit)?+ ) {+ with(backdrop1) { drawBackdrop(density, coordinates, layerBlock) }+ with(backdrop2) { drawBackdrop(density, coordinates, layerBlock) }+ with(backdrop3) { drawBackdrop(density, coordinates, layerBlock) }+ }+}++@Immutable+private class CombinedBackdrops(+ vararg val backdrops: Backdrop+) : Backdrop {++ override val isCoordinatesDependent: Boolean =+ backdrops.any { it.isCoordinatesDependent }++ override fun DrawScope.drawBackdrop(+ density: Density,+ coordinates: LayoutCoordinates?,+ layerBlock: (GraphicsLayerScope.() -> Unit)?+ ) {+ backdrops.forEach { backdrop ->+ with(backdrop) { drawBackdrop(density, coordinates, layerBlock) }+ }+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/backdrops/EmptyBackdrop.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/backdrops/EmptyBackdrop.ktnew file mode 100644index 00000000..3feb90ab--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/backdrops/EmptyBackdrop.kt@@ -0,0 +1,37 @@+/*+ * Vendored from Kyant0/backdrop v2.0.0 (io.github.kyant0:backdrop)+ * https://github.com/Kyant0/backdrop — Copyright 2025 Kyant0, Apache License 2.0+ *+ * Vendored so the library ships as source with this app (binary AARs compiled+ * against older Compose broke at runtime) and to add a backdrop resolution+ * scale for cheaper effect rendering. KMP expect/actual declarations were+ * merged into this single Android source set. Package renamed accordingly.+ * Myspoti copy taken from BitChord's vendored tree (github.com/kushagrasinghx/BitChord,+ * app/src/main/java/com/music/bitchord/ui/components/backdrop at edc1e6f), which adds+ * backdropScale and exportedBackdrop to drawBackdrop. Package renamed again for Myspoti.+ */+package com.music.spotui.ui.immersive.shell.backdrop.backdrops++import androidx.compose.runtime.Immutable+import androidx.compose.runtime.Stable+import androidx.compose.ui.graphics.GraphicsLayerScope+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.layout.LayoutCoordinates+import androidx.compose.ui.unit.Density+import com.music.spotui.ui.immersive.shell.backdrop.Backdrop++@Stable+fun emptyBackdrop(): Backdrop = EmptyBackdrop++@Immutable+private object EmptyBackdrop : Backdrop {++ override val isCoordinatesDependent: Boolean = false++ override fun DrawScope.drawBackdrop(+ density: Density,+ coordinates: LayoutCoordinates?,+ layerBlock: (GraphicsLayerScope.() -> Unit)?+ ) {+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/backdrops/LayerBackdrop.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/backdrops/LayerBackdrop.ktnew file mode 100644index 00000000..8d0510e6--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/backdrops/LayerBackdrop.kt@@ -0,0 +1,86 @@+/*+ * Vendored from Kyant0/backdrop v2.0.0 (io.github.kyant0:backdrop)+ * https://github.com/Kyant0/backdrop — Copyright 2025 Kyant0, Apache License 2.0+ *+ * Vendored so the library ships as source with this app (binary AARs compiled+ * against older Compose broke at runtime) and to add a backdrop resolution+ * scale for cheaper effect rendering. KMP expect/actual declarations were+ * merged into this single Android source set. Package renamed accordingly.+ * Myspoti copy taken from BitChord's vendored tree (github.com/kushagrasinghx/BitChord,+ * app/src/main/java/com/music/bitchord/ui/components/backdrop at edc1e6f), which adds+ * backdropScale and exportedBackdrop to drawBackdrop. Package renamed again for Myspoti.+ */+package com.music.spotui.ui.immersive.shell.backdrop.backdrops++import androidx.compose.runtime.Composable+import androidx.compose.runtime.Stable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.graphics.GraphicsLayerScope+import androidx.compose.ui.graphics.drawscope.ContentDrawScope+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.graphics.drawscope.withTransform+import androidx.compose.ui.graphics.layer.GraphicsLayer+import androidx.compose.ui.graphics.layer.drawLayer+import androidx.compose.ui.graphics.rememberGraphicsLayer+import androidx.compose.ui.layout.LayoutCoordinates+import androidx.compose.ui.layout.positionInWindow+import androidx.compose.ui.unit.Density+import com.music.spotui.ui.immersive.shell.backdrop.Backdrop+import com.music.spotui.ui.immersive.shell.backdrop.internal.InverseLayerScope++private val DefaultOnDraw: ContentDrawScope.() -> Unit = { drawContent() }++@Composable+fun rememberLayerBackdrop(+ graphicsLayer: GraphicsLayer = rememberGraphicsLayer(),+ onDraw: ContentDrawScope.() -> Unit = DefaultOnDraw+): LayerBackdrop {+ return remember(graphicsLayer, onDraw) {+ LayerBackdrop(graphicsLayer, onDraw)+ }+}++@Stable+class LayerBackdrop internal constructor(+ val graphicsLayer: GraphicsLayer,+ internal val onDraw: ContentDrawScope.() -> Unit+) : Backdrop {++ override val isCoordinatesDependent: Boolean = true++ internal var layerCoordinates: LayoutCoordinates? by mutableStateOf(null)++ private var inverseLayerScope: InverseLayerScope? = null++ override fun DrawScope.drawBackdrop(+ density: Density,+ coordinates: LayoutCoordinates?,+ layerBlock: (GraphicsLayerScope.() -> Unit)?+ ) {+ val coordinates = coordinates ?: return+ val layerCoordinates = layerCoordinates ?: return+ withTransform({+ if (layerBlock != null) {+ with(obtainInverseLayerScope()) { inverseTransform(density, layerBlock) }+ }+ val offset =+ try {+ layerCoordinates.localPositionOf(coordinates)+ } catch (_: Exception) {+ // TODO: outer transformations lead to wrong position calculation+ coordinates.positionInWindow() - layerCoordinates.positionInWindow()+ }+ translate(-offset.x, -offset.y)+ }) {+ drawLayer(graphicsLayer)+ }+ }++ private fun obtainInverseLayerScope(): InverseLayerScope {+ return inverseLayerScope?.apply { reset() }+ ?: InverseLayerScope().also { inverseLayerScope = it }+ }+}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.ktnew file mode 100644index 00000000..c52c0ff4--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/backdrops/LayerBackdropModifier.kt@@ -0,0 +1,102 @@+/*+ * Vendored from Kyant0/backdrop v2.0.0 (io.github.kyant0:backdrop)+ * https://github.com/Kyant0/backdrop — Copyright 2025 Kyant0, Apache License 2.0+ *+ * Vendored so the library ships as source with this app (binary AARs compiled+ * against older Compose broke at runtime) and to add a backdrop resolution+ * scale for cheaper effect rendering. KMP expect/actual declarations were+ * merged into this single Android source set. Package renamed accordingly.+ * Myspoti copy taken from BitChord's vendored tree (github.com/kushagrasinghx/BitChord,+ * app/src/main/java/com/music/bitchord/ui/components/backdrop at edc1e6f), which adds+ * backdropScale and exportedBackdrop to drawBackdrop. Package renamed again for Myspoti.+ */+package com.music.spotui.ui.immersive.shell.backdrop.backdrops++import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.drawscope.ContentDrawScope+import androidx.compose.ui.graphics.layer.drawLayer+import androidx.compose.ui.layout.LayoutCoordinates+import androidx.compose.ui.node.DrawModifierNode+import androidx.compose.ui.node.GlobalPositionAwareModifierNode+import androidx.compose.ui.node.ModifierNodeElement+import androidx.compose.ui.node.invalidateDraw+import androidx.compose.ui.platform.InspectorInfo+import com.music.spotui.ui.immersive.shell.backdrop.internal.recordLayer++fun Modifier.layerBackdrop(backdrop: LayerBackdrop): Modifier =+ this then LayerBackdropElement(backdrop)++private class LayerBackdropElement(+ val backdrop: LayerBackdrop+) : ModifierNodeElement<LayerBackdropNode>() {++ override fun create(): LayerBackdropNode {+ return LayerBackdropNode(backdrop)+ }++ override fun update(node: LayerBackdropNode) {+ if (node.backdrop != backdrop) {+ node.backdrop.layerCoordinates = null+ node.backdrop = backdrop+ }+ node.invalidateDraw()+ }++ override fun InspectorInfo.inspectableProperties() {+ name = "layerBackdrop"+ properties["backdrop"] = backdrop+ }++ override fun equals(other: Any?): Boolean {+ if (this === other) return true+ if (other !is LayerBackdropElement) return false++ if (backdrop != other.backdrop) return false++ return true+ }++ override fun hashCode(): Int {+ return backdrop.hashCode()+ }+}++private class LayerBackdropNode(+ var backdrop: LayerBackdrop+) : DrawModifierNode, GlobalPositionAwareModifierNode, Modifier.Node() {++ override fun ContentDrawScope.draw() {+ // Vendored change: record once and composite, rather than upstream's+ // draw-then-record.+ //+ // Upstream draws the content to the screen and then draws all of it a+ // second time into the layer, which puts the entire app through the draw+ // pass twice on every frame the glass is switched on — and this node+ // wraps the whole page, so "the entire app" is what that is. Recording+ // first and then blitting the finished layer to the screen produces the+ // same pixels off one pass.+ //+ // The layer is the node's own size, so this does clip anything a child+ // paints outside its bounds. Nothing here does — the pages are lists+ // inside a full-screen container — but a child that grew a shadow past+ // the edge would lose it, which upstream would not.+ // A degenerate size would record an empty layer, and unlike upstream there+ // is no direct draw left to fall back on — the page would simply vanish.+ if (size.width < 1f || size.height < 1f) {+ drawContent()+ return+ }+ recordLayer(this@LayerBackdropNode, backdrop.graphicsLayer) { backdrop.onDraw(this@draw) }+ drawLayer(backdrop.graphicsLayer)+ }++ override fun onGloballyPositioned(coordinates: LayoutCoordinates) {+ if (coordinates.isAttached) {+ backdrop.layerCoordinates = coordinates+ }+ }++ override fun onDetach() {+ backdrop.layerCoordinates = null+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/effects/Blur.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/effects/Blur.ktnew file mode 100644index 00000000..1e246a86--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/effects/Blur.kt@@ -0,0 +1,41 @@+/*+ * Vendored from Kyant0/backdrop v2.0.0 (io.github.kyant0:backdrop)+ * https://github.com/Kyant0/backdrop — Copyright 2025 Kyant0, Apache License 2.0+ *+ * Vendored so the library ships as source with this app (binary AARs compiled+ * against older Compose broke at runtime) and to add a backdrop resolution+ * scale for cheaper effect rendering. KMP expect/actual declarations were+ * merged into this single Android source set. Package renamed accordingly.+ * Myspoti copy taken from BitChord's vendored tree (github.com/kushagrasinghx/BitChord,+ * app/src/main/java/com/music/bitchord/ui/components/backdrop at edc1e6f), which adds+ * backdropScale and exportedBackdrop to drawBackdrop. Package renamed again for Myspoti.+ */+package com.music.spotui.ui.immersive.shell.backdrop.effects++import androidx.annotation.FloatRange+import androidx.compose.ui.graphics.BlurEffect+import androidx.compose.ui.graphics.TileMode+import com.music.spotui.ui.immersive.shell.backdrop.BackdropEffectScope+import com.music.spotui.ui.immersive.shell.backdrop.isRenderEffectSupported++fun BackdropEffectScope.blur(+ @FloatRange(from = 0.0) radius: Float,+ edgeTreatment: TileMode = TileMode.Clamp+) {+ if (!isRenderEffectSupported()) return+ if (radius <= 0f) return++ if (edgeTreatment != TileMode.Clamp || renderEffect != null) {+ if (radius > padding) {+ padding = radius+ }+ }++ renderEffect =+ BlurEffect(+ renderEffect,+ radius,+ radius,+ edgeTreatment+ )+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/effects/ColorFilter.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/effects/ColorFilter.ktnew file mode 100644index 00000000..d4222c1a--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/effects/ColorFilter.kt@@ -0,0 +1,87 @@+/*+ * Vendored from Kyant0/backdrop v2.0.0 (io.github.kyant0:backdrop)+ * https://github.com/Kyant0/backdrop — Copyright 2025 Kyant0, Apache License 2.0+ *+ * Vendored so the library ships as source with this app (binary AARs compiled+ * against older Compose broke at runtime) and to add a backdrop resolution+ * scale for cheaper effect rendering. KMP expect/actual declarations were+ * merged into this single Android source set. Package renamed accordingly.+ * Myspoti copy taken from BitChord's vendored tree (github.com/kushagrasinghx/BitChord,+ * app/src/main/java/com/music/bitchord/ui/components/backdrop at edc1e6f), which adds+ * backdropScale and exportedBackdrop to drawBackdrop. Package renamed again for Myspoti.+ */+package com.music.spotui.ui.immersive.shell.backdrop.effects++import androidx.annotation.FloatRange+import androidx.compose.ui.graphics.ColorFilter+import androidx.compose.ui.graphics.ColorMatrix+import androidx.compose.ui.graphics.ColorMatrixColorFilter+import com.music.spotui.ui.immersive.shell.backdrop.BackdropEffectScope+import com.music.spotui.ui.immersive.shell.backdrop.internal.ColorFilterEffect+import com.music.spotui.ui.immersive.shell.backdrop.isRenderEffectSupported++fun BackdropEffectScope.colorFilter(colorFilter: ColorFilter) {+ if (!isRenderEffectSupported()) return++ renderEffect = ColorFilterEffect(renderEffect, colorFilter)+}++fun BackdropEffectScope.opacity(@FloatRange(from = 0.0, to = 1.0) alpha: Float) {+ val colorMatrix = ColorMatrix(+ floatArrayOf(+ 1f, 0f, 0f, 0f, 0f,+ 0f, 1f, 0f, 0f, 0f,+ 0f, 0f, 1f, 0f, 0f,+ 0f, 0f, 0f, alpha, 0f+ )+ )+ colorFilter(ColorMatrixColorFilter(colorMatrix))+}++fun BackdropEffectScope.colorControls(+ brightness: Float = 0f,+ contrast: Float = 1f,+ saturation: Float = 1f+) {+ if (brightness == 0f && contrast == 1f && saturation == 1f) {+ return+ }++ colorFilter(colorControlsColorFilter(brightness, contrast, saturation))+}++private val VibrantColorFilter = colorControlsColorFilter(saturation = 1.5f)++fun BackdropEffectScope.vibrancy() {+ colorFilter(VibrantColorFilter)+}++private fun colorControlsColorFilter(+ brightness: Float = 0f,+ contrast: Float = 1f,+ saturation: Float = 1f+): ColorFilter {+ val invSat = 1f - saturation+ val r = 0.213f * invSat+ val g = 0.715f * invSat+ val b = 0.072f * invSat++ val c = contrast+ val t = (0.5f - c * 0.5f + brightness) * 255f+ val s = saturation++ val cr = c * r+ val cg = c * g+ val cb = c * b+ val cs = c * s++ val colorMatrix = ColorMatrix(+ floatArrayOf(+ cr + cs, cg, cb, 0f, t,+ cr, cg + cs, cb, 0f, t,+ cr, cg, cb + cs, 0f, t,+ 0f, 0f, 0f, 1f, 0f+ )+ )+ return ColorMatrixColorFilter(colorMatrix)+}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.ktnew file mode 100644index 00000000..79925e23--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/effects/Lens.kt@@ -0,0 +1,124 @@+/*+ * Vendored from Kyant0/backdrop v2.0.0 (io.github.kyant0:backdrop)+ * https://github.com/Kyant0/backdrop — Copyright 2025 Kyant0, Apache License 2.0+ *+ * Vendored so the library ships as source with this app (binary AARs compiled+ * against older Compose broke at runtime) and to add a backdrop resolution+ * scale for cheaper effect rendering. KMP expect/actual declarations were+ * merged into this single Android source set. Package renamed accordingly.+ * Myspoti copy taken from BitChord's vendored tree (github.com/kushagrasinghx/BitChord,+ * app/src/main/java/com/music/bitchord/ui/components/backdrop at edc1e6f), which adds+ * backdropScale and exportedBackdrop to drawBackdrop. Package renamed again for Myspoti.+ */+package com.music.spotui.ui.immersive.shell.backdrop.effects++import androidx.annotation.FloatRange+import androidx.compose.foundation.shape.AbsoluteRoundedCornerShape+import androidx.compose.foundation.shape.CornerBasedShape+import androidx.compose.ui.unit.LayoutDirection+import androidx.compose.ui.util.fastCoerceAtLeast+import androidx.compose.ui.util.fastCoerceAtMost+import com.music.spotui.ui.immersive.shell.backdrop.BackdropEffectScope+import com.music.spotui.ui.immersive.shell.backdrop.internal.RoundedRectRefractionShaderString+import com.music.spotui.ui.immersive.shell.backdrop.internal.RoundedRectRefractionWithDispersionShaderString+import com.music.spotui.ui.immersive.shell.backdrop.internal.RuntimeShaderEffect+import com.music.spotui.ui.immersive.shell.backdrop.isRuntimeShaderSupported++fun BackdropEffectScope.lens(+ @FloatRange(from = 0.0) refractionHeight: Float,+ @FloatRange(from = 0.0) refractionAmount: Float,+ depthEffect: Boolean = false,+ chromaticAberration: Boolean = false+) {+ if (!isRuntimeShaderSupported()) return+ if (refractionHeight <= 0f || refractionAmount <= 0f) return++ if (padding > 0f) {+ padding = (padding - refractionHeight).fastCoerceAtLeast(0f)+ }++ val cornerRadii = cornerRadii+ val effect =+ if (cornerRadii != null) {+ val shader =+ if (!chromaticAberration) {+ obtainRuntimeShader(+ "Refraction",+ RoundedRectRefractionShaderString+ )+ } else {+ obtainRuntimeShader(+ "RefractionWithDispersion",+ RoundedRectRefractionWithDispersionShaderString+ )+ }+ shader.apply {+ setFloatUniform("size", size.width, size.height)+ setFloatUniform("offset", -padding, -padding)+ setFloatUniform("cornerRadii", cornerRadii)+ setFloatUniform("refractionHeight", refractionHeight)+ setFloatUniform("refractionAmount", -refractionAmount)+ setFloatUniform("depthEffect", if (depthEffect) 1f else 0f)+ if (chromaticAberration) {+ setFloatUniform("chromaticAberration", 1f)+ }+ }+ RuntimeShaderEffect(shader, "content")+ } else {+ throwUnsupportedSDFException()+ }+ effect(effect)+}++// Vendored change: support for io.github.kyant0:shapes' RoundedRectangularShape was+// dropped so the vendored sources have no external dependency; this app only passes+// CornerBasedShape here.+private val BackdropEffectScope.cornerRadii: FloatArray?+ get() = when (val shape = shape) {+ 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)+ floatArrayOf(+ topLeft.fastCoerceAtMost(maxRadius),+ topRight.fastCoerceAtMost(maxRadius),+ bottomRight.fastCoerceAtMost(maxRadius),+ bottomLeft.fastCoerceAtMost(maxRadius)+ )+ }++ is CornerBasedShape -> {+ val size = size+ val maxRadius = size.minDimension / 2f+ val isLtr = layoutDirection == LayoutDirection.Ltr+ val topLeft =+ if (isLtr) shape.topStart.toPx(size, this)+ else shape.topEnd.toPx(size, this)+ val topRight =+ if (isLtr) shape.topEnd.toPx(size, this)+ else shape.topStart.toPx(size, this)+ val bottomRight =+ if (isLtr) shape.bottomEnd.toPx(size, this)+ else shape.bottomStart.toPx(size, this)+ val bottomLeft =+ if (isLtr) shape.bottomStart.toPx(size, this)+ else shape.bottomEnd.toPx(size, this)+ floatArrayOf(+ topLeft.fastCoerceAtMost(maxRadius),+ topRight.fastCoerceAtMost(maxRadius),+ bottomRight.fastCoerceAtMost(maxRadius),+ bottomLeft.fastCoerceAtMost(maxRadius)+ )+ }++ else -> null+ }++private fun throwUnsupportedSDFException(): Nothing {+ throw UnsupportedOperationException(+ "Only RoundedRectangularShape or CornerBasedShape is supported in lens effects."+ )+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/effects/RenderEffect.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/effects/RenderEffect.ktnew file mode 100644index 00000000..3b314557--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/effects/RenderEffect.kt@@ -0,0 +1,46 @@+/*+ * Vendored from Kyant0/backdrop v2.0.0 (io.github.kyant0:backdrop)+ * https://github.com/Kyant0/backdrop — Copyright 2025 Kyant0, Apache License 2.0+ *+ * Vendored so the library ships as source with this app (binary AARs compiled+ * against older Compose broke at runtime) and to add a backdrop resolution+ * scale for cheaper effect rendering. KMP expect/actual declarations were+ * merged into this single Android source set. Package renamed accordingly.+ * Myspoti copy taken from BitChord's vendored tree (github.com/kushagrasinghx/BitChord,+ * app/src/main/java/com/music/bitchord/ui/components/backdrop at edc1e6f), which adds+ * backdropScale and exportedBackdrop to drawBackdrop. Package renamed again for Myspoti.+ */+package com.music.spotui.ui.immersive.shell.backdrop.effects++import androidx.compose.ui.graphics.RenderEffect+import com.music.spotui.ui.immersive.shell.backdrop.BackdropEffectScope+import com.music.spotui.ui.immersive.shell.backdrop.RuntimeShader+import com.music.spotui.ui.immersive.shell.backdrop.internal.RuntimeShaderEffect+import com.music.spotui.ui.immersive.shell.backdrop.internal.chain+import com.music.spotui.ui.immersive.shell.backdrop.isRenderEffectSupported+import com.music.spotui.ui.immersive.shell.backdrop.isRuntimeShaderSupported+import org.intellij.lang.annotations.Language+import kotlin.contracts.ExperimentalContracts++fun BackdropEffectScope.effect(effect: RenderEffect) {+ if (!isRenderEffectSupported()) return++ renderEffect = renderEffect.chain(effect)+}++@OptIn(ExperimentalContracts::class)+fun BackdropEffectScope.runtimeShaderEffect(+ key: String,+ @Language("AGSL") shaderString: String,+ uniformShaderName: String,+ block: RuntimeShader.() -> Unit+) {+ if (!isRuntimeShaderSupported()) return++ val effect =+ RuntimeShaderEffect(+ runtimeShader = obtainRuntimeShader(key, shaderString).apply(block),+ uniformShaderName = uniformShaderName+ )+ renderEffect = renderEffect.chain(effect)+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/highlight/Highlight.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/highlight/Highlight.ktnew file mode 100644index 00000000..9fe0deb4--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/highlight/Highlight.kt@@ -0,0 +1,40 @@+/*+ * Vendored from Kyant0/backdrop v2.0.0 (io.github.kyant0:backdrop)+ * https://github.com/Kyant0/backdrop — Copyright 2025 Kyant0, Apache License 2.0+ *+ * Vendored so the library ships as source with this app (binary AARs compiled+ * against older Compose broke at runtime) and to add a backdrop resolution+ * scale for cheaper effect rendering. KMP expect/actual declarations were+ * merged into this single Android source set. Package renamed accordingly.+ * Myspoti copy taken from BitChord's vendored tree (github.com/kushagrasinghx/BitChord,+ * app/src/main/java/com/music/bitchord/ui/components/backdrop at edc1e6f), which adds+ * backdropScale and exportedBackdrop to drawBackdrop. Package renamed again for Myspoti.+ */+package com.music.spotui.ui.immersive.shell.backdrop.highlight++import androidx.annotation.FloatRange+import androidx.compose.runtime.Immutable+import androidx.compose.runtime.Stable+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp++@Immutable+data class Highlight(+ val width: Dp = 0.5f.dp,+ val blurRadius: Dp = width / 2f,+ @param:FloatRange(from = 0.0, to = 1.0) val alpha: Float = 1f,+ val style: HighlightStyle = HighlightStyle.Default+) {++ companion object {++ @Stable+ val Default: Highlight = Highlight()++ @Stable+ val Ambient: Highlight = Highlight(style = HighlightStyle.Ambient)++ @Stable+ val Plain: Highlight = Highlight(style = HighlightStyle.Plain)+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/highlight/HighlightModifier.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/highlight/HighlightModifier.ktnew file mode 100644index 00000000..3d9d14c7--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/highlight/HighlightModifier.kt@@ -0,0 +1,178 @@+/*+ * Vendored from Kyant0/backdrop v2.0.0 (io.github.kyant0:backdrop)+ * https://github.com/Kyant0/backdrop — Copyright 2025 Kyant0, Apache License 2.0+ *+ * Vendored so the library ships as source with this app (binary AARs compiled+ * against older Compose broke at runtime) and to add a backdrop resolution+ * scale for cheaper effect rendering. KMP expect/actual declarations were+ * merged into this single Android source set. Package renamed accordingly.+ * Myspoti copy taken from BitChord's vendored tree (github.com/kushagrasinghx/BitChord,+ * app/src/main/java/com/music/bitchord/ui/components/backdrop at edc1e6f), which adds+ * backdropScale and exportedBackdrop to drawBackdrop. Package renamed again for Myspoti.+ */+package com.music.spotui.ui.immersive.shell.backdrop.highlight++import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Outline+import androidx.compose.ui.graphics.Paint+import androidx.compose.ui.graphics.PaintingStyle+import androidx.compose.ui.graphics.Path+import androidx.compose.ui.graphics.drawOutline+import androidx.compose.ui.graphics.drawscope.ContentDrawScope+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.graphics.drawscope.translate+import androidx.compose.ui.graphics.layer.GraphicsLayer+import androidx.compose.ui.graphics.layer.drawLayer+import androidx.compose.ui.node.DrawModifierNode+import androidx.compose.ui.node.ModifierNodeElement+import androidx.compose.ui.node.invalidateDraw+import androidx.compose.ui.node.requireGraphicsContext+import androidx.compose.ui.platform.InspectorInfo+import androidx.compose.ui.unit.Density+import androidx.compose.ui.unit.IntSize+import androidx.compose.ui.util.fastCoerceAtMost+import com.music.spotui.ui.immersive.shell.backdrop.RuntimeShaderCacheImpl+import com.music.spotui.ui.immersive.shell.backdrop.internal.ShapeProvider+import com.music.spotui.ui.immersive.shell.backdrop.internal.blur+import com.music.spotui.ui.immersive.shell.backdrop.internal.clipOutline+import com.music.spotui.ui.immersive.shell.backdrop.internal.setRuntimeShader+import com.music.spotui.ui.immersive.shell.backdrop.isRuntimeShaderSupported+import kotlin.math.ceil++internal class HighlightElement(+ val shapeProvider: ShapeProvider,+ val highlight: () -> Highlight?+) : ModifierNodeElement<HighlightNode>() {++ override fun create(): HighlightNode {+ return HighlightNode(shapeProvider, highlight)+ }++ override fun update(node: HighlightNode) {+ node.shapeProvider = shapeProvider+ node.highlight = highlight+ node.invalidateDraw()+ }++ override fun InspectorInfo.inspectableProperties() {+ name = "highlight"+ properties["shapeProvider"] = shapeProvider+ properties["highlight"] = highlight+ }++ override fun equals(other: Any?): Boolean {+ if (this === other) return true+ if (other !is HighlightElement) return false++ if (shapeProvider != other.shapeProvider) return false+ if (highlight != other.highlight) return false++ return true+ }++ override fun hashCode(): Int {+ var result = shapeProvider.hashCode()+ result = 31 * result + highlight.hashCode()+ return result+ }+}++internal class HighlightNode(+ var shapeProvider: ShapeProvider,+ var highlight: () -> Highlight?+) : DrawModifierNode, Modifier.Node() {++ override val shouldAutoInvalidate: Boolean = false++ private var highlightLayer: GraphicsLayer? = null++ private val paint =+ Paint().apply {+ style = PaintingStyle.Stroke+ }+ private var clipPath: Path? = null++ private val runtimeShaderCache = RuntimeShaderCacheImpl()++ private var prevStyle: HighlightStyle? = null++ override fun ContentDrawScope.draw() {+ val highlight = highlight()+ if (highlight == null || highlight.width.value <= 0f) {+ return drawContent()+ }++ drawContent()++ val highlightLayer = highlightLayer+ if (highlightLayer != null) {+ val size = size+ val density: Density = this+ val layoutDirection = layoutDirection++ val safeSize =+ IntSize(+ ceil(size.width).toInt() + 2,+ ceil(size.height).toInt() + 2+ )++ val outline = shapeProvider.shape.createOutline(size, layoutDirection, density)+ val clipPath =+ if (outline is Outline.Rounded) {+ clipPath ?: Path().also { clipPath = it }+ } else {+ null+ }++ configurePaint(highlight)++ highlightLayer.alpha = highlight.alpha+ highlightLayer.blendMode = highlight.style.blendMode+ highlightLayer.record(safeSize) {+ translate(1f, 1f) {+ val canvas = drawContext.canvas+ canvas.save()+ canvas.clipOutline(outline, clipPath)+ canvas.drawOutline(outline, paint)+ canvas.restore()+ }+ }++ translate(-1f, -1f) {+ drawLayer(highlightLayer)+ }+ }+ }++ override fun onAttach() {+ val graphicsContext = requireGraphicsContext()+ highlightLayer = graphicsContext.createGraphicsLayer()+ }++ override fun onDetach() {+ val graphicsContext = requireGraphicsContext()+ highlightLayer?.let { layer ->+ graphicsContext.releaseGraphicsLayer(layer)+ highlightLayer = null+ }+ clipPath = null+ runtimeShaderCache.clear()+ prevStyle = null+ }++ private fun DrawScope.configurePaint(highlight: Highlight) {+ paint.color = highlight.style.color+ paint.strokeWidth = ceil(highlight.width.toPx().fastCoerceAtMost(size.minDimension / 2f)) * 2f+ paint.blur(highlight.blurRadius.toPx())+ if (isRuntimeShaderSupported()) {+ val shader =+ with(highlight.style) {+ createShader(+ shape = shapeProvider.shape,+ runtimeShaderCache = runtimeShaderCache+ )+ }+ paint.setRuntimeShader(shader)+ }+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/highlight/HighlightStyle.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/highlight/HighlightStyle.ktnew file mode 100644index 00000000..266efd2b--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/highlight/HighlightStyle.kt@@ -0,0 +1,150 @@+/*+ * Vendored from Kyant0/backdrop v2.0.0 (io.github.kyant0:backdrop)+ * https://github.com/Kyant0/backdrop — Copyright 2025 Kyant0, Apache License 2.0+ *+ * Vendored so the library ships as source with this app (binary AARs compiled+ * against older Compose broke at runtime) and to add a backdrop resolution+ * scale for cheaper effect rendering. KMP expect/actual declarations were+ * merged into this single Android source set. Package renamed accordingly.+ * Myspoti copy taken from BitChord's vendored tree (github.com/kushagrasinghx/BitChord,+ * app/src/main/java/com/music/bitchord/ui/components/backdrop at edc1e6f), which adds+ * backdropScale and exportedBackdrop to drawBackdrop. Package renamed again for Myspoti.+ */+package com.music.spotui.ui.immersive.shell.backdrop.highlight++import androidx.annotation.FloatRange+import androidx.compose.foundation.shape.CornerBasedShape+import androidx.compose.runtime.Immutable+import androidx.compose.runtime.Stable+import androidx.compose.ui.graphics.BlendMode+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.Shape+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.unit.LayoutDirection+import androidx.compose.ui.util.fastCoerceAtMost+import com.music.spotui.ui.immersive.shell.backdrop.RuntimeShader+import com.music.spotui.ui.immersive.shell.backdrop.RuntimeShaderCache+import com.music.spotui.ui.immersive.shell.backdrop.internal.AmbientHighlightShaderString+import com.music.spotui.ui.immersive.shell.backdrop.internal.DefaultHighlightShaderString+import com.music.spotui.ui.immersive.shell.backdrop.isRuntimeShaderSupported+import kotlin.math.PI++@Immutable+interface HighlightStyle {++ val color: Color++ val blendMode: BlendMode++ fun DrawScope.createShader(+ shape: Shape,+ runtimeShaderCache: RuntimeShaderCache+ ): RuntimeShader?++ @Immutable+ data class Plain(+ override val color: Color = Color.White.copy(alpha = 0.38f),+ override val blendMode: BlendMode = BlendMode.Plus+ ) : HighlightStyle {++ override fun DrawScope.createShader(+ shape: Shape,+ runtimeShaderCache: RuntimeShaderCache+ ): RuntimeShader? = null+ }++ @Immutable+ data class Default(+ override val color: Color = Color.White.copy(alpha = 0.5f),+ override val blendMode: BlendMode = BlendMode.Plus,+ val angle: Float = 45f,+ @param:FloatRange(from = 0.0) val falloff: Float = 1f+ ) : HighlightStyle {++ override fun DrawScope.createShader(+ shape: Shape,+ runtimeShaderCache: RuntimeShaderCache+ ): RuntimeShader? {+ return if (isRuntimeShaderSupported()) {+ runtimeShaderCache.obtainRuntimeShader(+ "Default",+ DefaultHighlightShaderString+ ).apply {+ setFloatUniform("size", size.width, size.height)+ setFloatUniform("cornerRadii", getCornerRadii(shape))+ setColorUniform("color", color.copy(alpha = 1f))+ setFloatUniform("angle", angle * (PI / 180f).toFloat())+ setFloatUniform("falloff", falloff)+ }+ } else {+ null+ }+ }+ }++ @Immutable+ data class Ambient(+ @param:FloatRange(from = 0.0, to = 1.0) val intensity: Float = 0.38f+ ) : HighlightStyle {++ override val color: Color = Color.White.copy(alpha = intensity)++ override val blendMode: BlendMode = DrawScope.DefaultBlendMode++ override fun DrawScope.createShader(+ shape: Shape,+ runtimeShaderCache: RuntimeShaderCache+ ): RuntimeShader? {+ return if (isRuntimeShaderSupported()) {+ runtimeShaderCache.obtainRuntimeShader(+ "Ambient",+ AmbientHighlightShaderString+ ).apply {+ setFloatUniform("size", size.width, size.height)+ setFloatUniform("cornerRadii", getCornerRadii(shape))+ setFloatUniform("angle", 45f * (PI / 180f).toFloat())+ setFloatUniform("falloff", 1f)+ }+ } else {+ null+ }+ }+ }++ companion object {++ @Stable+ val Default: Default = Default()++ @Stable+ val Ambient: Ambient = Ambient()++ @Stable+ val Plain: Plain = Plain()+ }+}++private fun DrawScope.getCornerRadii(shape: Shape): FloatArray {+ val size = size+ val maxRadius = size.minDimension / 2f+ val shape = shape as? CornerBasedShape ?: return FloatArray(4) { maxRadius }+ val isLtr = layoutDirection == LayoutDirection.Ltr+ val topLeft =+ if (isLtr) shape.topStart.toPx(size, this)+ else shape.topEnd.toPx(size, this)+ val topRight =+ if (isLtr) shape.topEnd.toPx(size, this)+ else shape.topStart.toPx(size, this)+ val bottomRight =+ if (isLtr) shape.bottomEnd.toPx(size, this)+ else shape.bottomStart.toPx(size, this)+ val bottomLeft =+ if (isLtr) shape.bottomStart.toPx(size, this)+ else shape.bottomEnd.toPx(size, this)+ return floatArrayOf(+ topLeft.fastCoerceAtMost(maxRadius),+ topRight.fastCoerceAtMost(maxRadius),+ bottomRight.fastCoerceAtMost(maxRadius),+ bottomLeft.fastCoerceAtMost(maxRadius)+ )+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/internal/InverseLayerScope.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/internal/InverseLayerScope.ktnew file mode 100644index 00000000..6971584e--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/internal/InverseLayerScope.kt@@ -0,0 +1,142 @@+/*+ * Vendored from Kyant0/backdrop v2.0.0 (io.github.kyant0:backdrop)+ * https://github.com/Kyant0/backdrop — Copyright 2025 Kyant0, Apache License 2.0+ *+ * Vendored so the library ships as source with this app (binary AARs compiled+ * against older Compose broke at runtime) and to add a backdrop resolution+ * scale for cheaper effect rendering. KMP expect/actual declarations were+ * merged into this single Android source set. Package renamed accordingly.+ * Myspoti copy taken from BitChord's vendored tree (github.com/kushagrasinghx/BitChord,+ * app/src/main/java/com/music/bitchord/ui/components/backdrop at edc1e6f), which adds+ * backdropScale and exportedBackdrop to drawBackdrop. Package renamed again for Myspoti.+ */+package com.music.spotui.ui.immersive.shell.backdrop.internal++import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.graphics.BlendMode+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.ColorFilter+import androidx.compose.ui.graphics.CompositingStrategy+import androidx.compose.ui.graphics.DefaultCameraDistance+import androidx.compose.ui.graphics.DefaultShadowColor+import androidx.compose.ui.graphics.GraphicsLayerScope+import androidx.compose.ui.graphics.Matrix+import androidx.compose.ui.graphics.RectangleShape+import androidx.compose.ui.graphics.RenderEffect+import androidx.compose.ui.graphics.Shape+import androidx.compose.ui.graphics.TransformOrigin+import androidx.compose.ui.graphics.drawscope.DrawTransform+import androidx.compose.ui.unit.Density+import kotlin.math.PI+import kotlin.math.cos+import kotlin.math.sin++internal class InverseLayerScope : GraphicsLayerScope {++ override var size: Size = Size.Unspecified+ override var density: Float = 1f+ override var fontScale: Float = 1f++ override var scaleX: Float = 1f+ override var scaleY: Float = 1f+ override var alpha: Float = 0f+ override var translationX: Float = 0f+ override var translationY: Float = 0f+ override var shadowElevation: Float = 0f+ override var ambientShadowColor: Color = DefaultShadowColor+ override var spotShadowColor: Color = DefaultShadowColor+ override var rotationX: Float = 0f+ override var rotationY: Float = 0f+ override var rotationZ: Float = 0f+ override var cameraDistance: Float = DefaultCameraDistance+ override var transformOrigin: TransformOrigin = TransformOrigin.Center+ override var shape: Shape = RectangleShape+ override var clip: Boolean = false+ override var renderEffect: RenderEffect? = null+ override var blendMode: BlendMode = BlendMode.SrcOver+ override var colorFilter: ColorFilter? = null+ override var compositingStrategy: CompositingStrategy = CompositingStrategy.Auto++ private var matrix: Matrix? = null++ fun DrawTransform.inverseTransform(+ density: Density,+ layerBlock: GraphicsLayerScope.() -> Unit+ ) {+ [email protected] = size+ [email protected] = density.density+ fontScale = density.fontScale++ layerBlock()++ inverseTransformAtTopLeft(+ rotationZ = rotationZ,+ scaleX = scaleX,+ scaleY = scaleY+ )+ }++ fun reset() {+ size = Size.Unspecified+ density = 1f+ fontScale = 1f++ scaleX = 1f+ scaleY = 1f+ alpha = 1f+ translationX = 0f+ translationY = 0f+ shadowElevation = 0f+ ambientShadowColor = DefaultShadowColor+ spotShadowColor = DefaultShadowColor+ rotationX = 0f+ rotationY = 0f+ rotationZ = 0f+ cameraDistance = DefaultCameraDistance+ transformOrigin = TransformOrigin.Center+ shape = RectangleShape+ clip = false+ renderEffect = null+ blendMode = BlendMode.SrcOver+ colorFilter = null+ compositingStrategy = CompositingStrategy.Auto++ matrix = null+ }++ private fun DrawTransform.inverseTransformAtTopLeft(+ rotationZ: Float = 0f,+ scaleX: Float = 1f,+ scaleY: Float = 1f+ ) {+ if (rotationZ == 0f) {+ if (scaleX != 0f && scaleY != 0f) {+ scale(1f / scaleX, 1f / scaleY, Offset.Zero)+ }+ return+ }++ val matrix = matrix ?: Matrix().also { matrix = it }+ if (matrix.values.size < 16) return++ val rz = rotationZ * (PI / 180.0)+ val rsz = sin(rz).toFloat()+ val rcz = cos(rz).toFloat()++ val a00 = rcz * scaleX+ val a01 = rsz * scaleY+ val a10 = -rsz * scaleX+ val a11 = rcz * scaleY++ val det = a00 * a11 - a01 * a10+ if (det == 0f) return+ val invDet = 1f / det+ matrix[0, 0] = a11 * invDet+ matrix[0, 1] = -a01 * invDet+ matrix[1, 0] = -a10 * invDet+ matrix[1, 1] = a00 * invDet++ transform(matrix)+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/internal/LayerRecorder.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/internal/LayerRecorder.ktnew file mode 100644index 00000000..f8f7fc01--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/internal/LayerRecorder.kt@@ -0,0 +1,42 @@+/*+ * Vendored from Kyant0/backdrop v2.0.0 (io.github.kyant0:backdrop)+ * https://github.com/Kyant0/backdrop — Copyright 2025 Kyant0, Apache License 2.0+ *+ * Vendored so the library ships as source with this app (binary AARs compiled+ * against older Compose broke at runtime) and to add a backdrop resolution+ * scale for cheaper effect rendering. KMP expect/actual declarations were+ * merged into this single Android source set. Package renamed accordingly.+ * Myspoti copy taken from BitChord's vendored tree (github.com/kushagrasinghx/BitChord,+ * app/src/main/java/com/music/bitchord/ui/components/backdrop at edc1e6f), which adds+ * backdropScale and exportedBackdrop to drawBackdrop. Package renamed again for Myspoti.+ */+package com.music.spotui.ui.immersive.shell.backdrop.internal++import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.graphics.layer.GraphicsLayer+import androidx.compose.ui.node.DelegatableNode+import androidx.compose.ui.node.requireDensity+import androidx.compose.ui.unit.IntSize+import androidx.compose.ui.unit.toIntSize++// Vendored change: the upstream declaration used an experimental Kotlin context+// parameter (`context(node: DelegatableNode)`), which would require enabling+// -Xcontext-parameters for the whole app module; the node is an explicit+// parameter instead.+internal fun DrawScope.recordLayer(+ node: DelegatableNode,+ layer: GraphicsLayer,+ size: IntSize = this.size.toIntSize(),+ block: DrawScope.() -> Unit+) {+ val density = node.requireDensity()+ layer.record(size) {+ val prevDensity = drawContext.density+ drawContext.density = density+ try {+ this.block()+ } finally {+ drawContext.density = prevDensity+ }+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/internal/Outline.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/internal/Outline.ktnew file mode 100644index 00000000..14590bcb--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/internal/Outline.kt@@ -0,0 +1,30 @@+/*+ * Vendored from Kyant0/backdrop v2.0.0 (io.github.kyant0:backdrop)+ * https://github.com/Kyant0/backdrop — Copyright 2025 Kyant0, Apache License 2.0+ *+ * Vendored so the library ships as source with this app (binary AARs compiled+ * against older Compose broke at runtime) and to add a backdrop resolution+ * scale for cheaper effect rendering. KMP expect/actual declarations were+ * merged into this single Android source set. Package renamed accordingly.+ * Myspoti copy taken from BitChord's vendored tree (github.com/kushagrasinghx/BitChord,+ * app/src/main/java/com/music/bitchord/ui/components/backdrop at edc1e6f), which adds+ * backdropScale and exportedBackdrop to drawBackdrop. Package renamed again for Myspoti.+ */+package com.music.spotui.ui.immersive.shell.backdrop.internal++import androidx.compose.ui.graphics.Canvas+import androidx.compose.ui.graphics.Outline+import androidx.compose.ui.graphics.Path++internal fun Canvas.clipOutline(outline: Outline, path: Path?) {+ when (outline) {+ is Outline.Rectangle -> clipRect(outline.rect)+ is Outline.Rounded -> {+ path!!.rewind()+ path.addRoundRect(outline.roundRect)+ clipPath(path)+ }++ is Outline.Generic -> clipPath(outline.path)+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/internal/Paint.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/internal/Paint.ktnew file mode 100644index 00000000..ea06a475--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/internal/Paint.kt@@ -0,0 +1,28 @@+/*+ * Vendored from Kyant0/backdrop v2.0.0 (io.github.kyant0:backdrop)+ * https://github.com/Kyant0/backdrop — Copyright 2025 Kyant0, Apache License 2.0+ *+ * Vendored so the library ships as source with this app (binary AARs compiled+ * against older Compose broke at runtime) and to add a backdrop resolution+ * scale for cheaper effect rendering. KMP expect/actual declarations were+ * merged into this single Android source set. Package renamed accordingly.+ * Myspoti copy taken from BitChord's vendored tree (github.com/kushagrasinghx/BitChord,+ * app/src/main/java/com/music/bitchord/ui/components/backdrop at edc1e6f), which adds+ * backdropScale and exportedBackdrop to drawBackdrop. Package renamed again for Myspoti.+ */+package com.music.spotui.ui.immersive.shell.backdrop.internal++import android.graphics.BlurMaskFilter+import androidx.compose.ui.graphics.Paint+import com.music.spotui.ui.immersive.shell.backdrop.RuntimeShader+import com.music.spotui.ui.immersive.shell.backdrop.asAndroidRuntimeShader++internal fun Paint.blur(radius: Float) {+ this.asFrameworkPaint().maskFilter =+ if (radius > 0f) BlurMaskFilter(radius, BlurMaskFilter.Blur.NORMAL)+ else null+}++internal fun Paint.setRuntimeShader(runtimeShader: RuntimeShader?) {+ this.asFrameworkPaint().shader = runtimeShader?.asAndroidRuntimeShader()+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/internal/RenderEffect.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/internal/RenderEffect.ktnew file mode 100644index 00000000..9a1a9bc1--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/internal/RenderEffect.kt@@ -0,0 +1,62 @@+/*+ * Vendored from Kyant0/backdrop v2.0.0 (io.github.kyant0:backdrop)+ * https://github.com/Kyant0/backdrop — Copyright 2025 Kyant0, Apache License 2.0+ *+ * Vendored so the library ships as source with this app (binary AARs compiled+ * against older Compose broke at runtime) and to add a backdrop resolution+ * scale for cheaper effect rendering. KMP expect/actual declarations were+ * merged into this single Android source set. Package renamed accordingly.+ * Myspoti copy taken from BitChord's vendored tree (github.com/kushagrasinghx/BitChord,+ * app/src/main/java/com/music/bitchord/ui/components/backdrop at edc1e6f), which adds+ * backdropScale and exportedBackdrop to drawBackdrop. Package renamed again for Myspoti.+ */+package com.music.spotui.ui.immersive.shell.backdrop.internal++import android.os.Build+import androidx.annotation.RequiresApi+import androidx.compose.ui.graphics.ColorFilter+import androidx.compose.ui.graphics.RenderEffect+import androidx.compose.ui.graphics.asAndroidColorFilter+import androidx.compose.ui.graphics.asComposeRenderEffect+import com.music.spotui.ui.immersive.shell.backdrop.RuntimeShader+import com.music.spotui.ui.immersive.shell.backdrop.asAndroidRuntimeShader++@RequiresApi(Build.VERSION_CODES.S)+internal fun RenderEffect?.chain(other: RenderEffect): RenderEffect {+ return if (this != null) {+ android.graphics.RenderEffect.createChainEffect(+ other.asAndroidRenderEffect(),+ this.asAndroidRenderEffect()+ ).asComposeRenderEffect()+ } else {+ other+ }+}++@RequiresApi(Build.VERSION_CODES.TIRAMISU)+internal fun RuntimeShaderEffect(+ runtimeShader: RuntimeShader,+ uniformShaderName: String+): RenderEffect {+ return android.graphics.RenderEffect.createRuntimeShaderEffect(+ runtimeShader.asAndroidRuntimeShader(),+ uniformShaderName+ ).asComposeRenderEffect()+}++@RequiresApi(Build.VERSION_CODES.S)+internal fun ColorFilterEffect(+ renderEffect: RenderEffect?,+ colorFilter: ColorFilter+): RenderEffect {+ return if (renderEffect != null) {+ android.graphics.RenderEffect.createColorFilterEffect(+ colorFilter.asAndroidColorFilter(),+ renderEffect.asAndroidRenderEffect()+ ).asComposeRenderEffect()+ } else {+ android.graphics.RenderEffect.createColorFilterEffect(+ colorFilter.asAndroidColorFilter(),+ ).asComposeRenderEffect()+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/internal/Shaders.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/internal/Shaders.ktnew file mode 100644index 00000000..67f70449--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/internal/Shaders.kt@@ -0,0 +1,216 @@+/*+ * Vendored from Kyant0/backdrop v2.0.0 (io.github.kyant0:backdrop)+ * https://github.com/Kyant0/backdrop — Copyright 2025 Kyant0, Apache License 2.0+ *+ * Vendored so the library ships as source with this app (binary AARs compiled+ * against older Compose broke at runtime) and to add a backdrop resolution+ * scale for cheaper effect rendering. KMP expect/actual declarations were+ * merged into this single Android source set. Package renamed accordingly.+ * Myspoti copy taken from BitChord's vendored tree (github.com/kushagrasinghx/BitChord,+ * app/src/main/java/com/music/bitchord/ui/components/backdrop at edc1e6f), which adds+ * backdropScale and exportedBackdrop to drawBackdrop. Package renamed again for Myspoti.+ */+/*+ Copyright 2025 Kyant++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.+ */++package com.music.spotui.ui.immersive.shell.backdrop.internal++import org.intellij.lang.annotations.Language++@Language("AGSL")+private const val RoundedRectSDF = """+float radiusAt(float2 coord, float4 radii) {+ if (coord.x >= 0.0) {+ if (coord.y <= 0.0) return radii.y;+ else return radii.z;+ } else {+ if (coord.y <= 0.0) return radii.x;+ else return radii.w;+ }+}++float sdRoundedRect(float2 coord, float2 halfSize, float radius) {+ float2 cornerCoord = abs(coord) - (halfSize - float2(radius));+ float outside = length(max(cornerCoord, 0.0)) - radius;+ float inside = min(max(cornerCoord.x, cornerCoord.y), 0.0);+ return outside + inside;+}++float2 gradSdRoundedRect(float2 coord, float2 halfSize, float radius) {+ float2 cornerCoord = abs(coord) - (halfSize - float2(radius));+ if (cornerCoord.x >= 0.0 || cornerCoord.y >= 0.0) {+ return sign(coord) * normalize(max(cornerCoord, 0.0));+ } else {+ float gradX = step(cornerCoord.y, cornerCoord.x);+ return sign(coord) * float2(gradX, 1.0 - gradX);+ }+}"""++@Language("AGSL")+internal const val RoundedRectRefractionShaderString = """+uniform shader content;++uniform float2 size;+uniform float2 offset;+uniform float4 cornerRadii;+uniform float refractionHeight;+uniform float refractionAmount;+uniform float depthEffect;++$RoundedRectSDF++float circleMap(float x) {+ return 1.0 - sqrt(1.0 - x * x);+}++half4 main(float2 coord) {+ float2 halfSize = size * 0.5;+ float2 centeredCoord = (coord + offset) - halfSize;+ float radius = radiusAt(coord, cornerRadii);++ float sd = sdRoundedRect(centeredCoord, halfSize, radius);+ if (-sd >= refractionHeight) {+ return content.eval(coord);+ }+ sd = min(sd, 0.0);++ float d = circleMap(1.0 - -sd / refractionHeight) * refractionAmount;+ float gradRadius = min(radius * 1.5, min(halfSize.x, halfSize.y));+ float2 grad = normalize(gradSdRoundedRect(centeredCoord, halfSize, gradRadius) + depthEffect * normalize(centeredCoord));++ float2 refractedCoord = coord + d * grad;+ return content.eval(refractedCoord);+}"""++@Language("AGSL")+internal val RoundedRectRefractionWithDispersionShaderString = """+uniform shader content;++uniform float2 size;+uniform float2 offset;+uniform float4 cornerRadii;+uniform float refractionHeight;+uniform float refractionAmount;+uniform float depthEffect;+uniform float chromaticAberration;++$RoundedRectSDF++float circleMap(float x) {+ return 1.0 - sqrt(1.0 - x * x);+}++half4 main(float2 coord) {+ float2 halfSize = size * 0.5;+ float2 centeredCoord = (coord + offset) - halfSize;+ float radius = radiusAt(coord, cornerRadii);++ float sd = sdRoundedRect(centeredCoord, halfSize, radius);+ if (-sd >= refractionHeight) {+ return content.eval(coord);+ }+ sd = min(sd, 0.0);++ float d = circleMap(1.0 - -sd / refractionHeight) * refractionAmount;+ float gradRadius = min(radius * 1.5, min(halfSize.x, halfSize.y));+ float2 grad = normalize(gradSdRoundedRect(centeredCoord, halfSize, gradRadius) + depthEffect * normalize(centeredCoord));++ float2 refractedCoord = coord + d * grad;+ float dispersionIntensity = chromaticAberration * ((centeredCoord.x * centeredCoord.y) / (halfSize.x * halfSize.y));+ float2 dispersedCoord = d * grad * dispersionIntensity;++ half4 color = half4(0.0);++ half4 red = content.eval(refractedCoord + dispersedCoord);+ color.r += red.r / 3.5;+ color.a += red.a / 7.0;++ half4 orange = content.eval(refractedCoord + dispersedCoord * (2.0 / 3.0));+ color.r += orange.r / 3.5;+ color.g += orange.g / 7.0;+ color.a += orange.a / 7.0;++ half4 yellow = content.eval(refractedCoord + dispersedCoord * (1.0 / 3.0));+ color.r += yellow.r / 3.5;+ color.g += yellow.g / 3.5;+ color.a += yellow.a / 7.0;++ half4 green = content.eval(refractedCoord);+ color.g += green.g / 3.5;+ color.a += green.a / 7.0;++ half4 cyan = content.eval(refractedCoord - dispersedCoord * (1.0 / 3.0));+ color.g += cyan.g / 3.5;+ color.b += cyan.b / 3.0;+ color.a += cyan.a / 7.0;++ half4 blue = content.eval(refractedCoord - dispersedCoord * (2.0 / 3.0));+ color.b += blue.b / 3.0;+ color.a += blue.a / 7.0;++ half4 purple = content.eval(refractedCoord - dispersedCoord);+ color.r += purple.r / 7.0;+ color.b += purple.b / 3.0;+ color.a += purple.a / 7.0;++ return color;+}"""++@Language("AGSL")+internal const val DefaultHighlightShaderString = """+uniform float2 size;+uniform float4 cornerRadii;+layout(color) uniform half4 color;+uniform float angle;+uniform float falloff;++$RoundedRectSDF++half4 main(float2 coord) {+ float2 halfSize = size * 0.5;+ float2 centeredCoord = coord - halfSize;+ float radius = radiusAt(coord, cornerRadii);++ float gradRadius = min(radius * 1.5, min(halfSize.x, halfSize.y));+ float2 grad = gradSdRoundedRect(centeredCoord, halfSize, gradRadius);+ float2 normal = float2(cos(angle), sin(angle));+ float d = dot(grad, normal);+ float intensity = pow(abs(d), falloff);+ return color * intensity;+}"""++@Language("AGSL")+internal const val AmbientHighlightShaderString = """+uniform float2 size;+uniform float4 cornerRadii;+uniform float angle;+uniform float falloff;++$RoundedRectSDF++half4 main(float2 coord) {+ float2 halfSize = size * 0.5;+ float2 centeredCoord = coord - halfSize;+ float radius = radiusAt(coord, cornerRadii);++ float gradRadius = min(radius * 1.5, min(halfSize.x, halfSize.y));+ float2 grad = gradSdRoundedRect(centeredCoord, halfSize, gradRadius);+ float2 normal = float2(cos(angle), sin(angle));+ float d = dot(grad, normal);+ float intensity = pow(abs(d), falloff);+ float t = step(0.0, d);+ return half4(t, t, t, 1.0) * intensity;+}"""diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/internal/ShapeProvider.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/internal/ShapeProvider.ktnew file mode 100644index 00000000..01733b9e--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/internal/ShapeProvider.kt@@ -0,0 +1,56 @@+/*+ * Vendored from Kyant0/backdrop v2.0.0 (io.github.kyant0:backdrop)+ * https://github.com/Kyant0/backdrop — Copyright 2025 Kyant0, Apache License 2.0+ *+ * Vendored so the library ships as source with this app (binary AARs compiled+ * against older Compose broke at runtime) and to add a backdrop resolution+ * scale for cheaper effect rendering. KMP expect/actual declarations were+ * merged into this single Android source set. Package renamed accordingly.+ * Myspoti copy taken from BitChord's vendored tree (github.com/kushagrasinghx/BitChord,+ * app/src/main/java/com/music/bitchord/ui/components/backdrop at edc1e6f), which adds+ * backdropScale and exportedBackdrop to drawBackdrop. Package renamed again for Myspoti.+ */+package com.music.spotui.ui.immersive.shell.backdrop.internal++import androidx.compose.runtime.Immutable+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.graphics.Outline+import androidx.compose.ui.graphics.Shape+import androidx.compose.ui.unit.Density+import androidx.compose.ui.unit.LayoutDirection++@Immutable+internal class ShapeProvider(val shapeBlock: () -> Shape) {++ private var _shape: Shape? = null+ private var _outline: Outline? = null+ private var _size: Size = Size.Unspecified+ private var _layoutDirection: LayoutDirection? = null+ private var _density: Float? = null++ val innerShape+ get() = shapeBlock()++ val shape = object : Shape {++ override fun createOutline(+ size: Size,+ layoutDirection: LayoutDirection,+ density: Density+ ): Outline {+ val shape = shapeBlock()+ if (_shape != shape) {+ _shape = shape+ _outline = null+ }+ if (_outline == null || _size != size || _layoutDirection != layoutDirection || _density != density.density) {+ _size = size+ _layoutDirection = layoutDirection+ _density = density.density+ _outline = shape.createOutline(size, layoutDirection, density)+ }++ return _outline!!+ }+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/shadow/InnerShadow.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/shadow/InnerShadow.ktnew file mode 100644index 00000000..5138367d--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/shadow/InnerShadow.kt@@ -0,0 +1,53 @@+/*+ * Vendored from Kyant0/backdrop v2.0.0 (io.github.kyant0:backdrop)+ * https://github.com/Kyant0/backdrop — Copyright 2025 Kyant0, Apache License 2.0+ *+ * Vendored so the library ships as source with this app (binary AARs compiled+ * against older Compose broke at runtime) and to add a backdrop resolution+ * scale for cheaper effect rendering. KMP expect/actual declarations were+ * merged into this single Android source set. Package renamed accordingly.+ * Myspoti copy taken from BitChord's vendored tree (github.com/kushagrasinghx/BitChord,+ * app/src/main/java/com/music/bitchord/ui/components/backdrop at edc1e6f), which adds+ * backdropScale and exportedBackdrop to drawBackdrop. Package renamed again for Myspoti.+ */+package com.music.spotui.ui.immersive.shell.backdrop.shadow++import androidx.annotation.FloatRange+import androidx.compose.runtime.Immutable+import androidx.compose.runtime.Stable+import androidx.compose.ui.graphics.BlendMode+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.graphics.lerp+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.DpOffset+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.lerp+import androidx.compose.ui.util.lerp++@Immutable+data class InnerShadow(+ val radius: Dp = 24f.dp,+ val offset: DpOffset = DpOffset(0f.dp, radius),+ val color: Color = Color.Black.copy(alpha = 0.15f),+ @param:FloatRange(from = 0.0, to = 1.0) val alpha: Float = 1f,+ val blendMode: BlendMode = DrawScope.DefaultBlendMode+) {++ companion object {++ @Stable+ val Default: InnerShadow = InnerShadow()+ }+}++@Stable+fun lerp(start: InnerShadow, stop: InnerShadow, fraction: Float): InnerShadow {+ return InnerShadow(+ radius = lerp(start.radius, stop.radius, fraction),+ offset = lerp(start.offset, stop.offset, fraction),+ color = lerp(start.color, stop.color, fraction),+ alpha = lerp(start.alpha, stop.alpha, fraction),+ blendMode = if (fraction < 0.5f) start.blendMode else stop.blendMode+ )+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/shadow/InnerShadowModifier.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/shadow/InnerShadowModifier.ktnew file mode 100644index 00000000..27a9cea8--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/shadow/InnerShadowModifier.kt@@ -0,0 +1,170 @@+/*+ * Vendored from Kyant0/backdrop v2.0.0 (io.github.kyant0:backdrop)+ * https://github.com/Kyant0/backdrop — Copyright 2025 Kyant0, Apache License 2.0+ *+ * Vendored so the library ships as source with this app (binary AARs compiled+ * against older Compose broke at runtime) and to add a backdrop resolution+ * scale for cheaper effect rendering. KMP expect/actual declarations were+ * merged into this single Android source set. Package renamed accordingly.+ * Myspoti copy taken from BitChord's vendored tree (github.com/kushagrasinghx/BitChord,+ * app/src/main/java/com/music/bitchord/ui/components/backdrop at edc1e6f), which adds+ * backdropScale and exportedBackdrop to drawBackdrop. Package renamed again for Myspoti.+ */+package com.music.spotui.ui.immersive.shell.backdrop.shadow++import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.BlendMode+import androidx.compose.ui.graphics.BlurEffect+import androidx.compose.ui.graphics.Outline+import androidx.compose.ui.graphics.Paint+import androidx.compose.ui.graphics.Path+import androidx.compose.ui.graphics.TileMode+import androidx.compose.ui.graphics.drawOutline+import androidx.compose.ui.graphics.drawscope.ContentDrawScope+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.graphics.layer.CompositingStrategy+import androidx.compose.ui.graphics.layer.GraphicsLayer+import androidx.compose.ui.graphics.layer.drawLayer+import androidx.compose.ui.node.DrawModifierNode+import androidx.compose.ui.node.ModifierNodeElement+import androidx.compose.ui.node.invalidateDraw+import androidx.compose.ui.node.requireGraphicsContext+import androidx.compose.ui.platform.InspectorInfo+import androidx.compose.ui.unit.Density+import com.music.spotui.ui.immersive.shell.backdrop.internal.ShapeProvider+import com.music.spotui.ui.immersive.shell.backdrop.internal.clipOutline+import com.music.spotui.ui.immersive.shell.backdrop.isRenderEffectSupported++internal class InnerShadowElement(+ val shapeProvider: ShapeProvider,+ val shadow: () -> InnerShadow?+) : ModifierNodeElement<InnerShadowNode>() {++ override fun create(): InnerShadowNode {+ return InnerShadowNode(shapeProvider, shadow)+ }++ override fun update(node: InnerShadowNode) {+ node.shapeProvider = shapeProvider+ node.shadow = shadow+ node.invalidateDraw()+ }++ override fun InspectorInfo.inspectableProperties() {+ name = "innerShadow"+ properties["shapeProvider"] = shapeProvider+ properties["shadow"] = shadow+ }++ override fun equals(other: Any?): Boolean {+ if (this === other) return true+ if (other !is InnerShadowElement) return false++ if (shapeProvider != other.shapeProvider) return false+ if (shadow != other.shadow) return false++ return true+ }++ override fun hashCode(): Int {+ var result = shapeProvider.hashCode()+ result = 31 * result + shadow.hashCode()+ return result+ }+}++internal class InnerShadowNode(+ var shapeProvider: ShapeProvider,+ var shadow: () -> InnerShadow?+) : DrawModifierNode, Modifier.Node() {++ override val shouldAutoInvalidate: Boolean = false++ private var shadowLayer: GraphicsLayer? = null++ private val paint = Paint()+ private var clipPath: Path? = null++ private var prevRadius = Float.NaN++ override fun ContentDrawScope.draw() {+ drawContent()++ if (!isRenderEffectSupported()) return++ val shadow = shadow() ?: return++ val shadowLayer = shadowLayer+ if (shadowLayer != null) {+ val size = size+ val density: Density = this+ val layoutDirection = layoutDirection++ val radius = shadow.radius.toPx()+ val offsetX = shadow.offset.x.toPx()+ val offsetY = shadow.offset.y.toPx()++ val outline = shapeProvider.shape.createOutline(size, layoutDirection, density)+ val clipPath =+ if (outline is Outline.Rounded) {+ clipPath ?: Path().also { clipPath = it }+ } else {+ null+ }++ configurePaint(shadow)++ shadowLayer.alpha = shadow.alpha+ shadowLayer.blendMode = shadow.blendMode+ if (prevRadius != radius) {+ shadowLayer.renderEffect =+ if (radius > 0f) {+ BlurEffect(radius, radius, TileMode.Decal)+ } else {+ null+ }+ prevRadius = radius+ }+ shadowLayer.record {+ val canvas = drawContext.canvas+ canvas.save()+ canvas.clipOutline(outline, clipPath)+ canvas.drawOutline(outline, paint)+ canvas.translate(offsetX, offsetY)+ canvas.drawOutline(outline, ShadowMaskPaint)+ canvas.translate(-offsetX, -offsetY)+ canvas.restore()+ }++ val canvas = drawContext.canvas+ canvas.save()+ canvas.clipOutline(outline, clipPath)+ drawLayer(shadowLayer)+ canvas.restore()+ }+ }++ override fun onAttach() {+ val graphicsContext = requireGraphicsContext()+ shadowLayer =+ graphicsContext.createGraphicsLayer().apply {+ compositingStrategy = CompositingStrategy.Offscreen+ }+ }++ override fun onDetach() {+ val graphicsContext = requireGraphicsContext()+ shadowLayer?.let { layer ->+ graphicsContext.releaseGraphicsLayer(layer)+ shadowLayer = null+ }+ }++ private fun DrawScope.configurePaint(shadow: InnerShadow) {+ paint.color = shadow.color+ }+}++private val ShadowMaskPaint = Paint().apply {+ blendMode = BlendMode.Clear+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/shadow/Shadow.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/shadow/Shadow.ktnew file mode 100644index 00000000..1bdf47c6--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/shadow/Shadow.kt@@ -0,0 +1,39 @@+/*+ * Vendored from Kyant0/backdrop v2.0.0 (io.github.kyant0:backdrop)+ * https://github.com/Kyant0/backdrop — Copyright 2025 Kyant0, Apache License 2.0+ *+ * Vendored so the library ships as source with this app (binary AARs compiled+ * against older Compose broke at runtime) and to add a backdrop resolution+ * scale for cheaper effect rendering. KMP expect/actual declarations were+ * merged into this single Android source set. Package renamed accordingly.+ * Myspoti copy taken from BitChord's vendored tree (github.com/kushagrasinghx/BitChord,+ * app/src/main/java/com/music/bitchord/ui/components/backdrop at edc1e6f), which adds+ * backdropScale and exportedBackdrop to drawBackdrop. Package renamed again for Myspoti.+ */+package com.music.spotui.ui.immersive.shell.backdrop.shadow++import androidx.annotation.FloatRange+import androidx.compose.runtime.Immutable+import androidx.compose.runtime.Stable+import androidx.compose.ui.graphics.BlendMode+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.DpOffset+import androidx.compose.ui.unit.dp++@Immutable+data class Shadow(+ val radius: Dp = 24f.dp,+ val offset: DpOffset = DpOffset(0f.dp, radius / 6f),+ val color: Color = Color.Black.copy(alpha = 0.1f),+ @param:FloatRange(from = 0.0, to = 1.0) val alpha: Float = 1f,+ val blendMode: BlendMode = DrawScope.DefaultBlendMode+) {++ companion object {++ @Stable+ val Default: Shadow = Shadow()+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/shadow/ShadowModifier.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/shadow/ShadowModifier.ktnew file mode 100644index 00000000..cc9ae7fb--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/shadow/ShadowModifier.kt@@ -0,0 +1,149 @@+/*+ * Vendored from Kyant0/backdrop v2.0.0 (io.github.kyant0:backdrop)+ * https://github.com/Kyant0/backdrop — Copyright 2025 Kyant0, Apache License 2.0+ *+ * Vendored so the library ships as source with this app (binary AARs compiled+ * against older Compose broke at runtime) and to add a backdrop resolution+ * scale for cheaper effect rendering. KMP expect/actual declarations were+ * merged into this single Android source set. Package renamed accordingly.+ * Myspoti copy taken from BitChord's vendored tree (github.com/kushagrasinghx/BitChord,+ * app/src/main/java/com/music/bitchord/ui/components/backdrop at edc1e6f), which adds+ * backdropScale and exportedBackdrop to drawBackdrop. Package renamed again for Myspoti.+ */+package com.music.spotui.ui.immersive.shell.backdrop.shadow++import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.BlendMode+import androidx.compose.ui.graphics.Paint+import androidx.compose.ui.graphics.drawOutline+import androidx.compose.ui.graphics.drawscope.ContentDrawScope+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.graphics.drawscope.translate+import androidx.compose.ui.graphics.layer.CompositingStrategy+import androidx.compose.ui.graphics.layer.GraphicsLayer+import androidx.compose.ui.graphics.layer.drawLayer+import androidx.compose.ui.node.DrawModifierNode+import androidx.compose.ui.node.ModifierNodeElement+import androidx.compose.ui.node.invalidateDraw+import androidx.compose.ui.node.requireGraphicsContext+import androidx.compose.ui.platform.InspectorInfo+import androidx.compose.ui.unit.Density+import androidx.compose.ui.unit.IntSize+import com.music.spotui.ui.immersive.shell.backdrop.internal.ShapeProvider+import com.music.spotui.ui.immersive.shell.backdrop.internal.blur+import kotlin.math.ceil++internal class ShadowElement(+ val shapeProvider: ShapeProvider,+ val shadow: () -> Shadow?+) : ModifierNodeElement<ShadowNode>() {++ override fun create(): ShadowNode {+ return ShadowNode(shapeProvider, shadow)+ }++ override fun update(node: ShadowNode) {+ node.shapeProvider = shapeProvider+ node.shadow = shadow+ node.invalidateDraw()+ }++ override fun InspectorInfo.inspectableProperties() {+ name = "shadow"+ properties["shapeProvider"] = shapeProvider+ properties["shadow"] = shadow+ }++ override fun equals(other: Any?): Boolean {+ if (this === other) return true+ if (other !is ShadowElement) return false++ if (shapeProvider != other.shapeProvider) return false+ if (shadow != other.shadow) return false++ return true+ }++ override fun hashCode(): Int {+ var result = shapeProvider.hashCode()+ result = 31 * result + shadow.hashCode()+ return result+ }+}++internal class ShadowNode(+ var shapeProvider: ShapeProvider,+ var shadow: () -> Shadow?+) : DrawModifierNode, Modifier.Node() {++ override val shouldAutoInvalidate: Boolean = false++ private var shadowLayer: GraphicsLayer? = null++ private val paint = Paint()++ override fun ContentDrawScope.draw() {+ val shadow = shadow() ?: return drawContent()++ val shadowLayer = shadowLayer+ if (shadowLayer != null) {+ val size = size+ val density: Density = this+ val layoutDirection = layoutDirection++ val radius = shadow.radius.toPx()+ val offsetX = shadow.offset.x.toPx()+ val offsetY = shadow.offset.y.toPx()+ val shadowSize = IntSize(+ ceil(size.width + radius * 4f + offsetX).toInt(),+ ceil(size.height + radius * 4f + offsetY).toInt()+ )+ val outline = shapeProvider.shape.createOutline(size, layoutDirection, density)++ configurePaint(shadow)++ shadowLayer.alpha = shadow.alpha+ shadowLayer.blendMode = shadow.blendMode+ shadowLayer.record(shadowSize) {+ translate(radius * 2f + offsetX, radius * 2f + offsetY) {+ val canvas = drawContext.canvas+ canvas.drawOutline(outline, paint)+ canvas.translate(-offsetX, -offsetY)+ canvas.drawOutline(outline, ShadowMaskPaint)+ canvas.translate(offsetX, offsetY)+ }+ }++ translate(-radius * 2f, -radius * 2f) {+ drawLayer(shadowLayer)+ }+ }++ drawContent()+ }++ override fun onAttach() {+ val graphicsContext = requireGraphicsContext()+ shadowLayer =+ graphicsContext.createGraphicsLayer().apply {+ compositingStrategy = CompositingStrategy.Offscreen+ }+ }++ override fun onDetach() {+ val graphicsContext = requireGraphicsContext()+ shadowLayer?.let { layer ->+ graphicsContext.releaseGraphicsLayer(layer)+ shadowLayer = null+ }+ }++ private fun DrawScope.configurePaint(shadow: Shadow) {+ paint.color = shadow.color+ paint.blur(shadow.radius.toPx())+ }+}++private val ShadowMaskPaint = Paint().apply {+ blendMode = BlendMode.Clear+}diff --git a/base/app/src/main/java/com/music/spotui/ui/look/DemoSong.kt b/base/app/src/main/java/com/music/spotui/ui/look/DemoSong.ktnew file mode 100644index 00000000..a56567ed--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/look/DemoSong.kt@@ -0,0 +1,170 @@+package com.music.spotui.ui.look++import androidx.compose.animation.core.FastOutSlowInEasing+import androidx.compose.foundation.Canvas+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.graphics.Brush+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.Path+import androidx.compose.ui.graphics.drawscope.clipRect++/*+ * The song the look preview plays: written for Myspoti, nothing real in it. The cover is drawn,+ * the words are original and timed by hand, and nothing goes through the network.+ */++object DemoSong {+ const val TITLE = "Night Drive"+ const val ARTIST = "The Demo Band"+ const val ALBUM = "Neon Miles"+ const val DURATION_MS = 204_000L++ /** The cover's two loud colours and the night behind them, as the Immersive backdrop. */+ val mesh = MeshPalette(listOf(Color(0xFFFF3D7F), Color(0xFF7B2FF7), Color(0xFFFF9A3C), Color(0xFF241A8C)))++ /** What the Classic player takes from the cover: its dark vibrant colour. */+ val dominant = Color(0xFF8E1B5A)++ /** The Classic lyrics page: the cover's colour, dark unsung words, white sung ones. */+ val lyricsBackground = Color(0xFFC2386F)+ val lyricsText = Color(0xFF3D0B24)++ private fun line(vararg words: Triple<String, Long, Long>) = SweptLine(+ timeMs = words.first().second,+ text = words.joinToString(" ") { it.first },+ words = words.map { (text, start, end) -> SweptWord(start, end, text) },+ )++ /** Three lines, timed word by word; the last word is held long enough to glow. */+ val lines = listOf(+ line(+ Triple("Headlights", 63_700L, 64_080L), Triple("paint", 64_080L, 64_300L), Triple("the", 64_300L, 64_400L),+ Triple("empty", 64_400L, 64_620L), Triple("road", 64_620L, 64_950L),+ ),+ line(+ Triple("Every", 64_950L, 65_200L), Triple("sign", 65_200L, 65_420L), Triple("is", 65_420L, 65_520L),+ Triple("pointing", 65_520L, 65_850L), Triple("home", 65_850L, 66_150L),+ ),+ line(+ Triple("Until", 66_150L, 66_400L), Triple("the", 66_400L, 66_500L), Triple("morning", 66_500L, 66_700L),+ Triple("glows", 66_700L, 67_700L),+ ),+ )++ /** The line being sung at [songMs]: the last one started, the first before any has. */+ fun activeLine(songMs: Long): Int = lines.indexOfLast { it.timeMs <= songMs }.coerceAtLeast(0)+}++/**+ * The preview's ~9 s loop, in milliseconds from its start: the mini player, the player opening,+ * a second's pause, the lyrics with their three lines, then everything closing again.+ */+object DemoScript {+ const val LOOP_MS = 9_200L+ private const val OPEN = 500L+ private const val MOVE = 500L+ private const val PAUSE_FROM = 2_000L+ private const val PAUSE_TO = 3_000L+ private const val LYRICS_OPEN = 3_300L+ private const val LYRICS_MOVE = 400L+ private const val LYRICS_CLOSE = 7_700L+ private const val CLOSE = 8_100L+ private const val SONG_START_MS = 61_000L++ /** Still frames for "Remove animations": the player, the pause, the lyrics. */+ val stills = listOf(1_500L, 2_700L, 5_300L)++ /** How far the player is open, 0..1. */+ fun open(t: Long): Float = rise(t, OPEN, MOVE) * (1f - rise(t, CLOSE, MOVE))++ /** How far the lyrics are open, 0..1. */+ fun lyrics(t: Long): Float = rise(t, LYRICS_OPEN, LYRICS_MOVE) * (1f - rise(t, LYRICS_CLOSE, LYRICS_MOVE))++ fun playing(t: Long): Boolean = t < PAUSE_FROM || t >= PAUSE_TO++ /** Where the song is: it runs with the loop except during the pause. */+ fun songMs(t: Long): Long = SONG_START_MS + t - (t.coerceIn(PAUSE_FROM, PAUSE_TO) - PAUSE_FROM)++ private fun rise(t: Long, from: Long, length: Long): Float =+ FastOutSlowInEasing.transform(((t - from).toFloat() / length).coerceIn(0f, 1f))+}++/** "m:ss", as players print a position. */+fun demoTime(ms: Long): String {+ val s = (ms / 1000).coerceAtLeast(0)+ return "${s / 60}:${(s % 60).toString().padStart(2, '0')}"+}++/** The demo cover, drawn: a sun going down over a road, in the two colours the backdrop picks up. */+@Composable+fun DemoCover(modifier: Modifier = Modifier) {+ Canvas(modifier) {+ val w = size.width+ val h = size.height+ drawRect(Brush.verticalGradient(listOf(Color(0xFF2A0B5E), Color(0xFFC2185B), Color(0xFFFF8A3D)), endY = h * 0.7f))+ // The sun, striped across its lower half.+ val sun = Offset(w * 0.5f, h * 0.56f)+ val r = w * 0.24f+ drawCircle(Brush.verticalGradient(listOf(Color(0xFFFFE07A), Color(0xFFFF4F8B), ), startY = sun.y - r, endY = sun.y + r), r, sun)+ for (i in 0 until 4) {+ val y = sun.y + r * (0.15f + i * 0.2f)+ drawRect(Color(0xFFC2185B).copy(alpha = 0.85f), Offset(sun.x - r, y), Size(r * 2, h * (0.012f + i * 0.006f)))+ }+ // The ground, and the road running into it.+ val horizon = h * 0.68f+ drawRect(Brush.verticalGradient(listOf(Color(0xFF3A1170), Color(0xFF12052B)), startY = horizon), Offset(0f, horizon), Size(w, h - horizon))+ val road = Path().apply {+ moveTo(w * 0.47f, horizon); lineTo(w * 0.53f, horizon); lineTo(w * 0.82f, h); lineTo(w * 0.18f, h); close()+ }+ drawPath(road, Color(0xFF1E0A40))+ clipRect(top = horizon) {+ for (i in 0 until 4) {+ val f = 0.12f + i * 0.24f+ val y = horizon + (h - horizon) * f+ val dash = (h - horizon) * (0.05f + f * 0.1f)+ val half = w * (0.004f + f * 0.012f)+ drawRect(Color(0xFFFFD54F), Offset(w * 0.5f - half, y), Size(half * 2, dash))+ }+ }+ // The horizon's glow.+ drawRect(+ Brush.verticalGradient(listOf(Color.Transparent, Color(0xFFFF8A3D).copy(alpha = 0.55f), Color.Transparent), startY = horizon - h * 0.04f, endY = horizon + h * 0.04f),+ Offset(0f, horizon - h * 0.04f), Size(w, h * 0.08f),+ )+ }+}++/** The look screen's own backdrop colours (Immersive), cycled one into the next. */+val LookMeshPalettes: List<MeshPalette> = listOf(+ DemoSong.mesh,+ MeshPalette(listOf(Color(0xFF00A6C8), Color(0xFF3D5AFE), Color(0xFF26C281), Color(0xFF0B2350))),+ MeshPalette(listOf(Color(0xFFFF6E40), Color(0xFFFFC233), Color(0xFFE0306A), Color(0xFF4A1430))),+ MeshPalette(listOf(Color(0xFF9C5CFF), Color(0xFFFF5CC8), Color(0xFF4E7BFF), Color(0xFF1C1250))),+)++/** Invented names for the home page's tiles. */+val DemoShelf = listOf("Night Drive", "Slow Hours", "Sunday Club", "Low Tide", "City Lights", "Late Bloom", "Paper Moons", "Blue Static")++/** A tile of the demo home page: a drawn cover in one of a few made-up palettes. */+@Composable+fun DemoTile(seed: Int, modifier: Modifier = Modifier) {+ val palettes = listOf(+ Color(0xFF1E88E5) to Color(0xFF00E5A8), Color(0xFFFF7043) to Color(0xFFFFD54F),+ Color(0xFF7E57C2) to Color(0xFFFF4F8B), Color(0xFF00897B) to Color(0xFFB2FF59),+ Color(0xFFD81B60) to Color(0xFFFF9E80), Color(0xFF3949AB) to Color(0xFF80DEEA),+ Color(0xFF6D4C41) to Color(0xFFFFB74D), Color(0xFF263238) to Color(0xFF4DD0E1),+ )+ val (a, b) = palettes[seed % palettes.size]+ Canvas(modifier) {+ drawRect(Brush.linearGradient(listOf(a, b), start = Offset.Zero, end = Offset(size.width, size.height)))+ val r = size.minDimension+ when (seed % 3) {+ 0 -> drawCircle(Color.White.copy(alpha = 0.22f), r * 0.32f, Offset(size.width * 0.68f, size.height * 0.36f))+ 1 -> for (i in 0 until 4) drawRect(Color.Black.copy(alpha = 0.12f), Offset(0f, size.height * (0.2f + i * 0.2f)), Size(size.width, size.height * 0.07f))+ else -> drawCircle(Color.Black.copy(alpha = 0.18f), r * 0.55f, Offset(size.width * 0.2f, size.height * 0.9f))+ }+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/look/Look.kt b/base/app/src/main/java/com/music/spotui/ui/look/Look.ktnew file mode 100644index 00000000..c72c5777--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/look/Look.kt@@ -0,0 +1,59 @@+package com.music.spotui.ui.look++import android.provider.Settings+import androidx.compose.runtime.Composable+import androidx.compose.runtime.CompositionLocalProvider+import androidx.compose.runtime.compositionLocalOf+import androidx.compose.runtime.remember+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.text.font.Font+import androidx.compose.ui.text.font.FontFamily+import androidx.compose.ui.text.font.FontWeight+import app.myspoti.engine.R+import com.music.spotui.data.preferences.Look+import com.music.spotui.data.preferences.LookPref++/** The look the screens below are drawn in; see [Look]. */+val LocalLook = compositionLocalOf { Look.CLASSIC }++/** Hands the chosen look ([LookPref.look]) to everything inside. */+@Composable+fun ProvideLook(content: @Composable () -> Unit) {+ CompositionLocalProvider(LocalLook provides LookPref.look, content = content)+}++/**+ * The Immersive look's typeface: Inter (SIL Open Font License 1.1, licenses/Inter-OFL.txt), the+ * free face closest to the system one of the player it follows, cut down to Latin. One variable+ * file with a weight axis and an optical-size axis: text sizes use its "Text" cut (opsz 14),+ * titles from 20sp up its "Display" cut (opsz 32), tighter and finer, as that face does.+ */+@OptIn(androidx.compose.ui.text.ExperimentalTextApi::class)+private fun inter(weight: Int, opticalSize: Float) = Font(+ R.font.inter,+ weight = FontWeight(weight),+ variationSettings = androidx.compose.ui.text.font.FontVariation.Settings(+ androidx.compose.ui.text.font.FontVariation.weight(weight),+ androidx.compose.ui.text.font.FontVariation.Setting("opsz", opticalSize),+ ),+)++private val weights = listOf(400, 500, 600, 700, 800)++/** Body text, captions, buttons. */+val ImmersiveSans = FontFamily(weights.map { inter(it, 14f) })++/** Titles, the player's title and the lyrics (20sp and up). */+val ImmersiveDisplay = FontFamily(weights.map { inter(it, 32f) })++/**+ * True when the phone asks for no animation ("Remove animations": the animator duration+ * scale is 0). Read once per composition; the setting rarely changes while a screen is up.+ */+@Composable+fun rememberReduceMotion(): Boolean {+ val context = LocalContext.current+ return remember(context) {+ Settings.Global.getFloat(context.contentResolver, Settings.Global.ANIMATOR_DURATION_SCALE, 1f) == 0f+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/look/LookPreview.kt b/base/app/src/main/java/com/music/spotui/ui/look/LookPreview.ktnew file mode 100644index 00000000..4a1bf833--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/look/LookPreview.kt@@ -0,0 +1,757 @@+package com.music.spotui.ui.look++import androidx.compose.animation.Crossfade+import androidx.compose.animation.core.animateFloatAsState+import androidx.compose.animation.core.tween+import androidx.compose.foundation.Canvas+import androidx.compose.foundation.background+import androidx.compose.foundation.border+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxScope+import androidx.compose.foundation.layout.BoxWithConstraints+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxHeight+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.requiredSize+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.rounded.FastForward+import androidx.compose.material.icons.rounded.FastRewind+import androidx.compose.material.icons.rounded.FormatListBulleted+import androidx.compose.material.icons.rounded.Home+import androidx.compose.material.icons.rounded.KeyboardArrowDown+import androidx.compose.material.icons.rounded.LibraryMusic+import androidx.compose.material.icons.rounded.Lyrics+import androidx.compose.material.icons.rounded.MoreHoriz+import androidx.compose.material.icons.rounded.MoreVert+import androidx.compose.material.icons.rounded.Pause+import androidx.compose.material.icons.rounded.PlayArrow+import androidx.compose.material.icons.rounded.QueueMusic+import androidx.compose.material.icons.rounded.Search+import androidx.compose.material.icons.rounded.Speaker+import androidx.compose.material.icons.rounded.StarOutline+import androidx.compose.material.icons.rounded.VolumeDown+import androidx.compose.material.icons.rounded.VolumeUp+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.Stable+import androidx.compose.runtime.State+import androidx.compose.runtime.derivedStateOf+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableLongStateOf+import androidx.compose.runtime.mutableStateListOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.withFrameNanos+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.blur+import androidx.compose.ui.draw.clip+import androidx.compose.ui.draw.clipToBounds+import androidx.compose.ui.draw.drawWithContent+import androidx.compose.ui.geometry.CornerRadius+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.graphics.BlendMode+import androidx.compose.ui.graphics.Brush+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.CompositingStrategy+import androidx.compose.ui.graphics.TransformOrigin+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.graphics.lerp+import androidx.compose.ui.graphics.vector.ImageVector+import androidx.compose.ui.layout.onSizeChanged+import androidx.compose.ui.res.painterResource+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.SpanStyle+import androidx.compose.ui.text.TextStyle+import androidx.compose.ui.text.buildAnnotatedString+import androidx.compose.ui.text.font.FontFamily+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.text.withStyle+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.TextUnit+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import app.myspoti.engine.R+import com.music.spotui.data.preferences.Look+import com.music.spotui.ui.theme.AppSans+import kotlin.math.abs+import kotlin.math.min++/*+ * The live preview of the onboarding's look step: each look drawn at a real phone's size, then+ * scaled down into a phone frame, playing DemoScript's loop with DemoSong. Small stateless+ * pieces for now; step (d) of docs/style-choix-onboarding.md swaps them for the real players.+ */++private val PhoneW = 360.dp+private val PhoneH = 760.dp++/** The preview's clock: where the loop is, and where the demo song is with it. */+@Stable+class DemoClock(startMs: Long) {+ val t = mutableLongStateOf(startMs)+ /** The song position, read by the lyric sweep in its draw phase. */+ val song = mutableLongStateOf(DemoScript.songMs(startMs))++ fun set(ms: Long) {+ t.longValue = ms+ song.longValue = DemoScript.songMs(ms)+ }+}++/** A clock that runs on the display's frames while [running], and holds still otherwise. */+@Composable+fun rememberDemoClock(running: Boolean): DemoClock {+ val clock = remember { DemoClock(0L) }+ LaunchedEffect(running) {+ if (!running) return@LaunchedEffect+ var last = -1L+ var nanos = clock.t.longValue * 1_000_000L+ while (true) withFrameNanos { now ->+ if (last >= 0) {+ nanos = (nanos + (now - last)) % (DemoScript.LOOP_MS * 1_000_000L)+ clock.set(nanos / 1_000_000L)+ }+ last = now+ }+ }+ return clock+}++/** A clock stopped at [ms], for the still frames. */+@Composable+fun rememberStillClock(ms: Long): DemoClock = remember(ms) { DemoClock(ms) }++/**+ * A phone, drawn: [content] is laid out at a real phone's size and scaled down to fit, so the+ * preview keeps the real proportions of text, icons and spacing.+ */+@Composable+fun PhoneFrame(modifier: Modifier = Modifier, content: @Composable BoxScope.() -> Unit) {+ BoxWithConstraints(modifier, contentAlignment = Alignment.Center) {+ val bezel = 5.dp+ val scale = min((maxWidth - bezel * 2) / PhoneW, (maxHeight - bezel * 2) / PhoneH).coerceAtLeast(0.05f)+ val outer = RoundedCornerShape(44.dp * scale + bezel)+ Box(+ Modifier+ .size(PhoneW * scale + bezel * 2, PhoneH * scale + bezel * 2)+ .background(Color(0xFF050505), outer)+ .border(1.dp, Color.White.copy(alpha = 0.16f), outer),+ contentAlignment = Alignment.Center,+ ) {+ Box(+ Modifier+ .requiredSize(PhoneW, PhoneH)+ .graphicsLayer {+ scaleX = scale+ scaleY = scale+ shape = RoundedCornerShape(44.dp)+ clip = true+ },+ content = content,+ )+ }+ }+}++/** One look, playing the demo loop on [clock]. [still] keeps the backdrop from drifting. */+@Composable+fun LookDemo(look: Look, clock: DemoClock, still: Boolean = false) {+ when (look) {+ Look.CLASSIC -> ClassicDemo(clock)+ Look.IMMERSIVE -> ImmersiveDemo(clock, still)+ }+}++/** The loop's moments, each recomposing only when it changes. */+private class DemoPhases(clock: DemoClock) {+ val open = derivedStateOf { DemoScript.open(clock.t.longValue) }+ val lyrics = derivedStateOf { DemoScript.lyrics(clock.t.longValue) }+ val playing = derivedStateOf { DemoScript.playing(clock.t.longValue) }+ val progress = derivedStateOf { clock.song.longValue.toFloat() / DemoSong.DURATION_MS }+ val seconds = derivedStateOf { clock.song.longValue / 1000 }+ val active = derivedStateOf { DemoSong.activeLine(clock.song.longValue) }+}++@Composable+private fun rememberPhases(clock: DemoClock) = remember(clock) { DemoPhases(clock) }++/** Where the cover is drawn, in phone dp. */+private data class CoverRect(val x: Float, val y: Float, val size: Float)++private fun lerp(a: CoverRect, b: CoverRect, f: Float) = CoverRect(+ a.x + (b.x - a.x) * f, a.y + (b.y - a.y) * f, a.size + (b.size - a.size) * f,+)++/**+ * The cover, flying between where it sits on each screen. Drawn at [base] dp at the phone's+ * top left and moved with a graphics layer, so a flight only relayers; [pause] is the Immersive+ * step back, about the cover's centre.+ */+@Composable+private fun FlyingCover(rect: () -> CoverRect, base: Float, radius: Dp, shadow: Boolean, pause: () -> Float = { 1f }) {+ val shape = RoundedCornerShape(radius)+ Box(+ Modifier+ .size(base.dp)+ .graphicsLayer {+ val r = rect()+ val p = pause()+ val s = r.size / base * p+ transformOrigin = TransformOrigin(0f, 0f)+ translationX = (r.x + r.size * (1f - p) / 2f).dp.toPx()+ translationY = (r.y + r.size * (1f - p) / 2f).dp.toPx()+ scaleX = s+ scaleY = s+ this.shape = shape+ clip = true+ if (shadow) shadowElevation = 20.dp.toPx()+ },+ ) { DemoCover(Modifier.fillMaxSize()) }+}++@Composable+private fun Glyph(icon: ImageVector, size: Dp, tint: Color = Color.White) =+ Icon(icon, contentDescription = null, tint = tint, modifier = Modifier.size(size))++@Composable+private fun Glyph(res: Int, size: Dp, tint: Color = Color.White) =+ Icon(painterResource(res), contentDescription = null, tint = tint, modifier = Modifier.size(size))++/** Play or pause, crossfading between the two glyphs. */+@Composable+private fun PlayGlyph(playing: Boolean, size: Dp, tint: Color) {+ Crossfade(playing, animationSpec = tween(150), label = "playGlyph") {+ Glyph(if (it) Icons.Rounded.Pause else Icons.Rounded.PlayArrow, size, tint)+ }+}++@Composable+private fun TimeRow(seconds: Long, color: Color, family: FontFamily, size: TextUnit, weight: FontWeight = FontWeight.Normal) {+ Row(Modifier.fillMaxWidth()) {+ Text(demoTime(seconds * 1000), color = color, fontSize = size, fontFamily = family, fontWeight = weight)+ Spacer(Modifier.weight(1f))+ Text("-" + demoTime(DemoSong.DURATION_MS - seconds * 1000), color = color, fontSize = size, fontFamily = family, fontWeight = weight)+ }+}++// ---------------------------------------------------------------- Classic: today's look++private val ClassicGrey = Color(0xFFB3B3B3)+private val ClassicGreen = Color(0xFF1DB954)+private val ClassicTop = Color(0xFF9A2A5C)+private val ClassicBottom = Color(0xFF2A0A1B)++@Composable+private fun ClassicDemo(clock: DemoClock) {+ val phases = rememberPhases(clock)+ val open by phases.open+ val lyrics by phases.lyrics+ val playing by phases.playing+ val mini = CoverRect(16f, 642f, 40f)+ val big = CoverRect(24f, 100f, 312f)+ Box(Modifier.fillMaxSize().background(Color(0xFF121212))) {+ ClassicHome()+ ClassicMini(playing, phases.progress, Modifier.align(Alignment.BottomCenter).padding(start = 8.dp, end = 8.dp, bottom = 70.dp))+ ClassicTabs(Modifier.align(Alignment.BottomCenter))+ if (open > 0f) ClassicPlayer(playing, phases, Modifier.graphicsLayer { translationY = (1f - open) * size.height })+ FlyingCover({ lerp(mini, big, open) }, base = 312f, radius = 8.dp, shadow = false)+ if (open > 0f) ClassicLyricsCard(clock, phases, { open }, { lyrics })+ }+}++/** A home page like today's: filter chips, eight shortcuts, a shelf of covers. */+@Composable+private fun ClassicHome() {+ Column(Modifier.fillMaxSize().padding(start = 16.dp, end = 16.dp, top = 48.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ Box(Modifier.size(32.dp).background(Color(0xFFFF8A65), CircleShape))+ listOf(R.string.look_demo_all, R.string.look_demo_music, R.string.look_demo_podcasts).forEachIndexed { i, label ->+ Text(+ stringResource(label), color = if (i == 0) Color.Black else Color.White, fontSize = 13.sp, fontFamily = AppSans,+ modifier = Modifier.background(if (i == 0) ClassicGreen else Color(0xFF2A2A2A), CircleShape).padding(horizontal = 14.dp, vertical = 7.dp),+ )+ }+ }+ Spacer(Modifier.height(4.dp))+ for (row in 0 until 4) {+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ for (col in 0 until 2) {+ val i = row * 2 + col+ Row(+ Modifier.weight(1f).height(56.dp).background(Color(0xFF2A2A2A), RoundedCornerShape(4.dp)).clip(RoundedCornerShape(4.dp)),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ DemoTile(i, Modifier.size(56.dp))+ Text(DemoShelf[i], color = Color.White, fontSize = 12.sp, fontWeight = FontWeight.Bold, fontFamily = AppSans,+ maxLines = 2, modifier = Modifier.padding(horizontal = 8.dp))+ }+ }+ }+ }+ Spacer(Modifier.height(12.dp))+ Text(stringResource(R.string.look_demo_section), color = Color.White, fontSize = 21.sp, fontWeight = FontWeight.Bold, fontFamily = AppSans)+ Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {+ for (i in 0 until 3) Column(Modifier.width(140.dp)) {+ DemoTile(i + 3, Modifier.size(140.dp).clip(RoundedCornerShape(4.dp)))+ Text(DemoShelf[(i + 5) % DemoShelf.size], color = ClassicGrey, fontSize = 12.sp, fontFamily = AppSans, maxLines = 1,+ modifier = Modifier.padding(top = 6.dp))+ }+ }+ }+}++@Composable+private fun ClassicMini(playing: Boolean, progress: State<Float>, modifier: Modifier) {+ Box(+ modifier+ .fillMaxWidth()+ .height(56.dp)+ .background(lerp(ClassicTop, Color.Black, 0.3f), RoundedCornerShape(6.dp))+ .clip(RoundedCornerShape(6.dp)),+ ) {+ Row(Modifier.fillMaxSize().padding(start = 56.dp, end = 14.dp), verticalAlignment = Alignment.CenterVertically) {+ Column(Modifier.weight(1f)) {+ Text(DemoSong.TITLE, color = Color.White, fontSize = 13.sp, fontWeight = FontWeight.Bold, fontFamily = AppSans, maxLines = 1)+ Text(DemoSong.ARTIST, color = Color.White.copy(alpha = 0.7f), fontSize = 12.sp, fontFamily = AppSans, maxLines = 1)+ }+ Glyph(R.drawable.ic_devices, 22.dp)+ Spacer(Modifier.width(18.dp))+ PlayGlyph(playing, 30.dp, Color.White)+ }+ Canvas(Modifier.align(Alignment.BottomCenter).fillMaxWidth().padding(horizontal = 8.dp).height(2.dp)) {+ drawRect(Color.White.copy(alpha = 0.25f))+ drawRect(Color.White, size = Size(size.width * progress.value, size.height))+ }+ }+}++@Composable+private fun ClassicTabs(modifier: Modifier) {+ Row(+ modifier+ .fillMaxWidth()+ .height(66.dp)+ .background(Brush.verticalGradient(listOf(Color.Black.copy(alpha = 0.55f), Color.Black))),+ horizontalArrangement = Arrangement.SpaceEvenly,+ verticalAlignment = Alignment.CenterVertically,+ ) {+ listOf(+ R.drawable.ic_home_filled to R.string.navigationbar_musicappitems_home_title,+ R.drawable.ic_search_big to R.string.navigationbar_musicappitems_search_title,+ R.drawable.ic_library_big to R.string.navigationbar_musicappitems_yourlibrary_title,+ ).forEachIndexed { i, (icon, label) ->+ val tint = if (i == 0) Color.White else ClassicGrey+ Column(horizontalAlignment = Alignment.CenterHorizontally) {+ Glyph(icon, 26.dp, tint)+ Text(stringResource(label), color = tint, fontSize = 10.sp, fontFamily = AppSans, fontWeight = FontWeight.Medium, maxLines = 1)+ }+ }+ }+}++/** Today's player: the cover's colour over the whole screen, a white round play button. */+@Composable+private fun ClassicPlayer(playing: Boolean, phases: DemoPhases, modifier: Modifier) {+ val seconds by phases.seconds+ Column(+ modifier+ .fillMaxSize()+ .background(Brush.verticalGradient(listOf(ClassicTop, lerp(ClassicTop, ClassicBottom, 0.55f), ClassicBottom)))+ .padding(horizontal = 24.dp),+ ) {+ Spacer(Modifier.height(40.dp))+ Row(Modifier.fillMaxWidth().height(36.dp), verticalAlignment = Alignment.CenterVertically) {+ Glyph(Icons.Rounded.KeyboardArrowDown, 30.dp)+ Text(DemoSong.ALBUM, color = Color.White, fontSize = 13.sp, fontWeight = FontWeight.Bold, fontFamily = AppSans,+ textAlign = TextAlign.Center, modifier = Modifier.weight(1f).padding(horizontal = 8.dp))+ Glyph(Icons.Rounded.MoreVert, 24.dp)+ }+ Spacer(Modifier.height(24.dp + 312.dp + 40.dp))+ Row(verticalAlignment = Alignment.CenterVertically) {+ Column(Modifier.weight(1f)) {+ Text(DemoSong.TITLE, color = Color.White, fontSize = 22.sp, fontWeight = FontWeight.Bold, fontFamily = AppSans, maxLines = 1)+ Text(DemoSong.ARTIST, color = Color.White.copy(alpha = 0.7f), fontSize = 15.sp, fontFamily = AppSans, maxLines = 1)+ }+ Glyph(R.drawable.ic_add, 26.dp)+ }+ Spacer(Modifier.height(16.dp))+ ClassicSeekBar(phases.progress)+ TimeRow(seconds, Color.White.copy(alpha = 0.7f), AppSans, 11.sp)+ Spacer(Modifier.height(6.dp))+ Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {+ Glyph(R.drawable.ic_shuffle, 24.dp)+ Glyph(R.drawable.ic_skip_prev, 34.dp)+ Box(Modifier.size(64.dp).background(Color.White, CircleShape), contentAlignment = Alignment.Center) {+ PlayGlyph(playing, 36.dp, Color.Black)+ }+ Glyph(R.drawable.ic_skip_next, 34.dp)+ Glyph(R.drawable.ic_repeat, 24.dp)+ }+ Spacer(Modifier.height(18.dp))+ Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {+ Glyph(R.drawable.ic_devices, 20.dp, Color.White.copy(alpha = 0.8f))+ Spacer(Modifier.weight(1f))+ Glyph(R.drawable.ic_share, 20.dp, Color.White.copy(alpha = 0.8f))+ Spacer(Modifier.width(24.dp))+ Glyph(Icons.Rounded.QueueMusic, 22.dp, Color.White.copy(alpha = 0.8f))+ }+ }+}++/** Today's seek bar: a 3dp track and a small white thumb. */+@Composable+private fun ClassicSeekBar(progress: State<Float>) {+ Canvas(Modifier.fillMaxWidth().height(16.dp)) {+ val y = size.height / 2f+ val track = 3.dp.toPx()+ val x = size.width * progress.value+ drawRoundRect(Color.White.copy(alpha = 0.3f), Offset(0f, y - track / 2), Size(size.width, track), CornerRadius(track))+ drawRoundRect(Color.White, Offset(0f, y - track / 2), Size(x, track), CornerRadius(track))+ drawCircle(Color.White, 6.dp.toPx(), Offset(x, y))+ }+}++/**+ * The lyrics card under the controls: it peeks at the bottom of the player and, when the lyrics+ * open, grows into the full-screen page (sung words white, the rest dark, a whole word at a time).+ */+@Composable+private fun ClassicLyricsCard(clock: DemoClock, phases: DemoPhases, open: () -> Float, lyrics: () -> Float) {+ val song = clock.song+ val playing by phases.playing+ val active by phases.active+ val sungWords by remember { derivedStateOf { DemoSong.lines.sumOf { l -> l.words.count { it.startMs <= song.longValue } } } }+ val heights = remember { mutableStateListOf(0, 0, 0) }+ val scroll by animateFloatAsState(heights.take(active).sum().toFloat(), tween(450), label = "classicScroll")+ val peekTop = 688f+ Box(+ Modifier+ .fillMaxSize()+ .graphicsLayer {+ val f = lyrics()+ val inset = 16.dp.toPx() * (1f - f)+ translationY = (1f - open()) * size.height + (peekTop * (1f - f)).dp.toPx()+ scaleX = (size.width - inset * 2) / size.width+ transformOrigin = TransformOrigin(0.5f, 0f)+ shape = RoundedCornerShape((12f * (1f - f)).dp)+ clip = true+ }+ .background(DemoSong.lyricsBackground),+ ) {+ // The card's own title while it peeks.+ Text(+ stringResource(R.string.lyrics_card_title), color = Color.White, fontSize = 15.sp, fontWeight = FontWeight.Bold, fontFamily = AppSans,+ modifier = Modifier.padding(start = 16.dp, top = 16.dp).graphicsLayer { alpha = 1f - lyrics() * 2f },+ )+ Column(Modifier.fillMaxSize().padding(horizontal = 24.dp).graphicsLayer { alpha = (lyrics() * 2f - 0.6f).coerceIn(0f, 1f) }) {+ Spacer(Modifier.height(40.dp))+ Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {+ Glyph(Icons.Rounded.KeyboardArrowDown, 30.dp)+ Column(Modifier.weight(1f), horizontalAlignment = Alignment.CenterHorizontally) {+ Text(DemoSong.TITLE, color = Color.White, fontSize = 14.sp, fontWeight = FontWeight.Bold, fontFamily = AppSans)+ Text(DemoSong.ARTIST, color = Color.White.copy(alpha = 0.75f), fontSize = 13.sp, fontFamily = AppSans)+ }+ Glyph(Icons.Rounded.MoreVert, 24.dp)+ }+ Spacer(Modifier.height(36.dp))+ Box(Modifier.fillMaxWidth().weight(1f).clipToBounds()) {+ Column(Modifier.graphicsLayer { translationY = -scroll }) {+ var before = 0+ DemoSong.lines.forEachIndexed { index, line ->+ val first = before+ before += line.words.size+ Text(+ buildAnnotatedString {+ line.words.forEachIndexed { i, w ->+ if (i > 0) append(" ")+ withStyle(SpanStyle(color = if (first + i < sungWords) Color.White else DemoSong.lyricsText)) { append(w.text) }+ }+ },+ fontSize = 26.sp, lineHeight = 33.sp, fontWeight = FontWeight.Bold, fontFamily = AppSans,+ modifier = Modifier.padding(bottom = 18.dp).onSizeChanged { heights[index] = it.height },+ )+ }+ }+ }+ // The page keeps a seek bar and the play button.+ ClassicSeekBar(phases.progress)+ TimeRow(phases.seconds.value, Color.White.copy(alpha = 0.8f), AppSans, 11.sp)+ Box(Modifier.fillMaxWidth().padding(top = 4.dp, bottom = 36.dp), contentAlignment = Alignment.Center) {+ Box(Modifier.size(56.dp).background(Color.White, CircleShape), contentAlignment = Alignment.Center) {+ PlayGlyph(playing, 32.dp, Color.Black)+ }+ }+ }+ }+}++// ---------------------------------------------------------------- Immersive++/** The pale tint lines take once they are not the one being sung (the cover's lightest colour). */+private val ImmersiveTint = Color(0xFFF2D3E4)+private val Glass = Color(0xFF2C2C34)++@Composable+private fun ImmersiveDemo(clock: DemoClock, still: Boolean) {+ val phases = rememberPhases(clock)+ val open by phases.open+ val lyrics by phases.lyrics+ val playing by phases.playing+ val pause by rememberPauseScale(playing)+ val mini = CoverRect(26f, 624f, 36f)+ val big = CoverRect(28f, 66f, 304f)+ val header = CoverRect(24f, 52f, 48f)+ Box(Modifier.fillMaxSize().background(Color.Black)) {+ ImmersiveHome()+ ImmersiveMini(playing, Modifier.align(Alignment.BottomCenter).padding(start = 14.dp, end = 14.dp, bottom = 88.dp))+ ImmersiveTabs(Modifier.align(Alignment.BottomCenter).padding(start = 14.dp, end = 14.dp, bottom = 18.dp))+ if (open > 0f) ImmersivePlayer(clock, phases, still, { lyrics }, Modifier.graphicsLayer {+ translationY = (1f - open) * size.height+ shape = RoundedCornerShape(topStart = 30.dp, topEnd = 30.dp)+ clip = true+ })+ FlyingCover(+ rect = { lerp(lerp(mini, big, open), header, lyrics) },+ base = 304f, radius = 12.dp, shadow = open > 0.5f,+ // Only the big cover steps back; the mini one and the lyrics header stay put.+ pause = { 1f + (pause - 1f) * open * (1f - lyrics) },+ )+ }+}++/** A home page in the Immersive look: a big title, a row of large cards, a shelf. */+@Composable+private fun ImmersiveHome() {+ val text = TextStyle(fontFamily = ImmersiveSans, color = Color.White)+ Column(Modifier.fillMaxSize().padding(start = 20.dp, end = 20.dp, top = 54.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {+ Row(verticalAlignment = Alignment.CenterVertically) {+ Text(stringResource(R.string.navigationbar_musicappitems_home_title), style = text, fontSize = 32.sp, fontWeight = FontWeight.Bold,+ modifier = Modifier.weight(1f))+ Box(Modifier.size(34.dp).background(Color(0xFF7E57C2), CircleShape))+ }+ Text(stringResource(R.string.look_demo_section), style = text, fontSize = 20.sp, fontWeight = FontWeight.SemiBold)+ Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {+ for (i in 0 until 2) Box(Modifier.size(width = 220.dp, height = 280.dp).clip(RoundedCornerShape(14.dp))) {+ DemoTile(i + 2, Modifier.fillMaxSize())+ Text(DemoShelf[i + 1], style = text, fontSize = 15.sp, fontWeight = FontWeight.SemiBold,+ modifier = Modifier.align(Alignment.BottomStart).padding(14.dp))+ }+ }+ Spacer(Modifier.height(4.dp))+ Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {+ for (i in 0 until 3) Column(Modifier.width(150.dp)) {+ DemoTile(i + 5, Modifier.size(150.dp).clip(RoundedCornerShape(10.dp)))+ Text(DemoShelf[(i + 3) % DemoShelf.size], style = text, fontSize = 13.sp, fontWeight = FontWeight.Medium,+ maxLines = 1, modifier = Modifier.padding(top = 6.dp))+ }+ }+ }+}++@Composable+private fun ImmersiveMini(playing: Boolean, modifier: Modifier) {+ Row(+ modifier+ .fillMaxWidth()+ .height(52.dp)+ .background(Glass.copy(alpha = 0.92f), CircleShape)+ .border(1.dp, Color.White.copy(alpha = 0.12f), CircleShape)+ .padding(start = 60.dp, end = 18.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Column(Modifier.weight(1f)) {+ Text(DemoSong.TITLE, color = Color.White, fontSize = 14.sp, fontWeight = FontWeight.Medium, fontFamily = ImmersiveSans, maxLines = 1)+ Text(DemoSong.ARTIST, color = Color.White.copy(alpha = 0.6f), fontSize = 12.sp, fontFamily = ImmersiveSans, maxLines = 1)+ }+ PlayGlyph(playing, 30.dp, Color.White)+ Spacer(Modifier.width(12.dp))+ Glyph(Icons.Rounded.FastForward, 28.dp)+ }+}++/** Floating, translucent tabs, with search in a bubble of its own. */+@Composable+private fun ImmersiveTabs(modifier: Modifier) {+ Row(modifier.fillMaxWidth().height(62.dp), horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.CenterVertically) {+ Row(+ Modifier+ .weight(1f)+ .fillMaxHeight()+ .background(Glass.copy(alpha = 0.9f), CircleShape)+ .border(1.dp, Color.White.copy(alpha = 0.12f), CircleShape)+ .padding(5.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ listOf(+ Icons.Rounded.Home to R.string.navigationbar_musicappitems_home_title,+ Icons.Rounded.LibraryMusic to R.string.navigationbar_musicappitems_yourlibrary_title,+ ).forEachIndexed { i, (icon, label) ->+ val tint = if (i == 0) Color.White else Color.White.copy(alpha = 0.7f)+ Column(+ Modifier.weight(1f).fillMaxHeight().background(if (i == 0) Color.White.copy(alpha = 0.14f) else Color.Transparent, CircleShape),+ horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center,+ ) {+ Glyph(icon, 24.dp, tint)+ Text(stringResource(label), color = tint, fontSize = 10.sp, fontFamily = ImmersiveSans, fontWeight = FontWeight.Medium, maxLines = 1)+ }+ }+ }+ Box(+ Modifier.size(62.dp).background(Glass.copy(alpha = 0.9f), CircleShape).border(1.dp, Color.White.copy(alpha = 0.12f), CircleShape),+ contentAlignment = Alignment.Center,+ ) { Glyph(Icons.Rounded.Search, 26.dp) }+ }+}++/** A disc of frosted white behind a small glyph (the star and the menu). */+@Composable+private fun GlassDisc(icon: ImageVector) {+ Box(Modifier.size(30.dp).background(Color.White.copy(alpha = 0.18f), CircleShape), contentAlignment = Alignment.Center) {+ Glyph(icon, 20.dp)+ }+}++/**+ * The Immersive player over the cover's mesh. When the lyrics open, the cover goes up to the+ * corner, the title moves beside it and the lyrics take the middle; the bar, the transport, the+ * volume and the bottom row stay where they are.+ */+@Composable+private fun ImmersivePlayer(clock: DemoClock, phases: DemoPhases, still: Boolean, lyrics: () -> Float, modifier: Modifier) {+ val seconds by phases.seconds+ val progress by phases.progress+ val playing by phases.playing+ val text = TextStyle(fontFamily = ImmersiveSans, color = Color.White)+ val faint = Color.White.copy(alpha = 0.55f)+ Box(modifier.fillMaxSize()) {+ MeshGradientBackground(DemoSong.mesh, animated = !still)+ Box(Modifier.align(Alignment.TopCenter).padding(top = 10.dp).size(width = 38.dp, height = 5.dp).background(Color.White.copy(alpha = 0.45f), CircleShape))+ // The title under the big cover, which gives way to the lyrics.+ Row(+ Modifier.padding(start = 28.dp, end = 28.dp).offset(y = 394.dp).graphicsLayer { alpha = 1f - lyrics() },+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Column(Modifier.weight(1f)) {+ Text(DemoSong.TITLE, style = text, fontSize = 20.sp, fontWeight = FontWeight.SemiBold, maxLines = 1)+ Text(DemoSong.ARTIST, style = text, color = Color.White.copy(alpha = 0.62f), fontSize = 20.sp, maxLines = 1)+ }+ GlassDisc(Icons.Rounded.StarOutline)+ Spacer(Modifier.width(10.dp))+ GlassDisc(Icons.Rounded.MoreHoriz)+ }+ // The lyrics, under the cover gone up to the corner.+ Box(Modifier.fillMaxSize().graphicsLayer { alpha = lyrics() }) {+ Row(Modifier.padding(start = 24.dp + 48.dp + 12.dp, top = 54.dp, end = 24.dp), verticalAlignment = Alignment.CenterVertically) {+ Column(Modifier.weight(1f)) {+ Text(DemoSong.TITLE, style = text, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis)+ Text(DemoSong.ARTIST, style = text, color = Color.White.copy(alpha = 0.62f), fontSize = 15.sp, maxLines = 1)+ }+ GlassDisc(Icons.Rounded.StarOutline)+ Spacer(Modifier.width(10.dp))+ GlassDisc(Icons.Rounded.MoreHoriz)+ }+ ImmersiveLyrics(clock, phases, Modifier.padding(top = 112.dp, start = 24.dp - GLOW_ROOM, end = 24.dp - GLOW_ROOM).height(336.dp))+ }+ // Bar, transport, volume and the bottom row: the same in both.+ Column(Modifier.fillMaxWidth().padding(horizontal = 28.dp).offset(y = 452.dp)) {+ ThinSlider(value = progress, onValueChange = {}, idleHeight = 6.dp)+ TimeRow(seconds, faint, ImmersiveSans, 12.sp, FontWeight.Medium)+ Spacer(Modifier.height(20.dp))+ Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly, verticalAlignment = Alignment.CenterVertically) {+ Glyph(Icons.Rounded.FastRewind, 44.dp)+ PlayGlyph(playing, 58.dp, Color.White)+ Glyph(Icons.Rounded.FastForward, 44.dp)+ }+ Spacer(Modifier.height(26.dp))+ Row(verticalAlignment = Alignment.CenterVertically) {+ Glyph(Icons.Rounded.VolumeDown, 18.dp, faint)+ Box(Modifier.weight(1f).padding(horizontal = 8.dp)) {+ ThinSlider(value = 0.62f, onValueChange = {}, idleHeight = 6.dp)+ }+ Glyph(Icons.Rounded.VolumeUp, 18.dp, faint)+ }+ Spacer(Modifier.height(18.dp))+ Row(Modifier.fillMaxWidth().padding(horizontal = 24.dp), verticalAlignment = Alignment.CenterVertically) {+ Box(+ Modifier.size(34.dp).background(Color.White.copy(alpha = 0.24f * lyrics()), CircleShape),+ contentAlignment = Alignment.Center,+ ) { Glyph(Icons.Rounded.Lyrics, 22.dp, Color.White.copy(alpha = 0.85f)) }+ Spacer(Modifier.weight(1f))+ Glyph(Icons.Rounded.Speaker, 22.dp, Color.White.copy(alpha = 0.85f))+ Spacer(Modifier.weight(1f))+ Glyph(Icons.Rounded.FormatListBulleted, 22.dp, Color.White.copy(alpha = 0.85f))+ }+ }+ }+}++/** Big bold lines swept word by word, the others tinted, blurred and set back, the edges faded. */+@Composable+private fun ImmersiveLyrics(clock: DemoClock, phases: DemoPhases, modifier: Modifier) {+ val active by phases.active+ val heights = remember { mutableStateListOf(0, 0, 0) }+ val spec = tween<Float>(LYRIC_SETTLE_MS, easing = LYRIC_EASING)+ val scroll by animateFloatAsState(heights.take(active).sum().toFloat(), spec, label = "immersiveScroll")+ val style = TextStyle(fontFamily = ImmersiveSans, fontWeight = FontWeight.Bold, fontSize = 30.sp, lineHeight = 36.sp)+ Box(+ modifier+ .fillMaxWidth()+ .clipToBounds()+ // Fades the lines out towards the top and the bottom of their area.+ .graphicsLayer { compositingStrategy = CompositingStrategy.Offscreen }+ .drawWithContent {+ drawContent()+ drawRect(+ Brush.verticalGradient(0f to Color.Transparent, 0.12f to Color.Black, 0.82f to Color.Black, 1f to Color.Transparent),+ blendMode = BlendMode.DstIn,+ )+ },+ ) {+ // The line being sung sits a little down, so the one before it stays in view above.+ Column(Modifier.graphicsLayer { translationY = 56.dp.toPx() - scroll }) {+ DemoSong.lines.forEachIndexed { index, line ->+ val distance = min(abs(index - active), LINE_FALLOFF_ALPHA.size - 1)+ val alpha by animateFloatAsState(LINE_FALLOFF_ALPHA[distance], spec, label = "lineAlpha")+ val blur by animateFloatAsState(LINE_FALLOFF_BLUR[distance].value, spec, label = "lineBlur")+ val scale by animateFloatAsState(if (distance == 0) 1f else INACTIVE_SCALE, spec, label = "lineScale")+ val tail by animateFloatAsState(if (index < active) 1f else UNSUNG_ALPHA, label = "lineTail")+ SweptLyricLine(+ line = line,+ clock = clock.song,+ style = style,+ dimAlpha = tail,+ color = if (distance == 0) Color.White else ImmersiveTint,+ glowAlpha = if (distance == 0) GLOW_ALPHA else 0f,+ glowRoom = GLOW_ROOM,+ feather = distance == 0,+ modifier = Modifier+ .padding(bottom = 6.dp)+ .onSizeChanged { heights[index] = it.height }+ .graphicsLayer {+ this.alpha = alpha+ scaleX = scale+ scaleY = scale+ transformOrigin = TransformOrigin(0f, 0.5f)+ }+ .then(if (blur > 0.05f) Modifier.blur(blur.dp) else Modifier),+ )+ }+ }+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/look/LookStep.kt b/base/app/src/main/java/com/music/spotui/ui/look/LookStep.ktnew file mode 100644index 00000000..7e9c833c--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/look/LookStep.kt@@ -0,0 +1,205 @@+package com.music.spotui.ui.look++import androidx.compose.animation.Crossfade+import androidx.compose.animation.animateColorAsState+import androidx.compose.animation.core.tween+import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.gestures.awaitEachGesture+import androidx.compose.foundation.gestures.awaitFirstDown+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.navigationBarsPadding+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.statusBarsPadding+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.Button+import androidx.compose.material3.ButtonDefaults+import androidx.compose.material3.Text+import androidx.compose.material3.TextButton+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.semantics.contentDescription+import androidx.compose.ui.semantics.semantics+import androidx.compose.ui.text.TextStyle+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import app.myspoti.engine.R+import com.music.spotui.data.preferences.Look+import com.music.spotui.data.preferences.LookPref+import com.music.spotui.ui.theme.AppBackground+import com.music.spotui.ui.theme.AppSans+import kotlin.math.abs++/** Set when the step is the "new look" popup shown to existing users: its own title, buttons and note. */+class LookOffer(val onKeep: () -> Unit)++/**+ * Onboarding, the look: two segments over a live preview that plays the demo song in the chosen+ * look. The choice is saved as soon as a segment is touched, and the page itself takes the look+ * (its backdrop, type and button), so the difference shows twice.+ */+@Composable+fun LookStep(onNext: () -> Unit, offer: LookOffer? = null) {+ val context = LocalContext.current+ val look = LocalLook.current+ val immersive = look == Look.IMMERSIVE+ val reduceMotion = rememberReduceMotion()+ var paused by remember { mutableStateOf(false) }+ val clock = rememberDemoClock(running = !paused && !reduceMotion)+ val choose: (Look) -> Unit = { if (it != look) LookPref.set(context, it) }+ val family = if (immersive) ImmersiveSans else AppSans+ val text = TextStyle(fontFamily = family, color = Color.White)+ val dim = Color.White.copy(alpha = if (immersive) 0.72f else 1f)+ val subtle = if (immersive) Color.White.copy(alpha = 0.7f) else Color(0xFFB3B3B3)++ Box(Modifier.fillMaxSize()) {+ Crossfade(look, animationSpec = tween(350), label = "lookBackdrop") {+ if (it == Look.IMMERSIVE) {+ MeshGradientBackground(cyclingMeshPalette(LookMeshPalettes), colorFadeMillis = MESH_CYCLE_MILLIS)+ } else {+ Box(Modifier.fillMaxSize().background(AppBackground))+ }+ }+ Column(+ Modifier.fillMaxSize().statusBarsPadding().navigationBarsPadding().padding(horizontal = 20.dp, vertical = 20.dp),+ verticalArrangement = Arrangement.spacedBy(12.dp),+ ) {+ Text(stringResource(if (offer != null) R.string.look_offer_title else R.string.setup_look_title), style = text, fontSize = 26.sp,+ fontWeight = if (immersive) FontWeight.SemiBold else FontWeight.Bold)+ Text(stringResource(R.string.setup_look_subtitle), style = text, color = subtle, fontSize = 14.sp)+ LookSegments(look, immersive, family, choose)+ Box(Modifier.fillMaxWidth().weight(1f)) {+ val description = stringResource(R.string.setup_look_preview, stringResource(look.nameRes()))+ if (reduceMotion) {+ LookStills(look, subtle, Modifier.fillMaxSize().semantics { contentDescription = description })+ } else {+ PhoneFrame(Modifier.fillMaxSize().semantics { contentDescription = description }) {+ Crossfade(look, animationSpec = tween(350), label = "lookPreview") { LookDemo(it, clock) }+ }+ }+ // Above the preview, so nothing in it reacts: a tap pauses or resumes, a swipe+ // changes the look.+ Box(Modifier.matchParentSize().pointerInput(look) {+ val swipe = 56.dp.toPx()+ awaitEachGesture {+ val down = awaitFirstDown()+ var dx = 0f+ var moved = false+ while (true) {+ val change = awaitPointerEvent().changes.firstOrNull { it.id == down.id } ?: break+ if (!change.pressed) break+ dx = change.position.x - down.position.x+ if (abs(dx) > viewConfiguration.touchSlop || abs(change.position.y - down.position.y) > viewConfiguration.touchSlop) moved = true+ change.consume()+ }+ when {+ !moved -> paused = !paused+ dx < -swipe -> choose(Look.IMMERSIVE)+ dx > swipe -> choose(Look.CLASSIC)+ }+ }+ })+ }+ Text(+ stringResource(if (reduceMotion) R.string.setup_look_still_hint else R.string.setup_look_tap_hint),+ style = text, color = dim.copy(alpha = 0.6f), fontSize = 12.sp, textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth(),+ )+ Button(+ onClick = onNext,+ shape = if (immersive) RoundedCornerShape(14.dp) else ButtonDefaults.shape,+ colors = ButtonDefaults.buttonColors(+ containerColor = if (immersive) Color.White else Color(0xFF1DB954),+ contentColor = Color.Black,+ ),+ modifier = Modifier.fillMaxWidth().height(50.dp),+ ) {+ Text(stringResource(if (offer != null) R.string.look_offer_try else R.string.setup_continue), fontFamily = family, fontSize = 16.sp,+ fontWeight = if (immersive) FontWeight.SemiBold else FontWeight.Bold)+ }+ if (offer != null) {+ TextButton(onClick = offer.onKeep, modifier = Modifier.fillMaxWidth()) {+ Text(stringResource(R.string.look_offer_keep), color = Color.White, fontFamily = family, fontSize = 15.sp)+ }+ Text(stringResource(R.string.look_offer_note), style = text, color = dim.copy(alpha = 0.6f), fontSize = 12.sp,+ textAlign = TextAlign.Center, modifier = Modifier.fillMaxWidth())+ }+ }+ }+}++private fun Look.nameRes() = if (this == Look.IMMERSIVE) R.string.look_immersive else R.string.look_classic+private fun Look.detailRes() = if (this == Look.IMMERSIVE) R.string.look_immersive_detail else R.string.look_classic_detail++/** "Classic | Immersive", each with a line on what it shows; drawn in the chosen look. */+@Composable+private fun LookSegments(look: Look, immersive: Boolean, family: androidx.compose.ui.text.font.FontFamily, choose: (Look) -> Unit) {+ val outer = if (immersive) RoundedCornerShape(18.dp) else RoundedCornerShape(24.dp)+ val inner = if (immersive) RoundedCornerShape(14.dp) else RoundedCornerShape(20.dp)+ Row(+ Modifier+ .fillMaxWidth()+ .background(if (immersive) Color.White.copy(alpha = 0.14f) else Color(0xFF242424), outer)+ .padding(4.dp),+ horizontalArrangement = Arrangement.spacedBy(4.dp),+ ) {+ Look.entries.forEach { option ->+ val selected = option == look+ val fill by animateColorAsState(+ when {+ !selected -> Color.Transparent+ immersive -> Color.White.copy(alpha = 0.92f)+ else -> Color(0xFF1DB954)+ },+ label = "segmentFill",+ )+ val ink = if (selected) Color.Black else Color.White+ Column(+ Modifier+ .weight(1f)+ .background(fill, inner)+ .clickable { choose(option) }+ .padding(horizontal = 10.dp, vertical = 8.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ ) {+ Text(stringResource(option.nameRes()), color = ink, fontFamily = family, fontSize = 15.sp,+ fontWeight = if (immersive) FontWeight.SemiBold else FontWeight.Bold)+ Text(stringResource(option.detailRes()), color = ink.copy(alpha = 0.72f), fontFamily = family, fontSize = 11.sp,+ lineHeight = 14.sp, textAlign = TextAlign.Center, minLines = 2, maxLines = 2)+ }+ }+ }+}++/** "Remove animations": three still frames of the loop instead of the loop. */+@Composable+private fun LookStills(look: Look, caption: Color, modifier: Modifier) {+ val captions = listOf(R.string.setup_look_still_player, R.string.setup_look_still_paused, R.string.setup_look_still_lyrics)+ Row(modifier, horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ DemoScript.stills.forEachIndexed { index, ms ->+ Column(Modifier.weight(1f).fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally) {+ PhoneFrame(Modifier.fillMaxWidth().weight(1f)) { LookDemo(look, rememberStillClock(ms), still = true) }+ Spacer(Modifier.height(6.dp))+ Text(stringResource(captions[index]), color = caption, fontSize = 12.sp, maxLines = 1)+ }+ }+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/look/LyricClock.kt b/base/app/src/main/java/com/music/spotui/ui/look/LyricClock.ktnew file mode 100644index 00000000..278a8263--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/look/LyricClock.kt@@ -0,0 +1,387 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * sharedUi/src/jvmSharedMain/kotlin/com/music/bitchord/ui/player/LyricClock.kt at edc1e6f.+ * Modified for Myspoti, 2026-10.+ *+ * Changes: package only. The readings it is steered by will be the Web Player's, which+ * arrive in steps just as BitChord's do.+ */+package com.music.spotui.ui.look++import kotlin.math.abs++/**+ * The lyric playhead: a clock that runs on its own frames and is *steered* by+ * the player's readings rather than set by them.+ *+ * Three rules, each the answer to a way this has gone wrong before:+ *+ * 1. **A reading is dated by when it was taken, not when it was seen.** The+ * player is read twice a second and the reading then waits on the main+ * thread; a busy frame holds it back by as long as the frame takes. Dated+ * on arrival, a reading from before a half-second stall looked half a+ * second old. Snapping to it moved the words back; refusing to go back (a+ * `maxOf` ratchet) froze them until the song caught up; easing back to it+ * rolled them back a line. All three were the same mistake. Every reading+ * now carries its own [System.nanoTime] stamp — see `PlaybackPosition` —+ * and is compared with where the song was *at that moment*.+ * 2. **Nothing but an announced jump moves the words backwards.** The player+ * says when it seeks, skips or starts over (the `discontinuity` handed to+ * [frame]); that, and only that, may roll the words back. A reading that+ * disagrees without one is held back until the next confirms it, and a+ * confirmed gap behind the words is absorbed by running slower — never by+ * stopping and never by reversing.+ * 3. **Readings steer, they don't set.** The newest reading, carried forward+ * at the learned playback rate, is where the song is; the words close the+ * gap to it by running up to [MAX_SLEW] faster or [MAX_SLOW] slower. The+ * rate is learned from the readings themselves, which is how a song at+ * 1.25x stays in step without being told.+ *+ * This is what am-lyrics gets from the browser for free: its wipes run on the+ * compositor's own clock, and the host's timestamp only touches them when the+ * two disagree by a lot.+ *+ * All times are milliseconds on the [System.nanoTime] clock. Plain arithmetic+ * with no Compose in it, so it can be tested frame by frame;+ * `rememberLyricClock` is the composable that drives it.+ */+internal class LyricClock(startMs: Long) {+ /** Where the lyrics are drawn, in song milliseconds. */+ var displayedMs: Double = startMs.toDouble()+ private set++ private var lastNowMs = Double.NaN++ // The newest reading seen, to tell a new one from the same one again.+ private var lastReportMs = Long.MIN_VALUE+ private var lastSampledAtMs = Double.NaN++ /** When playback was last seen stopped; a reading taken before then was taken standing still. */+ private var heldAtMs = Double.NEGATIVE_INFINITY++ private var lastDiscontinuity: Long? = null+ private var jumpPending = false++ // The newest reading believed: where the song was, and when.+ private var anchorAtMs = Double.NaN+ private var anchorMs = 0.0++ /** The playback rate, learned from how far the song moves between readings. */+ private var rate = 1.0++ // Readings believed since the playhead last jumped, oldest first: what the+ // rate is measured across. See [learnRate].+ private val historyAt = DoubleArray(HISTORY)+ private val historyMs = DoubleArray(HISTORY)+ private var historySize = 0++ /** Whether the rate has been measured across a long enough stretch to be trusted. */+ private var rateSettled = false++ // A reading that disagreed with the anchor, kept until the next one says+ // whether the song really moved or the reading was wrong.+ private var suspectAtMs = Double.NaN+ private var suspectMs = 0L+ private var rejections = 0++ private var glideStartMs = Double.NaN+ private var glideOffsetMs = 0.0++ /**+ * Forget the run so far: frames stopped arriving — playback paused, or the+ * app left the screen — and the next [frame] starts a new one.+ */+ fun restart() {+ lastNowMs = Double.NaN+ jumpPending = false+ glideStartMs = Double.NaN+ clearSuspect()+ }++ /**+ * Playback is not moving: settle on [positionMs] outright, as of [nowMs].+ * Called again for every reading that arrives while stopped, which is how a+ * seek made while paused still moves the words.+ */+ fun hold(positionMs: Long, nowMs: Double) {+ restart()+ displayedMs = positionMs.toDouble()+ heldAtMs = nowMs+ }++ /**+ * Advance to the frame at [nowMs] and return where the lyrics should be+ * drawn.+ *+ * [reportedMs] is the player's latest reading and [sampledAtMs] when it was+ * taken, or NaN where nobody said — it is then dated by the first frame that+ * sees it, the best that can be done. [discontinuity] is any value that+ * changes when the playhead jumps on purpose; only its changing matters.+ */+ fun frame(nowMs: Double, reportedMs: Long, sampledAtMs: Double, discontinuity: Long): Long {+ val firstOfRun = lastNowMs.isNaN()+ if (discontinuity != lastDiscontinuity) {+ if (lastDiscontinuity != null && !firstOfRun) jumpPending = true+ lastDiscontinuity = discontinuity+ }+ val isNew = reportedMs != lastReportMs ||+ (!sampledAtMs.isNaN() && sampledAtMs != lastSampledAtMs)+ lastReportMs = reportedMs+ lastSampledAtMs = sampledAtMs++ if (firstOfRun) {+ lastNowMs = nowMs+ // Taken while playback stood still — the last reading before a+ // pause, or one made during it — it is where the song still is now,+ // however long ago it was taken. Taken while playing, the song has+ // moved on since by exactly how long ago that was.+ val takenAt = when {+ sampledAtMs.isNaN() || sampledAtMs <= heldAtMs -> nowMs+ else -> minOf(sampledAtMs, nowMs)+ }+ anchor(takenAt, reportedMs)+ displayedMs = targetAt(nowMs)+ return displayedMs.toLong()+ }++ // Carried up to this frame on what was known before it, and only then+ // corrected by anything new: a jump folded in first would be advanced+ // by this frame a second time.+ val dt = (nowMs - lastNowMs).coerceAtLeast(0.0)+ lastNowMs = nowMs+ advance(nowMs, dt)++ if (isNew) {+ // A stamp from the future is a frame clock running a hair behind+ // the reading; one from before the anchor is out of order, and says+ // nothing the anchor does not.+ val takenAt = if (sampledAtMs.isNaN()) nowMs else minOf(sampledAtMs, nowMs)+ if (takenAt >= anchorAtMs || jumpPending) take(nowMs, takenAt, reportedMs)+ }+ return displayedMs.toLong()+ }++ /** Folds one new reading in — or holds it back, if it disagrees with the song so far. */+ private fun take(nowMs: Double, takenAt: Double, reportedMs: Long) {+ if (jumpPending) {+ // The reading the jump was announced with: where the song landed.+ jumpPending = false+ clearSuspect()+ anchor(takenAt, reportedMs)+ jumpTo(nowMs)+ return+ }+ val elapsed = takenAt - anchorAtMs+ if (abs(reportedMs - (anchorMs + elapsed * rate)) <= tolerance(elapsed)) {+ clearSuspect()+ anchor(takenAt, reportedMs, continues = true)+ return+ }+ // Off with nothing announced. One reading like that is a bad reading;+ // a second agreeing with it is the song somewhere else. And a run of+ // them, however they disagree, means the picture so far is what is+ // wrong — taken rather than refused forever, which is a clock that has+ // stopped listening.+ val sinceSuspect = takenAt - suspectAtMs+ val agrees = !suspectAtMs.isNaN() && sinceSuspect >= 0 &&+ abs(reportedMs - (suspectMs + sinceSuspect * rate)) <= tolerance(sinceSuspect)+ rejections+++ if (agrees) {+ // The two agree with each other, so between them they are the+ // start of the song's new stretch — and its first rate measurement.+ val firstAt = suspectAtMs+ val first = suspectMs+ clearSuspect()+ anchor(firstAt, first)+ anchor(takenAt, reportedMs, continues = true)+ } else if (rejections > MAX_REJECTIONS) {+ clearSuspect()+ anchor(takenAt, reportedMs)+ // From here [advance] closes the gap: ahead of the words it glides+ // forward; behind them it slows down — still never backwards.+ } else {+ suspectAtMs = takenAt+ suspectMs = reportedMs+ }+ }++ /**+ * How far a reading [elapsedMs] after the last may stray before it is+ * doubted: a fixed allowance for the player's own noise, and a little more+ * the longer the gap, for a rate not yet learned exactly.+ */+ private fun tolerance(elapsedMs: Double): Double =+ OUTLIER_MS + abs(elapsedMs) * if (rateSettled) RATE_SLACK else UNSETTLED_RATE_SLACK++ /**+ * Believes a reading. [continues] says it carries on from the one before —+ * the song has not jumped between them — so the two can measure the rate.+ */+ private fun anchor(atMs: Double, positionMs: Long, continues: Boolean = false) {+ anchorAtMs = atMs+ anchorMs = positionMs.toDouble()+ if (!continues) historySize = 0+ if (historySize == HISTORY) {+ historyAt.copyInto(historyAt, 0, 1, HISTORY)+ historyMs.copyInto(historyMs, 0, 1, HISTORY)+ historySize--+ }+ historyAt[historySize] = atMs+ historyMs[historySize] = anchorMs+ historySize+++ learnRate()+ }++ /**+ * The rate, measured from the oldest reading within [RATE_WINDOW_MS] to the+ * newest. Measured between neighbours half a second apart, a few+ * milliseconds of the player's own jitter was a few percent of rate, and+ * smoothing that away took long enough that a song at 1.5x had drifted a+ * third of a second before the clock agreed. Across seconds, the same jitter+ * is a fraction of a percent; and a rate that is really changing — Automix+ * easing a tempo back — is still followed within the window.+ */+ private fun learnRate() {+ val newest = historySize - 1+ if (newest < 1) return+ var oldest = 0+ while (oldest < newest && historyAt[newest] - historyAt[oldest] > RATE_WINDOW_MS) oldest+++ val span = historyAt[newest] - historyAt[oldest]+ if (span >= MIN_RATE_SPAN_MS) {+ rate = ((historyMs[newest] - historyMs[oldest]) / span).coerceIn(MIN_RATE, MAX_RATE)+ rateSettled = true+ return+ }+ // Not enough of a stretch yet: a rough step from the last two, so the+ // first second of a song at 1.5x is not spent believing it is at 1x.+ val pairSpan = historyAt[newest] - historyAt[newest - 1]+ if (!rateSettled && pairSpan >= MIN_PAIR_SPAN_MS) {+ val measured = ((historyMs[newest] - historyMs[newest - 1]) / pairSpan)+ .coerceIn(MIN_RATE, MAX_RATE)+ rate += (measured - rate) * PAIR_LEARNING+ }+ }++ private fun clearSuspect() {+ suspectAtMs = Double.NaN+ rejections = 0+ }++ private fun advance(nowMs: Double, dt: Double) {+ val target = targetAt(nowMs)+ // What this frame moves the words by on its own, and how far from the+ // song that leaves them.+ val step = dt * rate+ val error = target - (displayedMs + step)+ when {+ !glideStartMs.isNaN() -> {+ val progress = (nowMs - glideStartMs) / GLIDE_MS+ if (progress >= 1.0) {+ displayedMs = target+ glideStartMs = Double.NaN+ } else {+ // The offset eases out while the target keeps moving, so the+ // glide lands on a playhead that is still running.+ displayedMs = target + glideOffsetMs * (1.0 - smoothstep(progress))+ }+ }+ // Confirmed, unannounced, and far: the song is somewhere else+ // entirely and no amount of slowing down will get there.+ error <= -LOST_MS || error >= LOST_MS -> displayedMs = target+ error >= GLIDE_FROM_MS -> {+ startGlide(nowMs - dt, displayedMs - (target - step))+ displayedMs = target + glideOffsetMs * (1.0 - smoothstep(dt / GLIDE_MS))+ }+ else -> {+ // Behind runs fast, ahead runs slow — and slow is floored well+ // above zero, so the words never stop to wait. The share of the+ // gap closed grows with the frame but never reaches all of it, so+ // a long frame after a stall cannot carry the words past the song.+ val closing = error * (dt / (dt + CORRECTION_MS))+ displayedMs += step + closing.coerceIn(-MAX_SLOW * step, MAX_SLEW * step)+ }+ }+ }++ /** An announced jump: rolled to over [GLIDE_MS] when it is near, taken at once when it is not. */+ private fun jumpTo(nowMs: Double) {+ val offset = displayedMs - targetAt(nowMs)+ if (abs(offset) > GLIDE_MAX_MS) {+ displayedMs = targetAt(nowMs)+ glideStartMs = Double.NaN+ } else {+ startGlide(nowMs, offset)+ }+ }++ private fun startGlide(startMs: Double, offsetMs: Double) {+ glideStartMs = startMs+ glideOffsetMs = offsetMs+ }++ /** Where the song is at [atMs]: the newest reading believed, carried forward. */+ private fun targetAt(atMs: Double): Double = anchorMs + (atMs - anchorAtMs) * rate+}++private fun smoothstep(fraction: Double): Double {+ val t = fraction.coerceIn(0.0, 1.0)+ return t * t * (3.0 - 2.0 * t)+}++/**+ * A dated reading this far off where the song should be is not noise. Dated+ * properly, readings land within a few tens of milliseconds; this is several+ * times that, and well inside anything a listener would call out of sync.+ */+private const val OUTLIER_MS = 250.0++/**+ * Extra allowance per millisecond between readings, for a rate not known+ * exactly — and a wider one until it has been measured at all, or a song at+ * 1.5x looks like a run of jumps while the clock still thinks it is at 1x.+ */+private const val RATE_SLACK = 0.2+private const val UNSETTLED_RATE_SLACK = 0.75++/** Readings refused in a row before the next is taken whatever it says. */+private const val MAX_REJECTIONS = 2++/**+ * The rate is measured across readings at least [MIN_RATE_SPAN_MS] and at most+ * [RATE_WINDOW_MS] apart: closer, the player's own jitter is most of what the+ * measurement says; further, a real change of rate is followed too late.+ */+private const val MIN_RATE_SPAN_MS = 900.0+private const val RATE_WINDOW_MS = 4_000.0+private const val HISTORY = 16++/** Before then, a rough step from each pair at least this far apart. */+private const val MIN_PAIR_SPAN_MS = 300.0+private const val PAIR_LEARNING = 0.5++/** Playback rates the clock is allowed to conclude; a measurement outside these is noise. */+private const val MIN_RATE = 0.25+private const val MAX_RATE = 4.0++/**+ * The gap closes with a time constant of [CORRECTION_MS] — 60 ms behind runs+ * about 10 % fast — capped at [MAX_SLEW] faster and [MAX_SLOW] slower. A+ * sweep's speed changes far more than that from one word to the next, so the+ * correction never reads as anything; and at half speed at the slowest, the+ * words never read as stopped.+ */+private const val CORRECTION_MS = 600.0+private const val MAX_SLEW = 0.25+private const val MAX_SLOW = 0.5++/** Behind by this much, the words catch up over [GLIDE_MS] rather than by running fast. */+private const val GLIDE_FROM_MS = 300.0++/** am-lyrics eases its rewinds over 260 ms with the same smoothstep. */+private const val GLIDE_MS = 260.0++/** An announced jump further than this is taken at once rather than rolled through. */+private const val GLIDE_MAX_MS = 2_000.0++/** A confirmed gap this wide either way is another part of the song, and is jumped to. */+private const val LOST_MS = 3_000.0diff --git a/base/app/src/main/java/com/music/spotui/ui/look/MeshGradient.kt b/base/app/src/main/java/com/music/spotui/ui/look/MeshGradient.ktnew file mode 100644index 00000000..26f837a1--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/look/MeshGradient.kt@@ -0,0 +1,348 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * sharedUi/src/jvmSharedMain/kotlin/com/music/bitchord/ui/player/MeshGradient.kt at edc1e6f.+ * Modified for Myspoti, 2026-10.+ *+ * Changes: the artwork is loaded with Glide and quantised with androidx Palette, as the rest+ * of Myspoti does (di/Palette); "reduce animation" is the system's animator scale; the motion+ * artwork frame, the watch export and BitChord's own welcome palettes are left out.+ */+package com.music.spotui.ui.look++import android.content.Context+import android.graphics.Bitmap+import android.graphics.drawable.Drawable+import androidx.compose.animation.animateColorAsState+import androidx.compose.animation.core.Animatable+import androidx.compose.animation.core.AnimationSpec+import androidx.compose.animation.core.FastOutSlowInEasing+import androidx.compose.animation.core.LinearEasing+import androidx.compose.animation.core.snap+import androidx.compose.animation.core.tween+import androidx.compose.foundation.Canvas+import androidx.compose.foundation.background+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.Immutable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.blur+import androidx.compose.ui.draw.clipToBounds+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.graphics.Brush+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.graphics.toArgb+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp+import androidx.core.graphics.ColorUtils+import androidx.palette.graphics.Palette+import com.bumptech.glide.Glide+import com.bumptech.glide.request.target.CustomTarget+import com.bumptech.glide.request.transition.Transition+import kotlinx.coroutines.delay+import kotlinx.coroutines.isActive+import kotlin.math.PI+import kotlin.math.abs+import kotlin.math.cos+import kotlin.math.min+import kotlin.math.sin++private val FallbackColors = listOf(+ Color(0xFF3A1C71),+ Color(0xFFD76D77),+ Color(0xFF2B5876),+ Color(0xFFFFAF7B),+)++/** The four mesh colours, wrapped so the backdrop can skip recomposition. */+@Immutable+data class MeshPalette(val colors: List<Color>)++/**+ * The Immersive player's backdrop: four luminous colour blobs sampled from+ * the album art, drawn as soft radial gradients and blurred into a mesh.+ * Colour changes on track skip crossfade over ~1.4s instead of snapping.+ *+ * The blobs drift when there is a reason to — the player opening, or+ * [trackKey] changing — and then come to rest. Orbiting forever would mean+ * re-blurring a full-screen layer at display refresh rate for as long as the+ * player is up: the most expensive thing on screen, for motion that reads as+ * ambient at best. The settled frame looks the same; only the battery drain is gone.+ */+@Composable+fun MeshGradientBackground(+ palette: MeshPalette,+ modifier: Modifier = Modifier,+ trackKey: Any? = null,+ driftMillis: Int = 8_000,+ /**+ * Keep the blobs orbiting instead of letting them settle. Off wherever the+ * mesh fills a screen, for the reason in the note above.+ */+ continuous: Boolean = false,+ /**+ * How far the blobs are smeared. The default is sized for a full screen;+ * a small surface needs proportionally less, or the four colours blend into+ * one wash before they reach its edges.+ */+ blurRadius: Dp = 64.dp,+ /**+ * Off for a surface that should read as a still image: colours snap+ * straight to target instead of crossfading, and the blobs never drift+ * on a [trackKey] change, only settling once on first composition.+ */+ animated: Boolean = true,+ /**+ * How long a palette change takes to crossfade. A track skip wants it+ * brisk; a surface that changes colour on a timer wants it long enough+ * that one fade runs into the next and the colour never sits still.+ */+ colorFadeMillis: Int = 1400,+) {+ val reduceAnimation = rememberReduceMotion()++ val tuned = (palette.colors.ifEmpty { FallbackColors } + FallbackColors)+ .take(4)+ .map { it.tuned() }++ // Each colour slot crossfades independently when the track (palette) changes,+ // unless animations are off, in which case colours snap straight to target.+ val colorSpec: AnimationSpec<Color> = if (reduceAnimation || !animated) snap() else tween(colorFadeMillis)+ val animatedColors = tuned.mapIndexed { index, color ->+ animateColorAsState(color, colorSpec, label = "meshColor$index").value+ }+ val baseColor by animateColorAsState(tuned.first().dimmed(), colorSpec, label = "meshBase")++ // Read in the draw lambda, not here: an Animatable read during draw+ // invalidates only the drawing, leaving composition out of the loop.+ val phase = remember { Animatable(0f) }+ LaunchedEffect(trackKey, reduceAnimation, continuous, animated) {+ when {+ !animated || reduceAnimation -> phase.snapTo(0f)+ // A full turn at a time, restarted rather than looped with an+ // infinite spec: the blobs' speeds are irrational multiples of each+ // other, so the pattern never repeats, and a linear phase keeps the+ // orbit even instead of easing to a halt each lap.+ continuous -> while (isActive) {+ phase.animateTo(+ targetValue = phase.value + (2 * PI).toFloat(),+ animationSpec = tween(driftMillis * 4, easing = LinearEasing),+ )+ }+ else -> phase.animateTo(+ targetValue = phase.value + DRIFT_RADIANS,+ animationSpec = tween(driftMillis, easing = FastOutSlowInEasing),+ )+ }+ }++ // Scale up slightly so the blur's clamped edges never show, then blur the+ // whole layer (RenderEffect, API 31+; a no-op below — the radial falloff+ // already reads soft there).+ //+ // Clipped on the way out, and from a layer of its own rather than by setting+ // `clip` on the one below: that one clips what is drawn *into* it, in its own+ // coordinates, and the scale is applied after — so the overhang the scale+ // creates survives it. This has to sit outside the scale to contain it.+ Canvas(+ modifier = modifier+ .fillMaxSize()+ .clipToBounds()+ .graphicsLayer {+ scaleX = 1.3f+ scaleY = 1.3f+ }+ .background(baseColor)+ .blur(blurRadius),+ ) {+ val anchors = listOf(+ Offset(0.20f, 0.25f),+ Offset(0.80f, 0.20f),+ Offset(0.75f, 0.80f),+ Offset(0.25f, 0.75f),+ )+ val speeds = listOf(1f, -0.7f, 0.85f, -1.15f)+ val drift = phase.value++ animatedColors.forEachIndexed { index, color ->+ val anchor = anchors[index]+ val center = Offset(+ x = (anchor.x + 0.16f * cos(drift * speeds[index] + index * 1.7f)) * size.width,+ y = (anchor.y + 0.16f * sin(drift * speeds[index] * 0.9f + index * 2.3f)) * size.height,+ )+ val radius = size.maxDimension * 0.62f+ drawCircle(+ brush = Brush.radialGradient(+ colors = listOf(color.copy(alpha = 0.85f), color.copy(alpha = 0f)),+ center = center,+ radius = radius,+ ),+ radius = radius,+ center = center,+ )+ }++ // Gentle scrim so white text stays legible over bright art.+ drawRect(+ brush = Brush.verticalGradient(+ colors = listOf(+ Color.Black.copy(alpha = 0.10f),+ Color.Black.copy(alpha = 0.38f),+ ),+ ),+ )+ }+}++/**+ * How long each palette in a [cyclingMeshPalette] is held, which is also how+ * long the fade into it takes — pass it as `colorFadeMillis` so one crossfade+ * runs straight into the next and the colour is never at rest.+ */+const val MESH_CYCLE_MILLIS = 3_600++/**+ * Steps through [palettes] for as long as the caller is composed, one every+ * [stepMillis]. With animations off every step would be a snap, so there it+ * stays on the first palette instead.+ */+@Composable+fun cyclingMeshPalette(palettes: List<MeshPalette>, stepMillis: Int = MESH_CYCLE_MILLIS): MeshPalette {+ val reduceAnimation = rememberReduceMotion()+ var step by remember { mutableIntStateOf(0) }+ LaunchedEffect(reduceAnimation, stepMillis) {+ if (reduceAnimation) return@LaunchedEffect+ while (isActive) {+ delay(stepMillis.toLong())+ step+++ }+ }+ return palettes[step % palettes.size]+}++/**+ * Loads the artwork with Glide (software bitmap, thumbnail-sized) and pulls a+ * 4-colour palette out of it. Recomputes when [imageUrl] changes.+ */+@Composable+fun rememberArtworkColors(imageUrl: String?): MeshPalette {+ val context = LocalContext.current+ var palette by remember(imageUrl) { mutableStateOf(MeshPalette(FallbackColors)) }++ DisposableEffect(imageUrl) {+ val target = if (imageUrl == null) null else loadArtwork(context, imageUrl) { bitmap ->+ palette = MeshPalette(artworkMeshColors(bitmap))+ }+ onDispose { target?.let { Glide.with(context.applicationContext).clear(it) } }+ }+ return palette+}++private fun loadArtwork(context: Context, imageUrl: String, onLoaded: (Bitmap) -> Unit): CustomTarget<Bitmap> =+ Glide.with(context.applicationContext)+ .asBitmap()+ .load(imageUrl)+ .override(128, 128) // palette quality is fine at thumbnail size, and it's fast+ .disallowHardwareConfig() // Palette needs pixel access+ .into(object : CustomTarget<Bitmap>() {+ override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) = onLoaded(resource)+ override fun onLoadCleared(placeholder: Drawable?) = Unit+ })++/**+ * How far the blobs travel in one settle. A shade under half a turn: enough+ * that the backdrop visibly reacts to a track change, short of a full orbit+ * that would land the blobs back where they started.+ */+private const val DRIFT_RADIANS = (PI * 0.45f).toFloat()++/**+ * Four mesh colours drawn from the artwork.+ *+ * The named swatches — vibrant, muted and friends — are a convenience over the+ * full set, and on dark or desaturated sleeves every vibrant slot comes back+ * null. Topping the rest up from [FallbackColors] is what left those covers+ * sitting under the stock purple. So the whole swatch list is read instead, and+ * any shortfall is derived from the art's own colours rather than borrowed.+ */+fun artworkMeshColors(bitmap: Bitmap): List<Color> {+ fun swatchesOf(clearFilters: Boolean): List<Color> =+ Palette.from(bitmap).maximumColorCount(24)+ .apply { if (clearFilters) clearFilters() }+ .generate()+ .swatches+ .sortedByDescending { it.population }+ .map { Color(it.rgb) }++ val found = swatchesOf(clearFilters = false).ifEmpty {+ // The default filter discards near-black and near-white, which on a+ // monochrome sleeve can be everything there is.+ swatchesOf(clearFilters = true)+ }++ val distinct = found.distinctEnough()+ return when {+ distinct.isEmpty() -> FallbackColors+ distinct.size >= 4 -> distinct.take(4)+ else -> distinct.expandedToFour()+ }+}++/** Drop near-duplicates, so the four blobs don't collapse into one wash. */+private fun List<Color>.distinctEnough(): List<Color> {+ val kept = mutableListOf<Color>()+ forEach { color -> if (kept.none { it.isCloseTo(color) }) kept += color }+ return kept+}++private fun Color.isCloseTo(other: Color): Boolean {+ val a = hsl()+ val b = other.hsl()+ val hueGap = abs(a[0] - b[0]).let { min(it, 360f - it) }+ return hueGap < 15f && abs(a[2] - b[2]) < 0.12f+}++/** Fill the empty slots off the art itself, fanning hue and lightness out. */+private fun List<Color>.expandedToFour(): List<Color> {+ val out = toMutableList()+ var step = 1+ while (out.size < 4) {+ out += this[(out.size - size) % size].shifted(24f * step, 0.12f * step)+ step+++ }+ return out+}++private fun Color.shifted(hue: Float, lightness: Float): Color {+ val hsl = hsl()+ hsl[0] = (hsl[0] + hue) % 360f+ hsl[2] = (hsl[2] + lightness).coerceIn(0.2f, 0.7f)+ return Color(ColorUtils.HSLToColor(hsl))+}++private fun Color.hsl(): FloatArray =+ FloatArray(3).also { ColorUtils.colorToHSL(toArgb(), it) }++/** Boost saturation and clamp lightness so any artwork yields a rich, non-muddy mesh. */+private fun Color.tuned(): Color {+ val hsl = FloatArray(3)+ ColorUtils.colorToHSL(toArgb(), hsl)+ hsl[1] = (hsl[1] * 1.35f).coerceAtMost(1f)+ hsl[2] = hsl[2].coerceIn(0.28f, 0.58f)+ return Color(ColorUtils.HSLToColor(hsl))+}++private fun Color.dimmed(): Color {+ val hsl = FloatArray(3)+ ColorUtils.colorToHSL(toArgb(), hsl)+ hsl[2] = 0.12f+ return Color(ColorUtils.HSLToColor(hsl))+}diff --git a/base/app/src/main/java/com/music/spotui/ui/look/PauseShrink.kt b/base/app/src/main/java/com/music/spotui/ui/look/PauseShrink.ktnew file mode 100644index 00000000..c10bdd4b--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/look/PauseShrink.kt@@ -0,0 +1,22 @@+package com.music.spotui.ui.look++import androidx.compose.animation.core.Spring+import androidx.compose.animation.core.animateFloatAsState+import androidx.compose.animation.core.spring+import androidx.compose.runtime.Composable+import androidx.compose.runtime.State++/** How far the Immersive artwork steps back while the music is paused. */+const val PAUSED_ARTWORK_SCALE = 0.86f++/**+ * The Immersive artwork's scale: it steps back to [PAUSED_ARTWORK_SCALE] on pause and comes+ * forward again with a slight bounce when the music resumes. Read it in a graphics layer so+ * the spring only redraws. With animations off it snaps, like every other spring.+ */+@Composable+fun rememberPauseScale(playing: Boolean): State<Float> = animateFloatAsState(+ targetValue = if (playing) 1f else PAUSED_ARTWORK_SCALE,+ animationSpec = spring(dampingRatio = Spring.DampingRatioLowBouncy, stiffness = Spring.StiffnessLow),+ label = "pauseScale",+)diff --git a/base/app/src/main/java/com/music/spotui/ui/look/SweptLyricLine.kt b/base/app/src/main/java/com/music/spotui/ui/look/SweptLyricLine.ktnew file mode 100644index 00000000..4f085ce2--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/look/SweptLyricLine.kt@@ -0,0 +1,852 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * sharedUi/src/jvmSharedMain/kotlin/com/music/bitchord/ui/player/PlayerLyrics.kt at edc1e6f+ * (SweptLyricLine, its drawing helpers and the constants they use) and+ * sharedUi/src/androidMain/kotlin/com/music/bitchord/ui/player/PlayerPlatformUi.android.kt+ * (clipShiftedDown). Modified for Myspoti, 2026-10.+ *+ * Changes: public so the Immersive screens can draw it; drawn from SweptLine (see+ * SweptLyricModel.kt); the translation particles are left out.+ */+package com.music.spotui.ui.look++import androidx.compose.animation.core.CubicBezierEasing+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.padding+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.MutableLongState+import androidx.compose.runtime.derivedStateOf+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.runtime.structuralEqualityPolicy+import androidx.compose.ui.AbsoluteAlignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.BlurredEdgeTreatment+import androidx.compose.ui.draw.blur+import androidx.compose.ui.draw.drawWithContent+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.graphics.BlendMode+import androidx.compose.ui.graphics.Brush+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.CompositingStrategy+import androidx.compose.ui.graphics.drawscope.ContentDrawScope+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.graphics.drawscope.clipRect+import androidx.compose.ui.graphics.drawscope.scale+import androidx.compose.ui.graphics.drawscope.translate+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.text.TextLayoutResult+import androidx.compose.ui.text.TextStyle+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp++/** Returns true if most of the strongly directional characters in [text] are right-to-left. */+private fun isRtl(text: String): Boolean {+ var rtlCount = 0+ var ltrCount = 0+ for (ch in text) {+ val code = ch.code+ // Hebrew presentation forms+ if (code in 0xFB1D..0xFB4F) return true+ when (Character.getDirectionality(ch)) {+ Character.DIRECTIONALITY_RIGHT_TO_LEFT,+ Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC -> rtlCount+++ Character.DIRECTIONALITY_LEFT_TO_RIGHT -> ltrCount+++ }+ }+ return rtlCount > ltrCount+}++/** Whether this text should align to the right end of its box. */+private fun alignsRight(text: String, alignEnd: Boolean, laneLocked: Boolean): Boolean =+ if (laneLocked) alignEnd else isRtl(text)++/**+ * How far back the part of the playing line that hasn't been sung yet is held.+ *+ * The one-line strip gets less of a gap than the full panel: it is one line of+ * small type with nothing around it to compare against.+ */+const val UNSUNG_ALPHA = 0.45f+const val UNSUNG_ALPHA_STRIP = 0.55f++/**+ * The bloom behind the line being sung, at its very strongest.+ *+ * Kept well under half strength: the halo is drawn from the same white as the+ * text, so at full alpha it stops reading as light and starts reading as a+ * second, badly printed copy of the words. What is actually drawn is this+ * scaled by each letter's own bloom, so only a properly carried note ever sees+ * the whole of it — the bloom is attached to the letters of the held words+ * (see [SweptLine.growingWords]), not dragged along under the sweep.+ */+const val GLOW_ALPHA = 0.62f++/**+ * How far the bloom spreads off a letter. Tight, because it is a letter's worth+ * of light: a wide radius on something this small is a smudge behind the text+ * instead of a glow coming off it.+ */+private val GLOW_RADIUS = 6.dp++/**+ * Room reserved inside each copy of a line for the halo to spread into.+ *+ * A blur is computed on its layer's own bitmap, so a halo with nowhere to go+ * inside those bounds is a halo with a hard edge. Every copy carries the same+ * inset so they still lay out identically, and the list gives the width back+ * by taking it off its own padding and row spacing.+ */+val GLOW_ROOM = 10.dp++/** Where a lyric line is in its own animation; see [SweptLyricLine]. */+private const val PHASE_BEFORE = 0+private const val PHASE_MOVING = 1+private const val PHASE_AFTER = 2++/**+ * How far the sweep's leading edge fades out instead of ending on a cut.+ *+ * A hard boundary is legible as a boundary: the eye reads a bar travelling+ * across the words rather than the words themselves lighting up as they are+ * sung. Feathering it over roughly a character and a half is what turns the+ * cut back into a wavefront.+ */+private val WIPE_FEATHER = 30.dp++/**+ * How far the word being sung lifts off the line. Two pixels, and it has to be+ * about two: enough that the eye catches the words moving under the sweep,+ * little enough that nothing appears to come loose from the line it belongs to.+ */+private val WORD_RISE = 2.dp++/**+ * How much further up a row is opened when it holds a word being animated+ * letter by letter, in multiples of [WORD_RISE]: a letter that swells has to be+ * given the room above the line it grew out of.+ */+private const val GROW_HEADROOM = 3f++/**+ * How the stack falls away either side of the line being sung, indexed by+ * distance from it. The two lines around the playing one stay legible so you+ * can read ahead and behind; the last entry stands for everything further out.+ */+val LINE_FALLOFF_ALPHA = floatArrayOf(1f, 0.8f, 0.7f, 0.58f, 0.46f)+val LINE_FALLOFF_BLUR = arrayOf(0.dp, 1.dp, 1.dp, 1.7.dp, 2.4.dp)++/** The playing line sits at 1; the rest sit fractionally back from it. */+const val INACTIVE_SCALE = 0.98f++/**+ * The curve every handover runs on: away quickly, in slowly and softly. One+ * curve for the lot — dimming, blurring, scaling and the scroll — so a line+ * handing over reads as a single movement rather than four.+ */+val LYRIC_EASING = CubicBezierEasing(0.41f, 0f, 0.12f, 0.99f)+const val LYRIC_SETTLE_MS = 400++/** Clips to the box, then draws [block] moved down by [dy]. */+private fun DrawScope.clipShiftedDown(+ left: Float,+ top: Float,+ right: Float,+ bottom: Float,+ dy: Float,+ block: DrawScope.() -> Unit,+) {+ clipRect(left = left, top = top, right = right, bottom = bottom) {+ translate(top = dy) { block() }+ }+}++/**+ * A lyric line with the sung part of it lit, the rest dimmed, and the boundary+ * travelling across the words in time with the vocal.+ *+ * Two copies of the same text stacked: a dim one and a bright one clipped to+ * whatever has been sung. Same string, same style, same constraints, so the+ * two lay out identically and the bright copy lands exactly on top of the dim+ * one. The alternative — colouring an AnnotatedString word by word — can only+ * change a whole word at a time, which turns the sweep into a flicker.+ *+ * The clip is recomputed in the draw phase, so a frame costs one clip and one+ * redraw of already-measured text.+ *+ * [glowAlpha] adds the bloom: a third copy, blurred, behind the other two+ * and clipped to the letters of whatever word is being held. Blurring *after*+ * the clip rather than before is what makes the halo bleed out past the letter+ * it belongs to, which is the part that reads as light coming off a carried+ * note rather than a drop shadow sitting under the line.+ */+@Composable+fun SweptLyricLine(+ line: SweptLine,+ clock: MutableLongState,+ style: TextStyle,+ dimAlpha: Float,+ modifier: Modifier = Modifier,+ maxLines: Int = Int.MAX_VALUE,+ overflow: TextOverflow = TextOverflow.Clip,+ glowAlpha: Float = 0f,+ glowRadius: Dp = GLOW_RADIUS,+ glowRoom: Dp = 0.dp,+ feather: Boolean = false,+ rise: Boolean = true,+ alignEnd: Boolean = false,+ laneLocked: Boolean = false,+ /** What the words are set in. */+ color: Color = Color.White,+) {+ var layout by remember(line) { mutableStateOf<TextLayoutResult?>(null) }++ // Filled in and read back a letter at a time inside the draw lambdas, and+ // shared by all three copies of the line — they draw one after another on+ // the same thread, so there is only ever one letter in hand. Held here+ // rather than allocated per frame: a held word is seven letters at the+ // outside, but this runs on every frame of every line that has one.+ val growth = remember { CharGrowth() }++ // Where this line is in its own animation — not started, moving, or done —+ // which changes three times a line rather than sixty times a second. The+ // draw passes below read the clock only while it says moving; on either+ // side they draw a position that looks identical to any other there (see+ // [SweptLine.animatesFromMs]), so a line nobody is singing never redraws.+ //+ // Read in draw, every line on screen used to redraw on every frame of+ // playback, and each line away from the playing one sits under a blur+ // that then had to be worked out again — most of the panel's frame, for a+ // picture that had not changed. Paused, nothing moved, which is why the+ // panel was smooth paused and slow playing.+ val phase = remember(line, clock) {+ derivedStateOf(structuralEqualityPolicy()) {+ val now = clock.longValue+ when {+ now < line.animatesFromMs -> PHASE_BEFORE+ now > line.animatesUntilMs -> PHASE_AFTER+ else -> PHASE_MOVING+ }+ }+ }+ val drawnAt: () -> Long = {+ when (phase.value) {+ PHASE_MOVING -> clock.longValue+ PHASE_BEFORE -> line.animatesFromMs - 1+ else -> line.animatesUntilMs + 1+ }+ }++ // Carried by every copy: identical insets keep them laying out identically,+ // and the inset is what gives the blurred copy's layer somewhere to put the+ // halo. Sits inside the blur and outside the draw lambdas, so text-layout+ // coordinates and draw coordinates still agree.+ //+ // Off unless asked for. Only the full panel can afford it — it takes the+ // space back off its own row spacing and content padding. Handed to the+ // one-line strip above the scrubber, where there is no glow to make room+ // for and nothing paying the space back, it just left the line sitting in+ // a pocket of air with the chevron pushed off it.+ val room = if (glowRoom > 0.dp) Modifier.padding(glowRoom) else Modifier++ // Sits outside [room] and outside the sweep, so what it moves is the+ // finished picture of the word — dim tail, lit head and all — rather than+ // one copy sliding out from under another. Carried by both copies from the+ // same arithmetic, which is what keeps them on top of each other.+ //+ // Off for the one-line strip above the scrubber ([rise] = false). The lift+ // belongs to a page of lyrics, where a word rising out of the line it sits+ // in is the thing being read; on a single line pinned between the credits+ // and the slider it has nothing to rise away from and reads as the strip+ // itself twitching.+ val riseAgainst: (Modifier) -> Modifier = { inner ->+ if (!rise) {+ inner+ } else {+ Modifier+ .drawWithContent {+ val measured = layout+ if (measured == null || line.words.isEmpty()) {+ drawContent()+ } else {+ riseWith(+ layout = measured,+ line = line,+ positionMs = drawnAt(),+ inset = glowRoom.toPx(),+ peak = WORD_RISE.toPx(),+ growth = growth,+ )+ }+ }+ .then(inner)+ }+ }++ val sweep = Modifier.drawWithContent {+ val position = drawnAt()+ when {+ // Sung and done with: all of it is lit. Checked first so the lines+ // above and below the playing one — which are in this same state+ // for minutes at a time — cost a comparison per frame rather than+ // a walk of their words.+ position >= line.endMs -> drawContent()+ // Not started: nothing lit, the dim copy is the whole of it.+ position <= line.timeMs -> Unit+ else -> layout?.let {+ sweepTo(it, line.revealedChars(position), line.sweepSpans, feather)+ }+ }+ }++ val right = alignsRight(line.text, alignEnd, laneLocked)+ Box(+ modifier,+ contentAlignment = if (right) AbsoluteAlignment.TopRight else AbsoluteAlignment.TopLeft,+ ) {+ Text(+ text = line.text,+ style = style,+ color = color.copy(alpha = dimAlpha),+ maxLines = maxLines,+ overflow = overflow,+ onTextLayout = { layout = it },+ modifier = riseAgainst(room),+ )+ if (glowAlpha > 0.01f) {+ Text(+ text = line.text,+ style = style,+ color = color,+ maxLines = maxLines,+ overflow = overflow,+ modifier = Modifier+ .graphicsLayer { alpha = glowAlpha }+ .blur(glowRadius, BlurredEdgeTreatment.Unbounded)+ .then(room)+ // Each letter is masked to its own brightness with DstIn,+ // which needs a layer of its own to erase into — against the+ // backdrop it would take the artwork with it.+ .graphicsLayer { compositingStrategy = CompositingStrategy.Offscreen }+ .drawWithContent {+ // Deliberately not the shared sweep: that lights+ // everything sung so far, and this lights only the words+ // being held. Most lines draw nothing here at all, which+ // is the whole difference between this and a halo+ // travelling under the highlight.+ val measured = layout ?: return@drawWithContent+ glowGrown(+ layout = measured,+ line = line,+ positionMs = drawnAt(),+ inset = glowRoom.toPx(),+ peak = WORD_RISE.toPx(),+ growth = growth,+ )+ },+ )+ }+ Text(+ text = line.text,+ style = style,+ color = color,+ maxLines = maxLines,+ overflow = overflow,+ // The feather erases into this layer, so the layer has to exist —+ // and only while it is being drawn. Every line carrying one would+ // put the whole panel through an offscreen buffer to soften an edge+ // that at most two of them have.+ modifier = riseAgainst(+ Modifier+ .graphicsLayer {+ compositingStrategy = if (feather) {+ CompositingStrategy.Offscreen+ } else {+ CompositingStrategy.Auto+ }+ }+ .then(room)+ .then(sweep),+ ),+ )+ }+}++/**+ * Draws this text clipped to the letters of the words being held, each at its+ * own brightness — the light the singing is actually giving off, rather than a+ * band of it dragged along behind the highlight.+ *+ * Nothing at all on a line of ordinary syllables: the words that light up are+ * the ones held long enough to have earned it, so a verse of patter is simply+ * dark and costs one comparison to establish. That selectiveness is the point.+ * A glow present on every word is a property of the highlight; a glow that+ * arrives only when a note is carried is a property of the voice.+ *+ * Each letter is masked to its own bloom rather than drawn at it, because the+ * caller's layer is what this erases into — see [SweptLyricLine]. The mask+ * lands before the blur, so what spreads is already the right brightness.+ */+private fun ContentDrawScope.glowGrown(+ layout: TextLayoutResult,+ line: SweptLine,+ positionMs: Long,+ inset: Float,+ peak: Float,+ growth: CharGrowth,+) {+ if (!line.isGrowing(positionMs)) return+ val em = layout.layoutInput.style.fontSize.toPx()+ val length = layout.layoutInput.text.length+ for (word in line.growingWords) {+ if (positionMs < word.startMs || positionMs > word.restsAtMs) continue+ val span = line.wordSpans[word.index]+ val fall = line.wordFall(word.index, positionMs)+ for (char in span.first..minOf(span.last, length - 1)) {+ word.sampleInto(char - span.first, positionMs, growth)+ if (growth.bloom <= 0.01f) continue+ val visualLine = layout.getLineForOffset(char)+ // Row-aware, for the same reason the sweep is; see [xOn].+ val from = layout.xOn(char, visualLine, inset)+ val to = layout.xOn(char + 1, visualLine, inset)+ if (to <= from) continue+ val dx = growth.shift * em+ val dy = -growth.rise * peak * fall+ val rowTop = layout.getLineTop(visualLine) + inset+ val bottom = layout.getLineBottom(visualLine) + inset+ val overhang = (to - from) * (growth.scale - 1f) / 2f+ clipRect(+ left = from - overhang + dx,+ top = rowTop - peak * GROW_HEADROOM,+ right = to + overhang + dx,+ bottom = bottom,+ ) {+ translate(left = dx, top = dy) {+ scale(+ growth.scale,+ growth.scale,+ Offset((from + to) / 2f, (rowTop + bottom) / 2f),+ ) {+ }+ }+ // Scoped to this letter's own clip, so it takes this letter's+ // brightness down and leaves its neighbours — which have their+ // own, a beat behind — where they are.+ drawRect(+ color = Color.White.copy(alpha = growth.bloom),+ blendMode = BlendMode.DstIn,+ )+ }+ }+ }+}++/**+ * Redraws this row with the word being sung lifted off the line, and the ones+ * behind it settling back down.+ *+ * The line is cut at word boundaries and each piece replayed at its own+ * height, which is what CSS gets for free by making every syllable its own+ * box. Cutting between words rather than inside one means no glyph is ever+ * sliced, and the pieces that are on the floor — which is most of them, most+ * of the time — are one replay between them rather than one each.+ *+ * Costs nothing at all until something is off the floor: a line with no lift+ * on it draws exactly once, the same as it did before any of this.+ */+private fun ContentDrawScope.riseWith(+ layout: TextLayoutResult,+ line: SweptLine,+ positionMs: Long,+ inset: Float,+ peak: Float,+ growth: CharGrowth,+) {+ if (!line.isLifted(positionMs)) {+ drawContent()+ return+ }+ val em = layout.layoutInput.style.fontSize.toPx()+ for (visualLine in 0 until layout.lineCount) {+ val lineStart = layout.getLineStart(visualLine)+ val lineEnd = layout.getLineEnd(visualLine, visibleEnd = true)+ // The row's own box. Anything standing still is clipped to exactly+ // this: a band opened upwards would take in the bottom of the row+ // above and draw it a second time, and two passes of a half-transparent+ // line do not add up to the same line. That doubled sliver along every+ // row is what read as the lines overlapping.+ val top = layout.getLineTop(visualLine) + inset+ val bottom = layout.getLineBottom(visualLine) + inset+ var at = lineStart+ var edge = layout.getLineLeft(visualLine) + inset+ for (index in line.words.indices) {+ val span = line.wordSpans[index]+ val start = maxOf(span.first, lineStart)+ val end = minOf(span.last + 1, lineEnd)+ if (start >= end) continue+ // Only while it is actually moving. Once the last letter has come to+ // rest the word is back to being an ordinary sung word settling+ // down, and the two agree exactly at the handover — a letter rests+ // at precisely the lift [SweptLine.wordLift] would give it — so the+ // cheaper single slice takes over without a step.+ val held = line.growingAt(index)?.takeIf { positionMs in it.startMs..it.restsAtMs }+ val lift = line.wordLift(index, positionMs)+ // A word with nothing happening to it is left to the flat run,+ // which is the whole of the line for all but a syllable of it.+ if (held == null && lift <= 0.01f) continue+ val from = layout.xOn(start, visualLine, inset)+ val to = layout.xOn(end, visualLine, inset)+ // Nothing to cut. Left where it is rather than stepped over, so the+ // flat run still has it and the row keeps its words.+ if (to <= from) continue+ // Everything between the last risen word and this one is flat, and+ // goes down in a single piece however many words that spans.+ if (start > at) sliceRisen(edge, top, from, bottom, 0f)+ if (held != null) {+ growEach(+ layout, held, line, positionMs, visualLine,+ start, end, top, bottom, inset, peak, em, growth,+ )+ } else {+ // Only what is off the floor gets room above the row to be off+ // it in; see [top].+ sliceRisen(from, top - peak, to, bottom, -lift * peak)+ }+ at = end+ edge = to+ }+ if (at < lineEnd) {+ sliceRisen(edge, top, layout.getLineRight(visualLine) + inset, bottom, 0f)+ }+ }+}++/**+ * Redraws one held word a letter at a time, each at its own swell and height.+ *+ * The word is cut between characters rather than between words, so a letter can+ * be scaled about its own centre without the ones either side of it coming+ * along. Each piece is clipped to where its letter is *going* rather than where+ * it sits: a glyph grown about its middle reaches past the box it was laid out+ * in, and clipping to that box would shave both sides off it as it swells.+ *+ * The overlap that buys — a letter's clip reaching a pixel or so into its+ * neighbour's — is why this is only ever run on a word that has earned it. Two+ * copies of a glyph edge a pixel apart is nothing on a letter mid-swell and+ * would be an obvious double image across a whole line.+ */+@Suppress("LongParameterList")+private fun ContentDrawScope.growEach(+ layout: TextLayoutResult,+ word: GrowingWord,+ line: SweptLine,+ positionMs: Long,+ visualLine: Int,+ start: Int,+ end: Int,+ top: Float,+ bottom: Float,+ inset: Float,+ peak: Float,+ em: Float,+ growth: CharGrowth,+) {+ // The settle is shared with every other word: a letter comes to rest at the+ // same small lift, and then goes down with the rest of the line.+ val fall = line.wordFall(word.index, positionMs)+ val first = line.wordSpans[word.index].first+ // Room to swell into, above the row rather than inside it. The pivot stays+ // on the row's own middle: scaling about the middle of the *band* would+ // walk every letter downwards as it grew.+ val ceiling = top - peak * GROW_HEADROOM+ val middle = (top + bottom) / 2f+ for (char in start until end) {+ word.sampleInto(char - first, positionMs, growth)+ val from = layout.xOn(char, visualLine, inset)+ val to = layout.xOn(char + 1, visualLine, inset)+ if (to <= from) continue+ val dx = growth.shift * em+ val dy = -growth.rise * peak * fall+ val overhang = (to - from) * (growth.scale - 1f) / 2f+ clipShiftedDown(+ left = from - overhang + dx,+ top = ceiling,+ right = to + overhang + dx,+ bottom = bottom,+ dy = dy,+ ) {+ translate(left = dx) {+ scale(growth.scale, growth.scale, Offset((from + to) / 2f, middle)) {+ }+ }+ }+ }+}++/**+ * Where an offset sits horizontally *on the row it was cut out of*.+ *+ * [TextLayoutResult.getHorizontalPosition] answers for the row the offset+ * itself belongs to — and the offset one past the last character of a wrapped+ * row belongs to the next row, so asking where a word that runs up to a wrap+ * *ends* gives a position at the far left, one row down. A slice cut between+ * there and the word's start is empty, and the walk then treats the row as+ * finished: everything from that word to the end of the row is never drawn.+ *+ * Whole rows disappeared that way, and Japanese lines disappeared most, because+ * word spans there are often whole phrases and reach a wrap on their own where+ * an English word rarely does.+ */+/**+ * Where a character offset sits across a visual line, in pixels.+ *+ * For RTL paragraphs the first character of a visual line is at the right+ * edge and the last is at the left — this function respects that so callers+ * (horizontalAt, sweepTo) get correct clip boundaries regardless of text+ * direction. Interior offsets delegate to Compose's own cursor-position+ * calculation which already handles direction; only the two boundary cases+ * need special handling because getLineLeft / getLineRight return physical+ * bounding-box edges (always left ≤ right), not paragraph-direction edges.+ */+private fun TextLayoutResult.xOn(offset: Int, visualLine: Int, inset: Float): Float {+ val lineStart = getLineStart(visualLine)+ val lineEndVisible = getLineEnd(visualLine, visibleEnd = true)+ val lineLeft = getLineLeft(visualLine) + inset+ val lineRight = getLineRight(visualLine) + inset++ val rtl = getParagraphDirection(lineStart.coerceIn(0, (layoutInput.text.length - 1).coerceAtLeast(0))) ==+ androidx.compose.ui.text.style.ResolvedTextDirection.Rtl++ return when {+ offset <= lineStart -> if (rtl) lineRight else lineLeft+ offset >= lineEndVisible -> if (rtl) lineLeft else lineRight+ // The inset belongs on every answer, not just the two edges: the rows+ // are drawn [inset] in from the layout's origin, and an interior cut+ // without it lands that far left of the glyph boundary — the lifted+ // and swelling slices then sliced letters in half.+ else -> (getHorizontalPosition(offset, usePrimaryDirection = true) + inset)+ .coerceIn(lineLeft, lineRight)+ }+}++/** One piece of a line, clipped to its own width and drawn at its own height. */+private fun ContentDrawScope.sliceRisen(+ from: Float,+ top: Float,+ to: Float,+ bottom: Float,+ dy: Float,+) {+ if (to <= from) return+ clipShiftedDown(left = from, top = top, right = to, bottom = bottom, dy = dy) {+ }+}++/**+ * Where a fractional character index sits across a visual line, in pixels.+ *+ * Inside a timed piece — a syllable, or a word nobody split — that sits whole+ * on this row, the index is read as a share of the piece and laid across its+ * width. Read letter by letter instead, the edge crossed a "w" in the same time+ * as an "i": it sped up and slowed down inside every word, a wobble that a held+ * note made plain. am-lyrics wipes each syllable across its box at a constant+ * rate, and this is the same thing.+ */+private fun horizontalAt(+ layout: TextLayoutResult,+ chars: Float,+ visualLine: Int,+ spans: List<IntRange>,+): Float {+ val lineStart = layout.getLineStart(visualLine)+ val lineEndVisible = layout.getLineEnd(visualLine, visibleEnd = true)+ // Use the *all* end (including trailing whitespace/punctuation) for the+ // boundary check — visibleEnd can exclude chars that sit at the physical+ // edge of an RTL line and would cause xOn to resolve to the next visual+ // line instead of the current one's far edge.+ val lineEndAll = layout.getLineEnd(visualLine, visibleEnd = false)+ val word = spans.firstOrNull { chars >= it.first && chars < it.last + 1 }+ if (word != null && word.first >= lineStart && word.last + 1 <= lineEndVisible) {+ val from = layout.xOn(word.first, visualLine, 0f)+ val to = layout.xOn(word.last + 1, visualLine, 0f)+ return from + (to - from) * (chars - word.first) / (word.last + 1 - word.first)+ }+ // A word broken over a wrap, or the space between two words: letter by+ // letter, which is all a single space or a half-word needs.+ val index = chars.toInt().coerceIn(lineStart, lineEndAll)+ // Row-aware at both ends: on the last character of a wrapped row the next+ // position belongs to the row below, and read straight it puts the edge+ // back at the left margin — the highlight jumped backwards a letter before+ // every wrap. Guard against that by checking whether index+1 would land+ // on the next visual line; if so, clamp to this line's far edge instead.+ val here = layout.xOn(index, visualLine, 0f)+ val rawNext = index + 1+ val textLen = layout.layoutInput.text.length+ val spills: Boolean = layout.getLineForOffset(rawNext.coerceIn(0, textLen)) != visualLine+ val next: Float = if (spills) {+ // Spilled to the next visual line: use this line's far edge as the+ // interpolation target. For RTL that is getLineLeft; for LTR it is+ // getLineRight. The fallback below (xOn with coerceAtMost(lineEnd))+ // would return the wrong side for RTL.+ if (rawNext > lineEndVisible) {+ // At or past the visible end: use the all-end edge.+ val rtl = layout.getParagraphDirection(+ visualLine.coerceAtMost(lineEndAll).coerceIn(0, textLen - 1)+ ) == androidx.compose.ui.text.style.ResolvedTextDirection.Rtl+ val farLeft = layout.getLineLeft(visualLine)+ val farRight = layout.getLineRight(visualLine)+ // For RTL, the "far" edge in character order is getLineLeft;+ // for LTR it is getLineRight. We detect by comparing the two:+ if (rtl) farLeft else farRight+ } else {+ layout.xOn(rawNext.coerceAtMost(lineEndVisible), visualLine, 0f)+ }+ } else {+ layout.xOn(rawNext, visualLine, 0f)+ }+ return here + (next - here) * (chars - index)+}++/**+ * Draws this text clipped to its first [revealedChars] characters.+ *+ * Wrapped lines are handled a visual line at a time: the ones already passed+ * are drawn whole, the one holding the boundary is cut at it, and the rest are+ * left to the dim copy. Within a word the cut moves across the word's width+ * at a steady rate — see [horizontalAt] — rather than jumping a letter at a+ * time. [spans] are the line's timed pieces, [SweptLine.sweepSpans]; empty, the+ * cut goes letter by letter.+ *+ * The boundary itself is then feathered over the [WIPE_FEATHER] ahead of it+ * rather than left as the cut, which needs the caller to give this an offscreen layer to erase+ * into — see [SweptLyricLine]. Only the line actually being sung carries one;+ * everywhere else the boundary is at one end of the text or the other and+ * there is nothing to soften.+ */+private fun ContentDrawScope.sweepTo(+ layout: TextLayoutResult,+ revealedChars: Float,+ spans: List<IntRange>,+ feather: Boolean,+) {+ if (revealedChars <= 0f) return+ val textLen = layout.layoutInput.text.length+ if (revealedChars >= textLen) {+ drawContent()+ return+ }+ // Derive RTL from the layout's own resolved paragraph direction, not from+ // text heuristics. This keeps geometry in lock-step with how Compose+ // actually laid out the glyphs — critical when a translation line (Hebrew)+ // sits under an English lead and both get different text-analysis results.+ val offset = layout.getLineStart(0).coerceIn(0, (layout.layoutInput.text.length - 1).coerceAtLeast(0))+ val rtl = layout.getParagraphDirection(offset) == androidx.compose.ui.text.style.ResolvedTextDirection.Rtl++ for (visualLine in 0 until layout.lineCount) {+ val lineStart = layout.getLineStart(visualLine)+ val lineEndVisible = layout.getLineEnd(visualLine, visibleEnd = true)+ val lineEndAll = layout.getLineEnd(visualLine, visibleEnd = false)++ // Lines whose character-range start is past the sweep boundary have+ // nothing lit; lines after that too. Use `>` (not `>=`) so a line+ // whose *first* char is exactly at the boundary still gets drawn —+ // it is the boundary line and must show the feather edge.+ if (revealedChars <= lineStart) return++ val cut = revealedChars < lineEndAll+ val charPos = if (cut) {+ horizontalAt(layout, revealedChars, visualLine, spans)+ } else {+ // The sweep has passed this entire visual line. Its boundary is+ // the *far* edge: right edge for RTL (lineLeft), left edge for LTR.+ if (rtl) layout.getLineLeft(visualLine) else layout.getLineRight(visualLine)+ }++ val lineLeft = layout.getLineLeft(visualLine)+ val lineRight = layout.getLineRight(visualLine)++ // Clamp the sweep boundary so the clip rect is always valid and never+ // inverted near the line ends. For RTL the revealed prefix [0,k) must+ // occupy [x(k), lineRight], with x(k) clamped inside [lineLeft, lineRight].+ val safeCharPos = charPos.coerceIn(lineLeft, lineRight)++ // The feather runs *ahead* of the boundary, into what is still to be+ // sung: lit solid up to now, fading out over the next [WIPE_FEATHER].+ // Trailing behind it instead, the letter being sung right now was the+ // dimmest part of the lit copy, and the line ran out of time with a+ // faded tail still on it and then snapped to full — which read as the+ // highlight being late. Ahead of it, the fade runs off the end of the+ // text as the last letter is reached, and the line finishes already+ // whole.+ //+ // Grown in over the first [WIPE_FEATHER] of each row rather than+ // opened at full width, or the first letter of every row would pop in+ // half-lit the frame the sweep reached it.+ val featherPx = if (feather && cut) {+ minOf(+ WIPE_FEATHER.toPx(),+ if (rtl) lineRight - safeCharPos else safeCharPos - lineLeft,+ )+ } else {+ 0f+ }+ val lead = if (rtl) {+ (safeCharPos - featherPx).coerceAtLeast(lineLeft)+ } else {+ (safeCharPos + featherPx).coerceAtMost(lineRight)+ }++ // For RTL lines the sweep fills right-to-left: clip from the line's+ // right edge down to the feather's leading edge. For LTR it fills+ // left-to-right as before.+ val (clipLeft, clipRight) = if (rtl) {+ lead to lineRight+ } else {+ lineLeft to lead+ }++ // Guard: an empty or inverted clip is a no-op; skip it cleanly.+ if (clipLeft >= clipRight) continue++ val top = layout.getLineTop(visualLine)+ val bottom = layout.getLineBottom(visualLine)+ clipRect(+ left = clipLeft,+ top = top,+ right = clipRight,+ bottom = bottom,+ ) {+ }++ // Only the visual line holding the boundary has an edge to soften; a+ // line revealed to its end runs into the wrap, which is not an edge.+ if (featherPx < 0.5f) continue++ // Scoped to this line's band so the mask cannot reach the lines above+ // and below it: DstIn erases whatever the source does not cover, and+ // outside the clip there is no source at all, so they are left alone.+ // Within it the brush clamps — opaque up to the boundary, gone past+ // the feather. The gradient keeps its full width even where the clip+ // is cut short by the end of the row, so the last letters keep fading+ // up instead of being cut off.+ clipRect(top = top, bottom = bottom) {+ drawRect(+ brush = Brush.horizontalGradient(+ 0f to Color.White,+ 1f to Color.Transparent,+ startX = safeCharPos,+ endX = if (rtl) safeCharPos - featherPx else safeCharPos + featherPx,+ ),+ blendMode = BlendMode.DstIn,+ )+ }+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/look/SweptLyricModel.kt b/base/app/src/main/java/com/music/spotui/ui/look/SweptLyricModel.ktnew file mode 100644index 00000000..eeb58203--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/look/SweptLyricModel.kt@@ -0,0 +1,548 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * shared/src/jvmSharedMain/kotlin/com/music/bitchord/data/lyrics/LyricLine.kt at edc1e6f.+ * Modified for Myspoti, 2026-10.+ *+ * Changes: renamed SweptLine / SweptWord / SweptSyllable so they do not clash with Myspoti's+ * own lyric entities, which they are built from (see toSwept). The answering vocal, duet+ * sides, translation timing and character stripping are left out for now.+ */+package com.music.spotui.ui.look++/**+ * One word of a line, with the stretch of the song it is sung over.+ *+ * Some sources split long words into syllables. The word is still the unit+ * the line is laid out, lifted and lit in, so [startMs] is the first+ * syllable's start and [endMs] the last one's end; the sweep follows+ * [syllables] where there are some. Empty for a word nobody split, which is+ * most of them — the word is then its own single syllable.+ */+data class SweptWord(+ val startMs: Long,+ val endMs: Long,+ val text: String,+ val syllables: List<SweptSyllable> = emptyList(),+) {+ /**+ * How many of [text]'s characters have been sung at [positionMs], as a+ * fraction. Each syllable fills its own characters over its own time, and+ * a pause between two of them rests on the boundary rather than creeping+ * into the next one before it is sung.+ */+ fun charsSungAt(positionMs: Long): Float {+ if (positionMs <= startMs) return 0f+ if (positionMs >= endMs) return text.length.toFloat()+ if (syllables.isEmpty()) {+ val span = (endMs - startMs).coerceAtLeast(1L)+ return (positionMs - startMs).toFloat() / span * text.length+ }+ for (syllable in syllables) {+ if (positionMs < syllable.startMs) return syllable.startChar.toFloat()+ if (positionMs < syllable.endMs) {+ val span = (syllable.endMs - syllable.startMs).coerceAtLeast(1L)+ val through = (positionMs - syllable.startMs).toFloat() / span+ return syllable.startChar + through * (syllable.endChar - syllable.startChar)+ }+ }+ return text.length.toFloat()+ }+}++/**+ * One separately timed piece of a [SweptWord]: the characters [startChar]+ * until [endChar] of the word's text, sung from [startMs] to [endMs].+ */+data class SweptSyllable(+ val startMs: Long,+ val endMs: Long,+ val startChar: Int,+ val endChar: Int,+)++/**+ * One synced line. [timeMs] is when it starts; [words] is filled only when+ * the source carries word-level timing, otherwise the line highlights whole.+ * [sungUntilMs] is the line's own end where the source states one.+ */+data class SweptLine(+ val timeMs: Long,+ val text: String,+ val words: List<SweptWord> = emptyList(),+ val sungUntilMs: Long? = null,+) {+ val isGap: Boolean get() = text.isEmpty()++ val isWordSynced: Boolean get() = words.isNotEmpty()++ /**+ * Where each of [words] sits in [text], as character ranges.+ *+ * Walked from where the last one ended rather than searched from the start,+ * so a word repeated in the line lines up with its own occurrence — the+ * same walk [revealedChars] does, kept once because the rise reads it on+ * every frame of the line being sung rather than once as it passes.+ */+ val wordSpans: List<IntRange> by lazy(LazyThreadSafetyMode.NONE) {+ var offset = 0+ words.map { word ->+ val start = text.indexOf(word.text, offset).takeIf { it >= 0 } ?: offset+ val end = start + word.text.length+ offset = end+ start until end+ }+ }++ /**+ * Where each separately timed piece of the line sits in [text]: a word's+ * syllables where the source split it, the word itself where it did not.+ * The sweep crosses each of these at a steady pace of its own.+ */+ val sweepSpans: List<IntRange> by lazy(LazyThreadSafetyMode.NONE) {+ words.flatMapIndexed { index, word ->+ val span = wordSpans[index]+ if (word.syllables.isEmpty()) {+ listOf(span)+ } else {+ word.syllables.map { (span.first + it.startChar) until (span.first + it.endChar) }+ }+ }+ }++ /**+ * Whether anything on this line is off the floor at [positionMs].+ *+ * Two comparisons, so the lines that are not being sung — which is every+ * line but one, on every frame — settle the question without walking their+ * words to find out that none of them have moved.+ */+ fun isLifted(positionMs: Long): Boolean {+ val first = words.firstOrNull() ?: return false+ if (positionMs <= first.startMs) return false+ // A word animated letter by letter runs on past the ordinary fall — its+ // last letter only starts moving as the word ends. Stopping at the fall+ // would drop that letter back to the line mid-swell.+ return positionMs < words.last().endMs + RISE_MS || isGrowing(positionMs)+ }++ /**+ * The stretch of the song over which anything drawn for this line moves —+ * the sweep, the lift and its settle, a held word's letters — from+ * [animatesFromMs] to [animatesUntilMs]. Before it the line is drawn+ * unsung, after it sung and at rest, and either way exactly the same on+ * every frame — which is what lets a line outside it stop listening to the clock.+ */+ val animatesFromMs: Long by lazy(LazyThreadSafetyMode.NONE) {+ minOf(timeMs, words.firstOrNull()?.startMs ?: timeMs)+ }++ /** See [animatesFromMs]. */+ val animatesUntilMs: Long by lazy(LazyThreadSafetyMode.NONE) {+ val settled = words.lastOrNull()?.let { it.endMs + RISE_MS.toLong() } ?: endMs+ val grown = growingWords.maxOfOrNull { it.restsAtMs } ?: Long.MIN_VALUE+ maxOf(endMs, settled, grown)+ }++ /**+ * How far the word covering [positionMs] has lifted, 0..1.+ *+ * The words don't only light up, they rise as they land and settle back+ * once they are past — the lift travelling along the line is most of what+ * separates singing from a bar sliding across the text.+ *+ * How high a word goes is set by how long it is held — see [liftHeight]:+ * patter barely leaves the line and a carried note goes all the way up.+ * It rises over its own length, so a quick word's small lift is also a+ * quick one, and settles back over [RISE_MS] from its end.+ */+ fun wordLift(index: Int, positionMs: Long): Float {+ val word = words.getOrNull(index) ?: return 0f+ val riseMs = (word.endMs - word.startMs).toFloat().coerceIn(RISE_MIN_MS, RISE_MS)+ val rising = ((positionMs - word.startMs) / riseMs).coerceIn(0f, 1f)+ val falling = (1f - (positionMs - word.endMs) / RISE_MS).coerceIn(0f, 1f)+ return liftHeight(word) * smooth(minOf(rising, falling))+ }++ /** Whether anything actually told us when the singing stops, rather than only when it starts. */+ val hasKnownEnd: Boolean get() = words.isNotEmpty() || sungUntilMs != null++ /**+ * When the last word finishes — or the line's own end where the source+ * gave one, or [timeMs] when nothing did. Check [hasKnownEnd] before+ * reading a silence out of this.+ */+ val endMs: Long+ get() = words.lastOrNull()?.endMs ?: sungUntilMs ?: timeMs++ /**+ * How far through the line the singing has got, as a fractional index+ * into [text]. The sweep reveals up to this character.+ *+ * Within a word it interpolates across that word's own span, so a held+ * note draws slowly and a rattled-off one snaps. Whitespace between two+ * words is credited to the gap between them: it fills as the singer moves+ * on rather than jumping ahead of the next word's first letter.+ */+ fun revealedChars(positionMs: Long): Float {+ if (words.isEmpty()) return if (positionMs >= timeMs) text.length.toFloat() else 0f+ var offset = 0+ words.forEachIndexed { index, word ->+ // Where this word sits in [text]. Built by walking rather than+ // searching, so a word repeated in the line still lines up.+ val start = text.indexOf(word.text, offset).takeIf { it >= 0 } ?: offset+ val end = start + word.text.length+ if (positionMs < word.startMs) return start.toFloat()+ if (positionMs < word.endMs) return start + word.charsSungAt(positionMs)+ // Past this word: the trailing space fills over the pause before+ // the next one, so the highlight keeps creeping instead of resting+ // on the word's last letter.+ val next = words.getOrNull(index + 1)+ if (next != null && positionMs < next.startMs) {+ val gapStart = text.indexOf(next.text, end).takeIf { it >= 0 } ?: end+ val pause = (next.startMs - word.endMs).coerceAtLeast(1L)+ val through = (positionMs - word.endMs).toFloat() / pause+ return end + through * (gapStart - end)+ }+ offset = end+ }+ return text.length.toFloat()+ }++ /**+ * How much of a word's lift is left at [positionMs] — its full+ * [liftHeight] while it is being sung, easing to 0 over [RISE_MS] once it+ * is past. Carries the height so a letter-by-letter word comes to rest at+ * exactly the lift [wordLift] hands it over to.+ */+ fun wordFall(index: Int, positionMs: Long): Float {+ val word = words.getOrNull(index) ?: return 0f+ val falling = (1f - (positionMs - word.endMs) / RISE_MS).coerceIn(0f, 1f)+ return liftHeight(word) * smooth(falling)+ }++ /**+ * The words held long enough to be worth animating letter by letter: the+ * one moment in a line where there is time to see anything happen to a+ * word. Each letter of one swells, lifts and lights in turn — see+ * [GrowingWord] for the shape of it. Rare by design.+ */+ val growingWords: List<GrowingWord> by lazy(LazyThreadSafetyMode.NONE) {+ words.mapIndexedNotNull { index, word ->+ if (word.canGrow()) GrowingWord(index, word) else null+ }+ }++ /** The letter-by-letter treatment for word [index], where it has earned one. */+ fun growingAt(index: Int): GrowingWord? =+ growingWords.firstOrNull { it.index == index }++ /**+ * Whether any word on this line is mid-flight at [positionMs]. Answered+ * without touching the words themselves, so the lines that have no held+ * word — which is most of them — settle it in a comparison.+ */+ fun isGrowing(positionMs: Long): Boolean = growingWords.any {+ positionMs >= it.startMs && positionMs <= it.restsAtMs+ }+}++/**+ * Myspoti's lyric line as the sweep draws it. A word whose end is unknown (0) runs until+ * the next word starts, or [nextLineMs] for the last one.+ */+fun com.music.spotui.data.entity.LyricLine.toSwept(nextLineMs: Long? = null): SweptLine {+ val source = words.orEmpty()+ val swept = source.mapIndexed { index, word ->+ val next = source.getOrNull(index + 1)?.startMs ?: nextLineMs ?: (word.startMs + 500L)+ SweptWord(word.startMs, if (word.endMs > word.startMs) word.endMs else next, word.text.trim())+ }.filter { it.text.isNotEmpty() }+ return SweptLine(timeMs, text, swept)+}++/**+ * One word held long enough to be animated a letter at a time.+ *+ * Every letter runs the same three-beat move — swell up and forward, hold, then+ * settle back to the small lift every sung word carries — but each one starts+ * [GROW_STAGGER] of the word's own length after the one before it, so the+ * movement travels along the word instead of the whole thing pulsing at once.+ *+ * The peaks differ letter by letter as well. Later letters of a long word, and+ * every letter of a word that is only just held long enough to qualify, move+ * and light less: without that a seven-letter word read as a wave with a tail+ * that kept going after the singer had stopped.+ *+ * Peaks are precomputed here because they depend only on the word — its length+ * and how long it is held — while the frame only ever asks where in the move a+ * given letter has got to.+ */+class GrowingWord internal constructor(+ /** Which of the line's words this is. */+ val index: Int,+ word: SweptWord,+) {+ val startMs: Long = word.startMs+ val endMs: Long = word.endMs++ private val chars: Int = word.text.length+ private val scalePeak = FloatArray(chars)+ private val shiftPeak = FloatArray(chars)+ private val risePeak = FloatArray(chars)+ private val bloomPeak = FloatArray(chars)++ /** When the last letter has finished moving and is just sitting lifted. */+ val restsAtMs: Long++ init {+ val held = (endMs - startMs).coerceAtLeast(1L).toFloat()+ // How much of the full treatment this word has earned. Cubed, so the+ // difference between a word held for a second and one held for three is+ // most of the range and everything under a second is barely anything —+ // the alternative reads as every word twitching.+ val earned = ((held - GROW_RAMP_MIN_MS) / (GROW_RAMP_MAX_MS - GROW_RAMP_MIN_MS))+ .coerceIn(0f, 1f)+ .let { it * it * it }+ val decay = decayRate(chars, held)+ // A word barely over the line glows less than one held twice as long,+ // and a long word spreads what it has over more letters.+ val bloomPace = minOf(GROW_BLOOM_PACE_MAX, held / GROW_BLOOM_PACE_MS)+ val bloomSpread = when {+ chars <= 3 -> GROW_BLOOM_SHORT+ chars >= 6 -> GROW_BLOOM_LONG+ else -> 1f+ }+ // Short words swell a little more, having fewer letters to do it with.+ val base = if (chars <= 3) GROW_BASE_SHORT else GROW_BASE_LONG+ val liftPace = (held / GROW_LIFT_PACE_MS).coerceIn(GROW_LIFT_FLOOR, 1f)++ for (i in 0 until chars) {+ val place = if (chars > 1) i.toFloat() / (chars - 1) else 0f+ val reach = earned * (1f - place * decay)+ val scale = 1f + base + reach * GROW_SCALE_RANGE+ scalePeak[i] = scale * GROW_SCALE_TRIM+ bloomPeak[i] = (GROW_BLOOM_FLOOR + reach * GROW_BLOOM_RANGE) * bloomPace * bloomSpread+ // The lift is read off the swell rather than set on its own: a+ // letter that grows more rises further, which is what keeps the two+ // reading as one movement instead of two.+ risePeak[i] = ((scale - 1f) / GROW_SCALE_CEILING) * liftPace+ // Letters lean away from the middle of the word as it swells, so it+ // opens outwards rather than every letter sliding the same way.+ val centre = (i + 0.5f) / chars+ shiftPeak[i] = (centre - 0.5f) * 2f * (scale - 1f) * GROW_SHIFT_EM * GROW_SCALE_TRIM+ }++ val last = (chars - 1).coerceAtLeast(0) * GROW_STAGGER + GROW_SPAN+ restsAtMs = startMs + (held * last).toLong()+ }++ /**+ * Where letter [charIndex] has got to at [positionMs], written into [into]+ * rather than returned: this runs for every letter of the word on every+ * frame, three times over — dim copy, lit copy and bloom — and a line's+ * worth of short-lived objects per frame is a cost with nothing to show+ * for it.+ *+ * [CharGrowth.rise] comes back in multiples of the ordinary sung-word lift,+ * and [CharGrowth.shift] in ems, so the caller converts once with the font+ * size it is actually drawing at.+ */+ fun sampleInto(charIndex: Int, positionMs: Long, into: CharGrowth) {+ val span = (endMs - startMs).coerceAtLeast(1L).toFloat()+ val elapsed = positionMs - startMs - charIndex * span * GROW_STAGGER+ val phase = (elapsed / (span * GROW_SPAN)).coerceIn(0f, 1f)+ val peakScale = scalePeak[charIndex]+ when {+ phase < GROW_IN -> {+ val t = smooth(phase / GROW_IN)+ into.scale = 1f + (peakScale - 1f) * t+ into.shift = shiftPeak[charIndex] * t+ into.rise = risePeak[charIndex] * t+ into.bloom = bloomPeak[charIndex] * t+ }+ phase < GROW_HOLD -> {+ into.scale = peakScale+ into.shift = shiftPeak[charIndex]+ into.rise = risePeak[charIndex]+ into.bloom = bloomPeak[charIndex]+ }+ phase < GROW_OUT -> {+ val t = smooth((phase - GROW_HOLD) / (GROW_OUT - GROW_HOLD))+ into.scale = peakScale + (1f - peakScale) * t+ into.shift = shiftPeak[charIndex] * (1f - t)+ into.rise = risePeak[charIndex] + (GROW_REST - risePeak[charIndex]) * t+ into.bloom = bloomPeak[charIndex] * (1f - t)+ }+ else -> {+ into.scale = 1f+ into.shift = 0f+ into.rise = GROW_REST+ into.bloom = 0f+ }+ }+ }+}++/** Where one letter of a [GrowingWord] is, filled in by [GrowingWord.sampleInto]. */+class CharGrowth {+ /** Swell, about the letter's own centre. 1 is the letter as laid out. */+ var scale: Float = 1f++ /** Lean away from the middle of the word, in ems. */+ var shift: Float = 0f++ /** Lift, in multiples of the ordinary sung-word rise. */+ var rise: Float = 0f++ /** Bloom, 0..1, at its own peak partway up rather than at the top. */+ var bloom: Float = 0f+}++/** How long a word takes to rise, and to settle back down once it is past. */+private const val RISE_MS = 700f++/** The quickest a word ever rises: a 90 ms syllable snapping up reads as a twitch. */+private const val RISE_MIN_MS = 250f++/**+ * How far up a word goes, as a share of the full lift, from how long it is held.+ *+ * A word sung in [LIFT_QUICK_MS] or less only nudges up by [LIFT_FLOOR]; one+ * held for [LIFT_HELD_MS] or more goes the whole way. Eased between the two, so+ * the words of an ordinary line differ from one another by a little rather than+ * falling into "up" and "not up".+ */+private fun liftHeight(word: SweptWord): Float {+ val held = (word.endMs - word.startMs).toFloat()+ val through = ((held - LIFT_QUICK_MS) / (LIFT_HELD_MS - LIFT_QUICK_MS)).coerceIn(0f, 1f)+ return LIFT_FLOOR + (1f - LIFT_FLOOR) * smooth(through)+}++private const val LIFT_QUICK_MS = 150f+private const val LIFT_HELD_MS = 900f+private const val LIFT_FLOOR = 0.25f++/** Ease in and out of the ends, so the lift has no corners on it. */+private fun smooth(fraction: Float) = fraction * fraction * (3f - 2f * fraction)++/**+ * Whether this word is held long enough, and is short enough, to be animated a+ * letter at a time.+ *+ * The thresholds are steeper for short words than the length alone suggests: a+ * two-letter word held for a second is a held note, whereas a seven-letter one+ * held for the same second is just being sung at an ordinary pace, and only the+ * first of those has anything to show.+ *+ * Scripts whose letters are not laid out side by side independently are left+ * alone — Han, kana and Hangul draw as blocks, and right-to-left scripts join+ * up, so moving one letter of a word would come apart rather than swell. A+ * hyphenated word is really two words and would break at the hyphen.+ */+private fun SweptWord.canGrow(): Boolean {+ val length = text.length+ if (length == 0 || length > GROW_MAX_CHARS) return false+ if ('-' in text || text.any { it.isBlockScript() || it.isJoinedScript() }) return false+ val held = endMs - startMs+ return when {+ length == 1 -> held >= GROW_MIN_SOLO_MS+ length <= 3 -> held >= GROW_MIN_SHORT_MS + (length - 2) * GROW_SHORT_STEP_MS+ length == 4 -> held >= GROW_MIN_FOUR_MS+ else -> held >= GROW_MIN_LONG_MS && held >= length * GROW_MS_PER_CHAR+ }+}++/**+ * How much of the movement is taken back off the later letters of a word.+ *+ * Two reasons to hold back. A long word is a lot of letters to run a wave+ * through, and left flat the tail of it is still swelling well after the singer+ * has moved on. A word held only just long enough to qualify has no room for a+ * wave at all, so the whole thing is damped towards a single swell.+ */+private fun decayRate(length: Int, heldMs: Float): Float {+ val long = length > GROW_DECAY_LONG_CHARS+ val quick = heldMs < GROW_DECAY_QUICK_MS+ if (!long && !quick) return 0f+ var strength = 0f+ if (long) {+ strength += minOf((length - GROW_DECAY_LONG_CHARS) / 5f, 1f) * GROW_DECAY_LONG+ }+ if (quick) {+ val short = maxOf(0f, 1f - (heldMs - GROW_DECAY_QUICK_FLOOR_MS) / 400f)+ strength += short * if (length > 3) GROW_DECAY_QUICK else GROW_DECAY_QUICK_TINY+ }+ return minOf(strength, GROW_DECAY_MAX)+}++private fun Char.isBlockScript(): Boolean =+ this in '一'..'鿿' || this in ''..'ゟ' ||+ this in '゠'..'ヿ' || this in '가'..''++private fun Char.isJoinedScript(): Boolean =+ this in ''..'ࣿ'++/** Longest word worth running a wave through; past this it reads as a ripple. */+private const val GROW_MAX_CHARS = 7++/** How long a word of each length has to be held before it qualifies. */+private const val GROW_MIN_SOLO_MS = 1_100L+private const val GROW_MIN_SHORT_MS = 1_360L+private const val GROW_SHORT_STEP_MS = 140L+private const val GROW_MIN_FOUR_MS = 1_050L+private const val GROW_MIN_LONG_MS = 900L+private const val GROW_MS_PER_CHAR = 200L++private const val GROW_DECAY_LONG_CHARS = 5+private const val GROW_DECAY_QUICK_MS = 1_200f+private const val GROW_DECAY_QUICK_FLOOR_MS = 800f+private const val GROW_DECAY_LONG = 0.4f+private const val GROW_DECAY_QUICK = 0.3f+private const val GROW_DECAY_QUICK_TINY = 0.1f+private const val GROW_DECAY_MAX = 0.7f++/**+ * Each letter starts this far — as a share of the word's own length — after the+ * one before it, so the swell travels rather than pulsing.+ */+private const val GROW_STAGGER = 0.09f++/** The whole move runs half again as long as the word is held. */+private const val GROW_SPAN = 1.5f++/** Up by [GROW_IN], held to [GROW_HOLD], settled by [GROW_OUT]. */+private const val GROW_IN = 0.25f+private const val GROW_HOLD = 0.30f+private const val GROW_OUT = 0.75f++/** Where a letter comes to rest: the same small lift every sung word carries. */+private const val GROW_REST = 1f++/** The window over which a longer hold earns more of the treatment. */+private const val GROW_RAMP_MIN_MS = 400f+private const val GROW_RAMP_MAX_MS = 3_000f++/** Swell every qualifying letter gets, and the range the hold adds on top. */+private const val GROW_BASE_SHORT = 0.05f+private const val GROW_BASE_LONG = 0.04f+private const val GROW_SCALE_RANGE = 0.08f++/** The most any letter swells, which is what [GrowingWord] reads the lift off. */+private const val GROW_SCALE_CEILING = 0.1f++/** Taken back off the swell so it stops a hair short of the ceiling. */+private const val GROW_SCALE_TRIM = 0.98f++/** Lean, as a share of the font size at full swell. */+private const val GROW_SHIFT_EM = 25f / 34f++/** The bloom's floor, and what the hold adds to it. */+private const val GROW_BLOOM_FLOOR = 0.35f+private const val GROW_BLOOM_RANGE = 0.45f+private const val GROW_BLOOM_PACE_MS = 1_500f+private const val GROW_BLOOM_PACE_MAX = 1.1f+private const val GROW_BLOOM_SHORT = 0.85f+private const val GROW_BLOOM_LONG = 1.1f++/** A word held this long lifts as far as it is going to. */+private const val GROW_LIFT_PACE_MS = 2_000f+private const val GROW_LIFT_FLOOR = 0.3fdiff --git a/base/app/src/main/java/com/music/spotui/ui/look/ThinSlider.kt b/base/app/src/main/java/com/music/spotui/ui/look/ThinSlider.ktnew file mode 100644index 00000000..1b5e6c01--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/look/ThinSlider.kt@@ -0,0 +1,236 @@+/*+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,+ * sharedUi/src/jvmSharedMain/kotlin/com/music/bitchord/ui/player/ThinSlider.kt at edc1e6f.+ * Modified for Myspoti, 2026-10.+ *+ * Changes: only the slider and its loading sheen (lines 54-245 and the sheen it draws);+ * the Automix beat pulse, the mix crossfade and the transition window are left out.+ */+package com.music.spotui.ui.look++import androidx.compose.animation.AnimatedVisibility+import androidx.compose.animation.core.FastOutSlowInEasing+import androidx.compose.animation.core.LinearEasing+import androidx.compose.animation.core.RepeatMode+import androidx.compose.animation.core.Spring+import androidx.compose.animation.core.animateDpAsState+import androidx.compose.animation.core.animateFloat+import androidx.compose.animation.core.animateFloatAsState+import androidx.compose.animation.core.infiniteRepeatable+import androidx.compose.animation.core.rememberInfiniteTransition+import androidx.compose.animation.core.spring+import androidx.compose.animation.core.tween+import androidx.compose.animation.fadeIn+import androidx.compose.animation.fadeOut+import androidx.compose.animation.scaleIn+import androidx.compose.foundation.Canvas+import androidx.compose.foundation.gestures.awaitEachGesture+import androidx.compose.foundation.gestures.awaitFirstDown+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.CornerRadius+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.graphics.Brush+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.TransformOrigin+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.input.pointer.positionChanged+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp+import kotlinx.coroutines.delay++/**+ * The Immersive scrubber: a hairline capsule with no thumb knob, which+ * thickens under your finger and settles back when you let go. Material's+ * Slider can't be shaped like this — it always draws a thumb and a tall+ * track — so this is drawn directly.+ */+@Composable+fun ThinSlider(+ value: Float,+ onValueChange: (Float) -> Unit,+ modifier: Modifier = Modifier,+ onValueChangeFinished: (() -> Unit)? = null,+ /**+ * Sends a travelling sheen across the whole bar — played *and* unplayed,+ * the bar's full thickness — for as long as it is true.+ *+ * A wait with no measurable fraction to draw (the song still loading) gets+ * the bar itself rather than a second, indeterminate line beside it: no+ * extra chrome, nothing shifting under it, just motion along the bar,+ * pointing the way the music is going.+ */+ loading: Boolean = false,+ idleHeight: Dp = 7.dp,+ activeHeight: Dp = 12.dp,+ activeColor: Color = Color.White.copy(alpha = 0.92f),+ inactiveColor: Color = Color.White.copy(alpha = 0.26f),+) {+ var dragging by remember { mutableStateOf(false) }+ val height by animateDpAsState(+ targetValue = if (dragging) activeHeight else idleHeight,+ animationSpec = spring(+ dampingRatio = Spring.DampingRatioMediumBouncy,+ stiffness = Spring.StiffnessMediumLow,+ ),+ label = "sliderHeight",+ )+ // The sheen gets a minimum beat even when the wait resolves instantly, so+ // its entry, its sweep and its hand-over to the progress bar always play+ // out as one continuous morph. A flip back to loading during the hold+ // cancels it and the sheen simply stays, so rapid toggling never blinks+ // the bar out mid-morph.+ var shownLoading by remember { mutableStateOf(loading) }+ var sheenStart by remember { mutableStateOf(System.nanoTime()) }+ LaunchedEffect(loading) {+ if (loading) {+ sheenStart = System.nanoTime()+ shownLoading = true+ } else {+ val remaining = LOADING_MIN_MS - (System.nanoTime() - sheenStart) / 1_000_000L+ if (remaining > 0) delay(remaining)+ shownLoading = false+ }+ }+ val sheenVisible = shownLoading+ val fillFactor by animateFloatAsState(+ targetValue = if (sheenVisible) 0f else 1f,+ animationSpec = tween(durationMillis = MORPH_MS, easing = FastOutSlowInEasing),+ label = "fillFactor",+ )++ Box(+ modifier = modifier+ .fillMaxWidth()+ // Generous invisible touch target — the visible bar is only ~7dp.+ .height(activeHeight + 22.dp)+ // One gesture loop for both taps and drags. Two separate detectors+ // — a drag one plus a tap one — meant taps never landed: the drag+ // detector took the pointer and a tap has no drag to report.+ .pointerInput(Unit) {+ awaitEachGesture {+ val down = awaitFirstDown(requireUnconsumed = false)+ dragging = true+ onValueChange((down.position.x / size.width).coerceIn(0f, 1f))++ while (true) {+ val event = awaitPointerEvent()+ val pointer = event.changes.firstOrNull { it.id == down.id } ?: break+ if (!pointer.pressed) {+ pointer.consume()+ break+ }+ if (pointer.positionChanged()) {+ onValueChange((pointer.position.x / size.width).coerceIn(0f, 1f))+ pointer.consume()+ }+ }++ dragging = false+ onValueChangeFinished?.invoke()+ }+ },+ contentAlignment = Alignment.Center,+ ) {+ Canvas(+ Modifier+ .fillMaxWidth()+ .height(height),+ ) {+ val radius = CornerRadius(size.height / 2f)+ drawRoundRect(color = inactiveColor, cornerRadius = radius)+ // Scaled by [fillFactor]: retracted to nothing while the sheen+ // runs (two white signals on one bar would read as progress+ // fighting the wait) and slid back in when the wait ends. The+ // capsule's minimum width rides the same factor, so the nub at+ // zero progress retires with the fill instead of sitting as a+ // dot under the sheen.+ val filled = size.width * value.coerceIn(0f, 1f) * fillFactor+ if (filled > 0f) {+ drawRoundRect(+ color = activeColor,+ size = Size(+ filled.coerceAtLeast(size.height * fillFactor).coerceAtMost(size.width),+ size.height,+ ),+ cornerRadius = radius,+ )+ }+ }+ // Composed only while loading. The infinite animation therefore costs no+ // frames during ordinary playback, and AnimatedVisibility lets it leave gracefully.+ AnimatedVisibility(+ visible = sheenVisible,+ // Grown out of the bar's own left end — where the progress fill+ // begins — instead of slid in from outside the bar. Same duration+ // and curve as the fill's retraction, so the swap reads as one morph.+ enter = fadeIn(tween(durationMillis = MORPH_MS, easing = FastOutSlowInEasing)) ++ scaleIn(+ animationSpec = tween(durationMillis = MORPH_MS, easing = FastOutSlowInEasing),+ initialScale = 0f,+ transformOrigin = TransformOrigin(0f, 0.5f),+ ),+ exit = fadeOut(tween(durationMillis = MORPH_MS, easing = FastOutSlowInEasing)),+ ) {+ LoadingSheen(height = height, color = activeColor)+ }+ }+}++private const val SHEEN_BAND_FRACTION = 0.34f++/** How long the fill takes to retract under the sheen, and to slide back. */+private const val MORPH_MS = 450++/** The least time the sheen stays up once shown. */+private const val LOADING_MIN_MS = 600L++@Composable+private fun LoadingSheen(height: Dp, color: Color) {+ val transition = rememberInfiniteTransition(label = "loadingSheen")+ val phase by transition.animateFloat(+ initialValue = -SHEEN_BAND_FRACTION,+ targetValue = 1f,+ animationSpec = infiniteRepeatable(+ animation = tween(durationMillis = 1000, easing = LinearEasing),+ // Reverses rather than restarting: a restart teleports the band+ // back to the far edge every second, which is a hitch the eye+ // catches each time. Ping-pong has no edge to fall off.+ repeatMode = RepeatMode.Reverse,+ ),+ label = "loadingSheenPhase",+ )+ Canvas(+ Modifier+ .fillMaxWidth()+ .height(height),+ ) {+ val band = size.width * SHEEN_BAND_FRACTION+ val x = phase * size.width+ drawRoundRect(+ brush = Brush.horizontalGradient(+ colorStops = arrayOf(+ 0f to Color.Transparent,+ 0.5f to color,+ 1f to Color.Transparent,+ ),+ startX = x,+ endX = x + band,+ ),+ size = Size(size.width, size.height),+ // The band is clipped to the same capsule the track is drawn+ // with: a plain rect bared square corners wherever the sweep+ // crossed the rounded ends.+ cornerRadius = CornerRadius(size.height / 2f),+ )+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/navigation/MyNavHost.kt b/base/app/src/main/java/com/music/spotui/ui/navigation/MyNavHost.ktindex 090d2b02..c847ca2d 100644--- a/base/app/src/main/java/com/music/spotui/ui/navigation/MyNavHost.kt+++ b/base/app/src/main/java/com/music/spotui/ui/navigation/MyNavHost.kt@@ -45,12 +45,14 @@ import com.music.spotui.ui.screens.ShowScreenimport com.music.spotui.ui.screens.QueueScreenimport com.music.spotui.ui.screens.SearchScreenimport com.music.spotui.ui.viewmodel.PlayerViewModel+import com.music.spotui.ui.immersive.motion.ImmersiveMotion.Pages as IPages@Composablefun MyNavHost(navHostController: NavHostController,bottomBarState: MutableState<Boolean>,- bottomBarPlayerState: MutableState<Boolean>+ bottomBarPlayerState: MutableState<Boolean>,+ modifier: Modifier = Modifier,) {val playerViewModel : PlayerViewModel = viewModel()@@ -62,39 +64,45 @@ fun MyNavHost(val context = LocalContext.currentval startDestination = Routes.Home.route+ // The look (Settings > Display) is read through State objects: the graph builder and the+ // transitions keep the same lambdas, so a switch never rebuilds the graph (or the back stack).+ val immersiveState = androidx.compose.runtime.rememberUpdatedState(isImmersive())+ val reduceState = androidx.compose.runtime.rememberUpdatedState(com.music.spotui.ui.look.rememberReduceMotion())com.music.spotui.ui.components.ArtistChooserHost(navHostController)NavHost(navController = navHostController,startDestination = startDestination,+ modifier = modifier,// Pages: a short shift with a fade-through, tabs fade in, the player and queue rise// from the bottom (see navEnter). The fades put a page in an offscreen layer for// their 0.1-0.2 s: the owner's call, a page change read as a hard block without them.- enterTransition = { navEnter(initialState, targetState) },- exitTransition = { navExit(initialState, targetState) },- popEnterTransition = { navPopEnter(initialState, targetState) },- popExitTransition = { navPopExit(initialState, targetState) },+ // The Immersive look pushes pages like a navigation stack (ImmersiveMotion.Pages).+ enterTransition = { if (immersiveState.value) IPages.enter(reduceState.value)(this) else navEnter(initialState, targetState) },+ exitTransition = { if (immersiveState.value) IPages.exit(reduceState.value)(this) else navExit(initialState, targetState) },+ popEnterTransition = { if (immersiveState.value) IPages.popEnter(reduceState.value)(this) else navPopEnter(initialState, targetState) },+ popExitTransition = { if (immersiveState.value) IPages.popExit(reduceState.value)(this) else navPopExit(initialState, targetState) },){page(Routes.Home.route){LaunchedEffect(playerState) {bottomBarState.value = truebottomBarPlayerState.value = playerState != ""}- HomeScreen(navHostController)+ if (isImmersive()) com.music.spotui.ui.immersive.screens.ImmersiveHomeScreen(navHostController) else HomeScreen(navHostController)}page(Routes.Search.route){LaunchedEffect(playerState) {bottomBarState.value = truebottomBarPlayerState.value = playerState != ""}- SearchScreen(navHostController)+ if (isImmersive()) com.music.spotui.ui.immersive.screens.ImmersiveSearchScreen(navHostController) else SearchScreen(navHostController)}page(Routes.Library.route) {LaunchedEffect(playerState) {bottomBarState.value = truebottomBarPlayerState.value = playerState != ""}- LibraryScreen(navHostController)+ if (isImmersive()) com.music.spotui.ui.immersive.screens.ImmersiveLibraryScreen(navHostController) else LibraryScreen(navHostController)}// Older links to the player route open the player sheet over the page instead.page(Routes.Player.route){@@ -109,7 +117,7 @@ fun MyNavHost(bottomBarState.value = falsebottomBarPlayerState.value = false}- QueueScreen(navHostController)+ if (isImmersive()) com.music.spotui.ui.immersive.pages.ImmersiveQueueScreen(navHostController) else QueueScreen(navHostController)}page(Routes.LocalFiles.route){@@ -117,7 +125,7 @@ fun MyNavHost(bottomBarState.value = truebottomBarPlayerState.value = playerState != ""}- com.music.spotui.ui.screens.LocalFilesScreen(navHostController)+ if (isImmersive()) com.music.spotui.ui.immersive.pages.ImmersiveLocalFilesScreen(navHostController) else com.music.spotui.ui.screens.LocalFilesScreen(navHostController)}page(Routes.Downloads.route){@@ -125,7 +133,7 @@ fun MyNavHost(bottomBarState.value = truebottomBarPlayerState.value = playerState != ""}- com.music.spotui.ui.screens.DownloadsScreen(navHostController)+ if (isImmersive()) com.music.spotui.ui.immersive.pages.ImmersiveDownloadsScreen(navHostController) else com.music.spotui.ui.screens.DownloadsScreen(navHostController)}page(Routes.NewReleases.route) {@@ -133,7 +141,7 @@ fun MyNavHost(bottomBarState.value = truebottomBarPlayerState.value = playerState != ""}- com.music.spotui.ui.screens.NewReleasesScreen(navHostController)+ if (isImmersive()) com.music.spotui.ui.immersive.pages.ImmersiveNewReleasesScreen(navHostController) else com.music.spotui.ui.screens.NewReleasesScreen(navHostController)}page(Routes.Episodes.route) {@@ -141,7 +149,7 @@ fun MyNavHost(bottomBarState.value = truebottomBarPlayerState.value = playerState != ""}- com.music.spotui.ui.screens.EpisodesScreen(navHostController)+ if (isImmersive()) com.music.spotui.ui.immersive.pages.ImmersiveEpisodesScreen(navHostController) else com.music.spotui.ui.screens.EpisodesScreen(navHostController)}page(Routes.Recap.route) {@@ -149,7 +157,7 @@ fun MyNavHost(bottomBarState.value = truebottomBarPlayerState.value = playerState != ""}- com.music.spotui.ui.screens.RecapScreen(navHostController)+ if (isImmersive()) com.music.spotui.ui.immersive.pages.ImmersiveRecapScreen(navHostController) else com.music.spotui.ui.screens.RecapScreen(navHostController)}page(Routes.Friends.route) {@@ -157,7 +165,7 @@ fun MyNavHost(bottomBarState.value = truebottomBarPlayerState.value = playerState != ""}- com.music.spotui.ui.screens.FriendActivityScreen(navHostController)+ if (isImmersive()) com.music.spotui.ui.immersive.pages.ImmersiveFriendsScreen(navHostController) else com.music.spotui.ui.screens.FriendActivityScreen(navHostController)}// Spotify's own list for the account (every device), not this phone's counter.@@ -166,7 +174,7 @@ fun MyNavHost(bottomBarState.value = truebottomBarPlayerState.value = playerState != ""}- com.music.spotui.ui.screens.RecentlyPlayedScreen(navHostController)+ if (isImmersive()) com.music.spotui.ui.immersive.pages.ImmersiveRecentlyPlayedScreen(navHostController) else com.music.spotui.ui.screens.RecentlyPlayedScreen(navHostController)}page(Routes.Liked.route){@@ -174,7 +182,7 @@ fun MyNavHost(bottomBarState.value = truebottomBarPlayerState.value = playerState != ""}- ContextScreen(navHostController, type = "liked", id = "")+ if (isImmersive()) com.music.spotui.ui.immersive.screens.ImmersiveContextScreen(navHostController, type = "liked", id = "") else ContextScreen(navHostController, type = "liked", id = "")}// Settings: sound quality, downloads, data, display, language.@@ -183,7 +191,7 @@ fun MyNavHost(bottomBarState.value = truebottomBarPlayerState.value = playerState != ""}- com.music.spotui.ui.screens.SettingsScreen(navHostController)+ if (isImmersive()) com.music.spotui.ui.immersive.pages.ImmersiveSettingsScreen(navHostController) else com.music.spotui.ui.screens.SettingsScreen(navHostController)}// Extensions: the Store and Installed tabs; one installed extension's page; a repository's extension before install.@@ -232,7 +240,7 @@ fun MyNavHost(}val genre = navBackStackEntry.arguments?.getString("genre").orEmpty()val title = navBackStackEntry.arguments?.getString("title").orEmpty()- CategoryScreen(navHostController, genre = genre, title = title.ifBlank { genre })+ if (isImmersive()) com.music.spotui.ui.immersive.screens.ImmersiveCategoryScreen(navHostController, genre = genre, title = title.ifBlank { genre }) else CategoryScreen(navHostController, genre = genre, title = title.ifBlank { genre })}page(@@ -267,7 +275,7 @@ fun MyNavHost(}val pId = navBackStackEntry.arguments?.getString("pId")val name = navBackStackEntry.arguments?.getString("name").orEmpty()- pId?.let { ContextScreen(navHostController, type = "playlist", id = it) }+ pId?.let { if (isImmersive()) com.music.spotui.ui.immersive.screens.ImmersiveContextScreen(navHostController, type = "playlist", id = it) else ContextScreen(navHostController, type = "playlist", id = it) }}page(@@ -280,7 +288,7 @@ fun MyNavHost(}val uId = navBackStackEntry.arguments?.getString("uId")val name = navBackStackEntry.arguments?.getString("name").orEmpty()- uId?.let { com.music.spotui.ui.screens.ProfileScreen(navHostController, userId = it, userName = name) }+ uId?.let { if (isImmersive()) com.music.spotui.ui.immersive.people.ImmersiveProfileScreen(navHostController, userId = it, userName = name) else com.music.spotui.ui.screens.ProfileScreen(navHostController, userId = it, userName = name) }}page("$LIKED_BY_ARTIST_ROUTE/{key}") { navBackStackEntry ->@@ -288,7 +296,7 @@ fun MyNavHost(bottomBarState.value = truebottomBarPlayerState.value = playerState != ""}- navBackStackEntry.arguments?.getString("key")?.let { ContextScreen(navHostController, type = "liked-artist", id = it) }+ navBackStackEntry.arguments?.getString("key")?.let { if (isImmersive()) com.music.spotui.ui.immersive.screens.ImmersiveContextScreen(navHostController, type = "liked-artist", id = it) else ContextScreen(navHostController, type = "liked-artist", id = it) }}page(@@ -300,7 +308,7 @@ fun MyNavHost(}val uId = navBackStackEntry.arguments?.getString("uId")val mode = navBackStackEntry.arguments?.getString("mode")- uId?.let { com.music.spotui.ui.screens.FollowListScreen(navHostController, userId = it, followers = mode == "followers") }+ uId?.let { if (isImmersive()) com.music.spotui.ui.immersive.people.ImmersiveFollowListScreen(navHostController, userId = it, followers = mode == "followers") else com.music.spotui.ui.screens.FollowListScreen(navHostController, userId = it, followers = mode == "followers") }}page(@@ -313,7 +321,7 @@ fun MyNavHost(}val sId = navBackStackEntry.arguments?.getString("sId")val name = navBackStackEntry.arguments?.getString("name").orEmpty()- sId?.let { ShowScreen(navHostController, showId = it, showName = name) }+ sId?.let { if (isImmersive()) com.music.spotui.ui.immersive.podcast.ImmersiveShowScreen(navHostController, showId = it, showName = name) else ShowScreen(navHostController, showId = it, showName = name) }}page(@@ -326,7 +334,7 @@ fun MyNavHost(}val eId = navBackStackEntry.arguments?.getString("eId")val name = navBackStackEntry.arguments?.getString("name").orEmpty()- eId?.let { com.music.spotui.ui.screens.EpisodeScreen(navHostController, episodeId = it, fallbackName = name) }+ eId?.let { if (isImmersive()) com.music.spotui.ui.immersive.pages.ImmersiveEpisodeScreen(navHostController, episodeId = it, fallbackName = name) else com.music.spotui.ui.screens.EpisodeScreen(navHostController, episodeId = it, fallbackName = name) }}page(@@ -360,7 +368,7 @@ fun MyNavHost(}val aId = navBackStackEntry.arguments?.getString("aString")val artistId = navBackStackEntry.arguments?.getString("artistId").orEmpty()- aId?.let { ArtistReleasesScreen(navHostController, it, artistId) }+ aId?.let { if (isImmersive()) com.music.spotui.ui.immersive.screens.ImmersiveArtistReleasesScreen(navHostController, it, artistId) else ArtistReleasesScreen(navHostController, it, artistId) }}page(@@ -377,7 +385,7 @@ fun MyNavHost(val artistId = navBackStackEntry.arguments?.getString("artistId").orEmpty()/* We check if it's not null */aId?.let { aid->- ArtistScreen(navHostController, aid, artistId)+ if (isImmersive()) com.music.spotui.ui.immersive.screens.ImmersiveArtistScreen(navHostController, aid, artistId) else ArtistScreen(navHostController, aid, artistId)}}}@@ -454,7 +462,8 @@ private fun NavGraphBuilder.page(}}androidx.compose.runtime.CompositionLocalProvider(LocalPageSettled provides settled) {- Box(Modifier.fillMaxSize().background(AppBackground)) { scope.content(entry) }+ // Immersive look: every page (Classic fallbacks too) sits on its black page colour.+ Box(Modifier.fillMaxSize().background(if (isImmersive()) com.music.spotui.ui.immersive.Immersive.Page else AppBackground)) { scope.content(entry) }}}@@ -465,3 +474,8 @@ private fun NavGraphBuilder.page(val LocalPageSettled = androidx.compose.runtime.staticCompositionLocalOf<androidx.compose.runtime.State<Boolean>> {androidx.compose.runtime.mutableStateOf(true)}++/** The Immersive look is on (Settings > Display, or the onboarding's look step). */+@Composable+internal fun isImmersive(): Boolean =+ com.music.spotui.ui.look.LocalLook.current == com.music.spotui.data.preferences.Look.IMMERSIVEdiff --git a/base/app/src/main/java/com/music/spotui/ui/screens/AlbumByIdScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/AlbumByIdScreen.ktindex 8131c59a..4344640c 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/AlbumByIdScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/AlbumByIdScreen.kt@@ -32,7 +32,8 @@ fun AlbumByIdScreen(navController: NavController, name: String, artist: String,}val albumId = resolvedwhen {- albumId != null -> ContextScreen(navController, type = "album", id = albumId)+ albumId != null -> if (com.music.spotui.ui.navigation.isImmersive()) com.music.spotui.ui.immersive.screens.ImmersiveContextScreen(navController, type = "album", id = albumId)+ else ContextScreen(navController, type = "album", id = albumId)failed -> Text(stringResource(R.string.album_not_found), color = AppText)else -> Loader(SkeletonKind.Header)}diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/ContextScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/ContextScreen.ktindex b4ed3433..d2e278aa 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/ContextScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/ContextScreen.kt@@ -1136,7 +1136,7 @@ private fun RecommendedRow(song: SongsModel, isCurrent: Boolean, onPlay: () -> U/** The people of a collaborative playlist: owner first, then collaborators; a tap opens a profile. */@OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)@Composable-private fun MembersSheet(+internal fun MembersSheet(members: List<app.myspoti.api.PlaylistMember>,navController: NavController,ownPlaylist: Boolean,@@ -1147,7 +1147,7 @@ private fun MembersSheet(onLeave: () -> Unit,onDismiss: () -> Unit,) {- androidx.compose.material3.ModalBottomSheet(onDismissRequest = onDismiss, containerColor = tone(0xFF282828)) {+ com.music.spotui.ui.components.LookSheet(onDismissRequest = onDismiss, containerColor = tone(0xFF282828)) {Column(Modifier.navigationBarsPadding().padding(bottom = 12.dp)) {Text(stringResource(R.string.playlist_members_title), color = AppText, fontSize = 18.sp, fontWeight = FontWeight.Bold,modifier = Modifier.padding(20.dp, 0.dp, 20.dp, 12.dp))diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/DiscoverScreens.kt b/base/app/src/main/java/com/music/spotui/ui/screens/DiscoverScreens.ktindex 81eb01ff..de99194e 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/DiscoverScreens.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/DiscoverScreens.kt@@ -90,7 +90,7 @@ private fun Loading() = com.music.spotui.ui.components.SkeletonList(count = 7)private fun SectionTitle(text: String) =Text(text, color = AppText, fontSize = 20.sp, fontWeight = FontWeight.Bold, modifier = Modifier.padding(16.dp, 18.dp, 16.dp, 8.dp))-private data class ReleaseTile(val id: String, val name: String, val artists: String, val cover: String, val detail: String)+internal data class ReleaseTile(val id: String, val name: String, val artists: String, val cover: String, val detail: String)/** "New releases": what the followed artists just released, then the latest albums Spotify features. */@OptIn(ExperimentalGlideComposeApi::class)diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/ExtensionParts.kt b/base/app/src/main/java/com/music/spotui/ui/screens/ExtensionParts.ktindex d16f19cd..679f2fce 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/ExtensionParts.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/ExtensionParts.kt@@ -17,6 +17,7 @@ import androidx.compose.foundation.layout.ExperimentalLayoutApiimport androidx.compose.foundation.layout.FlowRowimport androidx.compose.foundation.layout.PaddingValuesimport androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacerimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.height@@ -460,6 +461,14 @@ internal fun Dot(color: Color, size: Dp = 10.dp) =@Composableinternal fun Page(titleRes: Int?, navController: NavController, title: String? = null, top: @Composable () -> Unit = {}, content: @Composable () -> Unit) {+ // Immersive look: the shared page scaffold (large title into the glass bar) around the same content.+ if (com.music.spotui.ui.navigation.isImmersive()) {+ com.music.spotui.ui.immersive.pages.ImmersivePage(title = title ?: stringResource(titleRes!!), onBack = { navController.popBackStack() }) {+ item(key = "ext:top") { top() }+ item(key = "ext:content") { Column(Modifier.fillMaxWidth()) { content() } }+ }+ return+ }Column(Modifier.fillMaxSize().background(AppBackground).statusBarsPadding()) {Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(4.dp)) {IconButton(onClick = { navController.popBackStack() }) {@@ -477,15 +486,30 @@ internal fun ExtSection(title: Int) = ExtSection(stringResource(title))@Composableinternal fun ExtSection(title: String) {+ if (com.music.spotui.ui.navigation.isImmersive()) {+ Text(title.uppercase(), style = com.music.spotui.ui.immersive.Immersive.Caption,+ modifier = Modifier.padding(start = 36.dp, end = 20.dp, top = 18.dp, bottom = 6.dp))+ return+ }Text(title.uppercase(), color = AppAccent, fontSize = 12.sp, fontWeight = FontWeight.Bold,letterSpacing = 1.sp, modifier = Modifier.padding(start = 20.dp, end = 20.dp, top = 16.dp, bottom = 8.dp))}@Composable-internal fun ExtDivider() = HorizontalDivider(color = tone(0xFF2A2A2A), modifier = Modifier.padding(top = 8.dp))+internal fun ExtDivider() {+ if (com.music.spotui.ui.navigation.isImmersive()) Spacer(Modifier.height(8.dp))+ else HorizontalDivider(color = tone(0xFF2A2A2A), modifier = Modifier.padding(top = 8.dp))+}@Composableinternal fun SwitchRow(label: String, detail: String, checked: Boolean, detailColor: Color = AppMuted, onChecked: (Boolean) -> Unit) {+ if (com.music.spotui.ui.navigation.isImmersive()) {+ Box(Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 6.dp).clip(com.music.spotui.ui.immersive.Immersive.Card)+ .background(com.music.spotui.ui.immersive.Immersive.Raised)) {+ com.music.spotui.ui.immersive.pages.ImmersiveSwitchRow(label, checked, onChecked, detail = detail, detailColor = detailColor)+ }+ return+ }Row(verticalAlignment = Alignment.CenterVertically,modifier = Modifier.fillMaxWidth().heightIn(min = 64.dp)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.ktindex 8573b6c0..8222d9b6 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@@ -214,6 +214,15 @@ fun ExtensionsScreen(navController: NavController) {/** "Store" and "Installed", the latter with the number of updates waiting. */@Composableprivate fun Tabs(selected: Int, updates: Int, onSelect: (Int) -> Unit) {+ if (com.music.spotui.ui.navigation.isImmersive()) {+ val installed = stringResource(R.string.extensions_installed)+ com.music.spotui.ui.immersive.pages.ImmersiveSegmentedControl(+ options = listOf(stringResource(R.string.extensions_tab_store), if (updates > 0) "$installed ($updates)" else installed),+ selectedIndex = selected, onSelect = onSelect,+ modifier = Modifier.padding(horizontal = 20.dp, vertical = 4.dp),+ )+ return+ }Row(Modifier.fillMaxWidth().padding(horizontal = 12.dp)) {listOf(R.string.extensions_tab_store, R.string.extensions_installed).forEachIndexed { i, label ->Column(@@ -238,6 +247,14 @@ private fun Tabs(selected: Int, updates: Int, onSelect: (Int) -> Unit) {@Composableprivate fun SearchField(query: String, onChange: (String) -> Unit) {+ if (com.music.spotui.ui.navigation.isImmersive()) {+ com.music.spotui.ui.immersive.components.ImmersiveSearchField(+ query = query, onQueryChange = onChange, onSubmit = {},+ placeholder = stringResource(R.string.extensions_search),+ modifier = Modifier.padding(horizontal = 20.dp, vertical = 8.dp),+ )+ return+ }OutlinedTextField(value = query, onValueChange = onChange, singleLine = true,placeholder = { Text(stringResource(R.string.extensions_search), color = AppMuted) },@@ -256,11 +273,14 @@ private fun SearchField(query: String, onChange: (String) -> Unit) {@Composableprivate fun CategoryChips(categories: List<Category>, selected: Category?, onSelect: (Category?) -> Unit) {if (categories.isEmpty()) return+ val immersive = com.music.spotui.ui.navigation.isImmersive()+ val chipOn = if (immersive) com.music.spotui.ui.immersive.Immersive.Accent else AppAccent+ val chipOff = if (immersive) com.music.spotui.ui.immersive.Immersive.Raised else tone(0xFF2A2A2A)Row(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).padding(horizontal = 16.dp, vertical = 10.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {(listOf<Category?>(null) + categories).forEach { c ->val on = c == selected- Text(stringResource(categoryLabel(c)), color = if (on) Color.Black else AppText, fontSize = 13.sp, maxLines = 1,- modifier = Modifier.clip(RoundedCornerShape(50)).background(if (on) AppAccent else tone(0xFF2A2A2A))+ Text(stringResource(categoryLabel(c)), color = if (on) (if (immersive) Color.White else Color.Black) else AppText, fontSize = 13.sp, maxLines = 1,+ modifier = Modifier.clip(RoundedCornerShape(50)).background(if (on) chipOn else chipOff).clickable { onSelect(if (on) null else c) }.padding(horizontal = 14.dp, vertical = 7.dp))}}@@ -460,6 +480,14 @@ private fun InstalledRow(e: InstalledExtension, error: String?, status: app.mysp@Composableprivate fun InstallButtons(onRepo: (() -> Unit)?, onFile: () -> Unit, onUrl: () -> Unit) {+ if (com.music.spotui.ui.navigation.isImmersive()) {+ Row(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).padding(horizontal = 20.dp, vertical = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ onRepo?.let { com.music.spotui.ui.immersive.components.ImmersiveButton(stringResource(R.string.extensions_repository_add), it) }+ com.music.spotui.ui.immersive.components.ImmersiveButton(stringResource(R.string.extensions_install_file), onFile)+ com.music.spotui.ui.immersive.components.ImmersiveButton(stringResource(R.string.extensions_install_url), onUrl)+ }+ return+ }Row(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).padding(horizontal = 16.dp, vertical = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {val border = BorderStroke(1.dp, AppMuted.copy(alpha = 0.5f))onRepo?.let { OutlinedButton(onClick = it, border = border) { Text(stringResource(R.string.extensions_repository_add), color = AppText, fontSize = 13.sp) } }diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/LibraryExtras.kt b/base/app/src/main/java/com/music/spotui/ui/screens/LibraryExtras.ktindex c61c7bb9..5258af76 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/LibraryExtras.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/LibraryExtras.kt@@ -174,7 +174,7 @@ fun LibraryCreateSheet(navController: NavController, onDismiss: () -> Unit, onLinavController.navigate(localPlaylistRoute(p.id))}"blend" -> BlendSheet(navController, onDismiss)- else -> ModalBottomSheet(onDismissRequest = onDismiss, containerColor = SheetColor) {+ else -> com.music.spotui.ui.components.LookSheet(onDismissRequest = onDismiss, containerColor = SheetColor) {Column(Modifier.navigationBarsPadding().padding(bottom = 12.dp)) {SheetRow(Icons.AutoMirrored.Filled.PlaylistAdd, stringResource(R.string.assisted_curation_search_playlist)) { asking = "playlist" }SheetRow(Icons.Outlined.Group, stringResource(R.string.blend_title), stringResource(R.string.blend_detail)) { asking = "blend" }@@ -220,7 +220,7 @@ private fun BlendSheet(navController: NavController, onDismiss: () -> Unit) {if (opened != null) { onDismiss(); navController.navigate(playlistRoute(opened.substringAfterLast(':'))) }}}- ModalBottomSheet(onDismissRequest = onDismiss, containerColor = SheetColor) {+ com.music.spotui.ui.components.LookSheet(onDismissRequest = onDismiss, containerColor = SheetColor) {Column(Modifier.navigationBarsPadding().padding(bottom = 12.dp)) {Text(stringResource(R.string.blend_title), color = AppText, fontSize = 18.sp, fontWeight = FontWeight.Bold,modifier = Modifier.padding(20.dp, 0.dp, 20.dp, 8.dp))@@ -269,7 +269,7 @@ fun BlendInviteSheet(link: com.music.spotui.data.api.InviteLinks.BlendLink, navC}.onFailure { failed = true }}- ModalBottomSheet(onDismissRequest = onDismiss, containerColor = SheetColor) {+ com.music.spotui.ui.components.LookSheet(onDismissRequest = onDismiss, containerColor = SheetColor) {Column(horizontalAlignment = Alignment.CenterHorizontally,modifier = Modifier.fillMaxWidth().navigationBarsPadding().padding(24.dp, 0.dp, 24.dp, 20.dp),@@ -376,7 +376,7 @@ fun FolderScreen(navController: NavController, uri: String, initialName: String)}// A change just written: the folder is read again once Spotify's list has had time to catch up.LaunchedEffect(uri) { com.music.spotui.data.api.LibraryEdits.reloads.collect { generation++ } }- if (menu) ModalBottomSheet(onDismissRequest = { menu = false }, containerColor = SheetColor) {+ if (menu) com.music.spotui.ui.components.LookSheet(onDismissRequest = { menu = false }, containerColor = SheetColor) {Column(Modifier.navigationBarsPadding().padding(bottom = 12.dp)) {SheetRow(Icons.AutoMirrored.Filled.PlaylistAdd, stringResource(R.string.add_to_playlist_new_playlist_button_text)) { menu = false; newPlaylist = true }SheetRow(Icons.Outlined.Edit, stringResource(R.string.context_menu_rename_folder)) { menu = false; renaming = true }@@ -472,7 +472,7 @@ fun LocalPlaylistScreen(navController: NavController, id: String) {LaunchedEffect(Unit) { navController.navigateUp() }return}- if (menu) ModalBottomSheet(onDismissRequest = { menu = false }, containerColor = SheetColor) {+ if (menu) com.music.spotui.ui.components.LookSheet(onDismissRequest = { menu = false }, containerColor = SheetColor) {Column(Modifier.navigationBarsPadding().padding(bottom = 12.dp)) {SheetRow(Icons.Outlined.Edit, stringResource(R.string.local_rename)) { menu = false; renaming = true }SheetRow(Icons.Outlined.Delete, stringResource(R.string.local_delete_playlist)) {@@ -536,7 +536,7 @@ fun AddLocalToPlaylistSheet(track: LocalTrack, onDismiss: () -> Unit) {}return}- ModalBottomSheet(onDismissRequest = onDismiss, containerColor = SheetColor) {+ com.music.spotui.ui.components.LookSheet(onDismissRequest = onDismiss, containerColor = SheetColor) {LazyColumn(Modifier.navigationBarsPadding().heightIn(max = 560.dp)) {item {Text(stringResource(R.string.context_menu_add_to_playlist), color = AppText, fontSize = 20.sp, fontWeight = FontWeight.Bold,@@ -602,7 +602,7 @@ fun LibraryItemSheet(entry: LibraryEntry, onDismiss: () -> Unit, onChanged: () -onDismiss()}val api = app.myspoti.host.android.MyspotiRuntime.api- ModalBottomSheet(onDismissRequest = onDismiss, containerColor = SheetColor) {+ com.music.spotui.ui.components.LookSheet(onDismissRequest = onDismiss, containerColor = SheetColor) {Column(Modifier.navigationBarsPadding().padding(bottom = 12.dp)) {Text(entry.name, color = AppText, fontSize = 18.sp, fontWeight = FontWeight.Bold, maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,modifier = Modifier.padding(20.dp, 0.dp, 20.dp, 8.dp))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.ktindex 3815cd62..6b51ecca 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@@ -846,7 +846,7 @@ private fun AccountSheet() {val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)val context = LocalContext.current- ModalBottomSheet(+ com.music.spotui.ui.components.LookSheet(onDismissRequest = onDismiss,sheetState = sheetState,containerColor = tone(0xFF1A1A1A),@@ -919,7 +919,7 @@ private fun sortLabel(sort: LibraryOrder.Sort) = when (sort) {@OptIn(ExperimentalMaterial3Api::class)@Composableprivate fun LibrarySortSheet(onDismiss: () -> Unit) {- ModalBottomSheet(onDismissRequest = onDismiss, containerColor = tone(0xFF282828)) {+ com.music.spotui.ui.components.LookSheet(onDismissRequest = onDismiss, containerColor = tone(0xFF282828)) {Column(Modifier.navigationBarsPadding().padding(bottom = 16.dp)) {Text(stringResource(R.string.filter_and_sort_sort_section_title), color = AppText, fontSize = 18.sp,fontWeight = FontWeight.Bold, modifier = Modifier.padding(horizontal = 20.dp, vertical = 8.dp))diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/LocalFilesScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/LocalFilesScreen.ktindex c4016dba..847e4167 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/LocalFilesScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/LocalFilesScreen.kt@@ -222,12 +222,12 @@ private fun EmptyState(title: String, subtitle: String, button: String?, onClick/** The phone's music folders, each shown in Local Files or left out (WhatsApp audio…). */@OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)@Composable-private fun LocalFoldersSheet(onChanged: () -> Unit, onDismiss: () -> Unit) {+internal fun LocalFoldersSheet(onChanged: () -> Unit, onDismiss: () -> Unit) {val context = LocalContext.currentvar folders by remember { mutableStateOf<List<Pair<String, Int>>>(emptyList()) }var version by remember { mutableStateOf(0) }LaunchedEffect(Unit) { folders = LocalMusic.folders(context) }- androidx.compose.material3.ModalBottomSheet(onDismissRequest = onDismiss, containerColor = tone(0xFF282828)) {+ com.music.spotui.ui.components.LookSheet(onDismissRequest = onDismiss, containerColor = tone(0xFF282828)) {Column(Modifier.navigationBarsPadding().padding(bottom = 16.dp)) {Text(stringResource(R.string.local_folders_title), color = AppText, fontSize = 18.sp, fontWeight = FontWeight.Bold,modifier = Modifier.padding(horizontal = 20.dp))diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/PlayerScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/PlayerScreen.ktindex eb28ddf0..f8ea3ee6 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/PlayerScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/PlayerScreen.kt@@ -550,7 +550,7 @@ fun PlayerScreen(navController: NavController) {val grow = 1f + (1f - coverAlpha) * 0.06fscaleX = grow; scaleY = grow},- model = cover,+ model = app.myspoti.host.android.Covers.large(cover),contentScale = ContentScale.Crop,contentDescription = "")}diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.ktindex f1d98816..88e55d36 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt@@ -185,6 +185,25 @@ fun SettingsScreen(navController: NavController) {onChecked = { com.music.spotui.data.preferences.SolidNavBar.set(ctx, it) },)AccentRow()+ LookRow()+ // The Immersive look's glass; nothing to switch in Classic.+ if (com.music.spotui.data.preferences.LookPref.look == com.music.spotui.data.preferences.Look.IMMERSIVE) {+ val glass = com.music.spotui.ui.immersive.shell.liquidGlassAvailability()+ OptionRow(+ label = stringResource(R.string.settings_liquid_glass_title),+ detail = stringResource(+ when (glass) {+ com.music.spotui.ui.immersive.shell.LiquidGlassAvailability.UNSUPPORTED -> R.string.settings_liquid_glass_unsupported+ com.music.spotui.ui.immersive.shell.LiquidGlassAvailability.REDUCED -> R.string.settings_liquid_glass_reduced+ com.music.spotui.ui.immersive.shell.LiquidGlassAvailability.AVAILABLE -> R.string.settings_liquid_glass_detail+ },+ ),+ checked = com.music.spotui.data.preferences.LiquidGlassPref.on &&+ glass != com.music.spotui.ui.immersive.shell.LiquidGlassAvailability.UNSUPPORTED,+ enabled = glass != com.music.spotui.ui.immersive.shell.LiquidGlassAvailability.UNSUPPORTED,+ onChecked = { com.music.spotui.data.preferences.LiquidGlassPref.set(ctx, it) },+ )+ }OrientationRow()LanguageRow()Divider()@@ -273,6 +292,32 @@ private fun Section(title: Int) {@Composableprivate fun Divider() = HorizontalDivider(color = tone(0xFF2A2A2A), modifier = Modifier.padding(top = 8.dp))+/** Classic or Immersive: the choice made in the onboarding, changeable here. */+@Composable+private fun LookRow() {+ val ctx = androidx.compose.ui.platform.LocalContext.current+ val current = com.music.spotui.data.preferences.LookPref.look+ Column(Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 10.dp)) {+ Text(stringResource(R.string.settings_look_title), color = AppText, fontSize = 16.sp)+ for (l in com.music.spotui.data.preferences.Look.entries) {+ val classic = l == com.music.spotui.data.preferences.Look.CLASSIC+ Row(+ verticalAlignment = Alignment.CenterVertically,+ modifier = Modifier.fillMaxWidth()+ .semantics { role = Role.RadioButton }+ .clickable { com.music.spotui.data.preferences.LookPref.set(ctx, l) }+ .padding(vertical = 8.dp),+ ) {+ androidx.compose.material3.RadioButton(selected = current == l, onClick = null)+ Column(Modifier.padding(start = 12.dp)) {+ Text(stringResource(if (classic) R.string.look_classic else R.string.look_immersive), color = AppText, fontSize = 15.sp)+ Text(stringResource(if (classic) R.string.look_classic_detail else R.string.look_immersive_detail), color = AppMuted, fontSize = 12.sp)+ }+ }+ }+ }+}+/** The app's accent colour, for everyone (the same palette the supporter sheet uses). */@Composableprivate fun AccentRow() {@@ -497,7 +542,7 @@ private fun CheckUpdateRow() {* if the provider refuses the path (external storage absent), the report's own path is shared* instead, so the tester still has something to send.*/-private fun shareDiagnosticReport(context: android.content.Context, file: java.io.File) {+internal fun shareDiagnosticReport(context: android.content.Context, file: java.io.File) {val send = android.content.Intent(android.content.Intent.ACTION_SEND).apply {type = "text/plain"putExtra(android.content.Intent.EXTRA_SUBJECT, "Myspoti diagnostic report")diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/SetupScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/SetupScreen.ktindex fecfd15c..7eb4e38d 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/SetupScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/SetupScreen.kt@@ -77,8 +77,9 @@ import com.music.spotui.ui.theme.AppBackground*/object Setup {private const val KEY = "SetupDone"- /** The permissions step, or the sound quality one (new in 2.0: shown once after the update too). */- fun needed(context: Context) = !permissionsDone(context) || !com.music.spotui.data.preferences.isQualityChosen(context)+ /** The permissions step, the sound quality one or the look one (each new step is shown once after the update too). */+ fun needed(context: Context) = !permissionsDone(context) || !com.music.spotui.data.preferences.isQualityChosen(context) ||+ !com.music.spotui.data.preferences.LookPref.isChosen(context)fun permissionsDone(context: Context) = context.getSharedPreferences("myspoti_prefs", Context.MODE_PRIVATE).getBoolean(KEY, false)fun done(context: Context) = context.getSharedPreferences("myspoti_prefs", Context.MODE_PRIVATE).edit().putBoolean(KEY, true).apply()}@@ -89,28 +90,40 @@ private fun granted(context: Context, permission: String) =@Composablefun SetupScreen(onDone: () -> Unit) {val context = LocalContext.current- // First the sound quality, then the permissions (skipped when done before an update).- var qualityStep by remember { mutableStateOf(!com.music.spotui.data.preferences.isQualityChosen(context)) }- // Two steps to go through: dots say where the user is.- val steps = remember { if (qualityStep && !Setup.permissionsDone(context)) 2 else 1 }+ // First the sound quality, then the look, then the permissions (each skipped when done before an update).+ val needQuality = remember { !com.music.spotui.data.preferences.isQualityChosen(context) }+ val needLook = remember { !com.music.spotui.data.preferences.LookPref.isChosen(context) }+ val needPerms = remember { !Setup.permissionsDone(context) }+ val order = remember { listOfNotNull(0.takeIf { needQuality }, 1.takeIf { needLook }, 2.takeIf { needPerms }).ifEmpty { listOf(2) } }+ var index by remember { mutableIntStateOf(0) }+ val steps = order.size+ fun next() { if (index + 1 < order.size) index++ else onDone() }Box(Modifier.fillMaxSize().background(AppBackground)) {Glow(Modifier.fillMaxSize(), alpha = 0.16f)Column(Modifier.fillMaxSize().statusBarsPadding().navigationBarsPadding()) {- if (steps == 2) StepDots(current = if (qualityStep) 0 else 1, Modifier.padding(start = 20.dp, top = 16.dp))+ // Several steps to go through: dots say where the user is.+ if (steps > 1) StepDots(count = steps, current = index, Modifier.padding(start = 20.dp, top = 16.dp))// One step slides away to the left as the next comes in from the right.AnimatedContent(- targetState = qualityStep,+ targetState = index,transitionSpec = {(slideInHorizontally(tween(420, easing = FastOutSlowInEasing)) { it / 2 } + fadeIn(tween(420))) togetherWith(slideOutHorizontally(tween(420, easing = FastOutSlowInEasing)) { -it / 3 } + fadeOut(tween(250)))},label = "setupStep",modifier = Modifier.weight(1f),- ) { quality ->- if (quality) QualityStep(onNext = {- com.music.spotui.data.preferences.setQualityChosen(context)- if (Setup.permissionsDone(context)) onDone() else qualityStep = false- }) else PermissionsStep(onDone)+ ) { i ->+ when (order[i]) {+ 0 -> QualityStep(onNext = {+ com.music.spotui.data.preferences.setQualityChosen(context)+ next()+ })+ 1 -> com.music.spotui.ui.look.LookStep(onNext = {+ com.music.spotui.data.preferences.LookPref.setChosen(context)+ next()+ })+ else -> PermissionsStep(onDone)+ }}}}@@ -118,9 +131,9 @@ fun SetupScreen(onDone: () -> Unit) {/** Where the user is in the steps: the current one a longer green dash. */@Composable-private fun StepDots(current: Int, modifier: Modifier = Modifier) {+private fun StepDots(count: Int, current: Int, modifier: Modifier = Modifier) {Row(horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = modifier) {- for (i in 0..1) {+ for (i in 0 until count) {val w by animateDpAsState(if (i == current) 22.dp else 8.dp, tween(350), label = "dot")val c by animateColorAsState(if (i == current) Color(0xFF1DB954) else AppText.copy(alpha = 0.25f), tween(350), label = "dotColor")Box(Modifier.height(6.dp).width(w).clip(RoundedCornerShape(50)).background(c))diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/StatsScreens.kt b/base/app/src/main/java/com/music/spotui/ui/screens/StatsScreens.ktindex ac54efa9..234484e4 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/StatsScreens.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/StatsScreens.kt@@ -77,7 +77,7 @@ import kotlinx.coroutines.withContextprivate val StatsSubtle: Color get() = AppMuted-private val rangeLabels = listOf(+internal val rangeLabels = listOf(TimeRange.SHORT_TERM to R.string.stats_range_short,TimeRange.MEDIUM_TERM to R.string.stats_range_medium,TimeRange.LONG_TERM to R.string.stats_range_long,diff --git a/base/app/src/main/res/font/inter.ttf b/base/app/src/main/res/font/inter.ttfnew file mode 100644index 00000000..1a4c6262Binary files /dev/null and b/base/app/src/main/res/font/inter.ttf differdiff --git a/base/app/src/main/res/values-fr/immersive_detail_strings.xml b/base/app/src/main/res/values-fr/immersive_detail_strings.xmlnew file mode 100644index 00000000..0de30e56--- /dev/null+++ b/base/app/src/main/res/values-fr/immersive_detail_strings.xml@@ -0,0 +1,15 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Textes des pages album, playlist et artiste du look Immersive (français). -->+<resources>+ <string name="immersive_detail_pause">Pause</string>+ <string name="immersive_detail_save">Ajouter à la bibliothèque</string>+ <string name="immersive_detail_unsave">Retirer de la bibliothèque</string>+ <string name="immersive_detail_find">Chercher dans la liste</string>+ <string name="immersive_detail_smart_shuffle_on">Lecture aléatoire intelligente : des recommandations rejoignent la liste mélangée.</string>+ <string name="immersive_detail_more">Plus</string>+ <string name="immersive_detail_less">Moins</string>+ <string name="immersive_detail_featured_on">En featuring sur</string>+ <string name="immersive_detail_remove_local">Retirer de cette playlist</string>+ <string name="immersive_detail_follow">Suivre</string>+ <string name="immersive_detail_unfollow">Ne plus suivre</string>+</resources>diff --git a/base/app/src/main/res/values-fr/immersive_glass_strings.xml b/base/app/src/main/res/values-fr/immersive_glass_strings.xmlnew file mode 100644index 00000000..8f1e7314--- /dev/null+++ b/base/app/src/main/res/values-fr/immersive_glass_strings.xml@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="settings_liquid_glass_title">Liquid Glass</string>+ <string name="settings_liquid_glass_detail">Les barres courbent et reflètent la page derrière elles, comme du verre</string>+ <string name="settings_liquid_glass_unsupported">Nécessite Android 12 ou plus récent</string>+ <string name="settings_liquid_glass_reduced">Givré à la place tant que le téléphone réduit le flou ou les animations</string>+ <string name="immersive_expand_tab_bar">Afficher tous les onglets</string>+</resources>diff --git a/base/app/src/main/res/values-fr/immersive_lyrics_strings.xml b/base/app/src/main/res/values-fr/immersive_lyrics_strings.xmlnew file mode 100644index 00000000..a83e5d2c--- /dev/null+++ b/base/app/src/main/res/values-fr/immersive_lyrics_strings.xml@@ -0,0 +1,11 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="immersive_lyrics_instrumental">Instrumental</string>+ <string name="immersive_lyrics_none">Pas de paroles pour ce titre</string>+ <string name="immersive_queue_title">File d\'attente</string>+ <string name="immersive_queue_now_playing">En cours de lecture</string>+ <string name="immersive_queue_empty">La file d\'attente est vide</string>+ <string name="immersive_queue_remove">Retirer de la file d\'attente</string>+ <string name="immersive_queue_shuffle">Lecture aléatoire</string>+ <string name="immersive_queue_repeat">Répéter</string>+</resources>diff --git a/base/app/src/main/res/values-fr/immersive_pages_strings.xml b/base/app/src/main/res/values-fr/immersive_pages_strings.xmlnew file mode 100644index 00000000..6453b52d--- /dev/null+++ b/base/app/src/main/res/values-fr/immersive_pages_strings.xml@@ -0,0 +1,11 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Textes des pages de bibliothèque du look Immersive : Récents, Téléchargé, Fichiers locaux, dossiers, Nouveautés (français). -->+<resources>+ <string name="immersive_pages_songs">Titres</string>+ <string name="immersive_pages_artists">Artistes</string>+ <string name="immersive_pages_albums">Albums</string>+ <string name="immersive_pages_unknown_artist">Artiste inconnu</string>+ <string name="immersive_pages_unknown_album">Album inconnu</string>+ <string name="immersive_pages_name_hint">Nom</string>+ <string name="immersive_pages_play_group">Lire %1$s</string>+</resources>diff --git a/base/app/src/main/res/values-fr/immersive_player_strings.xml b/base/app/src/main/res/values-fr/immersive_player_strings.xmlnew file mode 100644index 00000000..4de549b2--- /dev/null+++ b/base/app/src/main/res/values-fr/immersive_player_strings.xml@@ -0,0 +1,27 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="immersive_player_close">Fermer le lecteur</string>+ <string name="immersive_player_play">Lecture</string>+ <string name="immersive_player_pause">Pause</string>+ <string name="immersive_player_previous">Précédent</string>+ <string name="immersive_player_next">Suivant</string>+ <string name="immersive_player_like">Ajouter aux titres likés</string>+ <string name="immersive_player_unlike">Retirer des titres likés</string>+ <string name="immersive_player_more">Plus</string>+ <string name="immersive_player_lyrics">Paroles</string>+ <string name="immersive_player_lyrics_close">Fermer les paroles</string>+ <string name="immersive_player_queue">À suivre</string>+ <string name="immersive_player_queue_close">Fermer la file d\'attente</string>+ <string name="immersive_player_devices">Appareils</string>+ <string name="immersive_player_shuffle_on">Aléatoire : activé</string>+ <string name="immersive_player_shuffle_off">Aléatoire : désactivé</string>+ <string name="immersive_player_repeat_off">Répétition : désactivée</string>+ <string name="immersive_player_repeat_all">Répétition : tout</string>+ <string name="immersive_player_repeat_one">Répétition : un titre</string>+ <string name="immersive_player_volume_down">Volume moins</string>+ <string name="immersive_player_volume_up">Volume plus</string>+ <string name="immersive_player_ad">Publicité</string>+ <string name="immersive_player_explicit">Explicite</string>+ <string name="immersive_player_added_to_liked">Ajouté aux titres likés</string>+ <string name="immersive_player_mini_player">Ouvrir le lecteur</string>+</resources>diff --git a/base/app/src/main/res/values-fr/immersive_screens_strings.xml b/base/app/src/main/res/values-fr/immersive_screens_strings.xmlnew file mode 100644index 00000000..24da3094--- /dev/null+++ b/base/app/src/main/res/values-fr/immersive_screens_strings.xml@@ -0,0 +1,9 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Textes des écrans Accueil, Recherche, Bibliothèque et Catégorie du look Immersive (français). -->+<resources>+ <string name="immersive_screens_account">Compte</string>+ <string name="immersive_screens_account_page">Page du compte</string>+ <string name="immersive_screens_account_page_detail">Abonnement, confidentialité et appareils</string>+ <string name="immersive_screens_top_result">Meilleur résultat</string>+ <string name="immersive_screens_reset_order">Revenir à l\'ordre par défaut</string>+</resources>diff --git a/base/app/src/main/res/values-fr/immersive_shell_strings.xml b/base/app/src/main/res/values-fr/immersive_shell_strings.xmlnew file mode 100644index 00000000..0825c005--- /dev/null+++ b/base/app/src/main/res/values-fr/immersive_shell_strings.xml@@ -0,0 +1,13 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Textes des barres et des composants de liste partagés du look Immersive (français). -->+<resources>+ <string name="immersive_shell_back">Retour</string>+ <string name="immersive_shell_more">Plus d\'options</string>+ <string name="immersive_shell_search_hint">Rechercher</string>+ <string name="immersive_shell_search_clear">Effacer la recherche</string>+ <string name="immersive_shell_play">Lecture</string>+ <string name="immersive_shell_shuffle">Aléatoire</string>+ <string name="immersive_shell_see_all">Tout afficher</string>+ <string name="immersive_shell_now_playing">En cours de lecture</string>+ <string name="immersive_shell_explicit">Explicite</string>+</resources>diff --git a/base/app/src/main/res/values-fr/myspoti_strings.xml b/base/app/src/main/res/values-fr/myspoti_strings.xmlindex c8a2521f..6234d8c4 100644--- a/base/app/src/main/res/values-fr/myspoti_strings.xml+++ b/base/app/src/main/res/values-fr/myspoti_strings.xml@@ -232,6 +232,22 @@<string name="quality_download_hires_detail">24 bits quand il existe, fichiers environ trois fois plus lourds</string><string name="setup_quality_title">Qualité du son</string><string name="setup_quality_subtitle">Choisissez comment Myspoti lit et enregistre votre musique. Vous pourrez le changer plus tard dans les Réglages.</string>+ <string name="setup_look_title">Choisissez votre style</string>+ <string name="setup_look_subtitle">Regardez l\'aperçu, puis choisissez celui qui vous plaît.</string>+ <string name="look_classic">Classique</string>+ <string name="look_classic_detail">Lecteur sombre teinté par la pochette, bouton lecture rond</string>+ <string name="look_immersive">Immersif</string>+ <string name="look_immersive_detail">Pochette en grand, couleurs de l\'album, paroles animées</string>+ <string name="setup_look_preview">Aperçu du style %1$s</string>+ <string name="setup_look_tap_hint">Touchez l\'aperçu pour le mettre en pause, balayez pour changer</string>+ <string name="setup_look_still_hint">Les animations sont désactivées sur ce téléphone : trois images fixes</string>+ <string name="setup_look_still_player">Lecteur</string>+ <string name="setup_look_still_paused">En pause</string>+ <string name="setup_look_still_lyrics">Paroles</string>+ <string name="look_demo_all">Tout</string>+ <string name="look_demo_music">Musique</string>+ <string name="look_demo_podcasts">Podcasts</string>+ <string name="look_demo_section">Pour vous</string><string name="downloads_off_toast">Les téléchargements sont désactivés. Activez-les dans les Réglages.</string><string name="quality_streaming_high_detail">160 kbit/s, le meilleur son</string><string name="quality_download_small">La plus légère</string>@@ -489,4 +505,9 @@<string name="profile_blocked">Vous avez bloqué cet utilisateur</string><string name="profile_block_failed">Impossible de modifier le blocage, réessayez</string><string name="profile_more_options">Plus d’options</string>+ <string name="settings_look_title">Style</string>+ <string name="look_offer_title">Nouveau style disponible</string>+ <string name="look_offer_try">Essayer Immersif</string>+ <string name="look_offer_keep">Garder Classique</string>+ <string name="look_offer_note">Vous pourrez le changer plus tard dans Réglages > Affichage et langue.</string></resources>diff --git a/base/app/src/main/res/values-pl/immersive_glass_strings.xml b/base/app/src/main/res/values-pl/immersive_glass_strings.xmlnew file mode 100644index 00000000..4165f174--- /dev/null+++ b/base/app/src/main/res/values-pl/immersive_glass_strings.xml@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="settings_liquid_glass_title">Płynne szkło</string>+ <string name="settings_liquid_glass_detail">Paski uginają i odbijają stronę za nimi jak szkło</string>+ <string name="settings_liquid_glass_unsupported">Wymaga Androida 12 lub nowszego</string>+ <string name="settings_liquid_glass_reduced">Matowy efekt, gdy telefon ogranicza rozmycie lub animacje</string>+ <string name="immersive_expand_tab_bar">Pokaż wszystkie karty</string>+</resources>diff --git a/base/app/src/main/res/values-pl/myspoti_strings.xml b/base/app/src/main/res/values-pl/myspoti_strings.xmlindex 5d02e5b7..7345a936 100644--- a/base/app/src/main/res/values-pl/myspoti_strings.xml+++ b/base/app/src/main/res/values-pl/myspoti_strings.xml@@ -462,4 +462,8 @@<string name="profile_blocked">Zablokowano tego użytkownika</string><string name="profile_block_failed">Nie udało się zmienić blokady, spróbuj ponownie</string><string name="profile_more_options">Więcej opcji</string>+ <string name="look_offer_title">Dostępny nowy wygląd</string>+ <string name="look_offer_try">Wypróbuj Immersyjny</string>+ <string name="look_offer_keep">Zostaw Klasyczny</string>+ <string name="look_offer_note">Możesz to zmienić później w Ustawienia > Wyświetlanie i język.</string></resources>diff --git a/base/app/src/main/res/values-ru/immersive_glass_strings.xml b/base/app/src/main/res/values-ru/immersive_glass_strings.xmlnew file mode 100644index 00000000..0ec5513d--- /dev/null+++ b/base/app/src/main/res/values-ru/immersive_glass_strings.xml@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="settings_liquid_glass_title">Жидкое стекло</string>+ <string name="settings_liquid_glass_detail">Панели изгибаются и отражают страницу за ними, как стекло</string>+ <string name="settings_liquid_glass_unsupported">Требуется Android 12 или новее</string>+ <string name="settings_liquid_glass_reduced">Матовый эффект, пока телефон снижает размытие или анимации</string>+ <string name="immersive_expand_tab_bar">Показать все вкладки</string>+</resources>diff --git a/base/app/src/main/res/values-ru/myspoti_strings.xml b/base/app/src/main/res/values-ru/myspoti_strings.xmlindex e1a5586b..1662a483 100644--- a/base/app/src/main/res/values-ru/myspoti_strings.xml+++ b/base/app/src/main/res/values-ru/myspoti_strings.xml@@ -462,4 +462,8 @@<string name="profile_blocked">Вы заблокировали этого пользователя</string><string name="profile_block_failed">Не удалось изменить блокировку, попробуйте ещё раз</string><string name="profile_more_options">Ещё</string>+ <string name="look_offer_title">Доступен новый стиль</string>+ <string name="look_offer_try">Попробовать «Иммерсивный»</string>+ <string name="look_offer_keep">Оставить «Классический»</string>+ <string name="look_offer_note">Это можно изменить позже в Настройки > Экран и язык.</string></resources>diff --git a/base/app/src/main/res/values-zh/immersive_glass_strings.xml b/base/app/src/main/res/values-zh/immersive_glass_strings.xmlnew file mode 100644index 00000000..b042f199--- /dev/null+++ b/base/app/src/main/res/values-zh/immersive_glass_strings.xml@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="settings_liquid_glass_title">液态玻璃</string>+ <string name="settings_liquid_glass_detail">栏会像玻璃一样弯曲并映出身后的页面</string>+ <string name="settings_liquid_glass_unsupported">需要 Android 12 或更高版本</string>+ <string name="settings_liquid_glass_reduced">手机减少模糊或动画时,改用磨砂效果</string>+ <string name="immersive_expand_tab_bar">显示所有标签</string>+</resources>diff --git a/base/app/src/main/res/values-zh/myspoti_strings.xml b/base/app/src/main/res/values-zh/myspoti_strings.xmlindex 890fdf3b..21712237 100644--- a/base/app/src/main/res/values-zh/myspoti_strings.xml+++ b/base/app/src/main/res/values-zh/myspoti_strings.xml@@ -453,4 +453,8 @@<string name="profile_blocked">你已屏蔽此用户</string><string name="profile_block_failed">无法更改屏蔽状态,请重试</string><string name="profile_more_options">更多选项</string>+ <string name="look_offer_title">全新外观上线</string>+ <string name="look_offer_try">试用沉浸式</string>+ <string name="look_offer_keep">保持经典</string>+ <string name="look_offer_note">之后可在“设置 > 显示和语言”中更改。</string></resources>diff --git a/base/app/src/main/res/values/immersive_detail_strings.xml b/base/app/src/main/res/values/immersive_detail_strings.xmlnew file mode 100644index 00000000..4702cf23--- /dev/null+++ b/base/app/src/main/res/values/immersive_detail_strings.xml@@ -0,0 +1,15 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Texts of the Immersive look's album, playlist and artist pages (English default). -->+<resources>+ <string name="immersive_detail_pause">Pause</string>+ <string name="immersive_detail_save">Save to library</string>+ <string name="immersive_detail_unsave">Remove from library</string>+ <string name="immersive_detail_find">Find in list</string>+ <string name="immersive_detail_smart_shuffle_on">Smart shuffle on: recommendations join the shuffled list.</string>+ <string name="immersive_detail_more">More</string>+ <string name="immersive_detail_less">Less</string>+ <string name="immersive_detail_featured_on">Featured on</string>+ <string name="immersive_detail_remove_local">Remove from this playlist</string>+ <string name="immersive_detail_follow">Follow</string>+ <string name="immersive_detail_unfollow">Unfollow</string>+</resources>diff --git a/base/app/src/main/res/values/immersive_glass_strings.xml b/base/app/src/main/res/values/immersive_glass_strings.xmlnew file mode 100644index 00000000..6118e47c--- /dev/null+++ b/base/app/src/main/res/values/immersive_glass_strings.xml@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="settings_liquid_glass_title">Liquid Glass</string>+ <string name="settings_liquid_glass_detail">Bars bend and reflect the page behind them, like glass</string>+ <string name="settings_liquid_glass_unsupported">Needs Android 12 or later</string>+ <string name="settings_liquid_glass_reduced">Frosted instead while the phone reduces blur or animations</string>+ <string name="immersive_expand_tab_bar">Show all tabs</string>+</resources>diff --git a/base/app/src/main/res/values/immersive_lyrics_strings.xml b/base/app/src/main/res/values/immersive_lyrics_strings.xmlnew file mode 100644index 00000000..fe32920e--- /dev/null+++ b/base/app/src/main/res/values/immersive_lyrics_strings.xml@@ -0,0 +1,11 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="immersive_lyrics_instrumental">Instrumental</string>+ <string name="immersive_lyrics_none">No lyrics for this track</string>+ <string name="immersive_queue_title">Queue</string>+ <string name="immersive_queue_now_playing">Now playing</string>+ <string name="immersive_queue_empty">Nothing is queued</string>+ <string name="immersive_queue_remove">Remove from queue</string>+ <string name="immersive_queue_shuffle">Shuffle</string>+ <string name="immersive_queue_repeat">Repeat</string>+</resources>diff --git a/base/app/src/main/res/values/immersive_pages_strings.xml b/base/app/src/main/res/values/immersive_pages_strings.xmlnew file mode 100644index 00000000..31357237--- /dev/null+++ b/base/app/src/main/res/values/immersive_pages_strings.xml@@ -0,0 +1,11 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Texts of the Immersive look's library pages: Recents, Downloaded, Local Files, folders, New releases (English default). -->+<resources>+ <string name="immersive_pages_songs">Songs</string>+ <string name="immersive_pages_artists">Artists</string>+ <string name="immersive_pages_albums">Albums</string>+ <string name="immersive_pages_unknown_artist">Unknown artist</string>+ <string name="immersive_pages_unknown_album">Unknown album</string>+ <string name="immersive_pages_name_hint">Name</string>+ <string name="immersive_pages_play_group">Play %1$s</string>+</resources>diff --git a/base/app/src/main/res/values/immersive_player_strings.xml b/base/app/src/main/res/values/immersive_player_strings.xmlnew file mode 100644index 00000000..70d72c6b--- /dev/null+++ b/base/app/src/main/res/values/immersive_player_strings.xml@@ -0,0 +1,27 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="immersive_player_close">Close the player</string>+ <string name="immersive_player_play">Play</string>+ <string name="immersive_player_pause">Pause</string>+ <string name="immersive_player_previous">Previous</string>+ <string name="immersive_player_next">Next</string>+ <string name="immersive_player_like">Add to Liked Songs</string>+ <string name="immersive_player_unlike">Remove from Liked Songs</string>+ <string name="immersive_player_more">More</string>+ <string name="immersive_player_lyrics">Lyrics</string>+ <string name="immersive_player_lyrics_close">Close the lyrics</string>+ <string name="immersive_player_queue">Up next</string>+ <string name="immersive_player_queue_close">Close the queue</string>+ <string name="immersive_player_devices">Devices</string>+ <string name="immersive_player_shuffle_on">Shuffle: on</string>+ <string name="immersive_player_shuffle_off">Shuffle: off</string>+ <string name="immersive_player_repeat_off">Repeat: off</string>+ <string name="immersive_player_repeat_all">Repeat: all</string>+ <string name="immersive_player_repeat_one">Repeat: one</string>+ <string name="immersive_player_volume_down">Volume down</string>+ <string name="immersive_player_volume_up">Volume up</string>+ <string name="immersive_player_ad">Advertisement</string>+ <string name="immersive_player_explicit">Explicit</string>+ <string name="immersive_player_added_to_liked">Added to Liked Songs</string>+ <string name="immersive_player_mini_player">Open the player</string>+</resources>diff --git a/base/app/src/main/res/values/immersive_screens_strings.xml b/base/app/src/main/res/values/immersive_screens_strings.xmlnew file mode 100644index 00000000..7784dcdb--- /dev/null+++ b/base/app/src/main/res/values/immersive_screens_strings.xml@@ -0,0 +1,9 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Texts of the Immersive look's Home, Search, Library and Category screens (English default). -->+<resources>+ <string name="immersive_screens_account">Account</string>+ <string name="immersive_screens_account_page">Account page</string>+ <string name="immersive_screens_account_page_detail">Plan, privacy and devices</string>+ <string name="immersive_screens_top_result">Top result</string>+ <string name="immersive_screens_reset_order">Back to the default order</string>+</resources>diff --git a/base/app/src/main/res/values/immersive_shell_strings.xml b/base/app/src/main/res/values/immersive_shell_strings.xmlnew file mode 100644index 00000000..40307b8f--- /dev/null+++ b/base/app/src/main/res/values/immersive_shell_strings.xml@@ -0,0 +1,13 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Texts of the Immersive look's bars and shared list components (English default). -->+<resources>+ <string name="immersive_shell_back">Back</string>+ <string name="immersive_shell_more">More options</string>+ <string name="immersive_shell_search_hint">Search</string>+ <string name="immersive_shell_search_clear">Clear search</string>+ <string name="immersive_shell_play">Play</string>+ <string name="immersive_shell_shuffle">Shuffle</string>+ <string name="immersive_shell_see_all">See all</string>+ <string name="immersive_shell_now_playing">Now playing</string>+ <string name="immersive_shell_explicit">Explicit</string>+</resources>diff --git a/base/app/src/main/res/values/myspoti_strings.xml b/base/app/src/main/res/values/myspoti_strings.xmlindex 01768f06..22930883 100644--- a/base/app/src/main/res/values/myspoti_strings.xml+++ b/base/app/src/main/res/values/myspoti_strings.xml@@ -232,6 +232,22 @@<string name="quality_download_hires_detail">24-bit when it exists, files about three times bigger</string><string name="setup_quality_title">Sound quality</string><string name="setup_quality_subtitle">Choose how Myspoti plays and saves your music. You can change it later in Settings.</string>+ <string name="setup_look_title">Choose your look</string>+ <string name="setup_look_subtitle">Watch the preview, then pick the one you like.</string>+ <string name="look_classic">Classic</string>+ <string name="look_classic_detail">Dark player tinted by the cover, round play button</string>+ <string name="look_immersive">Immersive</string>+ <string name="look_immersive_detail">Big artwork, album colours, animated lyrics</string>+ <string name="setup_look_preview">Preview of the %1$s look</string>+ <string name="setup_look_tap_hint">Tap the preview to pause it, swipe to switch</string>+ <string name="setup_look_still_hint">Animations are off on this phone: three still frames</string>+ <string name="setup_look_still_player">Player</string>+ <string name="setup_look_still_paused">Paused</string>+ <string name="setup_look_still_lyrics">Lyrics</string>+ <string name="look_demo_all">All</string>+ <string name="look_demo_music">Music</string>+ <string name="look_demo_podcasts">Podcasts</string>+ <string name="look_demo_section">Made for you</string><string name="downloads_off_toast">Downloads are off. Turn them on in Settings.</string><string name="quality_streaming_high_detail">160 kbit/s, the best sound</string><string name="quality_download_small">Smallest</string>@@ -490,4 +506,9 @@<string name="profile_blocked">You blocked this user</string><string name="profile_block_failed">Couldn’t change the block, try again</string><string name="profile_more_options">More options</string>+ <string name="settings_look_title">Look</string>+ <string name="look_offer_title">New look available</string>+ <string name="look_offer_try">Try Immersive</string>+ <string name="look_offer_keep">Keep Classic</string>+ <string name="look_offer_note">You can change it later in Settings > Display and language.</string></resources>diff --git a/base/gradle.properties b/base/gradle.propertiesindex 59d7ec52..29327247 100644--- a/base/gradle.properties+++ b/base/gradle.properties@@ -18,3 +18,5 @@ kotlin.daemon.jvmargs=-Xmx1536m -Dfile.encoding=UTF-8android.useAndroidX=trueandroid.enableJetifier=falseandroid.nonTransitiveRClass=true+# Cronet ships cronet-api and cronet-shared under the same org.chromium.net namespace.+android.uniquePackageNames=falsediff --git a/base/gradle/libs.versions.toml b/base/gradle/libs.versions.tomlindex 10b6610f..956c6705 100644--- a/base/gradle/libs.versions.toml+++ b/base/gradle/libs.versions.toml@@ -60,6 +60,11 @@ brotli = { module = "org.brotli:dec", version.ref = "brotli" }# Utilsokhttp = { module = "com.squareup.okhttp3:okhttp", version.ref = "okhttp" }+# Chrome's Accept-Encoding on the relayed requests (br, zstd), decoded on the OkHttp path.+okhttp-brotli = { module = "com.squareup.okhttp3:okhttp-brotli", version.ref = "okhttp" }+okhttp-zstd = { module = "com.squareup.okhttp3:okhttp-zstd", version.ref = "okhttp" }+# Cronet from Google Play services: the Chromium network stack for refused commands before Android 14.+play-services-cronet = { module = "com.google.android.gms:play-services-cronet", version = "18.1.1" }# Serializationserialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "serialization" }diff --git a/base/host-android/build.gradle.kts b/base/host-android/build.gradle.ktsindex 0a6686c8..8c22b512 100644--- a/base/host-android/build.gradle.kts+++ b/base/host-android/build.gradle.kts@@ -24,6 +24,9 @@ dependencies {implementation(libs.androidx.media)implementation(libs.serialization.json)implementation(libs.okhttp)+ implementation(libs.okhttp.brotli)+ implementation(libs.okhttp.zstd)+ implementation(libs.play.services.cronet)implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2")testImplementation("junit:junit:4.13.2")diff --git a/base/host-android/src/main/AndroidManifest.xml b/base/host-android/src/main/AndroidManifest.xmlindex d34a70a8..164cd6a4 100644--- a/base/host-android/src/main/AndroidManifest.xml+++ b/base/host-android/src/main/AndroidManifest.xml@@ -3,6 +3,8 @@<uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.FOREGROUND_SERVICE" /><uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />+ <uses-permission android:name="android.permission.WAKE_LOCK" />+ <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /><uses-permission android:name="android.permission.POST_NOTIFICATIONS" /><application><servicediff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/ControlRelay.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/ControlRelay.ktindex 91859898..55e41af9 100644--- a/base/host-android/src/main/kotlin/app/myspoti/host/android/ControlRelay.kt+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/ControlRelay.kt@@ -8,11 +8,15 @@ import app.myspoti.spotify.bridge.RelayRouteimport app.myspoti.spotify.bridge.RelayRoutesimport okhttp3.Callimport okhttp3.Callback-import okhttp3.Cookie-import okhttp3.CookieJar+import okhttp3.CompressionInterceptor+import okhttp3.Gzipimport okhttp3.Headers-import okhttp3.HttpUrlimport okhttp3.OkHttpClient+import okhttp3.brotli.Brotli+import okhttp3.zstd.Zstd+import okio.BufferedSource+import okio.InflaterSource+import okio.Sourceimport okhttp3.Requestimport okhttp3.RequestBody.Companion.toRequestBodyimport okhttp3.Response@@ -40,31 +44,18 @@ internal class ControlRelay(private val view: WebView, private val fingerprint:private val main = Handler(Looper.getMainLooper())/**- * The WebView's own cookies. The page's `fetch` sends them, this app's OkHttp does not: a- * relayed request without them is not the shape of the real Web Player's request, which- * Spotify can tell apart (a `402 COMMAND_FAILED` on a free account is one such refusal).+ * No cookie jar: the real Web Player's requests to spclient carry no cookie (its `fetch` is+ * cross-origin with the default `credentials: same-origin`; 02-playback capture). The WebView's+ * cookies the relay sent from 2.0.2-beta.9 on (sp_dc, sp_t, sp_key...) were a shape no+ * browser's command has.+ *+ * Chrome's Accept-Encoding ([ACCEPT_ENCODING]) comes from [DECODING], which also decodes the+ * answer (Spotify answers track-playback in zstd, connect-state in gzip or br).*/- private val cookies = object : CookieJar {- override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) = Unit- override fun loadForRequest(url: HttpUrl): List<Cookie> = runCatching {- val raw = android.webkit.CookieManager.getInstance().getCookie(url.toString()) ?: return emptyList()- raw.split(';').mapNotNull { part ->- val at = part.indexOf('=')- if (at <= 0) null- else Cookie.Builder()- .name(part.take(at).trim())- .value(part.substring(at + 1).trim())- .domain(url.host)- .path("/")- .build()- }- }.getOrDefault(emptyList())- }-private val http = OkHttpClient.Builder().connectTimeout(15, TimeUnit.SECONDS).readTimeout(30, TimeUnit.SECONDS)- .cookieJar(cookies)+ .addInterceptor(DECODING).eventListener(RelayEvents).build()/** The same client, pinned to one address family (see RelayRoutes). */@@ -74,6 +65,8 @@ internal class ControlRelay(private val view: WebView, private val fingerprint:fun install() {NetworkReport.logOnce(view.context.applicationContext)+ // Before Android 14: Cronet from Play services, ready before any refusal needs it.+ CronetStack.prepare(view.context)view.exposeToPlayer("MyspotiNet", ::onMessage)val documentStart = androidx.webkit.WebViewFeature.isFeatureSupported(androidx.webkit.WebViewFeature.DOCUMENT_START_SCRIPT)if (documentStart) androidx.webkit.WebViewCompat.addDocumentStartJavaScript(view, SCRIPT, setOf("https://open.spotify.com"))@@ -130,8 +123,26 @@ internal class ControlRelay(private val view: WebView, private val fingerprint:return}if (m.optString("type") == "direct") {- if (m.has("kept")) Logbook.log("commands from the page: ${if (m.optBoolean("kept")) "kept, the music plays" else "dropped, nothing played in 10 s"}")- else Logbook.log("refused command sent again from the page -> ${m.optInt("status")}")+ if (m.has("kept")) {+ Logbook.log("commands from the page: ${if (m.optBoolean("kept")) "kept, the music plays" else "dropped, nothing played in 10 s"}")+ app.myspoti.spotify.report.Refusal402.pageKept(m.optBoolean("kept"))+ // A page fetch answered 200 can still be dropped (X-Requested-With): the matrix says which.+ matrixPageLine?.let { line ->+ matrixPageLine = null+ Logbook.fact("402 matrix", "$line (page: ${if (m.optBoolean("kept")) "played" else "nothing played"})")+ }+ } else {+ Logbook.log("refused command sent again from the page -> ${m.optInt("status")}")+ app.myspoti.spotify.report.Refusal402.pageFetch(m.optInt("status"))+ // The matrix's last row: the same command through the page's own fetch.+ if (matrixPage) {+ matrixPage = false+ val line = "$matrixRows; page fetch=${m.optInt("status")}"+ Logbook.log("402 matrix: $line")+ Logbook.fact("402 matrix", line)+ if (m.optInt("status") in 200..299) matrixPageLine = line+ }+ }return}val id = m.optInt("id", -1).takeIf { it >= 0 } ?: return@@ -144,30 +155,7 @@ internal class ControlRelay(private val view: WebView, private val fingerprint:reply(id, 0, "{}", "")return}- val headers = Headers.Builder()- given.keys().forEach { key ->- // OkHttp sets the transport headers itself.- if (key.lowercase() !in setOf("host", "content-length", "connection", "accept-encoding", "x-requested-with"))- runCatching { headers.add(key, given.getString(key)) }- }- val page = identity- fun fromPage(name: String, fallback: String) = page?.optString(name)?.takeIf { it.isNotEmpty() } ?: fallback- headers["User-Agent"] = fromPage("userAgent", fingerprint.userAgent)- headers["Origin"] = "https://open.spotify.com"- headers["Referer"] = "https://open.spotify.com/"- // The transport headers Chromium adds by itself, which the page's `fetch` cannot set- // (forbidden header names in JS) and OkHttp does not add either: without them the- // relayed request carries a shape the real Web Player's request never has.- headers["Sec-Fetch-Site"] = "same-site"- headers["Sec-Fetch-Mode"] = "cors"- headers["Sec-Fetch-Dest"] = "empty"- // Values taken from the page, not written by hand: whichever language and client hints it- // presents, the relayed request presents the same.- headers["Accept-Language"] = fromPage("acceptLanguage", fallbackLanguage)- headers["sec-ch-ua"] = fromPage("brands", fingerprint.secChUa)- headers["sec-ch-ua-mobile"] = fromPage("mobile", "?0")- headers["sec-ch-ua-platform"] = "\"${fromPage("platform", "Linux")}\""- val built = headers.build()+ val built = relayHeaders(given, identity, fingerprint.userAgent, fallbackLanguage, fingerprint.secChUa)// The registration goes out as the real Web Player sends it, except for its name: the phone's// own (see [deviceName]) replaces "Web Player (Chrome)".val registration = body != null && app.myspoti.spotify.bridge.AdBlock.isDeviceRegistration(method, url)@@ -175,6 +163,16 @@ internal class ControlRelay(private val view: WebView, private val fingerprint:Logbook.log("connect-state body: ${body.take(500)}")if (registration) runCatching { JSONObject(body!!).optJSONObject("device")?.optString("device_id") }.getOrNull()?.takeIf { it.isNotEmpty() }?.let { self = it }+ // The device the previous page left behind (app swiped away or killed before its unload+ // handler ran) is taken off the account alongside this registration, not after it: the+ // cluster the page joins next then lists this player alone.+ if (registration) self?.let { mine ->+ if (debuggable) Logbook.log("player device #${shortHash(mine)}")+ devices.registering(mine)?.let { (old, seq) ->+ staleOwn = old+ sayGoodbye(url, built, old, seq)+ }+ } else if (method != "DELETE") devices.sent(url, body)// 402 on some free accounts: which headers the page gave its commands (names only), so a// refused session can be set against a working one. Logged when the set changes.if (COMMAND.containsMatchIn(url)) {@@ -191,19 +189,42 @@ internal class ControlRelay(private val view: WebView, private val fingerprint:} else bodyval asked = android.os.SystemClock.uptimeMillis()// A refused command (or a refused registration) is sent again another way before the page- // hears of it (see RelayRoutes): the other address family, then the platform's own stack.+ // hears of it (see RelayRoutes): a Chromium network stack, then the other address family.val retriable = COMMAND.containsMatchIn(url) || registrationval tried = ArrayList<RelayRoute>()+ // What each route answered, for the 402 matrix (the first refused command of the session).+ val rows = ArrayList<String>()var refusal: Answer? = null+ fun matrixDone(page: Boolean) {+ if (refusal == null || !COMMAND.containsMatchIn(url) || !MATRIX_RUN.compareAndSet(false, true)) return+ val chromium = routes.chromiumRoute()+ if (chromium == null) rows += if (android.os.Build.VERSION.SDK_INT >= 34) "HTTP_ENGINE=unavailable" else "CRONET=${CronetStack.status}"+ matrixRows = rows.joinToString("; ")+ if (page) matrixPage = true+ val line = matrixRows + if (page) "; page fetch=pending" else "; page fetch=not needed"+ Logbook.log("402 matrix (first refused command): $line")+ Logbook.fact("402 matrix", line)+ }+ val command = COMMAND.containsMatchIn(url)+ val kind = if (command) commandKind(url, body) else ""+ fun finish(answer: Answer) {+ matrixDone(page = answer.code == 402)+ if (command) app.myspoti.spotify.report.Refusal402.command(kind, answer.code, retried = refusal != null)+ handle(id, url, method, body, registration, asked, answer)+ }fun attempt(route: RelayRoute) {tried += route+ val began = android.os.SystemClock.uptimeMillis()fetch(route, url, method, built, sent) { answer, error ->val via = if (route == RelayRoute.DEFAULT) "" else " via $route"+ if (command) app.myspoti.spotify.report.Refusal402.attempt(kind, shortRoute(route), answer?.code, android.os.SystemClock.uptimeMillis() - began,+ answer?.headers.orEmpty(), answer?.text.orEmpty())+ rows += "${routeLabel(route)}=${answer?.code ?: "failed (${error?.take(60)})"}"if (answer == null) {Logbook.log("relay $method ${shortPath(url)} failed$via: $error")val first = refusalwhen {- first != null -> routes.next(tried, null)?.let { attempt(it) } ?: handle(id, url, method, body, registration, asked, first)+ first != null -> routes.next(tried, null)?.let { attempt(it) } ?: finish(first)// A kept route the network no longer offers (IPv6 gone with the Wi-Fi): this// request goes the default way; the route stays kept for the next ones.route != RelayRoute.DEFAULT && RelayRoute.DEFAULT !in tried -> attempt(RelayRoute.DEFAULT)@@ -213,7 +234,11 @@ internal class ControlRelay(private val view: WebView, private val fingerprint:}val refused = answer.code == 402 || (registration && answer.code == 403)if (refused && retriable) {- if (refusal == null) { refusal = answer; logRefusal(answer, body) }+ if (refusal == null) {+ refusal = answer+ logRefusal(answer, body)+ Logbook.fact("ads", adsMode())+ }val next = routes.next(tried, answer.family)if (next != null) {Logbook.log("relay $method ${shortPath(url)} -> ${answer.code}$via (${answer.family ?: "family unknown"}): sent again via $next")@@ -226,9 +251,10 @@ internal class ControlRelay(private val view: WebView, private val fingerprint:routes.won(route)Logbook.log("relay: $route answered ${answer.code} where ${tried.first()} was refused: kept for this session")Logbook.fact("relay route", "$route (taken after a refusal on ${tried.first()})")+ if (command) checkAudio(shortRoute(route))} else Logbook.log("relay: refused on every route (${tried.joinToString()})")}- handle(id, url, method, body, registration, asked, answer)+ finish(answer)}}attempt(routes.kept)@@ -260,6 +286,12 @@ internal class ControlRelay(private val view: WebView, private val fingerprint:}return}+ if (route == RelayRoute.CRONET) {+ CronetStack.fetch(url, method, headers, sent) { code, heads, text, protocol, error ->+ done(if (error == null) Answer(code, heads, text, protocol, null, null) else null, error)+ }+ return+ }// Bytes, not a String body: OkHttp would append "; charset=utf-8" to the content type.val payload = if (method == "GET" || method == "HEAD") null else (sent ?: "").toByteArray().toRequestBody(null)val tag = RelayTag()@@ -296,25 +328,47 @@ internal class ControlRelay(private val view: WebView, private val fingerprint:it.headers.forEach { (name, value) -> out.put(name, value) }val text = it.textval net = android.os.SystemClock.uptimeMillis() - asked- Logbook.log("relay $method ${shortPath(url)} -> ${it.code} in $net ms")+ val path = shortPath(url)+ // Steady streams answered 2xx (play reports, playback state and volume PUTs: hundreds per+ // report, never read in an analysis) are logged once a minute; failures always.+ val steady = STEADY.find(path)?.value+ if (steady != null && it.code in 200..299) Logbook.logEvery("relay $method $steady", 60_000, "relay $method $path -> ${it.code} in $net ms")+ else Logbook.log("relay $method $path -> ${it.code} in $net ms")if (it.code >= 400) Logbook.log("relay error body: ${text.take(400)}")if (it.code in 200..299 && method == "POST" && url.substringBefore('?').endsWith("/track-playback/v1/devices")) onDeviceRegistered?.invoke()if (it.code == 402 && !(COMMAND.containsMatchIn(url) || registration)) logRefusal(it, body)if (registration) Regex("\"effective_license\"\\s*:\\s*\"([^\"]*)\"").find(text)?.let { m -> Logbook.log("registration: effective_license=${m.groupValues[1]}") }+ if (registration) app.myspoti.spotify.report.Refusal402.registered(it.code)if (registration && it.code in 200..299) Logbook.log("registration answer: ${registrationSummary(text)}")+ // The page's connect-state PUT (joining the cluster): its status and its answer's header names.+ if (method == "PUT" && url.contains("/connect-state/v1/devices/"))+ app.myspoti.spotify.report.Refusal402.connectStatePut(it.code, it.headers.map { h -> h.first.lowercase() }.distinct().sorted().joinToString(","))+ if (registration && it.code in 200..299) runCatching { JSONObject(text).optLong("initial_seq_num", 0) }.getOrNull()?.let(devices::answered)+ if (method == "DELETE" && it.code in 200..299 && url.contains("/track-playback/v1/devices/")) devices.deregistered(url)if (registration) Logbook.fact("registration", "${it.code}" + (Regex("\"effective_license\"\\s*:\\s*\"([^\"]*)\"").find(text)?.let { m -> " effective_license=${m.groupValues[1]}" } ?: ""))// What Spotify holds for this account's devices (this player's license, whether// it may play, another device active): the cluster comes back on joining and// on every cluster read, the one the page makes after a refused command.if (it.code in 200..299 && (url.contains("/connect-state/v1/cluster") || (method == "PUT" && url.contains("/connect-state/v1/devices/"))))- clusterSummary(text, self)?.let { s -> Logbook.log("cluster: $s"); Logbook.fact("devices", s) }+ clusterSummary(text, self, staleOwn)?.let { s ->+ // The same cluster again (every state PUT and cluster read returns it) is not logged twice.+ if (s != lastCluster) { lastCluster = s; Logbook.log("cluster: $s") }+ clusterBrief(text, self, staleOwn)?.let(app.myspoti.spotify.report.Refusal402::cluster)+ Logbook.fact("devices", s)+ // Debug builds: which devices these are, as short hashes (a ghost left by a+ // previous start shows under the hash its own start logged).+ if (debuggable) runCatching {+ val c = JSONObject(text).let { j -> j.optJSONObject("cluster") ?: j }+ Logbook.log("cluster devices: " + c.getJSONObject("devices").keys().asSequence().joinToString(" ") { k -> "#${shortHash(k)}" })+ }+ }if (debuggable && registration) Logbook.log("registration answered: ${text.take(500)}")if (debuggable && AD_MARK.containsMatchIn(text)) keepAdSample(method, url, body, text)// An ad in the queue Spotify sends: the song before it goes on to the next song// instead, before the page sees the queue (see AdBlock.withoutAds).val given = if (url.contains("/track-playback/")) app.myspoti.spotify.bridge.AdBlock.withoutAds(text) else null- given?.second?.forEach { note -> Logbook.log("ad left out: $note") }+ given?.second?.forEach { note -> Logbook.log("ad left out: $note"); ADS_LEFT_OUT.incrementAndGet(); app.myspoti.spotify.report.Refusal402.adStateLeftOut() }val sent = given?.first ?: text// The songs' media manifests, for extensions to read (spotify.media).if (it.code in 200..299 && url.contains("/track-playback/")) app.myspoti.spotify.bridge.MediaManifests.record(sent)@@ -341,8 +395,56 @@ internal class ControlRelay(private val view: WebView, private val fingerprint:)}+ /** The last page's playback device, kept across starts (see [PlayerDeviceRecord]). */+ private val devices = PlayerDeviceRecord(java.io.File(view.context.filesDir, "spotify/player-device"))++ /** The page's own goodbye for a device it left: the same DELETE, with that page's headers' twin. */+ private fun sayGoodbye(registrationUrl: String, headers: Headers, old: String, seq: Long) {+ val request = Request.Builder()+ .url(PlayerDeviceRecord.deviceUrl(registrationUrl, old))+ .headers(headers)+ .delete(PlayerDeviceRecord.goodbye(seq).toByteArray().toRequestBody(null))+ .build()+ http.newCall(request).enqueue(object : Callback {+ override fun onFailure(call: Call, e: IOException) = Logbook.log("previous player device: goodbye failed: ${e.message}")+ override fun onResponse(call: Call, response: Response) = response.use {+ Logbook.log("previous player device${if (debuggable) " #${shortHash(old)}" else ""} taken off -> ${it.code}")+ if (it.code >= 400) Logbook.log("goodbye error body: ${it.body.string().take(200)}")+ }+ })+ }++ private fun shortHash(id: String) = java.security.MessageDigest.getInstance("SHA-256")+ .digest(id.toByteArray()).take(3).joinToString("") { "%02x".format(it) }+/** This page's playback device id, read from its registration: never logged, only compared. */@Volatile private var self: String? = null++ /** The device id the previous start left registered (see [PlayerDeviceRecord]): only compared. */+ @Volatile private var staleOwn: String? = null++ @Volatile private var lastCluster: String? = null++ /**+ * A refused command another route answered 2xx: whether the page's media really plays 10 s+ * later (a 2xx alone proved nothing: the page path's 200s were all dropped, 402-ANALYSIS fact 2).+ */+ private fun checkAudio(route: String) = main.postDelayed({+ view.evaluateJavascript(PLAYING) { r ->+ val started = r == "true"+ Logbook.log("audio after the $route retry: ${if (started) "playing" else "nothing played"} within 10 s")+ app.myspoti.spotify.report.Refusal402.audioAfterRetry(route, started)+ }+ }, 10_000)++ /** The 402 matrix's rows once its relay part is done, while the page's own fetch is awaited. */+ @Volatile private var matrixRows = ""+ @Volatile private var matrixPage = false+ @Volatile private var matrixPageLine: String? = null++ /** The ads mode, for the 402 report: what this app does to ads (it has no setting for it). */+ private fun adsMode() = "blocked (page ad managers off, ${app.myspoti.spotify.bridge.AdBlock.blockedHosts.size} ad hosts blocked, " ++ "ad states left out this session=${ADS_LEFT_OUT.get()}, ad ahead=${app.myspoti.spotify.bridge.AdBlock.ahead.value != null})"@Volatile private var commandHeaders: String? = nullprivate val debuggable = view.context.applicationInfo.flags and android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE != 0@@ -420,8 +522,143 @@ internal class ControlRelay(private val view: WebView, private val fingerprint:fun isRelayed(url: String) = (RELAYED.containsMatchIn(url) || REPORTS.containsMatchIn(url)) && !NOT_RELAYED.containsMatchIn(url)- /** The route kept for this session, shared by every page and WebView of the process. */- private val ROUTES = RelayRoutes(engineAvailable = android.os.Build.VERSION.SDK_INT >= 34)+ /**+ * The route kept for this session, shared by every page and WebView of the process. The+ * Chromium stack a refusal goes to first: the platform's on Android 14+, else Cronet once+ * Play services has installed it.+ */+ private val ROUTES = RelayRoutes {+ when {+ android.os.Build.VERSION.SDK_INT >= 34 -> RelayRoute.HTTP_ENGINE+ CronetStack.available -> RelayRoute.CRONET+ else -> null+ }+ }++ /** The 402 matrix runs once per process, on the first refused command. */+ private val MATRIX_RUN = java.util.concurrent.atomic.AtomicBoolean(false)++ /** Ad states [app.myspoti.spotify.bridge.AdBlock.withoutAds] left out this session. */+ private val ADS_LEFT_OUT = java.util.concurrent.atomic.AtomicInteger(0)++ /** A route's name in the 402 summary. */+ internal fun shortRoute(route: RelayRoute) = when (route) {+ RelayRoute.DEFAULT -> "okhttp"+ RelayRoute.IPV4 -> "okhttp-v4"+ RelayRoute.IPV6 -> "okhttp-v6"+ else -> route.name+ }++ /** Whether one of the page's media elements plays (the same test as the page script's `plays`). */+ private const val PLAYING = "(() => { const m = window.__mspMedia; return !!m && [...m].some(e => !e.paused && !e.ended && e.readyState > 2); })()"++ /** Relayed requests that run all along (play reports, playback state, volume): their 2xx answers are rate-limited. */+ private val STEADY = Regex("^/melody/v1/msg/batch|^/track-playback/v1/devices/…/(state|volume)$")++ /** A command's kind for the 402 summary: "transfer", or its endpoint. */+ internal fun commandKind(url: String, body: String?): String =+ if (url.contains("/connect/transfer/")) "transfer"+ else runCatching { (JSONObject(body ?: "").optJSONObject("command") ?: JSONObject(body ?: "")).optString("endpoint") }+ .getOrNull()?.takeIf { it.isNotEmpty() && it.length <= 40 } ?: "command"++ /**+ * The cluster for the 402 summary: how many devices, their types, what each is to this+ * player (self, stale-own, foreign-webplayer, foreign) and whether a player state exists.+ */+ internal fun clusterBrief(text: String, self: String?, staleOwn: String?): String? {+ val full = clusterSummary(text, self, staleOwn) ?: return null+ val c = runCatching { JSONObject(text).let { j -> j.optJSONObject("cluster") ?: j } }.getOrNull() ?: return null+ val devices = c.optJSONObject("devices") ?: return null+ val ownSoftware = self?.let { devices.optJSONObject(it)?.optString("device_software_version") }?.takeIf { it.isNotEmpty() }+ val types = sortedMapOf<String, Int>()+ val kinds = sortedMapOf<String, Int>()+ devices.keys().forEach { id ->+ val d = devices.optJSONObject(id) ?: JSONObject()+ types.merge(d.optString("device_type").ifEmpty { "?" }, 1, Int::plus)+ val kind = when {+ id == self -> "self"+ staleOwn != null && id == staleOwn -> "stale-own"+ ownSoftware != null && d.optString("device_software_version") == ownSoftware -> "foreign-webplayer"+ else -> "foreign"+ }+ kinds.merge(kind, 1, Int::plus)+ }+ val state = Regex("player_state=(absent|present\\([^)]*\\))").find(full)?.groupValues?.get(1) ?: "?"+ val active = Regex("active=(\\w+)").find(full)?.groupValues?.get(1) ?: "?"+ return "devices=${devices.length()} types=${types.entries.joinToString(",") { (k, v) -> "$k×$v" }} " ++ "kinds=${kinds.entries.joinToString(",") { (k, v) -> "$k×$v" }} active=$active player_state=$state"+ }++ internal fun routeLabel(route: RelayRoute) = when (route) {+ RelayRoute.DEFAULT -> "okhttp(no cookies, chrome headers)"+ RelayRoute.IPV4 -> "okhttp-v4"+ RelayRoute.IPV6 -> "okhttp-v6"+ else -> route.name+ }++ /**+ * Chrome's own Accept-Encoding on spclient (02-playback capture), in its order. OkHttp's+ * transparent gzip covers gzip alone: [DECODING] sends this list and decodes each of them+ * (Spotify answers track-playback in zstd, connect-state in gzip or br).+ */+ internal const val ACCEPT_ENCODING = "gzip, deflate, br, zstd"++ /** HTTP's `deflate`: zlib-wrapped, as java.util.zip reads it by default. */+ private object Deflate : CompressionInterceptor.DecompressionAlgorithm {+ override val encoding = "deflate"+ override fun decompress(compressedSource: BufferedSource): Source = InflaterSource(compressedSource, java.util.zip.Inflater())+ }++ /** Chrome's encodings, each with its decoder, in [ACCEPT_ENCODING]'s order. */+ internal val DECODERS: List<CompressionInterceptor.DecompressionAlgorithm> = listOf(Gzip, Deflate, Brotli, Zstd)++ /** A zstd frame of "ok": whether zstd's native decoder loads on this phone. */+ private val ZSTD_PROBE = byteArrayOf(0x28, 0xb5.toByte(), 0x2f, 0xfd.toByte(), 0x04, 0x58, 0x11, 0x00, 0x00, 0x6f, 0x6b, 0xf9.toByte(), 0x5c, 0x14, 0x16)++ /**+ * The decoding interceptor: Chrome's list when zstd's native decoder loads, else the same+ * list without zstd (an answer that could not be read is worse than a shorter list).+ */+ private val DECODING: CompressionInterceptor by lazy {+ val zstd = runCatching {+ okio.Buffer().write(ZSTD_PROBE).let { Zstd.decompress(it) }.let { okio.Buffer().apply { writeAll(it) } }.readUtf8() == "ok"+ }.getOrElse { e -> Logbook.log("relay: zstd decoder unavailable (${e.javaClass.simpleName}): Accept-Encoding without zstd"); false }+ CompressionInterceptor(*DECODERS.filter { zstd || it !== Zstd }.toTypedArray())+ }++ /** Header names OkHttp or the page's `fetch` must not carry over (transport, cookies, the WebView's mark). */+ private val NOT_CARRIED = setOf("host", "content-length", "connection", "accept-encoding", "x-requested-with", "cookie")++ /**+ * The headers a relayed request carries: the page's own (its token, client token, app+ * version...), then what Chrome adds by itself, which the page's `fetch` cannot set+ * (forbidden names in JS) and OkHttp does not add either. [page] is the identity the page+ * presents (user agent, languages, client hints); the fallbacks only stand in for it until+ * it arrives. Matched against desktop Chrome's command request in ControlRelayTest.+ */+ internal fun relayHeaders(given: JSONObject, page: JSONObject?, userAgent: String, language: String, secChUa: String): Headers {+ val headers = Headers.Builder()+ given.keys().forEach { key ->+ if (key.lowercase() !in NOT_CARRIED) runCatching { headers.add(key, given.getString(key)) }+ }+ fun fromPage(name: String, fallback: String) = page?.optString(name)?.takeIf { it.isNotEmpty() } ?: fallback+ headers["User-Agent"] = fromPage("userAgent", userAgent)+ headers["Origin"] = "https://open.spotify.com"+ headers["Referer"] = "https://open.spotify.com/"+ if (headers["Accept"] == null) headers["Accept"] = "*/*"+ // RFC 9218: what Chromium sends with a fetch() from a page.+ if (headers["Priority"] == null) headers["Priority"] = "u=1, i"+ headers["Sec-Fetch-Site"] = "same-site"+ headers["Sec-Fetch-Mode"] = "cors"+ headers["Sec-Fetch-Dest"] = "empty"+ // Values taken from the page, not written by hand: whichever language and client hints it+ // presents, the relayed request presents the same.+ headers["Accept-Language"] = fromPage("acceptLanguage", language)+ headers["sec-ch-ua"] = fromPage("brands", secChUa)+ headers["sec-ch-ua-mobile"] = fromPage("mobile", "?0")+ headers["sec-ch-ua-platform"] = "\"${fromPage("platform", "Linux")}\""+ return headers.build()+ }private val COMMAND = Regex("/connect-state/v1/(player/command|connect/transfer)/")@@ -456,16 +693,29 @@ internal class ControlRelay(private val view: WebView, private val fingerprint:* The cluster without ids or names: each device's type, license, whether it may play and* take commands, which one is this player (`self`) and which one is active; then the* player state's restrictions that hold a reason. Null when the body is not a cluster.+ *+ * 402 diagnostics: whether the cluster holds a player state at all (the failing accounts'+ * clusters had none, 402-ANALYSIS fact 4), and what each other device is: `stale-own` when+ * it is the device the previous start left ([staleOwn], from PlayerDeviceRecord),+ * `foreign-webplayer` for another device running this player's software (an older ghost of+ * this app, or the user's own Web Player in a browser), else `foreign`.*/- internal fun clusterSummary(text: String, self: String?): String? = runCatching {+ internal fun clusterSummary(text: String, self: String?, staleOwn: String? = null): String? = runCatching {val j = JSONObject(text)val c = j.optJSONObject("cluster") ?: jval devices = c.optJSONObject("devices") ?: return nullval active = c.optString("active_device_id")+ val ownSoftware = self?.let { devices.optJSONObject(it)?.optString("device_software_version") }?.takeIf { it.isNotEmpty() }val list = devices.keys().asSequence().sortedBy { if (it == self) "" else it }.map { id ->val d = devices.optJSONObject(id) ?: JSONObject()val caps = d.optJSONObject("capabilities")- val marks = listOfNotNull("self".takeIf { id == self }, "active".takeIf { id == active && active.isNotEmpty() })+ val kind = when {+ id == self -> "self"+ staleOwn != null && id == staleOwn -> "stale-own"+ ownSoftware != null && d.optString("device_software_version") == ownSoftware -> "foreign-webplayer"+ else -> "foreign"+ }+ val marks = listOfNotNull(kind.takeIf { self != null || it != "foreign" }, "active".takeIf { id == active && active.isNotEmpty() })val facts = listOfNotNull(d.optString("device_type").ifEmpty { "?" },"license=${d.optString("license").ifEmpty { "-" }}",@@ -490,7 +740,16 @@ internal class ControlRelay(private val view: WebView, private val fingerprint:else "${k.removePrefix("disallow_").removeSuffix("_reasons")}=${(0 until reasons.length()).joinToString("|") { i -> reasons.optString(i) }}"}.joinToString(",")}.orEmpty()- ("devices=${list.size} active=$activeWhere self_listed=${self != null && devices.has(self)} " ++ val state = c.optJSONObject("player_state")+ val playerState = when {+ state == null || state.length() == 0 -> "absent"+ else -> {+ val context = state.optString("context_uri").split(':').getOrNull(1)?.takeIf { it.isNotEmpty() } ?: "none"+ val track = state.optJSONObject("track")?.optString("uri")?.isNotEmpty() == true+ "present(context=$context track=${if (track) "yes" else "no"} restrictions=${if (restrictions.isEmpty()) "none" else "some"})"+ }+ }+ ("devices=${list.size} active=$activeWhere self_listed=${self != null && devices.has(self)} player_state=$playerState " +list.joinToString("; ", "[", "]") +(if (restrictions.isNotEmpty()) " restrictions: $restrictions" else "")).take(700)}.getOrNull()diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/CronetStack.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/CronetStack.ktnew file mode 100644index 00000000..a0b39a29--- /dev/null+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/CronetStack.kt@@ -0,0 +1,110 @@+package app.myspoti.host.android++import android.content.Context+import okhttp3.Headers+import org.chromium.net.CronetEngine+import org.chromium.net.CronetException+import org.chromium.net.CronetProvider+import org.chromium.net.UploadDataProviders+import org.chromium.net.UrlRequest+import org.chromium.net.UrlResponseInfo+import java.io.ByteArrayOutputStream+import java.nio.ByteBuffer+import java.util.concurrent.Executors++/**+ * Cronet from Google Play services: the Chromium network stack for a refused relayed command+ * on Android 13 and older, where the platform has no [PlatformStack] (see RelayRoutes).+ *+ * The provider Play services installs adds a few hundred KB to the APK. The embedded Cronet+ * (org.chromium.net:cronet-embedded) needs no Play services but ships about 10 MB of native code+ * for the two ABIs this app is built for; a phone without Play services keeps OkHttp and the+ * other address family only.+ *+ * The request carries the relay's headers less Accept-Encoding: Chromium writes its own, as+ * Chrome does, and decodes what it asked for. No cookie: the real Web Player sends none to+ * spclient.+ */+internal object CronetStack {+ @Volatile private var engine: CronetEngine? = null+ @Volatile private var started = false++ /** What the stack is: "ready (<provider> <version>)", "unavailable: <why>", "starting"... */+ @Volatile var status: String = "not started"+ private set++ val available: Boolean get() = engine != null++ private val executor = Executors.newSingleThreadExecutor { r -> Thread(r, "relay-cronet").apply { isDaemon = true } }++ /** Installs the Play services provider in the background; [available] once it is there. */+ fun prepare(context: Context) {+ if (started || android.os.Build.VERSION.SDK_INT >= 34) return+ started = true+ status = "starting"+ val app = context.applicationContext+ runCatching {+ com.google.android.gms.net.CronetProviderInstaller.installProvider(app).addOnCompleteListener { task ->+ if (!task.isSuccessful) {+ status = "unavailable: ${task.exception?.javaClass?.simpleName ?: "no Google Play services"}"+ Logbook.log("relay: Cronet $status")+ return@addOnCompleteListener+ }+ runCatching {+ val provider = CronetProvider.getAllProviders(app)+ .firstOrNull { it.isEnabled && it.name != CronetProvider.PROVIDER_NAME_FALLBACK }+ ?: error("no native provider")+ engine = provider.createBuilder().enableHttp2(true).enableQuic(true).enableBrotli(true).build()+ status = "ready (${provider.name} ${provider.version})"+ }.onFailure { status = "unavailable: ${it.message}" }+ Logbook.log("relay: Cronet $status")+ }+ }.onFailure {+ status = "unavailable: ${it.message}"+ Logbook.log("relay: Cronet $status")+ }+ }++ fun fetch(+ url: String,+ method: String,+ headers: Headers,+ sent: String?,+ done: (code: Int, headers: List<Pair<String, String>>, text: String, protocol: String, error: String?) -> Unit,+ ) {+ val cronet = engine ?: return done(0, emptyList(), "", "", "Cronet $status")+ val out = ByteArrayOutputStream()+ val callback = object : UrlRequest.Callback() {+ override fun onRedirectReceived(request: UrlRequest, info: UrlResponseInfo, newLocationUrl: String) = request.followRedirect()++ override fun onResponseStarted(request: UrlRequest, info: UrlResponseInfo) = request.read(ByteBuffer.allocateDirect(32 * 1024))++ override fun onReadCompleted(request: UrlRequest, info: UrlResponseInfo, buffer: ByteBuffer) {+ buffer.flip()+ val bytes = ByteArray(buffer.remaining())+ buffer.get(bytes)+ out.write(bytes)+ buffer.clear()+ request.read(buffer)+ }++ override fun onSucceeded(request: UrlRequest, info: UrlResponseInfo) =+ done(info.httpStatusCode, info.allHeadersAsList.map { it.key to it.value }, out.toString(Charsets.UTF_8.name()), info.negotiatedProtocol, null)++ override fun onFailed(request: UrlRequest, info: UrlResponseInfo?, error: CronetException) =+ done(0, emptyList(), "", "", error.message ?: "failed")++ override fun onCanceled(request: UrlRequest, info: UrlResponseInfo?) = done(0, emptyList(), "", "", "canceled")+ }+ runCatching {+ val builder = cronet.newUrlRequestBuilder(url, callback, executor).setHttpMethod(method)+ headers.forEach { (name, value) -> if (!name.equals("Accept-Encoding", true)) builder.addHeader(name, value) }+ if (method != "GET" && method != "HEAD") {+ // Cronet refuses a body without a type: the one a browser's fetch gives a string body.+ if (headers["Content-Type"] == null) builder.addHeader("Content-Type", "text/plain;charset=UTF-8")+ builder.setUploadDataProvider(UploadDataProviders.create((sent ?: "").toByteArray()), executor)+ }+ builder.build().start()+ }.onFailure { done(0, emptyList(), "", "", it.message ?: "not sent") }+ }+}diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/Fingerprint.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/Fingerprint.ktindex 91fcc848..64134ac6 100644--- a/base/host-android/src/main/kotlin/app/myspoti/host/android/Fingerprint.kt+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/Fingerprint.kt@@ -147,7 +147,11 @@ internal data class Fingerprint(val major: Int, val build: Int, val patch: Int,file.writeText(JSONObject().put("lag", draw.lag).put("patch", draw.patch).put("kernel", draw.kernel).toString())}}- return resolve(engine, draw)+ // The WebView's own major, whatever lag was drawn: the page's requests leave through that+ // WebView's network stack (and the relay's Chromium routes come from the same family), so a+ // user agent one or two releases behind it ("Chrome/154" on WebView 155) contradicts the+ // TLS and HTTP/2 shape under it. The draw keeps its lag on disk, unused.+ return resolve(engine, draw.copy(lag = 0))}}}diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/Logbook.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/Logbook.ktindex 77188993..5c13b46a 100644--- a/base/host-android/src/main/kotlin/app/myspoti/host/android/Logbook.kt+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/Logbook.kt@@ -40,6 +40,26 @@ object Logbook {}}+ /** When each [logEvery] key last wrote, and how many lines it held back since. */+ private val every = HashMap<String, LongArray>()++ /**+ * [line] at most once per [intervalMs] for [key]: a steady stream (play reports, state PUTs+ * answered 2xx) shows that it runs and how often, without filling the ring buffer. The next+ * line written says how many were held back.+ */+ fun logEvery(key: String, intervalMs: Long, line: String) {+ val now = android.os.SystemClock.elapsedRealtime()+ val held = synchronized(every) {+ val e = every.getOrPut(key) { longArrayOf(Long.MIN_VALUE / 2, 0) }+ if (now - e[0] < intervalMs) { e[1]++; return }+ val n = e[1]+ e[0] = now; e[1] = 0+ n+ }+ log(if (held > 0) "$line (+$held like it since)" else line)+ }+/*** What the report's header says of this session, kept apart from the log (which may have cut* the line long ago): the account, the network, the devices, the registration... Set from@@ -68,6 +88,46 @@ object Logbook {return file}+ /**+ * What the device's Widevine is (security level, HDCP, version): a 403 on the audio licence+ * (seen on a new sign-in, Android 11) or a silent stream cannot be told from the log alone.+ * Read once; a MediaDrm failure is itself the answer.+ */+ private val drmFact: String? by lazy {+ runCatching {+ val drm = android.media.MediaDrm(java.util.UUID.fromString("edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"))+ try {+ fun p(k: String) = runCatching { drm.getPropertyString(k) }.getOrNull() ?: "?"+ "widevine ${p("version")} level=${p("securityLevel")} hdcp=${p("hdcpLevel")}/${p("maxHdcpLevel")} vendor=${p("vendor")} algorithms=${p("algorithms")}"+ } finally { if (android.os.Build.VERSION.SDK_INT >= 28) drm.close() else @Suppress("DEPRECATION") drm.release() }+ }.getOrElse { "MediaDrm failed: ${it.javaClass.simpleName} ${it.message?.take(80)}" }+ }++ /** Where the sound goes: a silent music volume or a route to a sink that makes none reads as "plays, no sound". */+ private fun audioDetails(context: Context): String? = runCatching {+ val am = context.getSystemService(Context.AUDIO_SERVICE) as android.media.AudioManager+ val outs = am.getDevices(android.media.AudioManager.GET_DEVICES_OUTPUTS).joinToString(",") { it.type.toString() }+ val v = am.getStreamVolume(android.media.AudioManager.STREAM_MUSIC)+ val max = am.getStreamMaxVolume(android.media.AudioManager.STREAM_MUSIC)+ "music volume $v/$max muted=${am.isStreamMute(android.media.AudioManager.STREAM_MUSIC)} mode=${am.mode} output types=$outs"+ }.getOrNull()++ /** The lines the 402 analyses read: refusals, the matrix, registration, clusters, licences, routes, ads. */+ private val RELEVANT_402 = Regex("""(?i)refus|\b402\b|registration|cluster:|licence|command headers|commands from the page|relay route|relay: |audio after|ad break|page ready|connect/transfer|previous player device""")+ private const val RELEVANT_LINES = 50++ /** An age in coarse buckets: never a date. */+ internal fun ageBucket(ms: Long): String {+ val days = ms / 86_400_000L+ return when {+ days < 1 -> "<1 d ago"+ days < 7 -> "1-7 d ago"+ days < 30 -> "7-30 d ago"+ days < 180 -> "1-6 months ago"+ else -> ">6 months ago"+ }+ }+private val FACT_ORDER = listOf("account", "network", "registration", "devices", "relay route")private fun report(context: Context): String {@@ -92,12 +152,26 @@ object Logbook {for (key in FACT_ORDER) facts[key]?.let { add(key to it) }facts.keys.filter { it !in FACT_ORDER }.sorted().forEach { add(it to facts.getValue(it)) }add("widevine" to (widevine ?: facts["widevine"] ?: "not reported missing"))+ drmFact?.let { add("drm" to it) }+ audioDetails(context)?.let { add("audio" to it) }runCatching { headerExtras?.invoke() }.getOrNull()?.let { addAll(it) }}+ val installAge = info?.firstInstallTime?.let { ageBucket(System.currentTimeMillis() - it) }+ val summary = app.myspoti.spotify.report.Refusal402.summary(facts["account"], installAge)// Masked and cut down (DiagnosticDigest): small enough to paste, nothing that opens an account.return buildString {appendLine("Myspoti diagnostic report")+ // The 402 questions answered in one screen (Refusal402), before anything else.+ appendLine("--- 402 summary ---")+ summary.forEach { (k, v) -> appendLine("${k.padEnd(12)}: ${app.myspoti.spotify.report.DiagnosticDigest.mask(v)}") }+ appendLine()header.forEach { (k, v) -> appendLine("${k.padEnd(12)}: ${app.myspoti.spotify.report.DiagnosticDigest.mask(v)}") }+ val relevant = tail.filter { RELEVANT_402.containsMatchIn(it.drop(13)) }.takeLast(RELEVANT_LINES)+ if (relevant.isNotEmpty()) {+ appendLine()+ appendLine("--- 402 lines (last $RELEVANT_LINES) ---")+ relevant.forEach { appendLine(app.myspoti.spotify.report.DiagnosticDigest.mask(it).take(400)) }+ }appendLine()appendLine("--- log ---")append(app.myspoti.spotify.report.DiagnosticDigest.digest(tail))diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/PlatformStack.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/PlatformStack.ktindex f485221d..fb72e31c 100644--- a/base/host-android/src/main/kotlin/app/myspoti/host/android/PlatformStack.kt+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/PlatformStack.kt@@ -15,13 +15,13 @@ import java.util.concurrent.Executors/*** The platform's own HTTP stack (android.net.http, Cronet in the system since Android 14): the- * last way a refused relayed command is sent (see RelayRoutes). Chromium's network stack, like- * the WebView's, without a new dependency.+ * first way a refused relayed command is sent again (see RelayRoutes). Chromium's network stack,+ * like the WebView's, without a new dependency.*- * The request carries exactly the headers the OkHttp relay sends, built in the same place; this- * stack adds no "X-Requested-With" (that header is the WebView's own), only its transport headers- * (Accept-Encoding, which it also decodes). The WebView's cookies are added by hand: this stack- * has no cookie jar of its own.+ * The request carries the headers the OkHttp relay sends, built in the same place, less+ * Accept-Encoding: this stack writes its own, as Chrome does, and decodes what it asked for. It+ * adds no "X-Requested-With" (that header is the WebView's own) and no cookie: the real Web+ * Player sends none to spclient.*//** A body from memory (the platform has no ready-made one). */@RequiresApi(34)@@ -46,7 +46,7 @@ internal object PlatformStack {private val executor = Executors.newSingleThreadExecutor { r -> Thread(r, "relay-platform").apply { isDaemon = true } }private fun engine(context: Context): HttpEngine =- engine ?: synchronized(this) { engine ?: HttpEngine.Builder(context).build().also { engine = it } }+ engine ?: synchronized(this) { engine ?: HttpEngine.Builder(context).setEnableBrotli(true).build().also { engine = it } }fun fetch(context: Context,@@ -81,8 +81,7 @@ internal object PlatformStack {}runCatching {val builder = engine(context).newUrlRequestBuilder(url, executor, callback).setHttpMethod(method)- headers.forEach { (name, value) -> builder.addHeader(name, value) }- android.webkit.CookieManager.getInstance().getCookie(url)?.takeIf { it.isNotBlank() }?.let { builder.addHeader("Cookie", it) }+ headers.forEach { (name, value) -> if (!name.equals("Accept-Encoding", true)) builder.addHeader(name, value) }if (method != "GET" && method != "HEAD") {// This stack refuses a body without a type: the one a browser's fetch gives a string body.if (headers["Content-Type"] == null) builder.addHeader("Content-Type", "text/plain;charset=UTF-8")diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/PlaybackService.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/PlaybackService.ktindex 7914aadc..7cb734ff 100644--- a/base/host-android/src/main/kotlin/app/myspoti/host/android/PlaybackService.kt+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/PlaybackService.kt@@ -141,6 +141,7 @@ class PlaybackService : MediaBrowserServiceCompat() {override fun onDestroy() {instance = null+ holdLocks(false)session.release()scope.cancel()super.onDestroy()@@ -300,8 +301,36 @@ class PlaybackService : MediaBrowserServiceCompat() {}}+ private var cpuLock: android.os.PowerManager.WakeLock? = null+ private var wifiLock: android.net.wifi.WifiManager.WifiLock? = null++ /**+ * Keeps the CPU and the Wi-Fi radio awake while a song plays: with the screen off the page's+ * timers and the audio downloads stalled in doze-like power saving. The timeout is only a+ * safety net against a lock leaked by a missed pause; every state refresh renews it.+ */+ @android.annotation.SuppressLint("WakelockTimeout")+ private fun holdLocks(on: Boolean) {+ runCatching {+ if (on) {+ val cpu = cpuLock ?: getSystemService(android.os.PowerManager::class.java)+ .newWakeLock(android.os.PowerManager.PARTIAL_WAKE_LOCK, "Myspoti:playback")+ .apply { setReferenceCounted(false) }.also { cpuLock = it }+ cpu.acquire(LOCK_TIMEOUT_MS)+ val wifi = wifiLock ?: applicationContext.getSystemService(android.net.wifi.WifiManager::class.java)+ .createWifiLock(android.net.wifi.WifiManager.WIFI_MODE_FULL_HIGH_PERF, "Myspoti:playback")+ .apply { setReferenceCounted(false) }.also { wifiLock = it }+ if (!wifi.isHeld) wifi.acquire()+ } else {+ cpuLock?.takeIf { it.isHeld }?.release()+ wifiLock?.takeIf { it.isHeld }?.release()+ }+ }+ }+private fun show(info: NowPlayingInfo) {val notification = build(info)+ holdLocks(info.playing || info.buffering)if (info.playing || info.buffering) {handler.removeCallbacks(leaveForeground)startForegroundSafely(notification)@@ -451,6 +480,7 @@ class PlaybackService : MediaBrowserServiceCompat() {/** Time left to the pause's fade-out before the notification goes. */private const val CLOSE_STOP_MS = 800Lprivate const val CLOSE_PREFS = "playback_service"+ private const val LOCK_TIMEOUT_MS = 6 * 60 * 60 * 1000Lprivate const val KEEP_PLAYING_KEY = "keep_playing_on_close"/** The music goes on when the app is closed from the recent apps (off: it stops). */diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/PlayerDeviceRecord.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/PlayerDeviceRecord.ktnew file mode 100644index 00000000..7468ed2a--- /dev/null+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/PlayerDeviceRecord.kt@@ -0,0 +1,110 @@+package app.myspoti.host.android++import org.json.JSONObject+import java.io.File++/**+ * The playback device the last page registered, kept across app starts so the next page can+ * take it off the account.+ *+ * The Web Player creates its harmony player with `randomizeId: true`: every page load registers+ * a brand-new device id (the `_spharmony_device_id` key in localStorage is skipped in that case),+ * and only says goodbye (`DELETE /track-playback/v1/devices/{id}`) from its unload handler. An+ * app swiped away or killed never runs it, so the old device stays in the account's cluster for+ * the registration's keep-alive (6 h), an idle COMPUTER next to the new one. On some free+ * accounts Spotify then refuses the commands with 402.+ *+ * When a new page registers, the previous id gets the same DELETE the page would have sent,+ * with the next sequence number of that device and no playback state.+ */+internal class PlayerDeviceRecord(private val file: File) {+ @Volatile private var id: String? = null+ @Volatile private var seq: Long = 0+ private var loaded = false++ @Synchronized private fun load() {+ if (loaded) return+ loaded = true+ runCatching { JSONObject(file.readText()) }.getOrNull()?.let {+ id = it.optString("id").takeIf { s -> s.isNotEmpty() }+ seq = it.optLong("seq", 0)+ }+ }++ @Synchronized private fun save() = runCatching {+ val current = id+ if (current == null) file.delete()+ else {+ file.parentFile?.mkdirs()+ file.writeText(JSONObject().put("id", current).put("seq", seq).toString())+ }+ }++ /**+ * A new page registers [newId]: returns the id of the device the previous page left, if any,+ * with the sequence number its goodbye carries, and keeps the new one.+ */+ @Synchronized fun registering(newId: String): Pair<String, Long>? {+ load()+ val previous = id?.takeIf { it != newId }?.let { it to seq + 1 }+ if (previous != null || id == null) {+ id = newId+ seq = 0+ save()+ }+ return previous+ }++ /** The registration's answer: the device's sequence numbers start at [initialSeq]. */+ @Synchronized fun answered(initialSeq: Long) {+ load()+ if (id != null && initialSeq > seq) {+ seq = initialSeq+ save()+ }+ }++ /** A request the page sent for its device: its sequence numbers move on. */+ @Synchronized fun sent(url: String, body: String?) {+ load()+ val current = id ?: return+ if (body == null || !url.substringBefore('?').contains("/track-playback/v1/devices/$current")) return+ val highest = highestSeq(body) ?: return+ if (highest > seq) {+ seq = highest+ save()+ }+ }++ /** The page took its own device off (its unload handler ran): nothing left to clean. */+ @Synchronized fun deregistered(url: String) {+ load()+ val current = id ?: return+ if (url.substringBefore('?').endsWith("/track-playback/v1/devices/$current")) {+ id = null+ save()+ }+ }++ companion object {+ internal fun highestSeq(body: String): Long? = runCatching {+ val j = JSONObject(body)+ val nums = j.optJSONArray("seq_nums")+ val all = listOfNotNull(j.opt("seq_num") as? Number) ++ (0 until (nums?.length() ?: 0)).mapNotNull { nums?.opt(it) as? Number }+ all.maxOfOrNull { it.toLong() }+ }.getOrNull()++ /** The goodbye the page sends on unload, without a playback state (the old page is gone). */+ internal fun goodbye(seq: Long): String = JSONObject()+ .put("seq_num", seq)+ .put("state_ref", JSONObject.NULL)+ .put("sub_state", JSONObject().put("playback_speed", 0).put("position", 0).put("duration", 0))+ .put("previous_position", 0)+ .put("debug_source", "deregister")+ .toString()++ /** `https://host/track-playback/v1/devices` + `/id`. */+ internal fun deviceUrl(registrationUrl: String, id: String) = registrationUrl.substringBefore('?').trimEnd('/') + "/" + id+ }+}diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/WebPlayerHost.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/WebPlayerHost.ktindex b35802aa..1c815f95 100644--- a/base/host-android/src/main/kotlin/app/myspoti/host/android/WebPlayerHost.kt+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/WebPlayerHost.kt@@ -53,6 +53,8 @@ class WebPlayerHost(private val context: Context) : BridgeHost {* (reload, replay) asked again. A storm of them ends playback here for a while (growing on* repeats) instead of feeding it; [licenseLimitedUntil] tells the app and the player.*/+ @Volatile private var heldLicenses = 0+ @Volatile private var licenseAnswersLogged = 0private val license429 = ArrayDeque<Long>()private var limitStreak = 0private var lastLimitAt = 0L@@ -72,6 +74,7 @@ class WebPlayerHost(private val context: Context) : BridgeHost {limitStreak++license429.clear()Logbook.log("Spotify is limiting audio licences (429 x$LIMIT_COUNT in ${LIMIT_WINDOW_MS / 1000} s): playback held ${hold / 1000} s")+ heldLicenses = 0_licenseLimitedUntil.value = now + hold}@@ -169,8 +172,12 @@ class WebPlayerHost(private val context: Context) : BridgeHost {webChromeClient = object : WebChromeClient() {override fun onConsoleMessage(message: android.webkit.ConsoleMessage): Boolean {if (message.messageLevel() == android.webkit.ConsoleMessage.MessageLevel.ERROR ||- message.messageLevel() == android.webkit.ConsoleMessage.MessageLevel.WARNING)- Logbook.log("console ${message.messageLevel()}: ${message.message().take(300)}")+ message.messageLevel() == android.webkit.ConsoleMessage.MessageLevel.WARNING) {+ // The page's steady console noise (font preloads, storage access refused on+ // every load) never helped a report: left out.+ if (CONSOLE_NOISE.none { it.containsMatchIn(message.message()) })+ Logbook.log("console ${message.messageLevel()}: ${message.message().take(300)}")+ }return true}@@ -189,6 +196,16 @@ class WebPlayerHost(private val context: Context) : BridgeHost {// Refused like a blocked request: the player reports a failed ad and moves on.return WebResourceResponse("text/plain", "utf-8", 403, "Blocked", emptyMap(), ByteArrayInputStream(ByteArray(0)))}+ // Spotify is limiting audio licences (429) and the app holds playback: the page still+ // skips on by itself through every song it gets no licence for (measured in the 25/10+ // logs: 20 to 25 more licence requests in the 4 s after the hold began, ~4 a second,+ // every one answered 429). Those are not sent: the page gets the same 429 from here+ // and Spotify sees no more of them while the hold lasts.+ if (request.method == "POST" && licenseLimited() && url.contains(LICENSE_PATH)) {+ if (heldLicenses++ == 0) Logbook.log("audio licence requests answered here while Spotify is limiting")+ app.myspoti.spotify.report.Refusal402.licenceHeld()+ return WebResourceResponse("application/octet-stream", "utf-8", 429, "Too Many Requests", emptyMap(), ByteArrayInputStream(ByteArray(0)))+ }// The sign-in flow lives on accounts.spotify.com: logging its steps is what turns// "the login is stuck" into the exact request that failed (with the status from// onReceivedHttpError below). Reported as B37 and unprovable without this trail.@@ -219,7 +236,7 @@ class WebPlayerHost(private val context: Context) : BridgeHost {pageStarts++_url.value = url_loginRequired.value = isLoginPage(url)- if (url.startsWith(PLAYER_URL)) { drmAsked = false; onPageStarting?.invoke(); relay.injectNow() }+ if (url.startsWith(PLAYER_URL)) { drmAsked = false; licenseAnswersLogged = 0; onPageStarting?.invoke(); relay.injectNow() }if (PLAYER_ROOT.matches(url) && url != roots.getString(ROOT_KEY, null)) roots.edit().putString(ROOT_KEY, url).apply()}@@ -232,11 +249,26 @@ class WebPlayerHost(private val context: Context) : BridgeHost {}override fun onReceivedHttpError(view: WebView, request: WebResourceRequest, response: WebResourceResponse) {- if (request.url.host?.contains("spotify") == true)- Logbook.log("http ${response.statusCode} ${request.method} ${request.url.toString().substringBefore('?').take(120)}")+ // Licence answers are counted in the 402 summary and their first ones logged below+ // with their headers; the same 429 three times per song was the bulk of some reports.+ if (request.url.host?.contains("spotify") == true && request.url.path?.contains("widevine-license") != true)+ Logbook.logEvery("http ${response.statusCode} ${request.url.host}${request.url.path}", 60_000,+ "http ${response.statusCode} ${request.method} ${request.url.toString().substringBefore('?').take(120)}")if (request.isForMainFrame && request.url.host == PLAYER_HOST && (response.statusCode >= 500 || response.statusCode == 429))playerPageFailed("http ${response.statusCode}")- if (response.statusCode == 429 && request.url.path?.contains("widevine-license") == true) onLicenseLimited()+ if (request.url.path?.contains("widevine-license") == true) {+ if (response.statusCode == 429) onLicenseLimited()+ response.responseHeaders.entries.firstOrNull { it.key.equals("retry-after", true) }+ ?.let { app.myspoti.spotify.report.Refusal402.licenceRetryAfter(it.value) }+ // A refused licence (403 seen on a new sign-in, 429 on others) says why in its+ // headers at best; nothing else of the answer reaches the app. A few per page.+ if (response.statusCode >= 400 && licenseAnswersLogged++ < LICENSE_ANSWERS_LOGGED) {+ val h = response.responseHeaders.entries+ .filter { (k, _) -> k.lowercase() in LICENSE_HEADERS }+ .joinToString(", ") { (k, v) -> "${k.lowercase()}=${v.take(60)}" }+ Logbook.log("licence answer ${response.statusCode}: $h")+ }+ }}override fun onPageFinished(view: WebView, url: String) {@@ -525,6 +557,10 @@ class WebPlayerHost(private val context: Context) : BridgeHost {private const val DRM_WATCH_MS = 10_000Lprivate const val DRM_REBUILDS_MAX = 2private const val DRM_REBUILD_WINDOW_MS = 600_000L+ private const val LICENSE_PATH = "/widevine-license/v1/audio/license"+ private const val LICENSE_ANSWERS_LOGGED = 6+ private val CONSOLE_NOISE = listOf(Regex("^The resource .* was preloaded"), Regex("^requestStorageAccess: Permission denied"))+ private val LICENSE_HEADERS = setOf("retry-after", "content-type", "server", "via", "x-ratelimit-remaining", "x-ratelimit-reset", "cf-ray", "x-envoy-upstream-service-time")private const val LIMIT_COUNT = 6private const val LIMIT_WINDOW_MS = 10_000Lprivate const val LIMIT_HOLD_MS = 60_000Ldiff --git a/base/host-android/src/test/kotlin/app/myspoti/host/android/ControlRelayTest.kt b/base/host-android/src/test/kotlin/app/myspoti/host/android/ControlRelayTest.ktindex bcb775a6..217aca32 100644--- a/base/host-android/src/test/kotlin/app/myspoti/host/android/ControlRelayTest.kt+++ b/base/host-android/src/test/kotlin/app/myspoti/host/android/ControlRelayTest.kt@@ -54,12 +54,96 @@ class ControlRelayTest {"player_state":{"restrictions":{"disallow_resuming_reasons":["not_paused"],"disallow_seeking_reasons":[]}}}""",self,)!!- assertTrue(s, s.startsWith("devices=2 active=other self_listed=true [self COMPUTER license=tft can_play=true controllable=true player=true; active SMARTPHONE license=mft"))+ assertTrue(s, s.startsWith("devices=2 active=other self_listed=true player_state=present(context=none track=no restrictions=some) " ++ "[self COMPUTER license=tft can_play=true controllable=true player=true; foreign active SMARTPHONE license=mft"))assertTrue(s, s.contains("Spotify 9.0.1"))assertTrue(s, s.endsWith("restrictions: resuming=not_paused"))assertFalse(s, s.contains(self) || s.contains(other) || s.contains("Alex") || s.contains("Pixel") || s.contains("1.2.3.4"))}+ // The failing accounts' clusters held no player state; a second device is told apart as the+ // one this app's previous start left, another Web Player, or something else.+ @Test fun `the cluster says whether it has a player state and what the other devices are`() {+ val self = "a".repeat(40)+ val ghost = "c".repeat(40)+ val older = "d".repeat(40)+ val phone = "e".repeat(40)+ val s = ControlRelay.clusterSummary(+ """{"devices":{+ "$self":{"device_type":"COMPUTER","license":"tft","device_software_version":"harmony:4.81.1"},+ "$ghost":{"device_type":"COMPUTER","license":"tft","device_software_version":"harmony:4.81.1"},+ "$older":{"device_type":"COMPUTER","license":"tft","device_software_version":"harmony:4.81.1"},+ "$phone":{"device_type":"SMARTPHONE","license":"tft","device_software_version":"Spotify 9.0.1"}}}""",+ self,+ ghost,+ )!!+ assertTrue(s, s.startsWith("devices=4 active=none self_listed=true player_state=absent [self COMPUTER"))+ assertTrue(s, s.contains("; stale-own COMPUTER") && s.contains("; foreign-webplayer COMPUTER") && s.contains("; foreign SMARTPHONE"))+ assertFalse(s, listOf(self, ghost, older, phone).any { s.contains(it) })+ val playing = ControlRelay.clusterSummary(+ """{"devices":{"$self":{}},"player_state":{"context_uri":"spotify:playlist:secret","track":{"uri":"spotify:track:secret"}}}""",+ self,+ )!!+ assertTrue(playing, playing.contains("player_state=present(context=playlist track=yes restrictions=none)"))+ assertFalse(playing, playing.contains("secret"))+ }++ @Test fun `the 402 summary's cluster counts types and kinds without ids`() {+ val self = "a".repeat(40)+ val ghost = "c".repeat(40)+ val phone = "e".repeat(40)+ val b = ControlRelay.clusterBrief(+ """{"devices":{+ "$self":{"device_type":"COMPUTER","device_software_version":"harmony:4.81.1"},+ "$ghost":{"device_type":"COMPUTER","device_software_version":"harmony:4.81.1"},+ "$phone":{"device_type":"SMARTPHONE","device_software_version":"Spotify 9.0.1"}},+ "player_state":{"context_uri":"spotify:album:secret","restrictions":{"disallow_pausing_reasons":["already_paused"]}}}""",+ self,+ ghost,+ )!!+ assertEquals("devices=3 types=COMPUTER×2,SMARTPHONE×1 kinds=foreign×1,self×1,stale-own×1 active=none " ++ "player_state=present(context=album track=no restrictions=some)", b)+ assertNull(ControlRelay.clusterBrief("""{"ack_id":"x"}""", null, null))+ }++ @Test fun `a command's kind is its endpoint or transfer`() {+ assertEquals("transfer", ControlRelay.commandKind("https://x.spotify.com/connect-state/v1/connect/transfer/from/a/to/b", "{}"))+ assertEquals("seek_to", ControlRelay.commandKind("https://x.spotify.com/connect-state/v1/player/command/from/a/to/b", """{"command":{"endpoint":"seek_to"}}"""))+ assertEquals("command", ControlRelay.commandKind("https://x.spotify.com/connect-state/v1/player/command/from/a/to/b", "not json"))+ }++ // Request parity (402 on some free accounts): a relayed command carries the header set desktop+ // Chrome's carries, with Chrome's values for what the page cannot set, and no cookie.+ @Test fun `a relayed command carries the headers of Chrome's own`() {+ val chrome = javaClass.getResource("/chrome-command-headers.txt")!!.readText().lines()+ .filter { it.isNotBlank() && !it.startsWith("#") }+ .associate { it.substringBefore('=') to it.substringAfter('=') }+ // What the page's fetch hands the relay for a command (the "command headers" log line).+ val given = org.json.JSONObject(+ """{"authorization":"Bearer t","client-token":"c","app-platform":"WebPlayer","spotify-app-version":"1.2.3","content-type":"application/json","Cookie":"sp_dc=x","X-Requested-With":"app.myspoti"}""",+ )+ val page = org.json.JSONObject(+ """{"userAgent":"Mozilla/5.0 (X11; Linux x86_64) Chrome/155.0.0.0","brands":"\"Chromium\";v=\"155\"","mobile":"?0","platform":"Linux","acceptLanguage":"fr-CH,fr;q=0.9"}""",+ )+ val h = ControlRelay.relayHeaders(given, page, "fallback", "en", "fallback")+ // OkHttp adds Content-Length for the body, the decoding interceptor Accept-Encoding.+ val sent = (h.names().map { it.lowercase() } + "content-length" + "accept-encoding").toSortedSet()+ assertEquals(chrome.getValue("names").split(',').toSortedSet(), sent)+ assertNull(h["Cookie"])+ assertNull(h["X-Requested-With"])+ listOf("accept", "priority", "origin", "referer", "sec-fetch-site", "sec-fetch-mode", "sec-fetch-dest", "sec-ch-ua-mobile", "sec-ch-ua-platform")+ .forEach { name -> assertEquals(name, chrome.getValue(name), h[name]) }+ assertEquals(chrome.getValue("accept-encoding"), ControlRelay.ACCEPT_ENCODING)+ assertEquals(ControlRelay.ACCEPT_ENCODING, ControlRelay.DECODERS.joinToString(", ") { it.encoding })+ assertEquals("fr-CH,fr;q=0.9", h["Accept-Language"])+ }++ @Test fun `the page's own Accept is kept`() {+ val h = ControlRelay.relayHeaders(org.json.JSONObject("""{"Accept":"application/json"}"""), null, "ua", "en", "b")+ assertEquals("application/json", h["accept"])+ assertEquals("ua", h["User-Agent"])+ }+@Test fun `a body that is not a cluster says nothing`() {assertNull(ControlRelay.clusterSummary("""{"ack_id":"x"}""", null))assertNull(ControlRelay.clusterSummary("not json", null))diff --git a/base/host-android/src/test/kotlin/app/myspoti/host/android/PlayerDeviceRecordTest.kt b/base/host-android/src/test/kotlin/app/myspoti/host/android/PlayerDeviceRecordTest.ktnew file mode 100644index 00000000..83b6047c--- /dev/null+++ b/base/host-android/src/test/kotlin/app/myspoti/host/android/PlayerDeviceRecordTest.kt@@ -0,0 +1,46 @@+package app.myspoti.host.android++import org.json.JSONObject+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNull+import org.junit.Test+import java.io.File++class PlayerDeviceRecordTest {+ private val base = "https://gew4-spclient.spotify.com/track-playback/v1/devices"++ private fun file() = File.createTempFile("player-device", ".json").apply { delete(); deleteOnExit() }++ @Test fun `the first page has nothing to clean`() {+ assertNull(PlayerDeviceRecord(file()).registering("a"))+ }++ // A page killed before its unload handler: the next start says its goodbye, with the next sequence number.+ @Test fun `the device a killed page left is named at the next start`() {+ val f = file()+ PlayerDeviceRecord(f).apply {+ registering("a")+ answered(1)+ sent("$base/a/state", """{"seq_num":4,"state_ref":null}""")+ sent("$base/a/state_conflict", """{"seq_nums":[5,6]}""")+ sent("$base/b/state", """{"seq_num":90}""")+ }+ val next = PlayerDeviceRecord(f)+ assertEquals("a" to 7L, next.registering("b"))+ assertNull(PlayerDeviceRecord(f).registering("b"))+ }++ @Test fun `a page that said goodbye itself leaves nothing`() {+ val f = file()+ PlayerDeviceRecord(f).apply { registering("a"); deregistered("$base/a") }+ assertNull(PlayerDeviceRecord(f).registering("b"))+ }++ @Test fun `the goodbye is the page's deregistration without a state`() {+ val j = JSONObject(PlayerDeviceRecord.goodbye(3))+ assertEquals(3, j.getInt("seq_num"))+ assertEquals(JSONObject.NULL, j.get("state_ref"))+ assertEquals("deregister", j.getString("debug_source"))+ assertEquals("$base/x", PlayerDeviceRecord.deviceUrl("$base?product=0", "x"))+ }+}diff --git a/base/host-android/src/test/resources/chrome-command-headers.txt b/base/host-android/src/test/resources/chrome-command-headers.txtnew file mode 100644index 00000000..0384aec1--- /dev/null+++ b/base/host-android/src/test/resources/chrome-command-headers.txt@@ -0,0 +1,14 @@+# Desktop Chrome 155 on Linux, POST https://<spclient>/connect-state/v1/player/command/from/<id>/to/<id>+# (the 02-playback capture, 2026-10). Header names without the HTTP/2 pseudo-headers, and the values+# that carry no account data. No token, no id, no cookie: the request has no cookie header at all.+names=accept,accept-encoding,accept-language,app-platform,authorization,client-token,content-length,content-type,origin,priority,referer,sec-ch-ua,sec-ch-ua-mobile,sec-ch-ua-platform,sec-fetch-dest,sec-fetch-mode,sec-fetch-site,spotify-app-version,user-agent+accept=*/*+accept-encoding=gzip, deflate, br, zstd+priority=u=1, i+origin=https://open.spotify.com+referer=https://open.spotify.com/+sec-fetch-site=same-site+sec-fetch-mode=cors+sec-fetch-dest=empty+sec-ch-ua-mobile=?0+sec-ch-ua-platform="Linux"diff --git a/base/licenses/Apache-2.0.txt b/base/licenses/Apache-2.0.txtnew file mode 100644index 00000000..d6456956--- /dev/null+++ b/base/licenses/Apache-2.0.txt@@ -0,0 +1,202 @@++ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++ Copyright [yyyy] [name of copyright owner]++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.diff --git a/base/licenses/Inter-OFL.txt b/base/licenses/Inter-OFL.txtnew file mode 100644index 00000000..21f6aff9--- /dev/null+++ b/base/licenses/Inter-OFL.txt@@ -0,0 +1,93 @@+Copyright 2020 The Inter Project Authors (https://github.com/rsms/inter)++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+https://scripts.sil.org/OFL+++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.