Native Android client for Spotify, built with Jetpack Compose
Kotlin ad-freeadblockandroidjetpack-composekotlinlyricsmusic-playermusic-videomyspotispotifyspotify-adblockerspotify-clientspotify-connectspotui
2.1.0: stable release of the 2.0.2 betas with the Immersive look and its pages, extensions for audio and download sources, Spotify Connect and Spotify counting for songs played by extensions (muted low-quality mirror, can be turned off), one accent colour and settings per look, Immersive shuffle with smart shuffle, search plays continuing with related songs, radio header and album links, wider back and profile buttons, better ad blocking, faster pages with caches, new onboarding with extensions, more languages
kota-zo320ba2a8fef4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 46a9a54d..95441980 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,25 @@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.1.0++The first stable release since 2.0.1, with everything from the 2.0.2 betas (their notes are below) and more.++- ✨ **New Immersive look** (optional, Apple-Music-like): Liquid Glass bars that fold away when you scroll, animated player and lyrics, glass sheets, and its own pages for albums, folders, local playlists, extensions and podcast episodes. Switch in Settings, Display; Classic stays the default. Each look keeps its own **accent colour** and shows only its own settings.+- 🧩 **Extensions**: audio and download sources are extensions now, ordered as you like with Spotify among them, found on GitHub, GitLab and Codeberg. Safer: public hosts only, new permissions need your OK, a crash no longer takes the app down.+- 📱 **Spotify Connect with extension sources**: when an extension plays a Spotify song, the phone stays a Connect device. The official Spotify apps and your other devices see it and control it, and the song counts on Spotify through a real muted play at low quality. Turn it off in Settings if you prefer to save data and battery.+- 📊 **Plays count on Spotify**, Recents included. **Listening stats** and **friend activity**.+- 👥 **Collaborative playlists**: leave one, or manage it as the owner.+- 🚫 **Fewer "Spotify refused to play this"** (402) and no songs skipping on their own; better ad blocking (more ad hosts, ads found by their metadata, reloads that stay silent).+- 🔀 **Shuffle in Immersive** goes through shuffle, smart shuffle and off, as in Classic.+- 🔎 **A song played from search** goes on with related songs, no longer with your Liked Songs.+- 📻 **Radios**: the playing-from header and the song title open the right page and album.+- 👋 **New onboarding**: how Myspoti works, then what extensions are and where to find them (shown once after the update too).+- 👆 **Easier taps**: wider back and profile buttons, and the glass bars no longer let taps through to the page.+- 🎧 **Headphones and car**: 15 s skips for podcasts, Android Auto that keeps playing, background playback that keeps running.+- ⚡ **Faster and lighter**: pages and Liked Songs kept on the phone, cached lyrics and searches, a smaller image cache, smoother lists and animations, Remove animations honoured everywhere.+- 🌍 **More languages**: Chinese, Russian, Polish, Turkish, Indonesian, and Spanish for Argentina and Mexico.+## 2.0.2-beta.8- 🎚️ **Source order** (Settings, Playback and Downloads): put your audio and download sources in the order you want; each song is asked from top to bottom. Spotify has its own place too, first if you like. Each source shows only what matters, details on a tap. Installing a second source no longer clashes with the first.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 05fd42c1..fb968460 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@@ -93,6 +93,16 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop* then): asked again when the ad is over (see [onState]).*/@Volatile private var pickBeforeAd: Pick? = null+ /**+ * A pick before an ad whose break ended in a reload of ours: played on the new page, however+ * long the reload took (it is the user's), unless they played or skipped something since.+ */+ @Volatile private var pickAfterReload: Pick? = null+ /**+ * The page was reloaded to get past an ad: the new page stays muted until a real song plays+ * (it can start on an ad before its state says so). See [muteForAd] / [onState].+ */+ @Volatile private var muteUntilSong = false/** When the user last played, skipped or picked: what an ad-avoiding skip started earlier must not undo. */@Volatile private var userMoveAt = 0L/** The last play sent was the user's: only its refusal walks [onRefused]'s steps. */@@ -190,15 +200,20 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop}val lost = playingAtLossplayingAtLoss = null- if (!ownReload && (lost != null || liveIntent() != null)) scope.launch {+ // A new page forgot it was unheard (clip sound, a mirror): told again before it plays on.+ if (clipHushed || localMuted) { hushedUri = null; applyHush() }+ // A pick held over a reload that was not ours, or whose own play did not run: played now.+ if (!ownReload && pickAfterReload != null) scope.launch { delay(RESTORE_GAP_MS); playPickAfterReload() }+ else if (!ownReload && (lost != null || liveIntent() != null)) scope.launch {runCatching { if (lost != null) resumeAfterReload(lost) else { delay(RESTORE_GAP_MS); playIntent() } }}repeatRestoreUntil = System.currentTimeMillis() + REPEAT_RESTORE_MS- if (audioQuality != "auto") applyAudioQuality()+ if (streamingLevel != "auto") applyAudioQuality()// The page keeps its volume: an app closed during a muted ad must not stay silent.runCatching { if (volume() == 0.0) setVolume(wantedVolume?.takeIf { v -> v > 0.0 } ?: 1.0) }- // A reloaded page during an ad break plays the ad again: muted again at once.- if (_adPlaying.value) muteForAd()+ // A reloaded page during an ad break plays the ad again: muted again at once. So is a+ // page reloaded to get past an ad, until a real song plays (an ad can come first).+ if (_adPlaying.value || muteUntilSong) muteForAd()}}}@@ -224,6 +239,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScoptry {runCatching {if (!reloadAndWait(reload)) return@runCatching+ if (playPickAfterReload()) return@runCatchingif (s == null) return@runCatchingif (next) { delay(1_500); playOn(s) } else resumeAfterReload(s)}@@ -233,6 +249,16 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop}}+ /** The pick held over our reload ([pickAfterReload]), played on the new page. True when there was one. */+ private suspend fun playPickAfterReload(): Boolean {+ val pick = pickAfterReload ?: return false+ pickAfterReload = null+ if (liveIntent() != null) return false+ bridge.logger?.invoke("playing the song picked before the ad, on the new page: ${pick.track ?: pick.context}")+ runCatching { playNow(pick.context, trackUri = pick.track, positionMs = pick.positionMs, order = pick.order, refusable = true) }+ return true+ }+/*** Reloads the page and waits until it is ready again; nothing is played. For a page whose* Spotify Connect layer hangs (a transfer from a device that went away never ends).@@ -317,6 +343,13 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop*/internal val remoteActive: Boolean get() = lastMedia?.let { it.active == false && it.paused } == true+ private val _playsElsewhere = MutableStateFlow(false)+ /**+ * [remoteActive] as the watcher last read it (no call of its own): true while another device of+ * the account plays and this page stands still; back to false once this page plays again.+ */+ val playsElsewhere: StateFlow<Boolean> = _playsElsewhere+/** Loads the song after the current one in advance (see "player.preloadNext"); on by default. */@Volatile var preloadNext = true/** "current|next" already preloaded. */@@ -328,7 +361,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop* the same when the song plays out; again when the next song changes (queue edits).*/private suspend fun preloadNextSong(s: PlayerState?, media: Media?) {- if (!preloadNext || s == null || s.isPaused || s.isBuffering || _adPlaying.value || media == null || media.active == false) return+ if (!preloadNext || mirroring || s == null || s.isPaused || s.isBuffering || _adPlaying.value || media == null || media.active == false) returnval next = s.next?.takeIf { it.kind == ItemKind.TRACK || it.kind == ItemKind.EPISODE } ?: returnif (s.positionAt(System.currentTimeMillis()) < PRELOAD_AFTER_MS) returnval key = "${s.item?.uri}|${next.uri}"@@ -440,6 +473,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScoppageSuspect = falseval media = read.getOrNull()lastMedia = media+ _playsElsewhere.value = remoteActiveval s = _state.valuepreloadNextSong(s, media)tickCrossfade(s, media, now)@@ -495,11 +529,13 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopif (stuck) {adAttempts++val last = lastTrackState- if (adRecovery(adAttempts) == "next") {+ if (adRecovery(adAttempts, playing = playing && !refused) == "next") {bridge.logger?.invoke("ad stuck on ${ad?.item?.name}: playing the next song (attempt $adAttempts)")last?.let { runCatching { playOn(it) } }} else {adReloaded = true+ // Until a real song plays on the new page, it stays muted (see [muteUntilSong]).+ muteUntilSong = truebridge.logger?.invoke("ad stuck on ${ad?.item?.name}: reloading the player (attempt $adAttempts)")if (reloadHost != null) reloadAndPlayOn(last) else last?.let { runCatching { playOn(it) } }}@@ -949,6 +985,12 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopval adJustEnded = _adPlaying.value_adPlaying.value = falseif (adJustEnded) bridge.logger?.invoke("ad break over after ${(System.currentTimeMillis() - adSince) / 1000} s: ${s?.item?.name ?: "nothing"}${if (s?.isPaused == true) " (paused)" else ""}")+ // A page reloaded to get past an ad: heard again only once a real song plays on it.+ if (muteUntilSong && s?.item != null && !s.isPaused && !s.isBuffering) {+ muteUntilSong = false+ bridge.logger?.invoke("a song plays after the reload: ${s.item?.name} heard again")+ scope.launch { unmuteAfterAd() }+ }val pick = pickBeforeAdif (adJustEnded && pick != null) {pickBeforeAd = null@@ -957,9 +999,17 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop// A pick of a whole list (no song) has landed when the page plays that list.val landed = if (pick.track != null) s?.item?.uri == pick.track else s?.contextUri == pick.contextif (!landed && System.currentTimeMillis() - pick.at < PICK_REPLAY_MS && liveIntent() == null) {- bridge.logger?.invoke("song picked before the ad not played: asked again")- // With the order it was picked in: a sorted list or a smart shuffle is not the list's own.- scope.launch { runCatching { play(pick.context, trackUri = pick.track, positionMs = pick.positionMs, order = pick.order) } }+ // The break "ended" because our own reload took the page away (an ad stuck): the+ // page going away takes no command ("local player is disabled"). The pick waits+ // for the new page and is played there ([playPickAfterReload]).+ if (ownReload || !bridge.ready.value) {+ pickAfterReload = pick+ bridge.logger?.invoke("song picked before the ad: played once the page is back")+ } else {+ bridge.logger?.invoke("song picked before the ad not played: asked again")+ // With the order it was picked in: a sorted list or a smart shuffle is not the list's own.+ scope.launch { runCatching { play(pick.context, trackUri = pick.track, positionMs = pick.positionMs, order = pick.order) } }+ }}}shufflePending?.takeIf { System.currentTimeMillis() - it.second < PICK_REPLAY_MS }?.let { (on, _) ->@@ -1306,6 +1356,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopreturn}pickBeforeAd = null+ pickAfterReload = nullplayNow(contextUri, trackUri, index, positionMs, order, refusable = true)}@@ -1417,7 +1468,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopreturn}pageSuspect = false- val quiet = _adPlaying.value || adMuted || crossfadeArmed || _state.value?.isPaused == false || lastMedia?.active == false+ val quiet = _adPlaying.value || adMuted || localMuted || clipHushed || crossfadeArmed || _state.value?.isPaused == false || lastMedia?.active == falseif (quiet) { command("player.resume"); return }fadeBackTo = lastMedia?.own?.takeIf { it > 0.01 } ?: 1.0fadeBack?.cancel()@@ -1447,6 +1498,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopoverride suspend fun next() {pausedByUser = falsepickBeforeAd = null+ pickAfterReload = nulluserMoveAt = System.currentTimeMillis()adRestore?.cancel()if (skipsHeld) { stepIntent(1); return }@@ -1500,6 +1552,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopoverride suspend fun previous() {pausedByUser = falsepickBeforeAd = null+ pickAfterReload = nulluserMoveAt = System.currentTimeMillis()adRestore?.cancel()if (skipsHeld) { stepIntent(-1); return }@@ -1586,6 +1639,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopuserMoveAt = System.currentTimeMillis()adRestore?.cancel()pickBeforeAd = null+ pickAfterReload = nullval base = lastWithSong()if (skipsHeld) { setIntent(base?.contextUri, item, base?.item?.uri); return }if (base?.item?.kind != ItemKind.AD) intent = Intent(base?.contextUri, item, base?.item?.uri, System.currentTimeMillis())@@ -1629,6 +1683,23 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopif (bridge.ready.value) applyAudioQuality()}+ /**+ * The page only mirrors a song the app plays itself, unheard (the app's Connect mirror): it then+ * streams at its lowest level ([MIRROR_QUALITY]) and loads no next song ahead, whatever+ * [audioQuality] says. Off: the user's quality again. Set before the song is played: the page+ * picks a song's file with the level it has when the song starts.+ */+ suspend fun setMirroring(on: Boolean) {+ if (mirroring == on) return+ mirroring = on+ if (bridge.ready.value) applyAudioQuality()+ }++ @Volatile private var mirroring = false++ /** The level the page is given: the user's, or the lowest one while it only mirrors. */+ val streamingLevel: String get() = if (mirroring) MIRROR_QUALITY else audioQuality+/** What the page plays now: bitrate (bit/s, 0 = unknown) and codec ("audio/mp4; codecs=…"). */suspend fun audioInfo(): Pair<Int, String> = runCatching {val o = bridge.call("player.audioInfo") as? JsonObject ?: return@runCatching 0 to ""@@ -1636,8 +1707,9 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop}.getOrDefault(0 to "")private suspend fun applyAudioQuality() {- runCatching { bridge.call("player.setAudioQuality", buildJsonObject { put("level", audioQuality) }) }- .onFailure { bridge.logger?.invoke("audio quality $audioQuality not set: ${it.message}") }+ val level = streamingLevel+ runCatching { bridge.call("player.setAudioQuality", buildJsonObject { put("level", level) }) }+ .onFailure { bridge.logger?.invoke("audio quality $level not set: ${it.message}") }}/** Pulls the state once, e.g. right after the bridge is ready. */@@ -1786,6 +1858,8 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop/** A song over with nothing after it: where an ad was left out. Next song quickly. */const val END_STUCK_MS = 1_000Lprivate const val WATCH_TICK_MS = 2_000L+ /** The page's lowest streaming level (24 kbit/s), used while it only mirrors (see [setMirroring]). */+ const val MIRROR_QUALITY = "low"/** Nothing plays: the watcher looks less often (see [watchStalls]). */private const val WATCH_IDLE_TICK_MS = 4_000L/** Buffering longer than this on one song is a stall, not a slow network. */@@ -1795,10 +1869,16 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop/*** What the [attempt]-th try on a stuck ad does: "reload" first (the only lever a refused- * ad yields to, see [watchStalls]), then "next" (play on) before reloading again.+ * ad yields to, see [watchStalls]), then "next" (play on) before reloading again. An ad+ * that [playing] (muted, not refused) is first played past ("next"), which costs no+ * reload when the page takes it; the reload stays the fallback.*/- fun adRecovery(attempt: Int): String =- if (attempt == 1 || attempt > 1 + AD_SKIPS_AFTER_RELOAD) "reload" else "next"+ fun adRecovery(attempt: Int, playing: Boolean = false): String = when {+ playing && attempt == 1 -> "next"+ playing -> adRecovery(attempt - 1)+ attempt == 1 || attempt > 1 + AD_SKIPS_AFTER_RELOAD -> "reload"+ else -> "next"+ }/*** Why [s] looks stalled at [now], or null. A song is stalled when its clock ran pastdiff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/BridgeHost.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/BridgeHost.ktindex 65071bd9..2b2c0c3b 100644--- a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/BridgeHost.kt+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/BridgeHost.kt@@ -55,6 +55,8 @@ object AdBlock {"googleads.g.doubleclick.net","pagead2.googlesyndication.com","imasdk.googleapis.com",+ // DoubleClick's ad media CDN (host list credit: coldMEW/Hush, GPL-3.0).+ "s0.2mdn.net",// Third-party audience trackers the page loads (nothing it needs to play)."googletagmanager.com","google-analytics.com",@@ -86,7 +88,7 @@ object AdBlock {* is left as it is; an ad that is already the current state cannot be left out either.*/fun withoutAds(body: String): Pair<String, List<String>>? {- if ("\"AD\"" !in body) return null+ if (!AD_HINT.containsMatchIn(body)) return nullval root = runCatching { Json.parseToJsonElement(body).jsonObject }.getOrNull() ?: return nullval notes = mutableListOf<String>()val out = root.toMutableMap()@@ -113,14 +115,14 @@ object AdBlock {/** The [AdAhead] in a track-playback reply (after [withoutAds]), or null. */fun adAhead(body: String): AdAhead? = runCatching {- if ("\"AD\"" !in body) return null+ if (!AD_HINT.containsMatchIn(body)) return nullval root = Json.parseToJsonElement(body).jsonObjectval machine = root["state_machine"] as? JsonObject ?: return nullval tracks = machine["tracks"] as? JsonArray ?: return nullval states = machine["states"] as? JsonArray ?: return nullfun index(o: JsonObject?, key: String) = (o?.get(key) as? JsonPrimitive)?.contentOrNull?.toIntOrNull()fun trackOf(state: Int) = index(states.getOrNull(state) as? JsonObject, "track")?.let { tracks.getOrNull(it) as? JsonObject }- fun isAd(state: Int) = (trackOf(state)?.get("content_type") as? JsonPrimitive)?.contentOrNull == "AD"+ fun isAd(state: Int) = isAdTrack(trackOf(state))fun uriOf(state: Int) = ((trackOf(state)?.get("metadata") as? JsonObject)?.get("uri") as? JsonPrimitive)?.contentOrNullval current = index(root["updated_state_ref"] as? JsonObject, "state_index") ?: return nullif (isAd(current)) return null@@ -133,12 +135,57 @@ object AdBlock {AdAhead((state["track_uid"] as? JsonPrimitive)?.contentOrNull, uriOf(current), next)}.getOrNull()+ /**+ * Something in a reply that may be an ad: Spotify's `content_type` "AD", or the markers its+ * metadata carries (the same ones the host's relay and the bridge's `isAd` look for). Only a+ * pre-check: [isAdTrack] decides, on the track itself.+ */+ private val AD_HINT = Regex("\"AD\"|spotify:ad:|\"is_advertisement\"|\"ad_id\"")++ /**+ * A track of a state machine that is an ad: `content_type` "AD", or metadata flagging it+ * (`is_advertisement` true, an `spotify:ad:` uri, an `ad_id`). Seen in every capture so far:+ * all four on each ad, none on a song; a song whose name or album merely says "ad" is no ad.+ */+ fun isAdTrack(track: JsonObject?): Boolean {+ track ?: return false+ if ((track["content_type"] as? JsonPrimitive)?.contentOrNull == "AD") return true+ val metadata = track["metadata"] as? JsonObject ?: return false+ val flag = (metadata["is_advertisement"] as? JsonPrimitive)?.contentOrNull+ if (flag.equals("true", ignoreCase = true)) return true+ if ((metadata["uri"] as? JsonPrimitive)?.contentOrNull?.startsWith("spotify:ad:") == true) return true+ return !(metadata["ad_id"] as? JsonPrimitive)?.contentOrNull.isNullOrBlank()+ }++ /**+ * Why [withoutAds] left a reply that looks like it holds an ad as it was, for the log: what+ * marked it, and what kept it (the ad is the song now, no song to send its way to, no ad track+ * at all). Null when it does not look like one.+ */+ fun whyKept(body: String): String? = runCatching {+ val marker = AD_HINT.find(body)?.value?.trim('"') ?: return null+ val root = Json.parseToJsonElement(body).jsonObject+ val machine = root["state_machine"] as? JsonObject ?: return "$marker: no state machine in the reply"+ val tracks = machine["tracks"] as? JsonArray ?: return "$marker: no tracks"+ val states = machine["states"] as? JsonArray ?: return "$marker: no states"+ fun index(o: JsonObject?, key: String) = (o?.get(key) as? JsonPrimitive)?.contentOrNull?.toIntOrNull()+ fun isAd(state: Int) = isAdTrack(index(states.getOrNull(state) as? JsonObject, "track")?.let { tracks.getOrNull(it) as? JsonObject })+ if (tracks.none { isAdTrack(it as? JsonObject) }) return "$marker: no ad track (the marker is elsewhere in the reply)"+ index(root["updated_state_ref"] as? JsonObject, "state_index")?.let { if (isAd(it)) return "$marker: the ad is the current song" }+ val blocked = states.indices.any { i ->+ val t = (states[i] as? JsonObject)?.get("transitions") as? JsonObject ?: return@any false+ !isAd(i) && listOf("advance", "skip_next").all { k -> index(t[k] as? JsonObject, "state_index")?.let(::isAd) == true }+ }+ if (blocked) "$marker: the song before the ad has no other way on (its skip leads to the ad too)"+ else "$marker: no song leads to the ad"+ }.getOrElse { "not readable: ${it.javaClass.simpleName}" }+private fun machineWithoutAds(machine: JsonObject, notes: MutableList<String>): JsonObject? {val tracks = machine["tracks"] as? JsonArray ?: return nullval states = machine["states"] as? JsonArray ?: return nullfun trackOf(state: Int) = ((states.getOrNull(state) as? JsonObject)?.get("track") as? JsonPrimitive)?.contentOrNull?.toIntOrNull()?.let { tracks.getOrNull(it) as? JsonObject }- fun isAd(state: Int) = (trackOf(state)?.get("content_type") as? JsonPrimitive)?.contentOrNull == "AD"+ fun isAd(state: Int) = isAdTrack(trackOf(state))fun nameOf(state: Int) = ((trackOf(state)?.get("metadata") as? JsonObject)?.get("name") as? JsonPrimitive)?.contentOrNullfun indexOf(transition: JsonObject) = (transition["state_index"] as? JsonPrimitive)?.contentOrNull?.toIntOrNull()var changed = falsediff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/gql/Gql.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/gql/Gql.ktindex 588b81ad..42dcd52d 100644--- a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/gql/Gql.kt+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/gql/Gql.kt@@ -1,6 +1,7 @@package app.myspoti.spotify.gqlimport app.myspoti.spotify.bridge.Bridge+import app.myspoti.spotify.bridge.BridgeExceptionimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.sync.Muteximport kotlinx.coroutines.sync.withLock@@ -116,11 +117,13 @@ class SpotifyHttp(val now = System.currentTimeMillis()return web?.takeIf { it.expiresAtMs - now > 60_000 } ?: run {val t = bridge.call("token.get").jsonObject+ // A page that answers without a field (a build that changed) is a bridge error, not a crash.+ fun field(name: String): JsonPrimitive = t[name] as? JsonPrimitive ?: throw BridgeException("token.get: no $name")WebToken(- access = t["accessToken"]!!.jsonPrimitive.content,- expiresAtMs = t["expiresAtMs"]!!.jsonPrimitive.long,- clientId = t["clientId"]!!.jsonPrimitive.content,- appVersion = t["appVersion"]!!.jsonPrimitive.content,+ access = field("accessToken").content,+ expiresAtMs = field("expiresAtMs").long,+ clientId = field("clientId").content,+ appVersion = field("appVersion").content,anonymous = t["isAnonymous"]?.jsonPrimitive?.contentOrNull == "true",).also { web = it }}@@ -234,7 +237,8 @@ class SpotifyHttp(val granted = runCatching { Bridge.json.parseToJsonElement(text).jsonObject["granted_token"]?.jsonObject }.getOrNull()?: throw GqlException("clienttoken", "HTTP $code: ${text.take(200)}")val seconds = (granted["expires_after_seconds"] as? JsonPrimitive)?.long ?: 86_400- return ClientToken(granted["token"]!!.jsonPrimitive.content, System.currentTimeMillis() + seconds * 1000)+ val token = (granted["token"] as? JsonPrimitive)?.content ?: throw GqlException("clienttoken", "no token in the answer")+ return ClientToken(token, System.currentTimeMillis() + seconds * 1000)}/** Who a raw request may go to: the account's own hosts (with its credentials) or Spotify's public CDN. */diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/gql/GqlOpsUpdater.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/gql/GqlOpsUpdater.ktindex 187df0e3..c053d8d7 100644--- a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/gql/GqlOpsUpdater.kt+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/gql/GqlOpsUpdater.kt@@ -68,8 +68,10 @@ class GqlOpsUpdater(private val http: OkHttpClient, private val cache: File) {}private fun parse(text: String): GqlOps {- val ops = Bridge.json.parseToJsonElement(text).jsonObject["operations"]!!.jsonObject- return GqlOps(ops.mapValues { it.value.jsonObject["hash"]!!.jsonPrimitive.content })+ val ops = Bridge.json.parseToJsonElement(text).jsonObject["operations"] as? JsonObject ?: throw GqlException("ops", "no operations in the table")+ return GqlOps(ops.mapValues { (name, op) ->+ (op.jsonObject["hash"] as? JsonPrimitive)?.content ?: throw GqlException(name, "no hash in the table")+ })}private fun get(url: String): String =diff --git a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/StallTest.kt b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/StallTest.ktindex 04584b37..4e1524cb 100644--- a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/StallTest.kt+++ b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/StallTest.kt@@ -44,6 +44,12 @@ class StallTest {assertEquals("reload", SpotifyPlayer.adRecovery(4))}+ @Test fun `a muted ad that plays is played past once before the reload`() {+ assertEquals("next", SpotifyPlayer.adRecovery(1, playing = true))+ assertEquals("reload", SpotifyPlayer.adRecovery(2, playing = true))+ assertEquals("next", SpotifyPlayer.adRecovery(3, playing = true))+ }+// Chromium pauses a hidden page's media that (re)starts at volume 0.@Test fun `a fade never reaches volume 0`() = SpotifyPlayer.FADE_STEPS.forEach { assertEquals(true, it > 0.0) }diff --git a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/AdBlockTest.kt b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/AdBlockTest.ktindex 5d3b0df0..94284107 100644--- a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/AdBlockTest.kt+++ b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/AdBlockTest.kt@@ -17,6 +17,8 @@ class AdBlockTest {fun `blocks foreign ad servers only`() {assertTrue(AdBlock.isBlocked("https://pubads.g.doubleclick.net/gampad/ads?x=1"))assertTrue(AdBlock.isBlocked("https://imasdk.googleapis.com/js/sdkloader/ima3.js"))+ assertTrue(AdBlock.isBlocked("https://s0.2mdn.net/ads/richmedia/studio/abc.mp4"))+ assertFalse(AdBlock.isBlocked("https://evil.com/s0.2mdn.net/x.mp4"))// Spotify's own ad endpoints stay reachable: a client that never calls them stands out.assertFalse(AdBlock.isBlocked("https://spclient.wg.spotify.com/ads/v2/config"))assertFalse(AdBlock.isBlocked("https://gew4-spclient.spotify.com/ad-logic/state/config?a=b"))diff --git a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/AdQueueTest.kt b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/AdQueueTest.ktindex 4b22b04e..b31660f9 100644--- a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/AdQueueTest.kt+++ b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/AdQueueTest.kt@@ -86,4 +86,56 @@ class AdQueueTest {}@Test fun `an unreadable reply is left alone`() = assertNull(AdBlock.withoutAds("""{"x":"AD" """))++ // ── Ads flagged by their metadata only, and songs that merely look like ads ──++ private fun raw(json: String) = json++ /** A track typed TRACK whose metadata alone says what it is. */+ private fun flagged(name: String, meta: String) =+ """{"content_type":"TRACK","metadata":{"uri":"spotify:track:${name.replace(' ', '-')}","name":"$name"$meta},"manifest":{}}"""++ private fun firstShapeWith(ad: String) = reply(+ listOf(raw(ad), track("TRACK", "Before"), track("TRACK", "Playing"), track("TRACK", "After")),+ listOf(state(0), state(1), state(2, advance = 0, next = 4, show = 4), state(2), state(3)),+ current = 2,+ )++ @Test fun `an ad flagged only by is_advertisement, an ad uri or an ad_id is left out too`() {+ val marked = listOf(+ flagged("Promo", ""","is_advertisement":"true""""),+ """{"content_type":"TRACK","metadata":{"uri":"spotify:ad:123","name":"Promo"},"manifest":{}}""",+ flagged("Promo", ""","ad_id":"abc123""""),+ )+ for (ad in marked) {+ val (body, notes) = AdBlock.withoutAds(firstShapeWith(ad))!!+ assertEquals(4, index(transitions(body, 2), "advance"), ad)+ assertEquals(listOf("advance after Playing: After instead of an ad"), notes)+ }+ }++ @Test fun `a song that only looks like an ad is never left out`() {+ val songs = listOf(+ flagged("AD", ""),+ flagged("Bad Ad", ""","album_title":"Ad Astra""""),+ flagged("Ads", ""","is_advertisement":"false""""),+ flagged("Adagio", ""","ad_id":"""""),+ """{"content_type":"TRACK","metadata":{"uri":"spotify:track:adadadad","name":"spotify:ad: in a title"},"manifest":{}}""",+ )+ for (song in songs) {+ val body = firstShapeWith(song)+ assertNull(AdBlock.withoutAds(body), song)+ assertNull(AdBlock.adAhead(body), song)+ assertTrue(!AdBlock.isAdTrack(Json.parseToJsonElement(song).jsonObject), song)+ }+ }++ @Test fun `why an ad was kept is told`() {+ val playing = reply(listOf(track("AD", "An ad"), track("TRACK", "B")), listOf(state(0), state(1)), current = 0)+ assertEquals("AD: the ad is the current song", AdBlock.whyKept(playing))+ assertEquals("AD: the song before the ad has no other way on (its skip leads to the ad too)", AdBlock.whyKept(second))+ val notAnAd = firstShapeWith(flagged("Ads", ""","is_advertisement":"false""""))+ assertEquals("is_advertisement: no ad track (the marker is elsewhere in the reply)", AdBlock.whyKept(notAnAd))+ assertNull(AdBlock.whyKept(reply(listOf(track("TRACK", "A")), listOf(state(0)), current = 0)))+ }}diff --git a/base/app/build.gradle.kts b/base/app/build.gradle.ktsindex 77d2344b..e002dfda 100644--- a/base/app/build.gradle.kts+++ b/base/app/build.gradle.kts@@ -22,8 +22,9 @@ android {// signed with the first key, as "Myspoti Beta"; releases are "app.myspoti.stable",// signed with their own key, as "Myspoti".// Local builds (no version given) are on the beta side, like the phone test builds.- val version = (findProperty("appVersionName") as String?) ?: "2.0.1"- val beta = findProperty("appVersionName") == null || version.contains("-")+ val version = (findProperty("appVersionName") as String?) ?: "2.1.0"+ // "-beta" as in UpdateChecker.isBeta, one predicate for the app id, the label and the log stripping.+ val beta = findProperty("appVersionName") == null || version.contains("-beta")defaultConfig {applicationId = if (beta) "app.myspoti" else "app.myspoti.stable"manifestPlaceholders["appLabel"] = if (beta) "Myspoti Beta" else "Myspoti"@@ -52,6 +53,11 @@ android {// Release key from the CI secrets (env), else keystore/keystore.properties.val envStore = System.getenv("MYSPOTI_KEYSTORE")val hasReleaseKey = envStore != null || keystorePropertiesFile.exists()+ // A stable release (a version without "-beta", given by CI) is never signed with the debug key:+ // without the release key the build stops. Local builds (no version) and -PoverDev are not stable releases.+ val stableRelease = !beta && findProperty("overDev") == null+ if (stableRelease && !hasReleaseKey && gradle.startParameter.taskNames.any { Regex("(assemble|bundle|package|install)Release").containsMatchIn(it) })+ throw GradleException("A stable release needs the release key: set MYSPOTI_KEYSTORE (CI) or add keystore/keystore.properties.")signingConfigs {create("release") {if (envStore != null) {diff --git a/base/app/proguard-rules.pro b/base/app/proguard-rules.proindex dd271ba5..0942528d 100644--- a/base/app/proguard-rules.pro+++ b/base/app/proguard-rules.pro@@ -3,6 +3,10 @@-keepclassmembers class app.myspoti.host.android.PlayerChannel {@android.webkit.JavascriptInterface <methods>;}+# The extension page's bridge (ExtensionPage.kt): the page's script calls it by method name.+-keepclassmembers class com.music.spotui.ui.screens.PageBridge {+ @android.webkit.JavascriptInterface <methods>;+}# Bundled resources read by name (bridge script, GraphQL operation table).-keep class app.myspoti.spotify.bridge.BridgeScript { *; }-keep class app.myspoti.spotify.gql.GqlOps { *; }diff --git a/base/app/src/main/java/app/myspoti/MainActivity.kt b/base/app/src/main/java/app/myspoti/MainActivity.ktindex 263cb507..81ab68cb 100644--- a/base/app/src/main/java/app/myspoti/MainActivity.kt+++ b/base/app/src/main/java/app/myspoti/MainActivity.kt@@ -186,7 +186,8 @@ class MainActivity : AppCompatActivity() {// The clip player follows the app on screen: paused with its side jobs in the background.override fun onStart() {- app.myspoti.host.android.MainThreadWatch.start()+ // Beta and dev builds only, like the log button: a stable release has no freeze reports to read.+ if (com.music.spotui.data.api.UpdateChecker.isBeta || app.myspoti.engine.BuildConfig.DEBUG) app.myspoti.host.android.MainThreadWatch.start()super.onStart()com.music.spotui.video.MusicVideoController.onForeground()// Asked for over adb (TestControlReceiver's "screenon"): One UI ignores the hugediff --git a/base/app/src/main/java/com/music/spotui/App.kt b/base/app/src/main/java/com/music/spotui/App.ktindex dc9252cc..1b56555a 100644--- a/base/app/src/main/java/com/music/spotui/App.kt+++ b/base/app/src/main/java/com/music/spotui/App.kt@@ -32,11 +32,10 @@ import androidx.compose.runtime.setValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.saveable.rememberSaveableimport androidx.compose.ui.Modifier-import androidx.navigation.compose.currentBackStackEntryAsStateimport androidx.navigation.compose.rememberNavControllerimport com.music.spotui.ui.navigation.MainBottomNavigationimport com.music.spotui.ui.navigation.MyNavHost-import com.music.spotui.ui.navigation.Routes+import com.music.spotui.ui.navigation.navigateSingleTop@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")@@ -45,20 +44,13 @@ fun App() {val bottomBarState = rememberSaveable { (mutableStateOf(true)) }val bottomBarPlayerState = rememberSaveable { (mutableStateOf(true)) }val navController = rememberNavController()- val navBackStackEntry by navController.currentBackStackEntryAsState()-- // Control TopBar and BottomBar: on a route change (writing state during composition- // forces an extra recomposition pass).- val route = navBackStackEntry?.destination?.route- LaunchedEffect(route) {- when (route) {- Routes.Home.route, Routes.Search.route, Routes.Library.route -> bottomBarState.value = true- Routes.Album.route -> bottomBarState.value = false- }- }// Debug and beta builds: `myspoti-cli nav <route>` (see CliReceiver).LaunchedEffect(Unit) { com.music.spotui.cli.CliReceiver.nav.collect { r -> runCatching { navController.navigate(r) } } }+ // A page the onboarding asked for ("See the extensions").+ LaunchedEffect(Unit) {+ com.music.spotui.ui.screens.Setup.openAfter?.let { r -> com.music.spotui.ui.screens.Setup.openAfter = null; runCatching { navController.navigate(r) } }+ }UpdatePrompt()SupportPrompt()@@ -71,7 +63,7 @@ fun App() {val i = invite?.takeIf { !it.opened } ?: return@LaunchedEffectapp.myspoti.host.android.MyspotiRuntime.api.ready.first { it }i.opened = true- navController.navigate(com.music.spotui.ui.navigation.playlistRoute(i.playlistId))+ navController.navigateSingleTop(com.music.spotui.ui.navigation.playlistRoute(i.playlistId))}// A Blend invitation was opened (see InviteLinks): who invites, and "Join", over the app.@@ -99,7 +91,7 @@ fun App() {val id = uri.substringAfterLast(':')com.music.spotui.ui.navigation.PlayerSheet.close()runCatching {- navController.navigate(when (uri.split(':')[1]) {+ navController.navigateSingleTop(when (uri.split(':')[1]) {"playlist" -> com.music.spotui.ui.navigation.playlistRoute(id)"album" -> com.music.spotui.ui.navigation.albumRoute("", "", id)"artist" -> com.music.spotui.ui.navigation.artistRoute("artist", id)@@ -118,11 +110,16 @@ fun App() {// 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()+ // Without it (Android 12+), the frost blurs the same recording, which follows page and tab+ // transitions frame by frame where Haze lagged behind.+ val frostPage = immersive && !liquidGlass && android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S// 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.look.LocalReduceMotion provides com.music.spotui.ui.look.rememberReduceMotion(),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.LocalImmersiveFrostPage provides if (frostPage) glassPage else null,com.music.spotui.ui.immersive.shell.LocalImmersiveChrome provides if (immersive) chrome else null,) {androidx.compose.foundation.layout.Box(Modifier.fillMaxSize()) {diff --git a/base/app/src/main/java/com/music/spotui/cli/CliReceiver.kt b/base/app/src/main/java/com/music/spotui/cli/CliReceiver.ktindex c4ae7077..0ca16007 100644--- a/base/app/src/main/java/com/music/spotui/cli/CliReceiver.kt+++ b/base/app/src/main/java/com/music/spotui/cli/CliReceiver.kt@@ -5,6 +5,7 @@ import android.content.Contextimport android.content.Intentimport android.util.Logimport app.myspoti.extensions.ExtensionPackage+import app.myspoti.host.android.MyspotiRuntimeimport com.music.spotui.di.SongPlayerimport com.music.spotui.extensions.Extensionsimport com.music.spotui.extensions.Grants@@ -58,7 +59,10 @@ class CliReceiver : BroadcastReceiver() {}private suspend fun run(ctx: Context, c: CliCommand): JsonElement = when (c) {- CliCommand.Status -> onMain {+ CliCommand.Status -> {+ // What the page streams now (bitrate, codec): one bridge call, for the mirror's quality check.+ val audio = withContext(Dispatchers.Main) { if (MyspotiRuntime.isStarted) MyspotiRuntime.spotify.player.audioInfo() else 0 to "" }+ onMain {val np = SongPlayer.nowPlaying.valuebuildJsonObject {put("package", ctx.packageName)@@ -88,7 +92,27 @@ class CliReceiver : BroadcastReceiver() {}put("extensions", if (Extensions.isReady) Extensions.registry.value.extensions.size else 0)put("ui", nav.subscriptionCount.value > 0)+ // The Connect mirror ("Count extension plays on Spotify") and the page under it.+ put("mirror", buildJsonObject {+ val m = com.music.spotui.di.ConnectMirror.status()+ put("on", m.on); put("running", m.running); put("handedAway", m.handedAway); put("landed", m.landed)+ m.uri?.let { put("uri", it) }; m.paused?.let { put("paused", it) }+ m.webPositionMs?.let { put("webPositionMs", it) }; m.failedUri?.let { put("failedUri", it) }+ if (MyspotiRuntime.isStarted) {+ val page = MyspotiRuntime.spotify.player+ val s = page.state.value+ put("pageUri", s?.item?.uri ?: "")+ put("pagePaused", s?.isPaused ?: true)+ put("pagePositionMs", s?.positionAt(System.currentTimeMillis()) ?: 0L)+ put("hushed", page.localMute)+ put("quality", page.streamingLevel)+ put("bitrate", audio.first); put("codec", audio.second)+ put("playsElsewhere", page.playsElsewhere.value)+ }+ SongPlayer.activeDevice.value?.let { put("activeDevice", it.name) }+ })}+ }}CliCommand.ExtList -> JsonArray(ready().registry.value.extensions.map { e ->val m = Extensions.manifest(e.id)diff --git a/base/app/src/main/java/com/music/spotui/data/DataSaverGlide.kt b/base/app/src/main/java/com/music/spotui/data/DataSaverGlide.ktindex a7abd8ad..921bcf66 100644--- a/base/app/src/main/java/com/music/spotui/data/DataSaverGlide.kt+++ b/base/app/src/main/java/com/music/spotui/data/DataSaverGlide.kt@@ -2,10 +2,12 @@ package com.music.spotui.dataimport android.content.Contextimport com.bumptech.glide.Glide+import com.bumptech.glide.GlideBuilderimport com.bumptech.glide.Priorityimport com.bumptech.glide.load.DataSourceimport com.bumptech.glide.load.Optionsimport com.bumptech.glide.load.data.DataFetcher+import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactoryimport com.bumptech.glide.load.model.GlideUrlimport com.bumptech.glide.load.model.ModelLoaderimport com.bumptech.glide.load.model.ModelLoaderFactory@@ -18,7 +20,12 @@ import java.io.InputStream* the network for nothing (see [DataSaver]).*/object DataSaverGlide {+ /** Glide's default is 250 MB; covers are small, so the cache stays at 150 MB. */+ private const val DISK_CACHE_BYTES = 150L * 1024 * 1024+fun install(context: Context) {+ // Before the first Glide.get: no annotation processor here, so the default builder is replaced by hand.+ Glide.init(context, GlideBuilder().setDiskCache(InternalCacheDiskCacheFactory(context, DISK_CACHE_BYTES)))Glide.get(context).registry.replace(GlideUrl::class.java, InputStream::class.java, Factory())}diff --git a/base/app/src/main/java/com/music/spotui/data/api/Api.kt b/base/app/src/main/java/com/music/spotui/data/api/Api.ktindex 9d23f35a..f1dc5850 100644--- a/base/app/src/main/java/com/music/spotui/data/api/Api.kt+++ b/base/app/src/main/java/com/music/spotui/data/api/Api.kt@@ -79,8 +79,12 @@ class Api constructor(/** Contents of the library folders opened so far, by folder uri. */val folders = java.util.concurrent.ConcurrentHashMap<String, List<LibraryEntry>>()+ /** A playlist's songs were changed from the app: the next page of it reads them again. */+ fun invalidatePlaylist(playlistId: String) = PlaylistFresh.drop("spotify:playlist:$playlistId")+/** Drop all cached feeds (e.g. on logout / account switch). */fun clear() {+ PlaylistFresh.drop(null)albums = null; artists = null; home = null; library = nulllibraryRoot = null; folders.clear()facets.clear()@@ -115,6 +119,13 @@ class Api constructor(* [head] (the newest liked songs, from Spotify) then the rest of [known] after them.* A song unliked inside the head's span is gone from it, so it goes from the list too.*/+ /** True when [head] ends inside [known] (or is the whole list), so [merge] loses nothing. */+ fun reaches(head: List<SongsModel>, known: List<SongsModel>): Boolean {+ if (head.size < 50) return true+ val last = head.last().spotifyTrackId+ return known.any { it.spotifyTrackId == last }+ }+fun merge(head: List<SongsModel>, known: List<SongsModel>): List<SongsModel> {val ids = head.mapTo(HashSet()) { it.spotifyTrackId }val lastHead = head.lastOrNull()?.spotifyTrackId@@ -646,6 +657,28 @@ class Api constructor(}}+ /**+ * The songs of playlists read in full lately, by playlist uri (a few, small ones: a long list+ * stays on the network). Dropped by an edit made from the app, see [invalidatePlaylist].+ */+ private object PlaylistFresh {+ const val FRESH_MS = 5 * 60_000L+ const val MAX_TRACKS = 1_000+ private const val KEEP = 6+ private val map = object : LinkedHashMap<String, Pair<Long, List<SongsModel>>>(8, 0.75f, true) {+ override fun removeEldestEntry(eldest: MutableMap.MutableEntry<String, Pair<Long, List<SongsModel>>>) = size > KEEP+ }++ @Synchronized fun get(uri: String): List<SongsModel>? =+ map[uri]?.takeIf { System.currentTimeMillis() - it.first < FRESH_MS }?.second++ @Synchronized fun put(uri: String, songs: List<SongsModel>) {+ if (songs.isEmpty() || songs.size > MAX_TRACKS) map.remove(uri) else map[uri] = System.currentTimeMillis() to songs+ }++ @Synchronized fun drop(uri: String?) { if (uri == null) map.clear() else map.remove(uri) }+ }+/** Artist pages shown lately, by artist uri, with when they were loaded. */private object ArtistCache {const val FRESH_MS = 5 * 60_000L@@ -699,8 +732,13 @@ class Api constructor()))}- /** Liked Songs as a page: cached list shown instantly, then refreshed page by page. */- suspend fun getLikedPage(): Flow<Response<ContextPageModel>> = flow {+ /**+ * Liked Songs as a page: cached list shown instantly, then refreshed. A list read in full less+ * than [LIKED_FULL_MS] ago only has its newest page read again (the hearts of this account+ * and a like or unlike anywhere else land there); after that, with no list on storage, or+ * with [full] (a pull-to-refresh), every page is read.+ */+ suspend fun getLikedPage(full: Boolean = false): Flow<Response<ContextPageModel>> = flow {fun page(tracks: List<SongsModel>, complete: Boolean) = ContextPageModel(uri = "spotify:collection:tracks",type = "liked",@@ -715,6 +753,24 @@ class Api constructor(if (LikedCache.tracks == null) LikedCache.tracks = withContext(Dispatchers.IO) { ScreenCache.liked.read() }LikedCache.tracks?.let { emit(Response.Success(page(it, true))) } ?: emit(Response.Loading())if (!ready()) { if (LikedCache.tracks == null) emit(Response.Error(notSignedIn())); return@flow }+ val known = LikedCache.tracks+ if (!full && known != null) {+ val at = withContext(Dispatchers.IO) { ScreenCache.likedFullAt() }+ if (at != null && System.currentTimeMillis() - at < LIKED_FULL_MS) {+ val head = runCatching { likedHead() }.getOrElse { if (it is CancellationException) throw it; null }+ // The list shown stays when Spotify cannot be reached.+ if (head == null) return@flow+ // A head that does not reach the list known (more than a page of new likes) cannot be merged.+ if (LikedCache.reaches(head, known)) {+ val merged = LikedCache.merge(head, known)+ LikedCache.tracks = merged+ ScreenCache.liked.write(merged)+ SongPlayer.registerLikedSongs(merged.map { it.url })+ emit(Response.Success(page(merged, true)))+ return@flow+ }+ }+ }val first = LikedCache.tracks == null// Cancellation must escape: emit() throws AbortFlowException (a CancellationException)// when the collector stops early (first { … }); catching it and emitting again@@ -727,6 +783,7 @@ class Api constructor(}LikedCache.tracks = tracksScreenCache.liked.write(tracks)+ ScreenCache.markLikedFull()SongPlayer.registerLikedSongs(tracks.map { it.url })emit(Response.Success(page(tracks, true)))}@@ -737,7 +794,7 @@ class Api constructor(*/suspend fun mergeLikedHead(): List<SongsModel>? = runCatching {if (!ready()) return null- val head = api.library.likedTracks(0, 50).items.map { songOf(it.track).copy(addedAt = it.addedAt.orEmpty()) }+ val head = likedHead()val merged = LikedCache.merge(head, LikedCache.tracks.orEmpty())LikedCache.tracks = mergedwithContext(Dispatchers.IO) { ScreenCache.liked.write(merged) }@@ -745,6 +802,10 @@ class Api constructor(merged}.getOrNull()+ /** The newest Liked Songs: one page of 50. */+ private suspend fun likedHead(): List<SongsModel> =+ api.library.likedTracks(0, 50).items.map { songOf(it.track).copy(addedAt = it.addedAt.orEmpty()) }+private suspend fun allLiked(onPage: suspend (List<SongsModel>) -> Unit): List<SongsModel> {val out = ArrayList<SongsModel>()var offset = 0@@ -757,10 +818,20 @@ class Api constructor(return out}- suspend fun getAlbumPage(albumId: String): Flow<Response<ContextPageModel>> = flow {+ /**+ * An album as a page: the copy on storage (opened before) at once, then the album and its+ * songs from Spotify, and the artist's avatar a moment after in a second emit. Without+ * [stored] the copy on storage is left out (a sync that must see the album as it is now).+ */+ suspend fun getAlbumPage(albumId: String, stored: Boolean = true): Flow<Response<ContextPageModel>> = flow {emit(Response.Loading())- if (!ready()) { emit(Response.Error(notSignedIn())); return@flow }val uri = "spotify:album:$albumId"+ val saved = if (stored) withContext(Dispatchers.IO) { ScreenCache.albumPage(albumId).read() } else null+ if (saved != null) {+ SongPlayer.registerContext(saved.tracks.map { it.url }, uri)+ emit(Response.Success(saved))+ }+ if (!ready()) { if (saved == null) emit(Response.Error(notSignedIn())); return@flow }val (album, tracks) = runCatching {coroutineScope {val a = async { api.catalog.album(uri) }@@ -776,7 +847,7 @@ class Api constructor(}a.await() to t.await()}- }.getOrElse { emit(Response.Error(context.getString(R.string.album_not_found))); return@flow }+ }.getOrElse { if (saved == null) emit(Response.Error(context.getString(R.string.album_not_found))); return@flow }val songs = tracks.map { songOf(it).copy(album = album.name, coverUri = cover(album.images), albumId = albumId) }SongPlayer.registerContext(songs.map { it.url }, uri)val type = context.getString(when (album.type) {@@ -784,33 +855,53 @@ class Api constructor("COMPILATION" -> R.string.album_type_compilation; else -> R.string.album_type_album})val firstArtist = album.artists.firstOrNull()- val avatar = firstArtist?.let { runCatching { api.catalog.artist(it.uri) }.getOrNull() }?.images?.let(::cover).orEmpty()- emit(Response.Success(ContextPageModel(+ val page = ContextPageModel(uri = uri,type = "album",name = album.name,coverUri = big(album.images),ownerName = album.artists.joinToString(", ") { it.name },- ownerAvatar = avatar,+ // The avatar of the copy on storage (same artist) until the new one is known.+ ownerAvatar = saved?.takeIf { it.ownerUri == firstArtist?.uri.orEmpty() }?.ownerAvatar.orEmpty(),ownerUri = firstArtist?.uri.orEmpty(),metaLine = listOf(type, dateLabel(album.releaseDate)).filter { it.isNotBlank() }.joinToString(" • "),explicit = songs.any { it.explicit },tracks = songs,- )))+ )+ // Written before the first emit: a collector that only wants the first page stops the flow there.+ ScreenCache.albumPage(albumId).write(page)+ ScreenCache.pruneAlbumPages(ALBUM_PAGES_KEPT)+ emit(Response.Success(page))+ val avatar = firstArtist?.let { runCatching { api.catalog.artist(it.uri) }.getOrNull() }?.images?.let(::cover).orEmpty()+ if (avatar.isNotBlank() && avatar != page.ownerAvatar) {+ val withAvatar = page.copy(ownerAvatar = avatar)+ ScreenCache.albumPage(albumId).write(withAvatar)+ emit(Response.Success(withAvatar))+ }}- suspend fun getPlaylistPage(playlistId: String): Flow<Response<ContextPageModel>> = flow {+ /**+ * A playlist as a page. Its details are always asked for; its songs are kept in memory for+ * [PlaylistFresh.FRESH_MS] after a full read and reused when the playlist still has as many+ * songs, so reopening it does not read every page again. An edit made here drops them+ * ([invalidatePlaylist]); [force] (a reload) reads everything.+ */+ suspend fun getPlaylistPage(playlistId: String, force: Boolean = false): Flow<Response<ContextPageModel>> = flow {emit(Response.Loading())if (!ready()) { emit(Response.Error(notSignedIn())); return@flow }val uri = "spotify:playlist:$playlistId"+ val fresh = if (force) null else PlaylistFresh.get(uri)// The first songs are asked for together with the playlist's details, not after them.- val firstPage = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.currentCoroutineContext()).async(Dispatchers.IO) {+ val flowScope = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.currentCoroutineContext())+ fun startFirstPage() = flowScope.async(Dispatchers.IO) {runCatching { api.playlists.tracks(uri, 0, 100) }}+ var firstPage = if (fresh == null) startFirstPage() else nullval pl = runCatching { api.playlists.playlist(uri) }.getOrElse {- firstPage.cancel()+ firstPage?.cancel()emit(Response.Error(context.getString(R.string.playlist_not_found))); return@flow}+ if (fresh != null && fresh.size != pl.trackCount) firstPage = startFirstPage()val saves = pl.followers?.takeIf { it > 0 }?.let {context.resources.getQuantityString(R.plurals.profile_list_item_saves_count, it.coerceAtMost(Int.MAX_VALUE.toLong()).toInt(), it)}.orEmpty()@@ -833,15 +924,22 @@ class Api constructor(// playlist took about two minutes (tester report).val songs = ArrayList<SongsModel>()var failed = false- val first = firstPage.await().getOrElse { failed = true; null }fun publish(done: Boolean): Response<ContextPageModel> {SongPlayer.registerContext(songs.map { it.url }, uri)+ // Kept before the emit: a collector that stops at the complete page ends the flow there.+ if (done && !failed) PlaylistFresh.put(uri, songs.toList())val total = songs.sumOf { it.durationMs.toLong() }val meta = listOf(saves, if (total > 0) durationLabel(total) else "").filter { it.isNotBlank() }.joinToString(" • ")// A playlist without a cover of its own shows the mosaic of its songs' albums, as in the official app.val cover = header.coverUri.ifBlank { com.music.spotui.ui.components.mosaicCoverFor(songs.take(200).map { it.coverUri }) }return Response.Success(header.copy(coverUri = cover, metaLine = meta, tracks = songs.toList(), complete = done))}+ if (firstPage == null) {+ songs += fresh!!+ emit(publish(done = true))+ return@flow+ }+ val first = firstPage.await().getOrElse { failed = true; null }if (first != null) {songs += first.items.map(::songOf)val offsets = generateSequence(first.nextOffset) { (it + PLAYLIST_PAGE).takeIf { n -> n < first.total } }.toList()@@ -1052,3 +1150,7 @@ class Api constructor(private const val PLAYLIST_PAGE = 100private const val PLAYLIST_PARALLEL = 4private const val PLAYLIST_EMIT_MS = 350L+/** A Liked Songs list read in full is trusted this long: only its newest page is read again. */+private const val LIKED_FULL_MS = 24 * 3_600_000L+/** Album pages kept on storage. */+private const val ALBUM_PAGES_KEPT = 30diff --git a/base/app/src/main/java/com/music/spotui/data/api/LyricsApi.kt b/base/app/src/main/java/com/music/spotui/data/api/LyricsApi.ktindex e77e752d..d5fdd301 100644--- a/base/app/src/main/java/com/music/spotui/data/api/LyricsApi.kt+++ b/base/app/src/main/java/com/music/spotui/data/api/LyricsApi.kt@@ -48,7 +48,13 @@ object LyricsApi {// "not found" is often just a timeout, not a fact.private class Miss(val at: Long = System.currentTimeMillis())private const val MISS_RETRY_MS = 120_000L- private val cache = java.util.concurrent.ConcurrentHashMap<String, Any>() // Lyrics | Miss+ // Newest MEMORY_MAX tracks only; the older ones are on storage (LyricsDisk) or asked for again.+ private const val MEMORY_MAX = 100+ private val cache: MutableMap<String, Any> = java.util.Collections.synchronizedMap( // Lyrics | Miss+ object : LinkedHashMap<String, Any>(128, 0.75f, true) {+ override fun removeEldestEntry(eldest: MutableMap.MutableEntry<String, Any>) = size > MEMORY_MAX+ }+ )private val inFlight = java.util.concurrent.ConcurrentHashMap<String, kotlinx.coroutines.Deferred<Lyrics?>>()private val scope =kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.SupervisorJob() + kotlinx.coroutines.Dispatchers.IO)@@ -78,10 +84,10 @@ object LyricsApi {scope.launch { runCatching { fetch(track) } }}- fun forget(track: Track) { cache.remove(track.key) }+ fun forget(track: Track) { cache.remove(track.key); scope.launch { LyricsDisk.drop(track.key) } }/** A setting changed what is looked for: every song is read again when next shown. */- fun forgetAll() { cache.clear() }+ fun forgetAll() { cache.clear(); scope.launch { LyricsDisk.clear() } }suspend fun fetch(track: Track): Lyrics? {when (val c = cache[track.key]) {@@ -91,7 +97,8 @@ object LyricsApi {// One request per track even when the card and the full screen ask together.val job = synchronized(inFlight) {inFlight[track.key] ?: scope.async(start = kotlinx.coroutines.CoroutineStart.LAZY) {- resolve(track)+ // Read on an earlier run: from storage, not asked for again.+ LyricsDisk.read(track.key)?.also { cache[track.key] = it } ?: resolve(track)}.also { created ->inFlight[track.key] = createdcreated.invokeOnCompletion { inFlight.remove(track.key, created) }@@ -119,10 +126,85 @@ object LyricsApi {}val result = com.music.spotui.extensions.LyricsMerge.choose(own, fromExt)cache[track.key] = result ?: Miss()+ result?.let { LyricsDisk.write(track.key, it) }Log.d("LyricsApi", "${track.title}: ${result?.let { "${it.lines.size} lines from ${it.provider}, synced=${it.synced}, words=${it.wordSynced}" } ?: "none"}")result}+ /**+ * The lyrics of the last [MAX_FILES] tracks, one file each in private storage, so a song heard+ * before is not looked up again after a restart. Only line- or word-synced lyrics are kept (a+ * plain text or a Free-cap preview may just be a fallback of the moment), for [MAX_AGE_MS].+ * The oldest file by last use goes first. Every call copes with there being no app (unit tests).+ */+ private object LyricsDisk {+ private const val MAX_FILES = 300+ private const val MAX_AGE_MS = 14 * 24 * 3_600_000L+ private val dir: java.io.File? by lazy {+ runCatching { java.io.File(com.music.spotui.di.Graph.app.filesDir, "lyrics_cache1").also { it.mkdirs() } }.getOrNull()+ }+ private var writes = 0++ private fun file(key: String): java.io.File? {+ val sha = java.security.MessageDigest.getInstance("SHA-1").digest(key.toByteArray())+ return dir?.let { java.io.File(it, sha.joinToString("") { b -> "%02x".format(b) } + ".json") }+ }++ fun read(key: String): Lyrics? = runCatching {+ val f = file(key)?.takeIf { it.exists() } ?: return null+ val o = JSONObject(f.readText())+ if (o.getString("key") != key) return null+ if (System.currentTimeMillis() - o.getLong("at") > MAX_AGE_MS) { f.delete(); return null }+ f.setLastModified(System.currentTimeMillis()) // used just now: it stays+ decode(o)+ }.onFailure { Log.w("LyricsApi", "unreadable lyrics file: ${it.javaClass.simpleName}") }.getOrNull()++ fun write(key: String, lyrics: Lyrics) {+ if (!lyrics.synced || !lyrics.uncapped || lyrics.isEmpty) return+ runCatching {+ val f = file(key) ?: return+ val o = encode(lyrics).put("key", key).put("at", System.currentTimeMillis())+ val tmp = java.io.File(f.parentFile, f.name + ".tmp")+ tmp.writeText(o.toString())+ if (!tmp.renameTo(f)) { f.delete(); tmp.renameTo(f) }+ if (++writes % 20 == 0) prune()+ }.onFailure { Log.w("LyricsApi", "could not keep lyrics: ${it.javaClass.simpleName}") }+ }++ fun drop(key: String) { runCatching { file(key)?.delete() } }++ fun clear() { runCatching { dir?.listFiles()?.forEach { it.delete() } } }++ private fun prune() {+ dir?.listFiles { f -> f.name.endsWith(".json") }+ ?.sortedByDescending { it.lastModified() }?.drop(MAX_FILES)?.forEach { it.delete() }+ }++ private fun encode(l: Lyrics) = JSONObject()+ .put("synced", l.synced).put("language", l.language).put("provider", l.provider)+ .put("colors", l.colors?.let { JSONArray(listOf(it.background, it.text, it.highlight)) })+ .put("lines", JSONArray().also { arr ->+ l.lines.forEach { line ->+ arr.put(JSONObject().put("t", line.timeMs).put("x", line.text).also { lo ->+ line.words?.let { ws -> lo.put("w", JSONArray().also { wa -> ws.forEach { w -> wa.put(JSONArray(listOf(w.startMs, w.endMs, w.text))) } }) }+ })+ }+ })++ private fun decode(o: JSONObject): Lyrics {+ val colors = o.optJSONArray("colors")?.let { LyricsColors(it.getInt(0), it.getInt(1), it.getInt(2)) }+ val lines = o.getJSONArray("lines").let { arr ->+ List(arr.length()) { i ->+ val lo = arr.getJSONObject(i)+ val words = lo.optJSONArray("w")?.let { wa -> List(wa.length()) { j -> wa.getJSONArray(j).let { LyricWord(it.getLong(0), it.getLong(1), it.getString(2)) } } }+ LyricLine(lo.getLong("t"), lo.getString("x"), words)+ }+ }+ return Lyrics(lines, o.getBoolean("synced"), o.optString("language").takeIf { it.isNotEmpty() && it != "null" },+ o.optString("provider").takeIf { it.isNotEmpty() && it != "null" }, colors)+ }+ }+/** Whether lyrics extensions are installed and running (false in unit tests: no app). */private fun extensionsAsked(): Boolean = runCatching { com.music.spotui.extensions.Extensions.hasLyrics() }.getOrDefault(false)diff --git a/base/app/src/main/java/com/music/spotui/data/api/ScreenCache.kt b/base/app/src/main/java/com/music/spotui/data/api/ScreenCache.ktindex 1d705197..345e07ca 100644--- a/base/app/src/main/java/com/music/spotui/data/api/ScreenCache.kt+++ b/base/app/src/main/java/com/music/spotui/data/api/ScreenCache.kt@@ -16,7 +16,7 @@ import kotlinx.serialization.json.Jsonimport java.io.File/**- * The last home feed, library and Liked Songs (and a few playlist pages), kept on disk: after a restart the screens+ * The last home feed, library and Liked Songs (and a few playlist and album pages), kept on disk: after a restart the screens* show them at once, while the hidden Web Player is still starting, then refresh.* Private app storage; cleared on logout ([clear]).*/@@ -34,6 +34,25 @@ object ScreenCache {val libraryRoot = Entry("library_root", ListSerializer(LibraryEntry.serializer()))val liked = Entry("liked", ListSerializer(SongsModel.serializer()))+ /**+ * When Liked Songs were last read in full from Spotify (not just their newest page): the list+ * on storage is trusted for a day after that, see Api.getLikedPage. Null when never.+ */+ fun likedFullAt(): Long? = runCatching { File(dir, "liked_full.stamp").takeIf { it.exists() }?.readText()?.trim()?.toLong() }.getOrNull()++ fun markLikedFull() { io.launch { runCatching { File(dir, "liked_full.stamp").writeText(System.currentTimeMillis().toString()) } } }++ /** An album page opened before, one file per album: it opens whole at once, the network refreshing it behind. */+ fun albumPage(id: String) = Entry("album_page_$id", com.music.spotui.data.entity.ContextPageModel.serializer())++ /** Keeps the [keep] most recent album pages on storage and deletes the others. */+ fun pruneAlbumPages(keep: Int) {+ io.launch {+ dir.listFiles { f -> f.name.startsWith("album_page_") && f.name.endsWith(".json") }+ ?.sortedByDescending { it.lastModified() }?.drop(keep)?.forEach { it.delete() }+ }+ }+/** A playlist page fetched ahead (see PagePrefetch), one file per playlist. */fun page(id: String) = Entry("page_$id", com.music.spotui.data.entity.ContextPageModel.serializer())diff --git a/base/app/src/main/java/com/music/spotui/data/api/SpotifySync.kt b/base/app/src/main/java/com/music/spotui/data/api/SpotifySync.ktindex f0e8cc97..b2c3548a 100644--- a/base/app/src/main/java/com/music/spotui/data/api/SpotifySync.kt+++ b/base/app/src/main/java/com/music/spotui/data/api/SpotifySync.kt@@ -40,7 +40,7 @@ object SpotifySync {scope.launch {val ok = runCatching { api.playlists.addTracks("spotify:playlist:$playlistId", listOf("spotify:track:$trackId")) }.onFailure { Log.w(TAG, "add $trackId to $playlistId failed: ${it.message}") }.isSuccess- if (ok) membershipCache[playlistId]?.add(trackId)+ if (ok) { membershipCache[playlistId]?.add(trackId); Api.invalidatePlaylist(playlistId) }if (ok) com.music.spotui.data.offline.OfflineCollections.refreshOne(context.applicationContext, "spotify:playlist:$playlistId")onDone(ok)}@@ -57,7 +57,7 @@ object SpotifySync {val ok = runCatching { api.playlists.addTracks("spotify:playlist:$playlistId", uris) }.onFailure { Log.w(TAG, "add ${uris.size} songs to $playlistId failed: ${it.message}") }.isSuccess// Part of it may be in even when refused: read the playlist again when asked.- membershipCache.remove(playlistId)+ membershipCache.remove(playlistId); Api.invalidatePlaylist(playlistId)com.music.spotui.data.offline.OfflineCollections.refreshOne(context.applicationContext, "spotify:playlist:$playlistId")onDone(ok)}@@ -78,7 +78,7 @@ object SpotifySync {api.playlists.removeTracks(uri, listOf(uid))}.onFailure { Log.w(TAG, "remove row $rowUid ($trackId) from $playlistId failed: ${it.message}") }.isSuccess// The song may still be in the playlist through another row: read it again when asked.- if (ok) membershipCache.remove(playlistId)+ if (ok) { membershipCache.remove(playlistId); Api.invalidatePlaylist(playlistId) }onDone(ok)}}@@ -96,7 +96,7 @@ object SpotifySync {check(uids.isNotEmpty()) { "track not in playlist" }api.playlists.removeTracks(uri, uids)}.onFailure { Log.w(TAG, "remove $trackId from $playlistId failed: ${it.message}") }.isSuccess- if (ok) membershipCache[playlistId]?.remove(trackId)+ if (ok) { membershipCache[playlistId]?.remove(trackId); Api.invalidatePlaylist(playlistId) }onDone(ok)}}diff --git a/base/app/src/main/java/com/music/spotui/data/api/SupportReminder.kt b/base/app/src/main/java/com/music/spotui/data/api/SupportReminder.ktindex f2b94d38..6981c88b 100644--- a/base/app/src/main/java/com/music/spotui/data/api/SupportReminder.kt+++ b/base/app/src/main/java/com/music/spotui/data/api/SupportReminder.kt@@ -9,6 +9,8 @@ import androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.setValueimport androidx.compose.ui.graphics.Color+import com.music.spotui.data.preferences.Look+import com.music.spotui.data.preferences.LookPref/*** Donations and their thank-yous. Reminders: a day after first use, then every 2 weeks;@@ -29,6 +31,10 @@ object SupportReminder {const val EVERY_MS = 14L * 24 * 3_600_000const val SUPPORTER_EVERY_MS = 90L * 24 * 3_600_000private const val PREFS = "support_reminder"+ /** The single accent of earlier versions, copied to both looks once ([init]). */+ private const val KEY_ACCENT = "accent"+ private const val KEY_ACCENT_CLASSIC = "accent_classic"+ private const val KEY_ACCENT_IMMERSIVE = "accent_immersive"enum class Level { NONE, ONCE, MONTHLY }@@ -45,17 +51,23 @@ object SupportReminder {private var storedLevel by mutableStateOf(Level.NONE)/** The supporter level in effect (NONE while perks are off). */val level: Level get() = if (PERKS_ENABLED) storedLevel else Level.NONE- /** The accent chosen (applied only for supporters). */- var accent by mutableStateOf(Accent.GREEN)+ /** The accent chosen for the Classic look. */+ var classicAccent by mutableStateOf(Accent.GREEN)private set- /** A colour was picked (green is also the default): the Immersive look has its own default accent until then. */- var accentChosen by mutableStateOf(false)+ /** The accent chosen for the Immersive look. */+ var immersiveAccent by mutableStateOf(Accent.GREEN)+ private set+ /** A colour was picked for Immersive (green is also the default): the look has its own default accent until then. */+ var immersiveAccentChosen by mutableStateOf(false)private setvar icon by mutableStateOf(Accent.GREEN)private set- /** The colour the whole app uses for its accent (Spotify green unless another was chosen in Settings). */- val accentColor: Color get() = accent.color+ /** The accent chosen for a look. */+ fun accentOf(look: Look): Accent = if (look == Look.IMMERSIVE) immersiveAccent else classicAccent++ /** The colour the active look uses for its accent (Spotify green unless another was chosen in Settings). */+ val accentColor: Color get() = accentOf(LookPref.look).color/** When the next reminder is due. */fun nextAt(firstSeen: Long, lastShown: Long, level: Level, supportedAt: Long): Long = when (level) {@@ -69,8 +81,14 @@ object SupportReminder {fun init(context: Context) {val p = prefs(context)storedLevel = runCatching { Level.valueOf(p.getString("level", "NONE")!!) }.getOrDefault(Level.NONE)- accent = Accent.entries.firstOrNull { it.key == p.getString("accent", "green") } ?: Accent.GREEN- accentChosen = p.contains("accent")+ // One accent used to serve both looks: whoever picked one keeps it for each look.+ if (p.contains(KEY_ACCENT) && !p.contains(KEY_ACCENT_CLASSIC) && !p.contains(KEY_ACCENT_IMMERSIVE)) {+ val old = p.getString(KEY_ACCENT, "green")+ p.edit().putString(KEY_ACCENT_CLASSIC, old).putString(KEY_ACCENT_IMMERSIVE, old).apply()+ }+ classicAccent = Accent.entries.firstOrNull { it.key == p.getString(KEY_ACCENT_CLASSIC, "green") } ?: Accent.GREEN+ immersiveAccent = Accent.entries.firstOrNull { it.key == p.getString(KEY_ACCENT_IMMERSIVE, "green") } ?: Accent.GREEN+ immersiveAccentChosen = p.contains(KEY_ACCENT_IMMERSIVE)icon = Accent.entries.firstOrNull { it.key == p.getString("icon", "green") } ?: Accent.GREEN}@@ -89,10 +107,15 @@ object SupportReminder {prefs(context).edit().putString("level", value.name).putLong("supported_at", System.currentTimeMillis()).apply()}- fun setAccent(context: Context, value: Accent) {- accent = value- accentChosen = true- prefs(context).edit().putString("accent", value.key).apply()+ fun setAccent(context: Context, look: Look, value: Accent) {+ if (look == Look.IMMERSIVE) {+ immersiveAccent = value+ immersiveAccentChosen = true+ prefs(context).edit().putString(KEY_ACCENT_IMMERSIVE, value.key).apply()+ } else {+ classicAccent = value+ prefs(context).edit().putString(KEY_ACCENT_CLASSIC, value.key).apply()+ }}/**diff --git a/base/app/src/main/java/com/music/spotui/data/local/LocalPlaylists.kt b/base/app/src/main/java/com/music/spotui/data/local/LocalPlaylists.ktindex cfd878bf..91ac3bdb 100644--- a/base/app/src/main/java/com/music/spotui/data/local/LocalPlaylists.kt+++ b/base/app/src/main/java/com/music/spotui/data/local/LocalPlaylists.kt@@ -6,6 +6,10 @@ import androidx.compose.runtime.mutableStateMapOfimport androidx.compose.runtime.snapshots.SnapshotStateMapimport org.json.JSONArrayimport org.json.JSONObject+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launchimport java.io.Fileimport java.util.UUID@@ -50,10 +54,23 @@ object LocalPlaylists {/** Spotify playlist id → phone files added to it on this phone. */val additions: SnapshotStateMap<String, List<LocalItem>> = mutableStateMapOf()+ @Volatile private var loaded = false+fun init(context: Context) {if (::file.isInitialized) returnfile = File(context.filesDir, "local_playlists.json")- runCatching { read(file.readText()) }+ // Read off the main thread; the screens show the lists as they land, and a change made+ // before then reads the file first ([ensureLoaded]) so it cannot overwrite it.+ CoroutineScope(SupervisorJob() + Dispatchers.IO).launch { ensureLoaded() }+ }++ private fun ensureLoaded() {+ if (loaded) return+ synchronized(lock) {+ if (loaded || !::file.isInitialized) return+ loaded = true+ runCatching { read(file.readText()) }+ }}/** Newest first. */@@ -84,6 +101,7 @@ object LocalPlaylists {private fun update(change: () -> Unit) {synchronized(lock) {+ ensureLoaded()change()if (::file.isInitialized) {val tmp = File(file.parentFile, file.name + ".tmp")diff --git a/base/app/src/main/java/com/music/spotui/data/offline/OfflineCollections.kt b/base/app/src/main/java/com/music/spotui/data/offline/OfflineCollections.ktindex d498966a..2a445404 100644--- a/base/app/src/main/java/com/music/spotui/data/offline/OfflineCollections.kt+++ b/base/app/src/main/java/com/music/spotui/data/offline/OfflineCollections.kt@@ -8,11 +8,12 @@ import com.music.spotui.data.api.Responseimport com.music.spotui.data.entity.ContextPageModelimport com.music.spotui.data.entity.SongsModelimport com.music.spotui.di.Graph+import kotlinx.coroutines.CoroutineExceptionHandlerimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.SupervisorJobimport kotlinx.coroutines.delay-import kotlinx.coroutines.flow.first+import kotlinx.coroutines.flow.firstOrNullimport kotlinx.coroutines.launchimport kotlinx.coroutines.withContextimport kotlinx.coroutines.withTimeoutOrNull@@ -42,7 +43,8 @@ object OfflineCollections {private const val SYNC_EVERY_MS = 6 * 3_600_000Lprivate lateinit var file: Fileprivate val lock = Any()- private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+ // A refresh that fails (no network, a page that cannot be read) is logged, never a crash of the app.+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO + CoroutineExceptionHandler { _, e -> Log.w(TAG, "refresh failed: ${e.javaClass.simpleName}: ${e.message}") })val collections: SnapshotStateMap<String, OfflineCollection> = mutableStateMapOf()/** Songs downloaded on their own, kept whatever the lists do. */@@ -168,8 +170,15 @@ object OfflineCollections {if (com.music.spotui.data.DataSaver.metered) { waitForWifi(); return@launch }val due = collections.values.filter { force || System.currentTimeMillis() - it.syncedAt > SYNC_EVERY_MS }for (c in due) {- val page = withTimeoutOrNull(60_000) { loadComplete(c) } ?: continue- withContext(Dispatchers.Main) { sync(page) }+ // One list that fails does not stop the others.+ try {+ val page = withTimeoutOrNull(60_000) { loadComplete(c) } ?: continue+ withContext(Dispatchers.Main) { sync(page) }+ } catch (e: kotlinx.coroutines.CancellationException) {+ throw e+ } catch (e: Throwable) {+ Log.w(TAG, "${c.name} not refreshed: ${e.javaClass.simpleName}: ${e.message}")+ }}}}@@ -193,11 +202,12 @@ object OfflineCollections {val api = Graph.apival id = c.uri.substringAfterLast(":")val flow = when (c.type) {- "album" -> api.getAlbumPage(id)+ "album" -> api.getAlbumPage(id, stored = false)"liked" -> api.getLikedPage()else -> api.getPlaylistPage(id)}- return (flow.first { it is Response.Error || (it is Response.Success && it.data.complete) } as? Response.Success)?.data+ // A flow that ends without a complete page (the player never ready) is no page, not an error.+ return (flow.firstOrNull { it is Response.Error || (it is Response.Success && it.data.complete) } as? Response.Success)?.data}private fun save() {diff --git a/base/app/src/main/java/com/music/spotui/data/offline/OfflineDownloader.kt b/base/app/src/main/java/com/music/spotui/data/offline/OfflineDownloader.ktindex 7b9a0735..ac6cb09d 100644--- a/base/app/src/main/java/com/music/spotui/data/offline/OfflineDownloader.kt+++ b/base/app/src/main/java/com/music/spotui/data/offline/OfflineDownloader.kt@@ -106,11 +106,14 @@ object OfflineDownloader {/** Re-queues what was waiting when the app last stopped. */fun resumePending() {- val saved = runCatching {- val a = JSONArray(OfflineStore.pendingFile.readText())- (0 until a.length()).map { Request.fromJson(a.getJSONObject(it)) }- }.getOrDefault(emptyList())- if (saved.isNotEmpty()) enqueueAll(saved)+ // Read off the main thread (the app is already drawing): the queue fills a moment later.+ scope.launch {+ val saved = runCatching {+ val a = JSONArray(OfflineStore.pendingFile.readText())+ (0 until a.length()).map { Request.fromJson(a.getJSONObject(it)) }+ }.getOrDefault(emptyList())+ if (saved.isNotEmpty()) enqueueAll(saved)+ }}/**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 30b8768a..849b7114 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@@ -47,6 +47,23 @@ object AutoplayPref {}}+/**+ * "Count extension plays on Spotify" (on by default): a song an extension streams is played by the+ * Web Player too, unheard, so Spotify counts it and Spotify Connect sees and controls it (see+ * [com.music.spotui.di.ConnectMirror]). Off: the extension's stream alone, as before.+ */+object ConnectMirrorPref {+ private const val KEY = "connect_mirror"+ 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()+ com.music.spotui.di.ConnectMirror.settingChanged()+ }+}+/*** The automatic update check at launch (on by default: the app behaved that way before this* option existed). Off means no check when the app starts — a check asked for in Settings stilldiff --git a/base/app/src/main/java/com/music/spotui/di/ConnectMirror.kt b/base/app/src/main/java/com/music/spotui/di/ConnectMirror.ktnew file mode 100644index 00000000..755940d0--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/di/ConnectMirror.kt@@ -0,0 +1,493 @@+package com.music.spotui.di++import android.os.Handler+import android.os.Looper+import android.os.SystemClock+import app.myspoti.api.PlayerState+import app.myspoti.host.android.MyspotiRuntime+import com.music.spotui.data.local.LocalTrack+import com.music.spotui.data.preferences.ConnectMirrorPref+import com.music.spotui.di.MirrorRules.Follow+import com.music.spotui.di.MirrorRules.Lead+import com.music.spotui.di.MirrorRules.Want+import kotlinx.coroutines.Job+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.combine+import kotlinx.coroutines.flow.distinctUntilChanged+import kotlinx.coroutines.launch+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock++/**+ * "Count extension plays on Spotify": while the local player plays a song an extension streams, the+ * Web Player plays the same Spotify song at the same place, unheard and at its lowest quality. The+ * phone stays one Spotify Connect device whatever makes the sound: Spotify's apps (and Myspoti on+ * another phone) see the song and command it. Their pause, seek or skip reach the page, whose state+ * the local player follows here; the phone's own controls drive the local player as before, and the+ * page follows it. The play is the page's own, counted by Spotify as any other: the app reports+ * nothing itself. Downloads and files of the device are never mirrored.+ *+ * Everything runs on the main thread, on the two players' own events (and one slow drift check).+ */+object ConnectMirror {+ private const val SPOTIFY_TRACK_PREFIX = "spotify:track:"+ /** A play is answered within that (the page loads the song, then reports it). */+ private const val PLAY_ECHO_MS = 6_000L+ /** A pause, resume or seek is answered within that. */+ private const val ECHO_MS = 2_500L+ /** The local player buffering longer than this: the page waits for it. */+ private const val STALL_MS = 1_000L+ /** The slow check of the drift between two events (the page reports changes, not its clock). */+ private const val DRIFT_CHECK_MS = 20_000L+ /** A play the page did not take is sent once more at once, then again later (see MirrorRules.backoffMs). */+ private const val MAX_RETRIES = 1+ /** After the echo window, before the state hidden by it is judged again. */+ private const val RECHECK_SLACK_MS = 100L+ /** A song the mirror asked the page to play this recently: a state on it is a late answer, not a remote command. */+ private const val RECENT_MS = 15_000L+ private const val MAX_RECENT = 4+ /** How often the asked song is sent again after late answers to earlier plays (then it is a play not taken). */+ private const val MAX_RESENDS = 2+ /** Songs the local player starts closer than this are sent to the page as one play (fast skips). */+ private const val START_COALESCE_MS = 300L+ /**+ * After an ad or a reload, the player's own recovery plays songs too (the pick before the ad, the+ * song "ahead" of the next ad): for that long, another song on the page is never a remote command.+ */+ private const val RECOVER_MS = 10_000L+ /** At most that many lists remembered as putting the page on another song. */+ private const val MAX_MISSED = 32++ private val api get() = MyspotiRuntime.api+ private val page get() = MyspotiRuntime.spotify.player+ private val main = Handler(Looper.getMainLooper())+ private val echo = MirrorRules.Echo(SystemClock::elapsedRealtime)+ private val lock = Mutex()+ /** Bumped when the mirror ends: commands still waiting for the lock are dropped. */+ private var generation = 0++ /** The mirror holds the page: unheard, at its lowest quality, following and followed. */+ @Volatile var running = false+ private set+ private var want: Want? = null+ /** The song the page was asked to be on before [want]'s (a stale state may still show it). */+ private var previousUri: String? = null+ /** Where the page stood on [want]'s song when a buffering gap began (see MirrorRules.onWeb); null: no gap. */+ private var gapFrom: Long? = null+ /** The local player's song at the last event (a new one forgets [failedUri]). */+ private var localUri: String? = null+ /** The local player at its last event: whether it played, where, when (for [MirrorRules.localMoved]). */+ private var localWasPlaying = false+ private var localAtMs = 0L+ private var localAtTime = 0L+ private var landed = false+ private var retries = 0+ private var resends = 0+ /** The plays the mirror sent lately: song and when (elapsed realtime), newest last. */+ private val recentPlays = ArrayDeque<Pair<String, Long>>()+ /** A play waiting [START_COALESCE_MS] for a quicker skip: its context. */+ private var pendingContext: String? = null+ /** The page's last state of [want]'s song (where it should be now). */+ private var lastWeb: PlayerState? = null+ private var stalled = false+ private var stallPending = false+ /**+ * A song the page would not play: the local player plays it alone meanwhile, the page paused+ * (still unheard, still at its lowest quality), and it is tried again ([backOff]).+ */+ private var failedUri: String? = null+ private var backoffStep = 0+ /** The list of the mirror's last play there (what a play not taken blames). */+ private var playedContext: String? = null+ /** Lists that put the page on another song than the asked one: their songs are played alone. */+ private val missedContexts = HashSet<String>()+ /** Until then (elapsed realtime) the page recovers from an ad or a reload (see [RECOVER_MS]). */+ private var recoverUntil = 0L+ /** Playback went to another device while mirrored: it comes back through the extensions. */+ private var handedAway = false+ private var driftJob: Job? = null+ /** The end of the last mirror (page heard again, quality back): the next command waits for it. */+ private var ending: Job? = null+ private var attached = false++ /** Follows the page's Connect status (read by its watcher, no call of its own). Once, at start. */+ fun attach() {+ if (attached) return+ attached = true+ MyspotiRuntime.scope.launch { page.playsElsewhere.collect { away -> if (away) wentAway() else cameBack() } }+ // Commands are held during an ad and while the page reloads (it refuses them: "local player+ // is disabled"); the page usable again gets the song the local player is on, where it is.+ MyspotiRuntime.scope.launch {+ combine(api.ready, page.adPlaying) { ready, ad -> ready && !ad }.distinctUntilChanged().collect { usable -> if (usable) pageBack() }+ }+ }++ /** The page can take commands: loaded, and no ad on. */+ private fun pageUsable(): Boolean = api.ready.value && !page.adPlaying.value++ /** The local player's song or state changed (SongPlayer.onLocalState, main thread). */+ fun onLocal(t: LocalTrack, playing: Boolean, positionMs: Long, durationMs: Long) {+ val id = LocalPlayer.spotifyIdOf(t)+ val origin = when (t.uri.scheme) {+ com.music.spotui.extensions.ExtensionAudio.SCHEME -> MirrorRules.Origin.AUDIO_SOURCE+ "file" -> MirrorRules.Origin.DOWNLOAD+ else -> MirrorRules.Origin.LOCAL_FILE+ }+ val uri = SPOTIFY_TRACK_PREFIX + id+ val now = SystemClock.elapsedRealtime()+ val expected = if (uri != localUri) null else localAtMs + if (localWasPlaying) now - localAtTime else 0L+ val moved = MirrorRules.localMoved(localWasPlaying, playing, expected, positionMs)+ if (uri != localUri) { localUri = uri; failedUri = null; backoffStep = 0 }+ localWasPlaying = playing; localAtMs = positionMs; localAtTime = now+ if (!MirrorRules.eligible(origin, id, ConnectMirrorPref.on, com.music.spotui.data.DataSaver.active)) {+ if (running) stop(if (origin == MirrorRules.Origin.AUDIO_SOURCE) "not mirrored: ${t.title}" else "a download or a file of the phone plays")+ return+ }+ if (running) trackStall(playing)+ // Backing off a song the page would not play: a play, resume or seek here tries it again now.+ if (running && failedUri == uri && pendingContext != null && moved && playing) {+ log("tried again on the page at a play or seek: $uri")+ main.removeCallbacks(sendPlay); sendPlay.run()+ }+ val w = want+ val local = MirrorRules.Local(uri, playing, positionMs, durationMs)+ // Another device has Connect: a pause or a seek from here would act on it.+ val elsewhere = page.playsElsewhere.value+ when (val lead = MirrorRules.onLocal(local, w, stalled, echo.quiet(), webAt(w), previousUri)) {+ Lead.Nothing -> {}+ is Lead.Start -> start(lead.uri, lead.positionMs)+ // A play still waiting (see [start]) is held instead: nothing plays there yet.+ Lead.Pause -> { want = w?.copy(paused = true); if (!elsewhere && pendingContext == null) command(ECHO_MS) { api.player.pause() } }+ is Lead.Resume -> {+ // Another device took Connect meanwhile: a resume would resume it; the song is played here again.+ if (elsewhere) start(uri, positionMs)+ else if (pendingContext != null) { want = w?.copy(paused = false); main.removeCallbacks(sendPlay); sendPlay.run() }+ else {+ want = w?.copy(paused = false)+ command(ECHO_MS) { lead.alignMs?.let { api.player.seek(it) }; api.player.resume() }+ }+ }+ is Lead.Align -> if (!elsewhere && pendingContext == null) { log("${lead.ms - (webAt(w) ?: lead.ms)} ms out of step: the page is put back"); command(ECHO_MS) { api.player.seek(lead.ms) } }+ }+ }++ /** A state of the page while the mirror runs (SongPlayer.engineWhileLocal): a remote command, or our own echo. */+ fun onWeb(s: PlayerState) {+ val w = want ?: return+ val item = s.item ?: return+ val now = System.currentTimeMillis()+ // An ad, a song still loading, Spotify limiting plays: nothing to judge on. The page's clock+ // after it lies between where it stood then and where its last state puts it: both are kept+ // for the seek test (a seek just before the gap is still followed, a stall in it is not one).+ if (s.isBuffering || page.adPlaying.value || MyspotiRuntime.host.licenseLimited()) {+ if (gapFrom == null) gapFrom = lastWeb?.takeIf { it.item?.uri == w.uri }?.positionAt(now)+ return+ }+ val web = MirrorRules.Web(item.uri, s.isPaused, s.positionAt(now))+ val before = lastWeb?.takeIf { it.item?.uri == w.uri }+ val predicted = before?.takeIf { item.uri == w.uri }?.positionAt(now)+ // Where the page is in the asked song, and its length as Spotify has it (the end it reaches).+ val wantAt = if (item.uri == w.uri) web.positionMs else before?.positionAt(now)+ val wantLength = (if (item.uri == w.uri) item.durationMs else before?.item?.durationMs) ?: 0L+ val gap = gapFrom+ gapFrom = null+ if (item.uri == w.uri) lastWeb = s+ if (item.uri == w.uri && !s.isPaused) {+ if (failedUri == w.uri) log("the page plays ${w.uri} again")+ landed = true; failedUri = null; backoffStep = 0+ }+ val t = LocalPlayer.current() ?: return+ val (previousId, nextId) = LocalPlayer.neighbourIds()+ val local = MirrorRules.Local(+ SPOTIFY_TRACK_PREFIX + LocalPlayer.spotifyIdOf(t), LocalPlayer.playWhenReady(), LocalPlayer.position(), LocalPlayer.duration(),+ nextUri = nextId.takeIf { it.isNotBlank() }?.let { SPOTIFY_TRACK_PREFIX + it },+ previousUri = previousId.takeIf { it.isNotBlank() }?.let { SPOTIFY_TRACK_PREFIX + it },+ )+ val quiet = echo.quiet()+ // A state the echo window hides is looked at again once it is over (a remote pause right after a command).+ if (quiet) { main.removeCallbacks(recheck); main.postDelayed(recheck, echo.remainingMs() + RECHECK_SLACK_MS) }+ // Recovering from an ad or a reload: a song other than the asked one is the player's own play, sent back.+ val sure = landed && SystemClock.elapsedRealtime() >= recoverUntil+ when (val f = MirrorRules.onWeb(web, w, local, quiet, sure, predicted, previousUri, gap, wantAt, wantLength, recentUris())) {+ Follow.Nothing -> {}+ // A play waits already (coalescing, backing off): not another one.+ Follow.Retry -> if (pendingContext != null) Unit else if (retries++ < MAX_RETRIES) {+ // Its list put the page elsewhere: that list's songs are played alone from now on.+ playedContext?.takeIf { it != w.uri && missedContexts.size < MAX_MISSED }?.let {+ missedContexts += it; log("$it put the page on ${web.uri}: its songs are played alone")+ }+ log("the page did not take ${w.uri}: played again")+ playNow(w.uri, w.uri)+ } else backOff(w)+ Follow.Pause -> { log("paused on another device"); want = w.copy(paused = true); LocalPlayer.pause() }+ Follow.Resume -> { log("resumed on another device"); want = w.copy(paused = false); LocalPlayer.resume() }+ is Follow.Seek -> { log("moved to ${f.ms} ms on another device"); LocalPlayer.seekTo(f.ms) }+ Follow.Next -> { log("next on another device"); moved(web, s); LocalPlayer.next() }+ Follow.Previous -> { log("previous on another device"); moved(web, s); LocalPlayer.previousItem() }+ Follow.Resend -> if (pendingContext != null) Unit else if (resends++ < MAX_RESENDS) {+ log("the page is still on ${web.uri}, played earlier by the mirror: ${w.uri} sent again")+ playNow(w.uri, w.uri)+ } else backOff(w)+ is Follow.Play -> { log("${f.uri} picked on another device"); moved(web, s); SongPlayer.followRemotePlay(item, s.contextUri, f.positionMs) }+ is Follow.Align -> command(ECHO_MS) { api.player.seek(f.ms) }+ }+ }++ /** The page's latest state, judged again when the echo window that hid it is over. */+ private val recheck: Runnable = object : Runnable {+ override fun run() {+ if (!running || !LocalPlayer.active.value || SongPlayer.routing) return+ // Renewed meanwhile (the page answered late): looked at once that one is over.+ if (echo.quiet()) { main.postDelayed(this, echo.remainingMs() + RECHECK_SLACK_MS); return }+ page.state.value?.let(::onWeb)+ }+ }++ /**+ * The page would not take [w]'s song (twice): never given up for good. It is paused meanwhile+ * (unheard, at its lowest quality, nothing else plays on the account) and the song is played there+ * again after [MirrorRules.backoffMs], or at the next play, resume or seek of the local player.+ */+ private fun backOff(w: Want) {+ val delayMs = MirrorRules.backoffMs(backoffStep++)+ failedUri = w.uri+ log("the page would not play ${w.uri}: the stream plays alone, tried again in ${delayMs / 1000} s or at the next play or seek")+ landed = false; lastWeb = null; gapFrom = null+ // One try each time from now on: a miss goes to the next, longer wait.+ retries = MAX_RETRIES; resends = MAX_RESENDS+ command(ECHO_MS) { api.player.pause() }+ pendingContext = w.uri+ main.removeCallbacks(sendPlay); main.postDelayed(sendPlay, delayMs)+ }++ /** The page is usable again after an ad or a reload: it gets the local player's song, where it is. */+ private fun pageBack() {+ val w = want?.takeIf { running } ?: return+ log("the page is back (ad over or reloaded): ${w.uri} played there again")+ landed = false; retries = 0; resends = 0; lastWeb = null; gapFrom = null+ recoverUntil = SystemClock.elapsedRealtime() + RECOVER_MS+ // The track alone: the list the page had went with the ad's or the reload's own plays.+ pendingContext = w.uri+ echo.sent(PLAY_ECHO_MS)+ main.removeCallbacks(sendPlay); main.postDelayed(sendPlay, START_COALESCE_MS)+ }++ /** The page went to [web]'s song by a remote command: that is what it is asked to be on now. */+ private fun moved(web: MirrorRules.Web, s: PlayerState) {+ previousUri = want?.uri+ want = Want(web.uri, web.paused); landed = true; retries = 0; resends = 0; lastWeb = s; gapFrom = null+ failedUri = null; backoffStep = 0+ echo.sent(PLAY_ECHO_MS)+ }++ /** The page plays [uri] from [at], unheard (the mirror starts, or goes on with the local player's next song). */+ private fun start(uri: String, at: Long) {+ if (!running) {+ running = true+ // An extension's own mirror (playback.mirror) gives way: two would fight over the page.+ com.music.spotui.extensions.Extensions.mirrorReset("Myspoti plays the song on Spotify itself")+ // The page asks Android for the audio focus as it plays: the local player must not yield it.+ LocalPlayer.setMirrorFocus(true)+ startDriftCheck()+ log("on")+ }+ handedAway = false+ previousUri = want?.uri+ want = Want(uri, paused = false); landed = false; retries = 0; resends = 0; lastWeb = null; gapFrom = null+ failedUri = null; backoffStep = 0+ // In the list the local queue came from, as the phone would play it: other devices see that queue after it.+ pendingContext = MirrorRules.playContext(LocalPlayer.contextUri, uri, missedContexts)+ log("$uri plays unheard on Spotify from $at ms")+ // A skip right after this one replaces it: one play for a burst of skips (they landed out of order).+ echo.sent(PLAY_ECHO_MS)+ main.removeCallbacks(sendPlay)+ main.postDelayed(sendPlay, START_COALESCE_MS)+ }++ private val sendPlay = Runnable {+ val w = want?.takeIf { running } ?: return@Runnable+ val context = pendingContext ?: return@Runnable+ // The local player paused or stalled meanwhile: played when it plays (Lead.Resume).+ if (w.paused) return@Runnable+ pendingContext = null+ playNow(w.uri, context)+ }++ /** Plays [uri] (in [context]) on the page from the local position, unheard, noted as the mirror's own play. */+ private fun playNow(uri: String, context: String) {+ val at = LocalPlayer.position()+ val now = SystemClock.elapsedRealtime()+ recentPlays.addLast(uri to now)+ while (recentPlays.size > MAX_RECENT) recentPlays.removeFirst()+ playedContext = context+ // Whether it landed is judged once its echo is over, even if the page reports nothing.+ main.removeCallbacks(recheck); main.postDelayed(recheck, PLAY_ECHO_MS + RECHECK_SLACK_MS)+ // An earlier mirror's end runs under the same lock, before this: never heard under this one.+ command(PLAY_ECHO_MS) { live ->+ // Before the play: the page picks the song's file with the quality it has then.+ page.setMirroring(true)+ if (!api.player.localMute) api.player.setLocalMute(true)+ // Ended meanwhile: no play that would be heard next to the local player.+ if (live()) api.player.play(context, trackUri = uri.takeIf { it != context }, positionMs = at)+ }+ }++ /** The songs the mirror asked the page to play in the last [RECENT_MS]. */+ private fun recentUris(): List<String> {+ val since = SystemClock.elapsedRealtime() - RECENT_MS+ return recentPlays.filter { it.second >= since }.map { it.first }+ }++ /**+ * Ends the mirror: the page is heard again, at the user's quality. [pausePage]: the song it played+ * is paused first (not when another device has playback, or a transfer moves it). True when it ran.+ */+ fun stop(reason: String, pausePage: Boolean = true): Boolean {+ if (!running) return false+ running = false+ generation+++ val heard = pausePage && want?.paused == false && !page.playsElsewhere.value+ want = null; previousUri = null; lastWeb = null; gapFrom = null; landed = false; stalled = false+ main.removeCallbacks(recheck)+ main.removeCallbacks(sendPlay); pendingContext = null; recentPlays.clear()+ if (stallPending) { main.removeCallbacks(stallCheck); stallPending = false }+ driftJob?.cancel(); driftJob = null+ echo.clear()+ LocalPlayer.setMirrorFocus(false)+ log("off: $reason")+ // Behind the lock: a play still on its way lands first, then is paused here. Waited for by+ // the next transport command (SongPlayer): a song Spotify plays next must find the page+ // heard, at the user's quality, the mirrored one paused. Each step on its own: a pause that+ // fails must not leave the page unheard or at its lowest quality.+ ending = MyspotiRuntime.scope.launch {+ lock.withLock {+ if (heard) runCatching { api.player.pause() }.onFailure { log("ending: pause failed: ${it.message}") }+ runCatching { api.player.setLocalMute(false) }.onFailure { log("ending: unmute failed: ${it.message}") }+ runCatching { page.setMirroring(false) }.onFailure { log("ending: quality not restored: ${it.message}") }+ }+ }+ return true+ }++ /** Waits until the last mirror's end reached the page (see [stop]). */+ suspend fun awaitEnded() { ending?.join() }++ /** Playback was handed to another device and has not come back to play here yet (see [onEngine]). */+ val waitsBack: Boolean get() = handedAway++ /** Myspoti moves playback to another device: the mirror ends there (the transfer moves the song). */+ fun leaving(device: String) {+ if (stop("playback moved to $device", pausePage = false)) handedAway = true+ }++ /** "Count extension plays on Spotify" was switched: off ends the mirror, on starts it on the song playing. */+ fun settingChanged() {+ if (!ConnectMirrorPref.on) { stop("the setting was turned off"); failedUri = null }+ else main.post(::poke)+ }++ /** Another device of the account took playback while mirrored: the local player stops, as it would have. */+ private fun wentAway() {+ if (!running || want?.paused != false) return+ log("another device took playback: the local player stops")+ handedAway = true+ // Ends the mirror too (SongPlayer.unmuteMirror); nothing to pause here, the page stands still.+ LocalPlayer.stop()+ }++ /**+ * This page is Connect's active device again. Often paused (a transfer that restores paused,+ * the phone picked in another app's list): [handedAway] then stays until the engine plays here+ * ([onEngine]), when the song goes back to the extensions.+ */+ private fun cameBack() {+ if (handedAway) page.state.value?.let { onEngine(it, moved = false, intended = SongPlayer.engineIntended()) }+ }++ /**+ * A state of the engine while no local player plays (SongPlayer.applyState). [moved]: it started+ * or changed song; [intended]: Myspoti asked for it. Playback back on this phone, or moved here+ * by another device, goes back through the extensions (the mirror starts with the local player).+ */+ fun onEngine(s: PlayerState, moved: Boolean, intended: Boolean) {+ if (LocalPlayer.active.value || SongPlayer.routing) return+ val playingHere = !s.isPaused && !s.isBuffering && s.item != null && !page.playsElsewhere.value+ if (!playingHere) return+ val back = MirrorRules.backHere(playingHere, handedAway, moved, intended, ConnectMirrorPref.on)+ handedAway = false+ if (back) SongPlayer.backThroughExtensions()+ }++ /** The local player as it is now, judged as a state of it. */+ private fun poke() {+ if (!LocalPlayer.active.value || SongPlayer.routing) return+ val t = LocalPlayer.current() ?: return+ onLocal(t, LocalPlayer.playWhenReady(), LocalPlayer.position(), LocalPlayer.duration())+ }++ /** Where the page should be now on [w]'s song, from its last state; null when unknown. */+ private fun webAt(w: Want?): Long? = if (gapFrom != null) null else+ lastWeb?.takeIf { w != null && it.item?.uri == w.uri && !it.isBuffering }?.positionAt(System.currentTimeMillis())++ private val stallCheck = Runnable {+ stallPending = false+ if (!running || !LocalPlayer.isBuffering() || !LocalPlayer.playWhenReady()) return@Runnable+ log("the local player is buffering: the page waits for it")+ stalled = true+ poke()+ }++ /** A buffering that lasts pauses the page ([stallCheck]); the local player playing again resumes both. */+ private fun trackStall(playing: Boolean) {+ if (playing && LocalPlayer.isBuffering()) {+ if (!stalled && !stallPending) { stallPending = true; main.postDelayed(stallCheck, STALL_MS) }+ } else {+ if (stallPending) { main.removeCallbacks(stallCheck); stallPending = false }+ stalled = false+ }+ }++ /** Between events the two clocks can part slowly: looked at again every [DRIFT_CHECK_MS], while it runs. */+ private fun startDriftCheck() {+ driftJob?.cancel()+ driftJob = MyspotiRuntime.scope.launch {+ while (true) {+ delay(DRIFT_CHECK_MS)+ if (LocalPlayer.isPlaying()) poke()+ }+ }+ }++ /**+ * Sends [block] after the mirror's earlier commands (and an ending, see [stop]); its answers are its+ * echo for [echoMs]. [block] is told whether this mirror still runs (`live`), to check between steps.+ */+ private fun command(echoMs: Long, block: suspend (live: () -> Boolean) -> Unit) {+ echo.sent(echoMs)+ val gen = generation+ val live = { gen == generation }+ MyspotiRuntime.scope.launch {+ lock.withLock {+ if (!live()) return@withLock+ // An ad or a reload: the page refuses commands now. Dropped: the page gets the song+ // again once it is usable ([pageBack]), what the local player does then included.+ if (!pageUsable()) { log("held: the page is in an ad or reloading"); return@withLock }+ runCatching { block(live) }.onFailure { log("command failed: ${it.message}") }+ // Ended while it ran: the ending, queued behind it, puts the page right; nothing more here.+ if (!live()) return@withLock+ // Counted from the page's answer: a slow play must not let its own states look remote.+ echo.sent(echoMs)+ }+ }+ }++ /** For the diagnostic (`status`): what the mirror does now. */+ data class Status(+ val on: Boolean, val running: Boolean, val uri: String?, val paused: Boolean?, val landed: Boolean,+ val webPositionMs: Long?, val handedAway: Boolean, val failedUri: String?,+ )++ fun status() = Status(ConnectMirrorPref.on, running, want?.uri, want?.paused, landed, webAt(want), handedAway, failedUri)++ private fun log(line: String) = app.myspoti.host.android.Logbook.log("mirror: $line")+}diff --git a/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt b/base/app/src/main/java/com/music/spotui/di/LocalPlayer.ktindex 758b5957..cac74764 100644--- a/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt+++ b/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt@@ -331,6 +331,18 @@ object LocalPlayer {else { com.music.spotui.extensions.Extensions.skipAsked("backward"); it.seekToPreviousMediaItem() }}}+ /** Back to the song before the current one, wherever this one is (a previous asked on another device). */+ fun previousItem() {+ endFade()+ exo?.let { if (it.hasPreviousMediaItem()) { com.music.spotui.extensions.Extensions.skipAsked("backward"); it.seekToPreviousMediaItem() } }+ }++ /** The Spotify ids of the songs before and after the current one ("" when none or no id). */+ fun neighbourIds(): Pair<String, String> {+ val i = exo?.currentMediaItemIndex ?: return "" to ""+ return spotifyId(tracks.getOrNull(i - 1)) to spotifyId(tracks.getOrNull(i + 1))+ }+fun seekTo(ms: Long) {endFade()exo?.let { p ->@@ -530,6 +542,8 @@ object LocalPlayer {?: t.uri.takeIf { it.scheme == com.music.spotui.extensions.ExtensionAudio.SCHEME }?.lastPathSegment.orEmpty()fun isPlaying() = exo?.isPlaying == true+ /** Waiting for audio (a stream that does not keep up, a seek still loading). */+ fun isBuffering() = exo?.playbackState == Player.STATE_BUFFERING/** For the diagnostic (`status`): whether it is to play, and its state (idle, buffering, ready, ended). */fun playWhenReady() = exo?.playWhenReady == truefun playbackState(): String = exo?.let { stateName(it.playbackState) } ?: "none"diff --git a/base/app/src/main/java/com/music/spotui/di/MirrorRules.kt b/base/app/src/main/java/com/music/spotui/di/MirrorRules.ktnew file mode 100644index 00000000..2403bc5f--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/di/MirrorRules.kt@@ -0,0 +1,184 @@+package com.music.spotui.di++import kotlin.math.abs++/**+ * The Connect mirror's decisions (see [ConnectMirror]), without Android: what the unheard Web+ * Player and the local player each do when the other one moves. The Web Player is the phone's+ * Spotify Connect device (what other devices see and command); the local player is what is heard.+ */+object MirrorRules {+ /** Out of step by more than this: put back in step (less is not heard, and every seek costs). */+ const val DRIFT_MS = 1_500L+ /** This close to the end of the local song, the Web Player moving on is the song ending, not a remote skip. */+ const val END_WINDOW_MS = 5_000L++ /** Where the local player's song comes from, as far as the mirror cares. */+ enum class Origin { AUDIO_SOURCE, DOWNLOAD, LOCAL_FILE }++ private val SPOTIFY_ID = Regex("[A-Za-z0-9]{22}")++ /**+ * Whether the song is mirrored: one an extension streams ([Origin.AUDIO_SOURCE]) with a Spotify+ * id, the setting [on], and Spotify able to stream ([dataSaver] off). Downloads and files of the+ * device never are: nothing of Spotify plays them.+ */+ fun eligible(origin: Origin, spotifyId: String, on: Boolean, dataSaver: Boolean): Boolean =+ on && !dataSaver && origin == Origin.AUDIO_SOURCE && SPOTIFY_ID.matches(spotifyId)++ /** What the Web Player was last asked to be on (by the mirror, or a remote command it followed). */+ data class Want(val uri: String, val paused: Boolean)++ /** The Web Player's state as it reports it, its position read for now. */+ data class Web(val uri: String, val paused: Boolean, val positionMs: Long)++ /** The local player now: its song, whether it is to play, where, and its neighbours in the queue. */+ data class Local(+ val uri: String, val playing: Boolean, val positionMs: Long, val durationMs: Long,+ val nextUri: String? = null, val previousUri: String? = null,+ ) {+ val nearEnd: Boolean get() = durationMs > 0 && durationMs - positionMs < END_WINDOW_MS+ }++ /** What the local player does about a Web Player state. */+ sealed interface Follow {+ data object Nothing : Follow+ /** The mirror's play never reached the Web Player: sent again, or given up. */+ data object Retry : Follow+ /** The Web Player answered an earlier play of the mirror's (fast skips): the asked song is sent again. */+ data object Resend : Follow+ data object Pause : Follow+ data object Resume : Follow+ data class Seek(val ms: Long) : Follow+ /** Skipped to the local queue's next / previous song. */+ data object Next : Follow+ data object Previous : Follow+ /** Another song, picked on another device: routed as a pick on the phone is. */+ data class Play(val uri: String, val positionMs: Long) : Follow+ /** Only drift: the unheard Web Player is put on the local position (no jump is heard). */+ data class Align(val ms: Long) : Follow+ }++ /**+ * A Web Player state came. [quiet]: the mirror's own last command may still be answering (its+ * echo, never a remote one). [landed]: the Web Player was seen playing [want]'s song since it was+ * asked. [predictedMs]: where its previous state of the same song puts it now (null: none).+ * [previousUri]: the song it was asked to be on before [want]'s (what a stale state still shows).+ * [gapFromMs]: where it stood when a buffering gap began, just before this state (null: no gap):+ * a page that stalled in the gap is anywhere between that and [predictedMs], a seek is not.+ * [wantAtMs], [wantLengthMs]: where the Web Player is in [want]'s song and that song's length as it+ * has it (a stream of the extension can be longer than Spotify's track). [recentUris]: the songs+ * the mirror itself asked the Web Player to play lately: a state on one of them is a late answer.+ */+ fun onWeb(+ web: Web, want: Want, local: Local, quiet: Boolean, landed: Boolean, predictedMs: Long?,+ previousUri: String? = null, gapFromMs: Long? = null, wantAtMs: Long? = null, wantLengthMs: Long = 0,+ recentUris: Collection<String> = emptyList(),+ ): Follow {+ val late = web.uri != want.uri && web.uri in recentUris+ // During an echo, only a third song once it landed is remote (a double skip on another+ // device): the old song, the asked one and the others just asked are our own commands' answers.+ if (quiet && !(landed && web.uri != want.uri && web.uri != previousUri && !late)) return Follow.Nothing+ // Fast skips: plays sent within a second can land out of order, the Web Player staying on an+ // earlier one. Never a remote command; the song the local player is on is sent again.+ if (late) return Follow.Resend+ // Not seen playing yet: sent again, unless the local player was paused meanwhile (its resume plays it).+ if (!landed) return if (want.paused || web.uri == want.uri && !web.paused) Follow.Nothing else Follow.Retry+ // The local player went on by itself, or the song is ending (on either side): the Web+ // Player's move is that end, and the local side sends what comes next.+ val pageEnding = wantLengthMs > 0 && wantAtMs != null && wantLengthMs - wantAtMs < END_WINDOW_MS+ if (local.uri != want.uri || local.nearEnd || pageEnding) return Follow.Nothing+ if (web.uri != want.uri) return when (web.uri) {+ local.nextUri -> Follow.Next+ local.previousUri -> Follow.Previous+ else -> Follow.Play(web.uri, web.positionMs)+ }+ if (web.paused != want.paused) return if (web.paused) Follow.Pause else Follow.Resume+ val jumped = predictedMs != null &&+ (web.positionMs > predictedMs + DRIFT_MS || web.positionMs < (gapFromMs ?: predictedMs) - DRIFT_MS)+ if (jumped) return Follow.Seek(web.positionMs)+ if (!web.paused && local.playing && abs(web.positionMs - local.positionMs) > DRIFT_MS) return Follow.Align(local.positionMs)+ return Follow.Nothing+ }++ /** What the Web Player is asked about a local player state. */+ sealed interface Lead {+ data object Nothing : Lead+ data class Start(val uri: String, val positionMs: Long) : Lead+ data object Pause : Lead+ /** [alignMs]: where it resumes when it stood elsewhere; null: where it is. */+ data class Resume(val alignMs: Long?) : Lead+ data class Align(val ms: Long) : Lead+ }++ /**+ * The local player moved. [want]: what the Web Player was asked last (null: nothing yet).+ * [stalled]: the local player has been buffering a while (the Web Player waits for it).+ * [webAtMs]: where the Web Player should be now, null when unknown. [previousUri]: the song it+ * was asked to be on before [want]'s.+ */+ fun onLocal(local: Local, want: Want?, stalled: Boolean, quiet: Boolean, webAtMs: Long?, previousUri: String? = null): Lead {+ val paused = !local.playing || stalled+ // A remote skip just moved the Web Player on and the local player still shows the song it+ // left: not a new song to send back there.+ if (quiet && want != null && local.uri != want.uri && local.uri == previousUri) return Lead.Nothing+ // A new song starts on the Web Player once the local one plays; until then the old one is+ // paused there (not counted for a song no longer heard).+ if (want == null || local.uri != want.uri) return when {+ !paused -> Lead.Start(local.uri, local.positionMs)+ want != null && !want.paused -> Lead.Pause+ else -> Lead.Nothing+ }+ val off = webAtMs != null && abs(webAtMs - local.positionMs) > DRIFT_MS+ if (paused != want.paused) return if (paused) Lead.Pause else Lead.Resume(local.positionMs.takeIf { off })+ if (!quiet && !paused && off) return Lead.Align(local.positionMs)+ return Lead.Nothing+ }++ private val BACKOFF_MS = longArrayOf(5_000, 15_000, 30_000)++ /**+ * How long after its [step]-th failed try (from 0) a song the page would not play is played there+ * again: 5 s, 15 s, then every 30 s. The mirror never gives a song up for good.+ */+ fun backoffMs(step: Int): Long = BACKOFF_MS[step.coerceIn(0, BACKOFF_MS.lastIndex)]++ /**+ * The list the Web Player plays [trackUri] in: the local queue's Spotify list ([contextUri]), so+ * other devices see that queue after it, else the track alone. Never an artist: its context is+ * only the artist's top songs, a song of a list taken from an artist page (a mix, the radio,+ * other artists) is often not in it, and the page then plays the artist's first song instead.+ * Nor a list that already put the page on another song ([missed]).+ */+ fun playContext(contextUri: String, trackUri: String, missed: Set<String>): String =+ contextUri.takeIf { it.startsWith("spotify:") && !it.startsWith("spotify:artist:") && it !in missed } ?: trackUri++ /**+ * The local player was moved (played after a pause, or put elsewhere than its clock says):+ * [expectedMs] is where its previous event puts it now (null: unknown).+ */+ fun localMoved(wasPlaying: Boolean, playing: Boolean, expectedMs: Long?, positionMs: Long): Boolean =+ (playing && !wasPlaying) || (expectedMs != null && abs(positionMs - expectedMs) > DRIFT_MS)++ /**+ * Whether a song the engine plays heard on this phone goes back to the extensions (and so to the+ * mirror): Connect playback came back here after the mirror had handed it away ([handedAway]), or+ * another device moved the engine here (a resume, a skip, a pick: [moved]) without Myspoti having+ * asked for it ([intended]). Only while it plays here ([playingHere]) with the setting [on].+ */+ fun backHere(playingHere: Boolean, handedAway: Boolean, moved: Boolean, intended: Boolean, on: Boolean): Boolean =+ on && playingHere && !intended && (handedAway || moved)++ /**+ * The loop guard: a command the mirror sends is answered by Web Player states that must not be+ * taken for a remote device's commands. Until [sent]'s window is over, its states are its echo.+ */+ class Echo(private val clock: () -> Long) {+ private var until = 0L+ fun sent(windowMs: Long) { until = maxOf(until, clock() + windowMs) }+ fun quiet(): Boolean = clock() < until+ /** How long the window still lasts (0 when over). */+ fun remainingMs(): Long = (until - clock()).coerceAtLeast(0)+ fun clear() { until = 0L }+ }+}diff --git a/base/app/src/main/java/com/music/spotui/di/Palette.kt b/base/app/src/main/java/com/music/spotui/di/Palette.ktindex 1375c7cf..bd40d392 100644--- a/base/app/src/main/java/com/music/spotui/di/Palette.kt+++ b/base/app/src/main/java/com/music/spotui/di/Palette.kt@@ -9,6 +9,12 @@ import com.bumptech.glide.Glideimport com.bumptech.glide.request.target.CustomTargetimport com.bumptech.glide.request.transition.Transition+/**+ * Side of the cover decode for colours and the mesh gradient. Glide keys its decodes on the size,+ * so one size means the cover is decoded once for both.+ */+const val COVER_DECODE_PX = 128+class Palette {companion object {/** The tint when a cover gives none (none loaded). */@@ -45,7 +51,7 @@ class Palette {Glide.with(context).asBitmap().load(imageUrl)- .override(64, 64)+ .override(COVER_DECODE_PX, COVER_DECODE_PX).disallowHardwareConfig().into(object : CustomTarget<Bitmap>() {override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {@@ -75,7 +81,7 @@ class Palette {Glide.with(context).asBitmap().load(imageUrl)- .override(64, 64)+ .override(COVER_DECODE_PX, COVER_DECODE_PX).disallowHardwareConfig().into(object : CustomTarget<Bitmap>() {override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {diff --git a/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt b/base/app/src/main/java/com/music/spotui/di/SongPlayer.ktindex 7b577e77..8208b0be 100644--- a/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt+++ b/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt@@ -98,6 +98,10 @@ object SongPlayer {private fun intendPlaying() { wantPlayingUntil = SystemClock.elapsedRealtime() + 4000; wantPausedUntil = 0 }private fun intendPaused() { wantPausedUntil = SystemClock.elapsedRealtime() + 1500; wantPlayingUntil = 0 }+ /** Myspoti itself asked the engine to play lately (a pick, a play, a skip): not another device's doing. */+ fun engineIntended(): Boolean =+ SystemClock.elapsedRealtime() < wantPlayingUntil || pendingTrackId != null || resumeWhenReady+private fun resolvePlaying(paused: Boolean): Boolean {val now = SystemClock.elapsedRealtime()if (now < wantPlayingUntil) {@@ -159,6 +163,7 @@ object SongPlayer {restoreLastTrack(state)restoreRepeat(state)scope.launch { api.player.state.collect { s -> if (acceptsSessionUpdates()) applyState(s) } }+ ConnectMirror.attach()// Another device plays (the phone as a remote): the state is read again every few seconds// so the notification, the mini player and the slider keep up. Reported: the notification// stopped refreshing in the background — this loop waited for _activeDevice, which only a@@ -484,6 +489,13 @@ object SongPlayer {prev = s.previous?.let(::songOf),next = s.next?.let(::songOf),)+ // Started or moved on without Myspoti asking (another device, a transfer back here): the+ // Connect mirror sends it back through the extensions. After this state's own follow-ups.+ val moved = trackChanged || (!wasPlaying && playing)+ if (moved || ConnectMirror.waitsBack) {+ val intended = engineIntended()+ main.post { if (!LocalPlayer.active.value && !routing) ConnectMirror.onEngine(s, moved, intended) }+ }val state = boundState ?: returnval holding = SystemClock.elapsedRealtime() < shuffleWantedUntilif (holding && s.shuffle == shuffleWanted) shuffleWantedUntil = 0L@@ -522,20 +534,26 @@ object SongPlayer {}val mv = com.music.spotui.video.MusicVideoControllermv.onAudioBuffering(isBuffering, song.spotifyTrackId)+ // Clips are shown by the Classic player only: under the Immersive look no clip is looked up.+ val clipsShown = com.music.spotui.data.preferences.LookPref.look == com.music.spotui.data.preferences.Look.CLASSIC// Clip lookup only where it can pay off: video wanted, or the player screen// is up (toggle then is instant). Looking up every track by default cost// searches and full-audio alignment downloads for users who never watch.- if (!isBuffering && playing && mv.inForeground && (mv.wantVideo || mv.hasPlayerScreen) && song.spotifyTrackId.isNotBlank())+ if (clipsShown && !isBuffering && playing && mv.inForeground && (mv.wantVideo || mv.hasPlayerScreen) && song.spotifyTrackId.isNotBlank())com.music.spotui.video.MusicVideoController.prepare(song.spotifyTrackId, song.title, song.singer, durationMs)- if (!isBuffering && playing && mv.inForeground && app.myspoti.power.EnergySettings.state.value.policy.allowBackgroundLookups) {+ val lookups = app.myspoti.power.EnergySettings.state.value.policy.allowBackgroundLookups+ // Lyrics are warmed in the background too (the next song's are there when it starts), but not on a metered network.+ if (!isBuffering && playing && lookups && (mv.inForeground || !com.music.spotui.data.DataSaver.metered)) {com.music.spotui.data.api.LyricsApi.prefetch(lyricsTrack(song))_nowPlaying.value.next?.let { com.music.spotui.data.api.LyricsApi.prefetch(lyricsTrack(it)) }+ }+ if (!isBuffering && playing && mv.inForeground && lookups) {// The next song's clip is looked up now, so its button is there when it starts. The// controller itself stays off under the data saver; a Spotify limit holds it too, as// it holds every other request. Only for someone who has the player open or wants// the clip: a lookup downloads ~145 s of audio, too much data and battery to spend on// every song for a user who never looks at the player.- if ((mv.wantVideo || mv.hasPlayerScreen) && !MyspotiRuntime.host.licenseLimited()) _nowPlaying.value.next?.takeIf { it.spotifyTrackId.isNotBlank() && it.durationMs > 0 }?.let {+ if (clipsShown && (mv.wantVideo || mv.hasPlayerScreen) && !MyspotiRuntime.host.licenseLimited()) _nowPlaying.value.next?.takeIf { it.spotifyTrackId.isNotBlank() && it.durationMs > 0 }?.let {// Without the song's length the match could not be checked, so nothing is cached for it.mv.prefetch(it.spotifyTrackId, it.title, it.singer, it.durationMs.toLong())}@@ -552,10 +570,15 @@ object SongPlayer {}}- /** Back from the local player: the page is heard again if an extension's mirror had muted it. */- fun unmuteMirror() { com.music.spotui.extensions.Extensions.mirrorReset("the local player stopped"); unmuteMirrorNow() }+ /** Back from the local player: the page is heard again if a mirror (an extension's, or the Connect mirror) had muted it. */+ fun unmuteMirror() {+ com.music.spotui.extensions.Extensions.mirrorReset("the local player stopped")+ // The Connect mirror unmutes the page itself, after pausing the song it mirrored.+ if (!ConnectMirror.stop("the local player stopped")) unmuteMirrorNow()+ }- fun unmuteMirrorNow() { if (api.player.localMute) command { api.player.setLocalMute(false) } }+ /** The page heard again, unless the Connect mirror holds it (an extension's mirror ending must not unmute it then). */+ fun unmuteMirrorNow() { if (api.player.localMute && !ConnectMirror.running) command { api.player.setLocalMute(false) } }/** The local player's state for the mirror guard: playing, track uri, duration. */fun localSnapshot3(): Triple<Boolean, String?, Long> =@@ -643,6 +666,8 @@ object SongPlayer {return@withLock}if (gen != transportGen.get()) return@withLock+ // A Connect mirror just ended: the page is heard again before this command reaches it.+ ConnectMirror.awaitEnded()val checkLater = pullBack && checkAfter && _activeDevice.value == nullif (pullBack && !checkLater && api.ready.value) takeBackPlayback()// A cancellation of the caller is never swallowed (it must unwind); only the@@ -720,10 +745,12 @@ object SongPlayer {* audio-source extensions: asked first when one is on ([askExtensions]), they play it in the* local player with the rest as the queue; a miss plays on Spotify as before. Without* [songs], the song is looked up on Spotify (a link, Recents, an extension's block).+ * [alone]: no list at all, not even the one that registered the track (a search hit), so+ * Spotify goes on with its own autoplay of related songs instead of, say, Liked Songs.*/fun playSong(song: String, context: Context? = null, contextUri: String? = null, order: List<String>? = null, positionMs: Long? = null,- songs: List<SongsModel>? = null, askExtensions: Boolean = true,+ songs: List<SongsModel>? = null, askExtensions: Boolean = true, alone: Boolean = false,) {// Data saver on mobile data: Spotify can't stream, only downloads and Local Files play.if (com.music.spotui.data.DataSaver.active) {@@ -734,9 +761,9 @@ object SongPlayer {}val routedId = if (song.startsWith("episode:")) null else spotifyTrackIdForPlayback(song)if (askExtensions && com.music.spotui.extensions.AudioRoute.asks(routedId, com.music.spotui.extensions.Extensions.hasAudioSource())) {- val ctx = (contextUri ?: contextRegistry[song]).orEmpty()+ val ctx = if (alone) "" else (contextUri ?: contextRegistry[song]).orEmpty()val shuffle = isShuffleOn()- playThroughExtensions(routedId!!, songs?.firstOrNull { it.spotifyTrackId == routedId }, knownContextName(ctx), { playSong(song, context, contextUri, order, positionMs, askExtensions = false) }) { isLatest, shown ->+ playThroughExtensions(routedId!!, songs?.firstOrNull { it.spotifyTrackId == routedId }, knownContextName(ctx), { playSong(song, context, contextUri, order, positionMs, askExtensions = false, alone = alone) }) { isLatest, shown ->com.music.spotui.extensions.ExtensionAudio.route(routedId, songs, knownContextName(ctx), shuffle, ctx, isLatest, shown, positionMs ?: 0L)}return@@ -750,7 +777,7 @@ object SongPlayer {val episodeId = song.removePrefix("episode:").takeIf { song.startsWith("episode:") }val trackId = episodeId ?: spotifyTrackIdForPlayback(song) ?: returnval itemUri = if (episodeId != null) "spotify:episode:$episodeId" else SPOTIFY_TRACK_PREFIX + trackId- val ctx = contextUri ?: contextRegistry[song]+ val ctx = if (alone) null else contextUri ?: contextRegistry[song]// What a smart shuffle ending brings back: the order of the last play that was not one.if (ctx != null) {val sent = order?.takeIf { ctx == contextUri }@@ -925,6 +952,34 @@ object SongPlayer {return true}+ /**+ * A song picked on another device while the Connect mirror played: asked to the extensions as a+ * pick here is, from where the page is, with the page's queue after it; Spotify plays it when they+ * have nothing. An episode is Spotify's own and already plays there: it is only heard again.+ */+ fun followRemotePlay(item: app.myspoti.api.NowPlaying, contextUri: String?, positionMs: Long) {+ if (!item.uri.startsWith(SPOTIFY_TRACK_PREFIX)) {+ ConnectMirror.stop("${item.uri} picked on another device", pausePage = false)+ LocalPlayer.stop()+ return+ }+ val after = apiQueue?.let { it.queued + it.nextUp }.orEmpty().filter { it.uri.startsWith(SPOTIFY_TRACK_PREFIX) && it.uri != item.uri }+ playSong(item.uri, contextUri = contextUri?.ifBlank { null }, positionMs = positionMs.takeIf { it > 0 },+ songs = listOf(songOf(item)) + after.map(::songOf))+ }++ /**+ * Playback came back to this phone (a transfer from another device, or picked here) after the+ * Connect mirror had handed it away: Spotify plays it here now, heard; the song goes back to the+ * extensions from where it is, as a resume does.+ */+ fun backThroughExtensions() {+ if (LocalPlayer.active.value || routing || !com.music.spotui.data.preferences.ConnectMirrorPref.on) return+ if (api.player.state.value?.isPaused != false) return+ _activeDevice.value = null+ if (resumeThroughExtensions()) app.myspoti.host.android.Logbook.log("mirror: playback back on this phone, the extensions play it again")+ }+/** The song being resolved, as if it played (paused, loading): screens, notification, lyrics. */private fun showRouted(song: SongsModel) {val uri = SPOTIFY_TRACK_PREFIX + song.spotifyTrackId@@ -1672,6 +1727,7 @@ object SongPlayer {val at = LocalPlayer.position()val wasPlaying = LocalPlayer.isPlaying()Log.i(TAG, "local song to ${device.name}: $track in $context at $at ms")+ ConnectMirror.leaving(device.name)LocalPlayer.stop()command {api.devices.transfer(device.id)@@ -1905,7 +1961,8 @@ object SongPlayer {// What the page reported last (the screens may already show the song asked for).engineUriBeforeLocal = lastPageUriengineRepaused = false- if (playing) command { api.player.pause() }+ // The Connect mirror's page goes on to the new song itself (or is paused by it if that one is not mirrored).+ if (playing && !ConnectMirror.running) command { api.player.pause() }playing = false// The local player keeps the output open itself; the engine's states, which// would close the silent stream, are ignored while it plays.@@ -1921,9 +1978,13 @@ object SongPlayer {* The engine reports playing while a local file plays. Two streams must never play* at once: a pause that did not take (the engine was not ready) is sent once more;* anything else is Spotify taking over (a Connect "play on this phone", a resume from- * another device), and the local player yields. True when the state is to be ignored.+ * another device), and the local player yields; with the Connect mirror on, the local player+ * follows those commands instead (see [ConnectMirror]). True when the state is to be ignored.*/private fun engineWhileLocal(s: PlayerState): Boolean {+ // The Connect mirror's page: its states are another device's commands for the local player+ // to follow, or the echo of the mirror's own; never a takeover.+ if (ConnectMirror.running) { ConnectMirror.onWeb(s); return true }if (s.isPaused) return true// An extension mirrors its own song in the page, muted: that is not the engine taking over.if (api.player.localMute) return true@@ -1970,6 +2031,7 @@ object SongPlayer {pushNotification(song.copy(coverUri = cover), liked)if (songChanged) refreshCurrentLiked()com.music.spotui.extensions.Extensions.mirrorTick(isPlaying, uri)+ ConnectMirror.onLocal(t, isPlaying, pos, dur)val source = if (t.uri.scheme == "file") com.music.spotui.data.local.ListenHistory.Source.DOWNLOADelse com.music.spotui.data.local.ListenHistory.Source.LOCALtrackListen("local:${t.id}", song, source, isPlaying)diff --git a/base/app/src/main/java/com/music/spotui/extensions/ExtensionAttestation.kt b/base/app/src/main/java/com/music/spotui/extensions/ExtensionAttestation.ktnew file mode 100644index 00000000..40e39682--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/extensions/ExtensionAttestation.kt@@ -0,0 +1,63 @@+package com.music.spotui.extensions++import android.security.keystore.KeyGenParameterSpec+import android.security.keystore.KeyProperties+import android.security.keystore.StrongBoxUnavailableException+import app.myspoti.extensions.Attestation+import app.myspoti.extensions.Enrollment+import java.security.KeyPairGenerator+import java.security.KeyStore+import java.security.PrivateKey+import java.security.Signature+import java.security.spec.ECGenParameterSpec+import java.util.Base64++/**+ * `myspoti.attest` ([app.myspoti.extensions.Action.ATTEST]): one EC P-256 signing key per+ * extension in the AndroidKeyStore, under the alias [Attestation.alias] of its id, so an+ * extension can only ever reach its own. The key is made with the challenge the extension's server+ * gave, StrongBox first and the TEE when the phone has none, and the keystore's attestation chain+ * (the app's package name and signing certificate digest inside) goes back to the extension, which+ * sends it to its server. Nothing leaves the phone from here: the app makes no request of its own.+ */+object ExtensionAttestation : Attestation {+ private const val PROVIDER = "AndroidKeyStore"++ private fun keyStore(): KeyStore = KeyStore.getInstance(PROVIDER).apply { load(null) }++ override fun enroll(extensionId: String, challenge: ByteArray): Enrollment {+ val alias = Attestation.alias(extensionId)+ val store = keyStore()+ store.deleteEntry(alias)+ fun generate(strongBox: Boolean) {+ val spec = KeyGenParameterSpec.Builder(alias, KeyProperties.PURPOSE_SIGN)+ .setAlgorithmParameterSpec(ECGenParameterSpec("secp256r1"))+ .setDigests(KeyProperties.DIGEST_SHA256)+ .setAttestationChallenge(challenge)+ .setIsStrongBoxBacked(strongBox)+ .build()+ KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, PROVIDER).apply { initialize(spec) }.generateKeyPair()+ }+ try { generate(strongBox = true) } catch (_: StrongBoxUnavailableException) { generate(strongBox = false) }+ val chain = store.getCertificateChain(alias)?.takeIf { it.isNotEmpty() } ?: run {+ store.deleteEntry(alias)+ throw IllegalStateException("this phone gave no attestation chain")+ }+ val b64 = Base64.getEncoder()+ return Enrollment(b64.encodeToString(chain[0].publicKey.encoded), chain.map { b64.encodeToString(it.encoded) })+ }++ override fun publicKey(extensionId: String): String? =+ keyStore().getCertificate(Attestation.alias(extensionId))?.publicKey?.let { Base64.getEncoder().encodeToString(it.encoded) }++ override fun sign(extensionId: String, data: ByteArray): String {+ val key = keyStore().getKey(Attestation.alias(extensionId), null) as? PrivateKey+ ?: throw IllegalStateException("not enrolled: call myspoti.attest.enroll(challenge) first")+ val signature = Signature.getInstance("SHA256withECDSA").apply { initSign(key); update(data) }.sign()+ return Base64.getEncoder().encodeToString(signature)+ }++ override fun reset(extensionId: String) {+ runCatching { keyStore().deleteEntry(Attestation.alias(extensionId)) }+ }+}diff --git a/base/app/src/main/java/com/music/spotui/extensions/ExtensionUi.kt b/base/app/src/main/java/com/music/spotui/extensions/ExtensionUi.ktindex 37301fd9..b77b68d5 100644--- a/base/app/src/main/java/com/music/spotui/extensions/ExtensionUi.kt+++ b/base/app/src/main/java/com/music/spotui/extensions/ExtensionUi.kt@@ -36,6 +36,7 @@ import androidx.compose.material.icons.rounded.Downloadimport androidx.compose.material.icons.rounded.Editimport androidx.compose.material.icons.rounded.Extensionimport androidx.compose.material.icons.rounded.Favorite+import androidx.compose.material.icons.rounded.Fingerprintimport androidx.compose.material.icons.rounded.GraphicEqimport androidx.compose.material.icons.rounded.Headphonesimport androidx.compose.material.icons.rounded.Home@@ -159,6 +160,7 @@ fun actionIcon(a: Action?): ImageVector = when (a) {Action.WEBVIEW_PAGE -> Icons.Rounded.WebAction.WEBVIEW_AUTH -> Icons.Rounded.KeyAction.STORAGE -> Icons.Rounded.Save+ Action.ATTEST -> Icons.Rounded.Fingerprintnull -> Icons.Rounded.Extension}@@ -186,6 +188,7 @@ fun actionLabel(a: Action?): Int = when (a) {Action.WEBVIEW_PAGE -> R.string.action_webview_pageAction.WEBVIEW_AUTH -> R.string.action_webview_authAction.STORAGE -> R.string.action_storage+ Action.ATTEST -> R.string.action_attestnull -> R.string.action_unknown}diff --git a/base/app/src/main/java/com/music/spotui/extensions/Extensions.kt b/base/app/src/main/java/com/music/spotui/extensions/Extensions.ktindex 60c8cb34..ed824153 100644--- a/base/app/src/main/java/com/music/spotui/extensions/Extensions.kt+++ b/base/app/src/main/java/com/music/spotui/extensions/Extensions.kt@@ -300,6 +300,7 @@ object Extensions {runningSha.remove(id)ExtensionAudio.forgetAll()ExtensionAuth.forget(id)+ ExtensionAttestation.reset(id)File(dir, id).deleteRecursively()Logbook.log("ext $id: uninstalled")}@@ -785,7 +786,14 @@ object Extensions {while (true) {kotlinx.coroutines.delay(60_000)if (!com.music.spotui.video.MusicVideoController.inForeground && !SongPlayer.isPlaying()) continue- runtimes.forEach { (id, rt) -> if (health.stale(id, STATUS_EVERY_MS)) scope.launch { probe(id, rt) } }+ // This loop runs on the main thread for the life of the app: one failed round must not end it nor crash it.+ try {+ runtimes.forEach { (id, rt) -> if (health.stale(id, STATUS_EVERY_MS)) scope.launch { probe(id, rt) } }+ } catch (e: kotlinx.coroutines.CancellationException) {+ throw e+ } catch (e: Throwable) {+ Logbook.log("ext: status round failed: ${e.javaClass.simpleName}: ${e.message}")+ }}}}@@ -801,11 +809,18 @@ object Extensions {// The title and the length follow the uri a moment later..debounce(1_500).collect {- val track = currentTrack() ?: return@collect- val (origin, providerId) = currentOrigin()- val json = PlaybackEvent.trackEventJson(track, origin, providerId)- runtimes.forEach { (id, rt) ->- scope.launch { runCatching { runInterruptible { rt.emit(ExtensionRuntime.EVENT_TRACK, json, TRACK_MS) } }.onFailure { failed(id, it.toString()) } }+ // A song whose details cannot be read tells nothing, it does not end the watch (nor crash the app).+ try {+ val track = currentTrack() ?: return@collect+ val (origin, providerId) = currentOrigin()+ val json = PlaybackEvent.trackEventJson(track, origin, providerId)+ runtimes.forEach { (id, rt) ->+ scope.launch { runCatching { runInterruptible { rt.emit(ExtensionRuntime.EVENT_TRACK, json, TRACK_MS) } }.onFailure { failed(id, it.toString()) } }+ }+ } catch (e: kotlinx.coroutines.CancellationException) {+ throw e+ } catch (e: Throwable) {+ Logbook.log("ext: track event failed: ${e.javaClass.simpleName}: ${e.message}")}}}@@ -1150,6 +1165,11 @@ object Extensions {if (!Extensions.mirror.disable(extensionId)) return "null"try { return dispatcher.execute(call) } finally { Extensions.mirrorEndedBy(extensionId) }}+ // Myspoti's own Connect mirror has the page already ("Count extension plays on Spotify"): it wins.+ if (com.music.spotui.di.ConnectMirror.running) {+ val why = "setLocalMute: Myspoti already plays this song on Spotify (Count extension plays on Spotify)"+ Extensions.log(extensionId, "refused: $why"); throw IllegalStateException(why)+ }if (!arbitrate(extensionId, "setLocalMute")) return "null"val (playing, uri, dur) = SongPlayer.localSnapshot3()Extensions.mirror.enable(extensionId, playing, uri, dur)?.let { Extensions.log(extensionId, "refused: $it"); throw IllegalStateException(it) }@@ -1181,6 +1201,8 @@ object Extensions {override fun openAuth(extensionId: String, request: app.myspoti.extensions.AuthRequest): String = ExtensionAuth.open(extensionId, request)override fun whenOnline(extensionId: String) = askOnline(extensionId)++ override fun attestation(): app.myspoti.extensions.Attestation = ExtensionAttestation}/** The raw door: the Web Player's GraphQL, page services and Spotify URLs, as the account. */diff --git a/base/app/src/main/java/com/music/spotui/ui/components/AboutSheet.kt b/base/app/src/main/java/com/music/spotui/ui/components/AboutSheet.ktindex 6db76c65..c7204c24 100644--- a/base/app/src/main/java/com/music/spotui/ui/components/AboutSheet.kt+++ b/base/app/src/main/java/com/music/spotui/ui/components/AboutSheet.kt@@ -22,7 +22,6 @@ import androidx.compose.foundation.rememberScrollStateimport androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.foundation.verticalScrollimport androidx.compose.material3.ExperimentalMaterial3Api-import androidx.compose.material3.ModalBottomSheetimport androidx.compose.material3.Textimport androidx.compose.runtime.Composableimport androidx.compose.ui.Alignment@@ -57,7 +56,7 @@ fun AboutSheet(onDismiss: () -> Unit) {val context = LocalContext.currentcom.music.spotui.extensions.ProtectedSurfaceEffect(app.myspoti.extensions.ProtectedSurface.ABOUT)// Opened in full: half open, it hid the support buttons at the bottom.- ModalBottomSheet(+ LookSheet(onDismissRequest = onDismiss,sheetState = androidx.compose.material3.rememberModalBottomSheetState(skipPartiallyExpanded = true),containerColor = tone(0xFF282828),@@ -108,7 +107,7 @@ fun GitHubSponsorButton(modifier: Modifier = Modifier, onClick: (() -> Unit)? =fun SupportSheet(onDismiss: () -> Unit) {val context = LocalContext.currentcom.music.spotui.extensions.ProtectedSurfaceEffect(app.myspoti.extensions.ProtectedSurface.SUPPORT)- ModalBottomSheet(+ LookSheet(onDismissRequest = onDismiss,sheetState = androidx.compose.material3.rememberModalBottomSheetState(skipPartiallyExpanded = true),containerColor = tone(0xFF282828),diff --git a/base/app/src/main/java/com/music/spotui/ui/components/AddSongsScreen.kt b/base/app/src/main/java/com/music/spotui/ui/components/AddSongsScreen.ktindex a5ada0c4..4c25fea7 100644--- a/base/app/src/main/java/com/music/spotui/ui/components/AddSongsScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/components/AddSongsScreen.kt@@ -3,6 +3,8 @@ package com.music.spotui.ui.componentsimport com.music.spotui.ui.theme.toneimport com.music.spotui.ui.theme.AppTextimport com.music.spotui.ui.theme.AppMuted+import com.music.spotui.ui.theme.AppBackground+import com.music.spotui.ui.theme.AppAccentimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.clickable@@ -75,7 +77,7 @@ import kotlinx.coroutines.delayimport kotlinx.coroutines.flow.firstimport kotlinx.coroutines.withContext-private val Green = Color(0xFF1ED760)+private val Green get() = AppAccentprivate const val SUGGESTIONS = 20private const val TYPE_PAUSE_MS = 300L@@ -120,7 +122,7 @@ fun AddSongsScreen(page: ContextPageModel, onClose: (added: Boolean) -> Unit) {val close = { onClose(added.isNotEmpty()) }Dialog(onDismissRequest = close, properties = DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false)) {- Column(Modifier.fillMaxSize().background(tone(0xFF121212)).statusBarsPadding().navigationBarsPadding().imePadding()) {+ Column(Modifier.fillMaxSize().background(AppBackground).statusBarsPadding().navigationBarsPadding().imePadding()) {Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().height(56.dp).padding(horizontal = 4.dp)) {Box(contentAlignment = Alignment.Center, modifier = Modifier.size(48.dp).clip(CircleShape).clickable(onClick = close)) {Icon(Icons.Default.Close, contentDescription = stringResource(R.string.add_songs_close), tint = AppText)diff --git a/base/app/src/main/java/com/music/spotui/ui/components/BetaLogButton.kt b/base/app/src/main/java/com/music/spotui/ui/components/BetaLogButton.ktindex 013b26fe..8fe1f7af 100644--- a/base/app/src/main/java/com/music/spotui/ui/components/BetaLogButton.kt+++ b/base/app/src/main/java/com/music/spotui/ui/components/BetaLogButton.kt@@ -3,6 +3,8 @@ package com.music.spotui.ui.componentsimport com.music.spotui.ui.theme.toneimport com.music.spotui.ui.theme.AppTextimport com.music.spotui.ui.theme.AppMuted+import com.music.spotui.ui.theme.AppBackground+import com.music.spotui.ui.theme.AppAccentimport android.content.ClipDataimport android.content.ClipboardManager@@ -92,7 +94,7 @@ fun BetaLogButton(modifier: Modifier = Modifier) {) {val g = grow.valueBugIcon(- color = androidx.compose.ui.graphics.lerp(AppMuted, Color(0xFF1DB954), g),+ color = androidx.compose.ui.graphics.lerp(AppMuted, AppAccent, g),modifier = Modifier.size((16 + 12 * g).dp),)}@@ -134,7 +136,7 @@ private fun LogsDialog(onDismiss: () -> Unit) {var text by remember { mutableStateOf<String?>(null) }LaunchedEffect(Unit) { text = BetaLogs.recent() }Dialog(onDismissRequest = onDismiss, properties = DialogProperties(usePlatformDefaultWidth = false)) {- Column(Modifier.fillMaxSize().background(tone(0xFF121212)).statusBarsPadding().navigationBarsPadding()) {+ Column(Modifier.fillMaxSize().background(AppBackground).statusBarsPadding().navigationBarsPadding()) {Row(Modifier.fillMaxWidth().padding(horizontal = 8.dp), verticalAlignment = Alignment.CenterVertically) {Text(stringResource(R.string.beta_logs_title, BetaLogs.MINUTES), color = AppText, fontSize = 17.sp,modifier = Modifier.weight(1f).padding(start = 8.dp))@@ -142,7 +144,7 @@ private fun LogsDialog(onDismiss: () -> Unit) {}Box(Modifier.weight(1f).fillMaxWidth().padding(horizontal = 8.dp)) {val logs = text- if (logs == null) CircularProgressIndicator(Modifier.align(Alignment.Center), color = Color(0xFF1DB954))+ if (logs == null) CircularProgressIndicator(Modifier.align(Alignment.Center), color = AppAccent)else SelectionContainer {// The newest lines matter most: the view opens scrolled to the end.val scroll = rememberScrollState()@@ -156,7 +158,7 @@ private fun LogsDialog(onDismiss: () -> Unit) {Text(stringResource(R.string.beta_logs_share), color = AppText)}TextButton(onClick = { text?.let { copy(context, it) } }, enabled = text != null,- modifier = Modifier.background(Color(0xFF1DB954), RoundedCornerShape(20.dp))) {+ modifier = Modifier.background(AppAccent, RoundedCornerShape(20.dp))) {Text(stringResource(R.string.beta_logs_copy), color = Color.Black)}}diff --git a/base/app/src/main/java/com/music/spotui/ui/components/Motion.kt b/base/app/src/main/java/com/music/spotui/ui/components/Motion.ktindex 023048af..33f0f7ca 100644--- a/base/app/src/main/java/com/music/spotui/ui/components/Motion.kt+++ b/base/app/src/main/java/com/music/spotui/ui/components/Motion.kt@@ -2,6 +2,8 @@ package com.music.spotui.ui.componentsimport androidx.compose.animation.core.Springimport androidx.compose.animation.AnimatedContent+import androidx.compose.animation.EnterTransition+import androidx.compose.animation.ExitTransitionimport androidx.compose.animation.fadeInimport androidx.compose.animation.fadeOutimport androidx.compose.animation.scaleIn@@ -15,12 +17,15 @@ import androidx.compose.ui.graphics.Colorimport androidx.compose.ui.res.painterResourceimport app.myspoti.engine.Rimport androidx.compose.animation.core.animateFloatAsState+import androidx.compose.animation.core.VisibilityThresholdimport androidx.compose.animation.core.springimport androidx.compose.foundation.clickable+import androidx.compose.foundation.lazy.LazyItemScopeimport androidx.compose.foundation.interaction.MutableInteractionSourceimport androidx.compose.foundation.interaction.collectIsPressedAsStateimport androidx.compose.runtime.getValueimport androidx.compose.runtime.remember+import androidx.compose.runtime.rememberUpdatedStateimport androidx.compose.ui.Modifierimport androidx.compose.ui.composedimport androidx.compose.ui.graphics.graphicsLayer@@ -49,19 +54,23 @@ fun Modifier.pressable(* touch slop) or taps it: the page behind it starts loading ~100 ms before the* click. A touch that turns into a scroll asks for nothing.*/-fun Modifier.pressHint(onHint: () -> Unit): Modifier = pointerInput(onHint) {- awaitEachGesture {- val down = awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial)- val slop = viewConfiguration.touchSlop- var moved = false- withTimeoutOrNull(80) {- while (true) {- val change = awaitPointerEvent(PointerEventPass.Initial).changes.firstOrNull { it.id == down.id } ?: break- if ((change.position - down.position).getDistance() > slop) { moved = true; break }- if (!change.pressed) break+fun Modifier.pressHint(onHint: () -> Unit): Modifier = composed {+ // The gesture is not restarted when a caller passes a new lambda: a recomposition under a finger keeps the touch.+ val currentOnHint by rememberUpdatedState(onHint)+ pointerInput(Unit) {+ awaitEachGesture {+ val down = awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial)+ val slop = viewConfiguration.touchSlop+ var moved = false+ withTimeoutOrNull(80) {+ while (true) {+ val change = awaitPointerEvent(PointerEventPass.Initial).changes.firstOrNull { it.id == down.id } ?: break+ if ((change.position - down.position).getDistance() > slop) { moved = true; break }+ if (!change.pressed) break+ }}+ if (!moved) currentOnHint()}- if (!moved) onHint()}}@@ -88,10 +97,12 @@ fun PlayPauseIcon(tint: Color,modifier: Modifier = Modifier,) {+ val reduce = com.music.spotui.ui.look.rememberReduceMotion()AnimatedContent(targetState = playing,transitionSpec = {- (scaleIn(spring(dampingRatio = 0.55f, stiffness = Spring.StiffnessMediumLow), initialScale = 0.6f) + fadeIn(tween(120))) togetherWith+ if (reduce) EnterTransition.None togetherWith ExitTransition.None+ else (scaleIn(spring(dampingRatio = 0.55f, stiffness = Spring.StiffnessMediumLow), initialScale = 0.6f) + fadeIn(tween(120))) togetherWith(scaleOut(tween(120), targetScale = 0.6f) + fadeOut(tween(90)))},contentAlignment = Alignment.Center,@@ -105,3 +116,17 @@ fun PlayPauseIcon()}}++/**+ * A row of a lazy list that reorders or loses items: it slides to its new place, on the spring+ * of the library's rows. No fades (a row that comes or goes simply is, or is not, there), and+ * no slide under "Remove animations". Only for items with stable keys.+ */+@Composable+fun LazyItemScope.animatedRow(): Modifier = Modifier.animateItem(+ fadeInSpec = null, fadeOutSpec = null,+ placementSpec = if (com.music.spotui.ui.look.rememberReduceMotion()) null else spring(+ stiffness = Spring.StiffnessMediumLow,+ visibilityThreshold = androidx.compose.ui.unit.IntOffset.VisibilityThreshold,+ ),+)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 6cee491d..34286195 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@@ -1,5 +1,6 @@package com.music.spotui.ui.components+import com.music.spotui.ui.theme.AppDestructiveimport com.music.spotui.ui.theme.toneimport com.music.spotui.ui.theme.AppTextimport com.music.spotui.ui.theme.AppMuted@@ -282,7 +283,7 @@ fun PlaylistOptionsSheet(com.music.spotui.data.api.LibraryEdits.run(context, com.music.spotui.data.api.LibraryEdits.Remove(page.uri),write = { MyspotiRuntime.api.blends.leave(page.uri) })onDismiss(); onDeleted()- }) { Text(stringResource(R.string.blend_leave_button), color = Color(0xFFF15E6C)) }+ }) { Text(stringResource(R.string.blend_leave_button), color = AppDestructive) }},dismissButton = { TextButton(onClick = { leavingBlend = false }) { Text(stringResource(R.string.cancel), color = AppText) } },)@@ -302,7 +303,7 @@ fun PlaylistOptionsSheet(android.widget.Toast.makeText(context, R.string.playlist_now_solo, android.widget.Toast.LENGTH_SHORT).show()// Written in order with the other visibility taps; a refusal puts back what Spotify has.com.music.spotui.data.api.SpotifySync.stopPlaylistCollaboration(page.uri) { ok -> if (ok) onChanged() else restore() }- }) { Text(stringResource(R.string.playlist_stop_collab), color = Color(0xFFF15E6C)) }+ }) { Text(stringResource(R.string.playlist_stop_collab), color = AppDestructive) }},dismissButton = { TextButton(onClick = { stoppingCollab = false }) { Text(stringResource(R.string.cancel), color = AppText) } },)@@ -321,7 +322,7 @@ fun PlaylistOptionsSheet(write = { MyspotiRuntime.api.playlists.leave(page.uri) },onDone = { ok -> if (ok) com.music.spotui.data.api.LibraryEdits.reloadSoon() })onDismiss(); onDeleted()- }) { Text(stringResource(R.string.playlist_leave_button), color = Color(0xFFF15E6C)) }+ }) { Text(stringResource(R.string.playlist_leave_button), color = AppDestructive) }},dismissButton = { TextButton(onClick = { leavingPlaylist = false }) { Text(stringResource(R.string.cancel), color = AppText) } },)@@ -337,7 +338,7 @@ fun PlaylistOptionsSheet(com.music.spotui.data.api.LibraryEdits.run(context, com.music.spotui.data.api.LibraryEdits.Remove(page.uri),write = { MyspotiRuntime.api.playlists.delete(page.uri) })onDismiss(); onDeleted()- }) { Text(stringResource(R.string.actions_picker_delete), color = Color(0xFFF15E6C)) }+ }) { Text(stringResource(R.string.actions_picker_delete), color = AppDestructive) }},dismissButton = { TextButton(onClick = { deleting = false }) { Text(stringResource(R.string.cancel), color = AppText) } },)diff --git a/base/app/src/main/java/com/music/spotui/ui/components/QualityPickers.kt b/base/app/src/main/java/com/music/spotui/ui/components/QualityPickers.ktindex 13c1212f..12d5059e 100644--- a/base/app/src/main/java/com/music/spotui/ui/components/QualityPickers.kt+++ b/base/app/src/main/java/com/music/spotui/ui/components/QualityPickers.kt@@ -3,6 +3,7 @@ package com.music.spotui.ui.componentsimport com.music.spotui.ui.theme.toneimport com.music.spotui.ui.theme.AppTextimport com.music.spotui.ui.theme.AppMuted+import com.music.spotui.ui.theme.AppAccentimport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.Row@@ -98,9 +99,9 @@ private fun <T> QualityGroup(.padding(horizontal = 8.dp, vertical = 4.dp),) {RadioButton(selected = on, onClick = null, modifier = Modifier.padding(horizontal = 8.dp),- colors = RadioButtonDefaults.colors(selectedColor = Color(0xFF1DB954), unselectedColor = AppMuted))+ colors = RadioButtonDefaults.colors(selectedColor = AppAccent, unselectedColor = AppMuted))Column(Modifier.weight(1f).padding(end = 12.dp)) {- Text(stringResource(o.label), color = if (on) Color(0xFF1DB954) else AppText, fontSize = 16.sp)+ Text(stringResource(o.label), color = if (on) AppAccent else AppText, fontSize = 16.sp)Text(stringResource(o.detail), color = AppMuted, fontSize = 12.sp)}}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 84ab7640..d191a4f6 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@@ -376,7 +376,7 @@ internal fun CreditsSheet(song: SongsModel, onDismiss: () -> Unit) {value = runCatching { app.myspoti.host.android.MyspotiRuntime.api.extras.credits("spotify:track:${song.spotifyTrackId}") }.getOrDefault(app.myspoti.api.Credits(emptyList()))}- ModalBottomSheet(onDismissRequest = onDismiss, containerColor = tone(0xFF282828), sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)) {+ LookSheet(onDismissRequest = onDismiss, containerColor = tone(0xFF282828), sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)) {Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState()).padding(bottom = 24.dp)) {Text(stringResource(R.string.track_credits), color = AppText, fontSize = 20.sp, fontWeight = androidx.compose.ui.text.font.FontWeight.Bold,modifier = Modifier.padding(20.dp, 8.dp))@@ -407,7 +407,7 @@ internal fun CreditsSheet(song: SongsModel, onDismiss: () -> Unit) {@OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)@Composableinternal fun SpeedSheet(onDismiss: () -> Unit) {- ModalBottomSheet(onDismissRequest = onDismiss, containerColor = tone(0xFF282828)) {+ LookSheet(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,modifier = Modifier.padding(20.dp, 8.dp))diff --git a/base/app/src/main/java/com/music/spotui/ui/components/SupporterSheet.kt b/base/app/src/main/java/com/music/spotui/ui/components/SupporterSheet.ktindex ab2a5436..f39511ca 100644--- a/base/app/src/main/java/com/music/spotui/ui/components/SupporterSheet.kt+++ b/base/app/src/main/java/com/music/spotui/ui/components/SupporterSheet.kt@@ -24,7 +24,6 @@ import androidx.compose.foundation.shape.CircleShapeimport androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.foundation.verticalScrollimport androidx.compose.material3.ExperimentalMaterial3Api-import androidx.compose.material3.ModalBottomSheetimport androidx.compose.material3.Switchimport androidx.compose.material3.Textimport androidx.compose.runtime.Composable@@ -48,6 +47,7 @@ import androidx.compose.ui.unit.spimport app.myspoti.engine.Rimport com.music.spotui.data.api.SupportReminderimport com.music.spotui.data.api.SupportReminder.Accent+import com.music.spotui.data.preferences.LookPrefimport com.music.spotui.data.api.SupportReminder.Levelimport com.music.spotui.ui.theme.AppAccent@@ -100,7 +100,7 @@ fun SupporterSheet(onDismiss: () -> Unit) {var choosing by remember { mutableStateOf(false) }val level = SupportReminder.level// Opened in full: half open, it hid the support buttons at the bottom.- ModalBottomSheet(+ LookSheet(onDismissRequest = onDismiss,sheetState = androidx.compose.material3.rememberModalBottomSheetState(skipPartiallyExpanded = true),containerColor = tone(0xFF282828),@@ -132,12 +132,12 @@ fun SupporterSheet(onDismiss: () -> Unit) {Text(stringResource(R.string.supporter_accent), color = AppText, fontSize = 16.sp, modifier = Modifier.padding(top = 20.dp, bottom = 10.dp))Row(horizontalArrangement = Arrangement.spacedBy(14.dp)) {for (a in Accent.entries) {- val selected = SupportReminder.accent == a+ val selected = SupportReminder.accentOf(LookPref.look) == aval name = stringResource(accentName(a))Box(Modifier.size(40.dp).semantics { contentDescription = name }.clip(CircleShape).background(a.color).then(if (selected) Modifier.border(3.dp, AppText, CircleShape) else Modifier)- .pressable(0.92f) { SupportReminder.setAccent(context, a) },+ .pressable(0.92f) { SupportReminder.setAccent(context, LookPref.look, a) },)}}diff --git a/base/app/src/main/java/com/music/spotui/ui/components/SwipeToQueue.kt b/base/app/src/main/java/com/music/spotui/ui/components/SwipeToQueue.ktindex 14a6ddce..5745ae64 100644--- a/base/app/src/main/java/com/music/spotui/ui/components/SwipeToQueue.kt+++ b/base/app/src/main/java/com/music/spotui/ui/components/SwipeToQueue.kt@@ -43,7 +43,7 @@ import kotlin.math.roundToInt* passes the threshold, adds the song ONCE on release, then springs back.*/@Composable-fun SwipeToQueue(song: SongsModel, content: @Composable () -> Unit) {+fun SwipeToQueue(song: SongsModel, modifier: Modifier = Modifier, content: @Composable () -> Unit) {val context = LocalContext.currentval haptic = LocalHapticFeedback.currentval scope = rememberCoroutineScope()@@ -52,7 +52,7 @@ fun SwipeToQueue(song: SongsModel, content: @Composable () -> Unit) {val offset = remember { Animatable(0f) }var armed by remember { mutableStateOf(false) }- Box(modifier = Modifier.fillMaxWidth()) {+ Box(modifier = modifier.fillMaxWidth()) {if (offset.value != 0f) {Box(contentAlignment = if (offset.value > 0) Alignment.CenterStart else Alignment.CenterEnd,diff --git a/base/app/src/main/java/com/music/spotui/ui/components/SwipeToRemove.kt b/base/app/src/main/java/com/music/spotui/ui/components/SwipeToRemove.ktindex 7e6b7cb2..a1d9a04a 100644--- a/base/app/src/main/java/com/music/spotui/ui/components/SwipeToRemove.kt+++ b/base/app/src/main/java/com/music/spotui/ui/components/SwipeToRemove.kt@@ -3,6 +3,7 @@ package com.music.spotui.ui.componentsimport com.music.spotui.ui.theme.AppTextimport androidx.compose.animation.core.Animatable+import androidx.compose.animation.core.snapimport androidx.compose.animation.core.springimport androidx.compose.animation.core.tweenimport androidx.compose.foundation.background@@ -49,6 +50,10 @@ fun SwipeToRemove(key: Any, onRemove: () -> Unit, content: @Composable () -> Unival offset = remember(key) { Animatable(0f) }var armed by remember(key) { mutableStateOf(false) }var width by remember { mutableFloatStateOf(0f) }+ // "Remove animations": the row goes back, or out, at once.+ val reduce = com.music.spotui.ui.look.rememberReduceMotion()+ val slideOut = if (reduce) snap<Float>() else tween(180)+ val springBack = if (reduce) snap<Float>() else spring<Float>()Box(modifier = Modifier.fillMaxWidth().onSizeChanged { width = it.width.toFloat() }) {if (offset.value < 0f) {@@ -69,14 +74,14 @@ fun SwipeToRemove(key: Any, onRemove: () -> Unit, content: @Composable () -> UnidetectHorizontalDragGestures(onDragEnd = {if (armed) scope.launch {- offset.animateTo(-width.coerceAtLeast(threshold), tween(180))+ offset.animateTo(-width.coerceAtLeast(threshold), slideOut)onRemove()- } else scope.launch { offset.animateTo(0f, spring()) }+ } else scope.launch { offset.animateTo(0f, springBack) }armed = false},onDragCancel = {armed = false- scope.launch { offset.animateTo(0f, spring()) }+ scope.launch { offset.animateTo(0f, springBack) }},) { change, dx ->change.consume()diff --git a/base/app/src/main/java/com/music/spotui/ui/components/WideTap.kt b/base/app/src/main/java/com/music/spotui/ui/components/WideTap.ktnew file mode 100644index 00000000..71dcc24e--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/components/WideTap.kt@@ -0,0 +1,175 @@+package com.music.spotui.ui.components++import androidx.compose.foundation.interaction.MutableInteractionSource+import androidx.compose.foundation.interaction.PressInteraction+import androidx.compose.runtime.remember+import androidx.compose.ui.Modifier+import androidx.compose.ui.composed+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.input.pointer.PointerEvent+import androidx.compose.ui.input.pointer.PointerEventPass+import androidx.compose.ui.node.ModifierNodeElement+import androidx.compose.ui.node.PointerInputModifierNode+import androidx.compose.ui.node.SemanticsModifierNode+import androidx.compose.ui.node.TouchBoundsExpansion+import androidx.compose.ui.node.requireDensity+import androidx.compose.ui.platform.InspectorInfo+import androidx.compose.ui.semantics.Role+import androidx.compose.ui.semantics.SemanticsPropertyReceiver+import androidx.compose.ui.semantics.onClick+import androidx.compose.ui.semantics.role+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.IntSize+import androidx.compose.ui.unit.dp++/**+ * A tap target wider than what is drawn: the element answers taps up to [horizontal] beyond its+ * left and right edges and [vertical] beyond its top and bottom, for a small control with empty+ * space around it (a back arrow in a corner, an avatar in a header). Taps that land on another+ * control still go to that control: Compose hits what is actually under the finger first.+ *+ * Put it before any `clip` / glass surface in the chain: a clipping layer stops taps outside its+ * shape before they reach this. Presses go to [interactionSource] for the caller's own feedback.+ */+fun Modifier.wideClickable(+ horizontal: Dp = 12.dp,+ vertical: Dp = 12.dp,+ interactionSource: MutableInteractionSource? = null,+ role: Role? = Role.Button,+ onClick: () -> Unit,+): Modifier = this then WideClickElement(horizontal, vertical, interactionSource, role, onClick)++/** [wideClickable] with the app's press feedback: the control shrinks a little under the finger. */+fun Modifier.widePressable(+ horizontal: Dp = 12.dp,+ vertical: Dp = 12.dp,+ pressedScale: Float = 0.9f,+ onClick: () -> Unit,+): Modifier = composed {+ val source = remember { MutableInteractionSource() }+ pressScale(source, pressedScale).wideClickable(horizontal, vertical, source, onClick = onClick)+}++private data class WideClickElement(+ val horizontal: Dp,+ val vertical: Dp,+ val interactionSource: MutableInteractionSource?,+ val role: Role?,+ val onClick: () -> Unit,+) : ModifierNodeElement<WideClickNode>() {+ override fun create() = WideClickNode(horizontal, vertical, interactionSource, role, onClick)+ override fun update(node: WideClickNode) {+ if (node.interactionSource != interactionSource) node.release()+ node.horizontal = horizontal+ node.vertical = vertical+ node.interactionSource = interactionSource+ node.role = role+ node.onClick = onClick+ }+ override fun InspectorInfo.inspectableProperties() {+ name = "wideClickable"+ properties["horizontal"] = horizontal+ properties["vertical"] = vertical+ }+}++private class WideClickNode(+ var horizontal: Dp,+ var vertical: Dp,+ var interactionSource: MutableInteractionSource?,+ var role: Role?,+ var onClick: () -> Unit,+) : Modifier.Node(), PointerInputModifierNode, SemanticsModifierNode {++ private val tap = WideTap()+ private var press: PressInteraction.Press? = null++ override val touchBoundsExpansion: TouchBoundsExpansion+ get() = with(requireDensity()) {+ val h = horizontal.roundToPx()+ val v = vertical.roundToPx()+ TouchBoundsExpansion(start = h, top = v, end = h, bottom = v)+ }++ override val shouldMergeDescendantSemantics: Boolean get() = true++ override fun SemanticsPropertyReceiver.applySemantics() {+ // Named through the node: inside this receiver, `role` alone is the semantics property.+ val node = this@WideClickNode+ node.role?.let { role = it }+ onClick { node.onClick(); true }+ }++ override fun onPointerEvent(pointerEvent: PointerEvent, pass: PointerEventPass, bounds: IntSize) {+ val change = pointerEvent.changes.firstOrNull { tap.follows(it.id.value) } ?: pointerEvent.changes.firstOrNull() ?: return+ val step = when (pass) {+ PointerEventPass.Main -> tap.main(change.id.value, change.pressed, change.previousPressed, change.isConsumed, inside(change.position, bounds))+ PointerEventPass.Final -> tap.final(change.id.value, change.pressed, change.previousPressed, change.isConsumed)+ else -> return+ }+ when (step) {+ WideTap.Step.PRESS -> {+ change.consume()+ press = PressInteraction.Press(change.position).also { interactionSource?.tryEmit(it) }+ }+ WideTap.Step.CLICK -> {+ change.consume()+ press?.let { interactionSource?.tryEmit(PressInteraction.Release(it)) }+ press = null+ onClick()+ }+ WideTap.Step.CANCEL -> cancelPress()+ WideTap.Step.NONE -> Unit+ }+ }++ private fun inside(p: Offset, bounds: IntSize): Boolean = with(requireDensity()) {+ val h = horizontal.toPx()+ val v = vertical.toPx()+ p.x >= -h && p.y >= -v && p.x <= bounds.width + h && p.y <= bounds.height + v+ }++ override fun onCancelPointerInput() {+ tap.cancel()+ cancelPress()+ }++ override fun onDetach() = onCancelPointerInput()++ fun release() = onCancelPointerInput()++ private fun cancelPress() {+ press?.let { interactionSource?.tryEmit(PressInteraction.Cancel(it)) }+ press = null+ }+}++/**+ * The tap rules of [wideClickable], kept apart from Compose so a JVM test can run them. Fed one+ * pointer change per pass: [main] in the Main pass, [final] in the Final pass.+ *+ * Read the raw pressed flags, not `changedToDown()` / `changedToUp()`: those answer false once a+ * change is consumed, and the node consumes the down itself.+ */+internal class WideTap {+ enum class Step { NONE, PRESS, CANCEL, CLICK }++ private var down: Long? = null++ fun follows(id: Long) = id == down++ fun main(id: Long, pressed: Boolean, previousPressed: Boolean, consumed: Boolean, inside: Boolean): Step = when {+ down == null && pressed && !previousPressed && !consumed -> { down = id; Step.PRESS }+ id != down -> Step.NONE+ // Something under the finger took it, or the finger left the (widened) target.+ consumed || !inside -> { down = null; Step.CANCEL }+ !pressed -> { down = null; Step.CLICK }+ else -> Step.NONE+ }++ /** A move consumed after us (Main runs from the deepest node up): a scroll took the finger over. */+ fun final(id: Long, pressed: Boolean, previousPressed: Boolean, consumed: Boolean): Step =+ if (id == down && consumed && pressed && previousPressed) { down = null; Step.CANCEL } else Step.NONE++ fun cancel() { down = null }+}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.ktindex d087478d..89d93a63 100644--- a/base/app/src/main/java/com/music/spotui/ui/immersive/ImmersiveTheme.kt+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/ImmersiveTheme.kt@@ -27,11 +27,14 @@ object Immersive {val Text = Color.Whiteval TextSecondary = Color.White.copy(alpha = 0.60f)val TextTertiary = Color.White.copy(alpha = 0.38f)- /** The look's own pink until an accent colour is chosen in Settings, then that colour (links, the selected tab, toggles). */- val Accent: Color get() =- if (com.music.spotui.data.api.SupportReminder.accentChosen) com.music.spotui.ui.theme.AppAccent else Color(0xFFFF4F7B)+ /** The look's own pink until an Immersive accent colour is chosen in Settings, then that colour (links, the selected tab, toggles). */+ val Accent: Color get() = com.music.spotui.data.api.SupportReminder.run {+ if (immersiveAccentChosen) immersiveAccent.color else Color(0xFFFF4F7B)+ }val GlassFill = Color(0xFF2C2C34).copy(alpha = 0.88f)val GlassEdge = Color.White.copy(alpha = 0.12f)+ /** The red of a destructive swipe, menu entry or confirmation (Leave, Remove, an error). */+ val Destructive = Color(0xFFFF453A)// Shapes.val CoverSmall: Shape = RoundedCornerShape(6.dp)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.ktindex d6af2e00..121a0501 100644--- 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.kt@@ -40,6 +40,7 @@ import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApiimport com.bumptech.glide.integration.compose.GlideImageimport com.music.spotui.ui.components.spotifyImageUrlimport com.music.spotui.ui.immersive.Immersive+import com.music.spotui.ui.look.rememberReduceMotion/** The hairline every cover carries, so a cover with light edges does not dissolve into the page. */fun Modifier.immersiveThumbnailBorder(shape: Shape): Modifier =@@ -117,7 +118,10 @@ fun ImmersiveCoverPlaceholder(*/@Composablefun ImmersivePlayingBars(modifier: Modifier = Modifier) {+ val reduceMotion = rememberReduceMotion()val heights = listOf(0.38f, 0.78f, 0.52f).mapIndexed { index, minimum ->+ // Under "reduce motion" the bars rest at their low mark instead of dancing.+ if (reduceMotion) return@mapIndexed minimumval transition = rememberInfiniteTransition(label = "immersive playing bar $index")val height by transition.animateFloat(initialValue = minimum,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.ktindex 83b16049..4872c437 100644--- 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.kt@@ -38,6 +38,7 @@ import androidx.compose.ui.graphics.graphicsLayerimport androidx.compose.ui.unit.Dpimport androidx.compose.ui.unit.dpimport com.music.spotui.ui.immersive.Immersive+import com.music.spotui.ui.look.rememberReduceMotion/** Grey stand-ins for content still on the wire, laid out to the same metrics as the real rows and@@ -65,7 +66,8 @@ private val SubtitleWidths = listOf(0.34f, 0.44f, 0.27f, 0.38f, 0.31f)fun ImmersiveShimmerBox(modifier: Modifier = Modifier, shape: Shape = BlockShape) {val base = Immersive.Raisedval highlight = Immersive.Text.copy(alpha = 0.10f).compositeOver(base)- val sweep = rememberInfiniteTransition(label = "immersive skeleton").animateFloat(+ // Under "reduce motion" the band stays off the block: a flat placeholder, nothing endless running.+ val sweep = if (rememberReduceMotion()) null else rememberInfiniteTransition(label = "immersive skeleton").animateFloat(initialValue = 0f,targetValue = 1f,animationSpec = infiniteRepeatable(tween(SHIMMER_PERIOD_MS, easing = LinearEasing)),@@ -78,7 +80,7 @@ fun ImmersiveShimmerBox(modifier: Modifier = Modifier, shape: Shape = BlockShape// 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 startX = -band + (sweep?.value ?: 0f) * (size.width + band * 2)val brush = Brush.horizontalGradient(colors = listOf(base, highlight, base),startX = startX,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.ktindex db9f3270..0919b7db 100644--- a/base/app/src/main/java/com/music/spotui/ui/immersive/lyrics/ImmersiveLyricsPanel.kt+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/lyrics/ImmersiveLyricsPanel.kt@@ -788,7 +788,8 @@ private const val SKELETON_PERIOD_MS = 1_400@Composableprivate fun LyricsSkeleton(modifier: Modifier = Modifier) {- val sweep = rememberInfiniteTransition(label = "lyricsSkeleton").animateFloat(+ // Under "reduce motion" the band stays off the bars: flat placeholders, nothing endless running.+ val sweep = if (rememberReduceMotion()) null else rememberInfiniteTransition(label = "lyricsSkeleton").animateFloat(initialValue = 0f,targetValue = 1f,animationSpec = infiniteRepeatable(tween(SKELETON_PERIOD_MS, easing = LinearEasing)),@@ -812,7 +813,7 @@ private fun LyricsSkeleton(modifier: Modifier = Modifier) {.drawWithCache {val full = column.toPx()val band = full * 0.45f- val startX = -band + sweep.value * (full + band * 2)+ val startX = -band + (sweep?.value ?: 0f) * (full + band * 2)val brush = Brush.horizontalGradient(colors = listOf(Color.White.copy(alpha = 0.10f),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.ktindex bc204c60..f1661e57 100644--- a/base/app/src/main/java/com/music/spotui/ui/immersive/motion/ImmersiveMotion.kt+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/motion/ImmersiveMotion.kt@@ -6,8 +6,6 @@ import androidx.compose.animation.ExitTransitionimport androidx.compose.animation.core.Springimport androidx.compose.animation.core.springimport androidx.compose.animation.core.tween-import androidx.compose.animation.fadeIn-import androidx.compose.animation.fadeOutimport androidx.compose.animation.slideInHorizontallyimport androidx.compose.animation.slideOutHorizontallyimport androidx.compose.foundation.lazy.LazyItemScope@@ -16,6 +14,7 @@ import androidx.compose.ui.Modifierimport androidx.compose.ui.unit.IntOffsetimport androidx.navigation.NavBackStackEntryimport com.music.spotui.ui.look.rememberReduceMotion+import com.music.spotui.ui.navigation.Routes/*** The motion constants of the Immersive look in one place, so screens share one feel instead of@@ -45,6 +44,9 @@ object ImmersiveMotion {const val LONG_MS = 420const val TINT_MS = 600+ /** A sheet warming into its cover's colours the first time it is seen: quicker than the player's [TINT_MS], as a sheet is brief. */+ const val SHEET_TINT_MS = 400+/** Press feedback (scale under the finger): stiff and fully damped, it never wobbles. */fun <T> pressSpring() = spring<T>(stiffness = 900f)@@ -72,28 +74,55 @@ object ImmersiveMotion {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`.+ * Enter/exit specs for `NavHost` in the Immersive look. Switching between the three tabs is+ * a short fade, as in Classic (tabs are siblings, not a stack); with "reduce motion" every+ * page change is that short fade. Pass them as `enterTransition`, `exitTransition`,+ * `popEnterTransition`, `popExitTransition`.+ */+ /**+ * Page transitions: the slides here, the fades run by the page itself ([PageFade], see+ * MyNavHost's `page`), so the Liquid Glass sampling a page fades with it frame by frame+ * instead of jumping once the transition is over.*/object Pages {+ private val tabRoutes = setOf(Routes.Home.route, Routes.Search.route, Routes.Library.route)++ private fun AnimatedContentTransitionScope<NavBackStackEntry>.isTabSwitch() =+ initialState.destination.route in tabRoutes && targetState.destination.route in tabRoutes+fun enter(reduce: Boolean): AnimatedContentTransitionScope<NavBackStackEntry>.() -> EnterTransition = {- if (reduce) fadeIn(tween(FADE_MS)) else slideInHorizontally(spring(stiffness = Spring.StiffnessMediumLow, visibilityThreshold = IntOffset(1, 1))) { it } +- fadeIn(tween(PAGE_MS / 2))+ val still = reduce || isTabSwitch()+ PageFade.enterMs = if (still) FADE_MS else PAGE_MS / 2+ if (still) EnterTransition.None else slideInHorizontally(spring(stiffness = Spring.StiffnessMediumLow, visibilityThreshold = IntOffset(1, 1))) { it }}fun exit(reduce: Boolean): AnimatedContentTransitionScope<NavBackStackEntry>.() -> ExitTransition = {- if (reduce) fadeOut(tween(FADE_MS)) else slideOutHorizontally(tween(PAGE_MS)) { -it / 3 } + fadeOut(tween(PAGE_MS))+ val still = reduce || isTabSwitch()+ PageFade.exitMs = if (still) FADE_MS else PAGE_MS+ if (still) ExitTransition.None else slideOutHorizontally(tween(PAGE_MS)) { -it / 3 }}fun popEnter(reduce: Boolean): AnimatedContentTransitionScope<NavBackStackEntry>.() -> EnterTransition = {- if (reduce) fadeIn(tween(FADE_MS)) else slideInHorizontally(tween(PAGE_MS)) { -it / 3 } + fadeIn(tween(PAGE_MS))+ val still = reduce || isTabSwitch()+ PageFade.enterMs = if (still) FADE_MS else PAGE_MS+ if (still) EnterTransition.None else slideInHorizontally(tween(PAGE_MS)) { -it / 3 }}fun popExit(reduce: Boolean): AnimatedContentTransitionScope<NavBackStackEntry>.() -> ExitTransition = {- if (reduce) fadeOut(tween(FADE_MS)) else slideOutHorizontally(tween(PAGE_MS)) { it } + fadeOut(tween(PAGE_MS / 2))+ val still = reduce || isTabSwitch()+ PageFade.exitMs = if (still) FADE_MS else PAGE_MS / 2+ if (still) ExitTransition.None else slideOutHorizontally(tween(PAGE_MS)) { it }}}++ /**+ * How long the page coming in fades in, and the one leaving fades out, in the transition+ * starting: set by [Pages] when the navigation picks its transition, read by the pages.+ */+ object PageFade {+ @Volatile var enterMs: Int = PAGE_MS / 2+ @Volatile var exitMs: Int = PAGE_MS+ }}/**diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveExtensionDetail.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveExtensionDetail.ktnew file mode 100644index 00000000..655d09cb--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveExtensionDetail.kt@@ -0,0 +1,437 @@+package com.music.spotui.ui.immersive.pages++import android.content.Intent+import android.net.Uri+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.width+import androidx.compose.foundation.text.BasicTextField+import androidx.compose.foundation.text.KeyboardOptions+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.collectAsState+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.draw.clip+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.SolidColor+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontFamily+import androidx.compose.ui.text.input.KeyboardType+import androidx.compose.ui.text.input.PasswordVisualTransformation+import androidx.compose.ui.text.input.VisualTransformation+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import androidx.navigation.NavController+import app.myspoti.engine.R+import app.myspoti.extensions.Category+import app.myspoti.extensions.Setting+import app.myspoti.extensions.Store+import app.myspoti.extensions.StoreAction+import com.music.spotui.extensions.ExtensionStore+import com.music.spotui.extensions.ExtensionUpdates+import com.music.spotui.extensions.Extensions+import com.music.spotui.extensions.Grants+import com.music.spotui.ui.immersive.Immersive+import com.music.spotui.ui.screens.ActionRow+import com.music.spotui.ui.screens.ExtIcon+import com.music.spotui.ui.screens.ExtPill+import com.music.spotui.ui.screens.InstallPrompt+import com.music.spotui.ui.screens.RateButtons+import com.music.spotui.ui.screens.RatingLine+import com.music.spotui.ui.screens.RefusedNeedsOk+import com.music.spotui.ui.screens.RepoChangedWarning+import com.music.spotui.ui.screens.Tags+import com.music.spotui.ui.screens.UpdateNeedsOk+import com.music.spotui.ui.screens.VersionPill+import com.music.spotui.ui.screens.Warning+import com.music.spotui.ui.screens.appVersion+import com.music.spotui.ui.screens.authorLine+import com.music.spotui.ui.screens.categoryLabel+import com.music.spotui.ui.screens.checkResult+import com.music.spotui.ui.screens.extensionPageRoute+import com.music.spotui.ui.screens.iconOf+import com.music.spotui.ui.screens.incompatibleLine+import com.music.spotui.ui.screens.incompatibleWith+import com.music.spotui.ui.screens.installFromStore+import com.music.spotui.ui.screens.installedRoute+import com.music.spotui.ui.screens.rememberEnabler+import com.music.spotui.ui.screens.rememberPackagePicker+import com.music.spotui.ui.screens.saveSetting+import com.music.spotui.ui.screens.settingInitial+import com.music.spotui.ui.screens.stateLine+import com.music.spotui.ui.screens.storeRoute+import com.music.spotui.ui.screens.toastError+import kotlinx.coroutines.launch++/** The sides of a Classic card (Warning or accent tint) placed on this page: its own 16 dp plus 4 dp make the page gutter. */+private val CardInset = Modifier.padding(horizontal = 4.dp)++/** Icon, author, version and category: the top of both detail pages (the name is the page's title). */+@Composable+private fun ExtHeader(id: String, name: String, author: String, repo: String?, version: String, category: Category, iconUrl: String?, iconBytes: ByteArray?) {+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(horizontal = Immersive.Gutter, vertical = 8.dp)) {+ ExtIcon(id, name, iconUrl, iconBytes, 72.dp)+ Column(Modifier.padding(start = 16.dp)) {+ Text(authorLine(author, repo), style = Immersive.Subhead, maxLines = 2)+ Row(Modifier.padding(top = 6.dp), horizontalArrangement = Arrangement.spacedBy(6.dp)) {+ VersionPill(version)+ ExtPill(stringResource(categoryLabel(category)), Immersive.Accent, Immersive.Accent.copy(alpha = 0.15f))+ }+ }+ }+}++/** A label and its value, the value in monospace for ids and hashes. */+@Composable+private fun DetailRow(label: Int, value: String, mono: Boolean = false) {+ Row(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 10.dp)) {+ Text(stringResource(label), style = Immersive.Caption, modifier = Modifier.width(100.dp))+ Text(+ value,+ style = Immersive.Caption.copy(color = Immersive.Text, fontFamily = if (mono) FontFamily.Monospace else FontFamily.Default),+ modifier = Modifier.weight(1f),+ )+ }+}++/** A note in a tinted rounded card (a warning, an update on offer), on the page's gutters. */+@Composable+private fun TintedCard(tint: Color, content: @Composable () -> Unit) {+ Column(+ Modifier.fillMaxWidth().padding(horizontal = Immersive.Gutter, vertical = 6.dp)+ .clip(Immersive.Card).background(tint.copy(alpha = 0.10f)).padding(14.dp),+ ) { content() }+}++private fun openLink(ctx: android.content.Context, url: String) {+ runCatching { ctx.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url))) }+}++/** A repository's extension before it is installed, in the Immersive look; the Classic `ExtensionEntryScreen`'s data and actions. */+@Composable+fun ImmersiveExtensionEntryScreen(navController: NavController, id: String) {+ val ctx = LocalContext.current+ val scope = rememberCoroutineScope()+ val registry by Extensions.registry.collectAsState()+ val repos by ExtensionStore.repos.collectAsState()+ val busy by ExtensionStore.busy.collectAsState()+ val ratings by ExtensionStore.ratings.collectAsState()+ val downloads by ExtensionStore.downloads.collectAsState()+ LaunchedEffect(registry.repositories) { ExtensionStore.refresh(registry.repositories) }+ val found = Store.newest(ExtensionStore.read())[id]++ ImmersivePage(title = found?.second?.name ?: id, onBack = { navController.popBackStack() }) {+ if (found == null) {+ immersiveBlock("missing") { Text(stringResource(R.string.extension_not_listed), style = Immersive.Subhead) }+ return@ImmersivePage+ }+ val (repo, e) = found+ val installed = registry.find(id)+ val action = Store.action(e, installed?.versionCode, appVersion)+ val m = e.preview()+ item(key = "ext:header") {+ ExtHeader(e.id, e.name, e.author, e.repo, e.version, e.category(), iconOf(repo, e), installed?.let { Extensions.pkg(id)?.icon })+ }+ if (e.repo != null) item(key = "ext:rating") {+ LaunchedEffect(e.repo) { ExtensionStore.loadDownloads(e.repo!!) }+ Column(Modifier.padding(horizontal = Immersive.Gutter)) {+ Row(verticalAlignment = Alignment.CenterVertically) {+ RatingLine(e.repo?.let { ratings[it] })+ e.repo?.let { downloads[it] }?.let {+ Text(" · " + stringResource(R.string.extension_downloads, it.toString()), style = Immersive.Caption.copy(fontSize = 11.sp))+ }+ }+ }+ }+ // The buttons keep their own 12 dp, 8 dp more make the gutter.+ if (e.repo != null) item(key = "ext:rate") { Box(Modifier.padding(horizontal = 8.dp)) { RateButtons(e.repo!!) } }+ item(key = "ext:state") {+ Column(Modifier.padding(horizontal = Immersive.Gutter, vertical = 8.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {+ if (action == StoreAction.INCOMPATIBLE) Text(incompatibleLine(e), style = Immersive.Subhead.copy(color = Warning))+ if (action == StoreAction.UPDATE && installed != null) Text(stringResource(R.string.extension_update_from, installed.version, e.version), style = Immersive.Caption)+ ImmersiveStateButton(action, id in busy, large = true,+ onInstall = { scope.launch { installFromStore(ctx, repo, e) } },+ onOpen = { navController.navigate(installedRoute(id)) })+ }+ }+ if (e.description.isNotBlank()) immersiveBlock("description") { Text(e.description, style = Immersive.Body) }+ item(key = "ext:tags") { Tags(e.tags) }+ if (e.changelog.isNotBlank()) immersiveGroup("changelog", headerRes = R.string.extension_changelog) {+ row { Text(e.changelog, style = Immersive.Subhead.copy(color = Immersive.Text), modifier = Modifier.padding(16.dp)) }+ }+ item(key = "ext:clash") {+ incompatibleWith(e, registry)?.let { Text(it, style = Immersive.Subhead.copy(color = Warning), modifier = Modifier.padding(horizontal = Immersive.Gutter, vertical = 6.dp)) }+ }+ val asks = m.asks().sortedByDescending { it.critical }+ immersiveGroup("actions", headerRes = R.string.actions_title) {+ asks.forEach { a -> row { Box(Modifier.padding(horizontal = 16.dp, vertical = 4.dp)) { ActionRow(a) } } }+ }+ if (asks.any { it.critical }) immersiveBlock("critical") {+ Text(stringResource(R.string.actions_critical_warning), style = Immersive.Caption.copy(color = Warning),+ modifier = Modifier.fillMaxWidth().clip(Immersive.Card).background(Warning.copy(alpha = 0.10f)).padding(12.dp))+ }+ immersiveGroup("details", headerRes = R.string.extension_details) {+ e.updatedAt?.let { row { DetailRow(R.string.extension_detail_updated, it.take(10)) } }+ e.minAppVersion?.let { row { DetailRow(R.string.extension_detail_min_app, it) } }+ if (e.size > 0) row { DetailRow(R.string.extension_detail_size, "${(e.size + 1023) / 1024} KB") }+ // What the package will be checked against when it is downloaded (the rest is on the store's list and, once installed, here).+ if (e.sha256.isNotBlank()) row { DetailRow(R.string.extension_detail_sha, e.sha256.take(16) + "…", mono = true) }+ }+ immersiveGroup("links") {+ e.homepage?.takeIf { it.startsWith("https://") }?.let { url ->+ row { ImmersiveGroupRow(stringResource(R.string.extension_homepage), chevron = true, onClick = { openLink(ctx, url) }) }+ }+ row {+ ImmersiveGroupRow(stringResource(R.string.extension_report), chevron = true, onClick = {+ openLink(ctx, app.myspoti.extensions.GitHub.reportUrl(e.id, e.version, e.repo, e.sha256.ifBlank { null }))+ })+ }+ }+ }+ InstallPrompt()+}++/** One installed extension's page in the Immersive look; the Classic `ExtensionScreen`'s data and actions. */+@Composable+fun ImmersiveExtensionScreen(navController: NavController, id: String) {+ val ctx = LocalContext.current+ val scope = rememberCoroutineScope()+ val registry by Extensions.registry.collectAsState()+ val errors by Extensions.errors.collectAsState()+ val statuses by Extensions.statuses.collectAsState()+ val logTick by Extensions.logTick.collectAsState()+ val repos by ExtensionStore.repos.collectAsState()+ val busy by ExtensionStore.busy.collectAsState()+ val checking by ExtensionUpdates.checking.collectAsState()+ LaunchedEffect(registry.repositories) { ExtensionStore.refresh(registry.repositories) }+ val e = registry.find(id)+ val pkg = remember(id, e?.sha256) { Extensions.pkg(id) }+ val m = pkg?.manifest+ val pickFile = rememberPackagePicker()+ var uninstall by remember { mutableStateOf(false) }+ val enable = rememberEnabler()+ val lines = remember(id, logTick) { Extensions.logLines(id) }++ ImmersivePage(title = e?.name ?: id, onBack = { navController.popBackStack() }) {+ if (e == null || m == null) {+ immersiveBlock("none") { Text(stringResource(R.string.extensions_none), style = Immersive.Subhead) }+ return@ImmersivePage+ }+ item(key = "ext:header") { ExtHeader(e.id, e.name, e.author, e.origin?.repo, e.version, m.category(), null, pkg.icon) }+ if (e.updateBlocked != null || ExtensionStore.identityChanged(e)) item(key = "ext:repo-changed") { Box(CardInset) { RepoChangedWarning() } }+ if (e.sourceGone) item(key = "ext:source-gone") {+ TintedCard(Warning) { Text(stringResource(R.string.extension_source_gone), style = Immersive.Caption.copy(color = Warning)) }+ }+ // A GitHub update that asks more than the user accepted: what it changes, Accept / Keep current.+ // Unticked actions left from before installs granted everything: paused until one OK.+ val refused = Grants.refused(e, m)+ if (refused.isNotEmpty()) item(key = "ext:refused") {+ Box(CardInset) {+ RefusedNeedsOk(m.asks().filter { it.key in refused }) {+ scope.launch { Extensions.acceptAll(id); enable(id, true) }+ }+ }+ }+ e.pendingUpdate?.let { p ->+ item(key = "ext:pending") {+ Box(CardInset) {+ UpdateNeedsOk(e.name, e.version, p, onAccept = { scope.launch { runCatching { ExtensionUpdates.accept(id) }.onFailure { toastError(ctx, it) } } },+ onKeep = { ExtensionUpdates.keepCurrent(id) })+ }+ }+ }++ // An update in a repository: its button right here.+ val listed = Store.newest(ExtensionStore.read())[id]+ if (listed != null && listed.second.versionCode > e.versionCode && e.pendingUpdate == null && e.origin == null) item(key = "ext:update") {+ val (repo, entry) = listed+ val action = Store.action(entry, e.versionCode, appVersion)+ TintedCard(Immersive.Accent) {+ Text(stringResource(R.string.extension_update_from, e.version, entry.version), style = Immersive.BodyStrong)+ if (entry.changelog.isNotBlank()) Text(entry.changelog, style = Immersive.Caption, maxLines = 4, modifier = Modifier.padding(top = 2.dp))+ if (action == StoreAction.INCOMPATIBLE) Text(incompatibleLine(entry), style = Immersive.Caption.copy(color = Warning), modifier = Modifier.padding(top = 4.dp))+ Spacer(Modifier.height(8.dp))+ ImmersiveStateButton(action, id in busy, onInstall = { scope.launch { installFromStore(ctx, repo, entry) } }, onOpen = {})+ }+ }++ // One state: why it is off, inactive, its last error, else whether it runs.+ immersiveGroup("enabled") {+ row {+ val state = stateLine(e, errors[id], statuses[id])+ ImmersiveSwitchRow(+ stringResource(R.string.extension_enabled), e.enabled, { enable(id, it) },+ detail = state?.first ?: stringResource(if (Extensions.isRunning(id)) R.string.extension_running else R.string.extension_not_running),+ detailColor = state?.second ?: Immersive.TextSecondary,+ )+ }+ if (Extensions.hasPage(id)) row {+ ImmersiveGroupRow(stringResource(R.string.ext_open_page), chevron = true, onClick = { navController.navigate(extensionPageRoute(id)) })+ }+ }+ if (m.description.isNotBlank()) immersiveBlock("description") { Text(m.description, style = Immersive.Body) }+ item(key = "ext:tags") { Tags(m.tags) }+ if (m.changelog.isNotBlank()) immersiveGroup("changelog", headerRes = R.string.extension_changelog) {+ row { Text(m.changelog, style = Immersive.Subhead.copy(color = Immersive.Text), modifier = Modifier.padding(16.dp)) }+ }++ immersiveGroup("actions", headerRes = R.string.actions_title) {+ m.asks().sortedByDescending { it.critical }.forEach { a -> row { Box(Modifier.padding(horizontal = 16.dp, vertical = 4.dp)) { ActionRow(a) } } }+ }+ // Writes allowed for good from a confirmation ("Always"): each one revocable here.+ if (e.rawGrants.isNotEmpty()) immersiveGroup("grants", headerRes = R.string.ext_grants_title, footerRes = R.string.ext_grants_note) {+ e.rawGrants.forEach { g ->+ row {+ Row(Modifier.fillMaxWidth().padding(start = 16.dp, end = 4.dp), verticalAlignment = Alignment.CenterVertically) {+ Text(g.toString(), style = Immersive.Caption.copy(color = Immersive.Text, fontFamily = FontFamily.Monospace), modifier = Modifier.weight(1f))+ TextButton(onClick = { Extensions.revokeRawGrant(id, g) }) {+ Text(stringResource(R.string.ext_grant_revoke), style = Immersive.Subhead.copy(color = Warning))+ }+ }+ }+ }+ }+ if (m.settings.isNotEmpty()) immersiveGroup("settings", headerRes = R.string.extension_settings) {+ m.settings.forEach { s -> row { SettingRow(id, s) } }+ }++ immersiveGroup("details", headerRes = R.string.extension_details) {+ row { DetailRow(R.string.extension_detail_id, e.id, mono = true) }+ row { DetailRow(R.string.extension_detail_source, e.source) }+ e.origin?.let { o ->+ row { DetailRow(R.string.extension_detail_github, o.repo, mono = true) }+ row { DetailRow(R.string.extension_detail_ref, o.label(), mono = true) }+ }+ row { DetailRow(R.string.extension_detail_sha, e.sha256.take(16) + "…", mono = true) }+ }+ immersiveGroup("manage") {+ if (e.origin != null) row {+ ImmersiveGroupRow(stringResource(R.string.extension_check_updates), enabled = id !in checking, chevron = true, onClick = {+ scope.launch {+ val r = ExtensionUpdates.check(id, manual = true)+ android.widget.Toast.makeText(ctx, ctx.getString(checkResult(r)), android.widget.Toast.LENGTH_SHORT).show()+ }+ })+ }+ e.previous?.let { prev ->+ row {+ ImmersiveGroupRow(stringResource(R.string.extension_revert, prev.version), chevron = true, onClick = {+ scope.launch {+ runCatching { ExtensionUpdates.revert(id) }+ .onSuccess { android.widget.Toast.makeText(ctx, ctx.getString(R.string.extension_reverted, prev.version), android.widget.Toast.LENGTH_SHORT).show() }+ .onFailure { toastError(ctx, it) }+ }+ })+ }+ }+ m.homepage?.takeIf { it.startsWith("https://") }?.let { url ->+ row { ImmersiveGroupRow(stringResource(R.string.extension_homepage), chevron = true, onClick = { openLink(ctx, url) }) }+ }+ if (listed != null) row {+ ImmersiveGroupRow(stringResource(R.string.extension_see_in_store), chevron = true, onClick = { navController.navigate(storeRoute(id)) })+ }+ row { ImmersiveGroupRow(stringResource(R.string.extension_update_file), chevron = true, onClick = pickFile) }+ row {+ ImmersiveGroupRow(stringResource(R.string.extension_report), chevron = true, onClick = {+ openLink(ctx, app.myspoti.extensions.GitHub.reportUrl(e.id, e.version, e.origin?.repo, e.sha256))+ })+ }+ row { ImmersiveGroupRow(stringResource(R.string.extension_uninstall), destructive = true, onClick = { uninstall = true }) }+ }++ immersiveGroup("log", headerRes = R.string.extension_log) {+ row {+ Column(Modifier.fillMaxWidth().padding(16.dp)) {+ if (lines.isEmpty()) Text(stringResource(R.string.extension_log_empty), style = Immersive.Caption)+ lines.takeLast(150).asReversed().forEach {+ Text(it, style = Immersive.Caption.copy(fontFamily = FontFamily.Monospace, fontSize = 11.sp), modifier = Modifier.padding(vertical = 1.dp))+ }+ }+ }+ if (lines.isNotEmpty()) row {+ ImmersiveGroupRow(stringResource(R.string.extension_log_clear), onClick = { Extensions.clearLog(id) })+ }+ }+ }++ if (uninstall && e != null) AlertDialog(+ onDismissRequest = { uninstall = false },+ containerColor = Immersive.Raised,+ text = { Text(stringResource(R.string.extension_uninstall_confirm, e.name), style = Immersive.Body) },+ confirmButton = {+ TextButton(onClick = {+ uninstall = false+ // Back out only if the page is still the one on top (the uninstall takes a moment).+ val page = navController.currentBackStackEntry+ scope.launch {+ Extensions.uninstall(id)+ if (navController.currentBackStackEntry == page) navController.popBackStack()+ }+ }) { Text(stringResource(R.string.extension_uninstall), style = Immersive.BodyStrong.copy(color = Immersive.Destructive)) }+ },+ dismissButton = {+ TextButton(onClick = { uninstall = false }) {+ Text(stringResource(R.string.extensions_cancel), style = Immersive.BodyStrong.copy(color = Immersive.Accent))+ }+ },+ )+ InstallPrompt()+}++/** One of the extension's options (manifest `settings`), saved as JSON as it changes (see `saveSetting`). */+@Composable+private fun SettingRow(id: String, s: Setting) {+ var value by remember(id, s.key) { mutableStateOf(settingInitial(id, s)) }+ fun save(v: String) {+ value = v+ saveSetting(id, s, v)+ }+ when (s.type) {+ "toggle" -> ImmersiveSwitchRow(s.label, value == "true", { save(it.toString()) }, detail = s.description)+ "button" -> ImmersiveGroupRow(s.label, detail = s.description.ifBlank { null }, chevron = true, onClick = { Extensions.pressSetting(id, s.key) })+ "choice" -> Column {+ Column(Modifier.padding(horizontal = 16.dp, vertical = 10.dp)) {+ Text(s.label, style = Immersive.Body)+ if (s.description.isNotBlank()) Text(s.description, style = Immersive.Caption)+ }+ s.options.forEach { o -> ImmersiveChoiceRow(o, selected = value == o, onClick = { save(o) }) }+ }+ else -> Column(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 10.dp)) {+ Text(s.label, style = Immersive.Caption)+ Box(+ Modifier.padding(top = 6.dp).fillMaxWidth()+ .background(Color.White.copy(alpha = 0.08f), Immersive.Button)+ .padding(horizontal = 14.dp, vertical = 12.dp),+ ) {+ BasicTextField(+ value = value,+ onValueChange = ::save,+ singleLine = true,+ textStyle = Immersive.Body,+ cursorBrush = SolidColor(Immersive.Accent),+ visualTransformation = if (s.type == "secret") PasswordVisualTransformation() else VisualTransformation.None,+ keyboardOptions = KeyboardOptions(keyboardType = when (s.type) { "number" -> KeyboardType.Number; "secret" -> KeyboardType.Password; else -> KeyboardType.Text }),+ modifier = Modifier.fillMaxWidth(),+ )+ }+ if (s.description.isNotBlank()) Text(s.description, style = Immersive.Caption, modifier = Modifier.padding(top = 4.dp))+ }+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveExtensionParts.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveExtensionParts.ktnew file mode 100644index 00000000..8d64b277--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveExtensionParts.kt@@ -0,0 +1,166 @@+package com.music.spotui.ui.immersive.pages++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.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+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.widthIn+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.material3.CircularProgressIndicator+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.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.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.extensions.StoreAction+import com.music.spotui.ui.immersive.Immersive+import com.music.spotui.ui.immersive.components.immersiveClickable+import com.music.spotui.ui.immersive.shell.ImmersiveTopBar+import com.music.spotui.ui.immersive.shell.immersiveTopContentPadding++/**+ * One row of an extension list (store, installed): the [leading] icon, a column of lines+ * ([content]) and, at the end, [trailing] controls. Meant for the rows of an `immersiveGroup`; the+ * whole row opens something when [onClick] is set.+ */+@Composable+internal fun ImmersiveExtRow(+ modifier: Modifier = Modifier,+ onClick: (() -> Unit)? = null,+ leading: @Composable () -> Unit,+ trailing: (@Composable () -> Unit)? = null,+ content: @Composable ColumnScope.() -> Unit,+) {+ Row(+ verticalAlignment = Alignment.CenterVertically,+ modifier = modifier+ .fillMaxWidth()+ .then(if (onClick != null) Modifier.immersiveClickable(onClick = onClick, pressedScale = 0.99f) else Modifier)+ .padding(horizontal = 16.dp, vertical = 12.dp),+ ) {+ leading()+ Column(Modifier.weight(1f).padding(horizontal = 12.dp), content = content)+ trailing?.invoke()+ }+}++/** A switch in the Immersive colours, for the end of a row that also opens something. */+@Composable+internal fun ImmersiveSwitch(checked: Boolean, onChecked: (Boolean) -> Unit) {+ Switch(+ checked = checked,+ onCheckedChange = onChecked,+ colors = SwitchDefaults.colors(+ checkedThumbColor = Color.White,+ checkedTrackColor = Immersive.Accent,+ uncheckedThumbColor = Color.White,+ uncheckedTrackColor = Color(0xFF3A3A3F),+ uncheckedBorderColor = Color.Transparent,+ ),+ )+}++/** A bare 32 dp icon button for the end of a row (a bin, an arrow, a refresh). */+@Composable+internal fun ImmersiveRowIcon(+ icon: ImageVector,+ contentDescription: String,+ onClick: () -> Unit,+ enabled: Boolean = true,+ tint: Color = Immersive.TextSecondary,+) {+ Box(+ contentAlignment = Alignment.Center,+ modifier = Modifier+ .size(36.dp)+ .clip(CircleShape)+ .immersiveClickable(onClick = onClick, enabled = enabled, pressedScale = 0.9f),+ ) {+ Icon(icon, contentDescription, tint = tint.copy(alpha = if (enabled) 1f else 0.3f), modifier = Modifier.size(22.dp))+ }+}++/**+ * The frame of an extension's own page (its WebView): the page colour and the glass top bar with+ * the page's [title] and a line saying whose page it is, the [content] under them.+ */+@Composable+internal fun ImmersiveExtensionPageFrame(title: String, subtitle: String, onBack: () -> Unit, content: @Composable () -> Unit) {+ ImmersivePageFrame {+ Column(Modifier.fillMaxSize().padding(top = immersiveTopContentPadding()).navigationBarsPadding()) {+ Text(+ subtitle,+ style = Immersive.Caption,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ modifier = Modifier.padding(horizontal = Immersive.Gutter, vertical = 4.dp),+ )+ Box(Modifier.fillMaxWidth().weight(1f)) { content() }+ }+ ImmersiveTopBar(title = title, collapse = { 1f }, onBack = onBack)+ }+}++/**+ * The one state button of a store row or page: Install (filled), Update (tinted), Up to date+ * (quiet, opens the installed page), or a spinner while the package downloads. [large] fills the+ * width, for the page of one extension.+ */+@Composable+internal fun ImmersiveStateButton(+ action: StoreAction,+ busy: Boolean,+ large: Boolean = false,+ onInstall: () -> Unit,+ onOpen: () -> Unit,+) {+ val sizing = if (large) Modifier.fillMaxWidth().heightIn(min = 46.dp) else Modifier.widthIn(min = 84.dp).heightIn(min = 32.dp)+ if (busy) {+ Box(sizing, contentAlignment = Alignment.Center) {+ CircularProgressIndicator(Modifier.size(20.dp), color = Immersive.Accent, strokeWidth = 2.dp)+ }+ return+ }+ val (label, fill, content) = when (action) {+ StoreAction.INSTALL -> Triple(R.string.extensions_install, Immersive.Accent, Color.White)+ StoreAction.UPDATE -> Triple(R.string.extensions_update, Immersive.Accent.copy(alpha = 0.22f), Immersive.Accent)+ StoreAction.INSTALLED -> Triple(R.string.extensions_up_to_date, Immersive.Raised, Immersive.TextSecondary)+ StoreAction.INCOMPATIBLE -> Triple(R.string.extensions_install, Immersive.Raised, Immersive.TextTertiary)+ }+ val click = when (action) {+ StoreAction.INSTALL, StoreAction.UPDATE -> onInstall+ StoreAction.INSTALLED -> onOpen+ StoreAction.INCOMPATIBLE -> ({})+ }+ Box(+ contentAlignment = Alignment.Center,+ modifier = sizing+ .clip(if (large) Immersive.Button else CircleShape)+ .background(fill)+ .immersiveClickable(onClick = click, enabled = action != StoreAction.INCOMPATIBLE)+ .padding(horizontal = if (large) 20.dp else 14.dp),+ ) {+ Text(+ stringResource(label),+ style = Immersive.Subhead.copy(color = content, fontWeight = FontWeight.SemiBold),+ maxLines = 1,+ )+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveExtensionsScreen.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveExtensionsScreen.ktnew file mode 100644index 00000000..a716c410--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveExtensionsScreen.kt@@ -0,0 +1,476 @@+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.fillMaxWidth+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.material.icons.Icons+import androidx.compose.material.icons.rounded.Add+import androidx.compose.material.icons.rounded.DeleteOutline+import androidx.compose.material.icons.rounded.Folder+import androidx.compose.material.icons.rounded.KeyboardArrowDown+import androidx.compose.material.icons.rounded.KeyboardArrowUp+import androidx.compose.material.icons.rounded.Link+import androidx.compose.material.icons.rounded.Refresh+import androidx.compose.material3.AlertDialog+import androidx.compose.material3.CircularProgressIndicator+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.material3.TextButton+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.rememberCoroutineScope+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.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontFamily+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import androidx.navigation.NavController+import app.myspoti.engine.R+import app.myspoti.extensions.Action+import app.myspoti.extensions.Area+import app.myspoti.extensions.Catalog+import app.myspoti.extensions.Category+import app.myspoti.extensions.Store+import app.myspoti.extensions.StoreAction+import app.myspoti.extensions.mode+import com.music.spotui.extensions.ExtensionStore+import com.music.spotui.extensions.Extensions+import com.music.spotui.extensions.InstalledExtension+import com.music.spotui.extensions.Registry+import com.music.spotui.extensions.actionIcon+import com.music.spotui.extensions.actionLabel+import com.music.spotui.extensions.areaLabel+import com.music.spotui.ui.immersive.Immersive+import com.music.spotui.ui.immersive.components.ImmersiveButton+import com.music.spotui.ui.immersive.components.ImmersiveSearchField+import com.music.spotui.ui.immersive.components.immersiveClickable+import com.music.spotui.ui.immersive.screens.ImmersiveChip+import com.music.spotui.ui.immersive.screens.ImmersiveChipRow+import com.music.spotui.ui.screens.ActionIcons+import com.music.spotui.ui.screens.Dot+import com.music.spotui.ui.screens.ExtIcon+import com.music.spotui.ui.screens.ExtPill+import com.music.spotui.ui.screens.InstallPrompt+import com.music.spotui.ui.screens.RatingLine+import com.music.spotui.ui.screens.UrlDialog+import com.music.spotui.ui.screens.VersionPill+import com.music.spotui.ui.screens.Warning+import com.music.spotui.ui.screens.appVersion+import com.music.spotui.ui.screens.authorLine+import com.music.spotui.ui.screens.categoryLabel+import com.music.spotui.ui.screens.iconOf+import com.music.spotui.ui.screens.incompatibleLine+import com.music.spotui.ui.screens.incompatibleWith+import com.music.spotui.ui.screens.installFromStore+import com.music.spotui.ui.screens.installedRoute+import com.music.spotui.ui.screens.offer+import com.music.spotui.ui.screens.rememberEnabler+import com.music.spotui.ui.screens.rememberPackagePicker+import com.music.spotui.ui.screens.stateLine+import com.music.spotui.ui.screens.storeRoute+import com.music.spotui.ui.screens.toastError+import kotlinx.coroutines.launch++/**+ * The extensions page of the Immersive look: Store and Installed behind a segmented control,+ * search and category pills, then the repositories' extensions or the installed ones by area, in+ * grouped rows. Everything the Classic `ExtensionsScreen` does is here, with its state and+ * helpers: install from a repository, a file or an address, turn on and off, uninstall, the order+ * of the sources of an area, repositories and GitHub discovery, refresh.+ */+@Composable+fun ImmersiveExtensionsScreen(navController: NavController) {+ val ctx = LocalContext.current+ val scope = rememberCoroutineScope()+ val registry by Extensions.registry.collectAsState()+ val errors by Extensions.errors.collectAsState()+ val statuses by Extensions.statuses.collectAsState()+ val repos by ExtensionStore.repos.collectAsState()+ val busy by ExtensionStore.busy.collectAsState()+ val pickFile = rememberPackagePicker()+ val enable = rememberEnabler()+ var askUrl by remember { mutableStateOf(false) }+ var askRepo by remember { mutableStateOf(false) }+ var downloading by remember { mutableStateOf(false) }+ var tab by rememberSaveable { mutableStateOf(if (registry.extensions.isEmpty()) 0 else 1) }+ var query by rememberSaveable { mutableStateOf("") }+ var categoryKey by rememberSaveable { mutableStateOf<String?>(null) }+ val category = categoryKey?.let { Category.of(it) }++ LaunchedEffect(registry.repositories) { ExtensionStore.refresh(registry.repositories) }+ val catalogs = repos.values.mapNotNull { r -> r.catalog?.let { r.url to it } }+ val installedCodes = registry.extensions.associate { it.id to it.versionCode }+ // Updates in a repository, and GitHub updates waiting for the user's OK.+ val updates = Store.updates(catalogs, installedCodes, appVersion) + registry.extensions.filter { it.pendingUpdate != null }.map { it.id }+ var showAll by rememberSaveable { mutableStateOf(false) }+ val ratings by ExtensionStore.ratings.collectAsState()+ val blocks by com.music.spotui.extensions.ExtensionUpdates.blocks.collectAsState()++ // The store's lists as the tab shows them, and the categories that have something in them.+ val officialShown = remember(repos) { ExtensionStore.officialShown() }+ val storeSources = ExtensionStore.sources(registry.repositories).filter { !ExtensionStore.isOfficial(it) || officialShown }+ val discovered = remember(repos, ratings, blocks, showAll) { ExtensionStore.discovered(showAll) }+ val present = if (tab == 0) (storeSources.flatMap { repos[it]?.catalog?.extensions.orEmpty() } + discovered.map { it.item }).map { it.category() }.toSet()+ else registry.extensions.mapNotNull { Extensions.manifest(it.id)?.category() }.toSet()+ val categories = Category.entries.filter { it in present || it == category }+ val github = repos[app.myspoti.extensions.Discovery.SOURCE]+ val githubShown = discovered.filter { Store.matches(it.item, query, category) }+ val hiddenCount = remember(repos, ratings, blocks) { ExtensionStore.hiddenCount() }+ val shown = storeSources.sumOf { url -> repos[url]?.catalog?.extensions?.count { Store.matches(it, query, category) } ?: 0 } ++ (if (github != null) githubShown.size else 0)+ val installedLabel = stringResource(R.string.extensions_installed)++ ImmersivePage(title = stringResource(R.string.extensions_title), onBack = { navController.popBackStack() }) {+ item(key = "ext:tabs") {+ ImmersiveSegmentedControl(+ options = listOf(stringResource(R.string.extensions_tab_store), if (updates.isNotEmpty()) "$installedLabel (${updates.size})" else installedLabel),+ selectedIndex = tab,+ onSelect = { tab = it },+ modifier = Modifier.padding(horizontal = Immersive.Gutter, vertical = 4.dp),+ )+ }+ item(key = "ext:search") {+ ImmersiveSearchField(+ query = query, onQueryChange = { query = it }, onSubmit = {},+ placeholder = stringResource(R.string.extensions_search),+ modifier = Modifier.padding(horizontal = Immersive.Gutter, vertical = 8.dp),+ )+ }+ if (categories.isNotEmpty()) item(key = "ext:categories") {+ ImmersiveChipRow {+ (listOf<Category?>(null) + categories).forEach { c ->+ ImmersiveChip(stringResource(categoryLabel(c)), selected = c == category) { categoryKey = if (c == category) null else c?.key }+ }+ }+ }+ if (downloading) immersiveBlock("downloading") {+ Text(stringResource(R.string.extensions_loading), style = Immersive.Caption)+ }++ if (tab == 0) {+ if (registry.repositories.none { !ExtensionStore.isOfficial(it) } && !officialShown) immersiveBlock("empty") { EmptyState() }+ storeSources.forEach { url ->+ val repo = repos[url] ?: ExtensionStore.Repo(url, loading = true)+ item(key = "repo:$url") {+ RepoHeader(repo, onRefresh = { ExtensionStore.refresh(registry.repositories, force = true) }, onRemove = { Extensions.removeRepository(url) })+ }+ val entries = repo.catalog?.extensions?.filter { Store.matches(it, query, category) }.orEmpty()+ immersiveGroup("store:$url") {+ entries.forEach { entry ->+ row {+ StoreRow(url, entry, Store.action(entry, installedCodes[entry.id], appVersion), entry.id in busy, registry,+ onOpen = { navController.navigate(storeRoute(entry.id)) },+ onInstall = { scope.launch { installFromStore(ctx, url, entry) } },+ onInstalled = { navController.navigate(installedRoute(entry.id)) })+ }+ }+ }+ }+ // Discovered on GitHub: by score, then the most recently updated; the hidden ones behind "Show all".+ if (github != null) {+ item(key = "repo:github") { GitHubHeader(github, onRefresh = { ExtensionStore.discover(force = true) }) }+ immersiveGroup("store:github") {+ githubShown.forEach { r ->+ row {+ val entry = r.item+ StoreRow(app.myspoti.extensions.Discovery.SOURCE, entry, Store.action(entry, installedCodes[entry.id], appVersion), entry.id in busy, registry,+ onOpen = { navController.navigate(storeRoute(entry.id)) },+ onInstall = { scope.launch { installFromStore(ctx, app.myspoti.extensions.Discovery.SOURCE, entry) } },+ onInstalled = { navController.navigate(installedRoute(entry.id)) },+ rating = r.rating, hidden = app.myspoti.extensions.Ranking.hidden(r, blocks, System.currentTimeMillis()) != null)+ }+ }+ if (hiddenCount > 0 || showAll) row {+ ImmersiveGroupRow(+ title = if (showAll) stringResource(R.string.extensions_show_less) else stringResource(R.string.extensions_show_all, hiddenCount),+ onClick = { showAll = !showAll },+ )+ }+ }+ }+ if (shown == 0 && catalogs.any { it.second.extensions.isNotEmpty() }) immersiveBlock("no-match") {+ Text(stringResource(R.string.extensions_no_match), style = Immersive.Subhead)+ }+ } else {+ val matches = { e: InstalledExtension ->+ val m = Extensions.manifest(e.id)+ (category == null || m?.category() == category) &&+ query.lowercase().split(' ').filter { it.isNotBlank() }.all { w -> listOf(e.name, e.author, m?.description.orEmpty(), e.id, m?.tags.orEmpty().joinToString(" ")).any { it.lowercase().contains(w) } }+ }+ if (registry.extensions.isEmpty()) immersiveBlock("none") {+ Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {+ Text(stringResource(R.string.extensions_none), style = Immersive.Subhead)+ ImmersiveButton(stringResource(R.string.extensions_browse_store), onClick = { tab = 0 })+ }+ }+ // By area: the extensions acting there, in order; an area without any is not listed.+ Extensions.byArea().forEach { (area, list) ->+ val inArea = list.filter(matches)+ if (inArea.isNotEmpty()) areaSection(area, inArea, errors, statuses, updates, enable, onOpen = { navController.navigate(installedRoute(it)) })+ }+ }++ immersiveGroup(+ "other-ways",+ headerRes = R.string.extensions_other_ways,+ footerRes = if (tab == 0) R.string.extensions_repository_warning else null,+ ) {+ if (tab == 0) row {+ ImmersiveGroupRow(stringResource(R.string.extensions_repository_add), icon = Icons.Rounded.Add, chevron = true, onClick = { askRepo = true })+ }+ row { ImmersiveGroupRow(stringResource(R.string.extensions_install_file), icon = Icons.Rounded.Folder, chevron = true, onClick = pickFile) }+ row { ImmersiveGroupRow(stringResource(R.string.extensions_install_url), icon = Icons.Rounded.Link, chevron = true, onClick = { askUrl = true }) }+ }+ }++ if (askUrl) UrlDialog(R.string.extensions_install_url, R.string.extensions_url_hint, onDismiss = { askUrl = false }) { url ->+ askUrl = false+ downloading = true+ scope.launch {+ // A GitHub repository's address: its newest release (or default branch), kept on the phone and updated from there.+ // (GitHub, GitLab or Codeberg; `gitlab:group/name` and `codeberg:owner/name` work too.)+ val gitHub = app.myspoti.extensions.GitHubRepo.parse(url)?.takeIf { !url.endsWith(".zip") }+ runCatching {+ if (gitHub != null) com.music.spotui.extensions.ExtensionUpdates.fromGitHub(gitHub)+ else Extensions.downloadPackage(url).let { (zip, p) -> com.music.spotui.extensions.ExtensionUpdates.Fetched(zip, p, null) }+ }+ .onSuccess { f -> offer(ctx, f.zip, f.origin?.page() ?: url, f.origin) }+ .onFailure { toastError(ctx, it) }+ downloading = false+ }+ }+ if (askRepo) UrlDialog(R.string.extensions_repository_add, R.string.extensions_repository_hint, warning = R.string.extensions_repository_warning, onDismiss = { askRepo = false }) { url ->+ askRepo = false+ Extensions.addRepository(url)+ tab = 0+ }+ InstallPrompt()+}++/** No repository yet: what extensions are, before anything is added. */+@Composable+private fun EmptyState() {+ Column(Modifier.fillMaxWidth()) {+ Text(stringResource(R.string.extensions_empty_title), style = Immersive.BodyStrong)+ Text(stringResource(R.string.extensions_empty_body), style = Immersive.Subhead, modifier = Modifier.padding(top = 4.dp))+ }+}++/** A repository: its name, address and how much it is trusted; refresh and remove. */+@Composable+private fun RepoHeader(repo: ExtensionStore.Repo, onRefresh: () -> Unit, onRemove: () -> Unit) {+ val official = ExtensionStore.isOfficial(repo.url)+ Column(Modifier.fillMaxWidth().padding(start = Immersive.Gutter + 16.dp, end = Immersive.Gutter - 8.dp, top = 18.dp, bottom = 4.dp)) {+ Row(verticalAlignment = Alignment.CenterVertically) {+ Column(Modifier.weight(1f)) {+ Row(verticalAlignment = Alignment.CenterVertically) {+ Text(repo.catalog?.name ?: runCatching { java.net.URI(repo.url).host }.getOrNull() ?: repo.url, style = Immersive.BodyStrong,+ maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))+ Spacer(Modifier.width(8.dp))+ if (official) ExtPill(stringResource(R.string.extensions_official_badge), androidx.compose.ui.graphics.Color.White, Immersive.Accent)+ else ExtPill(stringResource(R.string.extensions_repo_yours), Warning, Warning.copy(alpha = 0.15f))+ }+ Text(repo.url, style = Immersive.Caption.copy(fontFamily = FontFamily.Monospace, fontSize = 10.sp), maxLines = 1, overflow = TextOverflow.Ellipsis)+ Text(stringResource(if (official) R.string.extensions_repo_official_note else R.string.extensions_repo_yours_note),+ style = Immersive.Caption.copy(color = if (official) Immersive.TextSecondary else Warning))+ }+ if (repo.loading) CircularProgressIndicator(Modifier.padding(10.dp).size(20.dp), color = Immersive.Accent, strokeWidth = 2.dp)+ else ImmersiveRowIcon(Icons.Rounded.Refresh, stringResource(R.string.extensions_repository_refresh), onClick = onRefresh)+ if (!official) ImmersiveRowIcon(Icons.Rounded.DeleteOutline, stringResource(R.string.extensions_repository_remove), onClick = onRemove)+ }+ repo.error?.let { Text(stringResource(R.string.extensions_repo_error, it), style = Immersive.Caption.copy(color = Warning)) }+ if (repo.catalog?.extensions?.isEmpty() == true) Text(stringResource(R.string.extensions_repo_empty), style = Immersive.Caption)+ }+}++/** The GitHub discovery's header: what it is (not reviewed), refresh. */+@Composable+private fun GitHubHeader(repo: ExtensionStore.Repo, onRefresh: () -> Unit) {+ Column(Modifier.fillMaxWidth().padding(start = Immersive.Gutter + 16.dp, end = Immersive.Gutter - 8.dp, top = 18.dp, bottom = 4.dp)) {+ Row(verticalAlignment = Alignment.CenterVertically) {+ Column(Modifier.weight(1f)) {+ Row(verticalAlignment = Alignment.CenterVertically) {+ Text(stringResource(R.string.extensions_github_title), style = Immersive.BodyStrong)+ Spacer(Modifier.width(8.dp))+ ExtPill(stringResource(R.string.extensions_repo_community), Warning, Warning.copy(alpha = 0.15f))+ }+ Text(stringResource(R.string.extensions_github_note), style = Immersive.Caption.copy(color = Warning))+ }+ if (repo.loading) CircularProgressIndicator(Modifier.padding(10.dp).size(20.dp), color = Immersive.Accent, strokeWidth = 2.dp)+ else ImmersiveRowIcon(Icons.Rounded.Refresh, stringResource(R.string.extensions_repository_refresh), onClick = onRefresh)+ }+ repo.error?.let { Text(stringResource(R.string.extensions_repo_error, it), style = Immersive.Caption.copy(color = Warning)) }+ }+}++/** A store row: icon, name, version, one line, the rights, and the one state button. */+@Composable+private fun StoreRow(+ repo: String, e: Catalog.Entry, action: StoreAction, busy: Boolean, registry: Registry,+ onOpen: () -> Unit, onInstall: () -> Unit, onInstalled: () -> Unit, rating: app.myspoti.extensions.Rating? = null, hidden: Boolean = false,+) {+ ImmersiveExtRow(+ onClick = onOpen,+ leading = { ExtIcon(e.id, e.name, iconOf(repo, e), null) },+ trailing = { ImmersiveStateButton(action, busy, onInstall = onInstall, onOpen = onInstalled) },+ ) {+ Row(verticalAlignment = Alignment.CenterVertically) {+ Text(e.name, style = Immersive.BodyStrong, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))+ Spacer(Modifier.width(6.dp))+ VersionPill(e.version)+ }+ if (action == StoreAction.INCOMPATIBLE) Text(incompatibleLine(e), style = Immersive.Caption.copy(color = Warning), maxLines = 1, overflow = TextOverflow.Ellipsis)+ else Text(e.description.ifBlank { authorLine(e.author, e.repo) }, style = Immersive.Caption, maxLines = 1, overflow = TextOverflow.Ellipsis)+ incompatibleWith(e, registry)?.let { Text(it, style = Immersive.Caption.copy(color = Warning), maxLines = 1, overflow = TextOverflow.Ellipsis) }+ if (e.repo != null) RatingLine(rating, hidden)+ ActionIcons(e.preview().asks())+ }+}++/**+ * One area of the Installed tab: its extensions in the user's order (arrows to reorder, "Active" /+ * "Idle" for an exclusive action), and who did what lately, with one-tap turn off.+ */+private fun LazyListScope.areaSection(+ area: Area, list: List<InstalledExtension>, errors: Map<String, String>, statuses: Map<String, app.myspoti.extensions.ExtensionStatus>,+ updates: Set<String>, enable: (String, Boolean) -> Unit, onOpen: (String) -> Unit,+) {+ // The exclusive actions of this area: who acts now.+ val exclusive = Action.entries.filter { it.area == area && it.mode == app.myspoti.extensions.Mode.EXCLUSIVE }+ immersiveGroup(+ "area:$area",+ headerRes = areaLabel(area),+ footerRes = if (area == Area.AUDIO && list.size >= 2) R.string.sources_order_hint else null,+ ) {+ list.forEachIndexed { i, e ->+ row {+ val m = remember(e.id, e.sha256) { Extensions.manifest(e.id) }+ InstalledRow(e, errors[e.id], statuses[e.id], e.id in updates, enable, onOpen = { onOpen(e.id) }) {+ exclusive.filter { m?.actionSet()?.contains(it) == true }.forEach { a ->+ val active = Extensions.activeFor(a) == e.id+ Row(+ verticalAlignment = Alignment.CenterVertically,+ modifier = Modifier.padding(top = 2.dp)+ .then(if (!active && e.enabled) Modifier.immersiveClickable(onClick = { Extensions.setActive(a, e.id) }, pressedScale = 0.98f) else Modifier),+ ) {+ Icon(actionIcon(a), null, tint = if (active) Immersive.Accent else Immersive.TextSecondary, modifier = Modifier.size(14.dp))+ Spacer(Modifier.width(4.dp))+ Text(+ if (active) stringResource(R.string.area_active) else stringResource(R.string.area_idle) + " · " + stringResource(R.string.area_make_active, stringResource(actionLabel(a)).lowercase()),+ style = Immersive.Caption.copy(color = if (active) Immersive.Accent else Immersive.TextSecondary), maxLines = 1, overflow = TextOverflow.Ellipsis,+ )+ }+ }+ // Sources are ordered per action, in Settings (see the hint under them).+ if (list.size >= 2 && area != Area.AUDIO) Row {+ ImmersiveRowIcon(Icons.Rounded.KeyboardArrowUp, stringResource(R.string.extensions_move_up), enabled = i > 0, tint = Immersive.Text,+ onClick = { Extensions.movePriority(area, e.id, -1) })+ ImmersiveRowIcon(Icons.Rounded.KeyboardArrowDown, stringResource(R.string.extensions_move_down), enabled = i < list.lastIndex, tint = Immersive.Text,+ onClick = { Extensions.movePriority(area, e.id, 1) })+ }+ }+ }+ }+ }+ item(key = "area-activity:$area") { AreaActivity(area, enable) }+}++/** Who did what in an area lately, each with a one-tap turn off while the extension is on. */+@Composable+private fun AreaActivity(area: Area, enable: (String, Boolean) -> Unit) {+ val activity by Extensions.activity.state.collectAsState()+ val recent = remember(activity, area) { activity.filter { it.area == area }.takeLast(3).asReversed() }+ if (recent.isEmpty()) return+ Column(Modifier.fillMaxWidth().padding(start = Immersive.Gutter + 16.dp, end = Immersive.Gutter - 8.dp, top = 8.dp)) {+ Text(stringResource(R.string.area_activity).uppercase(), style = Immersive.Caption)+ recent.forEach { a ->+ val on = Extensions.registry.value.find(a.extensionId)?.enabled == true+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {+ Text(a.text, style = Immersive.Caption, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))+ Text(+ android.text.format.DateUtils.getRelativeTimeSpanString(a.at, System.currentTimeMillis(), android.text.format.DateUtils.MINUTE_IN_MILLIS).toString(),+ style = Immersive.Caption.copy(color = Immersive.TextTertiary), modifier = Modifier.padding(horizontal = 6.dp),+ )+ if (on) TextButton(onClick = { enable(a.extensionId, false) }) {+ Text(stringResource(R.string.area_turn_off), style = Immersive.Caption.copy(color = Warning))+ }+ }+ }+ }+}++/** An installed row: icon (a dot when it failed), name, version, its state or description, its action icons, the switch; [extra] under it. */+@Composable+private fun InstalledRow(+ e: InstalledExtension, error: String?, status: app.myspoti.extensions.ExtensionStatus?, update: Boolean,+ enable: (String, Boolean) -> Unit, onOpen: () -> Unit, extra: @Composable () -> Unit = {},+) {+ val pkg = remember(e.id, e.sha256) { Extensions.pkg(e.id) }+ val m = pkg?.manifest+ val state = stateLine(e, error, status)+ var askUninstall by remember { mutableStateOf(false) }+ val scope = rememberCoroutineScope()+ ImmersiveExtRow(+ onClick = onOpen,+ leading = {+ Box {+ ExtIcon(e.id, e.name, null, pkg?.icon)+ if (state != null) Box(Modifier.align(Alignment.TopEnd)) { Dot(state.second) }+ }+ },+ trailing = {+ ImmersiveRowIcon(Icons.Rounded.DeleteOutline, stringResource(R.string.extension_uninstall), onClick = { askUninstall = true })+ ImmersiveSwitch(e.enabled) { enable(e.id, it) }+ },+ ) {+ Row(verticalAlignment = Alignment.CenterVertically) {+ Text(e.name, style = Immersive.BodyStrong.copy(color = if (e.enabled) Immersive.Text else Immersive.TextSecondary),+ maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))+ Spacer(Modifier.width(6.dp))+ VersionPill(e.version)+ if (update) {+ Spacer(Modifier.width(4.dp))+ ExtPill(stringResource(R.string.extensions_update_badge), Immersive.Accent, Immersive.Accent.copy(alpha = 0.18f))+ }+ }+ when {+ state != null -> Text(state.first, style = Immersive.Caption.copy(color = state.second), maxLines = 2, overflow = TextOverflow.Ellipsis)+ !e.enabled -> Text(stringResource(R.string.extension_off), style = Immersive.Caption)+ else -> Text(m?.description?.ifBlank { null } ?: authorLine(e.author, e.origin?.repo), style = Immersive.Caption, maxLines = 1, overflow = TextOverflow.Ellipsis)+ }+ m?.let { ActionIcons(it.asks().filter { a -> a.key in e.granted }) }+ extra()+ }+ if (askUninstall) AlertDialog(+ onDismissRequest = { askUninstall = false },+ containerColor = Immersive.Raised,+ text = { Text(stringResource(R.string.extension_uninstall_confirm, e.name), style = Immersive.Body) },+ confirmButton = {+ TextButton(onClick = {+ askUninstall = false+ scope.launch { Extensions.uninstall(e.id) }+ }) { Text(stringResource(R.string.extension_uninstall), style = Immersive.BodyStrong.copy(color = Immersive.Destructive)) }+ },+ dismissButton = {+ TextButton(onClick = { askUninstall = false }) {+ Text(stringResource(R.string.extensions_cancel), style = Immersive.BodyStrong.copy(color = Immersive.Accent))+ }+ },+ )+}diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveLibraryPages.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveLibraryPages.ktnew file mode 100644index 00000000..e95beba7--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveLibraryPages.kt@@ -0,0 +1,238 @@+package com.music.spotui.ui.immersive.pages++import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.lazy.itemsIndexed+import androidx.compose.foundation.lazy.rememberLazyListState+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.automirrored.rounded.PlaylistAdd+import androidx.compose.material.icons.rounded.DeleteOutline+import androidx.compose.material.icons.rounded.Edit+import androidx.compose.material.icons.rounded.MoreHoriz+import androidx.compose.material3.AlertDialog+import androidx.compose.material3.ExperimentalMaterial3Api+import androidx.compose.material3.Text+import androidx.compose.material3.TextButton+import androidx.compose.material3.pulltorefresh.PullToRefreshBox+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.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.pluralStringResource+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.api.LibraryEdits+import com.music.spotui.data.api.LibraryFolders+import com.music.spotui.data.api.Response+import com.music.spotui.data.api.SpotifySync+import com.music.spotui.data.entity.LibraryEntry+import com.music.spotui.data.local.LibraryOrder+import com.music.spotui.data.local.LocalPlaylists+import com.music.spotui.di.Graph+import com.music.spotui.di.LocalPlayer+import com.music.spotui.di.SongPlayer+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.ImmersivePlayShuffleButtons+import com.music.spotui.ui.immersive.screens.LibraryList+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.rememberTopBarCollapse+import com.music.spotui.ui.screens.LibraryItemSheet+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext++/**+ * A Spotify library folder in the Immersive look: the folder's name over its folders and+ * playlists, in the Library's rows (long press and drag to reorder, the ⋯ menu of every row), a+ * ⋯ in the bar for a new playlist, renaming and deleting the folder. The loading, the pending+ * edits and the actions are the Classic `FolderScreen`'s.+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun ImmersiveFolderScreen(navController: NavController, uri: String, initialName: String) {+ val context = LocalContext.current+ var name by remember { mutableStateOf(initialName) }+ // The folder as Spotify gave it; [entries] is that with the changes Spotify has not caught up with.+ var server by remember { mutableStateOf<List<LibraryEntry>?>(null) }+ val edits by LibraryEdits.version.collectAsState()+ val entries = remember(server, edits) { server?.let { LibraryEdits.applyTo(uri, it) } }+ var menu by remember { mutableStateOf(false) }+ var renaming by remember { mutableStateOf(false) }+ var newPlaylist by remember { mutableStateOf(false) }+ var deletingFolder by remember { mutableStateOf(false) }+ var itemMenu by remember { mutableStateOf<LibraryEntry?>(null) }+ var generation by remember { mutableStateOf(0) }+ var refreshing by remember { mutableStateOf(false) }+ LaunchedEffect(uri, generation) {+ withContext(Dispatchers.IO) {+ Graph.repository.provideLibraryFolder(uri).collect { r ->+ if (r is Response.Success) server = r.data else if (r is Response.Error && server == null) server = emptyList()+ }+ }+ refreshing = false+ }+ // A change just written: the folder is read again once Spotify's list has had time to catch up.+ LaunchedEffect(uri) { LibraryEdits.reloads.collect { generation++ } }++ if (menu) ImmersiveSheet(onDismiss = { menu = false }) {+ ImmersiveSheetRow(Icons.AutoMirrored.Rounded.PlaylistAdd, stringResource(R.string.add_to_playlist_new_playlist_button_text), onClick = { menu = false; newPlaylist = true })+ ImmersiveSheetRow(Icons.Rounded.Edit, stringResource(R.string.context_menu_rename_folder), onClick = { menu = false; renaming = true })+ ImmersiveSheetRow(Icons.Rounded.DeleteOutline, stringResource(R.string.folder_delete), destructive = true, onClick = { menu = false; deletingFolder = true })+ }+ itemMenu?.let { LibraryItemSheet(it, onDismiss = { itemMenu = null }, onChanged = { generation++ }) }+ if (deletingFolder) AlertDialog(+ onDismissRequest = { deletingFolder = false },+ containerColor = Immersive.Raised,+ text = { Text(stringResource(R.string.folder_delete_confirm, name), style = Immersive.Body) },+ confirmButton = {+ TextButton(onClick = {+ deletingFolder = false+ // The folder is gone from the library at once; a refusal brings it back.+ LibraryFolders.delete(context, uri)+ navController.navigateUp()+ }) { Text(stringResource(R.string.actions_picker_delete), style = Immersive.BodyStrong.copy(color = Immersive.Destructive)) }+ },+ dismissButton = {+ TextButton(onClick = { deletingFolder = false }) {+ Text(stringResource(R.string.cancel), style = Immersive.BodyStrong.copy(color = Immersive.Accent))+ }+ },+ )+ // A Spotify playlist created straight inside this folder.+ if (newPlaylist) ImmersiveNameDialog(+ stringResource(R.string.create_playlist_content_description), context.getString(R.string.my_playlist),+ stringResource(R.string.create_playlist_create_button), onDismiss = { newPlaylist = false },+ ) { playlistName ->+ newPlaylist = false+ SpotifySync.createPlaylistWithTrack(context, playlistName, "", folderUri = uri)+ }+ if (renaming) ImmersiveNameDialog(+ stringResource(R.string.context_menu_rename_folder), name, stringResource(R.string.local_rename),+ onDismiss = { renaming = false },+ ) { newName ->+ renaming = false+ val before = name+ name = newName+ LibraryFolders.rename(context, uri, newName) { ok -> if (!ok) name = before }+ }++ val listState = rememberLazyListState()+ val arranged = entries?.let { list ->+ LibraryOrder.version+ LibraryOrder.arrange(list, LibraryOrder.sort, LibraryOrder.custom(uri), 0)+ }.orEmpty()+ ImmersivePageFrame {+ PullToRefreshBox(+ isRefreshing = refreshing,+ onRefresh = { refreshing = true; generation++ },+ modifier = Modifier.fillMaxSize(),+ ) {+ LibraryList(+ listState = listState,+ header = {+ ImmersiveLargeTitle(+ title = name,+ subtitle = entries?.size?.let { pluralStringResource(R.plurals.add_to_playlist_folder_subtitle_playlists_count, it, it.toString()) },+ )+ },+ loading = entries == null,+ entries = arranged,+ artists = emptyList(),+ loadFailed = false,+ onRetry = { generation++ },+ navController = navController,+ reorderLevel = uri,+ pinned = 0,+ onMenu = { itemMenu = it },+ )+ }+ ImmersiveTopBar(title = name, collapse = rememberTopBarCollapse(listState), onBack = { navController.navigateUp() }) {+ ImmersiveBarAction(Icons.Rounded.MoreHoriz, stringResource(R.string.content_description_context_menu), onClick = { menu = true })+ }+ }+}++/**+ * A playlist kept on this phone, in the Immersive look: Play and Shuffle over the phone's files,+ * each row swiping away to leave the playlist, a ⋯ in the bar to rename or delete it. The data+ * and the player are the Classic `LocalPlaylistScreen`'s ([LocalPlaylists], [LocalPlayer]).+ */+@Composable+fun ImmersiveLocalPlaylistScreen(navController: NavController, id: String) {+ val playlist = LocalPlaylists.playlists[id]+ var menu by remember { mutableStateOf(false) }+ var renaming by remember { mutableStateOf(false) }+ if (playlist == null) {+ LaunchedEffect(Unit) { navController.navigateUp() }+ return+ }+ if (menu) ImmersiveSheet(onDismiss = { menu = false }) {+ ImmersiveSheetRow(Icons.Rounded.Edit, stringResource(R.string.local_rename), onClick = { menu = false; renaming = true })+ ImmersiveSheetRow(Icons.Rounded.DeleteOutline, stringResource(R.string.local_delete_playlist), destructive = true, onClick = {+ menu = false+ navController.navigateUp()+ LocalPlaylists.delete(id)+ })+ }+ if (renaming) ImmersiveNameDialog(+ stringResource(R.string.local_rename), playlist.name, stringResource(R.string.local_rename),+ onDismiss = { renaming = false },+ ) { renaming = false; LocalPlaylists.rename(id, it) }++ val np by SongPlayer.nowPlaying+ val playingHere = LocalPlayer.active.value && LocalPlayer.contextName == playlist.name+ val tracks = playlist.items.map { it.toTrack() }+ ImmersivePage(+ title = playlist.name,+ subtitle = stringResource(R.string.local_playlist_subtitle) + " • " ++ pluralStringResource(R.plurals.add_to_playlist_subtitle_songs_count, playlist.items.size, playlist.items.size.toString()),+ onBack = { navController.navigateUp() },+ actions = {+ ImmersiveBarAction(Icons.Rounded.MoreHoriz, stringResource(R.string.content_description_context_menu), onClick = { menu = true })+ },+ ) {+ if (playlist.items.isEmpty()) {+ item(key = "empty") { ImmersiveMessageState(stringResource(R.string.local_playlist_empty)) }+ return@ImmersivePage+ }+ item(key = "buttons") {+ ImmersivePlayShuffleButtons(+ onPlay = {+ when {+ playingHere && SongPlayer.isPlaying() -> SongPlayer.pause()+ playingHere -> SongPlayer.play()+ else -> LocalPlayer.play(tracks, 0, context = playlist.name)+ }+ },+ onShuffle = { LocalPlayer.play(tracks, tracks.indices.random(), shuffle = true, context = playlist.name) },+ modifier = Modifier.padding(bottom = 8.dp),+ )+ }+ itemsIndexed(playlist.items, key = { _, item -> item.key }) { index, item ->+ val current = LocalPlayer.active.value && np.uri == "local:${tracks[index].id}"+ Column(Modifier.animateItem()) {+ ImmersiveSwipeToRemove(item.key, onRemove = { LocalPlaylists.remove(id, item.key) }) {+ ImmersiveListRow(+ title = item.title,+ subtitle = item.artist.ifBlank { null },+ imageUrl = item.artUri,+ round = false,+ playing = current && SongPlayer.isPlaying(),+ onClick = { LocalPlayer.play(tracks, index, context = playlist.name) },+ )+ }+ }+ }+ }+}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.ktindex def31d06..07055df2 100644--- a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersivePage.kt+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersivePage.kt@@ -185,7 +185,7 @@ internal fun ImmersiveGroupRow(onClick: (() -> Unit)? = null,trailing: (@Composable () -> Unit)? = null,) {- val tint = if (destructive) ImmersiveDestructive else Immersive.Text+ val tint = if (destructive) Immersive.Destructive else Immersive.TextRow(verticalAlignment = Alignment.CenterVertically,modifier = modifierdiff --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.ktindex 78bd3e47..bfe247d7 100644--- 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.kt@@ -75,13 +75,11 @@ import com.music.spotui.di.Hapticsimport com.music.spotui.ui.immersive.Immersiveimport com.music.spotui.ui.immersive.components.immersiveClickableimport com.music.spotui.ui.immersive.components.rememberImmersiveOverscrollFactory+import com.music.spotui.ui.immersive.motion.ImmersiveMotionimport com.music.spotui.ui.look.rememberReduceMotionimport kotlinx.coroutines.launchimport 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.@@ -109,12 +107,12 @@ internal fun ImmersiveSegmentedControl(val chosen = index == selectedIndexval pill by animateColorAsState(targetValue = if (chosen) Immersive.Accent else Color.Transparent,- animationSpec = if (reduceMotion) snap() else tween(160),+ animationSpec = if (reduceMotion) snap() else tween(ImmersiveMotion.FADE_MS),label = "segment pill",)val labelColor by animateColorAsState(targetValue = if (chosen) Color.White else Immersive.TextSecondary,- animationSpec = if (reduceMotion) snap() else tween(160),+ animationSpec = if (reduceMotion) snap() else tween(ImmersiveMotion.FADE_MS),label = "segment label",)Box(@@ -162,7 +160,7 @@ internal fun ImmersiveSwipeToRemove(key: Any, onRemove: () -> Unit, content: @CocontentAlignment = Alignment.CenterEnd,modifier = Modifier.matchParentSize()- .background(if (armed) ImmersiveDestructive else ImmersiveDestructive.copy(alpha = 0.6f)),+ .background(if (armed) Immersive.Destructive else Immersive.Destructive.copy(alpha = 0.6f)),) {Icon(Icons.Rounded.DeleteOutline,@@ -275,7 +273,7 @@ internal fun ImmersiveSheetRow(detail: String? = null,destructive: Boolean = false,) {- val tint = if (destructive) ImmersiveDestructive else Immersive.Text+ val tint = if (destructive) Immersive.Destructive else Immersive.TextRow(verticalAlignment = Alignment.CenterVertically,modifier = Modifierdiff --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.ktindex 84568aae..9f40c9eb 100644--- a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveRecentlyPlayedScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveRecentlyPlayedScreen.kt@@ -36,6 +36,8 @@ import androidx.compose.runtime.derivedStateOfimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.remember+import androidx.compose.runtime.saveable.listSaver+import androidx.compose.runtime.saveable.rememberSaveableimport androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifier@@ -114,8 +116,11 @@ fun ImmersiveRecentlyPlayedScreen(navController: NavController) {// 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>()) }+ // The pill and the unfolded contexts survive a recreation; the loaded entries load again.+ var podcasts by rememberSaveable { mutableStateOf(false) }+ var expanded by rememberSaveable(+ stateSaver = listSaver(save = { it.toList() }, restore = { it.toSet() }),+ ) { mutableStateOf(emptySet<String>()) }var generation by remember { mutableStateOf(0) }val listState = rememberLazyListState()val reduceMotion = rememberReduceMotion()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.ktindex 6b671935..e020bf12 100644--- a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt@@ -38,8 +38,10 @@ import androidx.compose.runtime.mutableStateListOfimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.saveable.listSaverimport androidx.compose.runtime.saveable.rememberSaveableimport androidx.compose.runtime.setValue+import androidx.compose.runtime.toMutableStateListimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clipimport androidx.compose.ui.platform.LocalContext@@ -95,7 +97,13 @@ private val DownloadChoices = listOf(@Composablefun ImmersiveSettingsScreen(navController: NavController) {// The pages pushed so far, so back pops one before it leaves Settings.- val stack = remember { mutableStateListOf<SettingsPage>() }+ // Saved by name, so a recreation (a language change, say) keeps the page the user is on.+ val stack = rememberSaveable(+ saver = listSaver(+ save = { list -> list.map { it.name } },+ restore = { names -> names.map { SettingsPage.valueOf(it) }.toMutableStateList() },+ ),+ ) { mutableStateListOf<SettingsPage>() }val page = stack.lastOrNull() ?: SettingsPage.Rootval reduce = rememberReduceMotion()var pushing by remember { mutableStateOf(true) }@@ -199,7 +207,6 @@ private fun PlaybackPage(navController: NavController, open: (SettingsPage) -> Uval 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 headsetSkip by remember { mutableStateOf(app.myspoti.host.android.PlaybackService.skipsOnEpisodes(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)) }@@ -239,16 +246,18 @@ private fun PlaybackPage(navController: NavController, open: (SettingsPage) -> Udetail = stringResource(R.string.settings_headset_skip_detail),)}- }- sourcesGroup(app.myspoti.extensions.Action.AUDIO_SOURCE, navController)- immersiveGroup("visuals") {- row {+ // Songs an extension streams, played by Spotify too (unheard): counted there, seen by Connect.+ if (com.music.spotui.extensions.Extensions.sources(app.myspoti.extensions.Action.AUDIO_SOURCE).isNotEmpty()) 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),+ stringResource(R.string.settings_connect_mirror_title),+ checked = com.music.spotui.data.preferences.ConnectMirrorPref.on,+ onChecked = { com.music.spotui.data.preferences.ConnectMirrorPref.set(ctx, it) },+ detail = stringResource(R.string.settings_connect_mirror_detail),)}+ }+ sourcesGroup(app.myspoti.extensions.Action.AUDIO_SOURCE, navController)+ immersiveGroup("visuals") {// Lyrics: word by word (karaoke) first, or line by line with Spotify's first.row {ImmersiveSwitchRow(@@ -349,7 +358,7 @@ private fun DownloadsPage(navController: NavController, open: (SettingsPage) ->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)+ Text(stringResource(R.string.playlist_entity_remove_download_dialog_positive_button), color = Immersive.Destructive)}},dismissButton = {@@ -428,7 +437,7 @@ private fun DisplayPage(open: (SettingsPage) -> Unit, back: () -> Unit) {chevron = true, onClick = { open(SettingsPage.Look) },)}- row { AccentRow() }+ row { AccentRow(com.music.spotui.data.preferences.Look.IMMERSIVE) }}immersiveGroup("display") {if (look == com.music.spotui.data.preferences.Look.IMMERSIVE) row {@@ -452,23 +461,10 @@ private fun DisplayPage(open: (SettingsPage) -> Unit, back: () -> Unit) {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 {@@ -494,15 +490,15 @@ private fun rotationLabel(mode: String): Int = when (mode) {else -> R.string.settings_rotation_portrait}-/** The app's accent colour, for everyone (the same palette the supporter sheet uses). */+/** The accent colour of one look, for everyone (the same palette the supporter sheet uses). */@Composable-private fun AccentRow() {+private fun AccentRow(look: com.music.spotui.data.preferences.Look) {val ctx = LocalContext.currentandroidx.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 selected = com.music.spotui.data.api.SupportReminder.accentOf(look) == aval name = stringResource(when (a) {com.music.spotui.data.api.SupportReminder.Accent.GREEN -> R.string.color_greencom.music.spotui.data.api.SupportReminder.Accent.BLUE -> R.string.color_blue@@ -515,7 +511,7 @@ private fun AccentRow() {.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) },+ .clickable { com.music.spotui.data.api.SupportReminder.setAccent(ctx, look, a) },)}}@@ -612,7 +608,7 @@ private fun AppPage(navController: NavController, back: () -> Unit) {ImmersiveGroupRow(stringResource(R.string.settings_about_version, app.myspoti.engine.BuildConfig.VERSION_NAME),detail = detail,- detailColor = if (check.isError) ImmersiveDestructive else Immersive.TextSecondary,+ detailColor = if (check.isError) Immersive.Destructive else Immersive.TextSecondary,onClick = if (known != null) ({ com.music.spotui.updateRelease.value = known }) else null,trailing = {if (check.checking) androidx.compose.material3.CircularProgressIndicator(Modifier.size(22.dp), strokeWidth = 2.dp, color = Immersive.Accent)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.ktindex b6d678a8..7dec203c 100644--- a/base/app/src/main/java/com/music/spotui/ui/immersive/player/ImmersivePlayer.kt+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/player/ImmersivePlayer.kt@@ -364,7 +364,7 @@ fun ImmersivePlayer(contentAlignment = Alignment.Center,) {Text(- text = "E",+ text = stringResource(R.string.explicit_badge),style = Immersive.Caption.copy(fontSize = 10.sp, lineHeight = 10.sp, fontWeight = FontWeight.Bold),color = Color.Black,)@@ -439,7 +439,8 @@ fun ImmersivePlayer(PlayerActionRow(lyricsOpen = lyricsOpen,queueOpen = queueOpen,- shuffleEnabled = state.shuffle,+ shuffleEnabled = state.shuffle || state.smart,+ smartEnabled = state.smart,repeatMode = state.repeatMode,deviceActive = state.deviceName != null,// Lyrics and the queue are two things to show in one place: opening one closes the other.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.ktindex 82f0c437..1e4a1809 100644--- a/base/app/src/main/java/com/music/spotui/ui/immersive/player/ImmersivePlayerOverlay.kt+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/player/ImmersivePlayerOverlay.kt@@ -37,7 +37,6 @@ import androidx.navigation.NavControllerimport com.music.spotui.di.SongPlayerimport com.music.spotui.ui.navigation.LocalPageSettledimport com.music.spotui.ui.navigation.PlayerSheet-import com.music.spotui.ui.screens.PodcastPlayerScreenimport kotlinx.coroutines.flow.dropimport kotlinx.coroutines.flow.firstimport kotlinx.coroutines.launch@@ -59,7 +58,7 @@ private fun slideSpec(reduce: Boolean) = com.music.spotui.ui.immersive.motion.Im* 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.+ * A podcast episode gets [ImmersivePodcastPlayer].*/@Composablefun ImmersivePlayerOverlay(navController: NavController) {@@ -162,9 +161,9 @@ fun ImmersivePlayerOverlay(navController: NavController) {.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.+ // A podcast episode gets the podcast player (15 s skips, speed); everything else the music one.if (SongPlayer.isEpisode) {- PodcastPlayerScreen(navController)+ ImmersivePodcastPlayer(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/ImmersivePodcastPlayer.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/player/ImmersivePodcastPlayer.ktnew file mode 100644index 00000000..fecfe085--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/player/ImmersivePodcastPlayer.kt@@ -0,0 +1,470 @@+package com.music.spotui.ui.immersive.player++import androidx.compose.animation.animateColorAsState+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.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.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.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.automirrored.rounded.QueueMusic+import androidx.compose.material.icons.rounded.Devices+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.RotateLeft+import androidx.compose.material.icons.rounded.RotateRight+import androidx.compose.material.icons.rounded.Star+import androidx.compose.material.icons.rounded.StarBorder+import androidx.compose.material.icons.rounded.Timer+import androidx.compose.material3.CircularProgressIndicator+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.CompositionLocalProvider+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.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.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.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.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.data.entity.SongsModel+import com.music.spotui.di.Graph+import com.music.spotui.di.Haptics+import com.music.spotui.di.SongPlayer+import com.music.spotui.ui.components.DevicesSheet+import com.music.spotui.ui.components.EpisodeOptionsSheet+import com.music.spotui.ui.components.PodcastSpeedSheet+import com.music.spotui.ui.components.QualitySheet+import com.music.spotui.ui.components.QueueSheet+import com.music.spotui.ui.components.SleepTimerSheet+import com.music.spotui.ui.components.playingSourceLabel+import com.music.spotui.ui.components.speedLabel+import com.music.spotui.ui.immersive.Immersive+import com.music.spotui.ui.look.MeshGradientBackground+import com.music.spotui.ui.look.rememberArtworkColors+import com.music.spotui.ui.look.rememberPauseScale+import com.music.spotui.ui.look.rememberReduceMotion+import com.music.spotui.ui.navigation.PlayerSheet+import com.music.spotui.ui.navigation.episodeRoute+import com.music.spotui.ui.navigation.showRoute+import com.music.spotui.ui.screens.episodeShowId+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext++/** The height of the line holding the title, the show and the round glyphs. */+private val TITLE_HEIGHT = 60.dp+private val ART_TITLE_GAP = 20.dp+private val ART_TOP_PAD = 8.dp+private val DISMISS_STRIP_HEIGHT = 32.dp+private val ArtCorner = RoundedCornerShape(8.dp)++/** The cover is always decoded at the size of the largest cover, whatever the box measures. */+private const val COVER_DECODE_PX = 640++/** A podcast skip, in milliseconds. */+private const val SKIP_MS = 15_000L++/**+ * The player of a podcast episode in the Immersive look, in the music player's frame: the+ * cover's colours drifting behind a large cover, the episode and its show, the scrubber, then+ * the podcast transport (15 s back, play/pause, 15 s forward) and a row of speed, sleep timer,+ * devices and queue. The state and every action are the Classic `PodcastPlayerScreen`'s: the+ * same playback, saved state, sheets and links to the show and the episode.+ */+@OptIn(ExperimentalGlideComposeApi::class, ExperimentalFoundationApi::class)+@Composable+fun ImmersivePodcastPlayer(navController: NavController) {+ val bridge = rememberImmersivePlayer(navController)+ val state = bridge.state+ val actions = bridge.actions+ val np by SongPlayer.nowPlaying+ val title = state.title+ val showName = state.artist.ifBlank { np.contextName }+ val cover = Graph.currentSongState.coverUri.value+ val episodeId = np.uri.removePrefix("spotify:episode:")+ val uri = "spotify:episode:$episodeId"+ val saved = SongPlayer.library[uri] == true+ LaunchedEffect(uri) { SongPlayer.requestSaved(uri) }++ var showSpeed by remember { mutableStateOf(false) }+ var showSleep by remember { mutableStateOf(false) }+ var showDevices by remember { mutableStateOf(false) }+ var showQueue by remember { mutableStateOf(false) }+ var showMenu by remember { mutableStateOf(false) }+ var showQuality by remember { mutableStateOf(false) }+ val scope = rememberCoroutineScope()++ val palette = rememberArtworkColors(state.coverUrl.takeIf { it.isNotBlank() })+ val tint by animateColorAsState(playerTintOf(palette), tween(com.music.spotui.ui.immersive.motion.ImmersiveMotion.TINT_MS), label = "podcastTint")+ val reduce = rememberReduceMotion()+ val pauseScale = rememberPauseScale(state.playing)++ fun openShow() {+ val showId = episodeShowId(np.contextUri)+ if (showId.isNotBlank()) navController.navigate(showRoute(showId, showName))+ }++ 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)))+ }++ // Where the episode plays from: a tap opens the show.+ Column(+ horizontalAlignment = Alignment.CenterHorizontally,+ modifier = Modifier+ .fillMaxWidth()+ .padding(horizontal = PLAYER_GUTTER)+ .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) { openShow() },+ ) {+ Text(+ stringResource(R.string.podcast_playing_from),+ style = Immersive.Caption,+ color = tint.copy(alpha = 0.55f),+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )+ Text(+ showName,+ style = Immersive.BodyStrong.copy(fontSize = 14.sp, lineHeight = 18.sp),+ textAlign = TextAlign.Center,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )+ }++ BoxWithConstraints(Modifier.weight(1f).fillMaxWidth()) {+ val contentWidth = minOf(maxWidth - PLAYER_GUTTER * 2, PLAYER_MAX_WIDTH)+ val art = minOf(contentWidth, maxHeight - ART_TOP_PAD - ART_TITLE_GAP - TITLE_HEIGHT - 16.dp).coerceAtLeast(96.dp)+ Column(+ modifier = Modifier.fillMaxSize().padding(top = ART_TOP_PAD),+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.Center,+ ) {+ Box(+ Modifier+ .size(art)+ .graphicsLayer {+ // The pause step back, as on the music player.+ val scale = if (reduce) 1f else pauseScale.value+ scaleX = scale+ scaleY = scale+ shadowElevation = 10.dp.toPx()+ shape = ArtCorner+ clip = true+ }+ .background(Color.Black.copy(alpha = 0.18f))+ .dragToClose(),+ ) {+ 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(),+ requestBuilderTransform = { it.override(COVER_DECODE_PX) },+ )+ }+ Spacer(Modifier.height(ART_TITLE_GAP))+ // The episode and its show, the star of the saved episodes and the episode's menu.+ Row(+ modifier = Modifier.width(contentWidth).height(TITLE_HEIGHT).dragToClose(),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ val sourceLabel = playingSourceLabel()+ Column(Modifier.weight(1f)) {+ Text(+ text = title,+ style = Immersive.Title.copy(fontSize = 20.sp, lineHeight = if (sourceLabel.isNotBlank()) 22.sp else 24.sp),+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ modifier = Modifier+ .then(if (reduce) Modifier else Modifier.basicMarquee(iterations = Int.MAX_VALUE))+ .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {+ navController.navigate(episodeRoute(episodeId, title))+ },+ )+ Text(+ text = showName,+ style = Immersive.Title.copy(+ fontSize = 20.sp,+ lineHeight = if (sourceLabel.isNotBlank()) 22.sp else 24.sp,+ fontWeight = FontWeight.W500,+ ),+ color = tint.copy(alpha = 0.55f),+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ modifier = Modifier+ .then(if (reduce) Modifier else Modifier.basicMarquee(iterations = Int.MAX_VALUE))+ .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) { openShow() },+ )+ // What the sound is when Myspoti's own player plays it; a tap opens its quality.+ if (sourceLabel.isNotBlank()) Text(+ text = sourceLabel,+ style = Immersive.Caption.copy(lineHeight = 14.sp),+ color = tint.copy(alpha = 0.45f),+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ modifier = Modifier.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) { showQuality = true },+ )+ }+ Spacer(Modifier.width(10.dp))+ CircleGlyph(+ icon = if (saved) Icons.Rounded.Star else Icons.Rounded.StarBorder,+ contentDescription = stringResource(if (saved) R.string.immersive_player_unlike else R.string.immersive_player_like),+ onClick = { SongPlayer.setSaved(uri, !saved) },+ active = saved,+ )+ Spacer(Modifier.width(8.dp))+ CircleGlyph(+ icon = Icons.Rounded.MoreHoriz,+ contentDescription = stringResource(R.string.episode_options),+ onClick = { showMenu = true },+ )+ }+ }+ }++ // ---- Bottom: scrubber, podcast transport, speed / sleep / devices / queue ----+ 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))+ PodcastTransportRow(+ isPlaying = state.playing,+ isLoading = state.buffering,+ onBack = { SongPlayer.skipBy(-SKIP_MS) },+ onPlayPause = actions.playPause,+ onForward = { SongPlayer.skipBy(SKIP_MS) },+ )+ Spacer(Modifier.height(12.dp))+ Row(+ modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically,+ ) {+ SpeedChip(label = stringResource(R.string.player_speed_chip, speedLabel(SongPlayer.speed.value)), onClick = { showSpeed = true })+ BottomGlyph(+ icon = Icons.Rounded.Timer,+ contentDescription = stringResource(R.string.player_sleep_timer),+ onClick = { showSleep = true },+ highlighted = SongPlayer.sleepEndsAt.value != null,+ )+ BottomGlyph(+ icon = Icons.Rounded.Devices,+ contentDescription = stringResource(R.string.immersive_player_devices),+ onClick = { showDevices = true },+ highlighted = state.deviceName != null,+ )+ BottomGlyph(+ icon = Icons.AutoMirrored.Rounded.QueueMusic,+ contentDescription = stringResource(R.string.immersive_player_queue),+ onClick = { showQueue = true },+ )+ }+ Spacer(Modifier.height(18.dp))+ }+ }+ }+ }++ if (showSpeed) PodcastSpeedSheet { showSpeed = false }+ if (showSleep) SleepTimerSheet { showSleep = false }+ if (showDevices) DevicesSheet { showDevices = false }+ if (showQueue) QueueSheet(contextName = showName) { showQueue = false }+ if (showQuality) QualitySheet { showQuality = false }+ if (showMenu) {+ val song = SongsModel(+ id = ("uri:$uri").hashCode() and 0x7fffffff,+ title = title,+ album = showName,+ singer = showName,+ coverUri = cover,+ url = "episode:$episodeId",+ durationMs = state.durationMs.toInt(),+ )+ EpisodeOptionsSheet(+ song = song,+ finished = false,+ onPlay = { SongPlayer.play() },+ onMarkFinished = { played ->+ scope.launch {+ withContext(Dispatchers.IO) { runCatching { Graph.api.setEpisodePlayed(uri, played) } }+ }+ },+ onOpen = { navController.navigate(episodeRoute(episodeId, title)) },+ onDismiss = { showMenu = false },+ )+ }+}++/** 15 s back, play/pause, 15 s forward: bare glyphs, no backgrounds, as the music player's transport. */+@Composable+private fun PodcastTransportRow(+ isPlaying: Boolean,+ isLoading: Boolean,+ onBack: () -> Unit,+ onPlayPause: () -> Unit,+ onForward: () -> Unit,+) {+ val playTouch = 92.dp+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceAround,+ verticalAlignment = Alignment.CenterVertically,+ ) {+ SkipButton(back = true, onClick = onBack)+ 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 {+ TransportButton(+ 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 = 88.dp,+ touchSize = playTouch,+ onClick = onPlayPause,+ )+ }+ SkipButton(back = false, onClick = onForward)+ }+}++/** The circular arrow with the number inside, as the official player draws a 15 s skip. */+@Composable+private fun SkipButton(back: Boolean, onClick: () -> Unit) {+ Box(contentAlignment = Alignment.Center) {+ TransportButton(+ icon = if (back) Icons.Rounded.RotateLeft else Icons.Rounded.RotateRight,+ contentDescription = stringResource(if (back) R.string.player_back_15 else R.string.player_forward_15),+ size = 56.dp,+ touchSize = 72.dp,+ onClick = onClick,+ )+ Text(+ text = "15",+ style = Immersive.Caption.copy(fontSize = 12.sp, lineHeight = 12.sp, fontWeight = FontWeight.Bold),+ color = Color.White,+ textAlign = TextAlign.Center,+ )+ }+}++/** A transport glyph: the touch target takes the press, the icon is never clipped. */+@Composable+private fun TransportButton(icon: ImageVector, contentDescription: String, size: androidx.compose.ui.unit.Dp, touchSize: androidx.compose.ui.unit.Dp, onClick: () -> Unit) {+ Box(+ modifier = Modifier+ .size(touchSize)+ .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {+ Haptics.click()+ onClick()+ },+ contentAlignment = Alignment.Center,+ ) {+ Icon(icon, contentDescription = contentDescription, tint = Color.White, modifier = Modifier.size(size))+ }+}++/** The speed, in a capsule: a tap opens the speeds. */+@Composable+private fun SpeedChip(label: String, onClick: () -> Unit) {+ Box(+ contentAlignment = Alignment.Center,+ modifier = Modifier+ .height(BOTTOM_GLYPH_SIZE)+ .clip(CircleShape)+ .background(LocalPlayerTint.current.copy(alpha = 0.12f))+ .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {+ Haptics.click()+ onClick()+ }+ .padding(horizontal = 16.dp),+ ) {+ Text(label, style = Immersive.Subhead.copy(fontWeight = FontWeight.Bold), color = LocalPlayerTint.current, maxLines = 1)+ }+}++private val BOTTOM_GLYPH_SIZE = 44.dp++/** One of the bottom row's round glyphs; lit while what it controls is on (a sleep timer, another device). */+@Composable+private fun BottomGlyph(icon: ImageVector, contentDescription: String, onClick: () -> Unit, highlighted: Boolean = false) {+ Box(+ modifier = Modifier+ .size(BOTTOM_GLYPH_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),+ )+ }+}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.ktindex 81e220aa..902fc716 100644--- 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.kt@@ -18,6 +18,7 @@ import androidx.compose.runtime.Stableimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableLongStateOfimport androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.runtime.setValueimport androidx.compose.ui.platform.LocalContextimport androidx.lifecycle.viewmodel.compose.viewModel@@ -27,9 +28,11 @@ import com.music.spotui.data.entity.SongsModelimport com.music.spotui.di.SongPlayerimport com.music.spotui.ui.navigation.PlayerSheetimport com.music.spotui.ui.navigation.albumRoute+import com.music.spotui.ui.screens.SmartShuffleimport com.music.spotui.ui.screens.nowPlayingSongimport com.music.spotui.ui.viewmodel.PlayerViewModelimport kotlinx.coroutines.delay+import kotlinx.coroutines.launch/** Repeat modes, as [SongPlayer.repeatMode] reports them. */object ImmersiveRepeat {@@ -54,6 +57,8 @@ data class ImmersivePlayerState(val positionMs: () -> Long = { 0L },val durationMs: Long = 0L,val shuffle: Boolean = false,+ /** Smart shuffle is on for the list that plays. */+ val smart: Boolean = false,/** [ImmersiveRepeat]. */val repeatMode: Int = ImmersiveRepeat.OFF,val liked: Boolean = false,@@ -108,6 +113,8 @@ fun rememberImmersivePlayer(navController: NavController): ImmersivePlayerBridgeval songId = vm.currentSongId.valueval liked = vm.likeState.valueval shuffle = vm.shuffleState.value+ val smart = SmartShuffle.on.value != null && SmartShuffle.on.value == np.contextUri+ val smartScope = rememberCoroutineScope()val repeat = SongPlayer.repeatMode.valueval buffering = SongPlayer.isBufferingval adPlaying = SongPlayer.adPlaying@@ -135,6 +142,7 @@ fun rememberImmersivePlayer(navController: NavController): ImmersivePlayerBridgepositionMs = remember { { SongPlayer.getCurrentPosition() } },durationMs = duration,shuffle = shuffle,+ smart = smart,repeatMode = repeat,liked = liked,isEpisode = episode,@@ -165,7 +173,24 @@ fun rememberImmersivePlayer(navController: NavController): ImmersivePlayerBridgenext = { SongPlayer.swipeNext() },previous = { SongPlayer.previous() },seekTo = { SongPlayer.seekTo(it) },- toggleShuffle = { vm.updateShuffleState(!vm.shuffleState.value) },+ // As in the Classic player: off → shuffle → smart shuffle (playlists, Liked Songs) → off.+ toggleShuffle = {+ val ctx = SongPlayer.nowPlaying.value.contextUri+ when {+ SmartShuffle.on.value != null && SmartShuffle.on.value == ctx -> { SmartShuffle.on.value = null; vm.updateShuffleState(false) }+ vm.shuffleState.value && SmartShuffle.canPlay(ctx) -> {+ SmartShuffle.on.value = ctx+ Toast.makeText(context, context.getString(R.string.smart_shuffle_on), Toast.LENGTH_SHORT).show()+ smartScope.launch {+ if (!SmartShuffle.startFor(ctx, SongPlayer.currentTrackId)) {+ SmartShuffle.on.value = null+ Toast.makeText(context, context.getString(R.string.page_load_failed), Toast.LENGTH_SHORT).show()+ }+ }+ }+ else -> vm.updateShuffleState(!vm.shuffleState.value)+ }+ },cycleRepeat = { SongPlayer.cycleRepeat() },toggleLike = {val on = !vm.likeState.valuediff --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.ktindex 078753a0..ad8c3ecf 100644--- a/base/app/src/main/java/com/music/spotui/ui/immersive/player/PlayerControls.kt+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/player/PlayerControls.kt@@ -46,6 +46,7 @@ import androidx.compose.material.icons.Iconsimport androidx.compose.material.icons.automirrored.rounded.QueueMusicimport androidx.compose.material.icons.automirrored.rounded.VolumeDownimport androidx.compose.material.icons.automirrored.rounded.VolumeUp+import androidx.compose.material.icons.rounded.AutoAwesomeimport androidx.compose.material.icons.rounded.Devicesimport androidx.compose.material.icons.rounded.Lyricsimport androidx.compose.material.icons.rounded.Pause@@ -59,6 +60,7 @@ import androidx.compose.material3.CircularProgressIndicatorimport androidx.compose.material3.Iconimport androidx.compose.material3.Textimport androidx.compose.runtime.Composable+import androidx.compose.runtime.Stateimport androidx.compose.runtime.compositionLocalOfimport androidx.compose.runtime.getValueimport androidx.compose.runtime.remember@@ -119,8 +121,9 @@ internal fun formatTime(ms: Long): String {}/**- * 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.+ * The seek bar, with elapsed and remaining either side under it. The playhead is read per tick,+ * in the bar's draw and in the two times, so a tick redraws the bar and recomposes only the times,+ * not the player the bar sits in.*/@Composableinternal fun PlayerScrubber(@@ -130,35 +133,41 @@ internal fun PlayerScrubber(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,+ value = { frame.value; scrub.shown(state.positionMs(), state.durationMs) },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),- )- }+ ScrubTimes(frame, scrub, state)+ }+}++/** The elapsed and remaining times under the seek bar, read per tick of [frame]. */+@Composable+private fun ScrubTimes(frame: State<Long>, scrub: PlayerScrub, state: ImmersivePlayerState) {+ frame.value+ val shown = scrub.shown(state.positionMs(), state.durationMs)+ 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),+ )}}@@ -458,6 +467,7 @@ internal fun PlayerActionRow(lyricsOpen: Boolean,queueOpen: Boolean,shuffleEnabled: Boolean,+ smartEnabled: Boolean,repeatMode: Int,deviceActive: Boolean,onToggleLyrics: () -> Unit,@@ -519,9 +529,13 @@ internal fun PlayerActionRow(if (showQueueModes) {Pill {PillSegment(- icon = Icons.Rounded.Shuffle,+ icon = if (smartEnabled) Icons.Rounded.AutoAwesome else Icons.Rounded.Shuffle,contentDescription = stringResource(- if (shuffleEnabled) R.string.immersive_player_shuffle_on else R.string.immersive_player_shuffle_off,+ when {+ smartEnabled -> R.string.smart_shuffle_title+ shuffleEnabled -> R.string.immersive_player_shuffle_on+ else -> R.string.immersive_player_shuffle_off+ },),onClick = onToggleShuffle,highlighted = shuffleEnabled,diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveAlbumByIdScreen.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveAlbumByIdScreen.ktnew file mode 100644index 00000000..29acb813--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveAlbumByIdScreen.kt@@ -0,0 +1,56 @@+package com.music.spotui.ui.immersive.screens++import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxWithConstraints+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+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.engine.R+import com.music.spotui.di.Graph+import com.music.spotui.ui.immersive.Immersive+import com.music.spotui.ui.immersive.components.ImmersiveMessageState+import com.music.spotui.ui.immersive.shell.ImmersiveTopBar+import com.music.spotui.ui.immersive.shell.immersiveTopContentPadding++/**+ * Opens the album page by Spotify id in the Immersive look, resolving it from the name only when+ * needed (the Classic `AlbumByIdScreen`'s look-up). The page itself is [ImmersiveContextScreen].+ */+@Composable+fun ImmersiveAlbumByIdScreen(navController: NavController, name: String, artist: String, id: String) {+ var resolved by remember(name, artist, id) { mutableStateOf(id.ifBlank { null }) }+ var failed by remember { mutableStateOf(false) }+ // Bumped by Try again: the look-up runs once more.+ var attempt by remember { mutableStateOf(0) }+ LaunchedEffect(name, artist, id, attempt) {+ if (resolved == null) {+ resolved = Graph.api.resolveAlbumId(name, artist)+ if (resolved == null) failed = true+ }+ }+ val albumId = resolved+ when {+ albumId != null -> ImmersiveContextScreen(navController, type = "album", id = albumId)+ failed -> Box(Modifier.fillMaxSize().background(Immersive.Page)) {+ ImmersiveMessageState(+ message = stringResource(R.string.album_not_found),+ actionLabel = stringResource(R.string.retry_button),+ onAction = { failed = false; attempt++ },+ modifier = Modifier.padding(top = immersiveTopContentPadding()),+ )+ ImmersiveTopBar(title = "", collapse = { 0f }, onBack = { navController.navigateUp() })+ }+ else -> BoxWithConstraints(Modifier.fillMaxSize().background(Immersive.Page)) {+ ContextLoading(navController, sleeve = albumSleeve(maxWidth, maxHeight))+ }+ }+}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.ktindex 6d7174b7..8189a9ec 100644--- 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.kt@@ -23,6 +23,7 @@ import androidx.compose.runtime.collectAsStateimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.remember+import androidx.compose.runtime.saveable.rememberSaveableimport androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifier@@ -68,7 +69,7 @@ fun ImmersiveArtistReleasesScreen(navController: NavController, artistName: Strival 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"+ var filter by rememberSaveable { mutableStateOf("") } // "" | "albums" | "singles" | "featured"val listState = rememberLazyListState()val releasesTitle = stringResource(R.string.releases_title)diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveContextScreen.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveContextScreen.ktindex f4461cad..dcf15daa 100644--- a/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveContextScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveContextScreen.kt@@ -67,6 +67,7 @@ import androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.produceStateimport androidx.compose.runtime.rememberimport androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.saveable.rememberSaveableimport androidx.compose.runtime.setValueimport androidx.compose.runtime.collectAsStateimport androidx.compose.ui.Alignment@@ -169,7 +170,7 @@ fun ImmersiveContextScreen(navController: NavController, type: String, id: Strinremember(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)+ val sleeve = albumSleeve(maxWidth, maxHeight)when (val r = resp) {is Response.Loading -> ContextLoading(navController, sleeve)is Response.Error -> {@@ -188,9 +189,12 @@ fun ImmersiveContextScreen(navController: NavController, type: String, id: Strin}}+/** The sleeve's side on a page of this size. */+internal fun albumSleeve(maxWidth: Dp, maxHeight: Dp): Dp = (maxWidth * SLEEVE_FRACTION).coerceAtMost(maxHeight * SLEEVE_MAX_HEIGHT)+/** Nothing is known of the page yet: the sleeve and the track list stand as shimmer. */@Composable-private fun ContextLoading(navController: NavController, sleeve: Dp) {+internal fun ContextLoading(navController: NavController, sleeve: Dp) {val listState = rememberLazyListState()Box(Modifier.fillMaxSize()) {LazyColumn(@@ -237,8 +241,8 @@ private fun ImmersiveContextContent(navController: NavController, vm: ContextVievar 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) }+ var find by rememberSaveable { mutableStateOf("") }+ var finding by rememberSaveable { 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) }@@ -277,7 +281,7 @@ private fun ImmersiveContextContent(navController: NavController, vm: ContextViewrite = { 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)) }+ }) { Text(stringResource(R.string.playlist_leave_button), color = Immersive.Destructive) }},dismissButton = {androidx.compose.material3.TextButton(onClick = { leaveAsk = false }) { Text(stringResource(R.string.cancel), color = Immersive.Text) }@@ -393,14 +397,6 @@ private fun ImmersiveContextContent(navController: NavController, vm: ContextViep.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@@ -411,6 +407,21 @@ private fun ImmersiveContextContent(navController: NavController, vm: ContextVieif (isThisContext) vm.playSmart(p, p.tracks.firstOrNull { it.id == currentSongId })}}+ // What the Shuffle pill does: start the list shuffled, or, while it plays, step through+ // shuffle → smart shuffle (playlists, Liked Songs) → off, as the Classic shuffle icon does.+ fun onShuffle() {+ if (p.tracks.isEmpty()) return+ when {+ !isThisContext && smart -> vm.playSmart(p, null)+ !isThisContext -> {+ playerVm.updateShuffleState(true)+ vm.play(p, p.tracks.random(), sort)+ }+ smart -> { SmartShuffle.on.value = null; playerVm.updateShuffleState(false) }+ shuffle && SmartShuffle.canPlay(p.uri) -> toggleSmart()+ else -> playerVm.updateShuffleState(!shuffle)+ }+ }val listState = rememberLazyListState()val findFocus = remember { FocusRequester() }@@ -448,6 +459,7 @@ private fun ImmersiveContextContent(navController: NavController, vm: ContextVieplaying = playing,saved = SongPlayer.library[p.uri] ?: contextSaved,smart = smart,+ shuffled = isThisContext && (shuffle || smart),onPlay = ::onPlay,onShuffle = ::onShuffle,onToggleSaved = { vm.toggleContextSaved(p) },@@ -622,6 +634,7 @@ private fun ContextHeader(playing: Boolean,saved: Boolean,smart: Boolean,+ shuffled: Boolean,onPlay: () -> Unit,onShuffle: () -> Unit,onToggleSaved: () -> Unit,@@ -748,8 +761,10 @@ private fun ContextHeader()ImmersiveButton(text = stringResource(R.string.immersive_shell_shuffle),- icon = Icons.Rounded.Shuffle,+ icon = if (shuffled && smart) Icons.Rounded.AutoAwesome else Icons.Rounded.Shuffle,onClick = onShuffle,+ // Lit while this list plays shuffled: a tap then steps to smart shuffle or off.+ filled = shuffled,modifier = Modifier.weight(1f),)}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.ktindex e5bb8d58..39be5dc2 100644--- 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.kt@@ -53,9 +53,12 @@ import com.music.spotui.ui.navigation.Routesimport com.music.spotui.ui.navigation.profileRouteimport com.music.spotui.ui.screens.AccountBrowser-/** The profile picture as a disc (the first letter of the name until it loads), opening [onClick]. */+/**+ * The profile picture as a disc (the first letter of the name until it loads), opening [onClick];+ * null when the caller takes the tap on a wider area around it.+ */@Composable-internal fun ProfileDisc(onClick: () -> Unit, modifier: Modifier = Modifier) {+internal fun ProfileDisc(onClick: (() -> Unit)?, modifier: Modifier = Modifier) {val avatar = ProfileCache.imageUrlval initial = ProfileCache.name?.trim()?.firstOrNull()?.uppercase() ?: "•"AvatarDisc(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.ktindex a43b47ac..689f87b1 100644--- 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.kt@@ -25,7 +25,9 @@ import androidx.compose.foundation.lazy.rememberLazyListStateimport androidx.compose.material3.Textimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.Stateimport androidx.compose.runtime.collectAsState+import androidx.compose.runtime.derivedStateOfimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.remember@@ -64,6 +66,7 @@ import com.music.spotui.ui.immersive.components.immersiveClickableimport com.music.spotui.ui.immersive.components.immersiveFeedSkeletonimport com.music.spotui.ui.immersive.components.immersiveHeroCardWidthimport com.music.spotui.ui.immersive.shell.ImmersiveFloatingHeader+import com.music.spotui.ui.immersive.shell.ImmersiveHeaderContentHeightimport com.music.spotui.ui.immersive.shell.LocalBarControlSizeimport com.music.spotui.ui.immersive.shell.immersiveChromeScrollimport com.music.spotui.ui.immersive.shell.immersiveHeaderContentPadding@@ -110,6 +113,12 @@ fun ImmersiveHomeScreen(navController: NavController) {)}+ // The context playing right now (empty while paused), derived once for every card: a card+ // only recomposes when its own answer flips, not on every change of the player's state.+ val playingContext = remember {+ derivedStateOf { if (Graph.currentSongState.playingState.value) SongPlayer.nowPlaying.value.contextUri else "" }+ }+// 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@@ -158,14 +167,14 @@ fun ImmersiveHomeScreen(navController: NavController) {feed != null && feed.sections.isNotEmpty() -> {gridSection?.let { section ->item(key = "home:shortcuts") {- ShortcutGrid(navController, section.items.take(8))+ ShortcutGrid(navController, section.items.take(8), playingContext)}}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)+ if (hero) HeroSection(navController, section, playingContext) else ShelfSection(navController, section, playingContext)}}// Sections from extensions (home.sections), after Spotify's own.@@ -186,11 +195,21 @@ fun ImmersiveHomeScreen(navController: NavController) {// The greeting and the profile disc on floating glass; the feed scrolls under it.ImmersiveFloatingHeader(title, collapse = rememberTopBarCollapse(listState, 24.dp)) {val size = LocalBarControlSize.current+ // The tap area is the header's full height and reaches past the disc toward the+ // title, so the small disc of the minimized bar is still easy to hit.Box(- Modifier.size(size).graphicsLayer { scaleX = size / 44.dp; scaleY = scaleX },- contentAlignment = Alignment.Center,+ Modifier+ .height(ImmersiveHeaderContentHeight)+ .width(size + 20.dp)+ .immersiveClickable(onClick = { showProfile = true }),+ contentAlignment = Alignment.CenterEnd,) {- ProfileDisc(onClick = { showProfile = true })+ Box(+ Modifier.size(size).graphicsLayer { scaleX = size / 44.dp; scaleY = scaleX },+ contentAlignment = Alignment.Center,+ ) {+ ProfileDisc(onClick = null)+ }}}}@@ -231,12 +250,23 @@ private fun HomeItem.contextUri(): String = when (this) {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 {+/** True while this card's album, playlist or artist is the playing context, [playingContext]. */+private fun HomeItem.isPlayingIn(playingContext: String): Boolean {val uri = contextUri()- if (uri.isEmpty()) return false- return SongPlayer.nowPlaying.value.contextUri == uri && Graph.currentSongState.playingState.value+ return uri.isNotEmpty() && playingContext == uri+}++/**+ * Keys for the cards of a shelf: the uri they open, or their kind and name for those with none+ * (an episode). A repeat within one shelf gets a suffix, as a lazy list refuses two equal keys.+ */+private fun homeItemKeys(items: List<HomeItem>): List<String> {+ val seen = HashMap<String, Int>()+ return items.map { item ->+ val base = item.contextUri().ifEmpty { "${item::class.simpleName}:${item.name}:${item.imageUrl}" }+ val count = seen.merge(base, 1, Int::plus) ?: 1+ if (count == 1) base else "$base#$count"+ }}@Composable@@ -249,22 +279,25 @@ private fun HomeItem.cardSubtitle(): String = when (this) {/** 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) {+private fun HeroSection(navController: NavController, section: HomeSection, playingContext: State<String>) {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)+ val keys = remember(section.items) { homeItemKeys(section.items) }ImmersiveShelfRow {- items(section.items.size) { i ->+ items(section.items.size, key = { keys[it] }) { i ->val item = section.items[i]+ // One lambda per card, so the press hint's pointer input is not restarted by a recomposition.+ val hint = remember(item) { { prefetchHomeItem(item) } }ImmersiveLargeAlbumCard(title = item.name,subtitle = item.cardSubtitle(),imageUrl = item.imageUrl,onClick = { onHomeItemClick(navController, item) },- modifier = Modifier.width(cardWidth).pressHint { prefetchHomeItem(item) },- playing = item.isPlayingNow(),+ modifier = Modifier.width(cardWidth).pressHint(hint),+ playing = item.isPlayingIn(playingContext.value),)}}@@ -274,19 +307,21 @@ private fun HeroSection(navController: NavController, section: HomeSection) {/** A titled row of square cards (round for artists). */@Composable-private fun ShelfSection(navController: NavController, section: HomeSection) {+private fun ShelfSection(navController: NavController, section: HomeSection, playingContext: State<String>) {+ val keys = remember(section.items) { homeItemKeys(section.items) }ImmersiveShelf(title = section.title) {- items(section.items.size) { i ->+ items(section.items.size, key = { keys[it] }) { i ->val item = section.items[i]+ val hint = remember(item) { { prefetchHomeItem(item) } }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) },+ .pressHint(hint),round = item is HomeItem.Artist,- playing = item.isPlayingNow(),+ playing = item.isPlayingIn(playingContext.value),)}}@@ -294,7 +329,7 @@ private fun ShelfSection(navController: NavController, section: HomeSection) {/** 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>) {+private fun ShortcutGrid(navController: NavController, items: List<HomeItem>, playingContext: State<String>) {Column(modifier = Modifier.padding(horizontal = Immersive.Gutter).padding(bottom = 22.dp),verticalArrangement = Arrangement.spacedBy(10.dp),@@ -302,7 +337,7 @@ private fun ShortcutGrid(navController: NavController, items: List<HomeItem>) {items.chunked(2).forEach { rowItems ->Row(horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth()) {rowItems.forEach { item ->- val playing = item.isPlayingNow()+ val playing = item.isPlayingIn(playingContext.value)Row(verticalAlignment = Alignment.CenterVertically,modifier = Modifierdiff --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.ktindex ea3d3a05..80a0e115 100644--- 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.kt@@ -169,8 +169,8 @@ fun ImmersiveLibraryScreen(navController: NavController) {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 searchActive by rememberSaveable { mutableStateOf(false) }+ var searchQuery by rememberSaveable { mutableStateOf("") }var kind by rememberSaveable { mutableStateOf(LibraryChip.ALL) }if (showAccount) {@@ -186,14 +186,14 @@ fun ImmersiveLibraryScreen(navController: NavController) {val loading = entries is Response.Loadingval (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)+ // The kind and search filters only run again when their inputs change, not on every recomposition.+ val (shownEntries, shownArtists) = remember(kind, allEntries, followedArtists, searchQuery) {+ val (byKind, artists) = LibraryChips.apply(kind, allEntries, followedArtists, LIBRARY_SONG_IDS)+ if (searchQuery.isBlank()) byKind to artists+ else byKind.filter {+ it.name.contains(searchQuery, ignoreCase = true) || it.subtitle.contains(searchQuery, ignoreCase = true)+ } to artists.filter { it.name.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@@ -270,12 +270,16 @@ fun ImmersiveLibraryScreen(navController: NavController) {},tint = if (searchActive) Immersive.Accent else Immersive.Text,)- Box(Modifier.size(44.dp), contentAlignment = Alignment.Center) {+ // The whole 44 dp slot takes the tap, not only the 36 dp disc in it.+ Box(+ Modifier.size(44.dp).immersiveClickable(onClick = { showAccount = true }),+ contentAlignment = Alignment.Center,+ ) {AvatarDisc(url = avatar?.imageUrl,initial = avatar?.name?.trim()?.firstOrNull()?.uppercase() ?: "•",contentDescription = stringResource(R.string.account_title),- onClick = { showAccount = true },+ onClick = null,)}}@@ -293,6 +297,9 @@ fun ImmersiveLibraryScreen(navController: NavController) {}}+/** The library rows that hold songs rather than a playlist, for [LibraryChips.apply]. */+private val LIBRARY_SONG_IDS = setOf(Api.HomeCache.LIKED_SONGS_ID, Api.HomeCache.LOCAL_FILES_ID, Api.HomeCache.DOWNLOADS_ID)+/** The collapse fraction (0..1) of a grid page, as [rememberTopBarCollapse] gives a list's. */@Composableinternal fun gridCollapse(state: LazyGridState): () -> Float {@@ -447,7 +454,7 @@ private fun openLibraryEntry(entry: LibraryEntry, navController: NavController)/** The rows layout. */@OptIn(ExperimentalFoundationApi::class)@Composable-private fun LibraryList(+internal fun LibraryList(listState: LazyListState,header: @Composable () -> Unit,loading: Boolean,@@ -737,7 +744,7 @@ private fun LibraryGrid(LazyVerticalGrid(state = gridState,columns = GridCells.Fixed(3),- modifier = Modifier.fillMaxSize().immersiveChromeScroll(),+ modifier = Modifier.fillMaxSize().immersiveHazeSource().immersiveChromeScroll(),contentPadding = PaddingValues(start = Immersive.Gutter, end = Immersive.Gutter,top = immersiveTopContentPadding(), bottom = Immersive.BottomChrome,diff --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.ktindex eb1c5515..f4ac470a 100644--- 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.kt@@ -165,7 +165,7 @@ fun ImmersiveSearchScreen(navController: NavController) {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)+ SongPlayer.playSong(song.url, context, songs = listOf(song), alone = true)vm.updateSongState(song.coverUri, song.title, song.singer, true, song.id, 0, song.album)}@@ -312,7 +312,7 @@ private fun openRecent(item: RecentItem, navController: NavController, vm: SearcdurationMs = item.durationMs,)vm.startRadioFromSong(song)- SongPlayer.playSong(song.url, context)+ SongPlayer.playSong(song.url, context, songs = listOf(song), alone = true)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()))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.ktindex b494b0e1..fa05d989 100644--- 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.kt@@ -73,6 +73,7 @@ import com.music.spotui.ui.immersive.components.ImmersiveCoverimport com.music.spotui.ui.immersive.components.ImmersiveSongTitleimport com.music.spotui.ui.immersive.components.immersiveClickableimport com.music.spotui.ui.immersive.components.rememberImmersiveOverscrollFactory+import com.music.spotui.ui.immersive.motion.ImmersiveMotionimport com.music.spotui.ui.look.rememberArtworkColorsimport com.music.spotui.ui.look.rememberReduceMotion@@ -82,9 +83,6 @@ 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. */@Immutabledata class ImmersiveSheetTint(val background: Color, val accent: Color)@@ -120,7 +118,7 @@ fun rememberImmersiveSheetTint(imageUrl: String?): ImmersiveSheetTint {Color(ColorUtils.HSLToColor(accent)),)}- val spec = if (rememberReduceMotion()) snap<Color>() else tween(TINT_FADE_MS)+ val spec = if (rememberReduceMotion()) snap<Color>() else tween(ImmersiveMotion.SHEET_TINT_MS)val background by animateColorAsState(target.background, spec, label = "sheetTintBackground")val accent by animateColorAsState(target.accent, spec, label = "sheetTintAccent")return ImmersiveSheetTint(background, accent)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.ktindex 60a21276..6e911781 100644--- a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/ImmersiveGlass.kt+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/ImmersiveGlass.kt@@ -113,7 +113,8 @@ fun rememberLiquidGlassActive(): Boolean {/*** 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+ * [rememberLiquidGlassActive] is true; null means the bars fall back to the frost (which samples+ * the same recording through [LocalImmersiveFrostPage] on Android 12+, Haze below). Pages feed* it through [immersiveHazeSource], which records the page here as well when it is provided.*/val LocalImmersiveBackdrop = compositionLocalOf<LayerBackdrop?> { null }@@ -234,6 +235,35 @@ internal fun Modifier.immersiveLiquidGlass()}+/**+ * Haze's frost drawn from the page recording ([LocalImmersiveFrostPage]) instead of Haze: a+ * [blur] (dp) under [tint], nothing else. It follows a page or tab transition frame by frame like+ * the Liquid Glass does. Clip it to its shape before this.+ */+@Composable+internal fun Modifier.immersivePageFrost(page: LayerBackdrop, tint: Color, blur: Float): Modifier {+ val backdrop = remember(page) { PageBackdrop(page) }+ val effects = remember(blur) {+ val block: com.music.spotui.ui.immersive.shell.backdrop.BackdropEffectScope.() -> Unit = {+ blur(blur * density * GLASS_RESOLUTION_SCALE)+ }+ block+ }+ val surface = remember(tint) {+ val block: DrawScope.() -> Unit = { drawRect(color = tint, size = size) }+ block+ }+ return drawBackdrop(+ backdrop = backdrop,+ shape = { androidx.compose.ui.graphics.RectangleShape },+ effects = effects,+ highlight = null,+ shadow = null,+ onDrawSurface = surface,+ backdropScale = GLASS_RESOLUTION_SCALE,+ )+}+/*** The 0..1 press of a glass surface for [source], on the Immersive press spring (a touch of* overshoot on release). Constant 0 under "reduce motion". Read it in the draw phase.@@ -265,6 +295,7 @@ internal class PageBackdrop(private val page: LayerBackdrop) : Backdrop {layerBlock: (GraphicsLayerScope.() -> Unit)?,) {val source = page.layerCoordinates+ page.moves // read: a page sliding or arriving redraws this glass on every frameval attached = coordinates != null && source != null && source.isAttached && coordinates.isAttached &&!page.isInsideSource(coordinates)val sameWindow = attached && source!!.findRoot() === coordinates!!.findRoot()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.ktindex 8ff496fd..582586f8 100644--- a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/ImmersiveHaze.kt+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/ImmersiveHaze.kt@@ -44,6 +44,14 @@ import dev.chrisbanes.haze.hazeSource*/val LocalImmersiveHaze = compositionLocalOf<HazeState?> { null }+/**+ * The page recording the frost samples instead of Haze: provided by the host on Android 12++ * while Liquid Glass is off. It is the same recording as the Liquid Glass one, which follows a+ * page or tab transition frame by frame (slide and fade); Haze's sampling kept showing the old+ * page until the transition ended. Null below Android 12, where Haze does not blur anyway.+ */+val LocalImmersiveFrostPage = compositionLocalOf<LayerBackdrop?> { null }+/** A [HazeState] kept for the lifetime of the calling composition. */@Composablefun rememberImmersiveHazeState(): HazeState = remember { HazeState() }@@ -53,27 +61,40 @@ fun rememberImmersiveHazeState(): HazeState = remember { HazeState() }* 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.+ * the glass to refract, so a page that calls this gets both looks with nothing else to do. With+ * [LocalImmersiveFrostPage] provided it records the content there only: the frost reads that.*/@Composablefun Modifier.immersiveHazeSource(state: HazeState? = LocalImmersiveHaze.current,backdrop: LayerBackdrop? = LocalImmersiveBackdrop.current,+ frost: LayerBackdrop? = LocalImmersiveFrostPage.current,): Modifier {+ if (backdrop == null && frost != null) return this.layerBackdrop(frost)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.+ * the missing pixels, and the bars are redrawn on every frame of every scroll. Over the app's own+ * page ([LocalImmersiveHaze]) with [LocalImmersiveFrostPage] provided, the same frost is drawn+ * from that recording instead ([immersivePageFrost]).*/@OptIn(ExperimentalHazeApi::class)+@Composableinternal fun Modifier.immersiveFrost(state: HazeState,tint: Color = Immersive.GlassFill.copy(alpha = 0.55f),blur: Float = 24f,-): Modifier = hazeEffect(state) {+): Modifier {+ val page = LocalImmersiveFrostPage.current+ if (page != null && state === LocalImmersiveHaze.current) return this.immersivePageFrost(page, tint, blur)+ return hazeFrost(state, tint, blur)+}++@OptIn(ExperimentalHazeApi::class)+private fun Modifier.hazeFrost(state: HazeState, tint: Color, blur: Float): Modifier = hazeEffect(state) {inputScale = HazeInputScale.Fixed(0.33f)backgroundColor = Immersive.Pagetints = listOf(HazeTint(tint))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.ktindex 90335eba..b01b6233 100644--- a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/ImmersiveTopBar.kt+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/ImmersiveTopBar.kt@@ -44,6 +44,8 @@ import com.music.spotui.ui.look.rememberReduceMotionimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clip+import androidx.compose.ui.input.pointer.pointerInput+import com.music.spotui.ui.components.wideClickableimport androidx.compose.ui.layout.layoutimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.graphics.graphicsLayer@@ -78,7 +80,7 @@ private val TitleInset = 64.dpprivate val BarControlSize = 44.dp/** The same controls while the chrome is minimized ([LocalImmersiveChrome]): small glass pills. */-private val BarControlSizeMinimized = 34.dp+private val BarControlSizeMinimized = 38.dp/*** The size of a top bar control right now: 44 dp, shrinking to small pills on a spring while the@@ -152,7 +154,7 @@ fun ImmersiveTopBar() {val page = LocalImmersiveBackdrop.currentval controlSize = rememberBarControlSize()- Box(modifier = modifier.fillMaxWidth()) {+ Box(modifier = modifier.fillMaxWidth().holdsTouches()) {// The glass panel hanging from the top (rounded bottom corners), fading in with the collapse.ImmersiveTopGlass(collapse, Modifier.matchParentSize(), hazeState)Box(@@ -181,9 +183,10 @@ fun ImmersiveTopBar(modifier = Modifier.align(Alignment.CenterStart).padding(start = Immersive.Gutter)+ // Taps around the disc count too, out to the screen edge and the bar's height.+ .wideClickable(horizontal = Immersive.Gutter, vertical = 12.dp, interactionSource = backSource, onClick = onBack).size(controlSize)- .immersiveGlassSurface(CircleShape, hazeState, interactionSource = backSource)- .clickable(interactionSource = backSource, indication = null, role = Role.Button, onClick = onBack),+ .immersiveGlassSurface(CircleShape, hazeState, interactionSource = backSource),contentAlignment = Alignment.Center,) {Icon(@@ -430,7 +433,7 @@ fun ImmersiveFloatingHeader(trailing: (@Composable RowScope.() -> Unit)? = null,) {val controlSize = rememberBarControlSize()- Box(modifier.fillMaxWidth()) {+ Box(modifier.fillMaxWidth().holdsTouches()) {ImmersiveTopGlass(collapse, Modifier.matchParentSize(), hazeState)Row(modifier = Modifier@@ -453,3 +456,14 @@ fun ImmersiveFloatingHeader(}}}++/**+ * Keeps a tap on the bar's glass from reaching the page under it: being hit at all is what keeps+ * the page from being hit. Nothing is consumed: a button in the bar drops its tap when it sees the+ * finger's moves consumed, so consuming here made the bar's buttons miss most taps.+ */+private fun Modifier.holdsTouches(): Modifier = pointerInput(Unit) {+ awaitPointerEventScope {+ while (true) awaitPointerEvent()+ }+}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.ktindex 0a6a4f0e..d1ba24fe 100644--- 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.kt@@ -34,6 +34,12 @@ import com.music.spotui.ui.immersive.shell.backdrop.internal.InverseLayerScopeprivate val DefaultOnDraw: ContentDrawScope.() -> Unit = { drawContent() }+/**+ * The opacity a page recording into a backdrop has on screen right now (its fade during a page+ * transition), provided by the navigation around each page: the glass draws the page with it.+ */+val LocalBackdropSourceAlpha = androidx.compose.runtime.staticCompositionLocalOf<() -> Float> { { 1f } }+@Composablefun rememberLayerBackdrop(graphicsLayer: GraphicsLayer = rememberGraphicsLayer(),@@ -63,16 +69,28 @@ class LayerBackdrop internal constructor(var coordinates: LayoutCoordinates? = null/** This source's own recording: every page keeps its own, so two pages in a transition are both sampled. */var layer: GraphicsLayer? = null+ /** Its opacity on screen now ([LocalBackdropSourceAlpha]); read while drawing, so a fade redraws the glass. */+ var alpha: () -> Float = { 1f }}internal val sources = ArrayList<Source>()+ /**+ * Bumped whenever a page records in, leaves or moves. The glass reads it while drawing: a page+ * sliding in does not redraw its content, and the same LayoutCoordinates object would not+ * invalidate [layerCoordinates], so without it the glass kept the page's old place until the+ * transition ended, then jumped.+ */+ internal var moves by androidx.compose.runtime.mutableIntStateOf(0)+internal fun publish(source: Source) {if (sources.lastOrNull() === source) layerCoordinates = source.coordinates+ moves++}internal fun retire(source: Source) {sources.remove(source)layerCoordinates = sources.lastOrNull()?.coordinates+ moves++}private var inverseLayerScope: InverseLayerScope? = null@@ -103,8 +121,19 @@ class LayerBackdrop internal constructor(continue}if (!c.isAttached || layer.size.width <= 0) continue+ val a = s.alpha().coerceIn(0f, 1f)+ if (a <= 0f) continueval o = offsetOf(c)- withTransform({ translate(-o.x, -o.y) }) { drawLayer(layer) }+ withTransform({ translate(-o.x, -o.y) }) {+ if (a >= 1f) drawLayer(layer)+ else drawContext.canvas.let { canvas ->+ // The page's fade, as on screen (the recording itself is always opaque).+ canvas.saveLayer(androidx.compose.ui.geometry.Rect(Offset.Zero, layer.size.let { androidx.compose.ui.geometry.Size(it.width.toFloat(), it.height.toFloat()) }),+ androidx.compose.ui.graphics.Paint().apply { alpha = a })+ drawLayer(layer)+ canvas.restore()+ }+ }}}@@ -114,6 +143,7 @@ class LayerBackdrop internal constructor(layerBlock: (GraphicsLayerScope.() -> Unit)?) {val coordinates = coordinates ?: return+ moves // read: a page moving or arriving redraws the glasswithTransform({if (layerBlock != null) {with(obtainInverseLayerScope()) { inverseTransform(density, layerBlock) }diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/backdrops/LayerBackdropModifier.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/backdrops/LayerBackdropModifier.ktindex b65d81ea..9ec3815d 100644--- a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/backdrops/LayerBackdropModifier.kt+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/backdrops/LayerBackdropModifier.kt@@ -19,6 +19,7 @@ import androidx.compose.ui.layout.LayoutCoordinatesimport androidx.compose.ui.node.DrawModifierNodeimport androidx.compose.ui.node.GlobalPositionAwareModifierNodeimport androidx.compose.ui.node.ModifierNodeElement+import androidx.compose.ui.node.currentValueOfimport androidx.compose.ui.node.invalidateDrawimport androidx.compose.ui.node.requireGraphicsContextimport androidx.compose.ui.platform.InspectorInfo@@ -64,7 +65,7 @@ private class LayerBackdropElement(private class LayerBackdropNode(var backdrop: LayerBackdrop-) : DrawModifierNode, GlobalPositionAwareModifierNode, Modifier.Node() {+) : DrawModifierNode, GlobalPositionAwareModifierNode, androidx.compose.ui.node.CompositionLocalConsumerModifierNode, Modifier.Node() {override fun ContentDrawScope.draw() {// Vendored change: record once and composite, rather than upstream's@@ -103,7 +104,9 @@ private class LayerBackdropNode(override fun onAttach() {registeredIn = backdropsource.layer = requireGraphicsContext().createGraphicsLayer()+ source.alpha = currentValueOf(LocalBackdropSourceAlpha)backdrop.sources.add(source)+ backdrop.moves++}override fun onGloballyPositioned(coordinates: LayoutCoordinates) {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.ktindex c72c5777..4969cb00 100644--- 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.kt@@ -46,12 +46,21 @@ 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) })+/**+ * The phone's "Remove animations" setting, read once at the root (see App) for both looks.+ * Null where nothing provides it: [rememberReduceMotion] then reads the setting itself.+ */+val LocalReduceMotion = compositionLocalOf<Boolean?> { null }+/*** 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 {+fun rememberReduceMotion(): Boolean = LocalReduceMotion.current ?: rememberReduceMotionSetting()++@Composable+private fun rememberReduceMotionSetting(): Boolean {val context = LocalContext.currentreturn remember(context) {Settings.Global.getFloat(context.contentResolver, Settings.Global.ANIMATOR_DURATION_SCALE, 1f) == 0fdiff --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.ktindex 7e9c833c..eed875f4 100644--- 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.kt@@ -45,6 +45,7 @@ import app.myspoti.engine.Rimport com.music.spotui.data.preferences.Lookimport com.music.spotui.data.preferences.LookPrefimport com.music.spotui.ui.theme.AppBackground+import com.music.spotui.ui.theme.AppAccentimport com.music.spotui.ui.theme.AppSansimport kotlin.math.abs@@ -127,7 +128,7 @@ fun LookStep(onNext: () -> Unit, offer: LookOffer? = null) {onClick = onNext,shape = if (immersive) RoundedCornerShape(14.dp) else ButtonDefaults.shape,colors = ButtonDefaults.buttonColors(- containerColor = if (immersive) Color.White else Color(0xFF1DB954),+ containerColor = if (immersive) Color.White else AppAccent,contentColor = Color.Black,),modifier = Modifier.fillMaxWidth().height(50.dp),@@ -167,7 +168,7 @@ private fun LookSegments(look: Look, immersive: Boolean, family: androidx.composwhen {!selected -> Color.Transparentimmersive -> Color.White.copy(alpha = 0.92f)- else -> Color(0xFF1DB954)+ else -> AppAccent},label = "segmentFill",)diff --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.ktindex 26f837a1..05fb56b3 100644--- 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.kt@@ -47,6 +47,7 @@ import androidx.palette.graphics.Paletteimport com.bumptech.glide.Glideimport com.bumptech.glide.request.target.CustomTargetimport com.bumptech.glide.request.transition.Transition+import com.music.spotui.di.COVER_DECODE_PXimport kotlinx.coroutines.delayimport kotlinx.coroutines.isActiveimport kotlin.math.PI@@ -250,7 +251,7 @@ private fun loadArtwork(context: Context, imageUrl: String, onLoaded: (Bitmap) -Glide.with(context.applicationContext).asBitmap().load(imageUrl)- .override(128, 128) // palette quality is fine at thumbnail size, and it's fast+ .override(COVER_DECODE_PX, COVER_DECODE_PX) // the same decode as the colours of the player: Glide reuses it.disallowHardwareConfig() // Palette needs pixel access.into(object : CustomTarget<Bitmap>() {override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) = onLoaded(resource)diff --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.ktindex 1b5e6c01..9901d3ff 100644--- 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.kt@@ -60,6 +60,34 @@ fun ThinSlider(onValueChange: (Float) -> Unit,modifier: Modifier = Modifier,onValueChangeFinished: (() -> Unit)? = null,+ 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),+) = ThinSlider(+ value = { value },+ onValueChange = onValueChange,+ modifier = modifier,+ onValueChangeFinished = onValueChangeFinished,+ loading = loading,+ idleHeight = idleHeight,+ activeHeight = activeHeight,+ activeColor = activeColor,+ inactiveColor = inactiveColor,+)++/**+ * The same bar, with the position read by [value] rather than passed in. [value] is read only+ * where the bar is drawn, so a value that moves every frame redraws the bar without recomposing+ * the screen that holds it.+ */+@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.@@ -154,7 +182,7 @@ fun ThinSlider(// 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+ val filled = size.width * value().coerceIn(0f, 1f) * fillFactorif (filled > 0f) {drawRoundRect(color = activeColor,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 c847ca2d..a1249fb7 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@@ -4,6 +4,8 @@ import android.os.Buildimport android.util.Logimport androidx.annotation.RequiresApiimport androidx.compose.animation.AnimatedContentScope+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.animation.core.animateFloatimport androidx.compose.animation.EnterTransitionimport androidx.compose.animation.ExitTransitionimport androidx.compose.animation.core.CubicBezierEasing@@ -46,6 +48,7 @@ import com.music.spotui.ui.screens.QueueScreenimport com.music.spotui.ui.screens.SearchScreenimport com.music.spotui.ui.viewmodel.PlayerViewModelimport com.music.spotui.ui.immersive.motion.ImmersiveMotion.Pages as IPages+import com.music.spotui.ui.immersive.motion.ImmersiveMotion.PageFade as IFade@Composablefun MyNavHost(@@ -78,10 +81,10 @@ fun MyNavHost(// 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.// 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) },+ enterTransition = { if (immersiveState.value) IPages.enter(reduceState.value)(this) else if (reduceState.value) EnterTransition.None else navEnter(initialState, targetState) },+ exitTransition = { if (immersiveState.value) IPages.exit(reduceState.value)(this) else if (reduceState.value) ExitTransition.None else navExit(initialState, targetState) },+ popEnterTransition = { if (immersiveState.value) IPages.popEnter(reduceState.value)(this) else if (reduceState.value) EnterTransition.None else navPopEnter(initialState, targetState) },+ popExitTransition = { if (immersiveState.value) IPages.popExit(reduceState.value)(this) else if (reduceState.value) ExitTransition.None else navPopExit(initialState, targetState) },){page(Routes.Home.route){LaunchedEffect(playerState) {@@ -107,7 +110,7 @@ fun MyNavHost(// Older links to the player route open the player sheet over the page instead.page(Routes.Player.route){LaunchedEffect(Unit) {- navHostController.popBackStack()+ navHostController.popBackStack(Routes.Player.route, inclusive = true)PlayerSheet.show()}}@@ -200,21 +203,21 @@ fun MyNavHost(bottomBarState.value = truebottomBarPlayerState.value = playerState != ""}- com.music.spotui.ui.screens.ExtensionsScreen(navHostController)+ if (isImmersive()) com.music.spotui.ui.immersive.pages.ImmersiveExtensionsScreen(navHostController) else com.music.spotui.ui.screens.ExtensionsScreen(navHostController)}page("${Routes.Extension.route}/{id}", arguments = listOf(navArgument("id") { defaultValue = "" })){ entry ->LaunchedEffect(playerState) {bottomBarState.value = truebottomBarPlayerState.value = playerState != ""}- com.music.spotui.ui.screens.ExtensionScreen(navHostController, entry.arguments?.getString("id").orEmpty())+ if (isImmersive()) com.music.spotui.ui.immersive.pages.ImmersiveExtensionScreen(navHostController, entry.arguments?.getString("id").orEmpty()) else com.music.spotui.ui.screens.ExtensionScreen(navHostController, entry.arguments?.getString("id").orEmpty())}page("${Routes.ExtensionEntry.route}/{id}", arguments = listOf(navArgument("id") { defaultValue = "" })){ entry ->LaunchedEffect(playerState) {bottomBarState.value = truebottomBarPlayerState.value = playerState != ""}- com.music.spotui.ui.screens.ExtensionEntryScreen(navHostController, entry.arguments?.getString("id").orEmpty())+ if (isImmersive()) com.music.spotui.ui.immersive.pages.ImmersiveExtensionEntryScreen(navHostController, entry.arguments?.getString("id").orEmpty()) else com.music.spotui.ui.screens.ExtensionEntryScreen(navHostController, entry.arguments?.getString("id").orEmpty())}// An extension's own page (webview.page), sandboxed.page("extension-page/{id}", arguments = listOf(navArgument("id") { defaultValue = "" })){ entry ->@@ -261,7 +264,7 @@ fun MyNavHost(/* We check if it's not null */val albumId = navBackStackEntry.arguments?.getString("albumId").orEmpty()uId?.let { name ->- AlbumByIdScreen(navHostController, name = name, artist = artist, id = albumId)+ if (isImmersive()) com.music.spotui.ui.immersive.screens.ImmersiveAlbumByIdScreen(navHostController, name = name, artist = artist, id = albumId) else AlbumByIdScreen(navHostController, name = name, artist = artist, id = albumId)}}@@ -347,7 +350,7 @@ fun MyNavHost(}val uri = navBackStackEntry.arguments?.getString("uri")val name = navBackStackEntry.arguments?.getString("name").orEmpty()- uri?.let { com.music.spotui.ui.screens.FolderScreen(navHostController, it, name) }+ uri?.let { if (isImmersive()) com.music.spotui.ui.immersive.pages.ImmersiveFolderScreen(navHostController, it, name) else com.music.spotui.ui.screens.FolderScreen(navHostController, it, name) }}page("${Routes.LocalPlaylist.route}/{id}") { navBackStackEntry ->@@ -355,7 +358,7 @@ fun MyNavHost(bottomBarState.value = truebottomBarPlayerState.value = playerState != ""}- navBackStackEntry.arguments?.getString("id")?.let { com.music.spotui.ui.screens.LocalPlaylistScreen(navHostController, it) }+ navBackStackEntry.arguments?.getString("id")?.let { if (isImmersive()) com.music.spotui.ui.immersive.pages.ImmersiveLocalPlaylistScreen(navHostController, it) else com.music.spotui.ui.screens.LocalPlaylistScreen(navHostController, it) }}page(@@ -461,9 +464,25 @@ private fun NavGraphBuilder.page(scope.transition.currentState == scope.transition.targetState}}- androidx.compose.runtime.CompositionLocalProvider(LocalPageSettled provides settled) {+ val immersive = isImmersive()+ // Immersive: the page runs its own fade (ImmersiveMotion.PageFade) and hands it to the Liquid+ // Glass recording it, which then fades with it on every frame of the transition.+ val fade = if (!immersive) null else scope.transition.animateFloat(+ transitionSpec = {+ val ms = if (targetState == androidx.compose.animation.EnterExitState.Visible) IFade.enterMs else IFade.exitMs+ tween(ms)+ },+ label = "pageFade",+ ) { if (it == androidx.compose.animation.EnterExitState.Visible) 1f else 0f }+ val alpha = androidx.compose.runtime.remember(fade) { { fade?.value ?: 1f } }+ androidx.compose.runtime.CompositionLocalProvider(+ LocalPageSettled provides settled,+ com.music.spotui.ui.immersive.shell.backdrop.backdrops.LocalBackdropSourceAlpha provides alpha,+ ) {// 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) }+ Box(Modifier.fillMaxSize()+ .then(if (fade == null) Modifier else Modifier.graphicsLayer { this.alpha = fade.value })+ .background(if (immersive) com.music.spotui.ui.immersive.Immersive.Page else AppBackground)) { scope.content(entry) }}}diff --git a/base/app/src/main/java/com/music/spotui/ui/navigation/PlayerSheet.kt b/base/app/src/main/java/com/music/spotui/ui/navigation/PlayerSheet.ktindex aea625d9..4d0df018 100644--- a/base/app/src/main/java/com/music/spotui/ui/navigation/PlayerSheet.kt+++ b/base/app/src/main/java/com/music/spotui/ui/navigation/PlayerSheet.kt@@ -73,17 +73,19 @@ fun PlayerOverlay(navController: NavController) {val progress = remember { Animatable(0f) }var shown by remember { mutableStateOf(false) }val settled = remember { mutableStateOf(false) }+ // "Remove animations": the player is there, or gone, at once.+ val reduce = com.music.spotui.ui.look.rememberReduceMotion()LaunchedEffect(open) {if (open) {shown = truesettled.value = false// Two frames for the player's first composition and layout before the clock runs.if (progress.value == 0f) { withFrameNanos { }; withFrameNanos { } }- progress.animateTo(1f, tween(OPEN_MS, easing = Decelerate))+ if (reduce) progress.snapTo(1f) else progress.animateTo(1f, tween(OPEN_MS, easing = Decelerate))settled.value = true} else if (shown) {settled.value = false- progress.animateTo(0f, tween(CLOSE_MS, easing = CloseEasing))+ if (reduce) progress.snapTo(0f) else progress.animateTo(0f, tween(CLOSE_MS, easing = CloseEasing))shown = false}}diff --git a/base/app/src/main/java/com/music/spotui/ui/navigation/Routes.kt b/base/app/src/main/java/com/music/spotui/ui/navigation/Routes.ktindex 466b6fef..862c43db 100644--- a/base/app/src/main/java/com/music/spotui/ui/navigation/Routes.kt+++ b/base/app/src/main/java/com/music/spotui/ui/navigation/Routes.kt@@ -90,3 +90,10 @@ fun artistRoute(name: String, id: String = ""): String {fun albumRoute(name: String, artist: String = "", id: String = ""): String ="${Routes.Album.route}/${android.net.Uri.encode(name.ifBlank { "album" })}" +"?artist=${android.net.Uri.encode(artist)}&id=${android.net.Uri.encode(id)}"++/**+ * Opens a page from outside the page's own UI (a shared link): a second link to the page already+ * on top reuses it instead of stacking a duplicate.+ */+fun androidx.navigation.NavController.navigateSingleTop(route: String) =+ navigate(route) { launchSingleTop = true }diff --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 4344640c..e898bf7f 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@@ -13,8 +13,18 @@ import androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.setValue-import androidx.compose.ui.graphics.Color-import androidx.compose.material3.Text+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.statusBarsPadding+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.automirrored.filled.ArrowBack+import androidx.compose.material3.Icon+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.dp+import com.music.spotui.ui.components.ErrorRetry+import com.music.spotui.ui.components.pressableimport androidx.navigation.NavControllerimport com.music.spotui.di.Graphimport com.music.spotui.ui.components.Loader@@ -24,7 +34,9 @@ import com.music.spotui.ui.components.Loaderfun AlbumByIdScreen(navController: NavController, name: String, artist: String, id: String) {var resolved by remember(name, artist, id) { mutableStateOf(id.ifBlank { null }) }var failed by remember { mutableStateOf(false) }- LaunchedEffect(name, artist, id) {+ // Bumped by Try again: the look-up runs once more.+ var attempt by remember { mutableStateOf(0) }+ LaunchedEffect(name, artist, id, attempt) {if (resolved == null) {resolved = Graph.api.resolveAlbumId(name, artist)if (resolved == null) failed = true@@ -32,9 +44,14 @@ fun AlbumByIdScreen(navController: NavController, name: String, artist: String,}val albumId = resolvedwhen {- 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)+ albumId != null -> ContextScreen(navController, type = "album", id = albumId)+ failed -> Column(Modifier.fillMaxSize().statusBarsPadding()) {+ Icon(+ Icons.AutoMirrored.Filled.ArrowBack, stringResource(R.string.accessibility_navigate_back), tint = AppText,+ modifier = Modifier.pressable(0.96f) { navController.navigateUp() }.padding(16.dp).size(26.dp),+ )+ ErrorRetry(stringResource(R.string.album_not_found)) { failed = false; attempt++ }+ }else -> Loader(SkeletonKind.Header)}}diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/ArtistScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/ArtistScreen.ktindex 349624f7..64c454be 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/ArtistScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/ArtistScreen.kt@@ -1,7 +1,10 @@package com.music.spotui.ui.screens+import com.music.spotui.ui.components.widePressable+import com.music.spotui.ui.components.wideClickableimport com.music.spotui.ui.theme.toneimport com.music.spotui.ui.theme.AppText+import com.music.spotui.ui.theme.AppMutedimport com.music.spotui.ui.components.SkeletonKindimport com.music.spotui.ui.components.pressable@@ -232,10 +235,10 @@ private fun ArtistOverviewContent(modifier = Modifier.statusBarsPadding().padding(12.dp)+ .wideClickable { navController.navigateUp() }.size(40.dp).clip(CircleShape)- .background(Color.Black.copy(alpha = 0.35f))- .clickable { navController.navigateUp() },+ .background(Color.Black.copy(alpha = 0.35f)),) {Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.accessibility_navigate_back), tint = Color.White)}@@ -414,7 +417,9 @@ private fun ArtistOverviewContent(modifier = Modifier.padding(16.dp, 8.dp, 16.dp, 4.dp),)}- itemsIndexed(tracks.take(if (showAllPopular) 10 else 5)) { index, item ->+ val popular = tracks.take(if (showAllPopular) 10 else 5)+ val popularKeys = rowKeys("pop", popular) { it.song.spotifyTrackId.ifBlank { it.song.title } }+ itemsIndexed(popular, key = { i, _ -> popularKeys[i] }) { index, item ->com.music.spotui.ui.components.SwipeToQueue(item.song) {PopularTrackRow(item, index, artistViewModel,@@ -445,7 +450,9 @@ private fun ArtistOverviewContent(// ── Popular releases (discography) — vertical list, first few + "Show all" ──if (overview.popularReleases.isNotEmpty()) {item { SectionHeader(stringResource(R.string.popular_releases_section_title)) }- itemsIndexed(overview.popularReleases.take(4)) { _, album ->+ val popularReleases = overview.popularReleases.take(4)+ val popularReleaseKeys = rowKeys("release", popularReleases) { it.spotifyId.ifBlank { it.name } }+ itemsIndexed(popularReleases, key = { i, _ -> popularReleaseKeys[i] }) { _, album ->ReleaseRow(album) {navController.navigate(albumRoute(album.name, album.artists.ifBlank { displayName }, album.spotifyId))}@@ -493,7 +500,7 @@ private fun ArtistOverviewContent(}Text(text = overview.biography.orEmpty(),- color = Color.Gray,+ color = AppMuted,fontSize = 13.sp,modifier = Modifier.padding(14.dp, 4.dp, 14.dp, 16.dp),)@@ -509,7 +516,8 @@ private fun ArtistOverviewContent(LazyRow(contentPadding = androidx.compose.foundation.layout.PaddingValues(12.dp, 0.dp),) {- items(overview.relatedArtists.size) { i ->+ val relatedKeys = rowKeys("related", overview.relatedArtists) { it.id.ifBlank { it.name } }+ items(overview.relatedArtists.size, key = { relatedKeys[it] }) { i ->RelatedArtistCard(overview.relatedArtists[i]) {navController.navigate(artistRoute(overview.relatedArtists[i].name, overview.relatedArtists[i].id))}@@ -525,7 +533,8 @@ private fun ArtistOverviewContent(LazyRow(contentPadding = androidx.compose.foundation.layout.PaddingValues(12.dp, 0.dp),) {- items(overview.appearsOn.size) { i ->+ val appearsOnKeys = rowKeys("appears", overview.appearsOn) { it.spotifyId.ifBlank { it.name } }+ items(overview.appearsOn.size, key = { appearsOnKeys[it] }) { i ->ReleaseCard(overview.appearsOn[i]) {navController.navigate(albumRoute(overview.appearsOn[i].name, overview.appearsOn[i].artists, overview.appearsOn[i].spotifyId))}@@ -552,7 +561,7 @@ private fun ArtistOverviewContent() {Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.accessibility_navigate_back), tint = AppText,- modifier = Modifier.size(26.dp).clickable { navController.navigateUp() },+ modifier = Modifier.wideClickable(horizontal = 12.dp, vertical = 15.dp) { navController.navigateUp() }.size(26.dp),)Text(displayName, color = AppText, fontSize = 18.sp, fontWeight = FontWeight.Bold,@@ -632,6 +641,21 @@ private fun PopularTrackRow(}}+/**+ * A key per row of a lazy list, so a row keeps its place (and its state) when the list around it+ * changes: [prefix] and the entry's [id], with a counter on repeats. The prefix keeps the lists+ * of one page apart.+ */+private fun <T> rowKeys(prefix: String, list: List<T>, id: (T) -> String): List<String> {+ val seen = HashMap<String, Int>()+ return list.map { e ->+ val k = "$prefix:${id(e)}"+ val n = (seen[k] ?: 0) + 1+ seen[k] = n+ if (n == 1) k else "$k#$n"+ }+}+@Composableprivate fun SectionHeader(title: String) {Text(@@ -639,6 +663,7 @@ private fun SectionHeader(title: String) {color = AppText,fontSize = 20.sp,fontWeight = FontWeight.Bold,+ maxLines = 2, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,modifier = Modifier.padding(16.dp, 20.dp, 16.dp, 8.dp),)}@@ -667,7 +692,7 @@ private fun ReleaseCard(album: AlbumsModel, onClick: () -> Unit) {Text(text = album.name, color = AppText, fontSize = 13.sp, fontWeight = FontWeight.Medium, maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis)Text(text = album.time.ifBlank { album.artists }.let { if (album.time.isNotBlank()) "${album.time} • Album" else it },- color = Color.Gray,+ color = AppMuted,fontSize = 11.sp,maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,)@@ -706,7 +731,7 @@ private fun ReleaseRow(album: AlbumsModel, onClick: () -> Unit) {val year = releaseYear(album)Text(text = listOf(year, kind).filter { it.isNotBlank() }.joinToString(" • "),- color = Color.Gray,+ color = AppMuted,fontSize = 13.sp,maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,modifier = Modifier.padding(top = 2.dp),@@ -778,9 +803,8 @@ fun ArtistReleasesScreen(navController: NavController, artistName: String, artisimageVector = Icons.AutoMirrored.Filled.ArrowBack,contentDescription = "",tint = AppText,- modifier = Modifier.pressable(0.96f) { navController.navigateUp() }- .size(26.dp)- ,+ modifier = Modifier.widePressable(horizontal = 16.dp, vertical = 12.dp, pressedScale = 0.96f) { navController.navigateUp() }+ .size(26.dp),)Spacer(Modifier.width(16.dp))Text(@@ -811,28 +835,33 @@ fun ArtistReleasesScreen(navController: NavController, artistName: String, artisif (overview is Response.Loading) {item { Loader() }}+ // One key per row across the whole list (the latest release is also among the albums).+ val albumKeys = rowKeys("album", albums) { it.spotifyId.ifBlank { it.name } }+ val singleKeys = rowKeys("single", singles) { it.spotifyId.ifBlank { it.name } }+ val featuredKeys = rowKeys("featured", featuredOn) { it.spotifyId.ifBlank { it.name } }+ val untypedKeys = rowKeys("untyped", untyped) { it.spotifyId.ifBlank { it.name } }when (filter) {- "albums" -> items(albums.size) { i -> ReleaseRow(albums[i]) { openAlbum(albums[i]) } }- "singles" -> items(singles.size) { i -> ReleaseRow(singles[i]) { openAlbum(singles[i]) } }- "featured" -> items(featuredOn.size) { i -> ReleaseRow(featuredOn[i]) { openAlbum(featuredOn[i]) } }+ "albums" -> items(albums.size, key = { albumKeys[it] }) { i -> ReleaseRow(albums[i]) { openAlbum(albums[i]) } }+ "singles" -> items(singles.size, key = { singleKeys[it] }) { i -> ReleaseRow(singles[i]) { openAlbum(singles[i]) } }+ "featured" -> items(featuredOn.size, key = { featuredKeys[it] }) { i -> ReleaseRow(featuredOn[i]) { openAlbum(featuredOn[i]) } }else -> {latest?.let {item { ReleaseSectionHeader(stringResource(R.string.latest_release_title)) }- item { ReleaseRow(it) { openAlbum(it) } }+ item(key = "latest") { ReleaseRow(it) { openAlbum(it) } }}if (albums.isNotEmpty()) {item { ReleaseSectionHeader(stringResource(R.string.artist_releases_albums)) }- items(albums.size) { i -> ReleaseRow(albums[i]) { openAlbum(albums[i]) } }+ items(albums.size, key = { albumKeys[it] }) { i -> ReleaseRow(albums[i]) { openAlbum(albums[i]) } }}if (singles.isNotEmpty()) {item { ReleaseSectionHeader(stringResource(R.string.artist_releases_singles)) }- items(singles.size) { i -> ReleaseRow(singles[i]) { openAlbum(singles[i]) } }+ items(singles.size, key = { singleKeys[it] }) { i -> ReleaseRow(singles[i]) { openAlbum(singles[i]) } }}if (untyped.isNotEmpty()) {if (albums.isEmpty() && singles.isEmpty()) {item { ReleaseSectionHeader(stringResource(R.string.popular_releases_section_title)) }}- items(untyped.size) { i -> ReleaseRow(untyped[i]) { openAlbum(untyped[i]) } }+ items(untyped.size, key = { untypedKeys[it] }) { i -> ReleaseRow(untyped[i]) { openAlbum(untyped[i]) } }}}}@@ -847,24 +876,27 @@ private fun ReleaseSectionHeader(title: String) {color = AppText,fontSize = 22.sp,fontWeight = FontWeight.Bold,+ maxLines = 2, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,modifier = Modifier.padding(16.dp, 18.dp, 16.dp, 8.dp),)}@Composableprivate fun ReleaseFilterChip(label: String, selected: Boolean, onClick: () -> Unit) {+ // Same pill as the Home chips.Box(+ contentAlignment = Alignment.Center,modifier = Modifier.pressable(0.96f) { onClick() }- .clip(RoundedCornerShape(20.dp))- .background(if (selected) AppText else tone(0xFF2A2A2A))-- .padding(14.dp, 8.dp),+ .clip(RoundedCornerShape(50))+ .background(if (selected) com.music.spotui.ui.theme.AppAccent else tone(0xFF2A2A2A))+ .padding(horizontal = 16.dp, vertical = 8.dp),) {Text(text = label,color = if (selected) Color.Black else AppText,- fontSize = 13.sp,- fontWeight = FontWeight.SemiBold,+ fontSize = 14.sp,+ fontWeight = FontWeight.Bold,+ maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,)}}@@ -892,6 +924,6 @@ private fun RelatedArtistCard(artist: ArtistsModel, onClick: () -> Unit) {)Spacer(Modifier.height(6.dp))Text(text = artist.name, color = AppText, fontSize = 13.sp, fontWeight = FontWeight.Medium, maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis)- Text(text = stringResource(R.string.artist_subtitle), color = Color.Gray, fontSize = 11.sp)+ Text(text = stringResource(R.string.artist_subtitle), color = AppMuted, fontSize = 11.sp)}}diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/CategoryScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/CategoryScreen.ktindex 4351b622..b69dddf2 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/CategoryScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/CategoryScreen.kt@@ -1,5 +1,6 @@package com.music.spotui.ui.screens+import com.music.spotui.ui.components.wideClickableimport com.music.spotui.ui.theme.AppTextimport androidx.compose.ui.res.stringResource@@ -78,9 +79,8 @@ fun CategoryScreen(navController: NavController, genre: String, title: String) {contentDescription = stringResource(R.string.accessibility_navigate_back),tint = AppText,modifier = Modifier+ .wideClickable(horizontal = 8.dp, vertical = 10.dp) { navController.popBackStack() }.size(40.dp)- .clip(RoundedCornerShape(20.dp))- .clickable { navController.popBackStack() }.padding(8.dp))Text(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 d2e278aa..48da8787 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@@ -1,5 +1,7 @@package com.music.spotui.ui.screens+import com.music.spotui.ui.components.wideClickable+import com.music.spotui.ui.theme.AppDestructiveimport com.music.spotui.ui.theme.toneimport com.music.spotui.ui.theme.AppTextimport com.music.spotui.ui.theme.headerTint@@ -14,6 +16,7 @@ import androidx.compose.ui.res.stringResourceimport kotlinx.coroutines.flow.firstimport kotlinx.coroutines.asyncimport com.music.spotui.ui.components.SkeletonKind+import com.music.spotui.ui.components.animatedRowimport com.music.spotui.ui.components.pressableimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.clickable@@ -124,6 +127,9 @@ class ContextViewModel(private val inflight = java.util.concurrent.ConcurrentHashMap<String, kotlinx.coroutines.Deferred<Unit>>()private val prefetchScope = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.SupervisorJob() + Dispatchers.IO)+ /** A playlist up to this long is prefetched whole, longer ones by their first page. */+ private const val WHOLE_PLAYLIST_MAX = 200+/** Pages likely to be opened next (top of the library, home shortcuts), loaded quietly. */fun prefetchSoon(pages: List<Pair<String, String>>) {prefetchScope.launch {@@ -149,13 +155,24 @@ class ContextViewModel("liked" -> api.getLikedPage()else -> api.getPlaylistPage(id)}- val first = flow.first { it !is Response.Loading }- if (first is Response.Success) {- recent[key] = first+ // The first page of tracks; a playlist of 200 songs or fewer is waited for whole (as+ // PagePrefetch does), so it opens complete rather than cut after its first 100.+ var first: Response<ContextPageModel>? = null+ val settled = flow.first { r ->+ if (r is Response.Loading) return@first false+ if (first == null) first = r+ r !is Response.Success || type != "playlist" || r.data.complete || r.data.tracks.size > WHOLE_PLAYLIST_MAX+ }+ val shown = (settled as? Response.Success)?.takeIf { it.data.complete } ?: first+ if (shown is Response.Success) {+ recent[key] = shown// The hearts are known before the page opens.- val p = first.data+ val p = shown.dataif (p.type != "liked" && p.type != "liked-artist") SongPlayer.libraryContains(p.tracks.mapNotNull { s -> s.spotifyTrackId.takeIf { it.isNotBlank() }?.let { "spotify:track:$it" } } + p.uri)+ // The header's cover (the big one) is on storage before the page draws it.+ if (p.coverUri.startsWith("http") && !com.music.spotui.data.DataSaver.metered)+ runCatching { com.bumptech.glide.Glide.with(Graph.app).downloadOnly().load(p.coverUri).submit() }}} catch (t: kotlinx.coroutines.CancellationException) {throw t@@ -221,11 +238,15 @@ class ContextViewModel(reload()}+ /** Set by [reload]: the next load skips the short-lived caches (whole Liked list, playlist songs). */+ private var fresh = false+/** After an edit (name, cover, description): the page from the server again. */fun reload() {val k = key ?: returnrecent.remove(k)key = null+ fresh = true// The likes, the members and who added each song are read again with the new list (a// song just added showed no face on a collaborative playlist).savedChecked = 0@@ -256,12 +277,13 @@ class ContextViewModel(com.music.spotui.data.offline.OfflineCollections.offlinePage(offlineUri)?.let { fromDisk = true; _page.value = Response.Success(it) }if (_page.value !is Response.Success && type == "playlist")com.music.spotui.data.api.ScreenCache.page(id).read()?.let { fromDisk = true; _page.value = Response.Success(it) }+ val force = fresh.also { fresh = false }val flow = when (type) {"album" -> api.getAlbumPage(id)- "liked" -> api.getLikedPage()+ "liked" -> api.getLikedPage(full = force)// id: "<artist id>|<artist name>""liked-artist" -> api.getLikedByArtistPage(id.substringBefore('|'), id.substringAfter('|', ""))- else -> api.getPlaylistPage(id)+ else -> api.getPlaylistPage(id, force = force)}// Liked Songs: a like or unlike anywhere puts the list right at once.if (type == "liked") {@@ -480,11 +502,10 @@ fun ContextScreen(navController: NavController, type: String, id: String) {Box(modifier = Modifier.fillMaxSize().background(PageBackground)) {when (val r = resp) {is Response.Loading -> Loader(SkeletonKind.Header)- is Response.Error -> Text(- r.error,- color = AppText,- modifier = Modifier.align(Alignment.Center).padding(24.dp),- )+ is Response.Error -> com.music.spotui.ui.components.ErrorRetry(+ stringResource(R.string.page_load_failed),+ Modifier.align(Alignment.Center),+ ) { vm.reload() }is Response.Success -> ContextContent(navController, vm, r.data)}}@@ -570,7 +591,7 @@ private fun ContextContent(navController: NavController, vm: ContextViewModel, pwrite = { 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(0xFFF15E6C)) }+ }) { Text(stringResource(R.string.playlist_leave_button), color = AppDestructive) }},dismissButton = { androidx.compose.material3.TextButton(onClick = { leaveAsk = false }) { Text(stringResource(R.string.cancel), color = AppText) } },)@@ -692,10 +713,10 @@ private fun ContextContent(navController: NavController, vm: ContextViewModel, pcontentAlignment = Alignment.Center,modifier = Modifier.padding(12.dp)+ .wideClickable { navController.navigateUp() }.size(40.dp).clip(CircleShape).background(Color.Black.copy(alpha = 0.35f))- .clickable { navController.navigateUp() }) {Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.accessibility_navigate_back), tint = AppText)}@@ -939,7 +960,7 @@ private fun ContextContent(navController: NavController, vm: ContextViewModel, p}val (listed, keys) = shownitemsIndexed(listed, key = { i, _ -> keys[i] }) { _, song ->- com.music.spotui.ui.components.SwipeToQueue(song) { TrackRow(+ com.music.spotui.ui.components.SwipeToQueue(song, animatedRow()) { TrackRow(song = song,showCover = p.type != "album",isCurrent = song.id == currentSongId,@@ -993,7 +1014,7 @@ private fun ContextContent(navController: NavController, vm: ContextViewModel, p) {Box(contentAlignment = Alignment.Center,- modifier = Modifier.padding(horizontal = 8.dp).size(40.dp).clip(CircleShape).clickable { navController.navigateUp() },+ modifier = Modifier.padding(horizontal = 8.dp).wideClickable(horizontal = 8.dp, vertical = 8.dp) { navController.navigateUp() }.size(40.dp),) {Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.accessibility_navigate_back), tint = AppText)}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 de99194e..b7457ee1 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@@ -1,5 +1,6 @@package com.music.spotui.ui.screens+import com.music.spotui.ui.components.wideClickableimport com.music.spotui.ui.theme.toneimport com.music.spotui.ui.theme.AppTextimport com.music.spotui.ui.theme.AppMuted@@ -76,7 +77,7 @@ private fun ScreenHeader(title: String, navController: NavController) {imageVector = Icons.AutoMirrored.Filled.ArrowBack,contentDescription = stringResource(R.string.accessibility_navigate_back),tint = AppText,- modifier = Modifier.size(40.dp).clip(RoundedCornerShape(20.dp)).clickable { navController.popBackStack() }.padding(8.dp),+ modifier = Modifier.wideClickable(horizontal = 8.dp, vertical = 10.dp) { navController.popBackStack() }.size(40.dp).padding(8.dp),)Text(title, fontWeight = FontWeight.Bold, color = AppText, fontSize = 22.sp, maxLines = 1,overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(start = 6.dp))@@ -131,7 +132,7 @@ fun NewReleasesScreen(navController: NavController) {modifier = Modifier.fillMaxWidth().aspectRatio(1f).clip(RoundedCornerShape(6.dp)))Text(t.name, color = AppText, fontSize = 13.sp, fontWeight = FontWeight.Bold, lineHeight = 16.sp, minLines = 2, maxLines = 2,overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(top = 6.dp))- Text(t.detail.ifBlank { t.artists }, color = Color.Gray, fontSize = 11.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)+ Text(t.detail.ifBlank { t.artists }, color = AppMuted, fontSize = 11.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)}}}diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/DownloadsScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/DownloadsScreen.ktindex 1ba17fb0..2eed2512 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/DownloadsScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/DownloadsScreen.kt@@ -1,5 +1,7 @@package com.music.spotui.ui.screens+import com.music.spotui.ui.components.widePressable+import com.music.spotui.ui.theme.AppDestructiveimport com.music.spotui.ui.theme.headerTintimport com.music.spotui.ui.theme.toneimport com.music.spotui.ui.theme.AppText@@ -32,6 +34,7 @@ import androidx.compose.material.icons.filled.MoreVertimport androidx.compose.material3.Iconimport androidx.compose.material3.Textimport androidx.compose.runtime.Composable+import androidx.compose.runtime.derivedStateOfimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.remember@@ -64,6 +67,7 @@ import com.music.spotui.data.offline.OfflineStoreimport com.music.spotui.di.LocalPlayerimport com.music.spotui.di.SongPlayerimport com.music.spotui.ui.components.DownloadBadge+import com.music.spotui.ui.components.animatedRowimport com.music.spotui.ui.components.pressableimport com.music.spotui.ui.theme.AppBackground@@ -73,21 +77,34 @@ import com.music.spotui.ui.theme.AppBackgroundfun DownloadsScreen(navController: NavController) {val context = LocalContext.currentval title = stringResource(R.string.collection_downloaded)- // Snapshot reads: the list follows downloads as they finish.- val tracks = OfflineStore.tracks.values.sortedByDescending { it.addedAt }+ // Snapshot reads: the list follows downloads as they finish. Derived, so a progress tick (which+ // changes no list) leaves the sorted lists and the counts alone instead of rebuilding them.+ val tracks by remember { derivedStateOf { OfflineStore.tracks.values.sortedByDescending { it.addedAt } } }// Shown by where they were downloaded from: each album or playlist downloaded as a whole is one// row (its songs are on its own page), newest first; the songs downloaded on their own follow.- val lists = com.music.spotui.data.offline.OfflineCollections.collections.values.mapNotNull { c ->- val mine = tracks.filter { it.trackId in c.trackIds }- if (mine.isEmpty()) null else c to mine- }.sortedByDescending { (_, mine) -> mine.maxOf { it.addedAt } }- val inLists = lists.flatMapTo(HashSet()) { (_, mine) -> mine.map { it.trackId } }- val singles = tracks.filter { it.trackId !in inLists }- val waiting = OfflineDownloader.requests.values.filter { !OfflineStore.isDownloaded(it.trackId) }+ val lists by remember {+ derivedStateOf {+ com.music.spotui.data.offline.OfflineCollections.collections.values.mapNotNull { c ->+ val mine = tracks.filter { it.trackId in c.trackIds }+ if (mine.isEmpty()) null else c to mine+ }.sortedByDescending { (_, mine) -> mine.maxOf { it.addedAt } }+ }+ }+ val singles by remember {+ derivedStateOf {+ val inLists = lists.flatMapTo(HashSet()) { (_, mine) -> mine.map { it.trackId } }+ tracks.filter { it.trackId !in inLists }+ }+ }+ val waiting by remember { derivedStateOf { OfflineDownloader.requests.values.filter { !OfflineStore.isDownloaded(it.trackId) } } }// A25: 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 stoppable by remember {+ derivedStateOf {+ waiting.count {+ val s = OfflineStore.status[it.trackId]+ s == OfflineStatus.Queued || s is OfflineStatus.Downloading+ }+ }}val np by SongPlayer.nowPlayingval playingHere = LocalPlayer.active.value && LocalPlayer.contextName == title@@ -122,7 +139,7 @@ fun DownloadsScreen(navController: NavController) {painterResource(R.drawable.downloads_cover), null,modifier = Modifier.align(Alignment.CenterHorizontally).size(200.dp).clip(RoundedCornerShape(6.dp)),)- Text(title, color = AppText, fontSize = 26.sp, fontWeight = FontWeight.Bold, modifier = Modifier.padding(top = 20.dp))+ Text(title, color = AppText, fontSize = 26.sp, fontWeight = FontWeight.Bold, maxLines = 2, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(top = 20.dp))val n = tracks.sizeval size = Formatter.formatShortFileSize(context, OfflineStore.totalBytes())Text(pluralStringResource(R.plurals.local_files_count, n, n) + " · " + stringResource(R.string.downloads_size, size),@@ -186,7 +203,7 @@ fun DownloadsScreen(navController: NavController) {val problem = status == OfflineStatus.Failed || status == OfflineStatus.UnavailableRow(verticalAlignment = Alignment.CenterVertically,- modifier = Modifier.fillMaxWidth()+ modifier = animatedRow().fillMaxWidth().pressable(0.97f) { if (status == OfflineStatus.Failed) OfflineDownloader.retry(r.trackId) }.padding(horizontal = 16.dp, vertical = 8.dp),) {@@ -203,7 +220,7 @@ fun DownloadsScreen(navController: NavController) {OfflineStatus.Failed -> stringResource(R.string.download_badge_error_content_description) + " · " + stringResource(R.string.download_retry)else -> stringResource(R.string.download_notification_downloading)}- Text(line, color = if (problem) Color(0xFFE22134) else AppMuted, fontSize = 13.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)+ Text(line, color = if (problem) AppDestructive else AppMuted, fontSize = 13.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)}DownloadBadge(status, size = 20.dp)Spacer(Modifier.width(16.dp))@@ -220,7 +237,7 @@ fun DownloadsScreen(navController: NavController) {}Row(verticalAlignment = Alignment.CenterVertically,- modifier = Modifier.fillMaxWidth().pressable(0.97f) {+ modifier = animatedRow().fillMaxWidth().pressable(0.97f) {val id = c.uri.substringAfterLast(":")navController.navigate(when (c.type) {"album" -> com.music.spotui.ui.navigation.albumRoute(c.name, mine.first().artist, id)@@ -281,8 +298,8 @@ fun DownloadsScreen(navController: NavController) {}Box(contentAlignment = Alignment.Center,- modifier = Modifier.statusBarsPadding().padding(12.dp).size(40.dp).clip(CircleShape)- .background(AppBackground.copy(alpha = 0.4f)).pressable { navController.navigateUp() },+ modifier = Modifier.statusBarsPadding().padding(12.dp).widePressable { navController.navigateUp() }+ .size(40.dp).clip(CircleShape).background(AppBackground.copy(alpha = 0.4f)),) {Icon(Icons.AutoMirrored.Filled.ArrowBack, stringResource(R.string.accessibility_navigate_back), tint = AppText)}diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/EpisodeScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/EpisodeScreen.ktindex 273610b7..0d2e0aa2 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/EpisodeScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/EpisodeScreen.kt@@ -1,5 +1,6 @@package com.music.spotui.ui.screens+import com.music.spotui.ui.components.wideClickableimport com.music.spotui.ui.theme.headerTintimport com.music.spotui.ui.theme.AppText@@ -127,10 +128,10 @@ fun EpisodeScreen(navController: NavController, episodeId: String, fallbackName:contentAlignment = Alignment.Center,modifier = Modifier.padding(12.dp)+ .wideClickable { navController.navigateUp() }.size(40.dp).clip(CircleShape)- .background(Color.Black.copy(alpha = 0.35f))- .clickable { navController.navigateUp() },+ .background(Color.Black.copy(alpha = 0.35f)),) {Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.accessibility_navigate_back), tint = Color.White)}diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/ExtensionDetail.kt b/base/app/src/main/java/com/music/spotui/ui/screens/ExtensionDetail.ktindex 96889a89..e408601e 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/ExtensionDetail.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/ExtensionDetail.kt@@ -75,7 +75,7 @@ internal fun authorLine(author: String, repo: String?): String {/** Updates from the repository are refused: its host ids changed (re-registered or transferred). */@Composable-private fun RepoChangedWarning() {+internal fun RepoChangedWarning() {Column(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 6.dp).clip(RoundedCornerShape(12.dp)).background(Warning.copy(alpha = 0.10f)).padding(12.dp)) {Text(stringResource(R.string.update_repo_changed_title), color = Warning, fontSize = 14.sp, fontWeight = FontWeight.SemiBold)Text(stringResource(R.string.update_repo_changed_body), color = AppMuted, fontSize = 12.sp, modifier = Modifier.padding(top = 2.dp))@@ -125,7 +125,7 @@ private fun Detail(label: Int, value: String, mono: Boolean = false) {@OptIn(ExperimentalLayoutApi::class)@Composable-private fun Tags(tags: List<String>) {+internal fun Tags(tags: List<String>) {if (tags.isEmpty()) returnFlowRow(Modifier.padding(horizontal = 20.dp, vertical = 6.dp), horizontalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {tags.forEach { ExtPill("#$it", AppMuted, tone(0xFF2A2A2A)) }@@ -353,7 +353,12 @@ fun ExtensionScreen(navController: NavController, id: String) {confirmButton = {TextButton(onClick = {uninstall = false- scope.launch { Extensions.uninstall(id); navController.popBackStack() }+ // Back out only if the page is still the one on top (the uninstall takes a moment).+ val page = navController.currentBackStackEntry+ scope.launch {+ Extensions.uninstall(id)+ if (navController.currentBackStackEntry == page) navController.popBackStack()+ }}) { Text(stringResource(R.string.extension_uninstall), color = Warning) }},dismissButton = { TextButton(onClick = { uninstall = false }) { Text(stringResource(R.string.extensions_cancel), color = AppText) } },@@ -361,21 +366,30 @@ fun ExtensionScreen(navController: NavController, id: String) {InstallPrompt()}+/** An option of the extension (manifest `settings`) as text: what the user set, else its default. */+internal fun settingInitial(id: String, s: Setting): String {+ val stored = Extensions.settingValues(id)[s.key]+ return (stored?.let { runCatching { kotlinx.serialization.json.Json.parseToJsonElement(it) }.getOrNull() } ?: s.default)+ ?.let { runCatching { it.jsonPrimitive.contentOrNull }.getOrNull() }.orEmpty()+}++/** Saves [v] as JSON, typed as the option is; a number that is not one saves nothing. */+internal fun saveSetting(id: String, s: Setting, v: String) {+ val json = when (s.type) {+ "toggle" -> JsonPrimitive(v == "true").toString()+ "number" -> v.toLongOrNull()?.let { JsonPrimitive(it).toString() } ?: v.toDoubleOrNull()?.let { JsonPrimitive(it).toString() }+ else -> JsonPrimitive(v).toString()+ }+ Extensions.setSetting(id, s.key, json)+}+/** One of the extension's options (manifest `settings`), saved as JSON as it changes. */@Composableprivate fun SettingEditor(id: String, s: Setting) {- val stored = remember(id, s.key) { Extensions.settingValues(id)[s.key] }- val initial = (stored?.let { runCatching { kotlinx.serialization.json.Json.parseToJsonElement(it) }.getOrNull() } ?: s.default)- ?.let { runCatching { it.jsonPrimitive.contentOrNull }.getOrNull() }.orEmpty()- var value by remember(id, s.key) { mutableStateOf(initial) }+ var value by remember(id, s.key) { mutableStateOf(settingInitial(id, s)) }fun save(v: String) {value = v- val json = when (s.type) {- "toggle" -> JsonPrimitive(v == "true").toString()- "number" -> v.toLongOrNull()?.let { JsonPrimitive(it).toString() } ?: v.toDoubleOrNull()?.let { JsonPrimitive(it).toString() }- else -> JsonPrimitive(v).toString()- }- Extensions.setSetting(id, s.key, json)+ saveSetting(id, s, v)}when (s.type) {"toggle" -> SwitchRow(s.label, s.description, value == "true") { save(it.toString()) }@@ -411,7 +425,7 @@ private fun SettingEditor(id: String, s: Setting) {// ── GitHub: the update card, report, rating ──/** The toast after "Check for updates". */-private fun checkResult(r: ExtensionUpdates.Result): Int = when (r) {+internal fun checkResult(r: ExtensionUpdates.Result): Int = when (r) {ExtensionUpdates.Result.UP_TO_DATE, ExtensionUpdates.Result.NOT_FROM_GITHUB -> R.string.extension_check_up_to_dateExtensionUpdates.Result.APPLIED -> R.string.extension_check_appliedExtensionUpdates.Result.WAITING -> R.string.update_check_waiting@@ -431,7 +445,7 @@ private fun checkResult(r: ExtensionUpdates.Result): Int = when (r) {* A protected surface, like the install prompt.*/@Composable-private fun UpdateNeedsOk(name: String, from: String, p: com.music.spotui.extensions.PendingUpdate, onAccept: () -> Unit, onKeep: () -> Unit) {+internal fun UpdateNeedsOk(name: String, from: String, p: com.music.spotui.extensions.PendingUpdate, onAccept: () -> Unit, onKeep: () -> Unit) {com.music.spotui.extensions.ProtectedSurfaceEffect(app.myspoti.extensions.ProtectedSurface.INSTALL)val critical = p.changes.any { it.critical }val tint = if (critical) Warning else AppAccent@@ -465,7 +479,7 @@ private fun UpdateNeedsOk(name: String, from: String, p: com.music.spotui.extens* until the user accepts all it lists, once, with the same tick as the install prompt.*/@Composable-private fun RefusedNeedsOk(refused: List<Ask>, onAccept: () -> Unit) {+internal fun RefusedNeedsOk(refused: List<Ask>, onAccept: () -> Unit) {com.music.spotui.extensions.ProtectedSurfaceEffect(app.myspoti.extensions.ProtectedSurface.INSTALL)Column(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 6.dp).clip(RoundedCornerShape(12.dp)).background(Warning.copy(alpha = 0.10f)).padding(12.dp)) {Text(stringResource(R.string.extension_refused_title), color = AppText, fontSize = 14.sp, fontWeight = FontWeight.SemiBold)@@ -519,7 +533,7 @@ private fun ReportButton(id: String, version: String, repo: String?, sha256: Str/** 👍 / 👎 on the extension's ratings issue; hidden while the GitHub OAuth app is not set ([app.myspoti.extensions.GitHubAuth.enabled]). */@Composable-private fun RateButtons(repo: String) {+internal fun RateButtons(repo: String) {if (!app.myspoti.extensions.GitHubAuth.enabled) returnval ctx = LocalContext.currentval scope = rememberCoroutineScope()diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/ExtensionPage.kt b/base/app/src/main/java/com/music/spotui/ui/screens/ExtensionPage.ktindex 1652b39e..e6e6879c 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/ExtensionPage.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/ExtensionPage.kt@@ -75,6 +75,14 @@ fun ExtensionPageScreen(navController: NavController, id: String) {val network = Action.NETWORK.key in grantedval any = Action.NETWORK_ANY in granted+ if (com.music.spotui.ui.navigation.isImmersive()) {+ com.music.spotui.ui.immersive.pages.ImmersiveExtensionPageFrame(+ title = loaded?.getOrNull()?.title ?: e?.name ?: id,+ subtitle = stringResource(R.string.ext_from, e?.name ?: id),+ onBack = { navController.popBackStack() },+ ) { ExtensionPageBody(id, loaded, hosts, network, any, shield.isNotEmpty()) }+ return+ }Column(Modifier.fillMaxSize().background(AppBackground).statusBarsPadding()) {Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(4.dp)) {IconButton(onClick = { navController.popBackStack() }) {@@ -86,45 +94,58 @@ fun ExtensionPageScreen(navController: NavController, id: String) {}}Box(Modifier.fillMaxWidth().weight(1f).navigationBarsPadding()) {- val page = loaded?.getOrNull()- when {- loaded == null -> CircularProgressIndicator(Modifier.align(Alignment.Center), color = AppAccent)- page == null -> Text(stringResource(R.string.ext_page_failed), color = AppMuted, modifier = Modifier.padding(20.dp))- else -> {- val html = remember(page) { PageNetwork.wrap(page.html, PageNetwork.csp(hosts, network, any)) }- val web = remember { arrayOfNulls<WebView>(1) }- AndroidView(- modifier = Modifier.fillMaxSize(),- factory = { ctx ->- WebView(ctx).apply {- web[0] = this- settings.javaScriptEnabled = true- settings.allowFileAccess = false- settings.allowContentAccess = false- settings.domStorageEnabled = false- settings.setGeolocationEnabled(false)- settings.javaScriptCanOpenWindowsAutomatically = false- settings.setSupportMultipleWindows(false)- settings.mediaPlaybackRequiresUserGesture = true- settings.mixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW- settings.cacheMode = WebSettings.LOAD_NO_CACHE- CookieManager.getInstance().setAcceptThirdPartyCookies(this, false)- setBackgroundColor(android.graphics.Color.BLACK)- webViewClient = SandboxClient(hosts, network, any)- addJavascriptInterface(PageBridge(id), "MyspotiPage")- Extensions.attachPage(id) { json -> evaluateJavascript("window.dispatchEvent(new MessageEvent('message', { data: $json }));", null) }- loadDataWithBaseURL(null, html, "text/html", "utf-8", null)- }- },- update = { wv ->- if (shield.isNotEmpty()) { wv.onPause(); wv.visibility = View.INVISIBLE } else { wv.onResume(); wv.visibility = View.VISIBLE }- },- )- DisposableEffect(id) {- onDispose {- Extensions.attachPage(id, null)- web[0]?.destroy()+ ExtensionPageBody(id, loaded, hosts, network, any, shield.isNotEmpty())+ }+ }+}++/**+ * What an extension's page shows in the space under its header: a spinner while it loads, the+ * failure, or the sandboxed WebView (hidden and paused while [shielded], a protected surface is on+ * screen). The same in both looks, which only differ in the frame around it.+ */+@SuppressLint("SetJavaScriptEnabled", "JavascriptInterface")+@Composable+internal fun ExtensionPageBody(id: String, loaded: Result<PageContent?>?, hosts: List<String>, network: Boolean, any: Boolean, shielded: Boolean) {+ Box(Modifier.fillMaxSize()) {+ val page = loaded?.getOrNull()+ when {+ loaded == null -> CircularProgressIndicator(Modifier.align(Alignment.Center), color = AppAccent)+ page == null -> Text(stringResource(R.string.ext_page_failed), color = AppMuted, modifier = Modifier.padding(20.dp))+ else -> {+ val html = remember(page) { PageNetwork.wrap(page.html, PageNetwork.csp(hosts, network, any)) }+ val web = remember { arrayOfNulls<WebView>(1) }+ AndroidView(+ modifier = Modifier.fillMaxSize(),+ factory = { ctx ->+ WebView(ctx).apply {+ web[0] = this+ settings.javaScriptEnabled = true+ settings.allowFileAccess = false+ settings.allowContentAccess = false+ settings.domStorageEnabled = false+ settings.setGeolocationEnabled(false)+ settings.javaScriptCanOpenWindowsAutomatically = false+ settings.setSupportMultipleWindows(false)+ settings.mediaPlaybackRequiresUserGesture = true+ settings.mixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW+ settings.cacheMode = WebSettings.LOAD_NO_CACHE+ CookieManager.getInstance().setAcceptThirdPartyCookies(this, false)+ setBackgroundColor(android.graphics.Color.BLACK)+ webViewClient = SandboxClient(hosts, network, any)+ addJavascriptInterface(PageBridge(id), "MyspotiPage")+ Extensions.attachPage(id) { json -> evaluateJavascript("window.dispatchEvent(new MessageEvent('message', { data: $json }));", null) }+ loadDataWithBaseURL(null, html, "text/html", "utf-8", null)}+ },+ update = { wv ->+ if (shielded) { wv.onPause(); wv.visibility = View.INVISIBLE } else { wv.onResume(); wv.visibility = View.VISIBLE }+ },+ )+ DisposableEffect(id) {+ onDispose {+ Extensions.attachPage(id, null)+ web[0]?.destroy()}}}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 1910d91b..4c435cf8 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@@ -119,8 +119,14 @@ internal class PendingInstall(val zip: ByteArray, val pkg: ExtensionPackage, valinternal val pending = MutableStateFlow<PendingInstall?>(null)-internal fun toastError(ctx: Context, t: Throwable) =- Toast.makeText(ctx, ctx.getString(R.string.extensions_error, t.message ?: t.toString()), Toast.LENGTH_LONG).show()+/** Runs installs the user confirmed, past the prompt that started them. */+private val installScope = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.SupervisorJob() + kotlinx.coroutines.Dispatchers.Main)++/** A failure said in a toast; a cancelled job (its screen closed) is not one. */+internal fun toastError(ctx: Context, t: Throwable) {+ if (t is kotlinx.coroutines.CancellationException) return+ Toast.makeText(ctx.applicationContext, ctx.getString(R.string.extensions_error, t.message ?: t.toString()), Toast.LENGTH_LONG).show()+}/** Reads [zip] and opens the install prompt; a refused package says why. */internal fun offer(ctx: Context, zip: ByteArray, source: String, origin: app.myspoti.extensions.Origin? = null) {@@ -178,7 +184,6 @@ internal fun InstallPrompt() {val p = pending.collectAsState().value ?: returnProtectedSurfaceEffect(ProtectedSurface.INSTALL)val ctx = LocalContext.current- val scope = rememberCoroutineScope()val registry by Extensions.registry.collectAsState()val m = p.pkg.manifestval plan = p.plan@@ -231,7 +236,9 @@ internal fun InstallPrompt() {onClick = {pending.value = nullval choice = keepNew.toMap()- scope.launch {+ // Not the prompt's scope: closing the prompt cancelled it, and the cancelled+ // (yet finished) install showed as an error.+ installScope.launch {runCatching { Extensions.install(p.zip, p.pkg, Grants.keys(m), p.source, clashes, { choice[it] != false }, noticeAccepted = true, origin = p.origin) }.onFailure { toastError(ctx, it) }}},@@ -295,7 +302,7 @@ internal fun ClashDialog(m: Manifest, clashes: List<Clash>, onDismiss: () -> UniAlertDialog(onDismissRequest = onDismiss,containerColor = tone(0xFF282828),- title = { Text(m.name, color = AppText) },+ title = { Text(m.name, color = AppText, maxLines = 2, overflow = TextOverflow.Ellipsis) },text = { Column(Modifier.verticalScroll(rememberScrollState())) { ClashChoices(m.name, clashes, keepNew) } },confirmButton = { TextButton(onClick = { onDone(keepNew.toMap()) }) { Text(stringResource(R.string.ext_clash_ok), color = AppAccent) } },dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.extensions_cancel), color = AppText) } },@@ -375,17 +382,31 @@ internal fun categoryLabel(c: Category?): Int = when (c) {@Composableinternal fun ExtIcon(id: String, name: String, iconUrl: String?, bytes: ByteArray?, size: Dp = 44.dp) {val tint = remember(id) { Color.hsv(((id.hashCode() and 0x7fffffff) % 360).toFloat(), 0.45f, 0.58f) }- val bitmap = remember(bytes) { bytes?.let { runCatching { BitmapFactory.decodeByteArray(it, 0, it.size)?.asImageBitmap() }.getOrNull() } }+ // Decoded off the main thread, at the size shown (an icon file can be a large picture).+ val targetPx = with(androidx.compose.ui.platform.LocalDensity.current) { size.roundToPx() }+ val bitmap by androidx.compose.runtime.produceState<androidx.compose.ui.graphics.ImageBitmap?>(null, bytes, targetPx) {+ value = bytes?.let { b -> withContext(Dispatchers.Default) { runCatching { decodeSampled(b, targetPx) }.getOrNull() } }+ }+ val icon = bitmapBox(Modifier.size(size).clip(RoundedCornerShape(size / 4)).background(tint), contentAlignment = Alignment.Center) {Text(name.firstOrNull { it.isLetterOrDigit() }?.uppercase() ?: "?", color = Color.White, fontWeight = FontWeight.Bold, fontSize = (size.value * 0.42f).sp)when {- bitmap != null -> Image(bitmap, null, Modifier.fillMaxSize(), contentScale = ContentScale.Crop)+ icon != null -> Image(icon, null, Modifier.fillMaxSize(), contentScale = ContentScale.Crop)iconUrl != null && iconUrl.startsWith("https://") && !com.music.spotui.data.DataSaver.active ->GlideImage(model = iconUrl, contentDescription = null, modifier = Modifier.fillMaxSize(), contentScale = ContentScale.Crop)}}}+/** [bytes] as a bitmap no larger than needed for [targetPx] on both sides (a power-of-two sample). */+private fun decodeSampled(bytes: ByteArray, targetPx: Int): androidx.compose.ui.graphics.ImageBitmap? {+ val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }+ BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)+ var sample = 1+ while (bounds.outWidth / (sample * 2) >= targetPx && bounds.outHeight / (sample * 2) >= targetPx) sample *= 2+ return BitmapFactory.decodeByteArray(bytes, 0, bytes.size, BitmapFactory.Options().apply { inSampleSize = sample })?.asImageBitmap()+}+/** An entry's icon address, resolved against its index's. */internal fun iconOf(repo: String, e: Catalog.Entry): String? =e.iconAddress()?.let { runCatching { Catalog.resolve(repo, it) }.getOrNull() }diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/HomeScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/HomeScreen.ktindex 21d99d2f..69b8b524 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/HomeScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/HomeScreen.kt@@ -3,6 +3,7 @@ package com.music.spotui.ui.screensimport com.music.spotui.ui.theme.toneimport com.music.spotui.ui.theme.AppTextimport com.music.spotui.ui.theme.AppMuted+import com.music.spotui.ui.theme.AppAccentimport com.music.spotui.ui.components.SkeletonKindimport com.music.spotui.ui.components.pressable@@ -129,7 +130,7 @@ fun HomeScreen(navController: NavController){textAlign = TextAlign.Center,)if (home is Response.Error) androidx.compose.material3.TextButton(onClick = { homeViewModel.retry() }) {- Text(stringResource(R.string.home_retry), color = Color(0xFF1DB954))+ Text(stringResource(R.string.home_retry), color = AppAccent)}}}@@ -172,10 +173,14 @@ fun HomeFeedContent(navController: NavController, feed: HomeFeedModel, facet: St// ("Jump back in", "Made For …"), it renders as a titled carousel first,// not force-squeezed into the grid.// Podcasts are off for now: their shows and episodes leave the feed.- val sections = if (com.music.spotui.data.api.Features.PODCASTS) feed.sections+ // Kept between recompositions: a new list for every one of them would restart the rows below.+ val sections = remember(feed) {+ if (com.music.spotui.data.api.Features.PODCASTS) feed.sectionselse feed.sections.map { s -> s.copy(items = s.items.filterNot { it is HomeItem.Show }) }.filter { it.items.isNotEmpty() }- val gridSection = sections.firstOrNull()?.takeIf { it.title.isBlank() }- val carousels = if (gridSection != null) sections.drop(1) else sections+ }+ val gridSection = remember(sections) { sections.firstOrNull()?.takeIf { it.title.isBlank() } }+ val carousels = remember(sections, gridSection) { if (gridSection != null) sections.drop(1) else sections }+ val carouselKeys = remember(carousels) { uniqueKeys(carousels.map { it.title }) }// The shortcuts at the top load in the background, ready before a tap.androidx.compose.runtime.LaunchedEffect(gridSection?.items?.map { it.name }) {val top = gridSection?.items.orEmpty().take(8).mapNotNull { item ->@@ -230,7 +235,7 @@ fun HomeFeedContent(navController: NavController, feed: HomeFeedModel, facet: StHomeShortcutGrid(navController, section.items.take(8))}}- items(carousels.size) { i ->+ items(carousels.size, key = { carouselKeys[it] }) { i ->HomeFeedSection(navController, carousels[i])}// Sections from extensions (home.sections), after Spotify's own, each under its extension's name.@@ -251,21 +256,24 @@ private fun HomeHeaderRow(navController: NavController, facet: String, onFacet:}Row(verticalAlignment = Alignment.CenterVertically,- modifier = Modifier- .fillMaxWidth()- .padding(top = 10.dp, bottom = 10.dp),+ // The row's 10 dp above and below sit in each child instead, so the avatar's tap area+ // takes them in (and the margin up to the separator) without moving anything.+ modifier = Modifier.fillMaxWidth(),) {val avatarUrl = com.music.spotui.data.api.ProfileCache.imageUrlval initial = com.music.spotui.data.api.ProfileCache.name?.trim()?.firstOrNull()?.uppercase() ?: "•"+ Box(+ modifier = Modifier+ .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) { showProfile = true }+ .padding(start = 16.dp, end = 10.dp, top = 10.dp, bottom = 10.dp),+ ) {Box(contentAlignment = Alignment.Center,modifier = Modifier- .padding(start = 16.dp).size(34.dp).clip(CircleShape)- .background(Color(0xFFE8622C))- .clickable { showProfile = true },+ .background(Color(0xFFE8622C)),) {if (avatarUrl != null) {GlideImage(@@ -284,11 +292,12 @@ private fun HomeHeaderRow(navController: NavController, facet: String, onFacet:)}}+ }// B31: a separator between the profile and the options, reported missing from this// header (the sheets already carry one).Box(modifier = Modifier- .padding(start = 10.dp)+ .padding(vertical = 10.dp).size(width = 1.dp, height = 22.dp).background(tone(0xFF3E3E3E)),)@@ -299,7 +308,7 @@ private fun HomeHeaderRow(navController: NavController, facet: String, onFacet:modifier = Modifier.weight(1f).horizontalScroll(androidx.compose.foundation.rememberScrollState())- .padding(start = 12.dp, end = 8.dp),+ .padding(start = 12.dp, end = 8.dp, top = 10.dp, bottom = 10.dp),) {// Spotify's home chips; tapping the selected one goes back to "Tout".HomePill(stringResource(R.string.filter_chip_all_label), selected = facet.isEmpty()) { onFacet("") }@@ -373,6 +382,16 @@ private fun HomeShortcutGrid(navController: NavController, items: List<HomeItem>}}+/** A key per entry that stays with it while the others around it change: [raw], with a counter on repeats. */+private fun uniqueKeys(raw: List<String>): List<String> {+ val seen = HashMap<String, Int>()+ return raw.map { k ->+ val n = (seen[k] ?: 0) + 1+ seen[k] = n+ if (n == 1) k else "$k#$n"+ }+}+@Composableprivate fun HomeFeedSection(navController: NavController, section: HomeSection) {Text(@@ -384,8 +403,9 @@ private fun HomeFeedSection(navController: NavController, section: HomeSection)overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,modifier = Modifier.padding(16.dp, 20.dp, 16.dp, 4.dp),)+ val keys = remember(section) { uniqueKeys(section.items.map { it.name + "|" + it.imageUrl }) }LazyRow(contentPadding = androidx.compose.foundation.layout.PaddingValues(10.dp, 0.dp)) {- items(section.items.size) { i ->+ items(section.items.size, key = { keys[it] }) { i ->HomeFeedCard(section.items[i]) { onHomeItemClick(navController, section.items[i]) }}}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 5258af76..82fb1c3f 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@@ -1,5 +1,6 @@package com.music.spotui.ui.screens+import com.music.spotui.ui.theme.AppDestructiveimport com.music.spotui.ui.theme.toneimport com.music.spotui.ui.theme.AppTextimport com.music.spotui.ui.theme.AppMuted@@ -393,7 +394,7 @@ fun FolderScreen(navController: NavController, uri: String, initialName: String)// The folder is gone from the library at once; a refusal brings it back.LibraryFolders.delete(context, uri)navController.navigateUp()- }) { Text(stringResource(R.string.actions_picker_delete), color = Color(0xFFF15E6C)) }+ }) { Text(stringResource(R.string.actions_picker_delete), color = AppDestructive) }},dismissButton = { androidx.compose.material3.TextButton(onClick = { deletingFolder = false }) { Text(stringResource(R.string.cancel), color = AppText) } },)@@ -634,7 +635,7 @@ fun LibraryItemSheet(entry: LibraryEntry, onDismiss: () -> Unit, onChanged: () -text = { Text(stringResource(R.string.folder_delete_confirm, entry.name), color = AppText) },confirmButton = {androidx.compose.material3.TextButton(onClick = { deleting = false; act(LibraryEdits.Remove(entry.uri)) { api.library.deleteFolder(entry.uri) } }) {- Text(stringResource(R.string.actions_picker_delete), color = Color(0xFFF15E6C))+ Text(stringResource(R.string.actions_picker_delete), color = AppDestructive)}},dismissButton = { androidx.compose.material3.TextButton(onClick = { deleting = false }) { Text(stringResource(R.string.cancel), color = AppText) } },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 8558540e..cca82b00 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@@ -3,6 +3,7 @@ package com.music.spotui.ui.screensimport com.music.spotui.ui.theme.toneimport com.music.spotui.ui.theme.AppTextimport com.music.spotui.ui.theme.AppMuted+import com.music.spotui.ui.theme.AppAccentimport androidx.compose.material.icons.filled.MoreVertimport androidx.compose.material.icons.filled.PushPin@@ -134,8 +135,8 @@ fun LibraryScreen(navController: NavController) {val context = LocalContext.current// Spotify-style layout toggle: rows or a 3-column grid, persisted across runs.var gridView by remember { mutableStateOf(isLibraryGridView(context)) }- var searchActive by remember { mutableStateOf(false) }- var searchQuery by remember { mutableStateOf("") }+ var searchActive by androidx.compose.runtime.saveable.rememberSaveable { mutableStateOf(false) }+ var searchQuery by androidx.compose.runtime.saveable.rememberSaveable { mutableStateOf("") }// The filter chips under the title; the chosen one is kept while the screen is open.var chip by androidx.compose.runtime.saveable.rememberSaveable { mutableStateOf(com.music.spotui.data.local.LibraryChip.ALL) }@@ -862,7 +863,7 @@ private fun AccountSheet(Column {Text(account.name.ifBlank { stringResource(R.string.spotify_user) }, color = AppText, fontSize = 18.sp, fontWeight = FontWeight.Bold, maxLines = 1, overflow = TextOverflow.Ellipsis)if (account.email.isNotBlank()) Text(account.email, color = AppMuted, fontSize = 13.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)- if (account.plan.isNotBlank()) Text("Spotify ${account.plan}", color = Color(0xFF1DB954), fontSize = 12.sp, fontWeight = FontWeight.Medium)+ if (account.plan.isNotBlank()) Text(stringResource(R.string.spotify_plan, account.plan), color = AppAccent, fontSize = 12.sp, fontWeight = FontWeight.Medium)}}HorizontalDivider(color = tone(0xFF2A2A2A))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 847e4167..3d43bfa9 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@@ -4,6 +4,7 @@ import com.music.spotui.ui.theme.headerTintimport com.music.spotui.ui.theme.toneimport com.music.spotui.ui.theme.AppTextimport com.music.spotui.ui.theme.AppMuted+import com.music.spotui.ui.theme.AppAccentimport kotlinx.coroutines.launchimport androidx.compose.foundation.layout.navigationBarsPadding@@ -255,7 +256,7 @@ internal fun LocalFoldersSheet(onChanged: () -> Unit, onDismiss: () -> Unit) {version++onChanged()},- colors = androidx.compose.material3.SwitchDefaults.colors(checkedTrackColor = Color(0xFF1DB954)),+ colors = androidx.compose.material3.SwitchDefaults.colors(checkedTrackColor = AppAccent),)}}diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/LyricsScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/LyricsScreen.ktindex e401ebab..3e11e484 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/LyricsScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/LyricsScreen.kt@@ -856,6 +856,8 @@ fun LyricsOverlay(// Window the container starts from, in this host's pixels; null = slide-up fallback.var from by remember { mutableStateOf<Rect?>(null) }val host = remember { arrayOfNulls<LayoutCoordinates>(1) }+ // "Remove animations": the lyrics are there, or gone, at once.+ val reduce = com.music.spotui.ui.look.rememberReduceMotion()fun cardRect(): Rect? {val h = host[0]?.takeIf { it.isAttached } ?: return null@@ -872,12 +874,12 @@ fun LyricsOverlay(from = cardRect()mounted = trueval spec = if (from != null) tween<Float>(560, easing = FastOutSlowInEasing) else tween(250, easing = EaseOut)- progress.animateTo(1f, spec)+ if (reduce) progress.snapTo(1f) else progress.animateTo(1f, spec)} else if (mounted) {// Fold into the card where it is now; a slide-up opening slides back down.if (from != null) cardRect()?.let { from = it }val spec = if (from != null) tween<Float>(470, easing = FastOutSlowInEasing) else tween(200, easing = EaseOut)- progress.animateTo(0f, spec)+ if (reduce) progress.snapTo(0f) else progress.animateTo(0f, spec)mounted = false}}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 ea006532..c78cd8e4 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@@ -80,6 +80,7 @@ import androidx.compose.runtime.derivedStateOfimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.remember+import androidx.compose.runtime.saveable.rememberSaveableimport com.music.spotui.ui.components.pressableimport kotlinx.coroutines.launchimport androidx.compose.ui.graphics.graphicsLayer@@ -163,11 +164,12 @@ fun PlayerScreen(navController: NavController) {val energy by EnergySettings.state.collectAsStateWithLifecycle()// Liked state is Spotify's (LibraryAPI), pushed by the engine.val isLiked = playerViewModel.likeState- var showMenu by remember { mutableStateOf(false) }- var showLyrics by remember { mutableStateOf(false) }+ val titleScope = androidx.compose.runtime.rememberCoroutineScope()+ var showMenu by rememberSaveable { mutableStateOf(false) }+ var showLyrics by rememberSaveable { mutableStateOf(false) }var showSavedIn by remember { mutableStateOf(false) }var showDevices by remember { mutableStateOf(false) }- var showQueue by remember { mutableStateOf(false) }+ var showQueue by rememberSaveable { mutableStateOf(false) }// Immersive view (official app: a tap on the artwork): artwork full-bleed, no top bar,// no title / controls block, only one compact strip. A second tap leaves it.var immersive by remember { mutableStateOf(false) }@@ -211,7 +213,7 @@ fun PlayerScreen(navController: NavController) {// Known cover (warmed by the mini player): the colour is there from the first frame.var coverColor by remember {- mutableStateOf(Palette.cachedSecond(songCoverUri) ?: Color(0xFF121212))+ mutableStateOf(Palette.cachedSecond(songCoverUri) ?: AppBackground)}LaunchedEffect(songCoverUri) {// Known: kept as it is (extracted again it could come out a shade off, and the background@@ -596,8 +598,21 @@ fun PlayerScreen(navController: NavController) {likeSong = { nowPlayingSong(playerViewModel) },adPlaying = adPlaying,onTitleClick = {- val albumId = np.albumUri.substringAfterLast(":")- if (albumId.isNotBlank()) navController.navigate(albumRoute(playerViewModel.currentSongAlbum.value, songSinger, albumId))+ // A radio's tracks may come without their album: asked from the track, else+ // by the album's name (the album page resolves it).+ val albumId = np.albumUri.substringAfterLast(":").ifBlank { nowPlayingSong(playerViewModel).albumId }+ val albumName = playerViewModel.currentSongAlbum.value+ if (albumId.isNotBlank()) navController.navigate(albumRoute(albumName, songSinger, albumId))+ else {+ val trackId = SongPlayer.currentTrackId+ titleScope.launch {+ val resolved = if (trackId.isBlank()) "" else kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {+ runCatching { app.myspoti.host.android.MyspotiRuntime.api.catalog.track("spotify:track:$trackId").album?.uri }+ .getOrNull()?.substringAfterLast(":").orEmpty()+ }+ if (resolved.isNotBlank() || albumName.isNotBlank()) navController.navigate(albumRoute(albumName, songSinger, resolved))+ }+ }},onArtistClick = {playerViewModel.goToArtist(SongPlayer.currentTrackId, songSinger) { route ->@@ -834,7 +849,7 @@ private fun playingFromLabels(np: SongPlayer.NowPlaying, fallbackName: String):val type = np.contextUri.split(":").getOrNull(1).orEmpty()val name = contextDisplayName(np, fallbackName)return when {- np.contextUri.contains(":collection") -> stringResource(R.string.context_type_description_collection_your_library) to stringResource(R.string.collection_liked_songs_title)+ isLikedContext(np.contextUri) -> stringResource(R.string.context_type_description_collection_your_library) to stringResource(R.string.collection_liked_songs_title)type == "playlist" -> stringResource(R.string.context_type_description_playlist) to nametype == "album" -> stringResource(R.string.context_type_description_album) to nametype == "artist" -> stringResource(R.string.context_type_description_artist) to name@@ -844,14 +859,28 @@ private fun playingFromLabels(np: SongPlayer.NowPlaying, fallbackName: String):}}-/** Route of the page the music is playing from (playlist, album, artist, liked). */+/** Spotify's uri of the user's Liked Songs: spotify:collection:tracks, or the older spotify:user:<name>:collection (by one artist: ...:artist:<id>). */+private val LIKED_CONTEXT = Regex("spotify:(collection(:tracks)?|user:[^:]+:collection(:artist:[^:]+)?)")++/** Only Liked Songs itself, not another collection (episodes) nor a radio that mentions one. */+private fun isLikedContext(uri: String) = LIKED_CONTEXT.matches(uri)++/**+ * Route of the page the music is playing from (playlist, album, artist, liked); null when there+ * is none to open. A radio (spotify:station:...) has no page of its own: it never falls back to+ * Liked Songs.+ */private fun contextRoute(np: SongPlayer.NowPlaying): String? {val parts = np.contextUri.split(":")val id = parts.getOrNull(2).orEmpty()// B26: opening that page again must carry the name the header shows.val name = contextDisplayName(np, "")return when {- np.contextUri.contains(":collection") -> Routes.Liked.route+ isLikedContext(np.contextUri) -> Routes.Liked.route+ parts.getOrNull(1) == "station" -> null+ // The older form of a playlist's uri: spotify:user:<name>:playlist:<id>.+ parts.getOrNull(1) == "user" && parts.getOrNull(3) == "playlist" && parts.getOrNull(4).orEmpty().isNotBlank() ->+ com.music.spotui.ui.navigation.playlistRoute(parts[4], name)parts.getOrNull(1) == "playlist" && id.isNotBlank() -> com.music.spotui.ui.navigation.playlistRoute(id, name)parts.getOrNull(1) == "album" && id.isNotBlank() -> albumRoute(name, "", id)parts.getOrNull(1) == "artist" && id.isNotBlank() -> com.music.spotui.ui.navigation.artistRoute(name, id)@@ -940,7 +969,7 @@ fun ExplicitBadge(modifier: Modifier = Modifier) {) {// No font padding + trimmed line height so the "E" sits dead centre.Text(- "E",+ stringResource(R.string.explicit_badge),color = Color.Black,fontWeight = FontWeight.Bold,style = androidx.compose.ui.text.TextStyle(@@ -963,8 +992,10 @@ fun LikeButton(liked: Boolean, size: androidx.compose.ui.unit.Dp = 28.dp, onClic// Nothing runs on first display, so long lists do not animate while scrolling.val scale = remember { androidx.compose.animation.core.Animatable(1f) }val firstShown = remember { booleanArrayOf(true) }+ val reduce = com.music.spotui.ui.look.rememberReduceMotion()LaunchedEffect(liked) {if (firstShown[0]) { firstShown[0] = false; return@LaunchedEffect }+ if (reduce) return@LaunchedEffectscale.snapTo(0.6f)scale.animateTo(1f, androidx.compose.animation.core.spring(dampingRatio = 0.4f, stiffness = 600f))}@@ -975,13 +1006,25 @@ fun LikeButton(liked: Boolean, size: androidx.compose.ui.unit.Dp = 28.dp, onClicinteractionSource = remember { MutableInteractionSource() },indication = null,) { onClick() }- if (liked) {- Box(contentAlignment = Alignment.Center, modifier = mod.clip(CircleShape).background(com.music.spotui.ui.theme.AppAccent)) {- // The official check is bolder, with round ends.- Icon(PlayerIcons.check, contentDescription = stringResource(R.string.remove_from_liked), tint = Color.Black, modifier = Modifier.size(size * 0.7f))+ // The disc fills and the glyphs cross-fade, instead of one swapping for the other.+ val disc by androidx.compose.animation.animateColorAsState(+ if (liked) com.music.spotui.ui.theme.AppAccent else Color.Transparent,+ if (reduce) androidx.compose.animation.core.snap() else androidx.compose.animation.core.tween(180),+ label = "likeDisc",+ )+ Box(contentAlignment = Alignment.Center, modifier = mod.background(disc, CircleShape)) {+ androidx.compose.animation.Crossfade(+ liked,+ animationSpec = if (reduce) androidx.compose.animation.core.snap() else androidx.compose.animation.core.tween(180),+ label = "likeGlyph",+ ) { on ->+ if (on) {+ // The official check is bolder, with round ends.+ Icon(PlayerIcons.check, contentDescription = stringResource(R.string.remove_from_liked), tint = Color.Black, modifier = Modifier.size(size * 0.7f))+ } else {+ Icon(painterResource(id = R.drawable.ic_add), contentDescription = stringResource(R.string.aligned_curation_context_menu_item_add_to_liked_songs), tint = Color.White, modifier = Modifier.size(size))+ }}- } else {- Icon(painterResource(id = R.drawable.ic_add), contentDescription = stringResource(R.string.aligned_curation_context_menu_item_add_to_liked_songs), tint = Color.White, modifier = mod)}}diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/PodcastPlayerScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/PodcastPlayerScreen.ktindex bd8fa3fc..9f6ca24e 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/PodcastPlayerScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/PodcastPlayerScreen.kt@@ -67,6 +67,61 @@ import com.music.spotui.ui.theme.AppAccentimport com.music.spotui.ui.theme.AppBackgroundimport kotlinx.coroutines.launch+/**+ * The seek bar and the two clocks, with their own ticker: the position moves every half second,+ * and only this part of the player follows it (as [ElapsedLabel] does for the music player).+ */+@Composable+private fun PodcastProgress(playing: Boolean, uri: String, duration: Long) {+ // Tapping the time flips it, as in the official player (it opens on what is left).+ var showRemaining by remember { mutableStateOf(true) }+ var drag by remember { mutableStateOf<Float?>(null) }+ var position by remember { mutableStateOf(SongPlayer.getCurrentPosition()) }+ LaunchedEffect(playing, uri) {+ while (true) {+ position = SongPlayer.getCurrentPosition()+ if (!playing) break+ kotlinx.coroutines.delay(500)+ }+ }+ val fraction = when {+ drag != null -> drag!!+ duration > 0 -> (position.toFloat() / duration).coerceIn(0f, 1f)+ else -> 0f+ }+ val shown = drag?.let { (it * duration).toLong() } ?: position+ SpotifySeekBar(+ fraction = { fraction },+ onDrag = { f -> drag = f },+ onRelease = {+ val f = drag ?: return@SpotifySeekBar+ drag = null+ if (duration > 0) {+ position = (f * duration).toLong()+ SongPlayer.seekTo(position)+ }+ },+ modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 4.dp),+ )+ Row(+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.SpaceBetween,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 24.dp),+ ) {+ Text(episodeClock(shown), color = Color.White.copy(alpha = 0.7f), fontSize = 12.sp)+ // The stock player's right-hand clock is a button: elapsed <-> remaining.+ Text(+ text = if (showRemaining) episodeClock((duration - shown).coerceAtLeast(0)) else episodeClock(shown),+ color = Color.White.copy(alpha = 0.7f),+ fontSize = 12.sp,+ modifier = Modifier.clickable(+ interactionSource = remember { MutableInteractionSource() },+ indication = null,+ ) { showRemaining = !showRemaining },+ )+ }+}+/*** The player, when a podcast episode plays: Spotify gives it its own controls — ±15 s instead* of previous / next, a speed selector, a sleep timer and no shuffle or repeat. Music keeps@@ -92,26 +147,9 @@ fun PodcastPlayerScreen(navController: NavController) {var showDevices by remember { mutableStateOf(false) }var showQueue by remember { mutableStateOf(false) }var showMenu by remember { mutableStateOf(false) }- // Tapping the time flips it, as in the official player (it opens on what is left).- var showRemaining by remember { mutableStateOf(true) }- var drag by remember { mutableStateOf<Float?>(null) }- var position by remember { mutableStateOf(SongPlayer.getCurrentPosition()) }val scope = androidx.compose.runtime.rememberCoroutineScope()val duration = SongPlayer.getDuration()- LaunchedEffect(playing, np.uri) {- while (true) {- position = SongPlayer.getCurrentPosition()- if (!playing) break- kotlinx.coroutines.delay(500)- }- }- val fraction = when {- drag != null -> drag!!- duration > 0 -> (position.toFloat() / duration).coerceIn(0f, 1f)- else -> 0f- }-val song = SongsModel(id = ("uri:$uri").hashCode() and 0x7fffffff,title = title,@@ -151,7 +189,7 @@ fun PodcastPlayerScreen(navController: NavController) {Box(Modifier.fillMaxSize()- .background(Brush.verticalGradient(listOf(tint, Color(0xFF121212)))),+ .background(Brush.verticalGradient(listOf(tint, AppBackground))),) {Column(Modifier.fillMaxSize().statusBarsPadding()) {// Top bar: down chevron, "playing from the podcast", the episode's own menu.@@ -252,37 +290,7 @@ fun PodcastPlayerScreen(navController: NavController) {LikeButton(liked = saved, size = 28.dp) { SongPlayer.setSaved(uri, !saved) }}- SpotifySeekBar(- fraction = { fraction },- onDrag = { f -> drag = f },- onRelease = {- val f = drag ?: return@SpotifySeekBar- drag = null- if (duration > 0) {- position = (f * duration).toLong()- SongPlayer.seekTo(position)- }- },- modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 4.dp),- )- Row(- verticalAlignment = Alignment.CenterVertically,- horizontalArrangement = Arrangement.SpaceBetween,- modifier = Modifier.fillMaxWidth().padding(horizontal = 24.dp),- ) {- Text(episodeClock(if (drag != null) (drag!! * duration).toLong() else position), color = Color.White.copy(alpha = 0.7f), fontSize = 12.sp)- // The stock player's right-hand clock is a button: elapsed ↔ remaining.- Text(- text = if (showRemaining) episodeClock((duration - if (drag != null) (drag!! * duration).toLong() else position).coerceAtLeast(0))- else episodeClock(if (drag != null) (drag!! * duration).toLong() else position),- color = Color.White.copy(alpha = 0.7f),- fontSize = 12.sp,- modifier = Modifier.clickable(- interactionSource = remember { MutableInteractionSource() },- indication = null,- ) { showRemaining = !showRemaining },- )- }+ PodcastProgress(playing = playing, uri = np.uri, duration = duration)// Podcast transport: speed, −15 s, play, +15 s, sleep timer. No shuffle, no repeat:// the official app does not put them on an episode.@@ -369,5 +377,5 @@ private fun SkipIcon(back: Boolean) {}/** The show id carried by the played context ("spotify:show:<id>"), "" when there is none. */-private fun episodeShowId(contextUri: String): String =+internal fun episodeShowId(contextUri: String): String =contextUri.takeIf { it.startsWith("spotify:show:") }?.removePrefix("spotify:show:").orEmpty()diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/ProfileScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/ProfileScreen.ktindex bb6a6a72..218ba5b0 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/ProfileScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/ProfileScreen.kt@@ -1,5 +1,6 @@package com.music.spotui.ui.screens+import com.music.spotui.ui.theme.AppDestructiveimport com.music.spotui.ui.theme.AppTextimport com.music.spotui.ui.theme.AppMutedimport com.music.spotui.ui.theme.tone@@ -103,7 +104,7 @@ fun ProfileScreen(navController: NavController, userId: String, userName: String.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), color = androidx.compose.ui.graphics.Color(0xFFF15E6C)) }+ }) { Text(stringResource(R.string.profile_block), color = AppDestructive) }},dismissButton = { androidx.compose.material3.TextButton(onClick = { blockAsk = false }) { Text(stringResource(R.string.cancel), color = AppText) } },)diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/RecentlyPlayedScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/RecentlyPlayedScreen.ktindex d3bf1721..44331e00 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/RecentlyPlayedScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/RecentlyPlayedScreen.kt@@ -1,5 +1,6 @@package com.music.spotui.ui.screens+import com.music.spotui.ui.components.wideClickableimport com.music.spotui.ui.theme.toneimport com.music.spotui.ui.theme.AppTextimport com.music.spotui.ui.theme.AppMuted@@ -151,8 +152,8 @@ fun RecentlyPlayedScreen(navController: NavController) {imageVector = Icons.AutoMirrored.Filled.ArrowBack,contentDescription = stringResource(R.string.accessibility_navigate_back),tint = AppText,- modifier = Modifier.size(40.dp).clip(RoundedCornerShape(20.dp))- .clickable { navController.popBackStack() }.padding(8.dp),+ modifier = Modifier.wideClickable(horizontal = 8.dp, vertical = 10.dp) { navController.popBackStack() }+ .size(40.dp).padding(8.dp),)Text(stringResource(R.string.recents_title),diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/SearchScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/SearchScreen.ktindex 9ae52a03..81f7404c 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/SearchScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/SearchScreen.kt@@ -259,7 +259,7 @@ fun SumUpSearchScreen(durationMs = item.durationMs,)searchViewModel.startRadioFromSong(song)- SongPlayer.playSong(song.url, context, songs = listOf(song))+ SongPlayer.playSong(song.url, context, songs = listOf(song), alone = true)searchViewModel.updateSongState(song.coverUri, song.title, song.singer, true, song.id, 0, song.album)}@@ -542,7 +542,7 @@ fun RecentItemRow("playlist" -> stringResource(R.string.assisted_curation_search_playlist) + (if (item.singer.isNotBlank()) " • ${item.singer}" else "")else -> ""}- Text(text = subtitle, color = Color.Gray, fontSize = 12.sp, fontWeight = FontWeight.Medium, maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis)+ Text(text = subtitle, color = AppMuted, fontSize = 12.sp, fontWeight = FontWeight.Medium, maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis)}Icon(imageVector = Icons.Default.Close,@@ -584,7 +584,7 @@ fun SearchSongRow(// Start a radio from the tapped track (queue = this song + Spotify// recommendations) rather than queuing the whole search list.searchViewModel.startRadioFromSong(song)- SongPlayer.playSong(song.url, context, songs = listOf(song))+ SongPlayer.playSong(song.url, context, songs = listOf(song), alone = true)searchViewModel.updateSongState(song.coverUri,song.title,@@ -618,7 +618,7 @@ fun SearchSongRow(Text(text = song.title, color = currentPlayingIndicatorColor, fontSize = 16.sp, maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis)androidx.compose.foundation.layout.Row(verticalAlignment = Alignment.CenterVertically) {if (song.explicit) { com.music.spotui.ui.screens.ExplicitBadge(); androidx.compose.foundation.layout.Spacer(Modifier.width(6.dp)) }- Text(text = stringResource(R.string.assisted_curation_search_song) + " • ${song.singer}", color = Color.Gray, fontSize = 13.sp, maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis)+ Text(text = stringResource(R.string.assisted_curation_search_song) + " • ${song.singer}", color = AppMuted, fontSize = 13.sp, maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis)}}}@@ -667,7 +667,7 @@ fun SearchShowRow(show: com.music.spotui.data.entity.PodcastModel, onClick: () -Text(text = show.name, color = AppText, fontSize = 14.sp, fontWeight = FontWeight.Medium, maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis)Text(text = stringResource(R.string.album_type_podcast) + (if (show.publisher.isNotBlank()) " • ${show.publisher}" else ""),- color = Color.Gray, fontSize = 12.sp, fontWeight = FontWeight.Medium, maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,+ color = AppMuted, fontSize = 12.sp, fontWeight = FontWeight.Medium, maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,)}}@@ -697,7 +697,7 @@ fun SearchArtistRow(artist: com.music.spotui.data.entity.ArtistsModel, onClick:)Column {Text(text = artist.name, color = AppText, fontSize = 14.sp, fontWeight = FontWeight.Medium, maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis)- Text(text = stringResource(R.string.artist_subtitle), color = Color.Gray, fontSize = 12.sp, fontWeight = FontWeight.Medium)+ Text(text = stringResource(R.string.artist_subtitle), color = AppMuted, fontSize = 12.sp, fontWeight = FontWeight.Medium)}}}@@ -726,7 +726,7 @@ fun SearchAlbumRow(album: com.music.spotui.data.entity.AlbumsModel, onClick: ())Column {Text(text = album.name, color = AppText, fontSize = 14.sp, fontWeight = FontWeight.Medium, maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis)- Text(text = stringResource(R.string.album) + " • ${album.artists}", color = Color.Gray, fontSize = 12.sp, fontWeight = FontWeight.Medium, maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis)+ Text(text = stringResource(R.string.album) + " • ${album.artists}", color = AppMuted, fontSize = 12.sp, fontWeight = FontWeight.Medium, maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis)}}}@@ -751,7 +751,7 @@ fun SearchPlaylistRow(playlist: com.music.spotui.data.entity.LibraryEntry, onCliText(text = playlist.name, color = AppText, fontSize = 14.sp, fontWeight = FontWeight.Medium, maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis)Text(text = stringResource(R.string.assisted_curation_search_playlist) +(if (playlist.subtitle.isNotBlank()) " • ${playlist.subtitle}" else ""),- color = Color.Gray, fontSize = 12.sp, fontWeight = FontWeight.Medium, maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis)+ color = AppMuted, fontSize = 12.sp, fontWeight = FontWeight.Medium, maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis)}}}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 49e97713..9a373a58 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@@ -138,6 +138,14 @@ fun SettingsScreen(navController: NavController) {com.music.spotui.data.api.LyricsApi.forgetAll()},)+ // Songs an extension streams, played by Spotify too (unheard): counted there, seen by Connect.+ if (com.music.spotui.extensions.Extensions.sources(app.myspoti.extensions.Action.AUDIO_SOURCE).isNotEmpty())+ OptionRow(+ label = stringResource(R.string.settings_connect_mirror_title),+ detail = stringResource(R.string.settings_connect_mirror_detail),+ checked = com.music.spotui.data.preferences.ConnectMirrorPref.on,+ onChecked = { com.music.spotui.data.preferences.ConnectMirrorPref.set(ctx, it) },+ )Divider()SourcesBlock(app.myspoti.extensions.Action.AUDIO_SOURCE, navController)@@ -218,26 +226,8 @@ fun SettingsScreen(navController: NavController) {checked = com.music.spotui.data.preferences.SolidNavBar.on,onChecked = { com.music.spotui.data.preferences.SolidNavBar.set(ctx, it) },)- AccentRow()+ AccentRow(com.music.spotui.data.preferences.Look.CLASSIC)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()}@@ -367,15 +357,15 @@ private fun LookRow() {}}-/** The app's accent colour, for everyone (the same palette the supporter sheet uses). */+/** The accent colour of one look, for everyone (the same palette the supporter sheet uses). */@Composable-private fun AccentRow() {+private fun AccentRow(look: com.music.spotui.data.preferences.Look) {val ctx = androidx.compose.ui.platform.LocalContext.currentColumn(Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 10.dp)) {Text(stringResource(R.string.supporter_accent), color = AppText, fontSize = 16.sp)Row(horizontalArrangement = androidx.compose.foundation.layout.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 selected = com.music.spotui.data.api.SupportReminder.accentOf(look) == aval name = stringResource(when (a) {com.music.spotui.data.api.SupportReminder.Accent.GREEN -> R.string.color_greencom.music.spotui.data.api.SupportReminder.Accent.BLUE -> R.string.color_blue@@ -388,7 +378,7 @@ private fun AccentRow() {.semantics { contentDescription = name; role = Role.RadioButton }.clip(CircleShape).background(a.color).then(if (selected) Modifier.border(3.dp, AppText, CircleShape) else Modifier)- .clickable { com.music.spotui.data.api.SupportReminder.setAccent(ctx, a) },+ .clickable { com.music.spotui.data.api.SupportReminder.setAccent(ctx, look, a) },)}}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 7eb4e38d..dd5be2a3 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@@ -3,6 +3,7 @@ package com.music.spotui.ui.screensimport com.music.spotui.ui.theme.toneimport com.music.spotui.ui.theme.AppTextimport com.music.spotui.ui.theme.AppMuted+import com.music.spotui.ui.theme.AppAccentimport android.Manifestimport android.content.Context@@ -11,10 +12,13 @@ import android.os.Buildimport androidx.activity.compose.rememberLauncherForActivityResultimport androidx.activity.result.contract.ActivityResultContractsimport androidx.compose.animation.AnimatedContent+import androidx.compose.animation.EnterTransition+import androidx.compose.animation.ExitTransitionimport androidx.compose.animation.animateColorAsStateimport androidx.compose.animation.core.Animatableimport androidx.compose.animation.core.FastOutSlowInEasingimport androidx.compose.animation.core.animateDpAsState+import androidx.compose.animation.core.snapimport androidx.compose.animation.core.springimport androidx.compose.animation.core.tweenimport androidx.compose.animation.fadeIn@@ -46,6 +50,13 @@ import androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.foundation.verticalScrollimport androidx.compose.material.icons.Iconsimport androidx.compose.material.icons.filled.CheckCircle+import androidx.compose.material.icons.rounded.AutoAwesome+import androidx.compose.material.icons.rounded.Download+import androidx.compose.material.icons.rounded.Extension+import androidx.compose.material.icons.rounded.GraphicEq+import androidx.compose.material.icons.rounded.Headphones+import androidx.compose.material.icons.rounded.VerifiedUser+import androidx.compose.material.icons.rounded.Widgetsimport androidx.compose.material3.Buttonimport androidx.compose.material3.ButtonDefaultsimport androidx.compose.material3.Icon@@ -77,11 +88,18 @@ import com.music.spotui.ui.theme.AppBackground*/object Setup {private const val KEY = "SetupDone"- /** The permissions step, the sound quality one or the look one (each new step is shown once after the update too). */+ private const val EXTENSIONS_KEY = "SetupExtensionsSeen"+ /** The permissions step, the sound quality one, the look one or the extensions 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()+ !com.music.spotui.data.preferences.LookPref.isChosen(context) || !extensionsSeen(context)+ fun permissionsDone(context: Context) = prefs(context).getBoolean(KEY, false)+ fun done(context: Context) = prefs(context).edit().putBoolean(KEY, true).apply()+ fun extensionsSeen(context: Context) = prefs(context).getBoolean(EXTENSIONS_KEY, false)+ fun setExtensionsSeen(context: Context) = prefs(context).edit().putBoolean(EXTENSIONS_KEY, true).apply()+ private fun prefs(context: Context) = context.getSharedPreferences("myspoti_prefs", Context.MODE_PRIVATE)++ /** A page to open once the app shows (the extensions step's "See the extensions"); taken by [App]. */+ var openAfter: String? = null}private fun granted(context: Context, permission: String) =@@ -90,14 +108,22 @@ private fun granted(context: Context, permission: String) =@Composablefun SetupScreen(onDone: () -> Unit) {val context = LocalContext.current- // First the sound quality, then the look, then the permissions (each skipped when done before an update).+ // How Myspoti works (first setup only), the look, the sound quality, the extensions, then the+ // permissions; each skipped when done before an update.+ val needPerms = remember { !Setup.permissionsDone(context) }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) } }+ val needExtensions = remember { !Setup.extensionsSeen(context) }+ val order = remember {+ listOfNotNull(+ STEP_INTRO.takeIf { needPerms }, STEP_LOOK.takeIf { needLook }, STEP_QUALITY.takeIf { needQuality },+ STEP_EXTENSIONS.takeIf { needExtensions }, STEP_PERMISSIONS.takeIf { needPerms },+ ).ifEmpty { listOf(STEP_PERMISSIONS) }+ }var index by remember { mutableIntStateOf(0) }val steps = order.sizefun next() { if (index + 1 < order.size) index++ else onDone() }+ val reduce = com.music.spotui.ui.look.rememberReduceMotion()Box(Modifier.fillMaxSize().background(AppBackground)) {Glow(Modifier.fillMaxSize(), alpha = 0.16f)Column(Modifier.fillMaxSize().statusBarsPadding().navigationBarsPadding()) {@@ -107,21 +133,31 @@ fun SetupScreen(onDone: () -> Unit) {AnimatedContent(targetState = index,transitionSpec = {- (slideInHorizontally(tween(420, easing = FastOutSlowInEasing)) { it / 2 } + fadeIn(tween(420))) togetherWith+ if (reduce) EnterTransition.None togetherWith ExitTransition.None+ else (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),) { i ->when (order[i]) {- 0 -> QualityStep(onNext = {+ STEP_INTRO -> IntroStep(onNext = ::next)+ STEP_QUALITY -> QualityStep(onNext = {com.music.spotui.data.preferences.setQualityChosen(context)next()})- 1 -> com.music.spotui.ui.look.LookStep(onNext = {+ STEP_LOOK -> com.music.spotui.ui.look.LookStep(onNext = {com.music.spotui.data.preferences.LookPref.setChosen(context)next()})+ STEP_EXTENSIONS -> ExtensionsStep(+ onBrowse = {+ Setup.setExtensionsSeen(context)+ Setup.openAfter = com.music.spotui.ui.navigation.Routes.Extensions.route+ next()+ },+ onLater = { Setup.setExtensionsSeen(context); next() },+ )else -> PermissionsStep(onDone)}}@@ -129,13 +165,20 @@ fun SetupScreen(onDone: () -> Unit) {}}+private const val STEP_INTRO = 0+private const val STEP_LOOK = 1+private const val STEP_QUALITY = 2+private const val STEP_EXTENSIONS = 3+private const val STEP_PERMISSIONS = 4+/** Where the user is in the steps: the current one a longer green dash. */@Composableprivate fun StepDots(count: Int, current: Int, modifier: Modifier = Modifier) {Row(horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = modifier) {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")+ val reduce = com.music.spotui.ui.look.rememberReduceMotion()+ val w by animateDpAsState(if (i == current) 22.dp else 8.dp, if (reduce) snap() else tween(350), label = "dot")+ val c by animateColorAsState(if (i == current) AppAccent else AppText.copy(alpha = 0.25f), if (reduce) snap() else tween(350), label = "dotColor")Box(Modifier.height(6.dp).width(w).clip(RoundedCornerShape(50)).background(c))}}@@ -145,7 +188,8 @@ private fun StepDots(count: Int, current: Int, modifier: Modifier = Modifier) {@Composableprivate fun Modifier.riseIn(index: Int): Modifier {val a = remember { Animatable(0f) }- LaunchedEffect(Unit) { delay(80L + index * 70L); a.animateTo(1f, tween(450, easing = FastOutSlowInEasing)) }+ val reduce = com.music.spotui.ui.look.rememberReduceMotion()+ LaunchedEffect(Unit) { if (reduce) a.snapTo(1f) else { delay(80L + index * 70L); a.animateTo(1f, tween(450, easing = FastOutSlowInEasing)) } }return graphicsLayer { alpha = a.value; translationY = (1f - a.value) * 18.dp.toPx() }}@@ -185,7 +229,7 @@ private fun PermissionsStep(onDone: () -> Unit) {Box(Modifier.riseIn(row)) {Button(onClick = { Setup.done(context); onDone() },- colors = ButtonDefaults.buttonColors(containerColor = Color(0xFF1DB954), contentColor = Color.Black),+ colors = ButtonDefaults.buttonColors(containerColor = AppAccent, contentColor = Color.Black),modifier = Modifier.fillMaxWidth().height(50.dp),) { Text(stringResource(R.string.setup_continue), fontWeight = FontWeight.Bold, fontSize = 16.sp) }}@@ -207,12 +251,89 @@ private fun QualityStep(onNext: () -> Unit) {Box(Modifier.riseIn(3)) { com.music.spotui.ui.components.DownloadQualityPicker() }Button(onClick = onNext,- colors = ButtonDefaults.buttonColors(containerColor = Color(0xFF1DB954), contentColor = Color.Black),+ colors = ButtonDefaults.buttonColors(containerColor = AppAccent, contentColor = Color.Black),modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp).height(50.dp).riseIn(4),) { Text(stringResource(R.string.setup_continue), fontWeight = FontWeight.Bold, fontSize = 16.sp) }}}+/** First setup, step one: what Myspoti is made of, in three cards. */+@Composable+private fun IntroStep(onNext: () -> Unit) {+ Column(+ Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(horizontal = 20.dp, vertical = 24.dp),+ verticalArrangement = Arrangement.spacedBy(12.dp),+ ) {+ var row = 0+ Text(stringResource(R.string.setup_intro_title), color = AppText, fontSize = 26.sp, fontWeight = FontWeight.Bold, modifier = Modifier.riseIn(row++))+ Text(stringResource(R.string.setup_intro_subtitle), color = AppMuted, fontSize = 14.sp, modifier = Modifier.riseIn(row++))+ Spacer(Modifier.height(8.dp))+ InfoRow(Icons.Rounded.GraphicEq, stringResource(R.string.setup_intro_spotify_title), stringResource(R.string.setup_intro_spotify_detail), Modifier.riseIn(row++))+ InfoRow(Icons.Rounded.AutoAwesome, stringResource(R.string.setup_intro_more_title), stringResource(R.string.setup_intro_more_detail), Modifier.riseIn(row++))+ InfoRow(Icons.Rounded.Extension, stringResource(R.string.setup_intro_ext_title), stringResource(R.string.setup_intro_ext_detail), Modifier.riseIn(row++))+ Spacer(Modifier.height(12.dp))+ Box(Modifier.riseIn(row)) {+ Button(+ onClick = onNext,+ colors = ButtonDefaults.buttonColors(containerColor = AppAccent, contentColor = Color.Black),+ modifier = Modifier.fillMaxWidth().height(50.dp),+ ) { Text(stringResource(R.string.setup_continue), fontWeight = FontWeight.Bold, fontSize = 16.sp) }+ }+ }+}++/**+ * What extensions are, shown once to everyone (new installs and updates): optional, written by+ * the community, permission-checked, where to find them. "See the extensions" opens their page+ * once the setup is over.+ */+@Composable+private fun ExtensionsStep(onBrowse: () -> Unit, onLater: () -> Unit) {+ Column(+ Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(horizontal = 20.dp, vertical = 24.dp),+ verticalArrangement = Arrangement.spacedBy(12.dp),+ ) {+ var row = 0+ Text(stringResource(R.string.setup_ext_title), color = AppText, fontSize = 26.sp, fontWeight = FontWeight.Bold, modifier = Modifier.riseIn(row++))+ Text(stringResource(R.string.setup_ext_subtitle), color = AppMuted, fontSize = 14.sp, modifier = Modifier.riseIn(row++))+ Spacer(Modifier.height(8.dp))+ InfoRow(Icons.Rounded.Headphones, stringResource(R.string.setup_ext_audio_title), stringResource(R.string.setup_ext_audio_detail), Modifier.riseIn(row++))+ InfoRow(Icons.Rounded.Download, stringResource(R.string.setup_ext_download_title), stringResource(R.string.setup_ext_download_detail), Modifier.riseIn(row++))+ InfoRow(Icons.Rounded.Widgets, stringResource(R.string.setup_ext_more_title), stringResource(R.string.setup_ext_more_detail), Modifier.riseIn(row++))+ InfoRow(Icons.Rounded.VerifiedUser, stringResource(R.string.setup_ext_safe_title), stringResource(R.string.setup_ext_safe_detail), Modifier.riseIn(row++))+ Text(stringResource(R.string.setup_ext_where), color = AppMuted, fontSize = 13.sp, modifier = Modifier.padding(horizontal = 4.dp).riseIn(row++))+ Spacer(Modifier.height(4.dp))+ Column(Modifier.riseIn(row), horizontalAlignment = Alignment.CenterHorizontally) {+ Button(+ onClick = onBrowse,+ colors = ButtonDefaults.buttonColors(containerColor = AppAccent, contentColor = Color.Black),+ modifier = Modifier.fillMaxWidth().height(50.dp),+ ) { Text(stringResource(R.string.setup_ext_browse), fontWeight = FontWeight.Bold, fontSize = 16.sp) }+ TextButton(onClick = onLater, modifier = Modifier.fillMaxWidth().height(48.dp)) {+ Text(stringResource(R.string.setup_ext_later), color = AppText, fontWeight = FontWeight.SemiBold, fontSize = 15.sp)+ }+ }+ }+}++/** A card of the intro and extensions steps: an accent icon, a title and a line of detail. */+@Composable+private fun InfoRow(icon: androidx.compose.ui.graphics.vector.ImageVector, title: String, detail: String, modifier: Modifier = Modifier) {+ Row(+ verticalAlignment = Alignment.CenterVertically,+ modifier = modifier.fillMaxWidth().background(tone(0xFF1E1E1E), RoundedCornerShape(12.dp)).padding(16.dp),+ ) {+ Box(+ contentAlignment = Alignment.Center,+ modifier = Modifier.size(40.dp).background(AppAccent.copy(alpha = 0.15f), RoundedCornerShape(10.dp)),+ ) { Icon(icon, contentDescription = null, tint = AppAccent, modifier = Modifier.size(22.dp)) }+ Column(Modifier.weight(1f).padding(start = 14.dp)) {+ Text(title, color = AppText, fontSize = 16.sp, fontWeight = FontWeight.SemiBold)+ Text(detail, color = AppMuted, fontSize = 13.sp, lineHeight = 18.sp)+ }+ }+}+@Composableprivate fun SetupRow(title: String, detail: String, on: Boolean, modifier: Modifier = Modifier, onEnable: () -> Unit) {Row(@@ -229,8 +350,8 @@ private fun SetupRow(title: String, detail: String, on: Boolean, modifier: ModiftransitionSpec = { (scaleIn(spring(dampingRatio = 0.5f)) + fadeIn()) togetherWith (scaleOut() + fadeOut()) },label = "allowed",) { allowed ->- if (allowed) Icon(Icons.Default.CheckCircle, contentDescription = null, tint = Color(0xFF1DB954), modifier = Modifier.padding(start = 12.dp).size(28.dp))- else TextButton(onClick = onEnable) { Text(stringResource(R.string.setup_enable), color = Color(0xFF1DB954), fontWeight = FontWeight.Bold) }+ if (allowed) Icon(Icons.Default.CheckCircle, contentDescription = null, tint = AppAccent, modifier = Modifier.padding(start = 12.dp).size(28.dp))+ else TextButton(onClick = onEnable) { Text(stringResource(R.string.setup_enable), color = AppAccent, fontWeight = FontWeight.Bold) }}}}diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/ShowScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/ShowScreen.ktindex 067c3f61..23f276cc 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/ShowScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/ShowScreen.kt@@ -1,5 +1,6 @@package com.music.spotui.ui.screens+import com.music.spotui.ui.components.wideClickableimport com.music.spotui.ui.theme.headerTintimport com.music.spotui.ui.theme.AppText@@ -179,12 +180,7 @@ fun ShowScreen(navController: NavController, showId: String, showName: String =}if (pageState is Response.Loading && page == null) item { Loader() }if (pageState is Response.Error && items.isEmpty()) item {- Text(- (pageState as Response.Error).error,- color = AppText.copy(alpha = 0.7f),- fontSize = 14.sp,- modifier = Modifier.padding(16.dp),- )+ com.music.spotui.ui.components.ErrorRetry(stringResource(R.string.page_load_failed)) { vm.loadShow(showId) }}if (tab == 1) item { About(show) }if (tab == 0 && page != null && items.isEmpty() && pageState !is Response.Loading) item {@@ -233,10 +229,10 @@ private fun Header(contentAlignment = Alignment.Center,modifier = Modifier.padding(12.dp)+ .wideClickable { navController.navigateUp() }.size(40.dp).clip(CircleShape)- .background(Color.Black.copy(alpha = 0.35f))- .clickable { navController.navigateUp() },+ .background(Color.Black.copy(alpha = 0.35f)),) {Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.accessibility_navigate_back), tint = Color.White)}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 234484e4..3ee796ef 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@@ -1,5 +1,6 @@package com.music.spotui.ui.screens+import com.music.spotui.ui.components.wideClickableimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.clickableimport androidx.compose.foundation.layout.Arrangement@@ -271,7 +272,7 @@ fun FriendActivityScreen(navController: NavController) {Column(Modifier.fillMaxSize().background(AppBackground).statusBarsPadding()) {Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(8.dp, 12.dp, 8.dp, 8.dp)) {Icon(Icons.AutoMirrored.Filled.ArrowBack, stringResource(R.string.accessibility_navigate_back), tint = AppText,- modifier = Modifier.size(40.dp).clip(CircleShape).clickable { navController.popBackStack() }.padding(8.dp))+ modifier = Modifier.wideClickable(horizontal = 8.dp, vertical = 10.dp) { navController.popBackStack() }.size(40.dp).padding(8.dp))Text(stringResource(R.string.friends_title), fontWeight = FontWeight.Bold, color = AppText, fontSize = 22.sp, maxLines = 1,overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(start = 6.dp).weight(1f))Icon(Icons.Filled.Refresh, stringResource(R.string.friends_refresh), tint = AppText,diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/WelcomeScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/WelcomeScreen.ktindex d5f6fb6d..6bda4e02 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/WelcomeScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/WelcomeScreen.kt@@ -4,6 +4,8 @@ import com.music.spotui.ui.theme.toneimport com.music.spotui.ui.theme.AppTextimport androidx.compose.animation.AnimatedContent+import androidx.compose.animation.EnterTransition+import androidx.compose.animation.ExitTransitionimport androidx.compose.animation.core.Animatableimport androidx.compose.animation.core.FastOutSlowInEasingimport androidx.compose.animation.core.LinearEasing@@ -135,8 +137,13 @@ fun WelcomeScreen(onLogin: () -> Unit) {/** A soft green light behind the logo, drifting slowly. */@Composableinternal fun Glow(modifier: Modifier = Modifier, alpha: Float = 0.30f) {- val t = rememberInfiniteTransition(label = "glow")- val phase by t.animateFloat(0f, (2 * PI).toFloat(), infiniteRepeatable(tween(16_000, easing = LinearEasing)), label = "phase")+ // "Remove animations": the light stays where it starts.+ val reduce = com.music.spotui.ui.look.rememberReduceMotion()+ val phase = if (reduce) 0f else {+ val t = rememberInfiniteTransition(label = "glow")+ val p by t.animateFloat(0f, (2 * PI).toFloat(), infiniteRepeatable(tween(16_000, easing = LinearEasing)), label = "phase")+ p+ }Canvas(modifier) {val c = Offset(size.width * (0.5f + 0.12f * sin(phase)), size.height * (0.30f + 0.05f * cos(phase)))val r = size.width * 1.05f@@ -154,6 +161,7 @@ private fun Features() {stringResource(R.string.welcome_rotate_offline),)var index by remember { mutableIntStateOf(0) }+ val reduce = com.music.spotui.ui.look.rememberReduceMotion()LaunchedEffect(Unit) {delay(1_200)while (true) { delay(2_400); index = (index + 1) % features.size }@@ -164,7 +172,8 @@ private fun Features() {AnimatedContent(targetState = index,transitionSpec = {- (slideInVertically(tween(400, easing = FastOutSlowInEasing)) { it / 2 } + fadeIn(tween(400))) togetherWith+ if (reduce) EnterTransition.None togetherWith ExitTransition.None+ else (slideInVertically(tween(400, easing = FastOutSlowInEasing)) { it / 2 } + fadeIn(tween(400))) togetherWith(slideOutVertically(tween(400, easing = FastOutSlowInEasing)) { -it / 2 } + fadeOut(tween(250)))},label = "feature",diff --git a/base/app/src/main/java/com/music/spotui/ui/theme/Color.kt b/base/app/src/main/java/com/music/spotui/ui/theme/Color.ktindex 3ba4e509..6f2090ed 100644--- a/base/app/src/main/java/com/music/spotui/ui/theme/Color.kt+++ b/base/app/src/main/java/com/music/spotui/ui/theme/Color.kt@@ -14,6 +14,8 @@ val AppAccent: Color get() = com.music.spotui.data.api.SupportReminder.accentColval AppText: Color = Color.White/** Secondary text and icons. */val AppMuted: Color = Color(0xFFB3B3B3)+/** Destructive actions (delete, leave, block) and failures shown as text. */+val AppDestructive = Color(0xFFF15E6C)/** What a tint is mixed with to make a header. */val AppShade: Color = Color.Blackdiff --git a/base/app/src/main/java/com/music/spotui/ui/viewmodel/SearchViewModel.kt b/base/app/src/main/java/com/music/spotui/ui/viewmodel/SearchViewModel.ktindex 88103738..de845ae5 100644--- a/base/app/src/main/java/com/music/spotui/ui/viewmodel/SearchViewModel.kt+++ b/base/app/src/main/java/com/music/spotui/ui/viewmodel/SearchViewModel.kt@@ -81,12 +81,20 @@ class SearchViewModel constructor(private val repository: AppRepository = Graph.fun search(query: String) {this.query = querysearchJob?.cancel()+ // Typed again lately (back to a shorter text, a retyped word): the results of then, at once.+ RecentSearches.get(query)?.let { cached ->+ _results.value = Response.Success(cached)+ _songs.value = Response.Success(cached.songs)+ return+ }searchJob = viewModelScope.launch(Dispatchers.IO) {- delay(150) // short debounce for snappy real-time results+ delay(300) // the debounce: a result per pause in typing, not per letter+ var last: SearchResults? = nullrepository.searchEverything(query).collect { result ->// While the next results load, the last ones stay on screen.val keep = result is Response.Loading && (_results.value as? Response.Success)?.data?.let { it != SearchResults() } == trueif (!keep) _results.value = result+ if (result is Response.Success) last = result.data// Keep the legacy songs flow in sync for any remaining consumers._songs.value = when (result) {is Response.Success -> Response.Success(result.data.songs)@@ -94,6 +102,26 @@ class SearchViewModel constructor(private val repository: AppRepository = Graph.is Response.Loading -> Response.Loading()}}+ // Only a search that ran to its end (not one cut by the next letter, nor an error) is remembered.+ last?.let { RecentSearches.put(query, it) }+ }+ }++ /** The last searches by their text, for a few minutes; shared by every instance. */+ private object RecentSearches {+ private const val KEEP = 20+ private const val FRESH_MS = 3 * 60_000L+ private val map = object : LinkedHashMap<String, Pair<Long, SearchResults>>(24, 0.75f, true) {+ override fun removeEldestEntry(eldest: MutableMap.MutableEntry<String, Pair<Long, SearchResults>>) = size > KEEP}++ @Synchronized fun get(query: String): SearchResults? =+ map[key(query)]?.takeIf { System.currentTimeMillis() - it.first < FRESH_MS }?.second++ @Synchronized fun put(query: String, results: SearchResults) {+ if (results != SearchResults()) map[key(query)] = System.currentTimeMillis() to results+ }++ private fun key(query: String) = query.trim().lowercase()}-}\ No newline at end of file+}diff --git a/base/app/src/main/java/com/music/spotui/ui/viewmodel/ShowViewModel.kt b/base/app/src/main/java/com/music/spotui/ui/viewmodel/ShowViewModel.ktindex f1100fb8..1f109259 100644--- a/base/app/src/main/java/com/music/spotui/ui/viewmodel/ShowViewModel.kt+++ b/base/app/src/main/java/com/music/spotui/ui/viewmodel/ShowViewModel.kt@@ -59,6 +59,8 @@ class ShowViewModel constructor(viewModelScope.launch(Dispatchers.IO) {repository.provideShowPage(showId).collect { response ->_page.value = response+ // A failed page may be loaded again (Try again, or opening it anew).+ if (response is Response.Error) showKey = nullval loaded = (response as? Response.Success)?.data ?: return@collectfollowing.value = loaded.show.saved || SongPlayer.library["spotify:show:$showId"] == true}diff --git a/base/app/src/main/res/values-de/myspoti_strings.xml b/base/app/src/main/res/values-de/myspoti_strings.xmlindex 346b6b31..a1f53d40 100644--- a/base/app/src/main/res/values-de/myspoti_strings.xml+++ b/base/app/src/main/res/values-de/myspoti_strings.xml@@ -173,6 +173,27 @@<string name="setup_battery_detail">Musik läuft weiter, wenn der Bildschirm aus ist</string><string name="setup_enable">Erlauben</string><string name="setup_continue">Weiter</string>+ <string name="setup_intro_title">So funktioniert Myspoti</string>+ <string name="setup_intro_subtitle">Drei Dinge, bevor es losgeht.</string>+ <string name="setup_intro_spotify_title">Spotify, ohne Werbung</string>+ <string name="setup_intro_spotify_detail">Dein Konto, deine Playlists und Likes, abgespielt von Spotifys eigenem Webplayer. Kostenlose Konten gehen auch.</string>+ <string name="setup_intro_more_title">Mehr als die offizielle App</string>+ <string name="setup_intro_more_detail">Songtexte Wort für Wort, offizielle Videos, Hörstatistiken und zwei Looks zur Wahl.</string>+ <string name="setup_intro_ext_title">Erweiterungen, wenn du willst</string>+ <string name="setup_intro_ext_detail">Zusätze aus der Community: andere Audioquellen, Downloads und mehr. Gleich mehr dazu.</string>+ <string name="setup_ext_title">Erweiterungen</string>+ <string name="setup_ext_subtitle">Myspoti funktioniert so, wie es ist: es spielt Spotify. Erweiterungen sind optionale Zusätze aus der Community, die mehr können.</string>+ <string name="setup_ext_audio_title">Andere Audioquellen</string>+ <string name="setup_ext_audio_detail">Eine Erweiterung kann deine Songs aus einer anderen Quelle abspielen, in der Qualität, die sie bietet.</string>+ <string name="setup_ext_download_title">Downloads</string>+ <string name="setup_ext_download_detail">Zum Offline-Hören installierst du eine Download-Erweiterung. Die Songs bleiben verschlüsselt in Myspoti.</string>+ <string name="setup_ext_more_title">Und mehr</string>+ <string name="setup_ext_more_detail">Startseiten-Bereiche, Seiten und Werkzeuge ihrer Autoren.</string>+ <string name="setup_ext_safe_title">Du behältst die Kontrolle</string>+ <string name="setup_ext_safe_detail">Vor der Installation zeigt sie, was sie darf. Für alles Weitere fragt sie erneut, und du kannst sie jederzeit entfernen.</string>+ <string name="setup_ext_where">Du findest sie unter Einstellungen, Erweiterungen, von GitHub, GitLab und Codeberg. Sie stammen von ihren Autoren, nicht von Myspoti.</string>+ <string name="setup_ext_browse">Erweiterungen ansehen</string>+ <string name="setup_ext_later">Später</string><string name="local_folders_button">Ordner</string><string name="local_folders_title">Ordner</string><string name="local_folders_detail">Wähle die Ordner aus, die in Lokale Dateien angezeigt werden. Messenger-Apps und Aufnahmen sind zunächst ausgeblendet.</string>@@ -521,4 +542,8 @@<string name="look_offer_note">Du kannst es später unter Einstellungen > Anzeige und Sprache ändern.</string><string name="settings_headset_skip_title">Kopfhörertasten springen 15 s bei Podcasts</string><string name="settings_headset_skip_detail">Aus: sie wechseln zur nächsten oder vorherigen Folge</string>+ <string name="settings_connect_mirror_title">Erweiterungs-Wiedergaben bei Spotify zählen</string>+ <string name="settings_connect_mirror_detail">Spielt den Spotify-Titel stumm im Hintergrund ab, damit er gezählt wird und deine Geräte ihn steuern können. Braucht etwas mehr Daten und Akku: schalte es aus, wenn du es nicht brauchst.</string>+ <string name="explicit_badge">E</string>+ <string name="spotify_plan">Spotify %1$s</string></resources>diff --git a/base/app/src/main/res/values-de/security_strings.xml b/base/app/src/main/res/values-de/security_strings.xmlindex 1e872259..8b18536a 100644--- a/base/app/src/main/res/values-de/security_strings.xml+++ b/base/app/src/main/res/values-de/security_strings.xml@@ -1,5 +1,6 @@<?xml version="1.0" encoding="utf-8"?><resources><string name="action_playback_mirror">Hält Spotify hier lautlos am Laufen; zählt Wiedergaben auf deinem Konto</string>+ <string name="action_attest">Beweisen, dass dies Myspoti ist</string><string name="mirror_indicator">Spotify gespiegelt von %1$s</string></resources>diff --git a/base/app/src/main/res/values-el/myspoti_strings.xml b/base/app/src/main/res/values-el/myspoti_strings.xmlindex a871e460..2aee3274 100644--- a/base/app/src/main/res/values-el/myspoti_strings.xml+++ b/base/app/src/main/res/values-el/myspoti_strings.xml@@ -173,6 +173,27 @@<string name="setup_battery_detail">Η μουσική συνεχίζει με την οθόνη σβηστή</string><string name="setup_enable">Επίτρεψε</string><string name="setup_continue">Συνέχεια</string>+ <string name="setup_intro_title">Πώς δουλεύει το Myspoti</string>+ <string name="setup_intro_subtitle">Τρία πράγματα πριν ξεκινήσεις.</string>+ <string name="setup_intro_spotify_title">Spotify, χωρίς διαφημίσεις</string>+ <string name="setup_intro_spotify_detail">Ο λογαριασμός σου, οι playlist και τα likes σου, από τον ίδιο τον web player του Spotify. Δουλεύουν και οι δωρεάν λογαριασμοί.</string>+ <string name="setup_intro_more_title">Περισσότερα από την επίσημη εφαρμογή</string>+ <string name="setup_intro_more_detail">Στίχοι λέξη προς λέξη, επίσημα βίντεο, στατιστικά ακρόασης και δύο εμφανίσεις για να διαλέξεις.</string>+ <string name="setup_intro_ext_title">Επεκτάσεις, αν θέλεις</string>+ <string name="setup_intro_ext_detail">Πρόσθετα από την κοινότητα: άλλες πηγές ήχου, λήψεις και άλλα. Περισσότερα σε λίγο.</string>+ <string name="setup_ext_title">Επεκτάσεις</string>+ <string name="setup_ext_subtitle">Το Myspoti δουλεύει όπως είναι: παίζει Spotify. Οι επεκτάσεις είναι προαιρετικά πρόσθετα από την κοινότητα που κάνουν περισσότερα.</string>+ <string name="setup_ext_audio_title">Άλλες πηγές ήχου</string>+ <string name="setup_ext_audio_detail">Μια επέκταση μπορεί να παίζει τα τραγούδια σου από άλλη πηγή, στην ποιότητα που προσφέρει.</string>+ <string name="setup_ext_download_title">Λήψεις</string>+ <string name="setup_ext_download_detail">Για ακρόαση εκτός σύνδεσης, εγκατέστησε μια επέκταση λήψεων. Τα τραγούδια μένουν κρυπτογραφημένα στο Myspoti.</string>+ <string name="setup_ext_more_title">Και άλλα</string>+ <string name="setup_ext_more_detail">Ενότητες αρχικής, σελίδες και εργαλεία από τους δημιουργούς τους.</string>+ <string name="setup_ext_safe_title">Εσύ έχεις τον έλεγχο</string>+ <string name="setup_ext_safe_detail">Πριν την εγκατάσταση δείχνει τι μπορεί να κάνει. Για οτιδήποτε άλλο ρωτά ξανά, και μπορείς να την αφαιρέσεις όποτε θέλεις.</string>+ <string name="setup_ext_where">Θα τις βρεις στις Ρυθμίσεις, Επεκτάσεις, από GitHub, GitLab και Codeberg. Τις γράφουν οι δημιουργοί τους, όχι το Myspoti.</string>+ <string name="setup_ext_browse">Δες τις επεκτάσεις</string>+ <string name="setup_ext_later">Αργότερα</string><string name="local_folders_button">Φάκελοι</string><string name="local_folders_title">Φάκελοι</string><string name="local_folders_detail">Επίλεξε τους φακέλους που εμφανίζονται στα Τοπικά αρχεία. Οι εφαρμογές μηνυμάτων και οι ηχογραφήσεις ξεκινούν κρυφές.</string>@@ -521,4 +542,8 @@<string name="look_offer_note">Μπορείτε να την αλλάξετε αργότερα στις Ρυθμίσεις > Οθόνη και γλώσσα.</string><string name="settings_headset_skip_title">Κουμπιά ακουστικών: 15 δ στα podcast</string><string name="settings_headset_skip_detail">Απενεργοποιημένο: πηγαίνουν στο επόμενο ή προηγούμενο επεισόδιο</string>+ <string name="settings_connect_mirror_title">Μέτρηση ακροάσεων επεκτάσεων στο Spotify</string>+ <string name="settings_connect_mirror_detail">Παίζει το τραγούδι του Spotify σε σίγαση στο παρασκήνιο, ώστε να μετράει και οι συσκευές σας να το ελέγχουν. Χρησιμοποιεί λίγο περισσότερα δεδομένα και μπαταρία: απενεργοποιήστε το αν δεν το χρειάζεστε.</string>+ <string name="explicit_badge">E</string>+ <string name="spotify_plan">Spotify %1$s</string></resources>diff --git a/base/app/src/main/res/values-el/security_strings.xml b/base/app/src/main/res/values-el/security_strings.xmlindex e01476ca..b74cd1e6 100644--- a/base/app/src/main/res/values-el/security_strings.xml+++ b/base/app/src/main/res/values-el/security_strings.xml@@ -1,5 +1,6 @@<?xml version="1.0" encoding="utf-8"?><resources><string name="action_playback_mirror">Κρατά το Spotify να παίζει αθόρυβα εδώ· μετρά ακροάσεις στον λογαριασμό σας</string>+ <string name="action_attest">Απόδειξη ότι είναι το Myspoti</string><string name="mirror_indicator">Spotify σε αντικατοπτρισμό από %1$s</string></resources>diff --git a/base/app/src/main/res/values-es-rAR/spotify_strings.xml b/base/app/src/main/res/values-es-rAR/spotify_strings.xmlindex 83aa22e9..8793fc71 100644--- a/base/app/src/main/res/values-es-rAR/spotify_strings.xml+++ b/base/app/src/main/res/values-es-rAR/spotify_strings.xml@@ -134,4 +134,17 @@<string name="find_in_context_edit_text_liked_songs_hint" formatted="false">Buscar en Tus me gusta</string><string name="find_in_context_edit_text_playlist_hint" formatted="false">Buscar en la playlist</string><string name="assisted_curation_search_empty_view_no_result_title" formatted="false">No se pudo encontrar \"%1$s\"</string>+ <string name="collection_liked_songs_title" formatted="false">Canciones que te gustan</string>+ <string name="context_menu_sleep_timer" formatted="false">Temporizador</string>+ <string name="context_menu_sleep_timer_turn_off" formatted="false">Desactivar el temporizador</string>+ <string name="context_menu_sleep_timer_end_of_track" formatted="false">Fin de la canción</string>+ <string name="context_type_description_play_queue" formatted="false">Reproduciendo desde la cola de reproducción</string>+ <string name="context_type_description_collection_your_library" formatted="false">Reproduciendo desde Tu biblioteca</string>+ <string name="context_type_description_playlist" formatted="false">Reproduciendo desde la playlist</string>+ <string name="context_type_description_album" formatted="false">Reproduciendo desde el álbum</string>+ <string name="context_type_description_artist" formatted="false">Reproduciendo desde el artista</string>+ <string name="context_type_description_show" formatted="false">Reproduciendo desde el podcast</string>+ <string name="context_type_description_search" formatted="false">Reproduciendo desde la búsqueda</string>+ <string name="mr_user_route_category_name" formatted="false">Dispositivos</string>+ <string name="local_files_title" formatted="false">Archivos locales</string></resources>diff --git a/base/app/src/main/res/values-es-rMX/spotify_strings.xml b/base/app/src/main/res/values-es-rMX/spotify_strings.xmlindex b5016ec9..b7c256dc 100644--- a/base/app/src/main/res/values-es-rMX/spotify_strings.xml+++ b/base/app/src/main/res/values-es-rMX/spotify_strings.xml@@ -134,4 +134,17 @@<string name="find_in_context_edit_text_liked_songs_hint" formatted="false">Buscar en Tus me gusta</string><string name="find_in_context_edit_text_playlist_hint" formatted="false">Buscar en la playlist</string><string name="assisted_curation_search_empty_view_no_result_title" formatted="false">No se pudo encontrar \"%1$s\"</string>+ <string name="collection_liked_songs_title" formatted="false">Canciones que te gustan</string>+ <string name="context_menu_sleep_timer" formatted="false">Temporizador</string>+ <string name="context_menu_sleep_timer_turn_off" formatted="false">Desactivar el temporizador</string>+ <string name="context_menu_sleep_timer_end_of_track" formatted="false">Fin de la canción</string>+ <string name="context_type_description_play_queue" formatted="false">Reproduciendo desde la cola de reproducción</string>+ <string name="context_type_description_collection_your_library" formatted="false">Reproduciendo desde Tu biblioteca</string>+ <string name="context_type_description_playlist" formatted="false">Reproduciendo desde la playlist</string>+ <string name="context_type_description_album" formatted="false">Reproduciendo desde el álbum</string>+ <string name="context_type_description_artist" formatted="false">Reproduciendo desde el artista</string>+ <string name="context_type_description_show" formatted="false">Reproduciendo desde el podcast</string>+ <string name="context_type_description_search" formatted="false">Reproduciendo desde la búsqueda</string>+ <string name="mr_user_route_category_name" formatted="false">Dispositivos</string>+ <string name="local_files_title" formatted="false">Archivos locales</string></resources>diff --git a/base/app/src/main/res/values-es/myspoti_strings.xml b/base/app/src/main/res/values-es/myspoti_strings.xmlindex 1398b454..b497ef5b 100644--- a/base/app/src/main/res/values-es/myspoti_strings.xml+++ b/base/app/src/main/res/values-es/myspoti_strings.xml@@ -173,6 +173,27 @@<string name="setup_battery_detail">La música sigue sonando con la pantalla apagada</string><string name="setup_enable">Permitir</string><string name="setup_continue">Continuar</string>+ <string name="setup_intro_title">Cómo funciona Myspoti</string>+ <string name="setup_intro_subtitle">Tres cosas que saber antes de empezar.</string>+ <string name="setup_intro_spotify_title">Spotify, sin anuncios</string>+ <string name="setup_intro_spotify_detail">Tu cuenta, tus playlists y tus me gusta, reproducidos por el propio reproductor web de Spotify. Las cuentas gratuitas también funcionan.</string>+ <string name="setup_intro_more_title">Más que la app oficial</string>+ <string name="setup_intro_more_detail">Letras palabra por palabra, vídeos oficiales, estadísticas de escucha y dos estilos a elegir.</string>+ <string name="setup_intro_ext_title">Extensiones, si las quieres</string>+ <string name="setup_intro_ext_detail">Complementos hechos por la comunidad: otras fuentes de audio, descargas y más. Enseguida te contamos.</string>+ <string name="setup_ext_title">Extensiones</string>+ <string name="setup_ext_subtitle">Myspoti funciona tal cual: reproduce Spotify. Las extensiones son complementos opcionales, hechos por la comunidad, que hacen más.</string>+ <string name="setup_ext_audio_title">Otras fuentes de audio</string>+ <string name="setup_ext_audio_detail">Una extensión puede reproducir tus canciones desde otra fuente, en la calidad que ofrezca.</string>+ <string name="setup_ext_download_title">Descargas</string>+ <string name="setup_ext_download_detail">Para escuchar sin conexión, instala una extensión de descarga. Las canciones quedan cifradas en Myspoti.</string>+ <string name="setup_ext_more_title">Y más</string>+ <string name="setup_ext_more_detail">Secciones de inicio, páginas y herramientas añadidas por sus autores.</string>+ <string name="setup_ext_safe_title">Tú tienes el control</string>+ <string name="setup_ext_safe_detail">Antes de instalarla, muestra lo que puede hacer. Pide permiso para todo lo demás y puedes quitarla cuando quieras.</string>+ <string name="setup_ext_where">Encuéntralas en Ajustes, Extensiones, desde GitHub, GitLab y Codeberg. Las escriben sus autores, no Myspoti.</string>+ <string name="setup_ext_browse">Ver las extensiones</string>+ <string name="setup_ext_later">Más tarde</string><string name="local_folders_button">Carpetas</string><string name="local_folders_title">Carpetas</string><string name="local_folders_detail">Elige las carpetas que se muestran en Archivos locales. Las apps de mensajería y las grabaciones empiezan ocultas.</string>@@ -521,4 +542,8 @@<string name="look_offer_note">Puedes cambiarlo más tarde en Ajustes > Pantalla e idioma.</string><string name="settings_headset_skip_title">Botones de auriculares: 15 s en podcasts</string><string name="settings_headset_skip_detail">Desactivado: pasan al episodio siguiente o anterior</string>+ <string name="settings_connect_mirror_title">Contar en Spotify lo que suena con extensiones</string>+ <string name="settings_connect_mirror_detail">Reproduce la canción de Spotify en silencio en segundo plano, para que cuente y tus dispositivos puedan controlarla. Usa algo más de datos y batería: desactívalo si no lo necesitas.</string>+ <string name="explicit_badge">E</string>+ <string name="spotify_plan">Spotify %1$s</string></resources>diff --git a/base/app/src/main/res/values-es/security_strings.xml b/base/app/src/main/res/values-es/security_strings.xmlindex 8c2ce441..a15d8ca1 100644--- a/base/app/src/main/res/values-es/security_strings.xml+++ b/base/app/src/main/res/values-es/security_strings.xml@@ -1,5 +1,6 @@<?xml version="1.0" encoding="utf-8"?><resources><string name="action_playback_mirror">Mantiene Spotify sonando en silencio aquí; cuenta reproducciones en tu cuenta</string>+ <string name="action_attest">Demostrar que es Myspoti</string><string name="mirror_indicator">Spotify reflejado por %1$s</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 ee116b98..197a1b28 100644--- a/base/app/src/main/res/values-fr/myspoti_strings.xml+++ b/base/app/src/main/res/values-fr/myspoti_strings.xml@@ -200,6 +200,27 @@<string name="setup_battery_detail">La musique continue écran éteint</string><string name="setup_enable">Autoriser</string><string name="setup_continue">Continuer</string>+ <string name="setup_intro_title">Comment marche Myspoti</string>+ <string name="setup_intro_subtitle">Trois choses à savoir avant de commencer.</string>+ <string name="setup_intro_spotify_title">Spotify, sans les pubs</string>+ <string name="setup_intro_spotify_detail">Ton compte, tes playlists et tes likes, lus par le lecteur web de Spotify lui-même. Les comptes gratuits marchent aussi.</string>+ <string name="setup_intro_more_title">Plus que l\'appli officielle</string>+ <string name="setup_intro_more_detail">Paroles mot à mot, clips officiels, statistiques d\'écoute et deux styles au choix.</string>+ <string name="setup_intro_ext_title">Des extensions, si tu veux</string>+ <string name="setup_intro_ext_detail">Des modules faits par la communauté : d\'autres sources audio, des téléchargements et plus. On y revient juste après.</string>+ <string name="setup_ext_title">Extensions</string>+ <string name="setup_ext_subtitle">Myspoti marche tel quel : il lit Spotify. Les extensions sont des modules facultatifs, faits par la communauté, qui en font plus.</string>+ <string name="setup_ext_audio_title">D\'autres sources audio</string>+ <string name="setup_ext_audio_detail">Une extension peut lire tes titres depuis une autre source, dans la qualité qu\'elle propose.</string>+ <string name="setup_ext_download_title">Téléchargements</string>+ <string name="setup_ext_download_detail">Pour écouter hors connexion, installe une extension de téléchargement. Les titres restent chiffrés dans Myspoti.</string>+ <string name="setup_ext_more_title">Et plus</string>+ <string name="setup_ext_more_detail">Des sections d\'accueil, des pages et des outils ajoutés par leurs auteurs.</string>+ <string name="setup_ext_safe_title">Tu gardes la main</string>+ <string name="setup_ext_safe_detail">Avant l\'installation, elle montre ce qu\'elle peut faire. Elle redemande pour tout le reste, et tu peux la supprimer quand tu veux.</string>+ <string name="setup_ext_where">Tu les trouves dans Paramètres, Extensions, depuis GitHub, GitLab et Codeberg. Elles sont écrites par leurs auteurs, pas par Myspoti.</string>+ <string name="setup_ext_browse">Voir les extensions</string>+ <string name="setup_ext_later">Plus tard</string><string name="local_folders_button">Dossiers</string><string name="local_folders_title">Dossiers</string><string name="local_folders_detail">Choisis les dossiers affichés dans Fichiers locaux. Les applis de messagerie et les enregistrements sont masqués au départ.</string>@@ -526,4 +547,8 @@<string name="look_offer_note">Vous pourrez le changer plus tard dans Réglages > Affichage et langue.</string><string name="settings_headset_skip_title">Boutons du casque : 15 s en podcast</string><string name="settings_headset_skip_detail">Désactivé : ils passent à l\'épisode suivant ou précédent</string>+ <string name="settings_connect_mirror_title">Compter les écoutes des extensions sur Spotify</string>+ <string name="settings_connect_mirror_detail">Joue le titre Spotify en sourdine en arrière-plan : l\'écoute compte et vos appareils peuvent la contrôler. Utilise un peu plus de données et de batterie : désactivez-le si vous n\'en avez pas besoin.</string>+ <string name="explicit_badge">E</string>+ <string name="spotify_plan">Spotify %1$s</string></resources>diff --git a/base/app/src/main/res/values-fr/security_strings.xml b/base/app/src/main/res/values-fr/security_strings.xmlindex 53b18e85..217dc2f1 100644--- a/base/app/src/main/res/values-fr/security_strings.xml+++ b/base/app/src/main/res/values-fr/security_strings.xml@@ -1,5 +1,6 @@<?xml version="1.0" encoding="utf-8"?><resources><string name="action_playback_mirror">Garde Spotify en lecture silencieuse ici ; compte des écoutes sur votre compte</string>+ <string name="action_attest">Prouver que c\'est Myspoti</string><string name="mirror_indicator">Spotify en miroir par %1$s</string></resources>diff --git a/base/app/src/main/res/values-in/strings.xml b/base/app/src/main/res/values-in/strings.xmlindex 93683590..fcd355be 100644--- a/base/app/src/main/res/values-in/strings.xml+++ b/base/app/src/main/res/values-in/strings.xml@@ -13,4 +13,12 @@<string name="notif_shuffle_disable">Nonaktifkan pemutaran acak</string><string name="notif_shuffle_disable_smart">Nonaktifkan pemutaran acak pintar</string><string name="player_source_downloaded">Diunduh</string>+ <string name="energy_saver_title">Penghemat baterai</string>+ <string name="energy_saver_summary">Canvas mati, video dan animasi lebih ringan</string>+ <string name="video_fullscreen_enter">Layar penuh</string>+ <string name="video_fullscreen_exit">Keluar dari layar penuh</string>+ <string name="playback_seek_description">Posisi pemutaran</string>+ <string name="account_page_title">Akun Spotify</string>+ <string name="account_page_detail">Paket, privasi, dan perangkat, di spotify.com</string>+ <string name="extension_change_write">Sekarang juga boleh mengirim ke Spotify: %1$s</string></resources>diff --git a/base/app/src/main/res/values-it/myspoti_strings.xml b/base/app/src/main/res/values-it/myspoti_strings.xmlindex 3c29890d..8bf7f29d 100644--- a/base/app/src/main/res/values-it/myspoti_strings.xml+++ b/base/app/src/main/res/values-it/myspoti_strings.xml@@ -173,6 +173,27 @@<string name="setup_battery_detail">La musica continua a schermo spento</string><string name="setup_enable">Consenti</string><string name="setup_continue">Continua</string>+ <string name="setup_intro_title">Come funziona Myspoti</string>+ <string name="setup_intro_subtitle">Tre cose da sapere prima di iniziare.</string>+ <string name="setup_intro_spotify_title">Spotify, senza pubblicità</string>+ <string name="setup_intro_spotify_detail">Il tuo account, le tue playlist e i tuoi Mi piace, riprodotti dal web player di Spotify stesso. Funzionano anche gli account gratuiti.</string>+ <string name="setup_intro_more_title">Più dell\'app ufficiale</string>+ <string name="setup_intro_more_detail">Testi parola per parola, video ufficiali, statistiche di ascolto e due stili tra cui scegliere.</string>+ <string name="setup_intro_ext_title">Estensioni, se le vuoi</string>+ <string name="setup_intro_ext_detail">Componenti aggiuntivi della community: altre sorgenti audio, download e altro. Ne parliamo tra un attimo.</string>+ <string name="setup_ext_title">Estensioni</string>+ <string name="setup_ext_subtitle">Myspoti funziona così com\'è: riproduce Spotify. Le estensioni sono componenti facoltativi, fatti dalla community, che fanno di più.</string>+ <string name="setup_ext_audio_title">Altre sorgenti audio</string>+ <string name="setup_ext_audio_detail">Un\'estensione può riprodurre i tuoi brani da un\'altra sorgente, nella qualità che offre.</string>+ <string name="setup_ext_download_title">Download</string>+ <string name="setup_ext_download_detail">Per ascoltare offline, installa un\'estensione di download. I brani restano cifrati in Myspoti.</string>+ <string name="setup_ext_more_title">E altro</string>+ <string name="setup_ext_more_detail">Sezioni della Home, pagine e strumenti aggiunti dai loro autori.</string>+ <string name="setup_ext_safe_title">Il controllo resta tuo</string>+ <string name="setup_ext_safe_detail">Prima dell\'installazione mostra cosa può fare. Chiede di nuovo per tutto il resto e puoi rimuoverla quando vuoi.</string>+ <string name="setup_ext_where">Le trovi in Impostazioni, Estensioni, da GitHub, GitLab e Codeberg. Sono scritte dai loro autori, non da Myspoti.</string>+ <string name="setup_ext_browse">Vedi le estensioni</string>+ <string name="setup_ext_later">Più tardi</string><string name="local_folders_button">Cartelle</string><string name="local_folders_title">Cartelle</string><string name="local_folders_detail">Scegli le cartelle mostrate nei File locali. App di messaggistica e registrazioni partono nascoste.</string>@@ -521,4 +542,8 @@<string name="look_offer_note">Puoi cambiarlo più tardi in Impostazioni > Schermo e lingua.</string><string name="settings_headset_skip_title">Tasti delle cuffie: 15 s nei podcast</string><string name="settings_headset_skip_detail">Disattivato: passano all\'episodio successivo o precedente</string>+ <string name="settings_connect_mirror_title">Conta su Spotify gli ascolti delle estensioni</string>+ <string name="settings_connect_mirror_detail">Riproduce il brano Spotify in silenzio in background, così viene conteggiato e i tuoi dispositivi possono controllarlo. Usa un po\' più di dati e batteria: disattivalo se non ti serve.</string>+ <string name="explicit_badge">E</string>+ <string name="spotify_plan">Spotify %1$s</string></resources>diff --git a/base/app/src/main/res/values-it/security_strings.xml b/base/app/src/main/res/values-it/security_strings.xmlindex 48bd3f6a..490a48e2 100644--- a/base/app/src/main/res/values-it/security_strings.xml+++ b/base/app/src/main/res/values-it/security_strings.xml@@ -1,5 +1,6 @@<?xml version="1.0" encoding="utf-8"?><resources><string name="action_playback_mirror">Mantiene Spotify in riproduzione silenziosa qui; conta gli ascolti sul tuo account</string>+ <string name="action_attest">Dimostrare che è Myspoti</string><string name="mirror_indicator">Spotify rispecchiato da %1$s</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 4436f2be..c25bbdfe 100644--- a/base/app/src/main/res/values-pl/myspoti_strings.xml+++ b/base/app/src/main/res/values-pl/myspoti_strings.xml@@ -197,6 +197,27 @@<string name="setup_battery_detail">Muzyka gra dalej przy wyłączonym ekranie</string><string name="setup_enable">Zezwól</string><string name="setup_continue">Dalej</string>+ <string name="setup_intro_title">Jak działa Myspoti</string>+ <string name="setup_intro_subtitle">Trzy rzeczy na początek.</string>+ <string name="setup_intro_spotify_title">Spotify bez reklam</string>+ <string name="setup_intro_spotify_detail">Twoje konto, playlisty i polubienia, odtwarzane przez własny odtwarzacz internetowy Spotify. Darmowe konta też działają.</string>+ <string name="setup_intro_more_title">Więcej niż oficjalna aplikacja</string>+ <string name="setup_intro_more_detail">Teksty słowo po słowie, oficjalne teledyski, statystyki słuchania i dwa wyglądy do wyboru.</string>+ <string name="setup_intro_ext_title">Rozszerzenia, jeśli chcesz</string>+ <string name="setup_intro_ext_detail">Dodatki od społeczności: inne źródła dźwięku, pobieranie i więcej. Zaraz o nich opowiemy.</string>+ <string name="setup_ext_title">Rozszerzenia</string>+ <string name="setup_ext_subtitle">Myspoti działa od razu: odtwarza Spotify. Rozszerzenia to opcjonalne dodatki od społeczności, które potrafią więcej.</string>+ <string name="setup_ext_audio_title">Inne źródła dźwięku</string>+ <string name="setup_ext_audio_detail">Rozszerzenie może odtwarzać Twoje utwory z innego źródła, w jakości, jaką oferuje.</string>+ <string name="setup_ext_download_title">Pobieranie</string>+ <string name="setup_ext_download_detail">Aby słuchać offline, zainstaluj rozszerzenie do pobierania. Utwory zostają zaszyfrowane w Myspoti.</string>+ <string name="setup_ext_more_title">I więcej</string>+ <string name="setup_ext_more_detail">Sekcje strony głównej, strony i narzędzia dodane przez ich autorów.</string>+ <string name="setup_ext_safe_title">Ty decydujesz</string>+ <string name="setup_ext_safe_detail">Przed instalacją pokazuje, co może robić. O wszystko inne pyta ponownie, a usunąć je możesz w każdej chwili.</string>+ <string name="setup_ext_where">Znajdziesz je w Ustawienia, Rozszerzenia, z GitHub, GitLab i Codeberg. Piszą je ich autorzy, nie Myspoti.</string>+ <string name="setup_ext_browse">Zobacz rozszerzenia</string>+ <string name="setup_ext_later">Później</string><string name="local_folders_button">Foldery</string><string name="local_folders_title">Foldery</string><string name="local_folders_detail">Wybierz foldery pokazywane w plikach lokalnych. Komunikatory i nagrania są domyślnie ukryte.</string>@@ -532,4 +553,8 @@<string name="settings_look_title">Wygląd</string><string name="settings_headset_skip_title">Przyciski słuchawek: 15 s w podcastach</string><string name="settings_headset_skip_detail">Gdy wyłączone, przechodzą do następnego lub poprzedniego odcinka</string>+ <string name="settings_connect_mirror_title">Liczenie odtworzeń z rozszerzeń w Spotify</string>+ <string name="settings_connect_mirror_detail">Odtwarza utwór Spotify bez dźwięku w tle, aby był liczony, a Twoje urządzenia mogły nim sterować. Zużywa nieco więcej danych i baterii: wyłącz, jeśli tego nie potrzebujesz.</string>+ <string name="explicit_badge">E</string>+ <string name="spotify_plan">Spotify %1$s</string></resources>diff --git a/base/app/src/main/res/values-pl/security_strings.xml b/base/app/src/main/res/values-pl/security_strings.xmlindex 1d2e68fc..6dce23b1 100644--- a/base/app/src/main/res/values-pl/security_strings.xml+++ b/base/app/src/main/res/values-pl/security_strings.xml@@ -1,5 +1,6 @@<?xml version="1.0" encoding="utf-8"?><resources><string name="action_playback_mirror">Utrzymuje ciche odtwarzanie Spotify tutaj; liczy odtworzenia na Twoim koncie</string>+ <string name="action_attest">Potwierdzić, że to Myspoti</string><string name="mirror_indicator">Spotify odzwierciedlane przez %1$s</string></resources>diff --git a/base/app/src/main/res/values-pt/myspoti_strings.xml b/base/app/src/main/res/values-pt/myspoti_strings.xmlindex 79344ca1..ffa0ba7a 100644--- a/base/app/src/main/res/values-pt/myspoti_strings.xml+++ b/base/app/src/main/res/values-pt/myspoti_strings.xml@@ -173,6 +173,27 @@<string name="setup_battery_detail">A música continua a tocar com o ecrã desligado</string><string name="setup_enable">Permitir</string><string name="setup_continue">Continuar</string>+ <string name="setup_intro_title">Como o Myspoti funciona</string>+ <string name="setup_intro_subtitle">Três coisas para saber antes de começar.</string>+ <string name="setup_intro_spotify_title">Spotify, sem anúncios</string>+ <string name="setup_intro_spotify_detail">Sua conta, suas playlists e curtidas, tocadas pelo próprio player web do Spotify. Contas gratuitas também funcionam.</string>+ <string name="setup_intro_more_title">Mais que o app oficial</string>+ <string name="setup_intro_more_detail">Letras palavra por palavra, clipes oficiais, estatísticas de audição e dois visuais para escolher.</string>+ <string name="setup_intro_ext_title">Extensões, se você quiser</string>+ <string name="setup_intro_ext_detail">Complementos feitos pela comunidade: outras fontes de áudio, downloads e mais. Já falamos delas.</string>+ <string name="setup_ext_title">Extensões</string>+ <string name="setup_ext_subtitle">O Myspoti funciona do jeito que é: ele toca o Spotify. Extensões são complementos opcionais, feitos pela comunidade, que fazem mais.</string>+ <string name="setup_ext_audio_title">Outras fontes de áudio</string>+ <string name="setup_ext_audio_detail">Uma extensão pode tocar suas músicas de outra fonte, na qualidade que ela oferece.</string>+ <string name="setup_ext_download_title">Downloads</string>+ <string name="setup_ext_download_detail">Para ouvir offline, instale uma extensão de download. As músicas ficam criptografadas no Myspoti.</string>+ <string name="setup_ext_more_title">E mais</string>+ <string name="setup_ext_more_detail">Seções da página inicial, páginas e ferramentas adicionadas pelos autores.</string>+ <string name="setup_ext_safe_title">Você no controle</string>+ <string name="setup_ext_safe_detail">Antes de instalar, ela mostra o que pode fazer. Pede de novo para qualquer coisa a mais, e você pode removê-la quando quiser.</string>+ <string name="setup_ext_where">Encontre-as em Configurações, Extensões, no GitHub, GitLab e Codeberg. Elas são escritas pelos autores, não pelo Myspoti.</string>+ <string name="setup_ext_browse">Ver as extensões</string>+ <string name="setup_ext_later">Depois</string><string name="local_folders_button">Pastas</string><string name="local_folders_title">Pastas</string><string name="local_folders_detail">Escolhe as pastas mostradas em Ficheiros locais. As apps de mensagens e as gravações começam ocultas.</string>@@ -521,4 +542,8 @@<string name="look_offer_note">Você pode mudar depois em Configurações > Tela e idioma.</string><string name="settings_headset_skip_title">Botões dos auscultadores: 15 s nos podcasts</string><string name="settings_headset_skip_detail">Desativado: passam ao episódio seguinte ou anterior</string>+ <string name="settings_connect_mirror_title">Contar no Spotify o que tocas com extensões</string>+ <string name="settings_connect_mirror_detail">Reproduz a música do Spotify sem som em segundo plano, para que conte e os seus dispositivos a possam controlar. Usa um pouco mais de dados e bateria: desative se não precisar.</string>+ <string name="explicit_badge">E</string>+ <string name="spotify_plan">Spotify %1$s</string></resources>diff --git a/base/app/src/main/res/values-pt/security_strings.xml b/base/app/src/main/res/values-pt/security_strings.xmlindex baa37fb2..a0476848 100644--- a/base/app/src/main/res/values-pt/security_strings.xml+++ b/base/app/src/main/res/values-pt/security_strings.xml@@ -1,5 +1,6 @@<?xml version="1.0" encoding="utf-8"?><resources><string name="action_playback_mirror">Mantém o Spotify a tocar em silêncio aqui; conta reproduções na sua conta</string>+ <string name="action_attest">Provar que é o Myspoti</string><string name="mirror_indicator">Spotify espelhado por %1$s</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 e9bdf020..f125e5dd 100644--- a/base/app/src/main/res/values-ru/myspoti_strings.xml+++ b/base/app/src/main/res/values-ru/myspoti_strings.xml@@ -197,6 +197,27 @@<string name="setup_battery_detail">Музыка продолжает играть при выключенном экране</string><string name="setup_enable">Разрешить</string><string name="setup_continue">Продолжить</string>+ <string name="setup_intro_title">Как работает Myspoti</string>+ <string name="setup_intro_subtitle">Три вещи, которые стоит знать.</string>+ <string name="setup_intro_spotify_title">Spotify без рекламы</string>+ <string name="setup_intro_spotify_detail">Ваш аккаунт, плейлисты и лайки — через собственный веб-плеер Spotify. Бесплатные аккаунты тоже работают.</string>+ <string name="setup_intro_more_title">Больше, чем официальное приложение</string>+ <string name="setup_intro_more_detail">Тексты слово за словом, официальные клипы, статистика прослушиваний и два стиля на выбор.</string>+ <string name="setup_intro_ext_title">Расширения — по желанию</string>+ <string name="setup_intro_ext_detail">Дополнения от сообщества: другие источники звука, загрузки и многое другое. Подробнее — дальше.</string>+ <string name="setup_ext_title">Расширения</string>+ <string name="setup_ext_subtitle">Myspoti работает и без них: он воспроизводит Spotify. Расширения — необязательные дополнения от сообщества, которые умеют больше.</string>+ <string name="setup_ext_audio_title">Другие источники звука</string>+ <string name="setup_ext_audio_detail">Расширение может воспроизводить ваши треки из другого источника, в том качестве, которое оно предлагает.</string>+ <string name="setup_ext_download_title">Загрузки</string>+ <string name="setup_ext_download_detail">Чтобы слушать офлайн, установите расширение для загрузок. Треки хранятся в Myspoti в зашифрованном виде.</string>+ <string name="setup_ext_more_title">И многое другое</string>+ <string name="setup_ext_more_detail">Разделы главной, страницы и инструменты от их авторов.</string>+ <string name="setup_ext_safe_title">Всё под вашим контролем</string>+ <string name="setup_ext_safe_detail">Перед установкой расширение показывает, что ему разрешено. За всё остальное оно спросит снова, а удалить его можно в любой момент.</string>+ <string name="setup_ext_where">Ищите их в Настройки, Расширения — с GitHub, GitLab и Codeberg. Их пишут авторы, а не Myspoti.</string>+ <string name="setup_ext_browse">Посмотреть расширения</string>+ <string name="setup_ext_later">Позже</string><string name="local_folders_button">Папки</string><string name="local_folders_title">Папки</string><string name="local_folders_detail">Выберите папки, показываемые в локальных файлах. Мессенджеры и записи изначально скрыты.</string>@@ -532,4 +553,8 @@<string name="settings_look_title">Оформление</string><string name="settings_headset_skip_title">Кнопки наушников: 15 с в подкастах</string><string name="settings_headset_skip_detail">Если выключено, переключают на следующий или предыдущий выпуск</string>+ <string name="settings_connect_mirror_title">Учитывать прослушивания расширений в Spotify</string>+ <string name="settings_connect_mirror_detail">Воспроизводит трек Spotify без звука в фоне, чтобы прослушивание засчитывалось и ваши устройства могли им управлять. Расходует немного больше трафика и заряда: отключите, если это не нужно.</string>+ <string name="explicit_badge">E</string>+ <string name="spotify_plan">Spotify %1$s</string></resources>diff --git a/base/app/src/main/res/values-ru/security_strings.xml b/base/app/src/main/res/values-ru/security_strings.xmlindex 355a5cfc..002aa4d4 100644--- a/base/app/src/main/res/values-ru/security_strings.xml+++ b/base/app/src/main/res/values-ru/security_strings.xml@@ -1,5 +1,6 @@<?xml version="1.0" encoding="utf-8"?><resources><string name="action_playback_mirror">Тихо воспроизводит Spotify здесь; засчитывает прослушивания в вашем аккаунте</string>+ <string name="action_attest">Подтвердить, что это Myspoti</string><string name="mirror_indicator">Spotify зеркалируется: %1$s</string></resources>diff --git a/base/app/src/main/res/values-tr/strings.xml b/base/app/src/main/res/values-tr/strings.xmlindex c7fbf22d..dd9609c3 100644--- a/base/app/src/main/res/values-tr/strings.xml+++ b/base/app/src/main/res/values-tr/strings.xml@@ -15,4 +15,12 @@<string name="player_source_downloaded">İndirildi</string>+ <string name="energy_saver_title">Pil tasarrufu</string>+ <string name="energy_saver_summary">Canvas kapalı, daha hafif videolar ve animasyonlar</string>+ <string name="video_fullscreen_enter">Tam ekran</string>+ <string name="video_fullscreen_exit">Tam ekrandan çık</string>+ <string name="playback_seek_description">Oynatma konumu</string>+ <string name="account_page_title">Spotify hesabı</string>+ <string name="account_page_detail">Plan, gizlilik ve cihazlar, spotify.com üzerinden</string>+ <string name="extension_change_write">Artık Spotify\'a da gönderebilir: %1$s</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 f28ae8f4..2d25f60e 100644--- a/base/app/src/main/res/values-zh/myspoti_strings.xml+++ b/base/app/src/main/res/values-zh/myspoti_strings.xml@@ -194,6 +194,27 @@<string name="setup_battery_detail">息屏后音乐继续播放</string><string name="setup_enable">允许</string><string name="setup_continue">继续</string>+ <string name="setup_intro_title">Myspoti 如何运作</string>+ <string name="setup_intro_subtitle">开始前需要知道的三件事。</string>+ <string name="setup_intro_spotify_title">Spotify,没有广告</string>+ <string name="setup_intro_spotify_detail">你的账号、歌单和喜欢的歌曲,由 Spotify 自己的网页播放器播放。免费账号也能用。</string>+ <string name="setup_intro_more_title">比官方应用更多</string>+ <string name="setup_intro_more_detail">逐字歌词、官方视频、收听统计,还有两种外观可选。</string>+ <string name="setup_intro_ext_title">扩展,按需使用</string>+ <string name="setup_intro_ext_detail">社区制作的附加组件:其他音源、下载等等。稍后详细介绍。</string>+ <string name="setup_ext_title">扩展</string>+ <string name="setup_ext_subtitle">Myspoti 本身就能用:它播放 Spotify。扩展是社区制作的可选附加组件,能做得更多。</string>+ <string name="setup_ext_audio_title">其他音源</string>+ <string name="setup_ext_audio_detail">扩展可以从其他音源播放你的歌曲,音质由它提供。</string>+ <string name="setup_ext_download_title">下载</string>+ <string name="setup_ext_download_detail">想离线收听,请安装下载类扩展。歌曲会加密保存在 Myspoti 中。</string>+ <string name="setup_ext_more_title">更多</string>+ <string name="setup_ext_more_detail">由作者添加的首页板块、页面和工具。</string>+ <string name="setup_ext_safe_title">一切由你掌控</string>+ <string name="setup_ext_safe_detail">安装前,它会显示可以做什么。需要更多权限时会再次询问,你也可以随时移除。</string>+ <string name="setup_ext_where">在 设置 › 扩展 中查找,来源包括 GitHub、GitLab 和 Codeberg。扩展由其作者编写,而非 Myspoti。</string>+ <string name="setup_ext_browse">查看扩展</string>+ <string name="setup_ext_later">稍后</string><string name="local_folders_button">文件夹</string><string name="local_folders_title">文件夹</string><string name="local_folders_detail">选择“本地文件”中显示的文件夹。通讯应用和录音文件夹默认隐藏。</string>@@ -523,4 +544,8 @@<string name="settings_look_title">外观</string><string name="settings_headset_skip_title">耳机按键在播客中快进/快退 15 秒</string><string name="settings_headset_skip_detail">关闭后,切换到下一集或上一集</string>+ <string name="settings_connect_mirror_title">在 Spotify 上统计扩展的播放</string>+ <string name="settings_connect_mirror_detail">在后台静音播放该 Spotify 歌曲,使其计入播放次数并可由你的设备控制。会多耗一些流量和电量:不需要时可以关闭。</string>+ <string name="explicit_badge">E</string>+ <string name="spotify_plan">Spotify %1$s</string></resources>diff --git a/base/app/src/main/res/values-zh/security_strings.xml b/base/app/src/main/res/values-zh/security_strings.xmlindex 667a4f1c..d525d44a 100644--- a/base/app/src/main/res/values-zh/security_strings.xml+++ b/base/app/src/main/res/values-zh/security_strings.xml@@ -1,5 +1,6 @@<?xml version="1.0" encoding="utf-8"?><resources><string name="action_playback_mirror">在此静音播放 Spotify;会在你的账户上计入收听次数</string>+ <string name="action_attest">证明这是 Myspoti</string><string name="mirror_indicator">Spotify 由 %1$s 镜像</string></resources>diff --git a/base/app/src/main/res/values/myspoti_strings.xml b/base/app/src/main/res/values/myspoti_strings.xmlindex 498338be..19294af1 100644--- a/base/app/src/main/res/values/myspoti_strings.xml+++ b/base/app/src/main/res/values/myspoti_strings.xml@@ -200,6 +200,27 @@<string name="setup_battery_detail">Music keeps playing with the screen off</string><string name="setup_enable">Allow</string><string name="setup_continue">Continue</string>+ <string name="setup_intro_title">How Myspoti works</string>+ <string name="setup_intro_subtitle">Three things to know before you start.</string>+ <string name="setup_intro_spotify_title">Spotify, without the ads</string>+ <string name="setup_intro_spotify_detail">Your account, playlists and likes, played by Spotify\'s own web player. Free accounts work too.</string>+ <string name="setup_intro_more_title">More than the official app</string>+ <string name="setup_intro_more_detail">Word-by-word lyrics, official videos, listening stats, and two looks to choose from.</string>+ <string name="setup_intro_ext_title">Extensions, if you want them</string>+ <string name="setup_intro_ext_detail">Add-ons made by the community: other audio sources, downloads and more. More on them in a moment.</string>+ <string name="setup_ext_title">Extensions</string>+ <string name="setup_ext_subtitle">Myspoti works as it is: it plays Spotify. Extensions are optional add-ons, made by the community, that do more.</string>+ <string name="setup_ext_audio_title">Other audio sources</string>+ <string name="setup_ext_audio_detail">An extension can play your songs from another source, in the quality it offers.</string>+ <string name="setup_ext_download_title">Downloads</string>+ <string name="setup_ext_download_detail">To listen offline, install a download-source extension. Songs stay encrypted in Myspoti.</string>+ <string name="setup_ext_more_title">And more</string>+ <string name="setup_ext_more_detail">Home sections, pages and tools added by their authors.</string>+ <string name="setup_ext_safe_title">You stay in control</string>+ <string name="setup_ext_safe_detail">Before you install one, it shows what it may do. It asks again for anything more, and you can remove it at any time.</string>+ <string name="setup_ext_where">Find them in Settings, Extensions, from GitHub, GitLab and Codeberg. They are written by their authors, not by Myspoti.</string>+ <string name="setup_ext_browse">See the extensions</string>+ <string name="setup_ext_later">Later</string><string name="local_folders_button">Folders</string><string name="local_folders_title">Folders</string><string name="local_folders_detail">Choose the folders shown in Local Files. Messaging apps and recordings start hidden.</string>@@ -527,4 +548,8 @@<string name="look_offer_note">You can change it later in Settings > Display and language.</string><string name="settings_headset_skip_title">Headphone buttons skip 15 s on podcasts</string><string name="settings_headset_skip_detail">When off, they go to the next or previous episode</string>+ <string name="settings_connect_mirror_title">Count extension plays on Spotify</string>+ <string name="settings_connect_mirror_detail">Plays the Spotify song muted in the background, so it counts and your devices can control it. Uses a little more data and battery: turn it off if you don\'t need it.</string>+ <string name="explicit_badge">E</string>+ <string name="spotify_plan">Spotify %1$s</string></resources>diff --git a/base/app/src/main/res/values/security_strings.xml b/base/app/src/main/res/values/security_strings.xmlindex d8e8d45d..4a04269f 100644--- a/base/app/src/main/res/values/security_strings.xml+++ b/base/app/src/main/res/values/security_strings.xml@@ -1,5 +1,6 @@<?xml version="1.0" encoding="utf-8"?><resources><string name="action_playback_mirror">Keeps Spotify playing silently here; counts listens on your account</string>+ <string name="action_attest">Prove this is Myspoti</string><string name="mirror_indicator">Spotify mirrored by %1$s</string></resources>diff --git a/base/app/src/test/java/com/music/spotui/data/api/LikedMergeTest.kt b/base/app/src/test/java/com/music/spotui/data/api/LikedMergeTest.ktindex bbf65b78..8a5e5f2a 100644--- a/base/app/src/test/java/com/music/spotui/data/api/LikedMergeTest.kt+++ b/base/app/src/test/java/com/music/spotui/data/api/LikedMergeTest.kt@@ -26,4 +26,15 @@ class LikedMergeTest {assertEquals(52, merged.size)assertEquals(listOf("old1", "old2"), ids(merged).takeLast(2))}++ @Test fun aShortHeadIsTheWholeList() {+ assertEquals(true, Api.LikedCache.reaches(listOf("a", "b").map(::song), listOf("z").map(::song)))+ }++ @Test fun aFullHeadReachesTheListOnlyThroughASongKnown() {+ val head = (1..50).map { song("n$it") }+ assertEquals(true, Api.LikedCache.reaches(head, listOf(song("n50"), song("old"))))+ // More than a page of new likes: nothing links the head to the list known.+ assertEquals(false, Api.LikedCache.reaches(head, listOf(song("old1"), song("old2"))))+ }}diff --git a/base/app/src/test/java/com/music/spotui/di/MirrorRulesTest.kt b/base/app/src/test/java/com/music/spotui/di/MirrorRulesTest.ktnew file mode 100644index 00000000..a4dfdd87--- /dev/null+++ b/base/app/src/test/java/com/music/spotui/di/MirrorRulesTest.kt@@ -0,0 +1,246 @@+package com.music.spotui.di++import com.music.spotui.di.MirrorRules.Follow+import com.music.spotui.di.MirrorRules.Lead+import com.music.spotui.di.MirrorRules.Local+import com.music.spotui.di.MirrorRules.Origin+import com.music.spotui.di.MirrorRules.Want+import com.music.spotui.di.MirrorRules.Web+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertTrue+import org.junit.Test++class MirrorRulesTest {+ private val id = "4uLU6hMCjMI75M1A2tKUQC"+ private val a = "spotify:track:$id"+ private val b = "spotify:track:7ouMYWpwJ422jRcDASZB7P"+ private val c = "spotify:track:0VjIjW4GlUZAMYd2vXMi3b"+ private val d = "spotify:track:1301WleyT98MSxVHPZCA6M"++ private fun local(uri: String = a, playing: Boolean = true, at: Long = 60_000, length: Long = 200_000) =+ Local(uri, playing, at, length, nextUri = b, previousUri = c)++ private fun onWeb(+ web: Web, want: Want = Want(a, false), local: Local = local(), quiet: Boolean = false, landed: Boolean = true,+ predicted: Long? = web.positionMs, previousUri: String? = null, gapFromMs: Long? = null, wantAtMs: Long? = null, wantLengthMs: Long = 0,+ recentUris: List<String> = emptyList(),+ ) = MirrorRules.onWeb(web, want, local, quiet, landed, predicted, previousUri, gapFromMs, wantAtMs, wantLengthMs, recentUris)++ // ── Which songs are mirrored ──++ @Test fun `only an extension's stream with a Spotify id is mirrored`() {+ assertTrue(MirrorRules.eligible(Origin.AUDIO_SOURCE, id, on = true, dataSaver = false))+ assertFalse(MirrorRules.eligible(Origin.DOWNLOAD, id, on = true, dataSaver = false))+ assertFalse(MirrorRules.eligible(Origin.LOCAL_FILE, id, on = true, dataSaver = false))+ assertFalse(MirrorRules.eligible(Origin.AUDIO_SOURCE, "", on = true, dataSaver = false))+ assertFalse(MirrorRules.eligible(Origin.AUDIO_SOURCE, "not-an-id", on = true, dataSaver = false))+ }++ @Test fun `the setting off or the data saver leave the stream alone`() {+ assertFalse(MirrorRules.eligible(Origin.AUDIO_SOURCE, id, on = false, dataSaver = false))+ assertFalse(MirrorRules.eligible(Origin.AUDIO_SOURCE, id, on = true, dataSaver = true))+ }++ // ── Loop guard: the mirror's own commands are not remote ones ──++ @Test fun `states of the asked or the previous song during the echo of a command are not followed`() {+ assertEquals(Follow.Nothing, onWeb(Web(a, paused = true, positionMs = 60_000), quiet = true))+ assertEquals(Follow.Nothing, onWeb(Web(d, paused = false, positionMs = 0), quiet = true, previousUri = d))+ assertEquals(Follow.Nothing, onWeb(Web(d, paused = false, positionMs = 0), quiet = true, landed = false))+ }++ @Test fun `the echo window lasts from the last command`() {+ var now = 0L+ val echo = MirrorRules.Echo { now }+ echo.sent(2_500)+ now = 2_000; assertTrue(echo.quiet())+ echo.sent(2_500)+ now = 4_000; assertTrue(echo.quiet())+ now = 4_600; assertFalse(echo.quiet())+ echo.sent(1_000); echo.clear(); assertFalse(echo.quiet())+ }++ @Test fun `a state that matches what was asked is not a command`() {+ assertEquals(Follow.Nothing, onWeb(Web(a, paused = false, positionMs = 60_500)))+ assertEquals(Follow.Nothing, onWeb(Web(a, paused = true, positionMs = 60_000), want = Want(a, true), local = local(playing = false)))+ }++ @Test fun `a play that never landed is sent again, whatever the page shows`() {+ assertEquals(Follow.Retry, onWeb(Web(d, paused = false, positionMs = 10_000), landed = false))+ assertEquals(Follow.Retry, onWeb(Web(a, paused = true, positionMs = 0), landed = false))+ }++ @Test fun `a play paused on the phone before it landed is not sent again`() {+ assertEquals(Follow.Nothing, onWeb(Web(a, paused = true, positionMs = 0), want = Want(a, true), local = local(playing = false), landed = false))+ }++ // ── Remote commands the local player follows ──++ @Test fun `pause and resume from another device`() {+ assertEquals(Follow.Pause, onWeb(Web(a, paused = true, positionMs = 60_000)))+ assertEquals(Follow.Resume, onWeb(Web(a, paused = false, positionMs = 60_000), want = Want(a, true), local = local(playing = false)))+ }++ @Test fun `a jump of the page's own clock is a seek`() {+ assertEquals(Follow.Seek(120_000), onWeb(Web(a, paused = false, positionMs = 120_000), predicted = 60_200))+ // A previous after 3 s is a seek to 0 on Spotify's side.+ assertEquals(Follow.Seek(0), onWeb(Web(a, paused = false, positionMs = 0), predicted = 60_200))+ }++ @Test fun `next and previous follow the local queue when the page went there`() {+ assertEquals(Follow.Next, onWeb(Web(b, paused = false, positionMs = 0)))+ assertEquals(Follow.Previous, onWeb(Web(c, paused = false, positionMs = 0)))+ }++ @Test fun `another song is routed from where the page is`() {+ assertEquals(Follow.Play(d, 4_000), onWeb(Web(d, paused = false, positionMs = 4_000)))+ }++ @Test fun `the page moving on at the end of the song is that end, not a skip`() {+ val ending = local(at = 197_000, length = 200_000)+ assertEquals(Follow.Nothing, onWeb(Web(d, paused = false, positionMs = 0), local = ending))+ assertEquals(Follow.Nothing, onWeb(Web(a, paused = true, positionMs = 200_000), local = ending))+ }++ @Test fun `the local player already on its next song, the page is told by the local side`() {+ assertEquals(Follow.Nothing, onWeb(Web(a, paused = false, positionMs = 199_000), local = local(uri = b, at = 500)))+ }++ // ── Drift ──++ @Test fun `drift under the threshold is left alone`() {+ assertEquals(Follow.Nothing, onWeb(Web(a, paused = false, positionMs = 61_400)))+ assertEquals(Lead.Nothing, MirrorRules.onLocal(local(), Want(a, false), stalled = false, quiet = false, webAtMs = 58_600))+ }++ @Test fun `drift over the threshold puts the unheard page back on the local position`() {+ assertEquals(Follow.Align(60_000), onWeb(Web(a, paused = false, positionMs = 62_000)))+ assertEquals(Lead.Align(60_000), MirrorRules.onLocal(local(), Want(a, false), stalled = false, quiet = false, webAtMs = 57_000))+ }++ @Test fun `no correction while a command is answering or when paused`() {+ assertEquals(Lead.Nothing, MirrorRules.onLocal(local(), Want(a, false), stalled = false, quiet = true, webAtMs = 57_000))+ assertEquals(Follow.Nothing, onWeb(Web(a, paused = true, positionMs = 50_000), want = Want(a, true), local = local(playing = false), predicted = 50_000))+ }++ // ── The local player leads the page ──++ @Test fun `a new local song starts on the page once it plays`() {+ assertEquals(Lead.Start(b, 0), MirrorRules.onLocal(local(uri = b, at = 0), Want(a, false), stalled = false, quiet = false, webAtMs = null))+ assertEquals(Lead.Start(a, 60_000), MirrorRules.onLocal(local(), null, stalled = false, quiet = false, webAtMs = null))+ }++ @Test fun `a new local song that does not play yet pauses the old one on the page`() {+ assertEquals(Lead.Pause, MirrorRules.onLocal(local(uri = b, playing = false), Want(a, false), stalled = false, quiet = false, webAtMs = null))+ assertEquals(Lead.Nothing, MirrorRules.onLocal(local(uri = b, playing = false), Want(a, true), stalled = false, quiet = false, webAtMs = null))+ assertEquals(Lead.Nothing, MirrorRules.onLocal(local(playing = false), null, stalled = false, quiet = false, webAtMs = null))+ }++ @Test fun `pause and resume on the phone go to the page`() {+ assertEquals(Lead.Pause, MirrorRules.onLocal(local(playing = false), Want(a, false), stalled = false, quiet = false, webAtMs = 60_000))+ assertEquals(Lead.Resume(null), MirrorRules.onLocal(local(), Want(a, true), stalled = false, quiet = true, webAtMs = 60_300))+ }++ @Test fun `a stall pauses the page and the resume puts both on the same place`() {+ assertEquals(Lead.Pause, MirrorRules.onLocal(local(), Want(a, false), stalled = true, quiet = false, webAtMs = 61_000))+ assertEquals(Lead.Resume(60_000), MirrorRules.onLocal(local(), Want(a, true), stalled = false, quiet = false, webAtMs = 62_000))+ }++ // ── Review fixes: echo window, the page's own end, seeks across a buffering gap ──++ @Test fun `a third song during the echo of a remote skip is still followed`() {+ // A -> B on another device (the mirror now wants B, A before it), then C within the window.+ val onB = local(uri = b).copy(nextUri = d, previousUri = a)+ assertEquals(Follow.Next, onWeb(Web(d, paused = false, positionMs = 0), want = Want(b, false), local = onB, quiet = true, previousUri = a))+ // The old song and the asked one stay the echo.+ assertEquals(Follow.Nothing, onWeb(Web(a, paused = false, positionMs = 61_000), want = Want(b, false), local = onB, quiet = true, previousUri = a))+ assertEquals(Follow.Nothing, onWeb(Web(b, paused = true, positionMs = 0), want = Want(b, false), local = onB, quiet = true, previousUri = a))+ }++ @Test fun `before the asked song landed, no third song is taken for a remote one`() {+ assertEquals(Follow.Nothing, onWeb(Web(d, paused = false, positionMs = 0), want = Want(b, false), local = local(uri = b), quiet = true, landed = false, previousUri = a))+ }++ @Test fun `the local player not yet on the song a remote skip chose is not sent back`() {+ assertEquals(Lead.Nothing, MirrorRules.onLocal(local(uri = a), Want(b, false), stalled = false, quiet = true, webAtMs = null, previousUri = a))+ assertEquals(Lead.Start(a, 60_000), MirrorRules.onLocal(local(uri = a), Want(b, false), stalled = false, quiet = false, webAtMs = null, previousUri = a))+ }++ @Test fun `the page reaching its own end first is that end, even with a longer local stream`() {+ // The extension's stream is 20 s longer than Spotify's 180 s track: the local player is not near its end.+ val longer = local(at = 178_000, length = 200_000)+ assertEquals(Follow.Nothing, onWeb(Web(d, paused = false, positionMs = 0), local = longer, wantAtMs = 178_500, wantLengthMs = 180_000))+ assertEquals(Follow.Nothing, onWeb(Web(a, paused = true, positionMs = 180_000), local = longer, wantAtMs = 180_000, wantLengthMs = 180_000))+ // Far from the page's end, the same moves are remote ones.+ assertEquals(Follow.Play(d, 0), onWeb(Web(d, paused = false, positionMs = 0), local = longer, wantAtMs = 120_000, wantLengthMs = 180_000))+ assertEquals(Follow.Pause, onWeb(Web(a, paused = true, positionMs = 120_000), local = longer, wantAtMs = 120_000, wantLengthMs = 180_000))+ }++ @Test fun `a remote seek followed by buffering is still a seek`() {+ // At 60 s before the gap, predicted 64 s after it: a jump to 150 s is a seek, not drift.+ assertEquals(Follow.Seek(150_000), onWeb(Web(a, paused = false, positionMs = 150_000), local = local(at = 64_000), predicted = 64_000, gapFromMs = 60_000))+ assertEquals(Follow.Seek(10_000), onWeb(Web(a, paused = false, positionMs = 10_000), local = local(at = 64_000), predicted = 64_000, gapFromMs = 60_000))+ }++ @Test fun `a page that stalled in a buffering gap is drift, put back on the local position`() {+ assertEquals(Follow.Align(64_000), onWeb(Web(a, paused = false, positionMs = 61_000), local = local(at = 64_000), predicted = 64_000, gapFromMs = 60_000))+ }++ // ── Phone test of build 223 ──++ @Test fun `the page left on an earlier play of a fast skip burst is resent, never a remote previous`() {+ // Plays of a, c (the local queue's previous) and b in 0.7 s; the page settled on c.+ val onB = local(uri = b).copy(nextUri = d, previousUri = c)+ val recent = listOf(a, c, b)+ assertEquals(Follow.Resend, onWeb(Web(c, paused = false, positionMs = 6_000), want = Want(b, false), local = onB, recentUris = recent))+ assertEquals(Follow.Resend, onWeb(Web(c, paused = false, positionMs = 6_000), want = Want(b, false), local = onB, landed = false, recentUris = recent))+ // During the echo it is nothing at all, not the "third song" of a remote double skip.+ assertEquals(Follow.Nothing, onWeb(Web(c, paused = false, positionMs = 1_000), want = Want(b, false), local = onB, quiet = true, previousUri = a, recentUris = recent))+ // A song the mirror did not ask lately is still a remote previous.+ assertEquals(Follow.Previous, onWeb(Web(c, paused = false, positionMs = 0), want = Want(b, false), local = onB, recentUris = listOf(b)))+ }++ @Test fun `playback back on the phone goes to the extensions once it plays here`() {+ // Transferred back paused: nothing yet, the hand-over is kept for when it plays.+ assertFalse(MirrorRules.backHere(playingHere = false, handedAway = true, moved = false, intended = false, on = true))+ assertTrue(MirrorRules.backHere(playingHere = true, handedAway = true, moved = false, intended = false, on = true))+ // Resumed or skipped from another device while the engine plays here.+ assertTrue(MirrorRules.backHere(playingHere = true, handedAway = false, moved = true, intended = false, on = true))+ // Myspoti's own play, nothing moved, or the setting off: the engine plays on.+ assertFalse(MirrorRules.backHere(playingHere = true, handedAway = true, moved = true, intended = true, on = true))+ assertFalse(MirrorRules.backHere(playingHere = true, handedAway = false, moved = false, intended = false, on = true))+ assertFalse(MirrorRules.backHere(playingHere = true, handedAway = true, moved = true, intended = false, on = false))+ }++ // ── Report on build 225: plays not taken, ads and reloads ──++ @Test fun `a song the page would not play is tried again later, never given up`() {+ assertEquals(5_000, MirrorRules.backoffMs(0))+ assertEquals(15_000, MirrorRules.backoffMs(1))+ assertEquals(30_000, MirrorRules.backoffMs(2))+ assertEquals(30_000, MirrorRules.backoffMs(9))+ }++ @Test fun `an artist context or one that missed plays the song alone`() {+ val artist = "spotify:artist:7jVv8c5Fj3E9VhNjxT4snq"+ val playlist = "spotify:playlist:37i9dQZF1DXcBWIGoYBM5M"+ assertEquals(a, MirrorRules.playContext(artist, a, emptySet()))+ assertEquals(playlist, MirrorRules.playContext(playlist, a, emptySet()))+ assertEquals(a, MirrorRules.playContext(playlist, a, setOf(playlist)))+ assertEquals(a, MirrorRules.playContext("", a, emptySet()))+ }++ @Test fun `a play, a resume or a seek of the local player is a move, its clock running on is not`() {+ assertTrue(MirrorRules.localMoved(wasPlaying = false, playing = true, expectedMs = 30_000, positionMs = 30_000))+ assertTrue(MirrorRules.localMoved(wasPlaying = true, playing = true, expectedMs = 30_000, positionMs = 90_000))+ assertFalse(MirrorRules.localMoved(wasPlaying = true, playing = true, expectedMs = 30_000, positionMs = 30_400))+ assertFalse(MirrorRules.localMoved(wasPlaying = true, playing = false, expectedMs = null, positionMs = 0))+ }++ @Test fun `while the page recovers, another song is sent back, never followed`() {+ // The player's own recovery (the song "ahead" of an ad) put the page elsewhere: seen as not landed.+ assertEquals(Follow.Retry, onWeb(Web(d, paused = false, positionMs = 0), landed = false))+ assertEquals(Follow.Nothing, onWeb(Web(a, paused = false, positionMs = 60_000), landed = false))+ }+}diff --git a/base/app/src/test/java/com/music/spotui/ui/components/WideTapTest.kt b/base/app/src/test/java/com/music/spotui/ui/components/WideTapTest.ktnew file mode 100644index 00000000..9bdc0846--- /dev/null+++ b/base/app/src/test/java/com/music/spotui/ui/components/WideTapTest.kt@@ -0,0 +1,66 @@+package com.music.spotui.ui.components++import com.music.spotui.ui.components.WideTap.Step+import org.junit.Assert.assertEquals+import org.junit.Test++class WideTapTest {++ private val id = 7L++ /** A down as the node sees it: Main unconsumed, then Final consumed by the node itself. */+ private fun WideTap.press(): Step {+ val step = main(id, pressed = true, previousPressed = false, consumed = false, inside = true)+ assertEquals(Step.NONE, final(id, pressed = true, previousPressed = false, consumed = step == Step.PRESS))+ return step+ }++ @Test+ fun tapClicks() {+ val tap = WideTap()+ assertEquals(Step.PRESS, tap.press())+ assertEquals(Step.CLICK, tap.main(id, pressed = false, previousPressed = true, consumed = false, inside = true))+ }++ @Test+ fun jitterBeforeTheLiftStillClicks() {+ val tap = WideTap()+ tap.press()+ repeat(3) {+ assertEquals(Step.NONE, tap.main(id, pressed = true, previousPressed = true, consumed = false, inside = true))+ assertEquals(Step.NONE, tap.final(id, pressed = true, previousPressed = true, consumed = false))+ }+ assertEquals(Step.CLICK, tap.main(id, pressed = false, previousPressed = true, consumed = false, inside = true))+ }++ @Test+ fun scrollTakingTheFingerCancels() {+ val tap = WideTap()+ tap.press()+ assertEquals(Step.NONE, tap.main(id, pressed = true, previousPressed = true, consumed = false, inside = true))+ assertEquals(Step.CANCEL, tap.final(id, pressed = true, previousPressed = true, consumed = true))+ assertEquals(Step.NONE, tap.main(id, pressed = false, previousPressed = true, consumed = false, inside = true))+ }++ @Test+ fun liftOutsideTheWidenedTargetCancels() {+ val tap = WideTap()+ tap.press()+ assertEquals(Step.CANCEL, tap.main(id, pressed = false, previousPressed = true, consumed = false, inside = false))+ }++ @Test+ fun downTakenByAControlUnderTheFingerIsIgnored() {+ val tap = WideTap()+ assertEquals(Step.NONE, tap.main(id, pressed = true, previousPressed = false, consumed = true, inside = true))+ assertEquals(Step.NONE, tap.main(id, pressed = false, previousPressed = true, consumed = false, inside = true))+ }++ @Test+ fun secondFingerDoesNotClick() {+ val tap = WideTap()+ tap.press()+ assertEquals(Step.NONE, tap.main(8L, pressed = false, previousPressed = true, consumed = false, inside = true))+ assertEquals(Step.CLICK, tap.main(id, pressed = false, previousPressed = true, consumed = false, inside = true))+ }+}diff --git a/base/extensions-cli/build.gradle.kts b/base/extensions-cli/build.gradle.ktsindex dd5516f3..2c42e41c 100644--- a/base/extensions-cli/build.gradle.kts+++ b/base/extensions-cli/build.gradle.kts@@ -21,4 +21,5 @@ dependencies {implementation(project(":host-cdp"))implementation(libs.serialization.json)implementation(libs.coroutines.core)+ testImplementation("junit:junit:4.13.2")}diff --git a/base/extensions-cli/src/main/kotlin/app/myspoti/extensions/cli/Run.kt b/base/extensions-cli/src/main/kotlin/app/myspoti/extensions/cli/Run.ktindex 7d71e123..0477ef88 100644--- a/base/extensions-cli/src/main/kotlin/app/myspoti/extensions/cli/Run.kt+++ b/base/extensions-cli/src/main/kotlin/app/myspoti/extensions/cli/Run.kt@@ -1,5 +1,6 @@package app.myspoti.extensions.cli+import app.myspoti.extensions.Attestationimport app.myspoti.extensions.AudioQueryimport app.myspoti.extensions.AudioStreamimport app.myspoti.extensions.Blocks@@ -102,8 +103,13 @@ private class DesktopHost(}override fun nowPlaying(): String? = track?.toJson()override fun control(extensionId: String, action: String, argument: Long?): Boolean { System.err.println("player: $action ${argument ?: ""}"); return true }+ override fun attestation(): Attestation = attestation+ private val attestation = SoftwareAttestation(File(stateDir(), "attest"), ::log)}+/** Where the runner keeps what must outlive a run (the software attestation keys): `$MYSPOTI_EXT_HOME`, else `~/.myspoti-ext`. */+private fun stateDir() = File(System.getenv("MYSPOTI_EXT_HOME") ?: (System.getProperty("user.home") + "/.myspoti-ext"))+/** The Web Player of a Chrome on [cdp] (a port, or its http address), as a Spotify account for extensions. */private class Account(cdp: String) : AutoCloseable {private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)diff --git a/base/extensions-cli/src/main/kotlin/app/myspoti/extensions/cli/SoftwareAttestation.kt b/base/extensions-cli/src/main/kotlin/app/myspoti/extensions/cli/SoftwareAttestation.ktnew file mode 100644index 00000000..819509de--- /dev/null+++ b/base/extensions-cli/src/main/kotlin/app/myspoti/extensions/cli/SoftwareAttestation.kt@@ -0,0 +1,131 @@+package app.myspoti.extensions.cli++import app.myspoti.extensions.Attestation+import app.myspoti.extensions.Enrollment+import java.io.ByteArrayOutputStream+import java.io.File+import java.math.BigInteger+import java.security.KeyFactory+import java.security.KeyPair+import java.security.KeyPairGenerator+import java.security.PrivateKey+import java.security.PublicKey+import java.security.Signature+import java.security.spec.ECGenParameterSpec+import java.security.spec.PKCS8EncodedKeySpec+import java.util.Base64++/**+ * `myspoti.attest` for the desktop runner: a software EC P-256 key per extension, kept in [dir]+ * so it survives between runs, with a self-signed one-certificate "chain". TEST ONLY. Nothing here+ * is hardware-backed and nothing names Myspoti's signing certificate: a server that verifies the+ * chain as it must (to Google's attestation roots, section "Prove it is a genuine Myspoti" of+ * docs/extensions/API.md) rejects it, which is what lets an author test both the happy path of the+ * signatures and the refusal of this key.+ *+ * The certificate carries the challenge and a marker in an extension of a private OID+ * ([MARKER_OID]), not in Google's attestation extension, so nothing can mistake it for the real one.+ */+class SoftwareAttestation(private val dir: File, private val log: (extensionId: String, message: String) -> Unit = { _, _ -> }) : Attestation {+ private data class Stored(val key: PrivateKey, val cert: ByteArray)++ override fun enroll(extensionId: String, challenge: ByteArray): Enrollment {+ val pair = KeyPairGenerator.getInstance("EC").apply { initialize(ECGenParameterSpec("secp256r1")) }.generateKeyPair()+ val cert = selfSigned(extensionId, pair, challenge)+ dir.mkdirs()+ val file = file(extensionId)+ val tmp = File(dir, file.name + ".tmp")+ tmp.writeText(b64(pair.private.encoded) + "\n" + b64(cert) + "\n")+ if (!tmp.renameTo(file)) { file.delete(); tmp.renameTo(file) }+ log(extensionId, "attest: made a SOFTWARE key for the desktop runner: test only, not hardware-backed, a real server must refuse it")+ return Enrollment(b64(pair.public.encoded), listOf(b64(cert)))+ }++ override fun publicKey(extensionId: String): String? = load(extensionId)?.let { b64(publicOf(it.cert).encoded) }++ override fun sign(extensionId: String, data: ByteArray): String {+ val stored = load(extensionId) ?: throw IllegalStateException("not enrolled: call myspoti.attest.enroll(challenge) first")+ return b64(Signature.getInstance("SHA256withECDSA").apply { initSign(stored.key); update(data) }.sign())+ }++ override fun reset(extensionId: String) { file(extensionId).delete() }++ /** The extension's key file: the id is a safe file name (lower case, digits, `_` and `.`), and one id never gives another's name. */+ private fun file(extensionId: String) = File(dir, "attest-$extensionId.key")++ private fun load(extensionId: String): Stored? {+ val lines = file(extensionId).takeIf { it.isFile }?.readLines().orEmpty()+ if (lines.size < 2) return null+ val cert = Base64.getDecoder().decode(lines[1])+ val key = KeyFactory.getInstance("EC").generatePrivate(PKCS8EncodedKeySpec(Base64.getDecoder().decode(lines[0])))+ return Stored(key, cert)+ }++ private fun publicOf(cert: ByteArray): PublicKey =+ java.security.cert.CertificateFactory.getInstance("X.509").generateCertificate(cert.inputStream()).publicKey++ private fun b64(bytes: ByteArray) = Base64.getEncoder().encodeToString(bytes)++ companion object {+ /** A private-use OID: the certificate's marker and challenge, apart from Google's attestation extension. */+ const val MARKER_OID = "1.3.6.1.4.1.99999.1"+ private const val ECDSA_SHA256 = "1.2.840.10045.4.3.2"+ private const val COMMON_NAME = "2.5.4.3"++ /** A self-signed X.509 v3 certificate over [pair]'s public key, valid for ten years, signed with its private key. */+ internal fun selfSigned(extensionId: String, pair: KeyPair, challenge: ByteArray): ByteArray {+ val name = seq(set(seq(oid(COMMON_NAME), tlv(0x0C, "Myspoti desktop TEST-ONLY software key ($extensionId)".toByteArray()))))+ val now = System.currentTimeMillis()+ val validity = seq(utcTime(now - 60_000), utcTime(now + 10L * 365 * 24 * 3_600_000))+ val marker = ("myspoti-software-test-only;challenge=" + Base64.getEncoder().encodeToString(challenge)).toByteArray()+ val extensions = tlv(0xA3, seq(seq(oid(MARKER_OID), tlv(0x04, marker))))+ val serial = BigInteger(64, java.security.SecureRandom()).abs().add(BigInteger.ONE)+ val algorithm = seq(oid(ECDSA_SHA256))+ val tbs = seq(+ tlv(0xA0, tlv(0x02, byteArrayOf(2))),+ tlv(0x02, serial.toByteArray()),+ algorithm,+ name,+ validity,+ name,+ pair.public.encoded,+ extensions,+ )+ val signature = Signature.getInstance("SHA256withECDSA").apply { initSign(pair.private); update(tbs) }.sign()+ return seq(tbs, algorithm, tlv(0x03, byteArrayOf(0) + signature))+ }++ // ── DER, just what a certificate needs ──++ private fun tlv(tag: Int, content: ByteArray): ByteArray {+ val out = ByteArrayOutputStream()+ out.write(tag)+ when {+ content.size < 0x80 -> out.write(content.size)+ content.size < 0x100 -> { out.write(0x81); out.write(content.size) }+ else -> { out.write(0x82); out.write(content.size shr 8); out.write(content.size and 0xFF) }+ }+ out.write(content)+ return out.toByteArray()+ }++ private fun seq(vararg parts: ByteArray) = tlv(0x30, parts.fold(ByteArray(0)) { a, b -> a + b })+ private fun set(vararg parts: ByteArray) = tlv(0x31, parts.fold(ByteArray(0)) { a, b -> a + b })++ private fun oid(dotted: String): ByteArray {+ val n = dotted.split('.').map { it.toLong() }+ val out = ByteArrayOutputStream()+ out.write((n[0] * 40 + n[1]).toInt())+ for (v in n.drop(2)) {+ val groups = generateSequence(v) { it shr 7 }.takeWhile { it > 0 }.toList().ifEmpty { listOf(0L) }.reversed()+ groups.forEachIndexed { i, g -> out.write(((g and 0x7F) or if (i < groups.lastIndex) 0x80L else 0L).toInt()) }+ }+ return tlv(0x06, out.toByteArray())+ }++ private fun utcTime(millis: Long): ByteArray {+ val f = java.text.SimpleDateFormat("yyMMddHHmmss'Z'", java.util.Locale.US).apply { timeZone = java.util.TimeZone.getTimeZone("UTC") }+ return tlv(0x17, f.format(java.util.Date(millis)).toByteArray())+ }+ }+}diff --git a/base/extensions-cli/src/test/kotlin/app/myspoti/extensions/cli/SoftwareAttestationTest.kt b/base/extensions-cli/src/test/kotlin/app/myspoti/extensions/cli/SoftwareAttestationTest.ktnew file mode 100644index 00000000..967cb548--- /dev/null+++ b/base/extensions-cli/src/test/kotlin/app/myspoti/extensions/cli/SoftwareAttestationTest.kt@@ -0,0 +1,172 @@+package app.myspoti.extensions.cli++import app.myspoti.extensions.ActionRequest+import app.myspoti.extensions.Attestation+import app.myspoti.extensions.ExtensionRuntime+import app.myspoti.extensions.Hook+import app.myspoti.extensions.Host+import app.myspoti.extensions.Manifest+import app.myspoti.extensions.MemoryStorage+import app.myspoti.extensions.Storage+import app.myspoti.extensions.TrackInfo+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertNotEquals+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Assert.fail+import org.junit.Rule+import org.junit.Test+import org.junit.rules.TemporaryFolder+import java.io.File+import java.security.KeyFactory+import java.security.PublicKey+import java.security.Signature+import java.security.cert.CertificateFactory+import java.security.cert.X509Certificate+import java.security.spec.X509EncodedKeySpec+import java.util.Base64++/** The desktop runner's software keys: sign/verify round trips, one key per extension, and `myspoti.attest` through the sandbox. */+class SoftwareAttestationTest {+ @get:Rule val tmp = TemporaryFolder()++ private val track = TrackInfo("abc", "spotify:track:abc", "Song", "Artist", listOf("Artist"), "Album", 180_000)+ private fun keys(dir: File = File(tmp.root, "attest")) = SoftwareAttestation(dir)++ private fun publicKey(spki: String): PublicKey = KeyFactory.getInstance("EC").generatePublic(X509EncodedKeySpec(Base64.getDecoder().decode(spki)))++ private fun verifies(spki: String, text: String, signature: String): Boolean =+ Signature.getInstance("SHA256withECDSA").apply { initVerify(publicKey(spki)); update(text.toByteArray()) }.verify(Base64.getDecoder().decode(signature))++ private fun certificate(der: String) = CertificateFactory.getInstance("X.509").generateCertificate(Base64.getDecoder().decode(der).inputStream()) as X509Certificate++ @Test fun signaturesVerifyWithTheEnrolledPublicKeyAndOnlyForTheSameText() {+ val k = keys()+ val enrollment = k.enroll("io.github.test.a", "challenge".toByteArray())+ assertEquals(enrollment.publicKey, k.publicKey("io.github.test.a"))+ val text = "POST\n/v1/sync\n1700000000\nnonce-1\nabc123"+ val signature = k.sign("io.github.test.a", text.toByteArray())+ assertTrue(verifies(enrollment.publicKey, text, signature))+ assertFalse(verifies(enrollment.publicKey, text + "x", signature))+ // The public key is an EC P-256 SPKI.+ assertEquals("EC", publicKey(enrollment.publicKey).algorithm)+ assertEquals(91, Base64.getDecoder().decode(enrollment.publicKey).size)+ }++ @Test fun theChainIsOneSelfSignedCertificateMarkedTestOnly() {+ val enrollment = keys().enroll("io.github.test.a", "server-challenge".toByteArray())+ assertEquals(1, enrollment.certChain.size)+ val cert = certificate(enrollment.certChain[0])+ assertEquals(enrollment.publicKey, Base64.getEncoder().encodeToString(cert.publicKey.encoded))+ cert.verify(cert.publicKey)+ cert.checkValidity()+ assertTrue(cert.subjectX500Principal.name, cert.subjectX500Principal.name.contains("TEST-ONLY"))+ assertEquals(cert.subjectX500Principal, cert.issuerX500Principal)+ // Not Google's attestation extension: a real verifier finds none and refuses the chain.+ assertNull(cert.getExtensionValue("1.3.6.1.4.1.11129.2.1.17"))+ val marker = String(cert.getExtensionValue(SoftwareAttestation.MARKER_OID)!!)+ assertTrue(marker.contains("myspoti-software-test-only;challenge=" + Base64.getEncoder().encodeToString("server-challenge".toByteArray())))+ }++ @Test fun theKeySurvivesBetweenRunsAndEnrollingAgainReplacesIt() {+ val first = keys().enroll("io.github.test.a", "c1".toByteArray())+ val again = keys()+ assertEquals(first.publicKey, again.publicKey("io.github.test.a"))+ assertTrue(verifies(first.publicKey, "x", again.sign("io.github.test.a", "x".toByteArray())))+ val second = again.enroll("io.github.test.a", "c2".toByteArray())+ assertNotEquals(first.publicKey, second.publicKey)+ val signature = keys().sign("io.github.test.a", "x".toByteArray())+ assertTrue(verifies(second.publicKey, "x", signature))+ assertFalse(verifies(first.publicKey, "x", signature))+ }++ @Test fun noKeyExistsBeforeEnrollAndSignThrows() {+ val k = keys()+ assertNull(k.publicKey("io.github.test.a"))+ try { k.sign("io.github.test.a", "x".toByteArray()); fail("signed without a key") } catch (e: IllegalStateException) { assertTrue(e.message!!.contains("not enrolled")) }+ }++ @Test fun resetDeletesTheKeyOfThatExtensionOnly() {+ val k = keys()+ k.enroll("io.github.test.a", "c".toByteArray())+ val b = k.enroll("io.github.test.b", "c".toByteArray())+ k.reset("io.github.test.a")+ k.reset("io.github.test.never")+ assertNull(k.publicKey("io.github.test.a"))+ assertEquals(b.publicKey, k.publicKey("io.github.test.b"))+ assertTrue(verifies(b.publicKey, "x", k.sign("io.github.test.b", "x".toByteArray())))+ }++ @Test fun twoExtensionsNeverShareAKey() {+ val k = keys()+ val a = k.enroll("io.github.test.a", "c".toByteArray())+ assertNull(k.publicKey("io.github.test.b"))+ try { k.sign("io.github.test.b", "x".toByteArray()); fail("b signed with a's key") } catch (_: IllegalStateException) {}+ val b = k.enroll("io.github.test.b", "c".toByteArray())+ assertNotEquals(a.publicKey, b.publicKey)+ val bySigner = k.sign("io.github.test.a", "x".toByteArray())+ assertTrue(verifies(a.publicKey, "x", bySigner))+ assertFalse(verifies(b.publicKey, "x", bySigner))+ // An id that is the start of another's does not reach its key file either.+ assertNull(k.publicKey("io.github.test"))+ assertNotEquals(Attestation.alias("io.github.test.a"), Attestation.alias("io.github.test.a.b"))+ }++ // ── Through the sandbox, as an extension uses it ──++ private class DesktopLikeHost(val keys: Attestation) : Host {+ override fun log(extensionId: String, message: String) {}+ override fun storage(extensionId: String): Storage = MemoryStorage()+ override fun setting(extensionId: String, key: String): String? = null+ override fun attestation(): Attestation = keys+ }++ private fun run(id: String, host: Host, script: String, vararg actions: String): String? {+ val m = Manifest(id, "Attest", "1.0", author = "me", actions = (listOf("lyrics.provide") + actions).map { ActionRequest(it, "Proves this is a real install") })+ val js = "myspoti.provide('lyrics', function () { try { return { v: (function () { $script })() }; } catch (e) { return { v: 'error: ' + e.message }; } });"+ return ExtensionRuntime(m, js, host, m.asks().map { it.key }.toSet()).use { it.start(); it.call(Hook.LYRICS, track.toJson(), 3_000) }+ }++ private fun value(json: String?) = kotlinx.serialization.json.Json.parseToJsonElement(json!!).let { (it as kotlinx.serialization.json.JsonObject)["v"]!! }++ @Test fun anExtensionSignsAndItsServerVerifiesWithTheKeyFromEnroll() {+ val host = DesktopLikeHost(keys())+ val out = run("io.github.test.a", host, """+ var e = myspoti.attest.enroll('nonce-from-server');+ var text = ['POST', '/v1/events', '1700000000', 'n-1', myspoti.util.sha256('{"a":1}')].join('\n');+ return { publicKey: e.publicKey, same: myspoti.attest.publicKey() === e.publicKey, chain: e.certChain.length, text: text, signature: myspoti.attest.sign(text) };+ """, "attest")+ val o = value(out) as kotlinx.serialization.json.JsonObject+ fun s(k: String) = (o[k] as kotlinx.serialization.json.JsonPrimitive).content+ assertEquals("true", s("same"))+ assertEquals("1", s("chain"))+ assertTrue(verifies(s("publicKey"), s("text"), s("signature")))+ assertFalse(verifies(s("publicKey"), s("text") + "!", s("signature")))+ }++ @Test fun anExtensionCannotSignWithAnotherExtensionsKey() {+ val host = DesktopLikeHost(keys())+ val a = run("io.github.test.a", host, "return myspoti.attest.enroll('c').publicKey;", "attest")+ // b has the right but never enrolled: a's key is not reachable from it, by any call.+ assertEquals("null", value(run("io.github.test.b", host, "return myspoti.attest.publicKey();", "attest")).toString())+ assertTrue(value(run("io.github.test.b", host, "return myspoti.attest.sign('x');", "attest")).toString().contains("not enrolled"))+ val b = run("io.github.test.b", host, "return myspoti.attest.enroll('c').publicKey;", "attest")+ assertNotEquals(a, b)+ val signed = value(run("io.github.test.b", host, "return myspoti.attest.sign('x');", "attest")).toString().trim('"')+ assertTrue(verifies(value(b).toString().trim('"'), "x", signed))+ assertFalse(verifies(value(a).toString().trim('"'), "x", signed))+ // Resetting b leaves a's key.+ run("io.github.test.b", host, "myspoti.attest.reset(); return 1;", "attest")+ assertEquals("null", value(run("io.github.test.b", host, "return myspoti.attest.publicKey();", "attest")).toString())+ assertEquals(value(a), value(run("io.github.test.a", host, "return myspoti.attest.publicKey();", "attest")))+ }++ @Test fun withoutTheActionTheSandboxRefusesBeforeTheKeysAreTouched() {+ val host = DesktopLikeHost(keys())+ val out = run("io.github.test.a", host, "return myspoti.attest.enroll('c');")+ assertTrue(out, out!!.contains("attest is not in this extension's manifest"))+ assertNull(host.keys.publicKey("io.github.test.a"))+ assertFalse(File(tmp.root, "attest").exists())+ }+}diff --git a/base/extensions/src/main/kotlin/app/myspoti/extensions/Actions.kt b/base/extensions/src/main/kotlin/app/myspoti/extensions/Actions.ktindex 7fab86a0..9eab5883 100644--- a/base/extensions/src/main/kotlin/app/myspoti/extensions/Actions.kt+++ b/base/extensions/src/main/kotlin/app/myspoti/extensions/Actions.kt@@ -93,7 +93,9 @@ enum class Action(WEBVIEW_AUTH("webview.auth", Level.CRITICAL, Area.OTHER, "Key", "Sign in on a website","myspoti.auth.open({ url, callback }) → myspoti.on('auth'): a full web view with its own cookies, apart from the app's; only the callback address comes back"),STORAGE("storage", Level.NORMAL, null, "Save", "Keep its own data",- "myspoti.storage get/set/remove (512 KB)");+ "myspoti.storage get/set/remove (512 KB)"),+ ATTEST("attest", Level.NORMAL, null, "Fingerprint", "Prove this is Myspoti",+ "myspoti.attest enroll/publicKey/sign/reset: a signing key of its own in this phone's hardware keystore, so its server can tell its requests come from a genuine Myspoti install");companion object {fun of(key: String) = entries.firstOrNull { it.key == key }diff --git a/base/extensions/src/main/kotlin/app/myspoti/extensions/Attest.kt b/base/extensions/src/main/kotlin/app/myspoti/extensions/Attest.ktnew file mode 100644index 00000000..ead83f48--- /dev/null+++ b/base/extensions/src/main/kotlin/app/myspoti/extensions/Attest.kt@@ -0,0 +1,41 @@+package app.myspoti.extensions++import kotlinx.serialization.Serializable++/**+ * The keys behind `myspoti.attest` ([Action.ATTEST]), one signing key per extension. The app+ * keeps them in the Android hardware keystore with a key attestation; the desktop runner+ * (`myspoti-ext`) keeps a software key for testing. The runtime has already checked the right and+ * the limits: an implementation only does the work, and throws with a plain reason.+ */+interface Attestation {+ /**+ * Creates the extension's EC P-256 signing key, or replaces it, with [challenge] as the+ * attestation challenge: the chain proves the key lives in hardware and names the app that made it.+ */+ fun enroll(extensionId: String, challenge: ByteArray): Enrollment++ /** The current key's public half, base64 SPKI, or null before [enroll]. */+ fun publicKey(extensionId: String): String?++ /** Base64 DER ECDSA-SHA256 signature of [data], made with the extension's key. Throws when it has none. */+ fun sign(extensionId: String, data: ByteArray): String++ /** Deletes the extension's key: nothing when it has none. Done when the extension is uninstalled. */+ fun reset(extensionId: String)++ companion object {+ /** The keystore alias of an extension's key: ids are unique, so no extension reaches another's key. */+ fun alias(extensionId: String) = "myspoti.ext.attest.$extensionId"++ /** The longest challenge `enroll` takes, in bytes (UTF-8). */+ const val MAX_CHALLENGE_BYTES = 128++ /** The longest text `sign` takes, in bytes (UTF-8). */+ const val MAX_SIGN_BYTES = 64 * 1024+ }+}++/** What `enroll` gives the script: the public key (base64 SPKI) and the attestation chain (base64 DER certificates, leaf first). */+@Serializable+data class Enrollment(val publicKey: String, val certChain: List<String>)diff --git a/base/extensions/src/main/kotlin/app/myspoti/extensions/ExtensionRuntime.kt b/base/extensions/src/main/kotlin/app/myspoti/extensions/ExtensionRuntime.ktindex 41c0c17d..dc682248 100644--- a/base/extensions/src/main/kotlin/app/myspoti/extensions/ExtensionRuntime.kt+++ b/base/extensions/src/main/kotlin/app/myspoti/extensions/ExtensionRuntime.kt@@ -5,6 +5,7 @@ import kotlinx.coroutines.runBlockingimport kotlinx.coroutines.withTimeoutimport kotlinx.serialization.builtins.ListSerializerimport kotlinx.serialization.builtins.MapSerializer+import kotlinx.serialization.builtins.nullableimport kotlinx.serialization.builtins.serializerimport kotlinx.serialization.json.JsonArrayimport kotlinx.serialization.json.JsonObject@@ -85,6 +86,10 @@ class ExtensionRuntime(/** The biggest answer a Spotify call gives the script. */val spotifyResultChars: Int = 2 * 1024 * 1024,val storageChars: Int = 512 * 1024,+ /** `myspoti.attest.sign` calls. */+ val attestSignsPerMinute: Int = 120,+ /** `myspoti.attest.enroll` calls: a new key each time, and a hardware keystore that is slow to make them. */+ val attestEnrollsPerHour: Int = 5,)private val id = manifest.id@@ -96,6 +101,8 @@ class ExtensionRuntime(private val requestTimes = ArrayDeque<Long>()private val spotifyTimes = ArrayDeque<Long>()private val notifyTimes = ArrayDeque<Long>()+ private val attestSignTimes = ArrayDeque<Long>()+ private val attestEnrollTimes = ArrayDeque<Long>()/** Time spent waiting for the user in the run on the thread now: it is not the script's time. */@Volatile private var activePause: Pause? = null@@ -295,7 +302,7 @@ class ExtensionRuntime(ScriptableObject.putProperty(o, name, LambdaFunction(s, name, length) { _, _, _, args -> fn(args) ?: Undefined.instance })fun str(args: Array<Any?>, i: Int): String = args.getOrNull(i)?.takeUnless { it is Undefined }?.let { Context.toString(it) }.orEmpty()- def("info", 0) { ExtJson.encodeToString(Info.serializer(), Info(manifest.id, manifest.name, manifest.version, has(Action.PLAYBACK_MIRROR))) }+ def("info", 0) { ExtJson.encodeToString(Info.serializer(), Info(manifest.id, manifest.name, manifest.version, has(Action.PLAYBACK_MIRROR), has(Action.ATTEST))) }def("mayProvide", 1) { a ->val key = str(a, 0)val hook = Hook.of(key) ?: throw error("unknown hook \"$key\" (known: ${Hook.entries.joinToString { it.key }})")@@ -364,6 +371,10 @@ class ExtensionRuntime(val request = try { AuthRequest(str(a, 0), str(a, 1), hidden = a.getOrNull(2) == true).checked() } catch (e: IllegalArgumentException) { throw error(e.message ?: "auth.open: refused") }runCatching { host.openAuth(id, request) }.getOrElse { throw error("auth.open: ${it.message ?: it.javaClass.simpleName}") }}+ def("attestEnroll", 1) { a -> attestEnroll(str(a, 0)) }+ def("attestPublicKey", 0) { attest().let { at -> ExtJson.encodeToString(String.serializer().nullable, at.publicKey(id)) } }+ def("attestSign", 1) { a -> attestSign(str(a, 0)) }+ def("attestReset", 0) { attest().reset(id); null }def("whenOnline", 0) { need(Action.NETWORK); host.whenOnline(id); null }def("log", 1) { a -> host.log(id, str(a, 0).take(2_000)); null }def("util", 2) { a -> util(str(a, 0), str(a, 1)) }@@ -379,6 +390,31 @@ class ExtensionRuntime()}+ /** The keys of `myspoti.attest`: the right is checked, and the host must have some. */+ private fun attest(): Attestation {+ need(Action.ATTEST)+ return host.attestation() ?: throw error("attest: this app cannot make hardware-backed keys here")+ }++ /** `attest.enroll(challenge)`: a new key, at most [Limits.attestEnrollsPerHour] an hour. */+ private fun attestEnroll(challenge: String): String {+ val at = attest()+ val bytes = challenge.toByteArray()+ if (bytes.isEmpty() || bytes.size > Attestation.MAX_CHALLENGE_BYTES) throw error("attest.enroll: the challenge is 1 to ${Attestation.MAX_CHALLENGE_BYTES} bytes")+ if (!allowRequest(attestEnrollTimes, limits.attestEnrollsPerHour, 3_600_000L)) throw error("attest.enroll: at most ${limits.attestEnrollsPerHour} an hour")+ val enrollment = runCatching { at.enroll(id, bytes) }.getOrElse { throw error("attest.enroll: ${it.message ?: it.javaClass.simpleName}") }+ return ExtJson.encodeToString(Enrollment.serializer(), enrollment)+ }++ /** `attest.sign(text)`: the signature of the UTF-8 text, [Limits.attestSignsPerMinute] a minute. */+ private fun attestSign(text: String): String {+ val at = attest()+ val bytes = text.toByteArray()+ if (bytes.size > Attestation.MAX_SIGN_BYTES) throw error("attest.sign: text over ${Attestation.MAX_SIGN_BYTES / 1024} KB")+ throttle(attestSignTimes, limits.attestSignsPerMinute, "attest.sign calls")+ return runCatching { at.sign(id, bytes) }.getOrElse { throw error("attest.sign: ${it.message ?: it.javaClass.simpleName}") }+ }+private fun http(json: String): String {val r = runCatching { ExtJson.decodeFromString(HttpRequest.serializer(), json) }.getOrElse { throw error("http: unreadable request") }refusal(r)?.let { throw error(it) }@@ -562,7 +598,7 @@ class ExtensionRuntime(}@kotlinx.serialization.Serializable- private data class Info(val id: String, val name: String, val version: String, val mirror: Boolean = false)+ private data class Info(val id: String, val name: String, val version: String, val mirror: Boolean = false, val attest: Boolean = false)/** Thrown inside the script's thread when its time is up; not catchable by the script. */private class TimeLimit : Error("time limit")diff --git a/base/extensions/src/main/kotlin/app/myspoti/extensions/Host.kt b/base/extensions/src/main/kotlin/app/myspoti/extensions/Host.ktindex 69ed59f3..bd052b1e 100644--- a/base/extensions/src/main/kotlin/app/myspoti/extensions/Host.kt+++ b/base/extensions/src/main/kotlin/app/myspoti/extensions/Host.kt@@ -83,6 +83,9 @@ interface Host {*/fun whenOnline(extensionId: String) {}+ /** The keys behind `myspoti.attest` ([Action.ATTEST]); null: this host cannot make any, and the script gets an error. */+ fun attestation(): Attestation? = null+fun userAgent(extensionId: String) = "Myspoti-Extension/$API_VERSION ($extensionId)"}diff --git a/base/extensions/src/main/resources/app/myspoti/extensions/prelude.js b/base/extensions/src/main/resources/app/myspoti/extensions/prelude.jsindex f8530d3b..5f398be9 100644--- a/base/extensions/src/main/resources/app/myspoti/extensions/prelude.js+++ b/base/extensions/src/main/resources/app/myspoti/extensions/prelude.js@@ -122,9 +122,9 @@/*** What this app understands beyond the first API, for an extension to adapt to: "audio.manifest",- * "audio.expires", "audio.quality", "audio.source", "audio.ahead", "http.all", "status", "raw.base64", and "player.localMute" only when the user granted playback.mirror.+ * "audio.expires", "audio.quality", "audio.source", "audio.ahead", "http.all", "status", "raw.base64", "player.localMute" only when the user granted playback.mirror, and "attest" only when it granted attest.*/- features: Object.freeze(['audio.manifest', 'audio.expires', 'audio.quality', 'audio.source', 'audio.ahead', 'http.all', 'status', 'raw.base64'].concat(parse(host.info()).mirror ? ['player.localMute'] : [])),+ features: Object.freeze(['audio.manifest', 'audio.expires', 'audio.quality', 'audio.source', 'audio.ahead', 'http.all', 'status', 'raw.base64'].concat(parse(host.info()).mirror ? ['player.localMute'] : [], parse(host.info()).attest ? ['attest'] : [])),/*** A sign-in page (webview.auth): open({ url, callback, hidden }) shows url in a web view of its@@ -139,6 +139,20 @@},}),+ /**+ * A signing key of its own in the phone's hardware keystore (attest), so its server can tell its+ * requests come from a genuine Myspoti install. No key exists before enroll(challenge), which+ * returns { publicKey, certChain } (base64; the Android key attestation chain, the challenge+ * inside). publicKey() is that key or null, sign(text) a base64 DER ECDSA-SHA256 signature of+ * the UTF-8 text (it throws before enroll), reset() deletes the key.+ */+ attest: Object.freeze({+ enroll: function (challenge) { return parse(host.attestEnroll(String(challenge))); },+ publicKey: function () { return parse(host.attestPublicKey()); },+ sign: function (text) { return host.attestSign(String(text)); },+ reset: function () { host.attestReset(); },+ }),+/** Work that waits for the network (network): whenOnline() asks for one on('online') once it is there. */work: Object.freeze({whenOnline: function () { host.whenOnline(); },diff --git a/base/extensions/src/test/kotlin/app/myspoti/extensions/ActionsTest.kt b/base/extensions/src/test/kotlin/app/myspoti/extensions/ActionsTest.ktindex 76ccd73b..7e125edc 100644--- a/base/extensions/src/test/kotlin/app/myspoti/extensions/ActionsTest.kt+++ b/base/extensions/src/test/kotlin/app/myspoti/extensions/ActionsTest.kt@@ -31,7 +31,7 @@ class ActionsTest {// ── The catalogue ──@Test fun theCatalogueIsClosedAndComplete() {- assertEquals(23, Action.entries.size)+ assertEquals(24, Action.entries.size)assertEquals(Action.entries.size, Action.entries.map { it.key }.toSet().size)assertEquals(setOf("audio.source", "download.source", "library.write", "playlists.write", "spotify.raw", "webview.page", "webview.auth", "playback.mirror"),diff --git a/base/extensions/src/test/kotlin/app/myspoti/extensions/AttestTest.kt b/base/extensions/src/test/kotlin/app/myspoti/extensions/AttestTest.ktnew file mode 100644index 00000000..3c736887--- /dev/null+++ b/base/extensions/src/test/kotlin/app/myspoti/extensions/AttestTest.kt@@ -0,0 +1,133 @@+package app.myspoti.extensions++import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertTrue+import org.junit.Test++/** `myspoti.attest`: the right it needs, what it checks before the host's keys are asked, and its limits. */+class AttestTest {+ private val track = TrackInfo("abc", "spotify:track:abc", "Song", "Artist", listOf("Artist"), "Album", 180_000)++ /** Keys that are only a record of what was asked: the host's side is tested with the desktop runner's real ones. */+ private class FakeKeys : Attestation {+ val enrolled = mutableListOf<Pair<String, String>>()+ val keys = mutableSetOf<String>()+ val reset = mutableListOf<String>()+ override fun enroll(extensionId: String, challenge: ByteArray): Enrollment {+ enrolled += extensionId to String(challenge)+ keys += extensionId+ return Enrollment("spki-$extensionId", listOf("leaf", "root"))+ }+ override fun publicKey(extensionId: String): String? = if (extensionId in keys) "spki-$extensionId" else null+ override fun sign(extensionId: String, data: ByteArray): String {+ check(extensionId in keys) { "not enrolled" }+ return "sig:${String(data)}"+ }+ override fun reset(extensionId: String) { keys -= extensionId; reset += extensionId }+ }++ private class Host(val keys: Attestation?) : app.myspoti.extensions.Host {+ override fun log(extensionId: String, message: String) {}+ override fun storage(extensionId: String): Storage = MemoryStorage()+ override fun setting(extensionId: String, key: String): String? = null+ override fun attestation(): Attestation? = keys+ }++ private fun manifest(vararg names: String) = Manifest("io.github.test.attest", "Attest", "1.0", author = "me",+ actions = (listOf("lyrics.provide") + names).map { ActionRequest(it, "Proves this is a real install") })++ /** The value of [body] (or its error message) as the script sees it. */+ private fun eval(body: String, host: app.myspoti.extensions.Host, declared: Array<String> = arrayOf("attest"), granted: Set<String> = declared.toSet() + "lyrics.provide", limits: ExtensionRuntime.Limits = ExtensionRuntime.Limits()): String? =+ ExtensionRuntime(manifest(*declared), "myspoti.provide('lyrics', function () { try { return { v: $body }; } catch (e) { return { v: 'error: ' + e.message }; } });", host, granted, limits)+ .use { it.start(); it.call(Hook.LYRICS, track.toJson(), 3_000) }++ @Test fun theActionIsNormalAndNeedsNoAreaLikeTheOtherSupportActions() {+ assertEquals(Level.NORMAL, Action.ATTEST.level)+ assertEquals(null, Action.ATTEST.area)+ assertEquals(Action.ATTEST, Action.of("attest"))+ assertEquals(emptyList<String>(), manifest("attest").problems())+ assertTrue(manifest("attest").asks().any { it.key == "attest" && it.why.isNotBlank() })+ }++ @Test fun withoutTheActionEveryCallThrowsAndNoKeyIsTouched() {+ val keys = FakeKeys()+ for (call in listOf("myspoti.attest.enroll('c')", "myspoti.attest.publicKey()", "myspoti.attest.sign('x')", "myspoti.attest.reset()")) {+ val out = eval(call, Host(keys), declared = emptyArray())!!+ assertTrue("$call: $out", out.contains("attest is not in this extension's manifest"))+ }+ assertTrue(keys.enrolled.isEmpty() && keys.reset.isEmpty())+ }++ @Test fun declaredButNotGrantedIsRefusedToo() {+ val keys = FakeKeys()+ val out = eval("myspoti.attest.enroll('c')", Host(keys), granted = setOf("lyrics.provide"))!!+ assertTrue(out, out.contains("the user did not grant attest"))+ assertTrue(keys.enrolled.isEmpty())+ }++ @Test fun enrollGivesTheKeyAndTheChainAndPassesTheChallenge() {+ val keys = FakeKeys()+ assertEquals("""{"v":null}""", eval("myspoti.attest.publicKey()", Host(keys)))+ assertEquals("""{"v":{"publicKey":"spki-io.github.test.attest","certChain":["leaf","root"]}}""", eval("myspoti.attest.enroll('server-challenge-1')", Host(keys)))+ assertEquals(listOf("io.github.test.attest" to "server-challenge-1"), keys.enrolled)+ assertEquals("""{"v":"spki-io.github.test.attest"}""", eval("myspoti.attest.publicKey()", Host(keys)))+ assertEquals("""{"v":"sig:GET /x"}""", eval("myspoti.attest.sign('GET /x')", Host(keys)))+ eval("myspoti.attest.reset()", Host(keys))+ assertEquals(listOf("io.github.test.attest"), keys.reset)+ assertEquals("""{"v":null}""", eval("myspoti.attest.publicKey()", Host(keys)))+ }++ @Test fun signBeforeEnrollThrowsAClearError() {+ val out = eval("myspoti.attest.sign('x')", Host(FakeKeys()))!!+ assertTrue(out, out.contains("attest.sign: not enrolled"))+ }++ @Test fun theChallengeIsOneToOneHundredTwentyEightBytes() {+ val keys = FakeKeys()+ for (bad in listOf("''", "'a'.repeat(129)", "'é'.repeat(65)")) {+ val out = eval("myspoti.attest.enroll($bad)", Host(keys))!!+ assertTrue("$bad: $out", out.contains("the challenge is 1 to 128 bytes"))+ }+ assertTrue(keys.enrolled.isEmpty())+ assertTrue(eval("myspoti.attest.enroll('a'.repeat(128)).publicKey", Host(keys))!!.startsWith("""{"v":"spki-"""))+ assertTrue(eval("myspoti.attest.enroll('é'.repeat(64)).publicKey", Host(keys))!!.startsWith("""{"v":"spki-"""))+ }++ @Test fun aHostWithoutKeysSaysSo() {+ val out = eval("myspoti.attest.enroll('c')", Host(null))!!+ assertTrue(out, out.contains("cannot make hardware-backed keys"))+ }++ @Test fun enrollIsLimitedPerHourAndSignPerMinute() {+ val keys = FakeKeys()+ val limits = ExtensionRuntime.Limits(attestSignsPerMinute = 3, attestEnrollsPerHour = 2)+ assertEquals("""{"v":"ok,ok,attest.enroll: at most 2 an hour"}""", eval(+ "(function () { var r = []; for (var i = 0; i < 3; i++) { try { myspoti.attest.enroll('c'); r.push('ok'); } catch (e) { r.push(e.message); } } return r.join(','); })()", Host(keys), limits = limits))+ // The window is the runtime's: a new one starts with its own count.+ assertEquals("""{"v":"s,s,s,more than 3 attest.sign calls in a minute"}""", eval(+ "(function () { myspoti.attest.enroll('c'); var r = []; for (var i = 0; i < 4; i++) { try { myspoti.attest.sign('x'); r.push('s'); } catch (e) { r.push(e.message); } } return r.join(','); })()", Host(keys), limits = limits))+ // Mind the defaults the docs promise.+ assertEquals(120, ExtensionRuntime.Limits().attestSignsPerMinute)+ assertEquals(5, ExtensionRuntime.Limits().attestEnrollsPerHour)+ }++ @Test fun signTakesAtMost64KB() {+ val keys = FakeKeys()+ val out = eval("(function () { myspoti.attest.enroll('c'); try { myspoti.attest.sign('a'.repeat(65 * 1024)); return 'signed'; } catch (e) { return e.message; } })()", Host(keys))!!+ assertTrue(out, out.contains("attest.sign: text over 64 KB"))+ }++ @Test fun featuresListAttestOnlyWhenGranted() {+ val js = "myspoti.features.indexOf('attest') >= 0"+ assertEquals("""{"v":true}""", eval(js, Host(FakeKeys())))+ assertEquals("""{"v":false}""", eval(js, Host(FakeKeys()), declared = emptyArray()))+ assertFalse(eval(js, Host(FakeKeys()), granted = setOf("lyrics.provide"))!!.contains("true"))+ }++ @Test fun keyAliasesNeverCollideAcrossExtensionIds() {+ val ids = listOf("io.github.a.x", "io.github.a.x.y", "io.github.a", "io.github.a_x")+ assertEquals(ids.size, ids.map(Attestation::alias).toSet().size)+ assertEquals("myspoti.ext.attest.io.github.a.x", Attestation.alias("io.github.a.x"))+ }+}diff --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 55e41af9..e143e35e 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@@ -369,6 +369,9 @@ internal class ControlRelay(private val view: WebView, private val fingerprint:// 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 nullgiven?.second?.forEach { note -> Logbook.log("ad left out: $note"); ADS_LEFT_OUT.incrementAndGet(); app.myspoti.spotify.report.Refusal402.adStateLeftOut() }+ // Marked as holding an ad, yet left as it was: why (which marker, what kept it), once per reason.+ if (given == null && url.contains("/track-playback/") && AD_MARK.containsMatchIn(text))+ app.myspoti.spotify.bridge.AdBlock.whyKept(text)?.takeIf { it != lastAdKept }?.let { why -> lastAdKept = why; Logbook.log("ad kept in the queue: $why") }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)@@ -424,6 +427,8 @@ internal class ControlRelay(private val view: WebView, private val fingerprint:@Volatile private var staleOwn: String? = null@Volatile private var lastCluster: String? = null+ /** The last reason an ad-marked reply was left as it was (logged once per reason). */+ @Volatile private var lastAdKept: String? = null/*** A refused command another route answered 2xx: whether the page's media really plays 10 s@@ -779,14 +784,15 @@ internal class ControlRelay(private val view: WebView, private val fingerprint:}}));} catch (e) { /* the host keeps its fallback identity */ }// The player's media elements, often never added to the document: the bridge- // silences them during an ad ("media.mute"); one started then starts silent.+ // silences them during an ad ("media.mute") or while the song is unheard here+ // ("media.hush"); one started then starts silent.// Silent is a tiny volume, never muted: Chromium pauses muted media of a hidden page.const media = new Set();window.__mspMedia = media;const play = HTMLMediaElement.prototype.play;HTMLMediaElement.prototype.play = function () {media.add(this);- if (window.__mspMuted) { this.muted = false; this.volume = 0.001; }+ if (window.__mspMuted || window.__mspHushed) { this.muted = false; this.volume = 0.001; }return play.apply(this, arguments);};const relayed = /^https:\/\/([a-z0-9-]+\.)*spotify\.com\/(connect-state|track-playback)\/v1\//;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 5c13b46a..7d073ed4 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,12 @@ object Logbook {}}+ /**+ * [url] without its query string and fragment: they carry tokens, ids and search terms, and a+ * report is handed to other people. For every URL put in a log line.+ */+ fun noQuery(url: String): String = url.substringBefore('#').substringBefore('?')+/** When each [logEvery] key last wrote, and how many lines it held back since. */private val every = HashMap<String, LongArray>()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 1c815f95..9ebbf3af 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@@ -192,7 +192,7 @@ class WebPlayerHost(private val context: Context) : BridgeHost {override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? {val url = request.url.toString()if (AdBlock.isBlocked(url)) {- Logbook.log("blocked ad request ${url.take(120)}")+ Logbook.log("blocked ad request ${Logbook.noQuery(url).take(120)}")// 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)))}@@ -221,13 +221,13 @@ class WebPlayerHost(private val context: Context) : BridgeHost {if (debuggable) Logbook.log("audio proxied ${url.substringAfterLast('/').take(12)}…")return proxied}- Logbook.log("audio proxy failed, the WebView fetches it: ${url.take(110)}")+ Logbook.log("audio proxy failed, the WebView fetches it: ${Logbook.noQuery(url).take(110)}")}return null}override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {- Logbook.log("page start ${url.take(120)}")+ Logbook.log("page start ${Logbook.noQuery(url).take(120)}")mainFrameFailed = false// A load that never ends (measured: a reload's document request answered nothing// for 9 minutes, the page stayed "loading", empty, without the bridge).@@ -242,7 +242,7 @@ class WebPlayerHost(private val context: Context) : BridgeHost {override fun onReceivedError(view: WebView, request: WebResourceRequest, error: android.webkit.WebResourceError) {if (request.url.host?.contains("spotify") == true)- Logbook.log("load error ${error.errorCode} ${error.description} ${request.url.toString().take(120)}")+ Logbook.log("load error ${error.errorCode} ${error.description} ${Logbook.noQuery(request.url.toString()).take(120)}")// ERR_ABORTED: a load this app stopped itself (a timeout, a newer load) — not a failure.if (request.isForMainFrame && request.url.host == PLAYER_HOST && "ERR_ABORTED" !in error.description.toString())playerPageFailed("load error ${error.errorCode}")@@ -272,7 +272,7 @@ class WebPlayerHost(private val context: Context) : BridgeHost {}override fun onPageFinished(view: WebView, url: String) {- Logbook.log("page finished ${url.take(120)}")+ Logbook.log("page finished ${Logbook.noQuery(url).take(120)}")main.removeCallbacks(loadTimeout)if (url.startsWith(PLAYER_URL) && !mainFrameFailed) { pageFailures = 0; main.removeCallbacks(retryPlayerPage) }_url.value = urldiff --git a/docs/CHANGELOG-full.md b/docs/CHANGELOG-full.mdindex d8f61970..2b334905 100644--- a/docs/CHANGELOG-full.md+++ b/docs/CHANGELOG-full.md@@ -2,6 +2,22 @@Every change, release by release. The short version is in [CHANGELOG.md](../CHANGELOG.md), which the app and the GitHub releases show.+## 2.1.0++Stable release of the 2.0.2 betas (see [CHANGELOG.md](../CHANGELOG.md) for their notes), plus:++- **Connect mirror for extension sources**: while an audio-source extension plays a Spotify song, the Web Player plays the same song muted at low quality as this phone's Connect device. Controls from other devices (official apps included) reach the local player through the track-playback state; transfers away and back, ads and page reloads are held; drift above 1.5 s is corrected. Setting in Playback (on by default, shown only with an audio-source extension).+- **Per-look settings**: one accent colour per look (seeded from the old one); each look's settings list only what concerns it.+- **Immersive pages**: album look-up, folders, local playlists, extensions store / detail / extension page, podcast episode player.+- **Immersive shuffle**: the list's Shuffle pill starts the list shuffled, then cycles shuffle → smart shuffle → off while it plays; the player's shuffle does the same.+- **Search**: a song played from search is played alone, without the list that last registered it (Liked Songs), so Spotify's autoplay follows.+- **Radios** (Classic): the playing-from header opens only real Liked Songs links; the song title falls back to the queue's album, then the track's album, then a name search.+- **Taps**: `wideClickable` (touch bounds expansion) on back buttons; profile buttons take the space around them; the Immersive top bars stop taps from reaching the page without cancelling their own buttons; Library grid feeds the bars' blur.+- **Ads**: DoubleClick's media CDN `s0.2mdn.net` blocked (from coldMEW/Hush, GPL-3.0); ads found by content type and ad ids; a playing muted ad is skipped before any reload; a reloaded page stays muted until a song plays.+- **Data and performance**: Liked Songs read in full once a day, album pages kept on storage, playlist songs reused for 5 min, search debounce and cache, lyrics memory and disk caches with background prefetch on unmetered networks, Glide disk cache at 150 MB with one shared 128 px decode, scrubber read in the draw phase.+- **Extensions API**: optional `attest` action (per-extension Android Keystore key with attestation), see docs/extensions/API.md section 10.+- **Release hygiene**: freeze watch only in beta and debug builds, no query strings in WebView log lines, a stable build fails without a signing key.+## 2.0.1- **402 `COMMAND_FAILED` on every play** (free accounts: Xiaomi Redmi 13 / Indonesia, Samsung A32 / Belarus, issue #55): the same accounts play in Spotui, which sends the Connect commands from the page itself, while Myspoti relays them through OkHttp. A relayed play or transfer answered 402 is now sent once more with the page's own `fetch`; if that one is accepted, the page's commands keep going that way, and only while something plays (checked 10 s later: a command sent from the page can be acknowledged and never delivered). Both refused: the refusal steps run as before. The diagnostic logs the retry's status and whether the page's way was kept.diff --git a/docs/cli.md b/docs/cli.mdindex 415dded5..919d8b48 100644--- a/docs/cli.md+++ b/docs/cli.md@@ -20,7 +20,7 @@ defaults (the beta is `-p app.myspoti`).| Command | Does || --- | --- |-| `status` | Version, debug/beta, signed in or not, what plays (uri, position, duration), installed extensions, whether the screen is open. `player` says who plays: `local` (the app's own player; `source` is `audio-source`, `download` or `file`, and `extension` the id of the extension that gave the stream) or `engine` (Spotify); `routing` is true while the extensions are asked for a song; while the local player has a queue, `playWhenReady` says whether it is to play and `playbackState` whether it is `idle` (stopped by an error), `buffering`, `ready` or `ended`. |+| `status` | Version, debug/beta, signed in or not, what plays (uri, position, duration), installed extensions, whether the screen is open. `player` says who plays: `local` (the app's own player; `source` is `audio-source`, `download` or `file`, and `extension` the id of the extension that gave the stream) or `engine` (Spotify); `routing` is true while the extensions are asked for a song; while the local player has a queue, `playWhenReady` says whether it is to play and `playbackState` whether it is `idle` (stopped by an error), `buffering`, `ready` or `ended`. `mirror` is the Connect mirror (Settings, "Count extension plays on Spotify"): `on` (the setting), `running`, the song it keeps the page on (`uri`, `paused`, `landed` once the page played it, `webPositionMs`), `handedAway` (playback went to another device), `failedUri` (a song the page would not play), and the page under it: `pageUri`, `pagePaused`, `pagePositionMs`, `hushed` (unheard), `quality` (the level given to the page: `low` while it mirrors), `bitrate` and `codec` of what it streams, `playsElsewhere` (another device has Connect), `activeDevice`. || `ext.list` | Installed extensions: version, enabled, running, last error, actions, settings (secret ones masked), and their last `status` probe: `status` (`live`, `inactive`, `unknown` for no answer, `not probed`), `inactive` (skipped for songs' audio and downloads) and `statusDetail`. || `ext.install <zip>` | Installs a package with all it asks, without the prompt. A zip on the computer is pushed first to `…/files/cli/in/`. || `ext.uninstall <id>` | As its page's Uninstall button. |diff --git a/docs/extensions/API.md b/docs/extensions/API.mdindex 31d8b917..56bd5a95 100644--- a/docs/extensions/API.md+++ b/docs/extensions/API.md@@ -598,6 +598,7 @@ until the user accepts them all with the same tick.| `webview.page` | Web | Its own web page | **critical** | takeover | `page` and `message` hooks, `myspoti.page.post` || `webview.auth` | Key | Sign in on a website | **critical** | takeover | `myspoti.auth.open`, `auth` event || `storage` | Save | Keep its own data | normal | shared | `myspoti.storage` (512 KB) |+| `attest` | Fingerprint | Prove this is Myspoti | normal | shared | `myspoti.attest` (section 10) |### 4.1 Old manifests@@ -667,7 +668,7 @@ A script that throws while loading fails to load, with `file:line` in the messag|---|---|| `myspoti.apiVersion` | `1`. || `myspoti.extension` | `{ id, name, version }` from the manifest. |-| `myspoti.features` | What this Myspoti understands beyond the first API: `audio.manifest`, `audio.expires`, `audio.quality`, `audio.ahead` (section 3, `audio-source`), `http.all`, `status` (section 3). Missing on an older Myspoti: test `myspoti.features && myspoti.features.indexOf(name) >= 0`. |+| `myspoti.features` | What this Myspoti understands beyond the first API: `audio.manifest`, `audio.expires`, `audio.quality`, `audio.ahead` (section 3, `audio-source`), `http.all`, `status` (section 3), `attest` (section 10, only when the user granted it). Missing on an older Myspoti: test `myspoti.features && myspoti.features.indexOf(name) >= 0`. || `myspoti.provide(hook, fn)` | Section 3. || `myspoti.on('track' \| 'playback', fn)` | Section 3. Needs `playback.events`. || `myspoti.on('auth', fn)` | Section 3, sign in. Needs `webview.auth`. |@@ -687,6 +688,7 @@ A script that throws while loading fails to load, with `file:line` in the messag| `myspoti.ui.refresh(place)` | Section 3, blocks. The place's action. || `myspoti.page.post(data)` | Section 3, pages. `webview.page`. || `myspoti.spotify.<area>.<method>(...)` | Section 6. |+| `myspoti.attest.enroll(challenge)` / `.publicKey()` / `.sign(text)` / `.reset()` | Section 10. A signing key of its own in the phone's hardware keystore, with its key attestation, to prove requests to your own server. Needs `attest`. || `myspoti.notify(text)` | A short message on screen, 200 characters, with your extension's name. `notify`. || `myspoti.log(...)`, `console.log/info/warn/error(...)` | Same thing: arguments joined by spaces, objects as JSON, 2000 characters at most. || `myspoti.util.base64Encode(s)` / `base64Decode(s)` | UTF-8 text. Decode throws on bad input. |@@ -854,7 +856,7 @@ type means optional/nullable. Returns of "—" mean `null`.| `skipTo(item: {uri,uid?})` | — | write | || `moveInQueue(item: {uri,uid?}, target: {uri,uid?}, after = false)` | — | write | || `setVolume(level: number)` | — | write | |-| `setLocalMute(on: boolean)` | `playback.mirror` (critical) | write | Keeps Spotify playing unheard on this phone (`myspoti.features` has `player.localMute` only when the user granted `playback.mirror`). It can keep Spotify playing silently and counts listens on the user's Spotify account, so the user ticks the accept-risk box. Host rules, whatever the script does: honoured only while Myspoti's own local / extension player is playing; one extension at a time; at most one enable per 20 s; cleared by itself on track change, local pause or stop, the local track's duration, and when the extension is disabled, uninstalled, blocked or crashes. Both players show "Spotify mirrored by <extension>", and the Activity log and Logbook record each enable and clear. Existing installs do not have it until the user accepts the action through the update / consent flow. |+| `setLocalMute(on: boolean)` | `playback.mirror` (critical) | write | Keeps Spotify playing unheard on this phone (`myspoti.features` has `player.localMute` only when the user granted `playback.mirror`). It can keep Spotify playing silently and counts listens on the user's Spotify account, so the user ticks the accept-risk box. Host rules, whatever the script does: honoured only while Myspoti's own local / extension player is playing; one extension at a time; at most one enable per 20 s; cleared by itself on track change, local pause or stop, the local track's duration, and when the extension is disabled, uninstalled, blocked or crashes. Refused while Myspoti's own Connect mirror (Settings, "Count extension plays on Spotify", on by default) plays the song on the page itself, and an extension's mirror ends when that one starts. Both players show "Spotify mirrored by <extension>", and the Activity log and Logbook record each enable and clear. Existing installs do not have it until the user accepts the action through the update / consent flow. || `setSpeed(speed: number)` | — | write | |`media(trackUri)` (also `myspoti.spotify.media(trackUri)`) returns the media manifest Spotify sent the@@ -1124,6 +1126,7 @@ is. `playlists.setCover` takes a JPEG as base64.| Time spent waiting for the user to confirm | Not counted || `myspoti.http` | 120 requests/min, 5 MB per response, 20 s per request, https only; `http.all`: 4 at once || `myspoti.spotify` | 60 calls/min, 256 KB of arguments, 1000 items per list, 2 MB per answer |+| `myspoti.attest` | `sign` 120/min and 64 KB of text; `enroll` 5/hour and a challenge of 128 bytes || Storage | 512 KB (keys and values together) || Sign-in page | One at a time || `myspoti.work.whenOnline()` | 30 s |@@ -1166,6 +1169,7 @@ to the confirmation prompt below. Give absolute paths.)as text; unset ones use the manifest `default`).What the runner does: every right the manifest asks is granted. Storage is in memory for the run.+`myspoti.attest` works with a software key kept between runs (section 10).`log`, `console`, `notify` and failures go to stderr as `[id] message`. `player` controls print`player: <action>` and answer `true`. `myspoti.player.current()` returns the `--title` track.`http` is real (same host rules as the app).@@ -1308,3 +1312,107 @@ store only when it lists at least one).### `raw.request` "Always allow" is per operationA write the user allows for good is a grant on method + host + path pattern. On a multiplexed endpoint (GraphQL / pathfinder, or any request whose JSON body carries `operationName` or a persisted-query `sha256Hash`) the grant also names that operation: it never covers another one. If no operation can be determined from the body on such an endpoint, "Always allow" is not offered and the user is asked each time. The consent shows the real operation, and the revocation list shows it too (`POST https://host/path [operation name]`). Grants stored before this change on such endpoints without an operation were dropped (the user is asked again). Writes declared in the manifest (`writes`) on a multiplexed path cannot cover operations; the user is asked.++## 10. Prove a request comes from a genuine install (`attest`)++Optional and generic: any extension that talks to **its author's own server** can use it, so that+the server can tell a request comes from a Myspoti install running that extension, and not from a+script that pulled a key out of the zip (there is nothing secret in a zip: anyone can read it).+Action `attest` (normal, "Prove this is Myspoti"): the user sees it at install like the others.+Without it, every `myspoti.attest` call throws `"attest is not in this extension's manifest+(actions)"`. No key exists until the extension calls `enroll`. The app makes no request of its own+for this: your script sends what it gets to your server.++| Call | Does |+|---|---|+| `myspoti.attest.enroll(challenge)` | `challenge`: a string from your server, 1 to 128 bytes (UTF-8). Creates, or replaces, an EC P-256 signing key for **this extension** in the Android hardware keystore (StrongBox when the phone has one, else the TEE) with `challenge` as the attestation challenge. Returns `{ publicKey, certChain }`: `publicKey` is the base64 SPKI (DER), `certChain` the base64 DER certificates of the Android key attestation, leaf first. At most 5 an hour. Throws if the phone cannot make such a key. |+| `myspoti.attest.publicKey()` | The current key's base64 SPKI, or `null` before `enroll`. |+| `myspoti.attest.sign(text)` | The base64 DER ECDSA-SHA256 signature of the UTF-8 `text` (64 KB at most), made with this extension's key. Throws `"attest.sign: not enrolled ..."` before `enroll`. 120 a minute. |+| `myspoti.attest.reset()` | Deletes this extension's key. Uninstalling the extension does it too. |++`myspoti.features` has `attest` when the user granted it. The key's alias holds the extension's id+(`myspoti.ext.attest.<id>`), so an extension can only ever use its own key, never another's. The key+cannot be exported: it signs only, and only for the extension that owns it, only while the app runs+that extension. No device identifier (serial number, IMEI) is requested: the chain says what app+made the key and how the phone's keystore and boot state look.++### What it proves, and what it does not++It proves that the key lives in Android hardware (the attestation's security level is+StrongBox or TrustedEnvironment, never Software), that **the app package made it** (the attestation+extension, `attestationApplicationId`, holds the package name and the SHA-256 digest of the+certificate that signed the app: `app.myspoti` or `app.myspoti.beta`, signed by the key you pin),+and that your server asked for it (the challenge). Every later signature then comes from that key.++It does **not** prove that the build is untouched: on a rooted phone, or with a patched official+build that keeps its signature, code can still ask the app to sign things. It does not prove who+the user is, that the content of a request is true (the extension reports what it saw), or that+one phone is not signing in a loop for someone: use a per-key rate limit. It is a barrier against+scripts that copy a key out of a package and against builds signed by anyone else, not against a+determined owner of a phone.++### It is optional++For the author: your server can still serve clients that did not enrol, or serve them less; Myspoti+never requires it. For the user: it is one more line in the install prompt, the extension works+without it for everything else, nothing is sent anywhere by the app, and the key is theirs to lose+by uninstalling.++### On the server++1. **Challenge.** Give a fresh random challenge (at most 128 bytes) to each enrolment, remember it+ against the session, accept it once and for a few minutes.+2. **Verify the chain.** Parse `certChain` (leaf first), check each certificate is signed by the+ next, and that the last one is one of Google's hardware attestation roots (published in the+ Android documentation, "Verify hardware-backed key pairs with Key Attestation"). Check none is+ on Google's revocation list. Check the leaf's public key is the `publicKey` that was sent.+3. **Read the attestation.** The leaf holds the extension `1.3.6.1.4.1.11129.2.1.17` (key+ description): check `attestationChallenge` equals your challenge, `attestationSecurityLevel` is+ StrongBox or TrustedEnvironment, and in the authorization lists that the key is an EC P-256 key+ with purpose `SIGN`, with no `ALL_APPLICATIONS` and no software-only part.+4. **Check the app.** In `attestationApplicationId`: the package name is `app.myspoti` (or+ `app.myspoti.beta` if you accept the beta), and one of the signing certificate digests is the+ SHA-256 of the release certificate **you choose to pin** (`apksigner verify --print-certs` on+ the official APK). Optionally also read the root of trust (verified boot, locked bootloader).+5. **Store** the key against the account or install, with the time and the level you saw.+6. **Verify each request.** Sign a canonical string that leaves nothing to interpretation:+ method, path (with the query), a timestamp in seconds, a random nonce and the SHA-256 of the+ body, one per line. The server rebuilds it from the request it received, verifies the+ ECDSA-SHA256 DER signature with the stored key, accepts a timestamp within about 60 seconds of+ its own clock, and keeps each `(key, nonce)` for twice that window to refuse a replay. A key it+ does not know, or a signature that fails, is refused like any bad credential.++The extension's side:++```js+var API = 'https://api.example.com';++function enrol() {+ var c = myspoti.http.get(API + '/attest/challenge').json(); // { challenge }+ var e = myspoti.attest.enroll(c.challenge);+ myspoti.http.post(API + '/attest/enrol', { challenge: c.challenge, publicKey: e.publicKey, certChain: e.certChain });+}++function signedPost(path, body) {+ if (!myspoti.attest.publicKey()) enrol();+ var text = JSON.stringify(body);+ var ts = String(Math.floor(Date.now() / 1000));+ var nonce = myspoti.util.sha256(ts + Math.random() + text).slice(0, 32);+ var canonical = ['POST', path, ts, nonce, myspoti.util.sha256(text)].join('\n');+ return myspoti.http.post(API + path, text, { headers: {+ 'Content-Type': 'application/json',+ 'X-Key': myspoti.util.sha256(myspoti.attest.publicKey()),+ 'X-Timestamp': ts,+ 'X-Nonce': nonce,+ 'X-Signature': myspoti.attest.sign(canonical),+ } });+}+```++(manifest: `"actions": [{ "name": "attest", "why": "Lets my server know this is a real Myspoti" }, { "name": "network", "hosts": ["api.example.com"], "why": "Talks to my server" }]`.)++On a computer, `myspoti-ext` gives each extension a **software** EC P-256 key kept in+`~/.myspoti-ext/attest/` (or under `$MYSPOTI_EXT_HOME`), and a one-certificate self-signed+"chain" that says `TEST-ONLY` and carries the challenge in an extension of a private OID. It is+there to test your signatures and your enrolment flow; a server that verifies the chain as in+step 2 must refuse it, since it is not hardware-backed and not Google's.