Skip to content

Unofficial YouTube Music / Spotify Premium client for Android, built in Liquid Glass. Audio effects, Spotify Connect, listening history, 8 languages. Rust core on librespot.

Give a track with no Canvas something of its own

Leloniod3e0734771f2
diff --git a/app/src/main/java/dev/lelonio/square/data/PreferencesStore.kt b/app/src/main/java/dev/lelonio/square/data/PreferencesStore.kt
index 7bac56c..394f633 100644
--- a/app/src/main/java/dev/lelonio/square/data/PreferencesStore.kt
+++ b/app/src/main/java/dev/lelonio/square/data/PreferencesStore.kt
@@ -27,6 +27,22 @@ class PreferencesStore(context: Context) {
prefs.edit().putString(KEY_TRACK_SORT, value).apply()
}
+ private val _coverAura = MutableStateFlow(prefs.getBoolean(KEY_COVER_AURA, false))
+
+ /**
+ * Whether a track with no Canvas gets the animation made from its cover.
+ *
+ * A taste rather than a property of a song, so it is remembered: whoever
+ * turns it on wants it on for the next track without one too, and for the
+ * next time they open the app.
+ */
+ val coverAura: StateFlow<Boolean> = _coverAura.asStateFlow()
+
+ fun setCoverAura(on: Boolean) {
+ _coverAura.value = on
+ prefs.edit().putBoolean(KEY_COVER_AURA, on).apply()
+ }
+
/**
* This phone's Connect id, made once and kept for good.
*
@@ -119,6 +135,7 @@ class PreferencesStore(context: Context) {
private companion object {
const val FILE_NAME = "square_preferences"
const val KEY_TRACK_SORT = "track_sort"
+ const val KEY_COVER_AURA = "cover_aura"
const val KEY_DEVICE_ID = "device_id"
const val KEY_ONBOARDED = "onboarded"
const val KEY_PLAYER_OPEN = "player_open"
diff --git a/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt b/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt
index fcbd4f1..701e804 100644
--- a/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt
@@ -1001,29 +1001,15 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
* account with no Web API application connected simply keeps it.
*/
/**
- * The account's playlists, from the access point or from the Web API.
+ * The account's library, as the active backend assembles it.
*
- * The access point is asked first: it is the same list, it needs no
- * registered application, and it carries the playlists this account follows
- * as well as its own. But `rootlist` answers 502 often enough to matter —
- * a Spotify-side failure nothing here can prevent — and losing the whole
- * library screen to it is out of proportion, since the Web API can answer
- * the same question.
+ * This used to build the Spotify list itself, which is why it went on
+ * showing the old one: the backend is where the access point, the Web API
+ * fallback and Liked Songs are put together, and a second copy here simply
+ * missed everything added there.
*/
private suspend fun playlists(): List<CatalogPlaylist> =
- runCatching { Catalog.playlists() }
- .onFailure { android.util.Log.w(TAG, "rootlist unavailable: ${describe(it)}") }
- .recoverCatching {
- check(container.webApi.isReady) { it.message ?: string(R.string.rootlist_unavailable) }
- container.api.playlists(limit = WEB_API_PAGE).items.map { dto ->
- CatalogPlaylist(
- uri = dto.uri,
- name = dto.name,
- artworkUrl = dto.images.firstOrNull()?.url,
- )
- }
- }
- .getOrThrow()
+ container.activeBackend.playlists()
/** Covers already looked up, so a second visit to the home page is free. */
private val coverCache = mutableMapOf<String, String>()
@@ -1075,6 +1061,32 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
/** Playlists in the order this device last opened them; see [PlaylistOrderStore]. */
val playlistOrder: StateFlow<List<String>> get() = container.playlistOrder.order
+ /** Pinned playlists, in the order they were pinned. */
+ val pinnedPlaylists: StateFlow<List<String>> get() = container.pinnedPlaylists.pinned
+
+ fun togglePinned(uri: String) = container.pinnedPlaylists.toggle(uri)
+
+ /**
+ * A station built from one track, as the official client's radio button does.
+ *
+ * `spotify:station:track:…` is a context like any other to the access
+ * point: Spotify assembles the list and this only has to ask for it. Empty
+ * when it will not, and the caller then leaves the queue alone rather than
+ * playing something the listener did not choose.
+ */
+ suspend fun radioFor(trackUri: String): List<CatalogTrack> {
+ val id = trackUri.substringAfterLast(':')
+ val station = "spotify:station:track:$id"
+ return runCatching { Catalog.tracks(Catalog.contextTrackUris(station)) }
+ .onFailure { android.util.Log.w(TAG, "no station for $trackUri: ${describe(it)}") }
+ .getOrDefault(emptyList())
+ }
+
+ /** The colour animation for tracks with no Canvas; see PreferencesStore. */
+ val coverAura: StateFlow<Boolean> get() = container.preferences.coverAura
+
+ fun setCoverAura(on: Boolean) = container.preferences.setCoverAura(on)
+
/** How the detail screen sorts its tracks; remembered between visits. */
val trackSort: StateFlow<String?> get() = container.preferences.trackSort
@@ -1157,10 +1169,47 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
/** Notes the tracks of a playlist that has just been read. */
private fun rememberMembership(contextUri: String, tracks: List<CatalogTrack>) {
- if (!contextUri.startsWith("spotify:playlist:") || tracks.isEmpty()) return
+ if (tracks.isEmpty()) return
+ // Liked Songs is not one of the playlists, and the player says so with
+ // a heart rather than a tick.
+ if (contextUri.endsWith(":collection")) {
+ _liked.value = _liked.value + tracks.map { it.uri }
+ return
+ }
+ if (!contextUri.startsWith("spotify:playlist:")) return
_inPlaylists.value = _inPlaylists.value + tracks.map { it.uri }
}
+ private val _liked = MutableStateFlow<Set<String>>(emptySet())
+
+ /**
+ * Tracks known to be in Liked Songs.
+ *
+ * Unlike [inPlaylists] this one can be asked outright: Spotify answers
+ * "is this saved?" in a single call, so the track on screen is checked as
+ * it starts rather than inferred from what happens to have been read.
+ */
+ val likedTracks: StateFlow<Set<String>> = _liked.asStateFlow()
+
+ /** Tracks already asked about, saved or not, so each is asked once. */
+ private val likedAsked = mutableSetOf<String>()
+
+ fun checkLiked(uri: String?) {
+ if (uri == null || !uri.startsWith("spotify:track:")) return
+ if (!container.webApi.isReady || !likedAsked.add(uri)) return
+ viewModelScope.launch {
+ runCatching { container.api.tracksAreSaved(uri.substringAfterLast(':')) }
+ .onSuccess { answers ->
+ if (answers.firstOrNull() == true) _liked.value = _liked.value + uri
+ }
+ .onFailure {
+ // Asked again next time it plays: this is a decoration.
+ likedAsked.remove(uri)
+ android.util.Log.i(TAG, "cannot tell if $uri is saved: ${describe(it)}")
+ }
+ }
+ }
+
private val contextCache =
object : LinkedHashMap<String, ContextCacheStore.Entry>(0, 0.75f, true) {
override fun removeEldestEntry(eldest: Map.Entry<String, ContextCacheStore.Entry>) =
diff --git a/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt b/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt
index cf30ff9..d07ef61 100644
--- a/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt
@@ -101,6 +101,7 @@ import dev.lelonio.square.ui.library.openLink
import com.adamglin.phosphoricons.regular.Download
import com.adamglin.phosphoricons.regular.LinkSimple
import com.adamglin.phosphoricons.regular.PencilSimple
+import com.adamglin.phosphoricons.regular.PushPin
import com.adamglin.phosphoricons.regular.Plus
import com.adamglin.phosphoricons.regular.Queue
import com.adamglin.phosphoricons.regular.SpotifyLogo
@@ -301,6 +302,9 @@ fun SquareApp(
val presets by viewModel.effectPresets.collectAsStateWithLifecycle()
val feed by viewModel.feed.collectAsStateWithLifecycle()
val playlistOrder by viewModel.playlistOrder.collectAsStateWithLifecycle()
+ val pinnedPlaylists by viewModel.pinnedPlaylists.collectAsStateWithLifecycle()
+ val likedTracks by viewModel.likedTracks.collectAsStateWithLifecycle()
+ val coverAura by viewModel.coverAura.collectAsStateWithLifecycle()
val devices by viewModel.devices.collectAsStateWithLifecycle()
val addToPlaylist by viewModel.addToPlaylist.collectAsStateWithLifecycle()
val trackSort by viewModel.trackSort.collectAsStateWithLifecycle()
@@ -450,6 +454,11 @@ fun SquareApp(
var lyrics by remember { mutableStateOf<Lyrics?>(null) }
var lyricsLoading by remember { mutableStateOf(false) }
+ // One small question per track: is this one saved? The player draws a heart
+ // from the answer, and there is no other way to know without reading the
+ // whole of Liked Songs.
+ LaunchedEffect(playback.mediaId) { viewModel.checkLiked(playback.mediaId) }
+
// Fetched per track. Most of the catalogue has none, so a null result is an
// ordinary answer that shows an empty state rather than an error.
LaunchedEffect(playback.mediaId) {
@@ -491,6 +500,7 @@ fun SquareApp(
val playAgainLabel = stringResource(R.string.play_again)
val trendingLabel = stringResource(R.string.trending_now)
val searchLabel = stringResource(R.string.search)
+ val radioLabel = stringResource(R.string.radio)
val inPip by YouTubeVideoMode.pictureInPicture.collectAsStateWithLifecycle()
@@ -594,7 +604,11 @@ fun SquareApp(
// The sheets that read this one are shut most of the time, so
// the whole app was paying for a full-screen copy of itself for
// nothing.
- val sheetsOpen = trackMenu != null || addToPlaylist.open
+ // The playlist sheet belongs in here too. Left out, the layer
+ // it refracts was not being recorded while it was the only
+ // thing open, so the glass had nothing behind it and the sheet
+ // came up as a transparent panel with no depth at all.
+ val sheetsOpen = trackMenu != null || addToPlaylist.open || playlistMenu != null
// Kept on a little past the close, or the layer would stop
// being recorded while the sheet is still fading out over it
// and the panel would go black on the way down.
@@ -709,6 +723,7 @@ fun SquareApp(
onLogOut = viewModel::logOut,
onOpenPlaylist = { navController.openPlaylist(viewModel, it) },
playlistOrder = playlistOrder,
+ pinned = pinnedPlaylists,
canEdit = viewModel.canEditPlaylists,
onCreatePlaylist = { naming = NamingRequest(null) },
onPlaylistMenu = { playlistMenu = it },
@@ -965,6 +980,29 @@ fun SquareApp(
onAnotherDevice = remote != null,
alreadySaved = playback.mediaId != null &&
playback.mediaId in inPlaylists,
+ inLikedSongs = playback.mediaId != null &&
+ playback.mediaId in likedTracks,
+ auraOn = coverAura,
+ onToggleAura = { viewModel.setCoverAura(!coverAura) },
+ // Spotify's own radio, and only where Spotify
+ // can answer: the station is a context on its
+ // access point and means nothing anywhere else.
+ onRadio = playback.mediaId
+ ?.takeIf {
+ it.startsWith("spotify:track:") &&
+ backend == dev.lelonio.square.backend.BackendId.SPOTIFY
+ }
+ ?.let { uri ->
+ {
+ scope.launch {
+ val tracks = viewModel.radioFor(uri)
+ if (tracks.isNotEmpty()) {
+ onPlay(tracks, 0, null, false, radioLabel, 0L)
+ }
+ }
+ Unit
+ }
+ },
onOpenDevices = viewModel::openDevices,
connectAvailable =
backend == dev.lelonio.square.backend.BackendId.SPOTIFY,
@@ -1027,7 +1065,21 @@ fun SquareApp(
onDismiss = { playlistMenu = null },
) {
if (shownPlaylist != null) {
+ // First action: this is the one that costs nothing and
+ // can be undone by pressing it again.
+ val isPinned = shownPlaylist.uri in pinnedPlaylists
TrackSheetAction(
+ stringResource(if (isPinned) R.string.unpin else R.string.pin),
+ PhosphorIcons.Regular.PushPin,
+ ) {
+ viewModel.togglePinned(shownPlaylist.uri)
+ playlistMenu = null
+ }
+ // Liked Songs is Spotify's own list: it can be pinned
+ // like any other row, but there is no name to change
+ // and no way to delete it.
+ val editable = !shownPlaylist.uri.endsWith(":collection")
+ if (editable) TrackSheetAction(
stringResource(R.string.rename),
PhosphorIcons.Regular.PencilSimple,
) {
@@ -1048,7 +1100,7 @@ fun SquareApp(
sendForDownload(context, shownPlaylist.openLink())
}
}
- TrackSheetAction(
+ if (editable) TrackSheetAction(
stringResource(R.string.delete),
PhosphorIcons.Regular.Trash,
destructive = true,
diff --git a/app/src/main/java/dev/lelonio/square/ui/player/CoverAura.kt b/app/src/main/java/dev/lelonio/square/ui/player/CoverAura.kt
new file mode 100644
index 0000000..572ef98
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/ui/player/CoverAura.kt
@@ -0,0 +1,197 @@
+package dev.lelonio.square.ui.player
+
+import androidx.compose.animation.core.LinearEasing
+import androidx.compose.animation.core.RepeatMode
+import androidx.compose.animation.core.animateFloat
+import androidx.compose.animation.core.infiniteRepeatable
+import androidx.compose.animation.core.rememberInfiniteTransition
+import androidx.compose.animation.core.tween
+import androidx.compose.foundation.Canvas
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableFloatStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.blur
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.geometry.Size
+import androidx.compose.ui.graphics.Brush
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.drawscope.DrawScope
+import androidx.compose.ui.graphics.drawscope.rotate
+import kotlin.math.cos
+import kotlin.math.sin
+
+/**
+ * Light in the cover's own colours, moving, for a track with no Canvas.
+ *
+ * Most of the catalogue has no clip, and those tracks got a still blurred cover
+ * where the rest of the app has something alive. This invents nothing about the
+ * song: it is the artwork's own palette drifting behind the glass.
+ *
+ * Built for the glass rather than for itself. A pane of liquid glass shows what
+ * is behind it bent at its edges, and bending an even wash of colour produces an
+ * even wash of colour — the first version was three soft blobs and the panels
+ * above it barely registered that anything had changed. What a lens has
+ * something to do with is an *edge*, so this draws edges: beams with a hard
+ * flank sweeping across the screen, and small bright caustics travelling with
+ * them. Under glass those read as the refraction moving.
+ *
+ * Slow, all the same. The periods are not multiples of one another, so nothing
+ * on screen ever pulses in time with anything else, and a screen you look at for
+ * the length of an album must not be doing anything you can count.
+ */
+@Composable
+fun CoverAura(
+ colors: List<Color>,
+ /** Stilled with the music: a paused track should not be dancing. */
+ playing: Boolean,
+ modifier: Modifier = Modifier,
+) {
+ if (colors.isEmpty()) return
+
+ val transition = rememberInfiniteTransition(label = "aura")
+ // One phase read at several speeds below, rather than several animations:
+ // they would drift apart on a dropped frame and this cannot.
+ val phase by transition.animateFloat(
+ initialValue = 0f,
+ targetValue = 1f,
+ animationSpec = infiniteRepeatable(
+ animation = tween(CYCLE_MS, easing = LinearEasing),
+ repeatMode = RepeatMode.Restart,
+ ),
+ label = "phase",
+ )
+
+ // Held where it was rather than snapped anywhere: the light stops, it does
+ // not jump back to a starting position.
+ val frozen = remember { mutableFloatStateOf(0f) }
+ if (playing) frozen.floatValue = phase
+ val turn = frozen.floatValue * TAU
+
+ Canvas(
+ modifier
+ .fillMaxSize()
+ // Blurred as one picture rather than drawn soft.
+ //
+ // Soft shapes and a blurred hard shape are not the same thing: a
+ // gradient fades evenly, while a blurred edge keeps a bright ridge
+ // where the edge was, and that ridge is what the glass above has
+ // something to bend. So the beams and the caustics are drawn crisp
+ // and the whole thing is put out of focus afterwards.
+ .blur(BLUR),
+ ) {
+ // The bed: wide, soft, and the only part that is meant to be looked at
+ // directly. Everything after this is for the glass.
+ repeat(3) { index ->
+ val color = colors[index % colors.size]
+ val angle = turn * DRIFT[index] + index * (TAU / 3f)
+ val centre = Offset(
+ x = size.width * (0.5f + 0.34f * cos(angle)),
+ y = size.height * (0.42f + 0.30f * sin(angle * 0.8f)),
+ )
+ val radius = size.maxDimension * 0.62f
+ drawCircle(
+ brush = Brush.radialGradient(
+ colors = listOf(color.copy(alpha = 0.5f), Color.Transparent),
+ center = centre,
+ radius = radius,
+ ),
+ radius = radius,
+ center = centre,
+ )
+ }
+
+ // The beams. Each is a band with one soft side and one abrupt one, and
+ // the abrupt side is the whole point: that is the edge the panes bend.
+ repeat(2) { index ->
+ val color = colors[(index + 1) % colors.size]
+ val sweep = turn * BEAM[index] + index * 1.7f
+ rotate(degrees = (sweep * 18f) + index * 40f - 20f) {
+ beam(
+ color = color,
+ // Travels across and wraps, so a beam is always crossing
+ // rather than all of them arriving together.
+ offset = ((sweep * 0.18f + index * 0.5f) % 1f),
+ )
+ }
+ }
+
+ // Caustics: the bright knots light makes through moving water. Small
+ // and few — under a lens each one throws a highlight far larger than
+ // itself, and a dozen would be glitter.
+ repeat(3) { index ->
+ val color = colors[(index + 2) % colors.size]
+ val angle = turn * CAUSTIC[index] + index * 2.1f
+ val centre = Offset(
+ x = size.width * (0.5f + 0.40f * sin(angle)),
+ y = size.height * (0.45f + 0.34f * cos(angle * 1.3f)),
+ )
+ val radius = size.minDimension * 0.10f
+ drawCircle(
+ brush = Brush.radialGradient(
+ // White at the core rather than more of the same colour: a
+ // highlight is where the light is, not where the paint is.
+ colors = listOf(
+ Color.White.copy(alpha = 0.30f),
+ color.copy(alpha = 0.40f),
+ Color.Transparent,
+ ),
+ center = centre,
+ radius = radius,
+ ),
+ radius = radius,
+ center = centre,
+ )
+ }
+ }
+}
+
+/**
+ * One band of light across the whole canvas, at whatever rotation is in force.
+ *
+ * Drawn well outside the bounds so that turning it never brings an end of the
+ * band into view: a beam has to arrive from off screen or it reads as a shape
+ * rather than as light.
+ */
+private fun DrawScope.beam(color: Color, offset: Float) {
+ val span = size.maxDimension * 2f
+ val x = -span / 4f + span * offset
+ val width = size.minDimension * 0.42f
+ drawRect(
+ brush = Brush.horizontalGradient(
+ // The stops are the shape: a long fade in, full colour, then a
+ // cliff. Symmetrical stops gave a soft band with nothing for the
+ // glass to catch.
+ colorStops = arrayOf(
+ 0f to Color.Transparent,
+ 0.62f to color.copy(alpha = 0.26f),
+ 0.88f to color.copy(alpha = 0.44f),
+ 0.92f to color.copy(alpha = 0.06f),
+ 1f to Color.Transparent,
+ ),
+ startX = x,
+ endX = x + width,
+ ),
+ topLeft = Offset(x, -span / 2f),
+ size = Size(width, span * 1.5f),
+ )
+}
+
+/**
+ * How far out of focus. Wide enough that no shape can be named, narrow enough
+ * that the beams still pass as beams.
+ */
+private val BLUR = 48.dp
+
+/** A full turn of the slowest element. Minutes, not seconds. */
+private const val CYCLE_MS = 42_000
+
+/** Deliberately not in simple ratios, so nothing lines up twice the same way. */
+private val DRIFT = floatArrayOf(1f, 0.61f, 1.37f)
+private val BEAM = floatArrayOf(0.83f, 1.19f)
+private val CAUSTIC = floatArrayOf(1.11f, 0.74f, 1.53f)
+
+private const val TAU = (2 * Math.PI).toFloat()
diff --git a/app/src/main/java/dev/lelonio/square/ui/player/PlayerScreen.kt b/app/src/main/java/dev/lelonio/square/ui/player/PlayerScreen.kt
index fa28543..2d5c214 100644
--- a/app/src/main/java/dev/lelonio/square/ui/player/PlayerScreen.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/player/PlayerScreen.kt
@@ -86,6 +86,7 @@ import dev.lelonio.square.ui.theme.softShadow
import com.adamglin.PhosphorIcons
import com.adamglin.phosphoricons.Fill
import com.adamglin.phosphoricons.Regular
+import com.adamglin.phosphoricons.fill.Heart
import com.adamglin.phosphoricons.fill.Pause
import com.adamglin.phosphoricons.fill.Play
import com.adamglin.phosphoricons.fill.SkipBack
@@ -95,10 +96,12 @@ import com.adamglin.phosphoricons.regular.Devices
import com.adamglin.phosphoricons.regular.Check
import com.adamglin.phosphoricons.regular.Plus
import com.adamglin.phosphoricons.regular.Queue
+import com.adamglin.phosphoricons.regular.Broadcast
import com.adamglin.phosphoricons.regular.YoutubeLogo
import com.adamglin.phosphoricons.regular.Repeat
import com.adamglin.phosphoricons.regular.RepeatOnce
import com.adamglin.phosphoricons.regular.Shuffle
+import com.adamglin.phosphoricons.regular.Sparkle
import kotlin.math.abs
/**
@@ -117,6 +120,12 @@ private const val CANVAS_SWIPE_FOLLOW = 0.35f
*/
private const val PAUSED_DIM = 0.55f
+/**
+ * How long a track is given to produce a Canvas before the app decides it has
+ * none. Long enough to cover a slow lookup, short enough not to feel withheld.
+ */
+private const val AURA_OFFER_DELAY_MS = 1_600L
+
/**
* The player, as a liquid-glass prototype.
*
@@ -194,6 +203,21 @@ fun PlayerScreen(
* and the answer is cheap for anything the app has already read.
*/
alreadySaved: Boolean = false,
+ /**
+ * Whether it is in Liked Songs, which is a different answer and a different
+ * mark: a heart, the way every Spotify client says it.
+ */
+ inLikedSongs: Boolean = false,
+ /**
+ * The colour animation for tracks with no Canvas, and its switch.
+ *
+ * Held outside this screen: it is remembered between sessions, and it used
+ * to be lost the moment the player was folded down to the bar.
+ */
+ auraOn: Boolean = false,
+ onToggleAura: () -> Unit = {},
+ /** Starts a station from the current track; null where there is none. */
+ onRadio: (() -> Unit)? = null,
/** The playlist picker's state, shown in the panel rather than as a sheet. */
addToPlaylist: MainViewModel.AddToPlaylistState,
onPickPlaylist: (dev.lelonio.square.data.CatalogPlaylist) -> Unit,
@@ -272,6 +296,24 @@ fun PlayerScreen(
var ambient by remember { mutableStateOf<AmbientEdges?>(null) }
LaunchedEffect(videoOn) { if (!videoOn) ambient = null }
+ val auraColors by dev.lelonio.square.ui.theme.rememberArtworkPalette(
+ state.artworkUrl.takeIf { auraOn && canvas == null },
+ )
+
+ // A Canvas is known about a moment after the track starts, not with it, so
+ // "this song has no clip" is only true once the app has waited for one. Put
+ // on screen immediately, the button appeared on every track and took itself
+ // away again half a second later.
+ var offerAura by remember { mutableStateOf(false) }
+ LaunchedEffect(state.mediaId, canvas) {
+ if (canvas != null) {
+ offerAura = false
+ return@LaunchedEffect
+ }
+ kotlinx.coroutines.delay(AURA_OFFER_DELAY_MS)
+ offerAura = true
+ }
+
Box(Modifier.fillMaxSize()) {
Box(
Modifier
@@ -300,6 +342,14 @@ fun PlayerScreen(
// colour without ever picking any of it up.
AmbientLight(ambient)
+ // The stand-in for a Canvas, for the tracks that have none, and
+ // only when it has been asked for. In the same layer as the light
+ // above and for the same reason.
+ if (canvas == null && auraOn) {
+ CoverAura(colors = auraColors, playing = state.isPlaying)
+ }
+
+
// Held at zero until the first frame, then faded up. Without this
// the clip's own surface appears the instant it decodes, which next
// to a cover crossfading out reads as two separate events.
@@ -489,14 +539,46 @@ fun PlayerScreen(
Modifier.fillMaxSize(),
contentAlignment = Alignment.Center,
) {
- Cover(
- state,
- panel,
- onNext,
- onPrevious,
- sharedScope,
- animatedScope,
- )
+ Column(
+ horizontalAlignment = Alignment.CenterHorizontally,
+ ) {
+ Cover(
+ state,
+ panel,
+ onNext,
+ onPrevious,
+ sharedScope,
+ animatedScope,
+ )
+ // Under the picture and almost against
+ // it, because it is about the picture:
+ // this is a switch for how the screen
+ // looks, not one of the per-track
+ // actions in the capsule below. Inside
+ // this slot rather than under it, so it
+ // goes away by itself whenever the
+ // lyrics or the effects take the space.
+ AnimatedVisibility(
+ visible = canvas == null && offerAura,
+ enter = fadeIn(tween(260)),
+ exit = fadeOut(tween(160)),
+ ) {
+ RoundGlassButton(
+ backdrop = glassBackdrop,
+ size = 28.dp,
+ onClick = onToggleAura,
+ modifier = Modifier.padding(top = 8.dp),
+ ) {
+ Icon(
+ PhosphorIcons.Regular.Sparkle,
+ contentDescription =
+ stringResource(R.string.cover_aura),
+ tint = panelTint(auraOn),
+ modifier = Modifier.size(14.dp),
+ )
+ }
+ }
+ }
}
// The picture in the cover's place rather than
@@ -622,6 +704,23 @@ fun PlayerScreen(
onOpenUri(uri, name)
},
)
+ // A station built from this track, the way the
+ // official client's own radio button does it.
+ if (onRadio != null) {
+ RoundGlassButton(
+ backdrop = glassBackdrop,
+ size = 40.dp,
+ onClick = onRadio,
+ ) {
+ Icon(
+ PhosphorIcons.Regular.Broadcast,
+ contentDescription = stringResource(R.string.radio),
+ tint = panelTint(false),
+ modifier = Modifier.size(20.dp),
+ )
+ }
+ Spacer(Modifier.size(8.dp))
+ }
// The queue's one control. It is a sheet that
// opens over the player rather than a view of
// it, which is why it sits here and not in the
@@ -663,19 +762,22 @@ fun PlayerScreen(
},
) {
Icon(
- if (alreadySaved) {
- PhosphorIcons.Regular.Check
- } else {
- PhosphorIcons.Regular.Plus
+ when {
+ inLikedSongs -> PhosphorIcons.Fill.Heart
+ alreadySaved -> PhosphorIcons.Regular.Check
+ else -> PhosphorIcons.Regular.Plus
},
contentDescription = stringResource(
- if (alreadySaved) R.string.in_a_playlist
- else R.string.add_to_playlist,
+ when {
+ inLikedSongs -> R.string.liked_songs
+ alreadySaved -> R.string.in_a_playlist
+ else -> R.string.add_to_playlist
+ },
),
tint = when {
panel == PlayerPanel.ADD_TO_PLAYLIST ->
panelTint(true)
- alreadySaved -> SavedInk
+ inLikedSongs || alreadySaved -> SavedInk
else -> panelTint(false)
},
modifier = Modifier.size(20.dp),
diff --git a/app/src/main/java/dev/lelonio/square/ui/theme/ArtworkColor.kt b/app/src/main/java/dev/lelonio/square/ui/theme/ArtworkColor.kt
index c9b5b51..af0fe1e 100644
--- a/app/src/main/java/dev/lelonio/square/ui/theme/ArtworkColor.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/theme/ArtworkColor.kt
@@ -47,6 +47,71 @@ private val cached = object : LinkedHashMap<String, Color>(16, 0.75f, true) {
override fun removeEldestEntry(eldest: Map.Entry<String, Color>?) = size > 64
}
+/**
+ * A handful of colours from an artwork, for something that has to move.
+ *
+ * [rememberArtworkColor] answers with one colour because a theme needs one.
+ * An animation needs several or it has nothing to travel between, and they
+ * have to come from the same picture or the movement stops being the cover's.
+ * Empty until the cover has been read, and empty for good if it cannot be.
+ */
+@Composable
+fun rememberArtworkPalette(artworkUrl: String?): State<List<Color>> {
+ val context = LocalContext.current
+ val state = remember { mutableStateOf<List<Color>>(emptyList()) }
+
+ LaunchedEffect(artworkUrl) {
+ if (artworkUrl == null) {
+ state.value = emptyList()
+ return@LaunchedEffect
+ }
+ cachedPalettes[artworkUrl]?.let {
+ state.value = it
+ return@LaunchedEffect
+ }
+ val swatches = extractPalette(context, artworkUrl)
+ if (swatches.isNotEmpty()) cachedPalettes[artworkUrl] = swatches
+ state.value = swatches
+ }
+ return state
+}
+
+private val cachedPalettes = object : LinkedHashMap<String, List<Color>>(16, 0.75f, true) {
+ override fun removeEldestEntry(eldest: Map.Entry<String, List<Color>>?) = size > 32
+}
+
+private suspend fun extractPalette(context: Context, url: String): List<Color> =
+ withContext(Dispatchers.IO) {
+ runCatching {
+ val request = ImageRequest.Builder(context)
+ .data(url)
+ .size(96)
+ .allowHardware(false)
+ .build()
+
+ val bitmap = (context.imageLoader.execute(request) as? SuccessResult)
+ ?.drawable
+ ?.let { (it as? android.graphics.drawable.BitmapDrawable)?.bitmap }
+ ?: return@runCatching emptyList()
+
+ val palette = Palette.from(bitmap).clearFilters().generate()
+ // In this order on purpose: the vivid ones lead, the muted ones fill
+ // in behind them, and a cover that is all one colour still answers
+ // with something rather than nothing.
+ listOfNotNull(
+ palette.vibrantSwatch,
+ palette.lightVibrantSwatch,
+ palette.darkVibrantSwatch,
+ palette.mutedSwatch,
+ palette.darkMutedSwatch,
+ palette.dominantSwatch,
+ )
+ .map { Color(it.rgb) }
+ .distinct()
+ .take(4)
+ }.getOrDefault(emptyList())
+ }
+
private suspend fun extractDominant(context: Context, url: String): Color? =
withContext(Dispatchers.IO) {
runCatching {