Native Android client for Spotify, built with Jetpack Compose
Kotlin ad-freeadblockandroidjetpack-composekotlinlyricsmusic-playermusic-videomyspotispotifyspotify-adblockerspotify-clientspotify-connectspotui
A player that grows out of the mini player with fades, and a sign-in that waits for the e-mail code
kota-zoff3098af4a55
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 cf6ca1e1..261423ee 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@@ -166,7 +166,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop*/private suspend fun reloadAndPlayOn(s: PlayerState?, next: Boolean = true) {val reload = reloadHost ?: return- if (recoveryHeld()) { bridge.logger?.invoke("reload held: Spotify is limiting playback"); return }+ if (recoveryHeld()) { bridge.logger?.invoke("reload held: a sign-in page is open or Spotify is limiting playback"); return }ownReload = truetry {runCatching {@@ -187,7 +187,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop*/suspend fun reloadPage(): Boolean {val reload = reloadHost ?: return false- if (recoveryHeld()) { bridge.logger?.invoke("reload held: Spotify is limiting playback"); return false }+ if (recoveryHeld()) { bridge.logger?.invoke("reload held: a sign-in page is open or Spotify is limiting playback"); return false }ownReload = truetry {reload()@@ -318,7 +318,9 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopif (withTimeoutOrNull(if (quiet) WATCH_IDLE_TICK_MS else WATCH_TICK_MS) { wake.receive() } != null)delay(AD_PLAYING_SKIP_MS + 50)tick++- if (!bridge.ready.value || ownReload) { key = null; attempts = 0; silentSince = 0L; continue }+ // Repairs held (a sign-in page open, playback limited): nothing is judged, not even a+ // silent page, which is what a sign-in page looks like from here.+ if (!bridge.ready.value || ownReload || recoveryHeld()) { key = null; attempts = 0; silentSince = 0L; frozenMisses = 0; continue }val now = System.currentTimeMillis()// The page answers nothing, not even a ping: frozen (a stuck renderer). Reloaded// at once, the song going on where it was.diff --git a/base/app/src/main/java/com/music/spotui/ui/components/AppComponents.kt b/base/app/src/main/java/com/music/spotui/ui/components/AppComponents.ktindex 6f41891d..b365b42a 100644--- a/base/app/src/main/java/com/music/spotui/ui/components/AppComponents.kt+++ b/base/app/src/main/java/com/music/spotui/ui/components/AppComponents.kt@@ -163,13 +163,10 @@ fun MiniPlayer(navController: NavHostController) {}}- // The big cover the player will open on, loaded now: the cover that flies into the player- // (CoverFlight) and the player's own then come from memory, with nothing to wait for.+ // The big cover the player will open on, loaded now: it is then read from Glide's caches.LaunchedEffect(songCoverUri) {- val target = CoverFlight.player ?: return@LaunchedEffectif (songCoverUri.isBlank()) return@LaunchedEffect- com.bumptech.glide.Glide.with(context).load(songCoverUri)- .override(target.width.toInt(), target.height.toInt()).optionalCenterCrop().preload()+ com.bumptech.glide.Glide.with(context).load(songCoverUri).preload()}// A new song cross-fades the card's colour instead of snapping to it.@@ -208,6 +205,8 @@ fun MiniPlayer(navController: NavHostController) {Column(modifier = Modifier.pressable(0.96f) { com.music.spotui.ui.navigation.PlayerSheet.show() }+ // Where the full player rises from and sinks back to.+ .onGloballyPositioned { com.music.spotui.ui.navigation.PlayerSheet.miniTop = it.boundsInWindow().top }.padding(horizontal = 8.dp).clip(RoundedCornerShape(8.dp)).background(animatedTint)@@ -242,12 +241,6 @@ fun MiniPlayer(navController: NavHostController) {transition = CrossFade,modifier = Modifier.size(40.dp)- // The current song's cover is where the player's cover flies from- // and back to (CoverFlight), and is hidden while it flies.- .then(if (page == 1) Modifier- .onGloballyPositioned { CoverFlight.mini = it.boundsInWindow() }- .graphicsLayer { alpha = CoverFlight.miniCoverAlpha() }- else Modifier).clip(RoundedCornerShape(4.dp)),model = m.cover,contentScale = ContentScale.Crop,diff --git a/base/app/src/main/java/com/music/spotui/ui/components/CoverFlight.kt b/base/app/src/main/java/com/music/spotui/ui/components/CoverFlight.ktdeleted file mode 100644index 10da1ed4..00000000--- a/base/app/src/main/java/com/music/spotui/ui/components/CoverFlight.kt+++ /dev/null@@ -1,129 +0,0 @@-package com.music.spotui.ui.components--import androidx.compose.foundation.layout.Box-import androidx.compose.foundation.layout.size-import androidx.compose.foundation.shape.RoundedCornerShape-import androidx.compose.runtime.Composable-import androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableStateOf-import androidx.compose.runtime.setValue-import androidx.compose.ui.Modifier-import androidx.compose.ui.draw.clip-import androidx.compose.ui.geometry.Rect-import androidx.compose.ui.graphics.TransformOrigin-import androidx.compose.ui.graphics.graphicsLayer-import androidx.compose.ui.layout.ContentScale-import androidx.compose.ui.platform.LocalDensity-import androidx.compose.ui.unit.dp-import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi-import com.bumptech.glide.integration.compose.GlideImage--/**- * The cover that flies between the mini player and the full player while the player opens- * or closes, as in the official app: the small artwork grows into the big one as the player- * rises, and shrinks back into the mini player as it goes down.- *- * Both covers report where they sit; while [progress] is set the real ones are hidden and- * [FlyingCover] draws one in between. Everything moves in the draw phase (graphicsLayer),- * so the flight recomposes nothing.- */-object CoverFlight {- /** The mini player's cover, in window pixels. */- var mini by mutableStateOf<Rect?>(null)- /** The full player's cover once it is open, in window pixels; null when it shows none (Canvas, video, immersive). */- var player by mutableStateOf<Rect?>(null)- /**- * Where the sheet is (0 .. 1) while it moves, null when still: set by the sheet, read- * straight from its transition in draw lambdas. Published by an effect it came one frame- * late, and that first frame showed the real covers and the flying one at once (a flash).- */- var progressSource: () -> Float? = { null }- /** 0 (mini player) .. 1 (full player) while the player opens or closes; null otherwise. */- val progress: Float? get() = progressSource()?.takeIf { mini != null && player != null }- /**- * How far down the sliding player is drawn right now (px), set by the player sheet: the- * player's cover is measured on the first frame of its opening, its slide taken back out,- * so the very first opening already knows where the cover lands.- */- var sheetOffsetPx: () -> Float = { 0f }- /**- * The sliding player's own layout: the cover is measured against it, so its target does not- * move while the sheet slides (measured against the window it was re-measured every frame,- * a frame off the slide, and the flying cover visibly jumped in size on the way).- */- var sheetCoords: androidx.compose.ui.layout.LayoutCoordinates? = null- /**- * How far the user's finger has pulled the player down (px), set by the player. A player- * closed by that pull leaves with its cover, as in the official app: no flight then (the- * flight started from where the cover would be without the pull, and a cover detached from- * the sliding player showed above it — captured frame by frame on the test phone).- */- var pulledPx: () -> Float = { 0f }-- /** Read in a draw-phase lambda: hides a real cover while its stand-in flies. */- val flying: Boolean get() = progress != null-- // Cross-fades at both ends of the flight (the owner's call: hard cuts between the real- // covers and the flying one read as the motion being out of step). Over the last 20 % the- // player's cover fades in as the flying one fades out, and over the first 20 % the same with- // the mini player's; each reads [progress] in a draw lambda.- private const val BLEND = 0.2f- /** Opacity of the full player's own cover. */- fun playerCoverAlpha(): Float = progress?.let { ((it - (1f - BLEND)) / BLEND).coerceIn(0f, 1f) } ?: 1f- /** Opacity of the mini player's own cover. */- fun miniCoverAlpha(): Float = progress?.let { ((BLEND - it) / BLEND).coerceIn(0f, 1f) } ?: 1f- /** Opacity of the flying cover. */- fun flyingAlpha(): Float = progress?.let { 1f - maxOf(playerCoverAlpha(), miniCoverAlpha()) } ?: 0f- /**- * Opacity of the player's background and controls while it slides: they fade in over the- * first 60 % of the opening and out over the last 60 % of the closing, so the sheet never- * arrives or leaves as a hard block.- */- fun sheetAlpha(p: Float): Float = (p / 0.6f).coerceIn(0f, 1f)-}--/**- * The flying cover. Drawn inside the sliding player, so the slide's own offset- * ([slideOffsetPx], from the same animation) is taken back out: the cover moves in window- * coordinates, not with the sheet.- */-@OptIn(ExperimentalGlideComposeApi::class)-@Composable-fun FlyingCover(coverUri: String, slideOffsetPx: () -> Float) {- val to = CoverFlight.player ?: return- val from = CoverFlight.mini ?: return- if (to.width <= 0f || to.height <= 0f) return- val density = LocalDensity.current- Box(- Modifier- .size(with(density) { to.width.toDp() }, with(density) { to.height.toDp() })- .graphicsLayer {- val p = CoverFlight.progress- if (p == null) { alpha = 0f; return@graphicsLayer }- alpha = CoverFlight.flyingAlpha()- transformOrigin = TransformOrigin(0f, 0f)- val left = from.left + (to.left - from.left) * p- val top = from.top + (to.top - from.top) * p- val width = from.width + (to.width - from.width) * p- scaleX = width / to.width- scaleY = scaleX- translationX = left- translationY = top - slideOffsetPx()- }- .clip(RoundedCornerShape(8.dp)),- ) {- val context = androidx.compose.ui.platform.LocalContext.current- GlideImage(- model = coverUri,- contentDescription = null,- contentScale = ContentScale.Crop,- modifier = Modifier.size(with(density) { to.width.toDp() }, with(density) { to.height.toDp() }),- // The mini player's own small picture (already in memory) until the big one is- // there: a cover that had to load first left an empty square flying (a flash).- requestBuilderTransform = {- it.thumbnail(com.bumptech.glide.Glide.with(context).load(coverUri)- .override(from.width.toInt().coerceAtLeast(1), from.height.toInt().coerceAtLeast(1)).optionalCenterCrop())- },- )- }-}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 69d6c0ce..f4d41711 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@@ -1,29 +1,25 @@package com.music.spotui.ui.navigationimport androidx.activity.compose.BackHandler-import androidx.compose.animation.AnimatedVisibility-import androidx.compose.animation.EnterExitState-import androidx.compose.animation.core.animateFloat+import androidx.compose.animation.core.Animatable+import androidx.compose.animation.core.CubicBezierEasing+import androidx.compose.animation.core.tween+import androidx.compose.foundation.backgroundimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.fillMaxSize-import androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableIntStateOf-import androidx.compose.runtime.setValue-import androidx.compose.ui.Modifier-import androidx.compose.ui.layout.onSizeChanged-import androidx.compose.ui.graphics.graphicsLayer-import androidx.compose.ui.layout.onGloballyPositioned-import com.music.spotui.ui.components.CoverFlight-import com.music.spotui.ui.components.FlyingCover-import androidx.compose.animation.core.tween-import androidx.compose.animation.slideInVertically-import androidx.compose.animation.slideOutVerticallyimport androidx.compose.runtime.Composableimport androidx.compose.runtime.CompositionLocalProviderimport androidx.compose.runtime.LaunchedEffect-import androidx.compose.runtime.derivedStateOf+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableFloatStateOf+import androidx.compose.runtime.mutableIntStateOfimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.runtime.withFrameNanos+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.layout.onSizeChangedimport androidx.navigation.NavControllerimport com.music.spotui.ui.screens.PlayerScreenimport kotlinx.coroutines.flow.drop@@ -38,64 +34,89 @@ object PlayerSheet {fun show() { open.value = true }fun close() { open.value = false }++ /** The mini player's top edge in the window (px), where the player rises from and goes back to. */+ var miniTop by mutableFloatStateOf(0f)}+/**+ * How far the player's content has come in while it opens (0 .. 1), read in draw lambdas: the+ * cover, the titles and the controls fade in once the sheet is under way, after its background.+ */+val LocalPlayerReveal = androidx.compose.runtime.staticCompositionLocalOf<() -> Float> { { 1f } }++/*+ * Opening, as the official app: the player grows out of the mini player. Its background rises+ * from the mini player's top edge and fades in over the first part of the way while the page+ * behind dims, then the cover, titles and controls fade in and settle a few dp up. Closing plays+ * it backwards: the content fades first, then the sheet sinks into the mini player and fades+ * into it as the page lights up again.+ *+ * It replaces a cover flown between the two players (a copy that ran out of step with the real+ * one: a ghost square during the slide, a lone cover crossing the page on the way down) and a+ * slide whose clock started on the frame that built the whole player (its first frames lost+ * to that work: the "jump" at the start).+ */+private const val OPEN_MS = 380+private const val CLOSE_MS = 300+/** The sheet's background is fully there by this share of the way. */+private const val SHEET_FADE = 0.3f+/** How dark the page behind gets under the open player. */+private const val SCRIM = 0.6f+private val CloseEasing = CubicBezierEasing(0.4f, 0f, 0.2f, 1f)+@Composablefun PlayerOverlay(navController: NavController) {// Any navigation from the player (album, artist, playlist…) lands on that page.LaunchedEffect(navController) {navController.currentBackStackEntryFlow.drop(1).collect { PlayerSheet.close() }}- AnimatedVisibility(- visible = PlayerSheet.open.value,- enter = slideInVertically(tween(SHEET_IN_MS, easing = Decelerate)) { it },- exit = slideOutVertically(tween(SHEET_OUT_MS, easing = Accelerate)) { it },- ) {- BackHandler { PlayerSheet.close() }- val settled = remember { derivedStateOf { transition.currentState == transition.targetState } }- // The sheet's own progress (same curves as its slide), for the cover's flight: read only- // in a flow and in draw lambdas, never in composition, so the player does not recompose- // on every frame of the slide.- val sheet = transition.animateFloat(- transitionSpec = {- if (targetState == EnterExitState.Visible) tween(SHEET_IN_MS, easing = Decelerate)- else tween(SHEET_OUT_MS, easing = Accelerate)- },- label = "sheet",- ) { if (it == EnterExitState.Visible) 1f else 0f }- // Closing after a pull: the player goes down with its cover, no flight.- val closedByPull = remember(transition.targetState) {- transition.targetState != EnterExitState.Visible && CoverFlight.pulledPx() > 1f- }- androidx.compose.runtime.SideEffect {- CoverFlight.progressSource = {- if (transition.currentState != transition.targetState && !closedByPull) sheet.value else null- }+ val open = PlayerSheet.open.value+ val progress = remember { Animatable(0f) }+ var shown by remember { mutableStateOf(false) }+ val settled = remember { mutableStateOf(false) }+ LaunchedEffect(open) {+ if (open) {+ shown = true+ settled.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))+ settled.value = true+ } else if (shown) {+ settled.value = false+ progress.animateTo(0f, tween(CLOSE_MS, easing = CloseEasing))+ shown = false}- androidx.compose.runtime.DisposableEffect(Unit) { onDispose { CoverFlight.progressSource = { null } } }- var heightPx by remember { mutableIntStateOf(0) }- androidx.compose.runtime.SideEffect { CoverFlight.sheetOffsetPx = { (1f - sheet.value) * heightPx } }- Box(Modifier.fillMaxSize().onSizeChanged { heightPx = it.height }- .onGloballyPositioned { CoverFlight.sheetCoords = it }) {- // The player fades with its slide (see CoverFlight.sheetAlpha); a full layer alpha only- // while it moves, so the open player draws without an offscreen buffer.- Box(Modifier.fillMaxSize().graphicsLayer {- alpha = if (transition.currentState != transition.targetState) CoverFlight.sheetAlpha(sheet.value) else 1f- }) {- CompositionLocalProvider(LocalPageSettled provides settled) {- // A podcast episode gets the podcast player (±15 s, speed, sleep timer, no shuffle);- // everything else keeps the music player.- if (com.music.spotui.di.SongPlayer.isEpisode) {- com.music.spotui.ui.screens.PodcastPlayerScreen(navController)- } else {- PlayerScreen(navController)- }- }+ }+ if (!shown) return+ BackHandler(enabled = open) { PlayerSheet.close() }+ var heightPx by remember { mutableIntStateOf(0) }+ // The page behind dims as the player rises and comes back as it goes: the player is seen to+ // come over the page instead of being pasted on it. Only while it moves (covered once open).+ if (!settled.value) Box(+ Modifier.fillMaxSize()+ .graphicsLayer { alpha = progress.value * SCRIM }+ .background(androidx.compose.ui.graphics.Color.Black),+ )+ val reveal = remember { { ((progress.value - 0.25f) / 0.6f).coerceIn(0f, 1f) } }+ Box(+ Modifier.fillMaxSize().onSizeChanged { heightPx = it.height }.graphicsLayer {+ val p = progress.value+ val from = PlayerSheet.miniTop.takeIf { it > 0f } ?: heightPx.toFloat()+ translationY = (1f - p) * from+ // A layer alpha only over the first part of the way: the open player draws plain.+ alpha = (p / SHEET_FADE).coerceIn(0f, 1f)+ },+ ) {+ CompositionLocalProvider(LocalPageSettled provides settled, LocalPlayerReveal provides reveal) {+ // A podcast episode gets the podcast player (±15 s, speed, sleep timer, no shuffle);+ // everything else keeps the music player.+ if (com.music.spotui.di.SongPlayer.isEpisode) {+ com.music.spotui.ui.screens.PodcastPlayerScreen(navController)+ } else {+ PlayerScreen(navController)}- if (!com.music.spotui.di.SongPlayer.isEpisode) FlyingCover(- coverUri = com.music.spotui.di.Graph.currentSongState.coverUri.value,- slideOffsetPx = { (1f - sheet.value) * heightPx },- )}}}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 82bb8b46..befcb561 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@@ -211,6 +211,9 @@ fun PlayerScreen(navController: NavController) {mutableStateOf(Palette.cachedSecond(songCoverUri) ?: Color(AppBackground.toArgb()))}LaunchedEffect(songCoverUri) {+ // Known: kept as it is (extracted again it could come out a shade off, and the background+ // shifted after the player had opened).+ Palette.cachedSecond(songCoverUri)?.let { coverColor = it; return@LaunchedEffect }if (songCoverUri.isNotBlank()) Palette().extractSecondColorFromCoverUrl(context = context, songCoverUri) { color ->coverColor = color}@@ -322,7 +325,6 @@ fun PlayerScreen(navController: NavController) {LaunchedEffect(mv.state.value, remote, audioBuffering, displayedTrackId) { if (videoReady && !audioBuffering) mv.warm() }// Pulled down from the top, the player closes, like the back button (issue #4).val pullToClose = com.music.spotui.ui.components.rememberPullToDismiss { com.music.spotui.ui.navigation.PlayerSheet.close() }- androidx.compose.runtime.SideEffect { com.music.spotui.ui.components.CoverFlight.pulledPx = { pullToClose.offset } }pullToClose.enabled = !showLyrics && !mv.fullscreen.valueBox(modifier = Modifier@@ -369,9 +371,13 @@ fun PlayerScreen(navController: NavController) {))}+ // The content comes in after the sheet's background (see PlayerOverlay).+ val reveal = com.music.spotui.ui.navigation.LocalPlayerReveal.current+ val revealShift = with(androidx.compose.ui.platform.LocalDensity.current) { 24.dp.toPx() }androidx.compose.foundation.lazy.LazyColumn(modifier = Modifier.fillMaxSize()+ .graphicsLayer { val r = reveal(); alpha = r; translationY = (1f - r) * revealShift }.nestedScroll(pullToClose.connection).statusBarsPadding(),horizontalAlignment = Alignment.CenterHorizontally@@ -467,18 +473,8 @@ fun PlayerScreen(navController: NavController) {modifier = (if (immersive) Modifier.fillMaxSize()// Normal layout keeps the inset, rounded cover.else Modifier.padding(horizontal = 24.dp).aspectRatio(1f).clip(RoundedCornerShape(8.dp)))- // Where the mini player's cover flies to (CoverFlight), the sheet's- // slide taken out, only for the plain cover of the current song.- .then(if (page == 1) Modifier.onGloballyPositioned {- val flight = com.music.spotui.ui.components.CoverFlight- val sheet = flight.sheetCoords?.takeIf { s -> s.isAttached }- // Against the sheet, which sits at the window's top once open: the- // same rect on every frame of the slide (an equal Rect notifies no one).- flight.player = if (immersive || coverAlpha < 1f) null- else sheet?.localBoundingBoxOf(it, clipBounds = false) ?: it.boundsInWindow()- } else Modifier).graphicsLayer {- alpha = coverAlpha * (if (page == 1) com.music.spotui.ui.components.CoverFlight.playerCoverAlpha() else 1f)+ alpha = coverAlphaval grow = 1f + (1f - coverAlpha) * 0.06fscaleX = grow; scaleY = grow},diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/MyspotiRuntime.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/MyspotiRuntime.ktindex f4dab261..ed8875da 100644--- a/base/host-android/src/main/kotlin/app/myspoti/host/android/MyspotiRuntime.kt+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/MyspotiRuntime.kt@@ -35,7 +35,10 @@ object MyspotiRuntime {host.onPageLoaded = { scope.launch { spotify.onPageLoaded() } }host.onPageStarting = { spotify.onPageStarting() }spotify.player.reloadHost = { host.reload() }- spotify.player.recoveryHeld = { host.licenseLimited() }+ // Repairs wait while Spotify limits playback, and while a Spotify sign-in page is open:+ // the player is not there to answer, and the "page not answering" reload threw the user+ // off the e-mail code step while they were away reading the code (reported, log seen).+ spotify.player.recoveryHeld = { host.licenseLimited() || host.loginRequired.value }// Spotify limiting this client: stop asking (a paused player requests no licence).scope.launch {host.licenseLimitedUntil.collect { until ->