Skip to content

Native Android client for Spotify, built with Jetpack Compose

The quality sheet can change the audio source for the session: a Source section, drawn in each look's own way, lists Spotify and the audio-source extensions turned on in the order they are asked, the one playing marked; a tap asks that source alone for the song while it goes on, and when it has it the source comes first of the order until Myspoti restarts (never saved, the order in Settings stays) and the song plays from it from where it was (Spotify picked: Spotify plays it in its list), when it has not the song goes on and the order stays as it was; while such a choice lasts the sheet says it is temporary with "Back to my order", the source line ends with "temporary", Settings → Playback says it above the order, its extension settings follow the source first now, and an extension turned off or removed leaves the choice [skip ci]

kota-zo87fe51ff9982
diff --git a/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt b/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt
index 3d70ad86..50eafd40 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
@@ -261,6 +261,25 @@ object LocalPlayer {
prefetchNext(p)
}
+ /**
+ * The song playing opened again where it is: its audio is read anew from the answer kept for it
+ * (another source was picked for it in the player, see SongPlayer.switchSource). The queue, the
+ * shuffle, the repeat and play or pause stay. False: nothing an extension streams plays here.
+ */
+ fun reopen(): Boolean {
+ val p = exo ?: return false
+ if (CastPlayback.active || !active.value) return false
+ if (p.currentMediaItem?.localConfiguration?.uri?.scheme != com.music.spotui.extensions.ExtensionAudio.SCHEME) return false
+ if (outgoing != null) endFade()
+ val at = p.currentPosition
+ log("${current()?.title}: another source picked, opened again at $at ms")
+ errors.played()
+ p.stop()
+ p.seekTo(p.currentMediaItemIndex, at)
+ p.prepare()
+ return true
+ }
+
/** The downloads deleted during this session, by file: the song each one is (see [downloadsDeleted]). */
private val deletedDownloads = HashMap<String, com.music.spotui.data.entity.SongsModel>()
diff --git a/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt b/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt
index 1bedcad4..0be4175f 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
@@ -1176,10 +1176,13 @@ object SongPlayer {
* plays it from [positionMs], in the list it came from, and goes on with that list (as a miss
* at the pick does). False: it cannot (no Spotify id, data saver), the caller skips it.
*/
- fun playUnavailableOnSpotify(t: com.music.spotui.data.local.LocalTrack, positionMs: Long): Boolean {
+ fun playUnavailableOnSpotify(t: com.music.spotui.data.local.LocalTrack, positionMs: Long): Boolean =
+ playLocalOnSpotify(t, positionMs, "not available from extensions")
+
+ private fun playLocalOnSpotify(t: com.music.spotui.data.local.LocalTrack, positionMs: Long, why: String): Boolean {
val id = streamedTrackId(t)
if (id.isBlank() || com.music.spotui.data.DataSaver.active) return false
- app.myspoti.host.android.Logbook.log("local: ${t.title} not available from extensions, Spotify plays it")
+ app.myspoti.host.android.Logbook.log("local: ${t.title} $why, Spotify plays it")
spotifyPlayed.add(id)
spotifyFallbackId = id
// The local queue after it, for the extensions to go on with once Spotify has played it.
@@ -1189,6 +1192,72 @@ object SongPlayer {
return true
}
+ /** What picking an audio source in the quality sheet did to the song playing ([switchSource]). */
+ enum class SourceSwitch {
+ /** The song plays from it, from where it was (or already did). */
+ PLAYING,
+ /** It does not have the song (or cannot answer now): the song goes on where it played, the order is the one before. */
+ MISSING,
+ /** The song goes on as it plays (its download, another device, a cast, the song changed): the songs after it come from it. */
+ NEXT_SONG,
+ }
+
+ /**
+ * The audio source [id] (an extension, or [com.music.spotui.extensions.SPOTIFY_SOURCE]) picked
+ * in the quality sheet: first of the order for this session (Extensions.setSessionSource, never
+ * saved) and the song playing plays from it, from where it is. An extension is asked for the
+ * song alone first, nothing stopping meanwhile: without it ([SourceSwitch.MISSING]) the song
+ * goes on and the order stays as it was. Spotify picked while an extension streams: Spotify
+ * plays the song from there, in its list. [done] on the main thread.
+ */
+ fun switchSource(id: String, done: (SourceSwitch) -> Unit) {
+ val ext = com.music.spotui.extensions.Extensions
+ val local = LocalPlayer.active.value
+ val t = if (local) LocalPlayer.current() else null
+ val streamed = t?.let(::streamedTrackId).orEmpty()
+ val trackId = if (local) streamed else trackIdOf(_nowPlaying.value.uri)
+ val elsewhere = _activeDevice.value != null || routing || com.music.spotui.data.DataSaver.active || com.music.spotui.cast.CastPlayback.active
+ if (id == com.music.spotui.extensions.SPOTIFY_SOURCE) {
+ ext.setSessionSource(id)
+ done(when {
+ !local -> SourceSwitch.PLAYING
+ t == null || streamed.isBlank() || elsewhere -> SourceSwitch.NEXT_SONG
+ playLocalOnSpotify(t, LocalPlayer.position(), "picked in the player") -> SourceSwitch.PLAYING
+ else -> SourceSwitch.NEXT_SONG
+ })
+ return
+ }
+ if (local && streamed.isNotBlank() && com.music.spotui.extensions.ExtensionAudio.providerOf(streamed) == id) { ext.setSessionSource(id); done(SourceSwitch.PLAYING); return }
+ val song = when {
+ trackId.isBlank() || elsewhere -> null
+ t != null -> localSong(t)
+ else -> _queue.value.current?.takeIf { it.spotifyTrackId == trackId }
+ }
+ if (song == null) { ext.setSessionSource(id); done(SourceSwitch.NEXT_SONG); return }
+ app.myspoti.host.android.Logbook.log("audio: ${song.title} asked to $id, picked in the player")
+ scope.launch {
+ val stream = runCatching {
+ ext.audioFrom(id, ext.trackInfo(trackId, song.title, song.singer, song.album, song.durationMs.toLong(), song.coverUri))
+ }.getOrNull()
+ main.post {
+ if (stream == null) { done(SourceSwitch.MISSING); return@post }
+ ext.setSessionSource(id)
+ // Another song meanwhile: it plays as it was asked; the songs after it follow the new order.
+ val nowLocal = LocalPlayer.active.value
+ val nowId = if (nowLocal) LocalPlayer.current()?.let(::streamedTrackId).orEmpty() else trackIdOf(_nowPlaying.value.uri)
+ if (nowId != trackId || routing) { done(SourceSwitch.NEXT_SONG); return@post }
+ com.music.spotui.extensions.ExtensionAudio.use(trackId, stream)
+ if (nowLocal) { done(if (LocalPlayer.reopen()) SourceSwitch.PLAYING else SourceSwitch.NEXT_SONG); return@post }
+ // Spotify played it: the extension plays it from there, the engine's queue after it, as a resume does.
+ val np = _nowPlaying.value
+ val q = _queue.value
+ val songs = (listOfNotNull(q.current) + (q.queued + q.nextUp).map { it.song }).takeIf { l -> l.any { it.spotifyTrackId == trackId } }
+ playSong(np.uri, contextUri = np.contextUri.ifBlank { null }, positionMs = getCurrentPosition(), songs = songs)
+ done(SourceSwitch.PLAYING)
+ }
+ }
+ }
+
/**
* The local queue the extensions played ended with no song radio to go on with: Spotify goes
* on after its last song [t] ([trackId]) as after a song played alone (its autoplay), from the
@@ -1218,7 +1287,8 @@ object SongPlayer {
spotifyPlayed.clear()
if (!any) return
val local = LocalPlayer.active.value
- com.music.spotui.extensions.ExtensionAudio.forgetAllBut(if (local) LocalPlayer.current()?.let(LocalPlayer::spotifyIdOf) else null)
+ // The song playing, or the one being asked (a source picked for it in the player), keeps its answer.
+ com.music.spotui.extensions.ExtensionAudio.forgetAllBut(if (local) LocalPlayer.current()?.let(LocalPlayer::spotifyIdOf) else routingState.value)
if (local) { LocalPlayer.sourcesChanged(); return }
if (added.isEmpty() || _activeDevice.value != null || routing || com.music.spotui.data.DataSaver.active) return
val id = trackIdOf(_nowPlaying.value.uri).ifBlank { return }
diff --git a/base/app/src/main/java/com/music/spotui/extensions/ExtensionAudio.kt b/base/app/src/main/java/com/music/spotui/extensions/ExtensionAudio.kt
index e0033ccc..3cd553c5 100644
--- a/base/app/src/main/java/com/music/spotui/extensions/ExtensionAudio.kt
+++ b/base/app/src/main/java/com/music/spotui/extensions/ExtensionAudio.kt
@@ -79,6 +79,9 @@ object ExtensionAudio {
answers.intValue++
}
+ /** [stream], from the source picked for it in the player (SongPlayer.switchSource), is the song [trackId]'s audio from now on. */
+ fun use(trackId: String, stream: AudioStream) = keep(trackId, stream)
+
private val warming = ConcurrentHashMap.newKeySet<String>()
/**
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.kt
index e88f0b40..27df9a5e 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
@@ -507,13 +507,59 @@ object Extensions {
*/
fun sourceLine(action: Action): List<String> = line(_registry.value, action)
- private fun line(r: Registry, action: Action): List<String> {
+ /** The order the user set for the source [action] (Settings), without this session's [sessionSource]. */
+ fun savedSourceLine(action: Action): List<String> = savedLine(_registry.value, action)
+
+ private fun savedLine(r: Registry, action: Action): List<String> {
val ids = r.extensions.filter { action in manifest(it.id)?.actionSet().orEmpty() }.map { it.id }
return r.bySourceOrder(action.key, Area.AUDIO.key, if (action == Action.AUDIO_SOURCE) ids + SPOTIFY_SOURCE else ids) { it }
}
+ /** The order the source [action] asks in now: the user's, with the audio source picked for this session first ([SessionSource]). */
+ private fun line(r: Registry, action: Action): List<String> {
+ val saved = savedLine(r, action)
+ if (action != Action.AUDIO_SOURCE) return saved
+ return SessionSource.effective(saved, SessionSource.valid(_sessionSource.value, saved) { r.find(it)?.enabled == true })
+ }
+
/** Moves [id] (an extension, or [SPOTIFY_SOURCE]) up (negative [delta]) or down in the order the source [action] asks in. */
- fun moveSource(action: Action, id: String, delta: Int) = update { r -> r.move(action.key, line(r, action), id, delta) }
+ fun moveSource(action: Action, id: String, delta: Int) = update { r -> r.move(action.key, savedLine(r, action), id, delta) }
+
+ private val _sessionSource = MutableStateFlow<String?>(null)
+
+ /**
+ * The audio source the user put first from the player for this session ([SessionSource]), or
+ * null: the order of Settings. In memory only, never saved: gone when the app restarts.
+ */
+ val sessionSource: StateFlow<String?> = _sessionSource.asStateFlow()
+
+ /** The audio sources the player's quality sheet offers (Spotify and the extensions on), in the order they are asked now. */
+ fun audioChoices(): List<String> = _registry.value.let { r ->
+ SessionSource.choices(savedLine(r, Action.AUDIO_SOURCE), _sessionSource.value) { r.find(it)?.enabled == true }
+ }
+
+ /**
+ * Puts [id] (an extension, or [SPOTIFY_SOURCE]) first of the audio order for this session; null,
+ * or the source the user's order asks first already: back to that order. The songs after the one
+ * playing are asked again in the new order (as for a change in Settings); the one playing is the
+ * caller's (SongPlayer.switchSource).
+ */
+ fun setSessionSource(id: String?) {
+ val r = _registry.value
+ val lead = id?.let { SessionSource.pick(it, savedLine(r, Action.AUDIO_SOURCE)) { x -> r.find(x)?.enabled == true } }
+ if (lead == _sessionSource.value) return
+ _sessionSource.value = lead
+ Logbook.log("audio: ${lead?.let { "$it first for this session" } ?: "back to the order of Settings"}")
+ refreshProvided()
+ }
+
+ /** The session's source still leads after [r] changed; turned off, removed or no longer a source, it leaves it. */
+ private fun keepSessionSource(r: Registry) {
+ val lead = _sessionSource.value ?: return
+ if (SessionSource.valid(lead, savedLine(r, Action.AUDIO_SOURCE)) { r.find(it)?.enabled == true } != null) return
+ _sessionSource.value = null
+ Logbook.log("audio: $lead no longer a source, back to the order of Settings")
+ }
/** Makes [id] the one acting for the exclusive [action]; the others stay installed, idle. */
fun setActive(action: Action, id: String) {
@@ -810,6 +856,36 @@ object Extensions {
return a.copy(providerId = c.first)
}
+ /**
+ * [track]'s audio from the audio source [id] alone, whatever the order: the one picked for it in
+ * the player's quality sheet (SongPlayer.switchSource), asked while the song goes on where it
+ * plays; one [PlayAttempt] of its own. Null: it does not have it, cannot answer now (set aside,
+ * busy) or is not a running audio source.
+ */
+ suspend fun audioFrom(id: String, track: TrackInfo): AudioStream? {
+ if (!isReady) return null
+ val rt = runtimes[id]?.takeIf { _registry.value.find(id)?.enabled == true && it.provides(Hook.AUDIO_SOURCE) && !health.inactive(id) } ?: return null
+ val attempt = attempts.start(track.id, track.title)
+ val picked = "picked in the player for this session"
+ cooldown.reason(id)?.let { why ->
+ attempts.update(attempt) { it.copy(asked = listOf(PlayAttempt.Ask(id, Outcome.Skipped().key, 0, "set aside: $why")), fallback = "the song goes on where it played") }
+ return null
+ }
+ val a = ask(id, rt, Hook.AUDIO_SOURCE, AudioQuery.toJson(withIsrc(track), false), AUDIO_MS, AudioStream::parse)
+ val asked = listOf(PlayAttempt.Ask(id, a.outcome.key, a.ms, detail = listOfNotNull(picked, a.outcome.detail).joinToString("; ")))
+ val found = a.value ?: run {
+ Logbook.log("audio: $id had no ${track.title} (${a.ms} ms), it goes on where it played")
+ attempts.update(attempt) { it.copy(asked = asked, fallback = "the song goes on where it played") }
+ return null
+ }
+ misses.forget(track.id)
+ log(id, "audio for ${track.title} (${a.ms} ms, picked in the player)")
+ did(Area.AUDIO, id, "Audio of ${track.title} from ${rt.manifest.name}")
+ val own = qualityLine(id, app.myspoti.extensions.SettingSection.PLAYBACK)
+ attempts.update(attempt) { it.copy(asked = asked, chosen = id, announced = found.qualityLabel(), sourceQuality = own) }
+ return found.copy(providerId = id)
+ }
+
/** The last [PlayAttempt]s through the extensions (20), for "Why this source?" and the diagnostic report. */
val attempts = PlayAttempts(capacity = 20)
@@ -1327,6 +1403,7 @@ object Extensions {
val r = change(_registry.value)
_registry.value = r
runCatching { Registry.write(File(dir, "registry.json"), r) }.onFailure { Logbook.log("ext: registry not saved: ${it.message}") }
+ keepSessionSource(r)
}
// Turned on or off, the order of the sources, the active one: who gives what may have changed.
refreshProvided()
diff --git a/base/app/src/main/java/com/music/spotui/extensions/SessionSource.kt b/base/app/src/main/java/com/music/spotui/extensions/SessionSource.kt
new file mode 100644
index 00000000..f2534809
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/extensions/SessionSource.kt
@@ -0,0 +1,29 @@
+package com.music.spotui.extensions
+
+/**
+ * The audio source the user put first from the player's quality sheet, for this session only: kept
+ * in memory (gone when the app's process ends), never in the registry, so the order set in
+ * Settings → Playback stays as it was. While it lasts, the audio sources are asked in the
+ * [effective] order: that source, then the user's order without it. Spotify first: no extension
+ * is asked. An extension turned off, removed or no longer a source leaves it ([valid]).
+ */
+object SessionSource {
+ /** [saved] (the user's audio order, [SPOTIFY_SOURCE] among it) with [lead] first; [saved] as it is without one, or with one not in it. */
+ fun effective(saved: List<String>, lead: String?): List<String> =
+ if (lead == null || lead !in saved) saved else listOf(lead) + saved.filter { it != lead }
+
+ /** [lead] while it can still lead: Spotify, or an extension of [saved] that is on; null otherwise. */
+ fun valid(lead: String?, saved: List<String>, enabled: (String) -> Boolean): String? =
+ lead?.takeIf { it in saved && (it == SPOTIFY_SOURCE || enabled(it)) }
+
+ /**
+ * The lead [id] picked in the player gives: [id], or null when it is the source the user's own
+ * order asks first already (the session is then on the user's order, nothing is temporary).
+ */
+ fun pick(id: String, saved: List<String>, enabled: (String) -> Boolean): String? =
+ valid(id, saved, enabled)?.takeIf { it != SectionSettings.leader(saved, enabled) }
+
+ /** What the quality sheet offers: Spotify and the extensions on, in the [effective] order. */
+ fun choices(saved: List<String>, lead: String?, enabled: (String) -> Boolean): List<String> =
+ effective(saved, valid(lead, saved, enabled)).filter { it == SPOTIFY_SOURCE || enabled(it) }
+}
diff --git a/base/app/src/main/java/com/music/spotui/ui/components/PlayerSheets.kt b/base/app/src/main/java/com/music/spotui/ui/components/PlayerSheets.kt
index 2a797f39..680c738b 100644
--- a/base/app/src/main/java/com/music/spotui/ui/components/PlayerSheets.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/components/PlayerSheets.kt
@@ -26,6 +26,7 @@ import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.zIndex
import kotlin.math.roundToInt
import androidx.compose.foundation.clickable
+import androidx.compose.foundation.verticalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
@@ -139,11 +140,13 @@ fun playingSourceLabel(): String {
val uri = SongPlayer.nowPlaying.value.uri
val answers = com.music.spotui.extensions.ExtensionAudio.answers.intValue
val downloaded = stringResource(R.string.player_source_downloaded)
+ // A source picked in the quality sheet for this session: said, discreetly, at the line's end.
+ val temporary = com.music.spotui.extensions.Extensions.sessionSource.collectAsState().value?.let { stringResource(R.string.source_pick_tag) }
if (SongPlayer.routing) return ""
- if (!com.music.spotui.di.LocalPlayer.active.value) return spotifyQualityLabel(uri)
- return remember(uri, answers, downloaded) {
+ val label = if (!com.music.spotui.di.LocalPlayer.active.value) spotifyQualityLabel(uri) else remember(uri, answers, downloaded) {
com.music.spotui.di.LocalPlayer.current()?.let { com.music.spotui.extensions.ExtensionAudio.sourceLabel(it, downloaded) }.orEmpty()
}
+ return if (temporary == null || label.isBlank() || uri.startsWith("spotify:episode:")) label else "$label · $temporary"
}
/**
@@ -316,7 +319,9 @@ internal fun streamingLabel(q: com.music.spotui.data.preferences.StreamingQualit
@Composable
fun QualitySheet(onDismiss: () -> Unit) {
val local = com.music.spotui.di.LocalPlayer.active.value
- val now by androidx.compose.runtime.produceState<String?>(null) {
+ // Read again when another source plays the song (picked below, see SourcePicker).
+ val answers = com.music.spotui.extensions.ExtensionAudio.answers.intValue
+ val now by androidx.compose.runtime.produceState<String?>(null, local, answers) {
value = if (local) {
val t = com.music.spotui.di.LocalPlayer.current()
val file = t?.let { com.music.spotui.data.offline.OfflineStore.byLocalId(it.id) }
@@ -331,7 +336,7 @@ fun QualitySheet(onDismiss: () -> Unit) {
}
}
com.music.spotui.ui.components.LookSheet(onDismissRequest = onDismiss, containerColor = SheetColor) {
- Column(Modifier.fillMaxWidth().navigationBarsPadding().padding(bottom = 16.dp)) {
+ Column(Modifier.fillMaxWidth().verticalScroll(androidx.compose.foundation.rememberScrollState()).navigationBarsPadding().padding(bottom = 16.dp)) {
Text(stringResource(R.string.quality_sheet_title), color = AppText, fontSize = 20.sp, fontWeight = FontWeight.Bold,
modifier = Modifier.padding(horizontal = 20.dp, vertical = 8.dp))
val text = now
@@ -352,6 +357,8 @@ fun QualitySheet(onDismiss: () -> Unit) {
modifier = Modifier.fillMaxWidth().clickable { why = true }.padding(horizontal = 20.dp, vertical = 12.dp))
if (why) WhySourceSheet(extId, detectedLabel(com.music.spotui.di.LocalPlayer.audioFormat())) { why = false }
}
+ // Another audio source for this song and the next ones, until the app restarts.
+ SourcePicker(Modifier.padding(top = 12.dp))
// The level of the network in use now (Wi-Fi and mobile data each keep their own).
if (!local) StreamingQualityPicker(Modifier.padding(top = 12.dp), cellular = com.music.spotui.data.DataSaver.metered,
title = if (com.music.spotui.data.DataSaver.metered) R.string.quality_streaming_cell_title else R.string.quality_streaming_wifi_title)
diff --git a/base/app/src/main/java/com/music/spotui/ui/components/SourcePicker.kt b/base/app/src/main/java/com/music/spotui/ui/components/SourcePicker.kt
new file mode 100644
index 00000000..d5fba52c
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/ui/components/SourcePicker.kt
@@ -0,0 +1,159 @@
+package com.music.spotui.ui.components
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.selection.selectable
+import androidx.compose.foundation.selection.selectableGroup
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.rounded.Restore
+import androidx.compose.material3.RadioButton
+import androidx.compose.material3.RadioButtonDefaults
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.collectAsState
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.semantics.Role
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import app.myspoti.engine.R
+import com.music.spotui.di.LocalPlayer
+import com.music.spotui.di.SongPlayer
+import com.music.spotui.extensions.ExtensionAudio
+import com.music.spotui.extensions.Extensions
+import com.music.spotui.extensions.SPOTIFY_SOURCE
+import com.music.spotui.ui.immersive.Immersive
+import com.music.spotui.ui.immersive.pages.ImmersiveChoiceRow
+import com.music.spotui.ui.immersive.pages.ImmersiveGroupRow
+import com.music.spotui.ui.theme.AppAccent
+import com.music.spotui.ui.theme.AppMuted
+import com.music.spotui.ui.theme.AppText
+
+/**
+ * What the quality sheet's Source section shows, the same in both looks: the audio sources the
+ * user can pick (Spotify and the extensions on, in the order they are asked now), their names, the
+ * one the song plays from (null: being asked, a download), the one first for this session (null:
+ * the order of Settings) and the one being asked for the song after a tap.
+ */
+private class SourceChoices(val ids: List<String>, val names: Map<String, String>, val playing: String?, val lead: String?, val asking: String?)
+
+/**
+ * The quality sheet's Source section: another audio source for this song and the next ones, until
+ * the app restarts (SongPlayer.switchSource, Extensions.setSessionSource); "Back to my order" while
+ * one is. Nothing without an audio-source extension on, or for an episode (Spotify's own).
+ * Drawn in each look's own way ([ImmersiveSourcePicker], [ClassicSourcePicker]).
+ */
+@Composable
+fun SourcePicker(modifier: Modifier = Modifier) {
+ val registry by Extensions.registry.collectAsState()
+ val lead by Extensions.sessionSource.collectAsState()
+ val answers = ExtensionAudio.answers.intValue
+ val uri = SongPlayer.nowPlaying.value.uri
+ val local = LocalPlayer.active.value
+ val ids = remember(registry, lead) { Extensions.audioChoices() }
+ if (ids.none { it != SPOTIFY_SOURCE } || uri.startsWith("spotify:episode:")) return
+ val spotify = stringResource(R.string.sources_spotify)
+ val names = remember(ids, registry, spotify) { ids.associateWith { if (it == SPOTIFY_SOURCE) spotify else registry.find(it)?.name ?: it } }
+ val playing = remember(uri, local, answers, SongPlayer.routing) {
+ when {
+ SongPlayer.routing -> null
+ !local -> SPOTIFY_SOURCE
+ // A song played from its download plays from no source.
+ else -> LocalPlayer.current()?.uri?.takeIf { it.scheme == ExtensionAudio.SCHEME }?.lastPathSegment?.let(ExtensionAudio::providerOf)
+ }
+ }
+ var asking by remember { mutableStateOf<String?>(null) }
+ val ctx = LocalContext.current
+ val pick = { id: String ->
+ // One ask at a time: a second tap waits for the first source's answer.
+ if (asking == null) {
+ asking = id
+ SongPlayer.switchSource(id) { r ->
+ asking = null
+ val name = names[id] ?: id
+ when (r) {
+ SongPlayer.SourceSwitch.MISSING -> ctx.getString(R.string.source_pick_missing, name)
+ SongPlayer.SourceSwitch.NEXT_SONG -> ctx.getString(R.string.source_pick_next, name)
+ SongPlayer.SourceSwitch.PLAYING -> null
+ }?.let { android.widget.Toast.makeText(ctx, it, android.widget.Toast.LENGTH_LONG).show() }
+ }
+ }
+ }
+ val reset = { Extensions.setSessionSource(null) }
+ val c = SourceChoices(ids, names, playing, lead, asking)
+ if (com.music.spotui.ui.navigation.isImmersive()) ImmersiveSourcePicker(c, pick, reset, modifier)
+ else ClassicSourcePicker(c, pick, reset, modifier)
+}
+
+/** What a source's row says under its name: being asked, first for this session, playing now. */
+@Composable
+private fun detailOf(c: SourceChoices, id: String): String? = when (id) {
+ c.asking -> "…"
+ c.lead -> stringResource(R.string.source_pick_temporary)
+ c.playing -> stringResource(R.string.source_pick_playing)
+ else -> null
+}
+
+/** Immersive: as its Settings pages and the streaming levels under it, a grouped card with a check on the source playing. */
+@Composable
+private fun ImmersiveSourcePicker(c: SourceChoices, pick: (String) -> Unit, reset: () -> Unit, modifier: Modifier) {
+ Column(modifier.fillMaxWidth().padding(horizontal = 20.dp).selectableGroup()) {
+ Text(stringResource(R.string.source_pick_title), style = Immersive.Headline, modifier = Modifier.padding(top = 4.dp))
+ Text(stringResource(R.string.source_pick_detail), style = Immersive.Caption.copy(color = Color.White.copy(alpha = 0.72f)),
+ modifier = Modifier.padding(top = 2.dp, bottom = 10.dp))
+ Column(Modifier.fillMaxWidth().clip(Immersive.Card).background(Immersive.Raised.copy(alpha = 0.92f))) {
+ c.ids.forEachIndexed { i, id ->
+ ImmersiveChoiceRow(c.names[id] ?: id, selected = id == c.playing, detail = detailOf(c, id), onClick = { pick(id) })
+ if (i < c.ids.lastIndex || c.lead != null) Box(Modifier.padding(start = 16.dp).fillMaxWidth().height(0.5.dp).background(Immersive.Separator))
+ }
+ if (c.lead != null) ImmersiveGroupRow(stringResource(R.string.source_pick_reset), detail = stringResource(R.string.source_pick_reset_detail),
+ icon = Icons.Rounded.Restore, onClick = reset)
+ }
+ }
+}
+
+/** Classic: as the streaming levels under it, radio rows, the source playing selected. */
+@Composable
+private fun ClassicSourcePicker(c: SourceChoices, pick: (String) -> Unit, reset: () -> Unit, modifier: Modifier) {
+ Column(modifier.fillMaxWidth().selectableGroup()) {
+ Text(stringResource(R.string.source_pick_title), color = AppText, fontSize = 17.sp, fontWeight = FontWeight.Bold,
+ modifier = Modifier.padding(horizontal = 20.dp, vertical = 4.dp))
+ Text(stringResource(R.string.source_pick_detail), color = AppMuted, fontSize = 13.sp,
+ modifier = Modifier.padding(start = 20.dp, end = 20.dp, bottom = 4.dp))
+ for (id in c.ids) {
+ val on = id == c.playing
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = Modifier.fillMaxWidth().heightIn(min = 56.dp)
+ .selectable(selected = on, role = Role.RadioButton, onClick = { pick(id) })
+ .padding(horizontal = 8.dp, vertical = 4.dp),
+ ) {
+ RadioButton(selected = on, onClick = null, modifier = Modifier.padding(horizontal = 8.dp),
+ colors = RadioButtonDefaults.colors(selectedColor = AppAccent, unselectedColor = AppMuted))
+ Column(Modifier.weight(1f).padding(end = 12.dp)) {
+ Text(c.names[id] ?: id, color = if (on) AppAccent else AppText, fontSize = 16.sp)
+ detailOf(c, id)?.let { Text(it, color = if (id == c.lead) AppAccent else AppMuted, fontSize = 12.sp) }
+ }
+ }
+ }
+ if (c.lead != null) TextButton(onClick = reset, modifier = Modifier.padding(horizontal = 8.dp)) {
+ Text(stringResource(R.string.source_pick_reset), color = AppAccent, fontSize = 14.sp)
+ }
+ }
+}
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt
index 4dcf630b..351cf786 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
@@ -214,7 +214,9 @@ private fun PlaybackPage(navController: NavController, open: (SettingsPage) -> U
// The first source of the audio order, when it is an extension announcing settings here:
// they show, and Spotify's quality (kept, still used for what Spotify plays) leaves the screen.
val registry by com.music.spotui.extensions.Extensions.registry.collectAsStateWithLifecycle()
- val ext = remember(registry) { com.music.spotui.extensions.Extensions.sectionPlacement(app.myspoti.extensions.SettingSection.PLAYBACK) }
+ // A source picked in the player for this session leads too ([com.music.spotui.extensions.SessionSource]).
+ val session by com.music.spotui.extensions.Extensions.sessionSource.collectAsStateWithLifecycle()
+ val ext = remember(registry, session) { com.music.spotui.extensions.Extensions.sectionPlacement(app.myspoti.extensions.SettingSection.PLAYBACK) }
val extHeader = ext?.let { stringResource(R.string.ext_section_settings, it.name) }
ImmersivePage(title = stringResource(R.string.settings_section_playback), onBack = back) {
if (ext != null && extHeader != null) extensionSectionGroup(ext, extHeader)
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.kt
index cdf40cf5..ede22d50 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
@@ -95,10 +95,12 @@ fun SettingsScreen(navController: NavController) {
Column(Modifier.fillMaxWidth().weight(1f).verticalScroll(rememberScrollState()).navigationBarsPadding()) {
// The first source of each order, when it is an extension announcing settings in that tab.
val registry by com.music.spotui.extensions.Extensions.registry.collectAsStateWithLifecycle()
+ // A source picked in the player for this session leads too ([com.music.spotui.extensions.SessionSource]).
+ val session by com.music.spotui.extensions.Extensions.sessionSource.collectAsStateWithLifecycle()
if (tab == 0) {
Section(R.string.settings_section_playback)
// An extension above Spotify: its settings, and Spotify's quality (kept, still used for what Spotify plays) leaves.
- val ext = remember(registry) { com.music.spotui.extensions.Extensions.sectionPlacement(app.myspoti.extensions.SettingSection.PLAYBACK) }
+ val ext = remember(registry, session) { com.music.spotui.extensions.Extensions.sectionPlacement(app.myspoti.extensions.SettingSection.PLAYBACK) }
ext?.let { ExtensionSectionSettings(it) }
if (ext?.hidesAppQuality != true) {
StreamingQualityPicker(title = R.string.quality_streaming_wifi_title)
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/SourceOrder.kt b/base/app/src/main/java/com/music/spotui/ui/screens/SourceOrder.kt
index ed099084..2906f58d 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/SourceOrder.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/SourceOrder.kt
@@ -69,9 +69,20 @@ internal fun SourceOrderList(action: Action, spotifyLast: Boolean, look: SourceL
val errors by Extensions.errors.collectAsState()
val statuses by Extensions.statuses.collectAsState()
val activity by Extensions.activity.state.collectAsState()
- val line = remember(registry, action) { Extensions.sourceLine(action).filter { spotifyLast || it != SPOTIFY_SOURCE } }
+ // The order the user set: a source picked in the player for this session is only said above it.
+ val line = remember(registry, action) { Extensions.savedSourceLine(action).filter { spotifyLast || it != SPOTIFY_SOURCE } }
+ val lead by Extensions.sessionSource.collectAsState()
val spotifyAt = line.indexOf(SPOTIFY_SOURCE)
Column(Modifier.fillMaxWidth()) {
+ lead?.takeIf { action == Action.AUDIO_SOURCE }?.let { id ->
+ val name = if (id == SPOTIFY_SOURCE) stringResource(R.string.sources_spotify) else registry.find(id)?.name ?: id
+ Column(Modifier.fillMaxWidth().then(rowPadding)) {
+ Text(stringResource(R.string.source_pick_active, name), style = look.line.copy(color = look.accent))
+ TextButton(onClick = { Extensions.setSessionSource(null) }, contentPadding = androidx.compose.foundation.layout.PaddingValues(0.dp)) {
+ Text(stringResource(R.string.source_pick_reset), color = look.accent, fontSize = 13.sp, fontWeight = FontWeight.SemiBold)
+ }
+ }
+ }
line.forEachIndexed { i, id ->
val arrows: @Composable () -> Unit = { MoveArrows(action, id, i, line.size, look) }
val e = registry.find(id)
diff --git a/base/app/src/main/res/values/sources_strings.xml b/base/app/src/main/res/values/sources_strings.xml
index cecd4f68..c0067603 100644
--- a/base/app/src/main/res/values/sources_strings.xml
+++ b/base/app/src/main/res/values/sources_strings.xml
@@ -14,4 +14,14 @@
<string name="sources_open">Open the extension</string>
<string name="sources_order_hint">Sources are asked in the order set in Settings (Playback, Downloads).</string>
<string name="sources_below_spotify">Not asked: Spotify is above</string>
+ <string name="source_pick_title">Source</string>
+ <string name="source_pick_detail">Plays this song and the next ones from the source you pick, until Myspoti restarts. Your order in Settings stays as it is.</string>
+ <string name="source_pick_playing">Playing now</string>
+ <string name="source_pick_temporary">Temporary: first until Myspoti restarts</string>
+ <string name="source_pick_reset">Back to my order</string>
+ <string name="source_pick_reset_detail">The order set in Settings → Playback</string>
+ <string name="source_pick_tag">temporary</string>
+ <string name="source_pick_missing">%1$s doesn\'t have this song: it goes on from where it played, and your order stays as it was.</string>
+ <string name="source_pick_next">%1$s plays from the next song: this one goes on as it plays.</string>
+ <string name="source_pick_active">Temporary choice for this session: %1$s is asked first, until Myspoti restarts.</string>
</resources>
diff --git a/base/app/src/test/java/com/music/spotui/extensions/SessionSourceTest.kt b/base/app/src/test/java/com/music/spotui/extensions/SessionSourceTest.kt
new file mode 100644
index 00000000..7436e149
--- /dev/null
+++ b/base/app/src/test/java/com/music/spotui/extensions/SessionSourceTest.kt
@@ -0,0 +1,57 @@
+package com.music.spotui.extensions
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Test
+
+/** The audio source picked in the player for the session: first, then the user's order; gone with the source. */
+class SessionSourceTest {
+ private val a = "io.github.a.hifi"
+ private val b = "io.github.b.tidal"
+ private val c = "io.github.c.below"
+ private val saved = listOf(a, b, SPOTIFY_SOURCE, c)
+ private val on = { _: String -> true }
+
+ @Test fun thePickedSourceComesFirstThenTheUsersOrder() {
+ assertEquals(listOf(b, a, SPOTIFY_SOURCE, c), SessionSource.effective(saved, b))
+ // One under Spotify, not asked in the user's order: it is, first.
+ assertEquals(listOf(c, a, b, SPOTIFY_SOURCE), SessionSource.effective(saved, c))
+ // Spotify first: no extension is asked before it.
+ assertEquals(listOf(SPOTIFY_SOURCE, a, b, c), SessionSource.effective(saved, SPOTIFY_SOURCE))
+ }
+
+ @Test fun withoutOneTheOrderIsTheUsers() {
+ assertEquals(saved, SessionSource.effective(saved, null))
+ // Back to my order: nothing picked any more.
+ assertEquals(saved, SessionSource.effective(saved, SessionSource.valid(null, saved, on)))
+ }
+
+ @Test fun aSourceTurnedOffOrRemovedLeavesIt() {
+ // Turned off: no longer a lead, the user's order is back.
+ assertNull(SessionSource.valid(b, saved, { it != b }))
+ assertEquals(saved, SessionSource.effective(saved, SessionSource.valid(b, saved, { it != b })))
+ // Removed (or no longer an audio source): not in the order, not a lead.
+ val without = saved - b
+ assertNull(SessionSource.valid(b, without, on))
+ assertEquals(without, SessionSource.effective(without, b))
+ // Spotify is always a source.
+ assertEquals(SPOTIFY_SOURCE, SessionSource.valid(SPOTIFY_SOURCE, saved, { false }))
+ }
+
+ @Test fun pickingTheSourceTheOrderAsksFirstIsTheUsersOrder() {
+ assertNull(SessionSource.pick(a, saved, on))
+ assertEquals(b, SessionSource.pick(b, saved, on))
+ assertEquals(SPOTIFY_SOURCE, SessionSource.pick(SPOTIFY_SOURCE, saved, on))
+ // The first one turned off: Spotify is asked first after it, picking it changes nothing.
+ assertNull(SessionSource.pick(SPOTIFY_SOURCE, listOf(a, SPOTIFY_SOURCE), { it != a }))
+ // A source turned off cannot be picked.
+ assertNull(SessionSource.pick(b, saved, { it != b }))
+ }
+
+ @Test fun theSheetOffersSpotifyAndTheSourcesOnInTheOrderAskedNow() {
+ assertEquals(listOf(a, b, SPOTIFY_SOURCE, c), SessionSource.choices(saved, null, on))
+ assertEquals(listOf(c, a, SPOTIFY_SOURCE), SessionSource.choices(saved, c, { it != b }))
+ // The pick turned off meanwhile: the user's order, without it.
+ assertEquals(listOf(a, SPOTIFY_SOURCE, c), SessionSource.choices(saved, b, { it != b }))
+ }
+}