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.

Pictures the size of the screen

Lelonio592827476c60
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index e698582..e46d974 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -191,6 +191,8 @@ dependencies {
// DASH, for Spotify's own video: its manifest is a set of segment
// templates, which is what a DASH source is built to walk.
implementation(libs.media3.exoplayer.dash)
+ // Apple's animated covers are HLS; see AppleCatalog and MotionCover.
+ implementation(libs.media3.exoplayer.hls)
implementation(libs.media3.ui)
implementation(libs.kotlinx.coroutines.android)
diff --git a/app/src/main/java/dev/lelonio/square/SquareApplication.kt b/app/src/main/java/dev/lelonio/square/SquareApplication.kt
index 903ddfc..baa560a 100644
--- a/app/src/main/java/dev/lelonio/square/SquareApplication.kt
+++ b/app/src/main/java/dev/lelonio/square/SquareApplication.kt
@@ -45,6 +45,12 @@ class SquareApplication : Application() {
downloads.isDownloaded(it)
}
+ // The other catalogue's answers, kept between runs. Without a store to
+ // write to it still works and simply asks again every time — which is
+ // the difference between a page that opens on the right picture and one
+ // that opens on Spotify's and changes it a second later.
+ dev.lelonio.square.data.AppleCatalog.attach(this)
+
// Two things feed the offline state, and one thing reads it out to the
// engine. The switch below is the listener's; the watch is the network
// going; and the engine has to be told either way, because it cannot
diff --git a/app/src/main/java/dev/lelonio/square/backend/SpotifyBackend.kt b/app/src/main/java/dev/lelonio/square/backend/SpotifyBackend.kt
index 9501572..4bc30d6 100644
--- a/app/src/main/java/dev/lelonio/square/backend/SpotifyBackend.kt
+++ b/app/src/main/java/dev/lelonio/square/backend/SpotifyBackend.kt
@@ -3,7 +3,6 @@ package dev.lelonio.square.backend
import androidx.media3.common.Player
import androidx.media3.common.util.UnstableApi
import dev.lelonio.square.SquareApplication
-import dev.lelonio.square.backend.lyrics.Lossless
import dev.lelonio.square.data.Catalog
import dev.lelonio.square.data.CatalogPlaylist
import dev.lelonio.square.data.CatalogTrack
@@ -230,9 +229,13 @@ class SpotifyBackend(private val container: SquareApplication) : MusicBackend {
title: String,
artist: String,
durationMs: Long,
- ) = dev.lelonio.square.backend.lyrics.Amll.lyrics(uri)
- ?: Lossless.lyrics(title, artist, durationMs)
- ?: Catalog.lyrics(uri)
+ ) = dev.lelonio.square.backend.lyrics.SpotifyLyrics.lyrics(
+ uri = uri,
+ title = title,
+ artist = artist,
+ durationMs = durationMs,
+ allowNetwork = !dev.lelonio.square.playback.OfflineMode.active.value,
+ )
/**
* Whether playlists can be made and changed.
diff --git a/app/src/main/java/dev/lelonio/square/backend/lyrics/SpotifyLyrics.kt b/app/src/main/java/dev/lelonio/square/backend/lyrics/SpotifyLyrics.kt
new file mode 100644
index 0000000..bf7e9be
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/backend/lyrics/SpotifyLyrics.kt
@@ -0,0 +1,64 @@
+package dev.lelonio.square.backend.lyrics
+
+import dev.lelonio.square.data.Catalog
+import dev.lelonio.square.data.Lyrics
+import dev.lelonio.square.download.DownloadExtras
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import kotlinx.serialization.json.Json
+
+/**
+ * The words behind a Spotify track, and the copy kept beside a download.
+ *
+ * The chain itself is not new — the TTML archive, then lossless.wtf, then
+ * Spotify's own — but it now has two callers rather than one: the player, which
+ * asks when a song starts, and the download queue, which asks so that the same
+ * song has its words in a tunnel. One function so the two cannot drift: a
+ * listener who downloads a song and then plays it offline must be shown the
+ * lyrics they would have been shown online, not a different source's.
+ *
+ * Storing is part of asking, for the same reason. Every answer that arrives for
+ * a downloaded track is written down on the way past — [DownloadExtras] decides
+ * which tracks those are — so nothing else has to remember to do it, and a song
+ * whose words were fetched while the player was showing them is a song that
+ * keeps them.
+ */
+object SpotifyLyrics {
+
+ private val json = Json { ignoreUnknownKeys = true }
+
+ /**
+ * @param allowNetwork false offline, where the only lyrics are the kept ones.
+ */
+ suspend fun lyrics(
+ uri: String,
+ title: String,
+ artist: String,
+ durationMs: Long,
+ allowNetwork: Boolean = true,
+ ): Lyrics? {
+ if (!allowNetwork) return kept(uri)
+
+ val found = Amll.lyrics(uri)
+ ?: Lossless.lyrics(title, artist, durationMs)
+ ?: Catalog.lyrics(uri)
+
+ return withContext(Dispatchers.IO) {
+ // Nothing found is an answer worth keeping too, so a downloaded
+ // song with no words is not looked up again on every turn of the
+ // queue; see DownloadExtras.note.
+ if (found == null) {
+ DownloadExtras.note("lyrics", uri)
+ return@withContext kept(uri)
+ }
+ runCatching { DownloadExtras.rememberLyrics(uri, json.encodeToString(found)) }
+ found
+ }
+ }
+
+ /** What was written down for this track, if it was ever asked about. */
+ suspend fun kept(uri: String): Lyrics? = withContext(Dispatchers.IO) {
+ val raw = DownloadExtras.lyrics(uri) ?: return@withContext null
+ runCatching { json.decodeFromString<Lyrics>(raw) }.getOrNull()
+ }
+}
diff --git a/app/src/main/java/dev/lelonio/square/data/ApiFactory.kt b/app/src/main/java/dev/lelonio/square/data/ApiFactory.kt
index 8ccb6c2..297af5d 100644
--- a/app/src/main/java/dev/lelonio/square/data/ApiFactory.kt
+++ b/app/src/main/java/dev/lelonio/square/data/ApiFactory.kt
@@ -67,6 +67,17 @@ object ApiFactory {
private class RateLimitInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val response = chain.proceed(chain.request())
+
+ // Spotify's gateway answers 502 and 503 a few times a day for no
+ // reason anybody can act on, and it is over by the time the message
+ // reaches the screen. One immediate retry turns "Errore 502" on an
+ // artist page into a page that simply loaded.
+ if (response.code == 502 || response.code == 503) {
+ android.util.Log.w(TAG, "upstream ${response.code}, retrying once")
+ response.close()
+ return chain.proceed(chain.request())
+ }
+
if (response.code != 429) return response
val retryAfter = response.header("Retry-After")?.toLongOrNull()
diff --git a/app/src/main/java/dev/lelonio/square/data/AppleCatalog.kt b/app/src/main/java/dev/lelonio/square/data/AppleCatalog.kt
new file mode 100644
index 0000000..ecb08e8
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/data/AppleCatalog.kt
@@ -0,0 +1,731 @@
+package dev.lelonio.square.data
+
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
+import kotlinx.coroutines.withContext
+import kotlinx.serialization.encodeToString
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.jsonArray
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.jsonPrimitive
+import okhttp3.OkHttpClient
+import okhttp3.Request
+import java.util.concurrent.TimeUnit
+
+/**
+ * Apple Music's own pictures of an artist.
+ *
+ * Spotify has one square photograph per artist and nothing else. Apple's
+ * catalogue has the two things an artist page in that style is made of: a wide
+ * editorial portrait, and the artist's name drawn in a face chosen for them —
+ * what their client puts across the top of the picture instead of setting the
+ * name in the system font.
+ *
+ * How it is reached: the public web player carries a developer token inside its
+ * own JavaScript, and that token opens the same catalogue endpoint the site
+ * reads. Nothing here is authenticated as a person and nothing is written; this
+ * asks for the artwork of a public catalogue page. It is, all the same, not an
+ * interface Apple publishes, so every part of it is written to fail quietly: no
+ * token, no match, a changed page shape or a refused request all end as "no
+ * pictures", and the artist page draws its own name over Spotify's photo
+ * exactly as it did before this file existed.
+ *
+ * Nothing calls this on the playback path. It is one lookup when an artist page
+ * opens, cached for the session.
+ */
+object AppleCatalog {
+
+ private const val TAG = "AppleCatalog"
+ private const val SITE = "https://beta.music.apple.com"
+ private const val API = "https://amp-api.music.apple.com/v1/catalog"
+
+ private val client by lazy {
+ OkHttpClient.Builder()
+ .connectTimeout(10, TimeUnit.SECONDS)
+ .readTimeout(15, TimeUnit.SECONDS)
+ .build()
+ }
+
+ private val json = Json { ignoreUnknownKeys = true }
+
+ /** The token, and the lock that keeps a burst of pages from fetching five. */
+ private var token: String? = null
+ private val tokenLock = Mutex()
+
+ /**
+ * Artists already looked up, by the name that was asked for.
+ *
+ * Misses are cached too, as nulls: an artist Apple does not have would
+ * otherwise be searched again every time their page is opened, and the
+ * answer would be the same every time.
+ */
+ private val cache = mutableMapOf<String, Any?>()
+
+ /**
+ * And the same answers on disk, so the second visit costs nothing.
+ *
+ * The cost this saves is not the request. It is that the page opens on
+ * Spotify's picture and changes to Apple's a second later, in front of the
+ * reader — every single time, on every cold start. Kept for a month:
+ * artwork does get replaced, and a stale photograph of somebody is worse
+ * than one more search.
+ */
+ private var store: android.content.SharedPreferences? = null
+
+ /** Called once, from the application. Without it this simply never caches. */
+ fun attach(context: android.content.Context) {
+ // Named for the shape of what is stored, not for the catalogue: the
+ // rows hold finished URLs with their sizes baked in, so asking for
+ // bigger pictures means the old rows are answers to a different
+ // question. A new name retires them in one line.
+ store = context.getSharedPreferences(
+ "apple-catalog-v5",
+ android.content.Context.MODE_PRIVATE,
+ )
+ }
+
+ private fun remembered(key: String): String? {
+ val prefs = store ?: return null
+ val row = prefs.getString(key, null) ?: return null
+ val cut = row.indexOf('\n')
+ if (cut < 0) return null
+ val written = row.take(cut).toLongOrNull() ?: return null
+ if (System.currentTimeMillis() - written > CACHE_MS) {
+ prefs.edit().remove(key).apply()
+ return null
+ }
+ return row.substring(cut + 1)
+ }
+
+ /**
+ * Whether the catalogue may be asked at all.
+ *
+ * Offline this object still answers — from the rows written down on the way
+ * past, which is what makes a downloaded record open on its own photograph
+ * in a tunnel — but it never reaches for the network, and a miss is not
+ * remembered as one: the answer offline is "not here yet", not "there is
+ * none", and caching the first would keep the picture away for the rest of
+ * the run.
+ */
+ private fun mayAsk(): Boolean =
+ !dev.lelonio.square.playback.OfflineMode.active.value
+
+ private fun remember(key: String, value: String) {
+ store?.edit()?.putString(key, System.currentTimeMillis().toString() + "\n" + value)?.apply()
+ }
+
+ /**
+ * What one record's page can use.
+ *
+ * The tall picture is the difference between the two headers the reference
+ * shows: a record that has one opens as a photograph, and a record that does
+ * not opens as its sleeve. The sleeve is here too, because Apple's copy of
+ * it is the better scan more often than not.
+ */
+ @kotlinx.serialization.Serializable
+ data class Album(
+ val heroUrl: String?,
+ val coverUrl: String?,
+ /**
+ * The colour Apple tints the page with, as six hex digits.
+ *
+ * Filed with the artwork rather than worked out from it, which is why
+ * it is worth taking: their page for a record is the colour their
+ * editors chose for that record, and a dominant-colour pass over the
+ * same picture lands somewhere near it and often on a skin tone.
+ */
+ val bgColor: String? = null,
+ /** What Apple's editors wrote about it, where they wrote anything. */
+ val notes: String? = null,
+ /**
+ * The cover as a moving picture, where the label made one.
+ *
+ * An HLS playlist of a few seconds that loops. Not every record has
+ * one; the ones that do are what the reference's header plays instead of
+ * showing a still.
+ */
+ val motionUrl: String? = null,
+ )
+
+ /** What one artist's page can use. Either field may be absent on its own. */
+ @kotlinx.serialization.Serializable
+ data class Artist(
+ /** The portrait Apple identifies them by. */
+ val heroUrl: String?,
+ /** The page's own tint, as six hex digits; see Album.bgColor. */
+ val bgColor: String? = null,
+ /** What Apple's editors wrote about them, where they wrote anything. */
+ val bio: String? = null,
+ /** Where they are from, or where the band was formed. */
+ val origin: String? = null,
+ /** Their name, drawn. White on transparent, meant to sit over the photo. */
+ val logoUrl: String?,
+ )
+
+ /**
+ * The pictures for an artist, or null.
+ *
+ * Matched by name, which is the only key the two catalogues share. The match
+ * has to be exact, ignoring case: "Queen" searched loosely returns a dozen
+ * acts with Queen in their name, and a page that shows the wrong person's
+ * face is worse than one that shows no face at all.
+ */
+ suspend fun artist(name: String, storefront: String = storefront()): Artist? {
+ if (name.isBlank()) return null
+ val key = "artist $storefront/${name.lowercase()}"
+ synchronized(cache) { if (cache.containsKey(key)) return cache[key] as Artist? }
+
+ remembered(key)?.let { row ->
+ val kept = runCatching { json.decodeFromString<Artist>(row) }.getOrNull()
+ synchronized(cache) { cache[key] = kept }
+ return kept
+ }
+
+ if (!mayAsk()) return null
+
+ val found = runCatching { lookUpArtist(name, storefront) }
+ .onFailure { android.util.Log.w(TAG, "no artwork for $name: ${it.message}") }
+ .getOrNull()
+
+ found?.let { runCatching { remember(key, json.encodeToString(it)) } }
+ synchronized(cache) { cache[key] = found }
+ return found
+ }
+
+ /**
+ * The full-height picture for a record, where there is one.
+ *
+ * This is the difference the reference's own pages show: most records open
+ * with a tall photograph filling the screen, and the rest — the ones the
+ * editors never made one for — open with the square sleeve. Asking for it is
+ * how a client can tell which of the two a record is.
+ */
+ suspend fun album(
+ name: String,
+ artist: String,
+ storefront: String = storefront(),
+ ): Album? {
+ if (name.isBlank()) return null
+ val key = "album $storefront/${artist.lowercase()}/${name.lowercase()}"
+ synchronized(cache) { if (cache.containsKey(key)) return cache[key] as Album? }
+
+ remembered(key)?.let { row ->
+ val kept = runCatching { json.decodeFromString<Album>(row) }.getOrNull()
+ synchronized(cache) { cache[key] = kept }
+ return kept
+ }
+
+ if (!mayAsk()) return null
+
+ val found = runCatching { lookUpAlbum(name, artist, storefront) }
+ .onFailure { android.util.Log.w(TAG, "no artwork for $name: ${it.message}") }
+ .getOrNull()
+
+ found?.let { runCatching { remember(key, json.encodeToString(it)) } }
+ synchronized(cache) { cache[key] = found }
+ return found
+ }
+
+ /**
+ * One song's own cover, for when its record cannot be found.
+ *
+ * Spotify's largest cover is 640 across, which is soft the moment it fills a
+ * phone. Apple files a song's artwork at three thousand and more, and a song
+ * is easier to match than a record: the title and the artist are exactly
+ * what the queue already knows.
+ */
+ suspend fun song(
+ name: String,
+ artist: String,
+ /**
+ * The record the queue says this song is on.
+ *
+ * A song row in the catalogue carries the artwork of whichever release
+ * it was found on, and a song that also appears on compilations is
+ * found on one of those as often as on its own record — which is how a
+ * Laura Pausini duet ended up wearing the sleeve of a restaurant
+ * playlist called "Pizza Time". Naming the record turns the search
+ * result into a choice rather than the first row.
+ */
+ album: String = "",
+ storefront: String = storefront(),
+ ): String? {
+ if (name.isBlank()) return null
+ val key = "song $storefront/${artist.lowercase()}/${name.lowercase()}/${album.lowercase()}"
+ synchronized(cache) { if (cache.containsKey(key)) return cache[key] as String? }
+
+ remembered(key)?.let { row ->
+ val kept = row.takeIf { it.isNotBlank() }
+ synchronized(cache) { cache[key] = kept }
+ return kept
+ }
+
+ if (!mayAsk()) return null
+
+ val found = runCatching { lookUpSong(name, artist, album, storefront) }
+ .onFailure { android.util.Log.w(TAG, "no artwork for $name: ${it.message}") }
+ .getOrNull()
+
+ found?.let { runCatching { remember(key, it) } }
+ synchronized(cache) { cache[key] = found }
+ return found
+ }
+
+ private suspend fun lookUpSong(
+ name: String,
+ artist: String,
+ album: String,
+ storefront: String,
+ ): String? {
+ // Searched without the decorations. A title as the queue carries it is
+ // often "BUONANOTTE ❈ (con NOYZ NARCOS, FRANCO126 & SIDE BABY)", and
+ // the catalogue files the same song with the guests in a field of its
+ // own — so the full string matches nothing while the song is right
+ // there.
+ val plain = plain(name)
+ val credited = credited(artist)
+ val results = search("${lead(artist)} $plain", "songs", storefront) ?: return null
+
+ val matches = results.mapNotNull { it.jsonObject["attributes"]?.jsonObject }
+ .filter {
+ val filed = it["name"]?.jsonPrimitive?.content.orEmpty()
+ filed.equals(name, ignoreCase = true) ||
+ plain(filed).equals(plain, ignoreCase = true)
+ }
+ .filter { row ->
+ val filed = row["artistName"]?.jsonPrimitive?.content.orEmpty()
+ filed.equals(artist, ignoreCase = true) ||
+ credited.any { filed.contains(it, ignoreCase = true) } ||
+ credited.any { it.contains(filed, ignoreCase = true) }
+ }
+
+ // The row from the record the song is actually on, where the search
+ // returned it. Otherwise the first match, which is what this always
+ // did — and is still right for a song whose record is not in the
+ // catalogue under the name Spotify files it under.
+ val match = matches.firstOrNull { row ->
+ val filed = row["albumName"]?.jsonPrimitive?.content.orEmpty()
+ album.isNotBlank() && sameTitle(filed, album)
+ }
+ // Failing that, a row whose record is not simply this song again: a
+ // song row carries the sleeve of the release it was found on, and the
+ // release named after the song is the single.
+ ?: matches.firstOrNull { row ->
+ val filed = row["albumName"]?.jsonPrimitive?.content.orEmpty()
+ filed.isNotBlank() && !sameTitle(filed, name)
+ }
+ ?: matches.firstOrNull() ?: return null
+
+ return match["artwork"]?.jsonObject?.template()?.let { size(it, COVER_PX, COVER_PX) }
+ }
+
+ /** Every name on a track's artist line, which is one string with commas. */
+ private fun credited(artist: String): List<String> = artist
+ .split(",", "&", "feat.", "Feat.")
+ .map { it.trim() }
+ .filter { it.isNotEmpty() }
+
+ /**
+ * The name to search under: the first one credited.
+ *
+ * The whole line is what the record is *not* filed under. "Laura Pausini,
+ * James Blunt Primavera in anticipo" asks the catalogue for a record by a
+ * duo of that name and comes back with whatever is nearest — a compilation
+ * with both of them on it, as often as not. The lead name alone finds the
+ * record, and the guests are still checked for below.
+ */
+ private fun lead(artist: String): String = credited(artist).firstOrNull() ?: artist
+
+ /**
+ * Whether two titles name the same record, decorations aside.
+ *
+ * Spotify and Apple disagree about editions constantly — "(Deluxe)",
+ * "(Special Edition)", "- Remastered" — and an exact comparison throws away
+ * the right record over a bracket.
+ */
+ private fun sameTitle(a: String, b: String): Boolean =
+ a.equals(b, ignoreCase = true) || plain(a).equals(plain(b), ignoreCase = true)
+
+ private suspend fun lookUpArtist(name: String, storefront: String): Artist? {
+ val results = search(name, "artists", storefront) ?: return null
+ val match = results.firstOrNull {
+ it.jsonObject["attributes"]?.jsonObject?.get("name")?.jsonPrimitive?.content
+ ?.equals(name, ignoreCase = true) == true
+ } ?: return null
+
+ val attributes = match.jsonObject["attributes"]?.jsonObject ?: return null
+ val editorial = attributes["editorialArtwork"]?.jsonObject
+
+ // The identity portrait rather than one of the wide banners: this is a
+ // phone, the header is taller than it is wide, and cropping a 4:1 banner
+ // into it leaves a strip of somebody's forehead.
+ //
+ // Cropped `va`, which is what the catalogue itself recommends for this
+ // picture — the vertical crop, framed on the face. The default `bb`
+ // fits the whole square inside the frame and pads the rest, which on a
+ // header this tall is two bars of flat colour.
+ val hero = attributes["artwork"]?.jsonObject?.template()
+ ?: editorial?.get("subscriptionHero")?.jsonObject?.template()
+
+ val logo = listOf("musicContentColorLogoTrimmed", "brandLogo", "logo")
+ .firstNotNullOfOrNull { editorial?.get(it)?.jsonObject }
+
+ if (hero == null && logo == null) return null
+ return Artist(
+ heroUrl = hero?.let { size(it, HERO_W, HERO_H, crop = "va") },
+ bgColor = attributes["artwork"]?.jsonObject?.get("bgColor")?.jsonPrimitive?.content,
+ bio = attributes["artistBio"]?.jsonPrimitive?.content,
+ origin = attributes["bornOrFormed"]?.jsonPrimitive?.content,
+ // At the picture's own proportions, whatever they are. Every crop
+ // code Apple has either cuts the sides off a name — which is how
+ // "BRUNO MARS" arrives as "UNO MA" — or pads it onto white. Asking
+ // for the shape it already is leaves nothing to crop.
+ logoUrl = logo?.template()?.let { url ->
+ val width = logo["width"]?.jsonPrimitive?.content?.toIntOrNull() ?: LOGO_W
+ val height = logo["height"]?.jsonPrimitive?.content?.toIntOrNull() ?: LOGO_H
+ size(
+ url,
+ LOGO_W,
+ (LOGO_W.toLong() * height / width).toInt().coerceAtLeast(1),
+ format = "png",
+ crop = "sr",
+ )
+ },
+ )
+ }
+
+ private suspend fun lookUpAlbum(name: String, artist: String, storefront: String): Album? {
+ val results = search("${lead(artist)} $name", "albums", storefront) ?: return null
+
+ // The name has to match; the artist only has to be one of the people
+ // credited. A track's artist line is every name on it run together —
+ // "K-Pro, M&n Pro" — while the record is filed under one of them, so an
+ // exact comparison threw away the right album on anything with a guest
+ // on it.
+ val credited = credited(artist)
+
+ val candidates = results.mapNotNull { it.jsonObject["attributes"]?.jsonObject }
+ .filter { sameTitle(it["name"]?.jsonPrimitive?.content.orEmpty(), name) }
+ .filter { row ->
+ val filed = row["artistName"]?.jsonPrimitive?.content.orEmpty()
+ filed.equals(artist, ignoreCase = true) ||
+ credited.any { filed.contains(it, ignoreCase = true) } ||
+ credited.any { it.contains(filed, ignoreCase = true) }
+ }
+
+ // The record, and not the single of the same name.
+ //
+ // A song released on its own before the album lands in the catalogue
+ // twice under one title: the single, whose one track is this song, and
+ // the record it later appeared on. Both match the name and the artist,
+ // and the single is very often the one the search returns first — so
+ // the album page and the player opened on the single's sleeve while the
+ // queue was playing the album's.
+ //
+ // The catalogue says which is which, so this asks: a single, or one
+ // track, is the last resort rather than the first answer.
+ fun single(row: kotlinx.serialization.json.JsonObject): Boolean =
+ row["isSingle"]?.jsonPrimitive?.content?.toBooleanStrictOrNull() == true ||
+ row["trackCount"]?.jsonPrimitive?.content?.toIntOrNull() == 1
+
+ // And within each of those two groups: the same record is in the
+ // catalogue several times — the plain edition, the deluxe, the one with
+ // the videos — and only some of those rows carry the tall picture. They
+ // are the same record to a listener, so the one that has a picture
+ // answers for all of them: without this, whether a page opens as a
+ // photograph depends on which edition Spotify's copy happens to be
+ // named after.
+ // Narrowed before it is ranked: the loose comparison above drops
+ // whatever is in brackets, so "Espresso (Working Late Remixes)" answers
+ // to "Espresso" as readily as the record itself does. This keeps the
+ // rows that are the asked-for name and nothing more — the edition
+ // marker Apple appends, " - Single" or " - EP", is not an addition.
+ // Scored rather than filtered, because the three things wanted here
+ // pull against each other and none of them can be a veto.
+ //
+ // A picture outranks everything: a record with no tall photograph opens
+ // as its sleeve, and an edition of the same record that has one is the
+ // same record to a listener. Then the name exactly as asked, which is
+ // what separates "GUTS" from "GUTS (spilled)" — the loose comparison
+ // above drops whatever is in brackets, so both answer to the same
+ // question. Then not a single, which is what separates a record from
+ // the song that came out ahead of it under the same name.
+ fun exact(row: kotlinx.serialization.json.JsonObject): Boolean =
+ row["name"]?.jsonPrimitive?.content.orEmpty()
+ .substringBefore(" - ")
+ .trim()
+ .equals(name.substringBefore(" - ").trim(), ignoreCase = true)
+
+ val match = candidates.maxByOrNull { row ->
+ (if (row.tall() != null) 4 else 0) +
+ (if (exact(row)) 2 else 0) +
+ (if (single(row)) 0 else 1)
+ }
+ val attributes = match ?: return null
+ val tall = attributes.tall()
+ val cover = attributes["artwork"]?.jsonObject?.template()
+
+ // The tall one first and the square one after it, which is the same
+ // order the still pictures are chosen in: the header is a portrait.
+ val motion = listOf("motionDetailTall", "motionTallVideo3x4", "motionDetailSquare")
+ .firstNotNullOfOrNull {
+ attributes["editorialVideo"]?.jsonObject?.get(it)?.jsonObject
+ }
+ val motionUrl = motion?.get("video")?.jsonPrimitive?.content
+ // A record with a moving cover has a still frame from it filed beside
+ // the video. It is the right picture to hold while the video loads —
+ // and the right one to keep on a page that never plays it.
+ val motionStill = motion?.get("previewFrame")?.jsonObject?.template()
+ val notes = attributes["editorialNotes"]?.jsonObject
+ ?.let { it["standard"] ?: it["short"] }
+ ?.jsonPrimitive?.content
+
+ if (tall == null && cover == null) return null
+ return Album(
+ heroUrl = (tall ?: motionStill)?.let { size(it, DETAIL_W, DETAIL_H) },
+ motionUrl = motionUrl,
+ bgColor = (
+ attributes["editorialArtwork"]?.jsonObject
+ ?.get("staticDetailTall")?.jsonObject
+ ?: attributes["artwork"]?.jsonObject
+ )?.get("bgColor")?.jsonPrimitive?.content,
+ coverUrl = cover?.let { size(it, COVER_PX, COVER_PX) },
+ notes = notes,
+ )
+ }
+
+ /**
+ * The full-height picture a record's page opens with, where it has one.
+ *
+ * Two keys, because the catalogue does not always file both: the detail
+ * picture is the one their own record page opens with, and the hero is what
+ * a wide screen shows — on plenty of records, including some very well known
+ * ones, only the second exists. Reading just the first was why a record
+ * could open as its sleeve while an edition of it opened as a photograph.
+ */
+ private fun kotlinx.serialization.json.JsonObject.tall(): String? =
+ get("editorialArtwork")?.jsonObject?.let { art ->
+ art["staticDetailTall"]?.jsonObject?.template()
+ ?: art["superHeroTall"]?.jsonObject?.template()
+ }
+
+ private suspend fun search(
+ term: String,
+ types: String,
+ storefront: String,
+ ): List<kotlinx.serialization.json.JsonElement>? {
+ val bearer = token() ?: return null
+ val url = "$API/$storefront/search" +
+ "?term=${java.net.URLEncoder.encode(term, "UTF-8")}" +
+ // Enough rows to see past a title's singles, remixes and live
+ // takes to the record itself; ten was not always.
+ "&types=$types&limit=25" +
+ "&extend=editorialArtwork,editorialVideo,editorialNotes,artistBio,bornOrFormed"
+
+ val body = get(url, bearer) ?: return null
+ return json.parseToJsonElement(body)
+ .jsonObject["results"]?.jsonObject
+ ?.get(types)?.jsonObject
+ ?.get("data")?.jsonArray
+ ?.toList()
+ }
+
+ /**
+ * A title with everything but the title taken out.
+ *
+ * Guests in brackets, "- Remastered 2019", the decorative characters some
+ * labels put in a name: none of it is how the other catalogue files the
+ * song, and all of it stops a search from finding it.
+ */
+ private fun plain(title: String): String = title
+ .replace(Regex("\\([^)]*\\)"), " ")
+ .replace(Regex("\\[[^]]*]"), " ")
+ .substringBefore(" - ")
+ .replace(Regex("[^\\p{L}\\p{N}' ]"), " ")
+ .replace(Regex("\\s+"), " ")
+ .trim()
+
+ /** The catalogue to ask, from wherever the phone says it is. */
+ private fun storefront(): String =
+ java.util.Locale.getDefault().country.lowercase().ifBlank { "us" }
+
+ /**
+ * The developer token the web player uses, read out of the player itself.
+ *
+ * Fetched once per run and kept: it is a JWT with months on it, and the only
+ * way to know it has gone stale is a request being refused — which is what
+ * clears it.
+ */
+ private suspend fun token(): String? = tokenLock.withLock {
+ token?.let { return it }
+
+ // The one written down last time, if it has not run out.
+ //
+ // Scraping it is not a cheap call: it is the site's front page and then
+ // the player's whole JavaScript bundle, which is several megabytes, and
+ // it was being paid on the first artwork lookup of every cold start —
+ // in front of the listener, with the cover held back until it finished.
+ // The token these carry is good for weeks; see its own expiry below.
+ keptToken()?.let {
+ token = it
+ return it
+ }
+
+ val page = get(SITE, null) ?: return null
+ // The player's own bundle, whichever hash it carries today.
+ val script = Regex("""/assets/[^"']*index[^"']*\.js""").find(page)?.value ?: return null
+ val bundle = get("$SITE$script", null) ?: return null
+ val jwt = Regex("""eyJ[\w-]+\.[\w-]+\.[\w-]+""").find(bundle)?.value ?: return null
+
+ token = jwt
+ rememberToken(jwt)
+ return jwt
+ }
+
+ /**
+ * The token from a previous run, while it lasts.
+ *
+ * Kept with the moment it expires rather than a time-to-live of our own: the
+ * expiry is in the token, and a guess would either throw away good ones or
+ * hold a dead one and spend a request finding out.
+ */
+ private fun keptToken(): String? {
+ val prefs = store ?: return null
+ val jwt = prefs.getString(KEY_TOKEN, null) ?: return null
+ val expiresAt = prefs.getLong(KEY_TOKEN_UNTIL, 0L)
+ if (System.currentTimeMillis() > expiresAt - TOKEN_MARGIN_MS) {
+ prefs.edit().remove(KEY_TOKEN).remove(KEY_TOKEN_UNTIL).apply()
+ return null
+ }
+ return jwt
+ }
+
+ private fun rememberToken(jwt: String) {
+ val prefs = store ?: return
+ // The middle third of a JWT is its claims, base64url without padding.
+ val expiresAt = runCatching {
+ val claims = jwt.split('.').getOrNull(1) ?: return@runCatching 0L
+ val json = String(
+ android.util.Base64.decode(
+ claims,
+ android.util.Base64.URL_SAFE or android.util.Base64.NO_PADDING,
+ ),
+ )
+ Regex("\"exp\"\\s*:\\s*(\\d+)").find(json)?.groupValues?.get(1)?.toLong()?.times(1000)
+ ?: 0L
+ }.getOrDefault(0L)
+
+ if (expiresAt <= System.currentTimeMillis()) return
+ prefs.edit()
+ .putString(KEY_TOKEN, jwt)
+ .putLong(KEY_TOKEN_UNTIL, expiresAt)
+ .apply()
+ }
+
+ private suspend fun get(url: String, bearer: String?): String? = withContext(Dispatchers.IO) {
+ val request = Request.Builder()
+ .url(url)
+ .apply {
+ if (bearer != null) {
+ header("Authorization", "Bearer $bearer")
+ // The endpoint answers 403 without them: it is the site's
+ // own API and it checks that the caller is the site.
+ header("Origin", "https://music.apple.com")
+ header("Referer", "https://music.apple.com/")
+ }
+ }
+ .build()
+
+ client.newCall(request).execute().use { response ->
+ if (response.code == 401 || response.code == 403) {
+ // Rotated, or refused. Either way the one we hold is no use —
+ // including the one on disk, or the next run would start by
+ // being refused again.
+ token = null
+ store?.edit()?.remove(KEY_TOKEN)?.remove(KEY_TOKEN_UNTIL)?.apply()
+ return@withContext null
+ }
+ if (!response.isSuccessful) return@withContext null
+ response.body?.string()
+ }
+ }
+
+ /** Apple gives a URL with the size still to be filled in. */
+ private fun kotlinx.serialization.json.JsonObject.template(): String? =
+ get("url")?.jsonPrimitive?.content
+
+ private fun size(
+ template: String,
+ width: Int,
+ height: Int,
+ /**
+ * WebP, which is what the catalogue's own client asks for.
+ *
+ * Not a small saving: measured on a tall editorial picture at the size
+ * this app uses, 174KB as a JPEG against 30KB as WebP — the same
+ * pixels, a sixth of the bytes — and on a square sleeve 950KB against
+ * 272KB. These are kept beside every downloaded song, so it is the
+ * difference between a library of artwork and a library of audio with
+ * artwork attached. Dropping the resolution instead would have saved a
+ * third and cost real sharpness.
+ */
+ format: String = "webp",
+ crop: String = "bb",
+ ): String {
+ val filled = template
+ .replace("{w}", width.toString())
+ .replace("{h}", height.toString())
+ .replace("{f}", format)
+ .replace("{c}", crop)
+
+ // Most templates carry the crop code and the file type baked into the
+ // last segment rather than as placeholders: `.../{w}x{h}bb.jpg`. The
+ // logo has to come back as a PNG cropped `sr`, or the transparency it is
+ // made of is flattened onto white and the artist name arrives as a white
+ // slab — so the segment is rewritten rather than filled in.
+ return filled.replace(
+ Regex("/\\d+x\\d+[a-z]{2}\\.(jpg|png|webp)$"),
+ "/" + width + "x" + height + crop + "." + format,
+ )
+ }
+
+ /** How long a remembered answer is still the right one. */
+ private const val CACHE_MS = 30L * 24 * 60 * 60 * 1000
+
+ private const val KEY_TOKEN = "token"
+ private const val KEY_TOKEN_UNTIL = "token-until"
+
+ /** Retired a day early, so a lookup never races the expiry. */
+ private const val TOKEN_MARGIN_MS = 24L * 60 * 60 * 1000
+
+ /**
+ * Sized for the screen it lands on, not for the header it was written for.
+ *
+ * These pictures are cropped to fill — a phone is far taller and narrower
+ * than the 3:4 the catalogue files them in — so the width that reaches the
+ * screen is only a fraction of what is asked for, and the rest is scaled up.
+ * At 900 across, a picture filling a 1080-wide screen was already being
+ * enlarged before the crop took its share, which is what made it grainy.
+ */
+ private const val HERO_W = 1400
+ private const val HERO_H = 1867
+
+ /** The name is wide and short, and has to stay legible at full width. */
+ private const val LOGO_W = 900
+ private const val LOGO_H = 276
+
+ /** A sleeve, large enough for the header and for the page's colour. */
+ private const val COVER_PX = 1600
+
+ /**
+ * A record's own full-height picture, at the shape Apple files it in.
+ *
+ * Large, for the reason above and one more: the player draws this over the
+ * whole screen, so the crop throws away most of its width. Not the source's
+ * full 2048x2732 — the decoder is asked for the size the screen needs, and
+ * a file twice as large only costs the download.
+ */
+ private const val DETAIL_W = 1600
+ private const val DETAIL_H = 2134
+}
diff --git a/app/src/main/java/dev/lelonio/square/data/Catalog.kt b/app/src/main/java/dev/lelonio/square/data/Catalog.kt
index e9f2048..23bbad4 100644
--- a/app/src/main/java/dev/lelonio/square/data/Catalog.kt
+++ b/app/src/main/java/dev/lelonio/square/data/Catalog.kt
@@ -33,6 +33,22 @@ data class CatalogTrack(
*/
val artists: List<CatalogArtist> = emptyList(),
val album: String = "",
+ /**
+ * The record's own address, where the source gives one.
+ *
+ * What makes the album under a title in the player a way to reach it rather
+ * than a caption. Null through the access point, which names the record but
+ * does not address it; the player falls back to a lookup there.
+ */
+ val albumUri: String? = null,
+ /**
+ * The year the record came out, or empty where the source does not say.
+ *
+ * Only the four digits: an artist page names a song by the record it is on
+ * and when that record happened, and the month and day of a release are not
+ * how anybody places an album.
+ */
+ val year: String = "",
val durationMs: Long = 0,
val explicit: Boolean = false,
val artworkUrl: String? = null,
@@ -52,6 +68,7 @@ data class CatalogTrack(
* @param startTimeMs when the line begins, or null for unsynced lyrics — the
* distinction decides whether the view can highlight along with playback.
*/
+@Serializable
data class LyricLine(
val startTimeMs: Long?,
val text: String,
@@ -75,8 +92,10 @@ data class LyricLine(
)
/** One word, and the moment it belongs to. */
+@Serializable
data class LyricWord(val startMs: Long, val endMs: Long, val text: String)
+@Serializable
data class Lyrics(val lines: List<LyricLine>, val synced: Boolean)
/**
@@ -122,6 +141,8 @@ fun TrackDto.toCatalogTrack(addedAt: String? = null): CatalogTrack = CatalogTrac
artistUri = artists.firstOrNull()?.uri,
artists = artists.map { CatalogArtist(it.name, it.uri) },
album = album?.name.orEmpty(),
+ albumUri = album?.uri,
+ year = album?.releaseDate?.take(4).orEmpty(),
durationMs = durationMs,
explicit = explicit,
artworkUrl = album?.images?.firstOrNull()?.url,
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 0ea1806..b1dff07 100644
--- a/app/src/main/java/dev/lelonio/square/data/PreferencesStore.kt
+++ b/app/src/main/java/dev/lelonio/square/data/PreferencesStore.kt
@@ -67,6 +67,23 @@ class PreferencesStore(context: Context) {
prefs.edit().putBoolean(KEY_ONBOARDED, value).apply()
}
+ private val _canvasEnabled = MutableStateFlow(prefs.getBoolean(KEY_CANVAS, true))
+
+ /**
+ * Whether a track's looping clip is fetched and played at all.
+ *
+ * On by default: it is the thing the player is built around. Off is for the
+ * listener who wants the artwork and nothing moving — and it is not only a
+ * drawing decision, since with this off no clip is asked for and the data
+ * is not spent either.
+ */
+ val canvasEnabled: StateFlow<Boolean> = _canvasEnabled.asStateFlow()
+
+ fun setCanvasEnabled(value: Boolean) {
+ _canvasEnabled.value = value
+ prefs.edit().putBoolean(KEY_CANVAS, value).apply()
+ }
+
/**
* Whether the player was open when the app was last left.
*
@@ -151,6 +168,7 @@ class PreferencesStore(context: Context) {
const val KEY_TRACK_DESC = "track_sort_descending"
const val KEY_DEVICE_ID = "device_id"
const val KEY_ONBOARDED = "onboarded"
+ const val KEY_CANVAS = "canvas_enabled"
const val KEY_PLAYER_OPEN = "player_open"
const val KEY_BACKEND = "backend"
const val KEY_PROFILE_NAME = "profile_name"
diff --git a/app/src/main/java/dev/lelonio/square/data/SpotifyApi.kt b/app/src/main/java/dev/lelonio/square/data/SpotifyApi.kt
index 16cfee5..b3e9634 100644
--- a/app/src/main/java/dev/lelonio/square/data/SpotifyApi.kt
+++ b/app/src/main/java/dev/lelonio/square/data/SpotifyApi.kt
@@ -164,6 +164,16 @@ interface SpotifyApi {
@GET("v1/albums/{id}")
suspend fun album(@Path("id") albumId: String): AlbumDto
+ /**
+ * One track, for the record it is on.
+ *
+ * The access point names a track's album but does not always address it —
+ * and a queue resolved before the app started keeping that address has none
+ * at all. This is the way back to it from the track alone.
+ */
+ @GET("v1/tracks/{id}")
+ suspend fun track(@Path("id") trackId: String): TrackDto
+
@GET("v1/playlists/{id}")
suspend fun playlist(
@Path("id") playlistId: String,
diff --git a/app/src/main/java/dev/lelonio/square/download/DownloadExtras.kt b/app/src/main/java/dev/lelonio/square/download/DownloadExtras.kt
index 7261bef..c304251 100644
--- a/app/src/main/java/dev/lelonio/square/download/DownloadExtras.kt
+++ b/app/src/main/java/dev/lelonio/square/download/DownloadExtras.kt
@@ -16,10 +16,11 @@ import java.net.URL
*
* ### Where it plugs in
*
- * Inside [dev.lelonio.square.data.Catalog], which is the one funnel every one of
- * these already goes through. A successful answer is written down on the way
- * past; a failed one is looked up here. So nothing else in the app has to know
- * this exists, and no screen grew an offline branch of its own.
+ * Inside the one funnel each of these already goes through — the lyrics chain
+ * in [dev.lelonio.square.backend.lyrics.SpotifyLyrics], the download queue for
+ * the pictures and the Canvas. A successful answer is written down on the way
+ * past; offline the same call reads it back, so no screen grew an offline
+ * branch of its own.
*
* ### What is kept, and what is not
*
@@ -36,6 +37,20 @@ import java.net.URL
*/
object DownloadExtras {
+ /**
+ * Where the other catalogue's answers are filed, and how they are retired.
+ *
+ * The name carries a number because the answers are only as good as the
+ * matching that produced them: a song matched against the wrong release
+ * keeps wearing that release's sleeve for as long as the file is here, and
+ * there is nothing in the file itself to say so. Bumping this asks every
+ * downloaded song again with the matching as it stands now, and the old
+ * directory is swept below. Bumped again when the pictures changed format:
+ * the answers name jpg files that are still on the phone, so nothing would
+ * have gone looking for the smaller ones.
+ */
+ private const val ART = "apple4"
+
private var root: File? = null
/** Whether a track is downloaded, and therefore worth keeping extras for. */
@@ -45,6 +60,12 @@ object DownloadExtras {
root = File(downloadsRoot, "extras")
kept = isKept
forgetArtAnswers()
+ // Answers filed by a matching this build no longer trusts; see ART.
+ root?.let { here ->
+ here.listFiles()
+ ?.filter { it.isDirectory && it.name.startsWith("apple") && it.name != ART }
+ ?.forEach { runCatching { it.deleteRecursively() } }
+ }
}
// ------------------------------------------------------------ the answers
@@ -57,6 +78,64 @@ object DownloadExtras {
fun canvas(trackUri: String): String? = recall("canvas", trackUri)
+ /**
+ * The Canvas as it can actually be played offline: the stored answer with
+ * its url swapped for the copy on this phone.
+ *
+ * The answer names a CDN url, and offline that url is nothing. The video
+ * beside it is the same clip, so this is the answer the player wanted.
+ * Null when either half is missing — a Canvas that was noted but never
+ * fetched is not one that can be shown.
+ */
+ fun localCanvas(trackUri: String): dev.lelonio.square.data.CanvasClip? {
+ val raw = canvas(trackUri) ?: return null
+ val answer = runCatching { JSONObject(raw) }.getOrNull() ?: return null
+ val url = answer.optString("url").takeIf { it.isNotBlank() } ?: return null
+ val video = answer.optBoolean("isVideo", true)
+ val file = fileOf(url, if (video) "video" else "art") ?: return null
+ return dev.lelonio.square.data.CanvasClip(
+ url = android.net.Uri.fromFile(file).toString(),
+ isVideo = video,
+ )
+ }
+
+ /**
+ * The other catalogue's pictures of the record a downloaded song is on.
+ *
+ * Kept per track rather than per record because a track is what the index
+ * knows: the download store holds songs, and the record they belong to is a
+ * name on each of them. Both urls may be absent — the answer is filed all
+ * the same, and its presence is what says this song has been asked about.
+ */
+ fun rememberArt(trackUri: String, heroUrl: String?, coverUrl: String?) {
+ val answer = JSONObject()
+ .put("hero", heroUrl.orEmpty())
+ .put("cover", coverUrl.orEmpty())
+ remember(ART, trackUri, answer.toString())
+ }
+
+ /** The tall picture and the sleeve kept for a track, either of them null. */
+ fun art(trackUri: String): Pair<String?, String?>? {
+ val raw = recall(ART, trackUri) ?: return null
+ val answer = runCatching { JSONObject(raw) }.getOrNull() ?: return null
+ return answer.optString("hero").takeIf { it.isNotBlank() } to
+ answer.optString("cover").takeIf { it.isNotBlank() }
+ }
+
+ /**
+ * Files that this song has been asked about, and had nothing.
+ *
+ * Most of the catalogue has no lyrics and no Canvas, and without a note of
+ * having asked, every one of those songs would be asked about again on
+ * every run of the queue — a library's worth of requests, for ever, to
+ * learn the same nothing. The note is the empty file itself: [recall] reads
+ * a blank one as no answer, so nothing else has to know it is there.
+ */
+ fun note(kind: String, uri: String) = remember(kind, uri, "")
+
+ /** Whether this song has been asked about at all, answer or not. */
+ fun asked(kind: String, uri: String): Boolean = fileFor(kind, uri)?.exists() == true
+
/**
* Artist descriptions are kept for anyone with a downloaded track, so the
* page behind a song is not empty offline. Not gated on [isKept]: the URI
@@ -78,7 +157,9 @@ object DownloadExtras {
private fun recall(kind: String, uri: String): String? {
val file = fileFor(kind, uri) ?: return null
- return runCatching { file.takeIf(File::exists)?.readText() }.getOrNull()
+ return runCatching { file.takeIf(File::exists)?.readText() }
+ .getOrNull()
+ ?.takeIf { it.isNotBlank() }
}
// -------------------------------------------------------------- the files
@@ -186,7 +267,7 @@ object DownloadExtras {
/** Drops everything kept for a track that is no longer downloaded. */
fun forget(trackUri: String) {
- listOf("lyrics", "canvas").forEach { kind ->
+ listOf("lyrics", "canvas", ART).forEach { kind ->
fileFor(kind, trackUri)?.let { runCatching { it.delete() } }
}
}
@@ -224,8 +305,18 @@ object DownloadExtras {
val keepLyrics = trackUris.mapNotNullTo(mutableSetOf()) { fileFor("lyrics", it)?.name }
val keepCanvas = trackUris.mapNotNullTo(mutableSetOf()) { fileFor("canvas", it)?.name }
+ val keepApple = trackUris.mapNotNullTo(mutableSetOf()) { fileFor(ART, it)?.name }
val keepArt = coverUrls.mapNotNullTo(mutableSetOf()) { fileFor("art", it)?.name }
+ // The tall pictures are named by the answers that point at them, the
+ // same way the Canvas videos are: read while those answers are still
+ // here to be read.
+ trackUris.forEach { uri ->
+ art(uri)?.toList()?.filterNotNull()?.forEach { url ->
+ fileFor("art", url)?.let { keepArt += it.name }
+ }
+ }
+
// Read before the Canvas answers are pruned: a video is named after the
// URL inside the answer that points at it, so the answers are the only
// way to know which videos are still wanted.
@@ -239,6 +330,7 @@ object DownloadExtras {
forgetArtAnswers()
prune("lyrics", keepLyrics)
prune("canvas", keepCanvas)
+ prune(ART, keepApple)
prune("art", keepArt)
prune("video", keepVideo)
}
diff --git a/app/src/main/java/dev/lelonio/square/download/DownloadQueue.kt b/app/src/main/java/dev/lelonio/square/download/DownloadQueue.kt
index b30a51b..52fcca7 100644
--- a/app/src/main/java/dev/lelonio/square/download/DownloadQueue.kt
+++ b/app/src/main/java/dev/lelonio/square/download/DownloadQueue.kt
@@ -56,6 +56,15 @@ class DownloadQueue(
val total: Int = 0,
/** Why nothing is happening, when nothing is happening. */
val waiting: Waiting? = null,
+ /**
+ * Whether what is left is the extras rather than the music.
+ *
+ * The counts above are about audio, and during a catch-up pass there is
+ * none owed — so the notification read "0 of 0", which is a progress
+ * bar about nothing. What is happening then is worth saying in words
+ * instead.
+ */
+ val extras: Boolean = false,
)
enum class Waiting { NETWORK, WIFI, ENGINE }
@@ -165,8 +174,11 @@ class DownloadQueue(
// Covers before everything else, including before the rest of
// the extras: they are the one thing whose absence is visible
// the moment it happens.
- if (pending.isEmpty() && backfillCovers()) continue
- if (pending.isEmpty() && backfillExtras()) continue
+ if (pending.isEmpty()) {
+ _status.value = Status(running = true, extras = true)
+ if (backfillCovers()) continue
+ if (backfillExtras()) continue
+ }
if (pending.isEmpty()) {
// Nothing to do now, but something may be waiting out a
// failure. Sleeping until then rather than spinning is the
@@ -222,10 +234,37 @@ class DownloadQueue(
*
* @return true when it did something, so the caller comes back for more.
*/
+ /**
+ * The covers of the pages themselves, which the songs' own do not include.
+ *
+ * A playlist downloaded before this existed has its songs and their
+ * sleeves, and a blank tile where its own picture should be. Fetched here
+ * rather than only when a page is downloaded, so a library built earlier
+ * fills in without anything being downloaded again.
+ */
+ private suspend fun backfillOwnerCovers(): Boolean {
+ val missing = store.owners.value.keys.asSequence()
+ .filterNot(coversTried::contains)
+ .mapNotNull { uri -> store.labelOf(uri)?.artworkUrl?.let { uri to it } }
+ .filter { (_, url) -> DownloadExtras.fileOf(url, "art") == null }
+ .take(COVER_BATCH)
+ .toList()
+ if (missing.isEmpty()) return false
+
+ for ((uri, url) in missing) {
+ coversTried += uri
+ DownloadExtras.keep(url, "art")
+ delay(COVER_GAP_MS)
+ }
+ return true
+ }
+
private suspend fun backfillCovers(): Boolean {
+ if (backfillOwnerCovers()) return true
+
val missing = store.files.value.keys.asSequence()
.filterNot(coversTried::contains)
- .filter { needsExtras(it) }
+ .filter { needsCover(it) }
.take(COVER_BATCH)
.toList()
if (missing.isEmpty()) return false
@@ -273,19 +312,66 @@ class DownloadQueue(
for (uri in missing) {
extrasTried += uri
- val sidecar = runCatching { NativeBridge.downloadState(uri) }.getOrNull() ?: continue
+ // No sidecar is not a reason to skip: it carries the cover url the
+ // engine recorded, and everything else here — the words, the tall
+ // picture — is asked for by name from the index instead.
+ val sidecar = runCatching { NativeBridge.downloadState(uri) }.getOrNull() ?: "{}"
keepExtras(uri, sidecar)
delay(TRACK_GAP_MS)
}
return true
}
- /** Whether the cover of a downloaded track is missing from the phone. */
- private fun needsExtras(trackUri: String): Boolean {
+ /**
+ * Whether any downloaded song is still short of something.
+ *
+ * Asked from outside, because the queue only runs while there is audio to
+ * fetch: a library that is fully downloaded never starts it, and the songs
+ * fetched by a build that kept none of this would have waited for the next
+ * playlist to be added. Reads the disk, so it belongs off the main thread.
+ */
+ fun anythingMissing(): Boolean = store.files.value.keys.any(::needsExtras)
+
+ /** Whether the sleeve of a downloaded track is missing from the phone. */
+ private fun needsCover(trackUri: String): Boolean {
val cover = store.trackOf(trackUri)?.artworkUrl ?: return false
return DownloadExtras.fileOf(cover, "art") == null
}
+ /**
+ * Whether anything a downloaded song is meant to carry is still missing.
+ *
+ * A download is the sleeve, the tall picture, the words and the Canvas as
+ * much as it is the audio: offline those are the difference between the app
+ * the listener uses and a list of file names. Each is checked on its own —
+ * a song can perfectly well have its cover and no lyrics — and each is
+ * checked as "has it been asked about", not "is there one": most of the
+ * catalogue has no Canvas and no words, and a check for the answer itself
+ * would ask about those songs for ever. See DownloadExtras.note.
+ */
+ private fun needsExtras(trackUri: String): Boolean =
+ needsCover(trackUri) ||
+ !DownloadExtras.asked("lyrics", trackUri) ||
+ !DownloadExtras.asked("canvas", trackUri) ||
+ needsArt(trackUri) ||
+ needsClip(trackUri)
+
+ /** The tall picture: never asked for, or asked for and never fetched. */
+ private fun needsArt(trackUri: String): Boolean {
+ val kept = DownloadExtras.art(trackUri) ?: return true
+ return listOfNotNull(kept.first, kept.second)
+ .any { DownloadExtras.fileOf(it, "art") == null }
+ }
+
+ /** The Canvas answer is here, but the video it names is not. */
+ private fun needsClip(trackUri: String): Boolean {
+ val raw = DownloadExtras.canvas(trackUri) ?: return false
+ val answer = runCatching { JSONObject(raw) }.getOrNull() ?: return false
+ val url = answer.optString("url").takeIf { it.isNotBlank() } ?: return false
+ val kind = if (answer.optBoolean("isVideo", true)) "video" else "art"
+ return DownloadExtras.fileOf(url, kind) == null
+ }
+
private enum class Outcome { DONE, FAILED, NOT_NOW }
private suspend fun attempt(trackUri: String): Outcome {
@@ -318,16 +404,17 @@ class DownloadQueue(
}
/**
- * The words, the Canvas, the cover and the artist behind the song.
+ * Everything a downloaded song carries besides the song: the sleeve, the
+ * tall picture, the words and the Canvas.
*
* Everything here fails quietly. A track with no lyrics is the ordinary
* case, a Canvas that will not fetch is a still cover, and neither is worth
* failing a download that has already succeeded — the music is on the
* phone, which is what was asked for.
*
- * Calling the catalogue is the whole of the caching: `Catalog` writes every
- * answer down on the way past for a track that is downloaded, which this
- * one now is. Only the two binaries have to be fetched by name.
+ * Each half is skipped when it has already been asked about, so this is
+ * also what the backfill runs: a song downloaded by a build that had none
+ * of this ends up with all of it, and a song that has it is left alone.
*/
private suspend fun keepExtras(trackUri: String, sidecar: String) {
runCatching {
@@ -340,24 +427,95 @@ class DownloadQueue(
// The size the engine recorded is the large one, which is what the
// player screen wants. The row thumbnail finds it too: covers are
// keyed on the picture rather than the size. See DownloadExtras.
- runCatching { JSONObject(sidecar).optString("coverUrl") }
+ val cover = runCatching { JSONObject(sidecar).optString("coverUrl") }
.getOrNull()
?.takeIf { it.isNotBlank() }
- ?.let { DownloadExtras.keep(it, "art") }
+ ?: store.trackOf(trackUri)?.artworkUrl
+ // The sidecar's cover comes from the engine's own metadata, which
+ // does not always carry one; the catalogue's does. Without either,
+ // a downloaded song plays offline with a drawn tile where its
+ // sleeve should be.
+ val kept = cover?.let { DownloadExtras.keep(it, "art") }
+ if (kept == null) {
+ android.util.Log.i("SquareDownloads", "no cover kept for $trackUri")
+ }
- // Asking is the whole of the caching: the catalogue writes every
- // answer down on the way past, so a track that is downloaded has
- // its words on the phone too.
- dev.lelonio.square.data.Catalog.lyrics(trackUri)
+ val track = store.trackOf(trackUri)
+
+ // The words. Asking is the whole of the keeping: the chain the
+ // player reads writes every answer down for a track that is
+ // downloaded, and files a note when there are none. See
+ // SpotifyLyrics.
+ if (!DownloadExtras.asked("lyrics", trackUri)) {
+ dev.lelonio.square.backend.lyrics.SpotifyLyrics.lyrics(
+ uri = trackUri,
+ title = track?.name.orEmpty(),
+ artist = track?.artist.orEmpty(),
+ durationMs = track?.durationMs ?: 0L,
+ )
+ }
- dev.lelonio.square.data.Catalog.canvas(trackUri)?.let { clip ->
- DownloadExtras.keep(clip.url, if (clip.isVideo) "video" else "art")
+ // The Canvas: the answer as well as the video, because offline the
+ // answer names a url that is nowhere and the player has no other
+ // way to learn there is a clip at all.
+ if (!DownloadExtras.asked("canvas", trackUri) || needsClip(trackUri)) {
+ val clip = dev.lelonio.square.data.Catalog.canvas(trackUri)
+ if (clip == null) {
+ DownloadExtras.note("canvas", trackUri)
+ } else {
+ DownloadExtras.rememberCanvas(
+ trackUri,
+ JSONObject()
+ .put("url", clip.url)
+ .put("isVideo", clip.isVideo)
+ .toString(),
+ )
+ DownloadExtras.keep(clip.url, if (clip.isVideo) "video" else "art")
+ }
}
+
+ // And the tall picture, which is what the player and the record's
+ // own page are built around now. Spotify has no such thing, so this
+ // is the other catalogue's — asked for here rather than when the
+ // page opens, because offline is exactly when it cannot be asked.
+ if (needsArt(trackUri)) keepArt(trackUri, track)
}.onFailure {
android.util.Log.i("SquareDownloads", "extras for $trackUri: $it")
}
}
+ /**
+ * The record's tall photograph and Apple's own scan of its sleeve.
+ *
+ * Matched on the record and its artist, and on the song itself when the
+ * record cannot be found — which is the same pair of lookups the player
+ * makes, so what lands here is what would have been shown online. Both
+ * urls are filed against the track even when only one arrives, and the
+ * answer is filed even when neither does: it is what stops the queue from
+ * asking about this song again on its next turn.
+ *
+ * The moving cover is deliberately not fetched. It is an HLS playlist of
+ * separate segments rather than a file, so there is nothing here that could
+ * keep it, and it is the one extra whose absence costs a still picture
+ * instead of a blank one.
+ */
+ private suspend fun keepArt(trackUri: String, track: dev.lelonio.square.data.CatalogTrack?) {
+ val artist = track?.artist.orEmpty()
+ if (artist.isBlank()) return
+
+ val named = track?.album.orEmpty()
+ val album = named.takeIf { it.isNotBlank() }
+ ?.let { dev.lelonio.square.data.AppleCatalog.album(it, artist) }
+ val cover = album?.coverUrl
+ ?: dev.lelonio.square.data.AppleCatalog.song(track?.name.orEmpty(), artist, named)
+
+ listOfNotNull(album?.heroUrl, cover).forEach {
+ DownloadExtras.keep(it, "art")
+ delay(COVER_GAP_MS)
+ }
+ DownloadExtras.rememberArt(trackUri, album?.heroUrl, cover)
+ }
+
/**
* Whether a failure was about the app's own footing rather than the track.
*
diff --git a/app/src/main/java/dev/lelonio/square/download/DownloadService.kt b/app/src/main/java/dev/lelonio/square/download/DownloadService.kt
index a050fc1..06e5bec 100644
--- a/app/src/main/java/dev/lelonio/square/download/DownloadService.kt
+++ b/app/src/main/java/dev/lelonio/square/download/DownloadService.kt
@@ -125,11 +125,16 @@ class DownloadService : android.app.Service() {
}
private fun build(status: DownloadQueue.Status): Notification {
- val text = when (status.waiting) {
- DownloadQueue.Waiting.WIFI -> getString(R.string.download_waiting_wifi)
- DownloadQueue.Waiting.NETWORK -> getString(R.string.download_waiting_network)
- DownloadQueue.Waiting.ENGINE -> getString(R.string.download_waiting_engine)
- null -> getString(R.string.download_progress_count, status.done, status.total)
+ val text = when {
+ status.waiting == DownloadQueue.Waiting.WIFI ->
+ getString(R.string.download_waiting_wifi)
+ status.waiting == DownloadQueue.Waiting.NETWORK ->
+ getString(R.string.download_waiting_network)
+ status.waiting == DownloadQueue.Waiting.ENGINE ->
+ getString(R.string.download_waiting_engine)
+ // The music is all here; what is left is what goes beside it.
+ status.extras -> getString(R.string.download_extras)
+ else -> getString(R.string.download_progress_count, status.done, status.total)
}
val stop = PendingIntent.getService(
@@ -148,7 +153,7 @@ class DownloadService : android.app.Service() {
.setProgress(
status.total.coerceAtLeast(1),
status.done,
- status.waiting != null || status.total == 0,
+ status.waiting != null || status.extras || status.total == 0,
)
.setOngoing(true)
.setSilent(true)
diff --git a/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt b/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt
index 9201e8c..9baa101 100644
--- a/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt
+++ b/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt
@@ -10,6 +10,10 @@ import androidx.media3.common.util.UnstableApi
import com.google.common.util.concurrent.Futures
import com.google.common.util.concurrent.ListenableFuture
import dev.lelonio.square.nativecore.NativeBridge
+import kotlinx.coroutines.cancel
+import kotlinx.coroutines.flow.distinctUntilChanged
+import kotlinx.coroutines.flow.drop
+import kotlinx.coroutines.launch
import dev.lelonio.square.nativecore.NativeEvents
/**
@@ -436,6 +440,54 @@ class LibrespotPlayer(
/** Set while a reconnection is in flight, so a burst of taps starts one. */
private var reconnecting = false
+ /** How long a track dissolves into the next; the listener's own setting. */
+ private val crossfade = dev.lelonio.square.data.CrossfadeStore(context)
+
+ /** Watches the one thing outside this class that changes what it must do. */
+ private val watch = kotlinx.coroutines.CoroutineScope(
+ kotlinx.coroutines.SupervisorJob() + kotlinx.coroutines.Dispatchers.Default,
+ )
+
+ init {
+ // Coming back online, the engine has to be given this queue again.
+ //
+ // Offline the tracks are loaded one at a time, straight into the
+ // player: the Connect device is not there to be told what the queue is.
+ // When the network returns that device comes back knowing nothing, and
+ // the song that was playing ran to its end with nobody to advance it —
+ // so the music stopped and stayed stopped, on a queue of songs that
+ // were all sitting on the phone.
+ watch.launch {
+ dev.lelonio.square.playback.OfflineMode.active
+ .drop(1)
+ .distinctUntilChanged()
+ .collect { offline ->
+ if (offline) return@collect
+ handler.post {
+ if (released || queue.items.isEmpty()) return@post
+ android.util.Log.i(
+ "SquarePlayer",
+ "back online: handing the queue over at ${positionMs}ms",
+ )
+ // From where it is, playing if it was: this is a
+ // handover, not a restart, and the listener should hear
+ // the same second of the same song either side of it.
+ pushQueue(startPlaying = playWhenReady, positionMs = positionMs.toInt())
+ }
+ }
+ }
+ }
+
+ /**
+ * The track this side has already moved on from, by uri.
+ *
+ * Offline nothing else advances the queue — there is no Connect device to
+ * own it — so this side does, and it must do it once. Kept as the uri
+ * rather than a flag so a track that comes round again in a loop is a
+ * different question each time.
+ */
+ private var advancedFrom: String? = null
+
/**
* Runs `then` on the looper with a live Connect device, rebuilding one first
* if the engine has lost its.
@@ -1158,6 +1210,7 @@ class LibrespotPlayer(
override fun handleRelease(): ListenableFuture<*> {
released = true
+ watch.cancel()
handler.removeCallbacks(settleSkip)
focus.release()
engine("shutdown") { NativeBridge.shutdown() }
@@ -1191,6 +1244,39 @@ class LibrespotPlayer(
return true
}
+ /**
+ * Moves to the next track, offline, where nothing else will.
+ *
+ * With a connection the Connect device owns the queue: it loads the next
+ * track while the current one is still sounding, and that overlap is what
+ * the crossfade is made of. Offline there is no device, so the app has to
+ * be the one that looks ahead — otherwise a track ends, the player stops,
+ * and the next one is loaded into silence. That is why offline had no
+ * dissolve at all, and why the queue stopped at the end of every song
+ * unless somebody pressed skip.
+ *
+ * @param early true when this is the run-up to a crossfade rather than the
+ * end of the track, which is the only difference between a dissolve and a
+ * plain advance.
+ */
+ private fun advanceOffline(early: Boolean) {
+ val from = queue.currentIndex
+ val current = queue.items.getOrNull(from) ?: return
+ if (advancedFrom == current.uri) return
+ val next = from + 1
+ // The end of the queue is the end. Repeat is the engine's own setting
+ // and it is not reachable from here; a queue that restarted itself
+ // offline would be doing something the listener did not ask for.
+ if (next > queue.items.lastIndex) return
+
+ advancedFrom = current.uri
+ android.util.Log.i(
+ "SquarePlayer",
+ "offline: ${if (early) "dissolving into" else "advancing to"} track $next",
+ )
+ requestSkipTo(next, 0L)
+ }
+
private fun applyEvent(type: String, uri: String, eventPositionMs: Long) {
if (released) return
@@ -1275,6 +1361,9 @@ class LibrespotPlayer(
handler.removeCallbacks(stallWatch)
}
"playing" -> {
+ // A new track to watch, and one this side has not moved on
+ // from yet.
+ if (uri != advancedFrom) advancedFrom = null
playbackState = Player.STATE_READY
playWhenReady = true
if (uri.isNotEmpty()) bandwidth.playing(uri)
@@ -1303,6 +1392,20 @@ class LibrespotPlayer(
// longer the one on screen.
if (skipPending || skipInFlight) return
positionMs = eventPositionMs
+
+ // Offline, the run-up to the next track is this side's job.
+ //
+ // Started exactly one crossfade before the end, so the two
+ // tracks overlap by the length the listener asked for. With the
+ // setting at zero there is nothing to run up to, and the track
+ // is left to end on its own.
+ if (dev.lelonio.square.playback.OfflineMode.active.value) {
+ val length = queue.items.getOrNull(queue.currentIndex)?.durationMs ?: 0L
+ val fade = crossfade.durationMs().toLong()
+ if (fade > 0 && length > 0 && length - eventPositionMs in 1..fade) {
+ advanceOffline(early = true)
+ }
+ }
}
"stopped" -> {
playbackState = Player.STATE_IDLE
@@ -1337,7 +1440,23 @@ class LibrespotPlayer(
}
"end_of_track" -> {
- takeOverForQueued()
+ if (takeOverForQueued()) return
+ // Offline the engine has no queue to advance, so a track that
+ // ran to its end without a crossfade — because the setting is
+ // off, or because it was shorter than one — stops here unless
+ // this side moves on.
+ //
+ // Except when this is the end of the track already being
+ // dissolved out of. That event belongs to the song being left,
+ // and it arrives milliseconds after the crossfade has started —
+ // by which point the queue has moved on, so advancing again
+ // stepped over the track that was just beginning. One song in
+ // two was skipped without ever being heard, which is what "it
+ // sometimes jumps straight to the next one" was.
+ if (uri == advancedFrom) return
+ if (dev.lelonio.square.playback.OfflineMode.active.value) {
+ advanceOffline(early = false)
+ }
return
}
@@ -1381,6 +1500,7 @@ class LibrespotPlayer(
MediaMetadata.Builder()
.setTitle(track.title)
.setArtist(track.artist)
+ .setAlbumTitle(track.album.takeIf { it.isNotEmpty() })
.setArtworkUri(track.artworkUri)
// Put back, because this item is rebuilt rather than
// passed through: whatever is not restored here is
@@ -1398,6 +1518,9 @@ class LibrespotPlayer(
track.artistUri?.let {
putString(dev.lelonio.square.ui.EXTRA_ARTIST_URI, it)
}
+ track.albumUri?.let {
+ putString(dev.lelonio.square.ui.EXTRA_ALBUM_URI, it)
+ }
val credited = track.artists.filter { it.uri != null }
if (credited.isNotEmpty()) {
putStringArrayList(
diff --git a/app/src/main/java/dev/lelonio/square/playback/PlayQueue.kt b/app/src/main/java/dev/lelonio/square/playback/PlayQueue.kt
index 8105dc4..d9a334d 100644
--- a/app/src/main/java/dev/lelonio/square/playback/PlayQueue.kt
+++ b/app/src/main/java/dev/lelonio/square/playback/PlayQueue.kt
@@ -32,6 +32,16 @@ class PlayQueue {
val artistUri: String? = null,
/** Every credited artist with a page of their own, in credit order. */
val artists: List<dev.lelonio.square.data.CatalogArtist> = emptyList(),
+ /**
+ * The record it is on, and its address where the source gave one.
+ *
+ * Carried here because the queue rebuilds every item it holds — see
+ * toMediaItemData — and whatever is not carried is lost to everything
+ * that reads the player. The album's name went that way, which is why
+ * the player could not say what record was playing.
+ */
+ val album: String = "",
+ val albumUri: String? = null,
val durationMs: Long,
val artworkUri: Uri?,
/**
@@ -382,6 +392,8 @@ class PlayQueue {
artist = metadata.artist?.toString().orEmpty(),
artistUri = metadata.extras?.getString(dev.lelonio.square.ui.EXTRA_ARTIST_URI),
artists = creditedArtists(metadata.extras),
+ album = metadata.albumTitle?.toString().orEmpty(),
+ albumUri = metadata.extras?.getString(dev.lelonio.square.ui.EXTRA_ALBUM_URI),
durationMs = metadata.durationMs ?: 0L,
artworkUri = metadata.artworkUri,
queued = metadata.extras?.getBoolean(EXTRA_PLAY_NEXT) == true,
diff --git a/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt b/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt
index 3a05352..0b3876b 100644
--- a/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt
+++ b/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt
@@ -1243,6 +1243,7 @@ class PlaybackService : MediaLibraryService() {
androidx.media3.common.MediaMetadata.Builder()
.setTitle(track.name)
.setArtist(track.artist)
+ .setAlbumTitle(track.album.takeIf { it.isNotEmpty() })
.setDurationMs(track.durationMs.takeIf { it > 0 })
.setArtworkUri(track.artworkUrl?.let(android.net.Uri::parse))
.setExtras(
@@ -1250,6 +1251,9 @@ class PlaybackService : MediaLibraryService() {
track.artistUri?.let {
putString(dev.lelonio.square.ui.EXTRA_ARTIST_URI, it)
}
+ track.albumUri?.let {
+ putString(dev.lelonio.square.ui.EXTRA_ALBUM_URI, it)
+ }
val credited = track.artists.filter { it.uri != null }
if (credited.isNotEmpty()) {
putStringArrayList(
@@ -1302,6 +1306,8 @@ class PlaybackService : MediaLibraryService() {
artist = track.artist,
artistUri = track.artistUri,
artists = track.artists,
+ album = track.album,
+ albumUri = track.albumUri,
durationMs = track.durationMs,
artworkUri = track.artworkUrl?.let(android.net.Uri::parse),
)
diff --git a/app/src/main/java/dev/lelonio/square/ui/MainActivity.kt b/app/src/main/java/dev/lelonio/square/ui/MainActivity.kt
index b8583e8..8709a6d 100644
--- a/app/src/main/java/dev/lelonio/square/ui/MainActivity.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/MainActivity.kt
@@ -393,6 +393,9 @@ class MainActivity : ComponentActivity() {
// So the artist's name in the player is a way to
// reach them, rather than a caption.
track.artistUri?.let { putString(EXTRA_ARTIST_URI, it) }
+ // And the record, so its name under the title is a
+ // way in as well.
+ track.albumUri?.let { putString(EXTRA_ALBUM_URI, it) }
// And each credited artist separately, so a track
// by two people opens the one that was pressed.
val credited = track.artists.filter { it.uri != null }
@@ -435,6 +438,9 @@ const val EXTRA_CONTEXT_LABEL = "dev.lelonio.square.CONTEXT_LABEL"
/** The first artist's own uri, so the player's second line can be opened. */
const val EXTRA_ARTIST_URI = "dev.lelonio.square.ARTIST_URI"
+/** The record the playing track is from; see [EXTRA_ARTIST_URI]. */
+const val EXTRA_ALBUM_URI = "dev.lelonio.square.ALBUM_URI"
+
/** Every credited artist, in order, as two lists that line up. */
const val EXTRA_ARTIST_NAMES = "dev.lelonio.square.ARTIST_NAMES"
const val EXTRA_ARTIST_URIS = "dev.lelonio.square.ARTIST_URIS"
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 e521dd5..e8b5c5b 100644
--- a/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt
@@ -1,5 +1,6 @@
package dev.lelonio.square.ui
+import coil.imageLoader
import android.app.Application
import androidx.annotation.StringRes
import androidx.lifecycle.AndroidViewModel
@@ -99,6 +100,21 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
* not, which is not enough to justify three near-identical screens that
* would then drift apart.
*/
+ /**
+ * One record, said the way the artist page's top card says it.
+ *
+ * Its own type rather than a [SearchItem] because the card leads with the
+ * date and counts the songs, and neither fits in a subtitle line.
+ */
+ data class ArtistRelease(
+ val uri: String,
+ val title: String,
+ val artworkUrl: String?,
+ /** ISO-8601 as Spotify gives it: a full date, a month, or a year. */
+ val releaseDate: String,
+ val trackCount: Int,
+ )
+
data class PlaylistState(
val uri: String? = null,
val name: String = "",
@@ -142,6 +158,66 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
val appearsOn: List<SearchItem> = emptyList(),
/** The playlists Spotify built around them, "This Is" first. */
val artistPlaylists: List<SearchItem> = emptyList(),
+ /**
+ * The record they put out last, for the card under the artist's photo.
+ *
+ * Null on every page that is not an artist, and on an artist whose
+ * discography came back empty — the card is then simply absent rather
+ * than a row of placeholders.
+ */
+ /**
+ * The picture the page opens with, when there is an editorial one.
+ *
+ * Apple's catalogue keeps a full-height photograph for artists and for
+ * some records; where it exists the page is that photograph, and where
+ * it does not the page is the square cover — which is the difference
+ * between the two kinds of header the reference shows.
+ */
+ val heroUrl: String? = null,
+ /**
+ * The sleeve as Apple scanned it, where the page has one.
+ *
+ * Beside [artworkUrl] rather than replacing it: that one is the cover
+ * this app downloads, caches and colours pages from, and swapping the
+ * source under it would have every kept playlist fetch its cover again.
+ * This is only what the header draws.
+ */
+ val coverUrl: String? = null,
+ /** What Apple's editors wrote about the record; see AppleCatalog. */
+ val notes: String? = null,
+ /** The page's tint as six hex digits, where the catalogue names one. */
+ val tintHex: String? = null,
+ /**
+ * Whose list it is: the account that made a playlist.
+ *
+ * An album's is taken from its own tracks and does not need a request,
+ * so only a playlist fills this in; see openPlaylist.
+ */
+ val byline: String = "",
+ /** Where an artist is from, or when the band was formed. */
+ val origin: String? = null,
+ /** The cover as a moving picture, where the label made one. */
+ val motionUrl: String? = null,
+ /**
+ * The other catalogue has been asked and has not answered yet.
+ *
+ * The header holds its picture back while this is true. Spotify's cover
+ * is already in hand and could be drawn at once, but on a page that is
+ * about to have a different photograph that only means opening on the
+ * wrong one and swapping it out in front of the reader. The wait is
+ * capped; see dressPage.
+ */
+ val heroPending: Boolean = false,
+ /** The artist's name drawn in their own face; see AppleCatalog. */
+ val logoUrl: String? = null,
+ val latest: ArtistRelease? = null,
+ /**
+ * Whether that record is already in the library.
+ *
+ * Null while unknown, and the "+" on the card is then absent — the same
+ * rule the save button on every other page follows.
+ */
+ val latestSaved: Boolean? = null,
/** How many accounts follow them, and what Spotify files them under. */
val followers: Int = 0,
val genres: List<String> = emptyList(),
@@ -197,6 +273,92 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
val loading: Boolean = false,
)
+ /**
+ * What is out, arranged the way a "new" page is read.
+ *
+ * Separate from [FeedState] and loaded only when the tab is opened: the
+ * home page needs a dozen records for one shelf, and this needs forty of
+ * them split by date plus a song out of each of the first few. Making the
+ * home feed carry all that would spend it on every cold start for a page
+ * most sessions never open.
+ */
+ data class NewPage(
+ /** The few records the page leads with, drawn large. */
+ val hero: List<SearchItem> = emptyList(),
+ /** Out in the last seven days. */
+ val thisWeek: List<SearchItem> = emptyList(),
+ /** Everything else Spotify calls new, newest first. */
+ val recent: List<SearchItem> = emptyList(),
+ /** One song out of each of the first few records above. */
+ val songs: List<CatalogTrack> = emptyList(),
+ val loading: Boolean = false,
+ )
+
+ private val _newPage = MutableStateFlow(NewPage())
+ val newPage: StateFlow<NewPage> = _newPage.asStateFlow()
+ private var newPageJob: Job? = null
+
+ /**
+ * Fills the new-releases tab, once.
+ *
+ * Reloaded only when it is empty: records do not come out while somebody is
+ * switching tabs, and rebuilding the page under the reader every time they
+ * come back to it would move what they were about to tap.
+ */
+ fun loadNewPage() {
+ if (!container.webApi.isReady || newPageJob?.isActive == true) return
+ if (_newPage.value.recent.isNotEmpty() || _newPage.value.thisWeek.isNotEmpty()) return
+
+ _newPage.value = _newPage.value.copy(loading = true)
+ newPageJob = viewModelScope.launch {
+ val albums = runCatching {
+ container.api.newReleases(limit = NEW_RELEASES).albums?.items.orEmpty()
+ }
+ .onFailure { android.util.Log.w(TAG, "new releases unavailable: ${describe(it)}") }
+ .getOrDefault(emptyList())
+ .sortedByDescending { it.releaseDate.orEmpty() }
+
+ val week = java.time.LocalDate.now().minusDays(7).toString()
+ fun item(album: dev.lelonio.square.data.AlbumDto): SearchItem? = SearchItem(
+ uri = album.uri ?: return null,
+ title = album.name,
+ subtitle = album.artists.joinToString(", ") { it.name },
+ artworkUrl = album.images.firstOrNull()?.url,
+ )
+
+ val thisWeek = albums.filter { (it.releaseDate ?: "") >= week }.mapNotNull(::item)
+ val rest = albums.filter { (it.releaseDate ?: "") < week }.mapNotNull(::item)
+
+ // The records by the artists this account listens to lead the page,
+ // because "new" without "to you" is a catalogue. The global list is
+ // the fallback for an account too young to have artists of its own.
+ val mine = _feed.value.fromYourArtists
+ val hero = (if (mine.isNotEmpty()) mine else thisWeek + rest).take(HERO_RELEASES)
+
+ _newPage.value = NewPage(
+ hero = hero,
+ thisWeek = thisWeek,
+ recent = rest,
+ loading = false,
+ )
+
+ // And a song out of each of the first few, which is the one part of
+ // the page that has to be heard rather than looked at. Resolved
+ // through the access point rather than the Web API: this is a track
+ // list for a context, which is exactly what that side answers, and
+ // it does not come out of the account's own quota.
+ if (!awaitEngine()) return@launch
+ val songs = withContext(Dispatchers.IO) {
+ (thisWeek + rest).take(NEW_SONGS).mapNotNull { album ->
+ runCatching {
+ Catalog.tracks(Catalog.contextTrackUris(album.uri).take(1)).firstOrNull()
+ }.getOrNull()
+ }
+ }
+ _newPage.value = _newPage.value.copy(songs = songs)
+ }
+ }
+
private val _feed = MutableStateFlow(FeedState())
val feed: StateFlow<FeedState> = _feed.asStateFlow()
private var feedJob: Job? = null
@@ -1244,6 +1406,10 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
_videoFileId.value = null
_videoMode.value = false
if (trackUri == null || !trackUri.startsWith("spotify:track:")) return
+ // Offline there is no video to offer: it is streamed, and the lookup
+ // itself is a request. Leaving the answer null is what takes the button
+ // off the player — the button is drawn from having one.
+ if (dev.lelonio.square.playback.OfflineMode.active.value) return
videoLookup = viewModelScope.launch(Dispatchers.IO) {
val answer = NativeBridge.trackVideo(trackUri) ?: return@launch
val fileId = runCatching {
@@ -1497,6 +1663,10 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
loadFriends()
loadFollowedArtists()
loadSavedAlbums()
+ // The pictures of whatever is downloaded, while there is a
+ // connection to fetch them with.
+ keepPageCovers()
+ catchUpDownloads()
}
.onFailure {
android.util.Log.e(TAG, "library load failed: ${chain(it)}", it)
@@ -1525,6 +1695,50 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
* Null when there is nothing downloaded, which is the one case where an
* error really is the honest answer.
*/
+ /**
+ * Fetches the covers of downloaded pages that have none yet.
+ *
+ * Not left to the download queue, which is where the songs' own covers are
+ * filled in: that queue only runs while there is something to download, so
+ * a library that is already complete never starts it and the pages kept
+ * their blank tiles for ever. This is a handful of images against a
+ * library's worth of audio, so it can simply be done.
+ *
+ * Online only, and quietly: a failure here means a tile stays drawn.
+ */
+ private fun keepPageCovers() = viewModelScope.launch {
+ if (dev.lelonio.square.playback.OfflineMode.active.value) return@launch
+ val owners = container.downloads.owners.value.keys
+ if (owners.isEmpty()) return@launch
+ withContext(Dispatchers.IO) {
+ owners.forEach { uri ->
+ val url = container.downloads.labelOf(uri)?.artworkUrl ?: return@forEach
+ if (dev.lelonio.square.download.DownloadExtras.fileOf(url, "art") != null) {
+ return@forEach
+ }
+ runCatching { dev.lelonio.square.download.DownloadExtras.keep(url, "art") }
+ }
+ }
+ }
+
+ /**
+ * Starts the queue when something downloaded is still short of its extras.
+ *
+ * A download is meant to carry its sleeve, its tall picture, its words and
+ * its Canvas, and songs fetched by an earlier build carry none of those.
+ * The queue catches them up on its own — but only while it is running, and
+ * it only runs while there is audio owed, so a library that is complete
+ * would never have started it. This is that missing nudge, once per launch
+ * and only when there is really something to fetch.
+ */
+ private fun catchUpDownloads() = viewModelScope.launch {
+ if (dev.lelonio.square.playback.OfflineMode.active.value) return@launch
+ val wanting = withContext(Dispatchers.IO) {
+ runCatching { container.downloadQueue.anythingMissing() }.getOrDefault(false)
+ }
+ if (wanting) DownloadService.start(getApplication())
+ }
+
private suspend fun offlineLibrary(): UiState.Ready? {
container.downloads.load()
val owners = container.downloads.owners.value
@@ -1745,6 +1959,22 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
description = state.description.ifEmpty { current.description },
saved = state.saved ?: current.saved,
mine = state.mine ?: current.mine,
+ // Everything the other catalogue answered, kept across the
+ // republishes the page makes while it loads. It arrives once, on
+ // its own schedule, and the batch of tracks that lands after it
+ // used to take the photograph and the bio back off the page.
+ heroUrl = state.heroUrl ?: current.heroUrl,
+ coverUrl = state.coverUrl ?: current.coverUrl,
+ logoUrl = state.logoUrl ?: current.logoUrl,
+ notes = state.notes ?: current.notes,
+ byline = state.byline.ifEmpty { current.byline },
+ origin = state.origin ?: current.origin,
+ tintHex = state.tintHex ?: current.tintHex,
+ motionUrl = state.motionUrl ?: current.motionUrl,
+ // Owned by the lookup alone: every other publish carries the
+ // flag's default and would clear the wait a batch of tracks
+ // early, which is the swap this exists to prevent.
+ heroPending = current.heroPending,
)
}
}
@@ -1756,7 +1986,14 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
* playlist endpoint returns both, so splitting them would double the
* traffic for a page that is already waiting on its tracks.
*/
- private suspend fun detailsOf(uri: String): Pair<String?, Boolean?>? {
+ /** What one lookup says about a playlist: its words, whose it is, and their name. */
+ private data class PlaylistDetails(
+ val description: String?,
+ val mine: Boolean?,
+ val owner: String?,
+ )
+
+ private suspend fun detailsOf(uri: String): PlaylistDetails? {
if (!container.webApi.isReady || !uri.startsWith("spotify:playlist:")) return null
val dto = runCatching { container.api.playlist(uri.substringAfterLast(':')) }
.onFailure { android.util.Log.w(TAG, "no details for $uri: ${describe(it)}") }
@@ -1774,7 +2011,11 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
?.replace("&#39;", "'")
?.trim()
?.takeIf { it.isNotEmpty() }
- return text to mine
+ return PlaylistDetails(
+ description = text,
+ mine = mine,
+ owner = dto.owner?.displayName?.takeIf { it.isNotBlank() },
+ )
}
@@ -1840,6 +2081,32 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
}
}
+ /**
+ * Keeps the record on the artist page's top card, or lets it go.
+ *
+ * Its own function rather than [toggleSaved]: that one is about the page
+ * being read, and this is about a different record shown on it. Sharing the
+ * code would mean one of the two buttons writing the other's state.
+ */
+ fun toggleLatestSaved() = viewModelScope.launch {
+ val page = _playlist.value
+ val release = page.latest ?: return@launch
+ val was = page.latestSaved ?: return@launch
+ val id = release.uri.substringAfterLast(':')
+
+ _playlist.value = _playlist.value.copy(latestSaved = !was)
+ runCatching {
+ if (was) container.api.removeAlbums(id) else container.api.saveAlbums(id)
+ }
+ .onSuccess { refresh() }
+ .onFailure {
+ android.util.Log.e(TAG, "keeping the release failed: ${chain(it)}", it)
+ if (_playlist.value.uri == page.uri) {
+ _playlist.value = _playlist.value.copy(latestSaved = was)
+ }
+ }
+ }
+
/** A link's own title, from whichever side of Spotify will say. */
private suspend fun nameOf(uri: String): String? {
val kind = kindOf(uri)
@@ -2188,6 +2455,12 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
inFlight.forEach { runCatching { NativeBridge.cancelDownload(it) } }
sweepOrphans()
} else {
+ // The page's own cover, kept like the songs are. It is one
+ // picture against a playlist's worth of audio, and without it
+ // the library offline is a wall of drawn tiles.
+ page.artworkUrl?.let {
+ launch { dev.lelonio.square.download.DownloadExtras.keep(it, "art") }
+ }
container.downloads.setOwner(
ownerUri = uri,
tracks = page.tracks,
@@ -2272,7 +2545,110 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
}
}
+ /**
+ * Detail pages opened over other detail pages, newest last.
+ *
+ * The navigation graph has one route for all of them, so an album opened
+ * from an artist is not a second destination — it is the same screen showing
+ * something else, and back had nowhere to go but out of the screen entirely.
+ * This is that missing history: what the page was before it became this one.
+ */
+ private val pageStack = ArrayDeque<PlaylistState>()
+
+ /**
+ * Whether there is a page behind this one, as something the screen can watch.
+ *
+ * A plain getter is what this was, and it is worth saying why that was a
+ * bug rather than a style: the back handler reads it while it composes, and
+ * nothing about a plain field tells Compose to compose again. Opening an
+ * album from an artist changed the answer and nothing noticed — so the
+ * gesture kept leaving the screen entirely, or kept being swallowed after
+ * the history had run out, which is the "back shows the wrong page" this is
+ * behind.
+ */
+ private val _hasPreviousPage = MutableStateFlow(false)
+ val hasPreviousPage: StateFlow<Boolean> = _hasPreviousPage.asStateFlow()
+
+ /**
+ * How deep into the detail pages the listener has walked.
+ *
+ * Only the screen's own transition uses it, and only to tell a push from a
+ * pop: the two have to move in opposite directions, and one destination
+ * shared by every page means the navigation library cannot say which way
+ * this is going.
+ */
+ private val _pageDepth = MutableStateFlow(0)
+ val pageDepth: StateFlow<Int> = _pageDepth.asStateFlow()
+
+ /**
+ * Whether the detail screen is the one on screen right now.
+ *
+ * What decides whether opening a page pushes the last one onto the history.
+ * Without it the state left behind by a page that was closed minutes ago
+ * still counted as "the page you were on": open a playlist, leave it, open
+ * an artist, press back — and the playlist came back, because it was still
+ * sitting in [_playlist] when the artist was opened.
+ */
+ private var pageOnScreen = false
+
+ /** Told by the screen itself; see the detail route. */
+ fun detailShown() {
+ pageOnScreen = true
+ }
+
+ /** And when it goes, so does everything behind it. */
+ fun detailClosed() {
+ pageOnScreen = false
+ clearPageHistory()
+ }
+
+ /**
+ * Goes back one detail page, and says whether there was one.
+ *
+ * False leaves the caller to pop the navigation stack as it always did:
+ * the page underneath is then a tab, not another detail.
+ */
+ fun popPage(): Boolean {
+ val previous = pageStack.removeLastOrNull() ?: return false
+ playlistJob?.cancel()
+ _playlist.value = previous
+ _hasPreviousPage.value = pageStack.isNotEmpty()
+ _pageDepth.value = pageStack.size
+ return true
+ }
+
+ /**
+ * Nothing is behind a page reached from a tab.
+ *
+ * Called when a tab is tapped: the detail screen is one destination shared
+ * by every tab, so a history left over from the last one would have back
+ * walking into a page opened from somewhere the listener has since left.
+ */
+ fun clearPageHistory() {
+ pageStack.clear()
+ _hasPreviousPage.value = false
+ _pageDepth.value = 0
+ }
+
fun openPlaylist(playlist: CatalogPlaylist) {
+ // What is on screen now, if it is a different page and a real one. The
+ // list is kept whole rather than re-resolved on the way back: an artist
+ // page is four requests and a discography, and walking back into it
+ // should be instant.
+ _playlist.value
+ .takeIf {
+ pageOnScreen && it.uri != null && it.uri != playlist.uri &&
+ it.tracks.isNotEmpty()
+ }
+ ?.let {
+ pageStack.addLast(it)
+ // Deep enough to walk back through a listening session, short
+ // enough that a thousand-track playlist is not held forever.
+ while (pageStack.size > PAGE_HISTORY) pageStack.removeFirst()
+ _hasPreviousPage.value = true
+ _pageDepth.value = pageStack.size
+ }
+
// A station reopens as the list it already is; see [showStation].
lastStation?.takeIf { it.uri == playlist.uri }?.let {
playlistJob?.cancel()
@@ -2362,15 +2738,26 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
// What the list says about itself, when its source says anything.
// Asked for beside the picture and written the same way, through
// `base`, so a later publish cannot take it back off the screen.
- if (base.description.isEmpty() && kind == DetailKind.PLAYLIST) launch {
+ // Asked whenever anything it answers is still missing. Keyed on the
+ // description alone, it never ran for a list that had one — and the
+ // name under the title, which comes from the same request, was then
+ // absent on exactly the lists that describe themselves.
+ if (kind == DetailKind.PLAYLIST &&
+ (base.description.isEmpty() || base.byline.isEmpty())
+ ) launch {
val details = detailsOf(playlist.uri) ?: return@launch
- val text = details.first
- val mine = details.second
- base = base.copy(description = text.orEmpty(), mine = mine)
+ val text = details.description
+ val mine = details.mine
+ base = base.copy(
+ description = text.orEmpty(),
+ mine = mine,
+ byline = details.owner.orEmpty(),
+ )
if (_playlist.value.uri == playlist.uri) {
_playlist.value = _playlist.value.copy(
description = text.orEmpty().ifEmpty { _playlist.value.description },
mine = mine,
+ byline = details.owner.orEmpty(),
)
}
}
@@ -2384,6 +2771,21 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
base = base.copy(saved = kept)
}
+ // Apple's own pictures for the page. Deliberately last and
+ // deliberately quiet: it is a different catalogue reached over a
+ // different network, everything on screen is already correct
+ // without it, and an artist it has never heard of simply keeps the
+ // header it has.
+ if (kind == DetailKind.ARTIST || kind == DetailKind.ALBUM) {
+ if (!dev.lelonio.square.playback.OfflineMode.active.value) {
+ base = base.copy(heroPending = true)
+ if (_playlist.value.uri == playlist.uri) {
+ _playlist.value = _playlist.value.copy(heroPending = true)
+ }
+ }
+ launch { dressPage(playlist.uri, playlist.name, kind) }
+ }
+
if (base.artworkUrl == null) launch {
val art = artworkFor(playlist.uri, kind) ?: return@launch
base = base.copy(artworkUrl = art)
@@ -2415,6 +2817,7 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
publishPlaylist(
base.copy(
tracks = page.tracks,
+ latest = page.latest,
albums = page.albums,
singles = page.singles,
appearsOn = page.appearsOn,
@@ -2424,6 +2827,18 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
following = _playlist.value.following,
),
)
+
+ // Asked after the page is on screen, not before it: whether
+ // one album is in the library is not worth holding an
+ // artist's whole page for.
+ page.latest?.let { release ->
+ launch {
+ val kept = savedState(release.uri) ?: return@launch
+ if (_playlist.value.uri == playlist.uri) {
+ _playlist.value = _playlist.value.copy(latestSaved = kept)
+ }
+ }
+ }
} else if (cached.isNotEmpty() && isUnchanged(playlist.uri, entry?.snapshotId)) {
// Nothing to do: one small request said the copy on screen
// is the current one.
@@ -2849,6 +3264,307 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
return loaded
}
+ /**
+ * The artwork the record a track comes from carries, for the player.
+ *
+ * A song in Apple's catalogue has one square picture and nothing else; the
+ * tall one and the moving one belong to its album, which is where their own
+ * player takes them from too. Empty until a track is playing, and empty
+ * again for anything the catalogue does not have — the player then shows the
+ * square cover it already had.
+ */
+ private val _nowPlayingArt = MutableStateFlow<dev.lelonio.square.data.AppleCatalog.Album?>(null)
+ val nowPlayingArt: StateFlow<dev.lelonio.square.data.AppleCatalog.Album?> =
+ _nowPlayingArt.asStateFlow()
+
+ /**
+ * Whether the other catalogue is still being asked about this track.
+ *
+ * The player holds its picture back while this is true. Spotify's cover is
+ * already in hand and could be drawn at once, but on a track that is about
+ * to have a better copy of the same artwork that only means showing the
+ * soft one and swapping it in front of the listener. Capped, so a slow
+ * network costs a moment of plain colour rather than a player with no
+ * picture at all.
+ */
+ private val _nowPlayingArtPending = MutableStateFlow(false)
+ val nowPlayingArtPending: StateFlow<Boolean> = _nowPlayingArtPending.asStateFlow()
+
+ private var nowPlayingArtJob: Job? = null
+ private var prefetchArtJob: Job? = null
+
+ /**
+ * Looks up, and downloads, the artwork of the song that comes next.
+ *
+ * The wait a listener notices is not the picture arriving — thirty
+ * kilobytes on a wifi is nothing — it is everything before it: a search of
+ * the other catalogue, then a fetch, then a decode of a picture sixteen
+ * hundred across, all of it started at the moment the song changed. Done
+ * for the *next* song while the current one plays, all three are over
+ * before the change, and the answer is waiting in the caches the real
+ * lookup reads.
+ *
+ * Fails quietly and cancels freely: nothing on screen depends on it.
+ */
+ fun prefetchArt(title: String, album: String, artist: String) {
+ if (artist.isBlank() || dev.lelonio.square.playback.OfflineMode.active.value) return
+ prefetchArtJob?.cancel()
+ prefetchArtJob = viewModelScope.launch {
+ val found = dev.lelonio.square.data.AppleCatalog.album(album, artist)
+ .takeIf { album.isNotBlank() }
+ val cover = found?.coverUrl
+ ?: dev.lelonio.square.data.AppleCatalog.song(title, artist, album)
+ // The bytes and the decode as well as the answer: Coil keeps what it
+ // has already read, and this is the half that takes the longest.
+ val context = getApplication<SquareApplication>()
+ // At the size the player will ask for, not at the picture's own.
+ // Coil files what it has decoded under the size it decoded it at, so
+ // a copy read at sixteen hundred across is not the copy the screen
+ // wants and the decode happens again in front of the listener. The
+ // header fills the width at three by four.
+ val width = context.resources.displayMetrics.widthPixels
+ val height = width * DETAIL_TALL / DETAIL_WIDE
+ listOfNotNull(found?.heroUrl, cover).forEach { url ->
+ runCatching {
+ context.imageLoader.enqueue(
+ coil.request.ImageRequest.Builder(context)
+ .data(url)
+ .size(width, height)
+ .scale(coil.size.Scale.FILL)
+ .build(),
+ )
+ }
+ }
+ // And the colour the page takes from it, which is a second read of
+ // the same file: without this the cover arrived out of memory in one
+ // frame and the page followed it a moment later. See
+ // warmArtworkColor.
+ (found?.heroUrl ?: cover)?.let { url ->
+ runCatching {
+ dev.lelonio.square.ui.theme.warmArtworkColor(context, url)
+ }
+ }
+ }
+ }
+
+ /**
+ * The record a track is on, asked for when nothing already knew it.
+ *
+ * The address travels with the queue where the source gave one, but a
+ * playlist resolved before this app kept it — the copies on disk outlive a
+ * version — has only the album's name. Rather than leave the title inert on
+ * those, it is looked up once, on the tap.
+ */
+ suspend fun albumOf(trackUri: String): CatalogPlaylist? {
+ if (!trackUri.startsWith("spotify:track:") || !container.webApi.isReady) return null
+ val id = trackUri.substringAfterLast(':')
+ val dto = runCatching { container.api.track(id) }
+ .onFailure { android.util.Log.w(TAG, "no album for $trackUri: ${describe(it)}") }
+ .getOrNull() ?: return null
+ val album = dto.album ?: return null
+ val uri = album.uri ?: return null
+ return CatalogPlaylist(
+ uri = uri,
+ name = album.name,
+ artworkUrl = album.images.firstOrNull()?.url,
+ )
+ }
+
+ /** Called when the track changes; cached and cheap on a repeat. */
+ fun loadNowPlayingArt(uri: String?, title: String, album: String, artist: String) {
+ nowPlayingArtJob?.cancel()
+ _nowPlayingArt.value = null
+ if (artist.isBlank()) {
+ _nowPlayingArtPending.value = false
+ return
+ }
+ _nowPlayingArtPending.value = true
+ nowPlayingArtJob = viewModelScope.launch {
+ launch {
+ delay(ART_WAIT_MS)
+ _nowPlayingArtPending.value = false
+ }
+
+ // What came down with the download, first and without asking
+ // anybody. A downloaded song keeps the tall picture beside its
+ // audio, which is the whole point of keeping it: offline there is
+ // nobody to ask, and online this is the same answer without the
+ // round trip.
+ //
+ // "Asked and there is nothing" counts as an answer here, and ends
+ // the wait just as an answer does. Otherwise every downloaded song
+ // the other catalogue does not have would hold its own cover back
+ // for the length of a lookup that was made days ago.
+ keptArt(uri)?.let {
+ _nowPlayingArt.value = it.album
+ _nowPlayingArtPending.value = false
+ return@launch
+ }
+
+ // The record's name is worth waiting a moment for.
+ //
+ // Metadata arrives in pieces: the id first, the title and artist
+ // next, the record's name sometimes after that. Asking with it
+ // missing does not fail — it falls through to searching for the
+ // song, which answers with whichever release the search puts first,
+ // and that is as often a compilation or a single as the record. Two
+ // different answers for one song, each filed under its own key, is
+ // why the cover could change between one opening of the app and the
+ // next.
+ //
+ // Nothing is polled: the caller re-runs this the moment the name
+ // lands, which cancels this job where it stands. The wait is only
+ // for the songs that never get one — a local file, a stream — and
+ // those go on to the search below as they did before.
+ if (album.isBlank()) delay(ALBUM_WAIT_MS)
+
+ val found = dev.lelonio.square.data.AppleCatalog.album(album, artist)
+ .takeIf { album.isNotBlank() }
+ _nowPlayingArt.value = found
+
+ // No record found, or one with no sleeve of its own: ask for the
+ // song instead. Spotify's largest cover is 640 across and the player
+ // draws it the width of the screen, so falling back to it is
+ // falling back to a soft picture — where Apple keeps a song's
+ // artwork at several thousand.
+ if (found?.coverUrl == null && title.isNotBlank()) {
+ val fromSong = dev.lelonio.square.data.AppleCatalog.song(title, artist, album)
+ if (fromSong != null) {
+ _nowPlayingArt.value = (found ?: dev.lelonio.square.data.AppleCatalog.Album(
+ heroUrl = null,
+ coverUrl = null,
+ )).copy(coverUrl = fromSong)
+ }
+ }
+ _nowPlayingArtPending.value = false
+ }
+ }
+
+ /**
+ * What was filed for a downloaded song when it was asked about.
+ *
+ * Null and [album] null are different answers, and the difference is the
+ * whole reason this is wrapped: null means nobody has asked yet, so the
+ * catalogue still might have something; an [album] of null means it was
+ * asked and had nothing, and there is nothing to wait for.
+ */
+ private class KeptArt(val album: dev.lelonio.square.data.AppleCatalog.Album?)
+
+ /**
+ * The pictures kept beside a downloaded song, as the player wants them.
+ *
+ * Only urls with a file behind them: a url whose picture never came down is
+ * a header that draws nothing at all offline. See DownloadExtras.
+ */
+ private suspend fun keptArt(uri: String?): KeptArt? {
+ val track = uri ?: return null
+ return withContext(Dispatchers.IO) {
+ val extras = dev.lelonio.square.download.DownloadExtras
+ val (hero, cover) = extras.art(track) ?: return@withContext null
+ val onDisk = { url: String? -> url?.takeIf { extras.fileOf(it, "art") != null } }
+ val kept = dev.lelonio.square.data.AppleCatalog.Album(
+ heroUrl = onDisk(hero),
+ coverUrl = onDisk(cover),
+ )
+ KeptArt(kept.takeIf { it.heroUrl != null || it.coverUrl != null })
+ }
+ }
+
+ /**
+ * Asks Apple's catalogue for the page's photograph, and its name drawn.
+ *
+ * An album is matched on its own name and its artist's, and the artist is
+ * only known once the tracks are in — so this waits for them rather than
+ * guessing. Everything about it is optional: no network, no match, no
+ * pictures, and the page keeps the header it already has.
+ */
+ private suspend fun dressPage(uri: String, opened: String, kind: DetailKind) {
+ // Offline this still runs. AppleCatalog answers from what it wrote down
+ // and reaches for nothing, so a record whose songs are on the phone
+ // opens on its own photograph in a tunnel; one that was never looked up
+ // simply keeps Spotify's header, as it did before.
+
+ // Whatever happens below, the header stops waiting: an answer, no
+ // answer, or a network that is simply slow. A page that holds its
+ // picture back for a lookup that is never coming is worse than one that
+ // shows Spotify's.
+ viewModelScope.launch {
+ delay(HERO_WAIT_MS)
+ if (_playlist.value.uri == uri) {
+ _playlist.value = _playlist.value.copy(heroPending = false)
+ }
+ }
+ val done = { if (_playlist.value.uri == uri) {
+ _playlist.value = _playlist.value.copy(heroPending = false)
+ } }
+
+ // The name the page was opened with is empty when it was opened from a
+ // link — the title arrives with the rest of it a moment later — and a
+ // lookup for "" is a lookup for nothing.
+ val name = opened.ifBlank {
+ withTimeoutOrNull(ARTIST_WAIT_MS) {
+ while (_playlist.value.uri == uri && _playlist.value.name.isBlank()) {
+ delay(POLL_INTERVAL_MS)
+ }
+ _playlist.value.name
+ }.orEmpty()
+ }
+ if (name.isBlank()) {
+ done()
+ return
+ }
+
+ if (kind == DetailKind.ARTIST) {
+ val found = dev.lelonio.square.data.AppleCatalog.artist(name)
+ if (found == null) {
+ done()
+ return
+ }
+ if (_playlist.value.uri != uri) return
+ _playlist.value = _playlist.value.copy(
+ heroUrl = found.heroUrl,
+ logoUrl = found.logoUrl,
+ tintHex = found.bgColor,
+ notes = found.bio,
+ origin = found.origin,
+ heroPending = false,
+ )
+ return
+ }
+
+ // The record's artist, once there is a track to read it off.
+ val artist = withTimeoutOrNull(ARTIST_WAIT_MS) {
+ while (_playlist.value.uri == uri && _playlist.value.tracks.isEmpty()) {
+ delay(POLL_INTERVAL_MS)
+ }
+ _playlist.value.tracks.firstOrNull()?.artist
+ }
+ if (artist == null) {
+ done()
+ return
+ }
+
+ // The catalogue's answer, or the one that came down with the songs.
+ // The rows it writes expire after a month; the pictures beside a
+ // download do not, so a record kept on the phone opens on its own
+ // photograph however long it has been there.
+ val found = dev.lelonio.square.data.AppleCatalog.album(name, artist)
+ ?: keptArt(_playlist.value.tracks.firstOrNull()?.uri)?.album
+ if (found == null) {
+ done()
+ return
+ }
+ if (_playlist.value.uri != uri) return
+ _playlist.value = _playlist.value.copy(
+ heroUrl = found.heroUrl,
+ coverUrl = found.coverUrl,
+ notes = found.notes,
+ tintHex = found.bgColor,
+ motionUrl = found.motionUrl,
+ heroPending = false,
+ )
+ }
+
/**
* Top tracks and albums for an artist.
*
@@ -2860,6 +3576,7 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
/** Everything an artist page shows, gathered in one go. */
private data class ArtistPage(
val tracks: List<CatalogTrack>,
+ val latest: ArtistRelease?,
val albums: List<SearchItem>,
val singles: List<SearchItem>,
val appearsOn: List<SearchItem>,
@@ -2912,9 +3629,30 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
}
}
+ // The newest thing with the artist's own name on it. Compilations and
+ // the records that are somebody else's are left out: "latest release"
+ // meaning a greatest-hits reissue somebody else assembled is how that
+ // card ends up wrong on half the artists in the catalogue.
+ val latest = releases
+ .filter { it.albumGroup == "album" || it.albumGroup == "single" }
+ .filter { !it.releaseDate.isNullOrBlank() }
+ .maxByOrNull { it.releaseDate.orEmpty() }
+ ?.let { album ->
+ album.uri?.let { uri ->
+ ArtistRelease(
+ uri = uri,
+ title = album.name,
+ artworkUrl = album.images.firstOrNull()?.url,
+ releaseDate = album.releaseDate.orEmpty(),
+ trackCount = album.totalTracks,
+ )
+ }
+ }
+
return ArtistPage(
playlists = artistPlaylists(artist?.name.orEmpty()),
tracks = tracks,
+ latest = latest,
albums = shelf("album", "compilation"),
singles = shelf("single"),
appearsOn = shelf("appears_on"),
@@ -3146,9 +3884,49 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
/** A page of saved albums; the API's own maximum. */
const val ALBUM_PAGE = 50
+ /** How many detail pages back the in-screen history holds. */
+ const val PAGE_HISTORY = 12
+
/** How long a home row gets before it stops being worth scrolling. */
const val FEED_ROW = 12
+ /** Records asked of Spotify's own new-releases list for the New tab. */
+ const val NEW_RELEASES = 40
+
+ /** How many of them the page leads with, drawn large. */
+ const val HERO_RELEASES = 6
+
+ /** And how many are opened for a song to put in the list under them. */
+ const val NEW_SONGS = 10
+
+ /**
+ * How long a header holds its picture back for the other catalogue.
+ *
+ * Long enough for a cached answer and a quick search, short enough that
+ * a bad network costs a moment of plain colour rather than a page with
+ * no picture at all.
+ */
+ const val HERO_WAIT_MS = 1_200L
+
+ /**
+ * How long the player holds its picture back for the other catalogue.
+ *
+ * Long enough for a cached answer and a search on a working connection,
+ * short enough that a bad one costs a moment of colour rather than a
+ * screen with no artwork.
+ */
+ const val ART_WAIT_MS = 1_500L
+
+ /** How long a song's record has to arrive before it is given up on. */
+ const val ALBUM_WAIT_MS = 900L
+
+ /** The shape the header draws a cover in; see PlayerScreen. */
+ const val DETAIL_WIDE = 3
+ const val DETAIL_TALL = 4
+
+ /** How long the album lookup waits for a track to name the artist. */
+ const val ARTIST_WAIT_MS = 8_000L
+
const val ENGINE_TIMEOUT_MS = 30_000L
const val POLL_INTERVAL_MS = 250L
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 a49866a..a4ed3cc 100644
--- a/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt
@@ -1,5 +1,6 @@
package dev.lelonio.square.ui
+import androidx.annotation.StringRes
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.ui.graphics.luminance
@@ -28,6 +29,7 @@ import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Icon
import androidx.compose.material3.LocalContentColor
+import androidx.compose.material3.LocalTextStyle
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
@@ -77,6 +79,7 @@ import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.ContentScale
@@ -101,6 +104,8 @@ import dev.lelonio.square.ui.components.BlurTransformation
import dev.lelonio.square.ui.glass.backdrop.Backdrop
import dev.lelonio.square.ui.glass.backdrop.backdrops.layerBackdrop
import dev.lelonio.square.ui.glass.backdrop.backdrops.rememberLayerBackdrop
+import dev.lelonio.square.ui.glass.backdrop.backdrops.rememberCombinedBackdrop
+import dev.lelonio.square.ui.glass.backdrop.drawBackdrop
import dev.lelonio.square.R
import dev.lelonio.square.data.CanvasClip
import dev.lelonio.square.data.Catalog
@@ -110,7 +115,10 @@ import dev.lelonio.square.data.Lyrics
import dev.lelonio.square.backend.youtube.YouTubeVideoMode
import dev.lelonio.square.playback.AudioEffects
import dev.lelonio.square.ui.glass.LiquidBottomTab
+import dev.lelonio.square.ui.browse.NewScreen
+import dev.lelonio.square.ui.browse.RadioScreen
import dev.lelonio.square.ui.glass.LiquidBottomTabs
+import dev.lelonio.square.ui.glass.LiquidBottomTab
import dev.lelonio.square.ui.glass.LiquidButton
import dev.lelonio.square.ui.home.HomeScreen
import dev.lelonio.square.ui.library.LibraryScreen
@@ -152,6 +160,15 @@ import dev.lelonio.square.ui.onboarding.BackendChoiceScreen
import dev.lelonio.square.ui.onboarding.OnboardingScreen
import dev.lelonio.square.ui.settings.SettingsScreen
import dev.lelonio.square.ui.theme.Ink
+import dev.lelonio.square.ui.theme.pageColorFor
+import dev.lelonio.square.ui.theme.pageColorForHex
+import dev.lelonio.square.ui.theme.PageFloor
+import androidx.compose.animation.animateColorAsState
+import androidx.compose.animation.slideOutHorizontally
+import androidx.compose.animation.slideInHorizontally
+import androidx.compose.animation.fadeOut
+import androidx.compose.animation.fadeIn
+import androidx.compose.animation.togetherWith
import dev.lelonio.square.ui.theme.SquareTheme
import dev.lelonio.square.ui.theme.rememberArtworkColor
import kotlinx.coroutines.flow.first
@@ -161,10 +178,20 @@ import com.adamglin.phosphoricons.fill.ArrowCircleDown
import com.adamglin.phosphoricons.fill.Check
import com.adamglin.phosphoricons.fill.Play
import com.adamglin.phosphoricons.Fill
+import com.adamglin.phosphoricons.Bold
import com.adamglin.phosphoricons.Regular
import com.adamglin.phosphoricons.fill.House
import com.adamglin.phosphoricons.fill.MagnifyingGlass
import com.adamglin.phosphoricons.fill.MusicNotes
+import com.adamglin.phosphoricons.bold.House
+import com.adamglin.phosphoricons.bold.MusicNotes
+import com.adamglin.phosphoricons.bold.SquaresFour
+import com.adamglin.phosphoricons.bold.Broadcast
+import com.adamglin.phosphoricons.bold.MagnifyingGlass
+import com.adamglin.phosphoricons.fill.SquaresFour
+import com.adamglin.phosphoricons.fill.Broadcast
+import com.adamglin.phosphoricons.regular.SquaresFour
+import com.adamglin.phosphoricons.regular.Broadcast
import com.adamglin.phosphoricons.regular.House
import com.adamglin.phosphoricons.regular.MagnifyingGlass
import com.adamglin.phosphoricons.regular.MusicNotes
@@ -180,6 +207,8 @@ private data class TrackMenuRequest(
object Routes {
const val HOME = "home"
+ const val NEW = "new"
+ const val RADIO = "radio"
const val SEARCH = "search"
const val LIBRARY = "library"
const val PLAYLIST = "playlist"
@@ -194,6 +223,100 @@ private val expandSpec = spring<Float>(
private val BottomBarHeight = 62.dp
+/**
+ * White, carrying a colour's hue.
+ *
+ * Mixing plain white with the colour itself is what a first version did, and on
+ * a page whose colour is a deep purple that gives grey: the darkness comes along
+ * with the hue. This takes the hue and the saturation, sets the brightness where
+ * a tint belongs, and only then mixes — so a purple page gives a purple-white and
+ * a green one a green-white, whatever the page's own colour was worth.
+ */
+private fun inkTintedBy(color: Color): Color {
+ val hsv = FloatArray(3)
+ android.graphics.Color.colorToHSV(color.toArgb(), hsv)
+ if (hsv[1] < 0.06f) return Ink
+ hsv[1] = hsv[1].coerceIn(0.5f, 1f)
+ hsv[2] = 0.9f
+ return androidx.compose.ui.graphics.lerp(Ink, Color(android.graphics.Color.HSVToColor(hsv)), 0.3f)
+}
+
+/** Roughly what the search circle takes: the row's height, which is its own. */
+private val SearchCircle = 58.dp
+
+/**
+ * The bar's own inset, and the size of a glyph in it.
+ *
+ * Both measured off the reference: at its scale the bar holds its slots 3.9px
+ * clear of its ends and draws a 21px glyph in a 50px-tall bar, which is 5dp and
+ * 25dp at this one.
+ */
+private val BarInset = 6.dp
+private val TabIcon = 26.dp
+
+/**
+ * One place in the bar's tab row.
+ *
+ * A thin wrapper over the catalog's own tab so the four of them are not four
+ * copies of the same eight lines. The colours are the app's: the place you are
+ * takes the accent the cover gave the theme, and the rest are the bar's white
+ * with the page's colour in it.
+ */
+@Composable
+private fun androidx.compose.foundation.layout.RowScope.BarTab(
+ @StringRes label: Int,
+ icon: androidx.compose.ui.graphics.vector.ImageVector,
+ selected: Boolean,
+ accent: Color,
+ ink: Color,
+ modifier: Modifier = Modifier,
+ onClick: () -> Unit,
+) {
+ LiquidBottomTab(onClick = onClick, modifier = modifier) {
+ Icon(
+ icon,
+ contentDescription = stringResource(label),
+ tint = if (selected) accent else ink,
+ modifier = Modifier.size(TabIcon),
+ )
+ Text(
+ stringResource(label),
+ fontSize = 9.sp,
+ lineHeight = 11.sp,
+ style = LocalTextStyle.current.copy(
+ platformStyle = androidx.compose.ui.text.PlatformTextStyle(
+ includeFontPadding = false,
+ ),
+ lineHeightStyle = androidx.compose.ui.text.style.LineHeightStyle(
+ alignment = androidx.compose.ui.text.style.LineHeightStyle.Alignment.Center,
+ trim = androidx.compose.ui.text.style.LineHeightStyle.Trim.Both,
+ ),
+ ),
+ fontWeight = FontWeight.Bold,
+ color = if (selected) accent else ink,
+ )
+ }
+}
+
+/**
+ * The folded bar's search button.
+ *
+ * A key of its own rather than the search route's: the route belongs to the tab
+ * now, and a standalone sharing that key would be reported as the selected tab
+ * and light up beside itself.
+ */
+private const val SEARCH_CIRCLE = "search-circle"
+
+/** How tall the open bar stands; measured off the reference. See barMargin. */
+private val BarHeight = 61.dp
+
+/** The pages that are somewhere you are, rather than somewhere you went. */
+private val TAB_ROUTES =
+ setOf(Routes.HOME, Routes.NEW, Routes.RADIO, Routes.LIBRARY, Routes.SEARCH)
+
+/** How many stations the radio tab offers. Enough to scroll, few enough to read. */
+private const val RADIO_SEEDS = 14
+
/**
* Decode size of the page backdrop, in pixels.
*
@@ -368,6 +491,52 @@ fun SquareApp(
val reverb by AudioEffects.reverb.collectAsStateWithLifecycle()
val presets by viewModel.effectPresets.collectAsStateWithLifecycle()
val feed by viewModel.feed.collectAsStateWithLifecycle()
+
+ /**
+ * What the radio tab builds its stations from.
+ *
+ * One song per artist: the account's most played tracks name the same
+ * handful of people over and over, and four cards saying "Radio of X" is
+ * not a page of stations. Spotify tracks only — a station is a context on
+ * Spotify's access point and means nothing on any other backend.
+ */
+ val newPage by viewModel.newPage.collectAsStateWithLifecycle()
+
+ // The playing record's own artwork, asked for once per track and cached.
+ val nowPlayingArt by viewModel.nowPlayingArt.collectAsStateWithLifecycle()
+ val nowPlayingArtPending by viewModel.nowPlayingArtPending.collectAsStateWithLifecycle()
+ LaunchedEffect(playback.mediaId, playback.title, playback.album, playback.artist) {
+ viewModel.loadNowPlayingArt(
+ uri = playback.mediaId,
+ title = playback.title,
+ album = playback.album,
+ artist = playback.artist,
+ )
+
+ // And the one after it, while there is time to spare. Read off the
+ // player's own timeline rather than the queue list: the media item
+ // carries the record's name, which is what the other catalogue is
+ // searched by, and the list does not. See prefetchArt.
+ val next = runCatching {
+ val at = player?.nextMediaItemIndex ?: androidx.media3.common.C.INDEX_UNSET
+ if (at == androidx.media3.common.C.INDEX_UNSET) null
+ else player?.getMediaItemAt(at)?.mediaMetadata
+ }.getOrNull()
+ if (next != null) {
+ viewModel.prefetchArt(
+ title = next.title?.toString().orEmpty(),
+ album = next.albumTitle?.toString().orEmpty(),
+ artist = next.artist?.toString().orEmpty(),
+ )
+ }
+ }
+
+ val radioSeeds = remember(feed.topTracks, feed.allTimeTracks) {
+ (feed.topTracks + feed.allTimeTracks)
+ .filter { it.uri.startsWith("spotify:track:") }
+ .distinctBy { it.artist.lowercase() }
+ .take(RADIO_SEEDS)
+ }
val playlistOrder by viewModel.playlistOrder.collectAsStateWithLifecycle()
val pinnedPlaylists by viewModel.pinnedPlaylists.collectAsStateWithLifecycle()
val likedTracks by viewModel.likedTracks.collectAsStateWithLifecycle()
@@ -442,6 +611,8 @@ fun SquareApp(
// What the menu may offer for the playlist it is open on. Defaults say yes,
// because the library's own rows are the account's own library: only the
// detail page, which can be a playlist belonging to anyone, ever says no.
+ /** The page whose downloads are about to be given back; see the menu. */
+ var unkeeping by remember { mutableStateOf<MainViewModel.PlaylistState?>(null) }
var playlistMenuMine by remember { mutableStateOf(true) }
var playlistMenuSaved by remember { mutableStateOf(true) }
var deleting by remember { mutableStateOf<CatalogPlaylist?>(null) }
@@ -593,15 +764,33 @@ fun SquareApp(
// ordinary answer and the player falls back to the cover.
// Canvas is Spotify's own, served by its access point: on another source
// there is nobody to ask.
- LaunchedEffect(playback.mediaId, backend) {
+ // Turned off, no clip is ever asked for — which is the point of the switch:
+ // it saves the video as well as hiding it.
+ val canvasEnabled by preferences.canvasEnabled.collectAsStateWithLifecycle()
+
+ LaunchedEffect(playback.mediaId, backend, canvasEnabled, offlineNow) {
val uri = playback.mediaId
canvas = null
- if (uri != null && backend == dev.lelonio.square.backend.BackendId.SPOTIFY) {
+ // Offline means offline, including for the things that are only
+ // decoration: nothing here is fetched with the mode on — whether the
+ // listener set it or the signal went — and what shows then is the copy
+ // that came down with the download.
+ if (uri != null &&
+ canvasEnabled &&
+ backend == dev.lelonio.square.backend.BackendId.SPOTIFY
+ ) {
// After the song, not beside it: a Canvas is a video, and fetching
// one while the track is still arriving takes the connection the
// track needs. See awaitAudible.
awaitAudible(localState)
- canvas = Catalog.canvas(uri)
+ // The copy kept beside a download first, and not only offline: it
+ // is the same clip, it is already here, and playing it costs
+ // nothing. Offline it is the only one there is — the answer names a
+ // url on a CDN that cannot be reached, so without this a downloaded
+ // Canvas was a video sitting unplayed on the phone.
+ canvas = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
+ dev.lelonio.square.download.DownloadExtras.localCanvas(uri)
+ } ?: if (offlineNow) null else Catalog.canvas(uri)
}
}
@@ -690,6 +879,7 @@ fun SquareApp(
// that start one are not composables of their own.
val playAgainLabel = stringResource(R.string.play_again)
val trendingLabel = stringResource(R.string.trending_now)
+ val newLabel = stringResource(R.string.tab_new)
val searchLabel = stringResource(R.string.search)
val radioLabel = stringResource(R.string.radio)
// Resolved here rather than at the tap: a composable's resources are not
@@ -805,10 +995,36 @@ fun SquareApp(
// What folds the bar, and what tells the glass the page is moving. Built
// here rather than beside the bar because both of those are read at the
// top of the app: the glass configuration is provided from this scope.
- val tabBarScroll = rememberFloatingTabBarScrollConnection()
+ // The bar never folds itself: what folds it is the connection below,
+ // which knows something the library's own does not — whether the page
+ // has any more room above it.
+ val tabBarScroll = rememberFloatingTabBarScrollConnection(
+ inlineBehavior = dev.lelonio.square.ui.glass.floatingtabbar
+ .FloatingTabBarInlineBehavior.Never,
+ )
+ val foldThresholdPx = with(LocalDensity.current) { 50.dp.toPx() }
+ // Beside the bar's own rather than inside it; see ScrollActivity.
+ val scrollActivity = remember(tabBarScroll, foldThresholdPx) {
+ dev.lelonio.square.ui.glass.ScrollActivity(
+ onFold = { tabBarScroll.inline() },
+ // Only at the top. Scrolling up in the middle of a list leaves
+ // the bar where it is: it went away because the reader is
+ // reading, and it comes back when they have finished.
+ onTop = { tabBarScroll.expand() },
+ foldThresholdPx = foldThresholdPx,
+ )
+ }
// Held as a lambda so a scroll starting or stopping costs no
// recomposition of the app: the surfaces ask during draw.
- val pageMoving = remember(tabBarScroll) { { tabBarScroll.scrolling } }
+ // And still again while a screen is arriving or leaving. A push is not a
+ // scroll, so the freeze above never covered it, and every navigation
+ // re-recorded the whole page for each frame of its own animation. Keyed
+ // on the route and on the open page, because the detail screen swaps its
+ // contents without the route changing at all.
+ val navFreeze = remember { dev.lelonio.square.ui.glass.NavTransitionFreeze() }
+ val pageMoving = remember(scrollActivity, navFreeze) {
+ { scrollActivity.scrolling || navFreeze.frozen() }
+ }
CompositionLocalProvider(
LocalContentColor provides Ink,
@@ -820,6 +1036,11 @@ fun SquareApp(
val currentEntry by navController.currentBackStackEntryAsState()
val route = currentEntry?.destination?.route
+ // Every arrival starts the freeze window above. Keyed on the
+ // page as well as the route: the detail screen changes what it
+ // is showing without the route changing at all.
+ LaunchedEffect(route, playlist.uri) { navFreeze.mark() }
+
// Which tab the bar shows as the current one.
//
// Not the route: a playlist, an album and an artist are pages
@@ -836,13 +1057,29 @@ fun SquareApp(
// with the search key selected and no tab to put it on — nothing
// lit again, by a different route.
var activeTab by rememberSaveable { mutableStateOf(Routes.HOME) }
+ /**
+ * Whether the bar is currently the search field.
+ *
+ * Not the same question as "is the search page on screen": the
+ * page stays while the field goes, which is what tapping the
+ * search tab a second time does — the results are still there to
+ * read, the keyboard and the field are out of the way, and the
+ * bar is a bar again. Reset on the way out of the page, so
+ * coming back to search opens typing-ready as it did the first
+ * time.
+ */
+ var searchOpen by rememberSaveable { mutableStateOf(false) }
+
LaunchedEffect(route) {
- if (route == Routes.HOME || route == Routes.LIBRARY) {
- activeTab = route
- }
+ if (route in TAB_ROUTES) activeTab = route.orEmpty()
+ if (route != Routes.SEARCH) searchOpen = false
}
val focus = androidx.compose.ui.platform.LocalFocusManager.current
+ // Clearing the focus is usually enough to put the keyboard away,
+ // but not on every phone: this asks for it directly.
+ val keyboard = androidx.compose.ui.platform.LocalSoftwareKeyboardController.current
+
// Read here as well as at the bar: what the page does about the
// keyboard depends on it, and the bar is built much further down.
val searching = route == Routes.SEARCH
@@ -987,12 +1224,27 @@ fun SquareApp(
.fillMaxSize()
.layerBackdrop(artBackdrop),
) {
- AppBackdrop(playback.artworkUrl)
+ // The playing record as the other catalogue draws it:
+ // its own page colour where there is one, and its own
+ // picture to take a colour from where there is not. The
+ // same two sources a record's page uses, so home and
+ // library are tinted exactly as the page you reach from
+ // them — instead of a duller colour off Spotify's
+ // thumbnail, which is what made them look like a
+ // different app's screens.
+ AppBackdrop(
+ artworkUrl = nowPlayingArt?.heroUrl
+ ?: nowPlayingArt?.coverUrl
+ ?: playback.artworkUrl,
+ asColor = true,
+ tintHex = nowPlayingArt?.bgColor,
+ )
}
Box(
Modifier
.nestedScroll(tabBarScroll)
+ .nestedScroll(scrollActivity)
// Touching the page puts the keyboard away.
//
// The field is in the bar at the bottom of the screen
@@ -1010,7 +1262,31 @@ fun SquareApp(
}
},
) {
- NavHost(navController, startDestination = Routes.HOME) {
+ NavHost(
+ navController,
+ startDestination = Routes.HOME,
+ // Two different movements, because there are two
+ // different kinds of navigation here. Opening a page is
+ // a push: it comes in from the edge and the page under
+ // it stays put and dims, so the new one reads as having
+ // arrived over the old. Changing tab is not a push —
+ // neither place is on top of the other — so those
+ // crossfade, which is what the reference does too.
+ enterTransition = {
+ if (targetState.destination.route in TAB_ROUTES ||
+ targetState.destination.route == Routes.SEARCH
+ ) {
+ fadeIn(tween(180))
+ } else {
+ slideInHorizontally(tween(280)) { it / 5 } + fadeIn(tween(220))
+ }
+ },
+ exitTransition = { fadeOut(tween(180)) },
+ popEnterTransition = { fadeIn(tween(200)) },
+ popExitTransition = {
+ slideOutHorizontally(tween(260)) { it / 5 } + fadeOut(tween(200))
+ },
+ ) {
composable(Routes.HOME) {
HomeScreen(
state = state,
@@ -1055,9 +1331,59 @@ fun SquareApp(
)
}
+ composable(Routes.NEW) {
+ LaunchedEffect(Unit) { viewModel.loadNewPage() }
+ NewScreen(
+ page = newPage,
+ contentPadding = listPadding,
+ onPlaySong = { tracks, index ->
+ onPlay(tracks, index, null, false, newLabel, 0L)
+ },
+ onOpen = { item ->
+ viewModel.openContext(
+ item.uri,
+ item.title,
+ item.artworkUrl,
+ )
+ navController.navigate(Routes.PLAYLIST)
+ },
+ )
+ }
+
+ composable(Routes.RADIO) {
+ RadioScreen(
+ seeds = radioSeeds,
+ loading = feed.loading,
+ contentPadding = listPadding,
+ onOpen = { seed ->
+ scope.launch {
+ val tracks = viewModel.radioFor(seed.uri)
+ if (tracks.isEmpty()) return@launch
+ val station = "spotify:station:track:" +
+ seed.uri.substringAfterLast(':')
+ val name = radioOfTemplate.format(seed.artist)
+ // The station as a page and then as a
+ // queue, in that order: what the tab
+ // promises is a station to look at, not
+ // a shuffle that starts under a page
+ // the listener never sees.
+ viewModel.showStation(
+ uri = station,
+ name = name,
+ artworkUrl = seed.artworkUrl,
+ tracks = tracks,
+ )
+ navController.navigate(Routes.PLAYLIST)
+ onPlay(tracks, 0, station, true, name, 0L)
+ }
+ },
+ )
+ }
+
composable(Routes.SEARCH) {
SearchScreen(
state = search,
+ onQuery = viewModel::onSearchQuery,
webApi = webApi,
contentPadding = listPadding,
nowPlayingUri = playback.mediaId,
@@ -1142,33 +1468,62 @@ fun SquareApp(
}
composable(Routes.PLAYLIST) {
+ // While this screen is up, a page opened from it is
+ // opened *over* it; once it is gone, whatever it was
+ // showing is not "the page you were on" any more.
+ DisposableEffect(Unit) {
+ viewModel.detailShown()
+ onDispose { viewModel.detailClosed() }
+ }
+
+ // The system gesture, answered the same way as the
+ // arrow: the page behind this one is usually inside
+ // this screen rather than under it.
+ val hasPreviousPage by viewModel.hasPreviousPage
+ .collectAsStateWithLifecycle()
+ androidx.activity.compose.BackHandler(
+ enabled = hasPreviousPage,
+ ) { viewModel.popPage() }
+
+ // One destination holds every detail page, so a
+ // page opening over another is not a navigation the
+ // library can animate — it is the same screen with
+ // different contents. This is that missing movement:
+ // the page being left slides out the way it came,
+ // the new one slides in from the other side, and the
+ // depth says which side that is.
+ val pageDepth by viewModel.pageDepth
+ .collectAsStateWithLifecycle()
+ androidx.compose.animation.AnimatedContent(
+ targetState = playlist to pageDepth,
+ contentKey = { (page, depth) -> page.uri to depth },
+ transitionSpec = {
+ val deeper = targetState.second > initialState.second
+ val from = { width: Int ->
+ if (deeper) width / 4 else -width / 4
+ }
+ (
+ slideInHorizontally(tween(280)) { from(it) } +
+ fadeIn(tween(200))
+ ).togetherWith(
+ slideOutHorizontally(tween(280)) { -from(it) } +
+ fadeOut(tween(180)),
+ )
+ },
+ label = "detailPage",
+ ) { (page, _) ->
// Re-seeded from the open playlist, album or artist.
// The rest of the app is themed after whatever is
// playing, which is right for the home page and
// wrong here: an album page tinted by an unrelated
// track reads as belonging to something else.
- val detailAccent by rememberArtworkColor(playlist.artworkUrl)
+ val detailAccent by rememberArtworkColor(page.artworkUrl)
// Resolved here rather than inside the play
// callbacks: those are not composables.
- val source = playlist.sourceLabel()
+ val source = page.sourceLabel()
SquareTheme(seed = detailAccent) {
PlaylistScreen(
- state = playlist,
- downloadState = playlist.uri
- ?.let { downloadOwners[it] }
- ?: dev.lelonio.square.data.OwnerState.None,
- onToggleDownload = { viewModel.toggleDownload(playlist) },
- // The store belongs to the librespot
- // engine, so only Spotify pages can be
- // kept — and the local-files shelf is
- // already on the phone.
- canDownload = backend ==
- dev.lelonio.square.backend.BackendId.SPOTIFY &&
- playlist.uri?.startsWith("spotify:") == true &&
- // Nothing can be fetched with no
- // network, so the button would only
- // ever queue work that cannot start.
- !offlineNow,
+ state = page,
offline = offlineNow,
// Read per row rather than handed over as a
// map: the progress map changes several
@@ -1187,7 +1542,13 @@ fun SquareApp(
},
contentPadding = listPadding,
nowPlayingUri = playback.mediaId,
- onBack = { navController.popBackStack() },
+ // One route holds every detail page, so
+ // back is the screen's own history first
+ // and the navigation stack only once that
+ // is empty; see MainViewModel.popPage.
+ onBack = {
+ if (!viewModel.popPage()) navController.popBackStack()
+ },
onAskLocalPermission = { askLocalPermission() },
onPlay = { tracks, index, asContext ->
onPlay(
@@ -1245,7 +1606,20 @@ fun SquareApp(
item.artworkUrl,
)
},
+ downloadState = playlist.uri
+ ?.let { downloadOwners[it] }
+ ?: dev.lelonio.square.data.OwnerState.None,
+ onToggleDownload = { viewModel.toggleDownload(playlist) },
+ // The store belongs to the librespot engine,
+ // so only Spotify pages can be kept — and
+ // with no network the button would only ever
+ // queue work that cannot start.
+ canDownload = backend ==
+ dev.lelonio.square.backend.BackendId.SPOTIFY &&
+ playlist.uri?.startsWith("spotify:") == true &&
+ !offlineNow,
onToggleFollow = viewModel::toggleFollowArtist,
+ onToggleLatestSaved = viewModel::toggleLatestSaved,
onToggleSaved = viewModel::toggleSaved,
onShare = {
val uri = playlist.uri ?: return@PlaylistScreen
@@ -1276,6 +1650,7 @@ fun SquareApp(
},
)
}
+ }
}
}
@@ -1468,7 +1843,88 @@ fun SquareApp(
// narrower capsule than its three do, and the row centres
// itself — which is the point of measuring the parts rather
// than the whole.
- val barMargin = if (tabBarScroll.isInline) 16.dp else 26.dp
+ // Measured off the reference frame (314 px wide, bar 299 px
+ // of it): the bar leaves about the same margin either side
+ // as a tab is tall is wide — 17dp here once its own width is
+ // taken off the screen. Folded it pulls in slightly, which
+ // is what the reference does too.
+ // Measured off the recording of the reference running on
+ // this phone: 27 video pixels of a 720-wide capture, which
+ // is 16dp here, and the same on both sides in both states.
+ val barMargin = 16.dp
+
+ // What one of the four gets, once the row's own margins and
+ // the search circle beside it have been taken off. Measured
+ // from the screen rather than fixed: four labels and a circle
+ // on a narrow phone is exactly where a constant starts
+ // pushing the last tab off the end.
+ // The colour the current tab is drawn in: the artwork's
+ // own, straight from the palette rather than through the
+ // theme.
+ //
+ // The theme's primary is that colour after the material
+ // scheme has had it — pulled toward its own tonal palette,
+ // which is what made the lit tab a near-relative of the
+ // cover rather than the cover's colour. This is the same
+ // value the pages are tinted from, at full strength, which
+ // is how the reference draws the place you are.
+ // The app's accent, which is the cover's own: the theme is
+ // seeded from it through ArtworkColor and every switch,
+ // slider and progress bar in the app is drawn in it.
+ //
+ // This used to read the palette a second time here, and off
+ // the *other* catalogue's picture — so the bar could be
+ // violet while the rest of the app was orange, on the same
+ // song. One accent, taken from where the app already keeps
+ // it.
+ val tabAccent = MaterialTheme.colorScheme.primary
+
+ // And the white the rest of the bar is drawn in: never a
+ // pure one. The reference tints its icons with the colour of
+ // what is *behind* them — on a green page they are a green
+ // white — which is most of why the bar reads as part of the
+ // page rather than as a strip laid over it.
+ //
+ // Behind, and not what is playing. Those are two different
+ // colours as soon as you open a record while something else
+ // is on: a purple page under a pink bar is exactly the seam
+ // this is meant to remove. So on a detail page the tint is
+ // that page's own — the catalogue's colour for it where
+ // there is one, and the colour of the picture where there is
+ // not — and everywhere else it falls back to the playing
+ // track, which is what those pages are tinted by.
+ val onDetail = route == Routes.PLAYLIST
+ val detailArt = playlist.heroUrl ?: playlist.coverUrl ?: playlist.artworkUrl
+ val detailAccent by rememberArtworkColor(detailArt.takeIf { onDetail })
+ val surfaceTint = when {
+ // Off a detail page the bar is tinted by what is
+ // playing, which is what those pages are tinted by too.
+ !onDetail -> tabAccent
+ playlist.tintHex != null -> runCatching {
+ Color(android.graphics.Color.parseColor("#${playlist.tintHex}"))
+ }.getOrDefault(tabAccent)
+ else -> detailAccent ?: tabAccent
+ }
+ val barInk = inkTintedBy(surfaceTint)
+
+ // What the lit slot is filled with. The listener's own glass
+ // settings still own it — the puck was a surface of this
+ // app's making before the library grew one — so an opacity of
+ // zero leaves the row unmarked rather than drawing a shape
+ // nobody asked for.
+ // Darker than the bar, not lighter.
+ //
+ // The reference sinks its lit slot into the bar rather than
+ // lifting it off: measured off it, the puck reads at about
+ // three fifths of the brightness of the glass around it. A
+ // white sticker was the older idea and it made the bar look
+ // like it had a highlight stuck on it.
+ //
+ // The listener's own slider still sets how far it goes; only
+ // the direction is fixed here.
+ val puckWash = Color.Black.copy(
+ alpha = (glassConfig.puckOpacity.coerceIn(0f, 1f) * 1.3f).coerceAtMost(0.5f),
+ )
// Searching opens the bar and keeps it open.
//
@@ -1483,110 +1939,439 @@ fun SquareApp(
// fold is a bar whose scrolling is not allowed to change it.
val barFolds by glassStore.barFolds.collectAsStateWithLifecycle()
LaunchedEffect(searching, barFolds) {
- tabBarScroll.locked = searching || !barFolds
if (searching || !barFolds) tabBarScroll.expand()
}
FloatingTabBar(
- // Always the tab the page belongs to, search included.
- //
- // Naming the search circle here instead left the search
- // bar with no tab beside it: the bar keeps one tab in
- // search mode — the one you came from, so you can go
- // back by tapping it — and it finds it by matching this
- // key against the regular tabs. A key belonging to none
- // of them matched nothing and the tab disappeared,
- // leaving the back gesture as the only way out.
+ // The page's own tab, search included — it is one of
+ // them now. The bar keeps this tab when it folds and
+ // finds it by matching this key.
selectedTabKey = activeTab,
scrollConnection = tabBarScroll,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = barMargin)
.padding(bottom = navBar + 8.dp),
- // The glass is the caller's to apply, and it is what the
- // bar is made of: transparent colours underneath, and
- // every surface sampling the page through this.
+ // Where the glass goes in. The library applies this after
+ // its own background and before its padding, which is
+ // exactly the seam a pane of glass belongs in: the
+ // surfaces below draw nothing of their own — see the
+ // transparent colours — and this is what they are made
+ // of.
tabBarContentModifier = barGlass,
colors = FloatingTabBarDefaults.colors(
- backgroundColor = Color.Transparent,
- accessoryBackgroundColor = Color.Transparent,
+ // A film over the glass, not nothing.
+ //
+ // The bar was left transparent so the glass alone
+ // made it, and over a dark page that is very nearly
+ // black — which leaves a dark puck with nothing to be
+ // darker than. The reference's bar is a lighter
+ // surface for exactly this reason: it is what its lit
+ // slot is cut out of.
+ backgroundColor = GlassFilm,
+ accessoryBackgroundColor = GlassFilm,
+ selectedTabBackgroundColor = puckWash,
+ selectedStandaloneTabBackgroundColor = puckWash,
),
sizes = FloatingTabBarDefaults.sizes(
- tabBarContentPadding = PaddingValues(4.dp),
- tabExpandedContentPadding = PaddingValues(vertical = 6.dp, horizontal = 6.dp),
- tabInlineContentPadding = PaddingValues(8.dp),
- // The reference's capsule is 272dp wide whatever
- // is in it: three tabs at 88 there, two at 132
- // here. Keeping the tab width instead would have
- // made this app's bar visibly shorter than the one
- // it is copying — and the accessory above it, which
- // matches the row, shorter with it.
- tabWidth = (272.dp - 8.dp) / 2,
+ // Measured off the reference running on this phone;
+ // see the notes on barMargin.
+ // What separates the lit slot from the bar's own
+ // edge. Measured off the reference: its puck stands
+ // four fifths of the bar's height, which is six
+ // points of glass above and below it.
+ tabBarContentPadding = PaddingValues(
+ vertical = 6.dp,
+ horizontal = 2.dp,
+ ),
+ // Measured off Music OS 26 on this phone, which is
+ // the bar this one is trying to be: its row stands
+ // 61dp, its glyphs are 26, and the circle beside the
+ // pill is as tall as the pill is. The library sizes
+ // that circle off the row for us, so the only
+ // numbers here are the paddings that make the row
+ // that tall.
+ tabExpandedContentPadding = PaddingValues(
+ vertical = 8.dp,
+ horizontal = 14.dp,
+ ),
+ tabInlineContentPadding = PaddingValues(14.dp),
+ componentSpacing = 14.dp,
),
- inlineAccessory = accessory,
- expandedAccessory = accessory,
- backdrop = pageBackdrop,
- accentColor = Ink,
- searchMode = searching,
- searchBarContent = if (searching) {
+ // The tab group is the catalog's own component, as it
+ // ships it: the pill, the four tabs and the indicator
+ // that can be dragged between them. The bar around it —
+ // the fold, the mini player, the search circle — is
+ // still the library's.
+ expandedTabs = { tabsModifier, tabsVisibility ->
+ // The bar's own configuration, not the app's.
+ //
+ // The component reads the glass settings from
+ // composition, and the setting that governs this
+ // surface is the one for the navigation bar — so a
+ // listener who turns the glass off there gets a flat
+ // bar, exactly as they do for the mini player and the
+ // player's own panes.
+ val tabRoutes = remember {
+ listOf(
+ Routes.HOME,
+ Routes.NEW,
+ Routes.RADIO,
+ Routes.LIBRARY,
+ Routes.SEARCH,
+ )
+ }
+ val here = tabRoutes.indexOf(activeTab).coerceAtLeast(0)
+ // Stable, or the component throws away the state it
+ // keys on this and the indicator stops animating.
+ val hereState = rememberUpdatedState(here)
+ val selectedTabIndex = remember { { hereState.value } }
+ // The catalog's component as this app carries it:
+ // same code, with its shell made of the app's own
+ // glass so the bar answers the listener's settings
+ // like every other pane. See LiquidBottomTabs.
+ CompositionLocalProvider(
+ dev.lelonio.square.ui.glass.LocalGlassEffectConfig provides barConfig,
+ ) {
+ LiquidBottomTabs(
+ selectedTabIndex = selectedTabIndex,
+ onTabSelected = { index ->
+ viewModel.clearPageHistory()
+ navController.switchTab(tabRoutes[index])
+ },
+ backdrop = pageBackdrop,
+ tabsCount = tabRoutes.size,
+ accentColor = tabAccent,
+ containerColor = GlassFilm,
+ // Darker than the bar, not lighter: the mark is
+ // cut into the glass rather than stuck on it.
+ // Still the listener's own slider — at zero the
+ // row goes unmarked.
+ indicatorColor = puckWash,
+ height = BarHeight,
+ // Under half the height, or the refraction from
+ // the two long edges meets in the middle and
+ // draws a seam across the capsule.
+ lensDepth = 20.dp,
+ // Nothing is lit while the page on screen is not
+ // one of these four; search is a place of its
+ // own.
+ indicatorVisible = activeTab in TAB_ROUTES,
+ modifier = tabsModifier,
+ ) {
+ BarTab(
+ R.string.home,
+ PhosphorIcons.Fill.House,
+ activeTab == Routes.HOME,
+ tabAccent,
+ barInk,
+ ) {
+ viewModel.clearPageHistory()
+ navController.switchTab(Routes.HOME)
+ }
+ BarTab(
+ R.string.tab_new,
+ PhosphorIcons.Fill.SquaresFour,
+ activeTab == Routes.NEW,
+ tabAccent,
+ barInk,
+ ) {
+ viewModel.clearPageHistory()
+ navController.switchTab(Routes.NEW)
+ }
+ BarTab(
+ R.string.tab_radio,
+ PhosphorIcons.Fill.Broadcast,
+ activeTab == Routes.RADIO,
+ tabAccent,
+ barInk,
+ ) {
+ viewModel.clearPageHistory()
+ navController.switchTab(Routes.RADIO)
+ }
+ BarTab(
+ R.string.library,
+ PhosphorIcons.Fill.MusicNotes,
+ activeTab == Routes.LIBRARY,
+ tabAccent,
+ barInk,
+ ) {
+ viewModel.clearPageHistory()
+ navController.switchTab(Routes.LIBRARY)
+ }
+ BarTab(
+ R.string.search,
+ // Heavy rather than solid: a filled
+ // magnifier reads as a blob at this size,
+ // and it is the one glyph here whose shape
+ // is the whole of its meaning.
+ PhosphorIcons.Bold.MagnifyingGlass,
+ activeTab == Routes.SEARCH,
+ tabAccent,
+ barInk,
+ // This slot is the folded bar's search
+ // circle standing in the row. Sharing its
+ // bounds is what keeps it at the right edge
+ // while the pill collapses to the left,
+ // instead of shrinking away with the pill
+ // and a circle fading in where it was — which
+ // is what the reference does: the first and
+ // last of the row survive the fold, the
+ // three in between go.
+ modifier = Modifier.sharedElement(
+ sharedContentState = rememberSharedContentState("standaloneTab"),
+ animatedVisibilityScope = tabsVisibility,
+ zIndexInOverlay = 2f,
+ ),
+ ) {
+ viewModel.clearPageHistory()
+ searchOpen = true
+ navController.switchTab(Routes.SEARCH)
+ }
+ }
+ }
+ },
+ // What the tabs are built out of, so the builder runs
+ // again when it changes.
+ //
+ // The library remembers the scope and runs the content
+ // lambda once — so the icons registered in it captured
+ // the colours of the first composition and kept them for
+ // ever. That is why the folded bar's circle stayed the
+ // accent of whatever was playing at startup while the
+ // open bar followed the song, and why the search icon
+ // drifted from the rest.
+ contentKey = listOf(activeTab, searching, searchOpen, tabAccent, barInk),
+ expandedTabsHeight = BarHeight,
+ // Search is one of the places now, so the circle beside
+ // the pill would be the same control twice. It stays for
+ // the folded bar, where there is no pill to hold it.
+ standaloneInExpanded = false,
+ // Tapping the search tab grows it into the field, and
+ // the tabs fold away behind it. Tapping it again puts
+ // the field away and leaves the results; see searchOpen.
+ searchMode = searching && searchOpen,
+ searchBarContent = if (searching && searchOpen) {
{ fieldModifier ->
BarSearchField(
query = search.query,
onQuery = viewModel::onSearchQuery,
modifier = fieldModifier,
+ ink = barInk,
)
}
} else {
null
},
+ tabsFillWidth = true,
+ inlineAccessory = accessory,
+ expandedAccessory = accessory,
) {
tab(
key = Routes.HOME,
- title = { Text(stringResource(R.string.home), fontSize = 10.sp) },
+ title = {
+ Text(
+ stringResource(R.string.home),
+ fontSize = 9.sp,
+ lineHeight = 11.sp,
+ style = LocalTextStyle.current.copy(
+ platformStyle = androidx.compose.ui.text.PlatformTextStyle(
+ includeFontPadding = false,
+ ),
+ lineHeightStyle = androidx.compose.ui.text.style.LineHeightStyle(
+ alignment = androidx.compose.ui.text.style.LineHeightStyle.Alignment.Center,
+ trim = androidx.compose.ui.text.style.LineHeightStyle.Trim.Both,
+ ),
+ ),
+ fontWeight = FontWeight.Bold,
+ color = if (activeTab == Routes.HOME) tabAccent else barInk,
+ )
+ },
icon = {
Icon(
- if (activeTab == Routes.HOME) PhosphorIcons.Fill.House
- else PhosphorIcons.Regular.House,
+ PhosphorIcons.Fill.House,
contentDescription = stringResource(R.string.home),
- tint = Ink,
- modifier = Modifier.size(30.dp),
+ tint = if (activeTab == Routes.HOME) tabAccent else barInk,
+ modifier = Modifier.size(TabIcon),
+ )
+ },
+ onClick = {
+ viewModel.clearPageHistory()
+ navController.switchTab(Routes.HOME)
+ },
+ )
+ tab(
+ key = Routes.NEW,
+ title = {
+ Text(
+ stringResource(R.string.tab_new),
+ fontSize = 9.sp,
+ lineHeight = 11.sp,
+ style = LocalTextStyle.current.copy(
+ platformStyle = androidx.compose.ui.text.PlatformTextStyle(
+ includeFontPadding = false,
+ ),
+ lineHeightStyle = androidx.compose.ui.text.style.LineHeightStyle(
+ alignment = androidx.compose.ui.text.style.LineHeightStyle.Alignment.Center,
+ trim = androidx.compose.ui.text.style.LineHeightStyle.Trim.Both,
+ ),
+ ),
+ fontWeight = FontWeight.Bold,
+ color = if (activeTab == Routes.NEW) tabAccent else barInk,
+ )
+ },
+ icon = {
+ Icon(
+ PhosphorIcons.Fill.SquaresFour,
+ contentDescription = stringResource(R.string.tab_new),
+ tint = if (activeTab == Routes.NEW) tabAccent else barInk,
+ modifier = Modifier.size(TabIcon),
)
},
- onClick = { navController.switchTab(Routes.HOME) },
+ onClick = {
+ viewModel.clearPageHistory()
+ navController.switchTab(Routes.NEW)
+ },
+ )
+ tab(
+ key = Routes.RADIO,
+ title = {
+ Text(
+ stringResource(R.string.tab_radio),
+ fontSize = 9.sp,
+ lineHeight = 11.sp,
+ style = LocalTextStyle.current.copy(
+ platformStyle = androidx.compose.ui.text.PlatformTextStyle(
+ includeFontPadding = false,
+ ),
+ lineHeightStyle = androidx.compose.ui.text.style.LineHeightStyle(
+ alignment = androidx.compose.ui.text.style.LineHeightStyle.Alignment.Center,
+ trim = androidx.compose.ui.text.style.LineHeightStyle.Trim.Both,
+ ),
+ ),
+ fontWeight = FontWeight.Bold,
+ color = if (activeTab == Routes.RADIO) tabAccent else barInk,
+ )
+ },
+ icon = {
+ Icon(
+ PhosphorIcons.Fill.Broadcast,
+ contentDescription = stringResource(R.string.tab_radio),
+ tint = if (activeTab == Routes.RADIO) tabAccent else barInk,
+ modifier = Modifier.size(TabIcon),
+ )
+ },
+ onClick = {
+ viewModel.clearPageHistory()
+ navController.switchTab(Routes.RADIO)
+ },
)
tab(
key = Routes.LIBRARY,
- title = { Text(stringResource(R.string.library), fontSize = 10.sp) },
+ title = {
+ Text(
+ stringResource(R.string.library),
+ fontSize = 9.sp,
+ lineHeight = 11.sp,
+ style = LocalTextStyle.current.copy(
+ platformStyle = androidx.compose.ui.text.PlatformTextStyle(
+ includeFontPadding = false,
+ ),
+ lineHeightStyle = androidx.compose.ui.text.style.LineHeightStyle(
+ alignment = androidx.compose.ui.text.style.LineHeightStyle.Alignment.Center,
+ trim = androidx.compose.ui.text.style.LineHeightStyle.Trim.Both,
+ ),
+ ),
+ fontWeight = FontWeight.Bold,
+ color = if (activeTab == Routes.LIBRARY) tabAccent else barInk,
+ )
+ },
icon = {
Icon(
- if (activeTab == Routes.LIBRARY) PhosphorIcons.Fill.MusicNotes
- else PhosphorIcons.Regular.MusicNotes,
+ PhosphorIcons.Fill.MusicNotes,
contentDescription = stringResource(R.string.library),
- tint = Ink,
- modifier = Modifier.size(30.dp),
+ tint = if (activeTab == Routes.LIBRARY) tabAccent else barInk,
+ modifier = Modifier.size(TabIcon),
)
},
- onClick = { navController.switchTab(Routes.LIBRARY) },
+ onClick = {
+ viewModel.clearPageHistory()
+ navController.switchTab(Routes.LIBRARY)
+ },
)
- // Search is a standalone circle rather than a third tab,
- // which is what lets it grow into the field: you go there
- // to do something and come back, and the bar treats it as
- // that kind of destination.
- standaloneTab(
+ // Search is one of the places, so it is registered like
+ // one: this is the tab the folded bar shows when it is
+ // where you are, and the key the search field grows out
+ // of.
+ tab(
key = Routes.SEARCH,
+ title = {
+ Text(
+ stringResource(R.string.search),
+ fontSize = 9.sp,
+ lineHeight = 11.sp,
+ style = LocalTextStyle.current.copy(
+ platformStyle = androidx.compose.ui.text.PlatformTextStyle(
+ includeFontPadding = false,
+ ),
+ lineHeightStyle = androidx.compose.ui.text.style.LineHeightStyle(
+ alignment = androidx.compose.ui.text.style.LineHeightStyle.Alignment.Center,
+ trim = androidx.compose.ui.text.style.LineHeightStyle.Trim.Both,
+ ),
+ ),
+ fontWeight = FontWeight.Bold,
+ color = if (activeTab == Routes.SEARCH) tabAccent else barInk,
+ )
+ },
icon = {
Icon(
- PhosphorIcons.Regular.MagnifyingGlass,
+ // Heavy rather than solid: a filled magnifier
+ // reads as a blob at this size, and it is the
+ // one glyph here whose shape is the whole of
+ // its meaning.
+ PhosphorIcons.Bold.MagnifyingGlass,
contentDescription = stringResource(R.string.search),
- tint = Ink,
- modifier = Modifier.size(26.dp),
+ tint = if (activeTab == Routes.SEARCH) tabAccent else barInk,
+ modifier = Modifier.size(TabIcon),
)
},
onClick = {
- if (searching) navController.switchTab(Routes.HOME)
- else navController.switchTab(Routes.SEARCH)
+ if (searching && searchOpen) {
+ // Already typing: this is the way out of it.
+ // The field goes and the keyboard with it,
+ // the results stay where they are.
+ searchOpen = false
+ focus.clearFocus()
+ keyboard?.hide()
+ } else {
+ viewModel.clearPageHistory()
+ searchOpen = true
+ navController.switchTab(Routes.SEARCH)
+ }
},
)
+ // And still a circle beside the folded bar, so a reader
+ // halfway down a list can search without opening it
+ // first. Gone while search is where you are: the folded
+ // tab is already this control.
+ if (!searching) {
+ standaloneTab(
+ key = SEARCH_CIRCLE,
+ icon = {
+ Icon(
+ PhosphorIcons.Bold.MagnifyingGlass,
+ contentDescription = stringResource(R.string.search),
+ tint = barInk,
+ modifier = Modifier.size(TabIcon),
+ )
+ },
+ onClick = {
+ viewModel.clearPageHistory()
+ searchOpen = true
+ navController.switchTab(Routes.SEARCH)
+ },
+ )
+ }
}
}
}
@@ -1608,6 +2393,31 @@ fun SquareApp(
) {
PlayerScreen(
state = playerState,
+ // The title is the way onto the record. The
+ // address travels with the queue where the
+ // source gave one; where it did not — a list
+ // resolved before the app kept it — it is
+ // looked up on the tap rather than left inert.
+ onOpenAlbum = playback.mediaId
+ ?.takeIf { it.startsWith("spotify:track:") }
+ ?.let { track ->
+ {
+ scope.launch {
+ val album = playback.albumUri?.let { uri ->
+ CatalogPlaylist(
+ uri = uri,
+ name = playback.album,
+ artworkUrl = playback.artworkUrl,
+ )
+ } ?: viewModel.albumOf(track)
+ if (album != null) {
+ expand.animateTo(0f, expandSpec)
+ navController.openPlaylist(viewModel, album)
+ }
+ }
+ Unit
+ }
+ },
positionMs = positionMs,
videoFileId = videoFileId,
videoMode = spotifyVideoOn,
@@ -1731,6 +2541,19 @@ fun SquareApp(
onDeletePreset = viewModel::deleteEffectPreset,
backdrop = artBackdrop,
canvas = canvas,
+ // The record's own artwork from the other
+ // catalogue, where it has any: the tall picture
+ // and the moving cover a song inherits from its
+ // album. Null leaves the player with the square
+ // cover it always had.
+ coverHeroUrl = nowPlayingArt?.heroUrl,
+ coverMotionUrl = nowPlayingArt?.motionUrl,
+ coverSquareUrl = nowPlayingArt?.coverUrl,
+ // Spotify's cover is the fallback, not the
+ // first draft: while the catalogue is still
+ // being asked, the player shows colour rather
+ // than a picture it is about to replace.
+ coverPending = nowPlayingArtPending,
devices = devices,
onAnotherDevice = remote != null,
alreadySaved = playback.mediaId != null &&
@@ -1824,8 +2647,11 @@ fun SquareApp(
backend == dev.lelonio.square.backend.BackendId.SPOTIFY,
onWatchVideo = player
?.takeIf {
- playback.mediaId
- ?.startsWith("ytmusic:track:") == true
+ // A video is streamed, so there is
+ // nothing to offer offline.
+ !offlineNow &&
+ playback.mediaId
+ ?.startsWith("ytmusic:track:") == true
}
?.let { { YouTubeVideoMode.toggle(it) } },
videoOn = videoOn || spotifyVideoOn,
@@ -1898,6 +2724,52 @@ fun SquareApp(
sendForDownload(context, shownPlaylist.openLink())
}
}
+ // Keeping the page on the phone lives here rather
+ // than under the cover: the reference has no button for
+ // it beside play, and the three that are there are the
+ // three you press while listening. This is a decision
+ // about storage, which is what a menu is for.
+ //
+ // The store belongs to the librespot engine, so only
+ // Spotify pages can be kept — and with no network the
+ // entry would only ever queue work that cannot start.
+ //
+ // Offered only for the page that is open, because
+ // keeping one means keeping its songs and the track list
+ // is what this reads: the same sheet opens over a
+ // library row, where there is a name and nothing to
+ // fetch yet.
+ val keepable = backend == dev.lelonio.square.backend.BackendId.SPOTIFY &&
+ shownPlaylist.uri.startsWith("spotify:") &&
+ playlist.uri == shownPlaylist.uri &&
+ playlist.tracks.isNotEmpty() &&
+ // An artist page has no keep button of its own: its
+ // three controls are the ones the reference gives an
+ // artist, so for that one page this is the way in.
+ playlist.kind == MainViewModel.DetailKind.ARTIST &&
+ !offlineNow
+ if (keepable) {
+ val kept = downloadOwners[shownPlaylist.uri]
+ val isKept = kept is dev.lelonio.square.data.OwnerState.Complete ||
+ kept is dev.lelonio.square.data.OwnerState.Partial
+ TrackSheetAction(
+ stringResource(
+ if (isKept) R.string.remove_download else R.string.download,
+ ),
+ if (isKept) {
+ PhosphorIcons.Regular.Trash
+ } else {
+ PhosphorIcons.Regular.Download
+ },
+ ) {
+ playlistMenu = null
+ // Asked rather than done when it takes songs
+ // away: a mis-tap should not delete a hundred
+ // of them.
+ if (isKept) unkeeping = playlist
+ else viewModel.toggleDownload(playlist)
+ }
+ }
if (editable) TrackSheetAction(
stringResource(R.string.delete),
PhosphorIcons.Regular.Trash,
@@ -1910,6 +2782,19 @@ fun SquareApp(
}
}
+ unkeeping?.let { target ->
+ dev.lelonio.square.ui.components.ConfirmDialog(
+ title = stringResource(R.string.remove_download),
+ message = stringResource(R.string.remove_download_confirm, target.name),
+ confirmLabel = stringResource(R.string.remove_download_confirm_action),
+ onConfirm = {
+ viewModel.toggleDownload(target)
+ unkeeping = null
+ },
+ onDismiss = { unkeeping = null },
+ )
+ }
+
deleting?.let { target ->
dev.lelonio.square.ui.components.ConfirmDialog(
title = stringResource(R.string.delete_playlist_title),
@@ -2236,7 +3121,46 @@ fun SquareApp(
* cover — the palette is built for a dark page.
*/
@Composable
-private fun AppBackdrop(artworkUrl: String?) {
+private fun AppBackdrop(
+ artworkUrl: String?,
+ asColor: Boolean = false,
+ /** The catalogue's own page colour for what is playing; see pageColorForHex. */
+ tintHex: String? = null,
+) {
+ // The pages are the colour of what is playing, not a picture of it.
+ //
+ // A blurred cover behind a home page full of covers is a picture behind
+ // pictures: every shelf sits on a different smear of the same artwork, and
+ // nothing on the page is helped by it. The detail pages already answer this
+ // properly — one tone taken from the record, falling away down the screen —
+ // and this is that same treatment for everywhere else, which is also what
+ // makes moving between them feel like one app rather than two.
+ //
+ // The player keeps the picture: there the cover is the subject, and a wash
+ // of its colour behind the very artwork it was taken from says nothing.
+ if (asColor) {
+ val accent by rememberArtworkColor(artworkUrl.takeIf { tintHex == null })
+ // Eased rather than cut: a track change would otherwise repaint the
+ // whole window in one frame, which reads as a flash.
+ val tone by animateColorAsState(
+ targetValue = tintHex?.let(::pageColorForHex) ?: pageColorFor(accent),
+ animationSpec = tween(durationMillis = 700),
+ label = "pageTone",
+ )
+ Box(
+ Modifier
+ .fillMaxSize()
+ .background(
+ Brush.verticalGradient(
+ 0f to tone,
+ 0.45f to tone,
+ 1f to PageFloor,
+ ),
+ ),
+ )
+ return
+ }
+
Box(
Modifier
.fillMaxSize()
@@ -2287,9 +3211,11 @@ private fun BottomBar(
) {
// Search sits outside the capsule as its own round button, the way the
// reference has it: it is a different kind of destination — you go there to
- // do something and come back — and giving it the same weight as Home and
- // Library made all three read as places.
- val routes = remember { listOf(Routes.HOME, Routes.LIBRARY) }
+ // do something and come back — and giving it the same weight as the places
+ // made all of them read as places.
+ val routes = remember {
+ listOf(Routes.HOME, Routes.NEW, Routes.RADIO, Routes.LIBRARY)
+ }
// The last tab that was actually on screen, held across screens that are not
// tabs at all — a playlist, the search page.
@@ -2335,7 +3261,7 @@ private fun BottomBar(
BottomItem(
stringResource(R.string.home),
PhosphorIcons.Fill.House,
- PhosphorIcons.Regular.House,
+ PhosphorIcons.Bold.House,
// Nothing is lit while the page on screen is not one of these
// two: search is a destination of its own, and leaving Home
// filled behind it said the app was somewhere it was not.
@@ -2343,11 +3269,23 @@ private fun BottomBar(
) {
onSelect(Routes.HOME)
}
+ BottomItem(
+ stringResource(R.string.tab_new),
+ PhosphorIcons.Fill.SquaresFour,
+ PhosphorIcons.Bold.SquaresFour,
+ routeIndex >= 0 && selected == 1,
+ ) { onSelect(Routes.NEW) }
+ BottomItem(
+ stringResource(R.string.tab_radio),
+ PhosphorIcons.Fill.Broadcast,
+ PhosphorIcons.Bold.Broadcast,
+ routeIndex >= 0 && selected == 2,
+ ) { onSelect(Routes.RADIO) }
BottomItem(
stringResource(R.string.library),
PhosphorIcons.Fill.MusicNotes,
- PhosphorIcons.Regular.MusicNotes,
- routeIndex >= 0 && selected == 1,
+ PhosphorIcons.Bold.MusicNotes,
+ routeIndex >= 0 && selected == 3,
) { onSelect(Routes.LIBRARY) }
}
}
@@ -2366,7 +3304,7 @@ private fun BottomBar(
// reads as clearer glass than the bar it sits next to.
) {
Icon(
- imageVector = if (searching) PhosphorIcons.Fill.MagnifyingGlass else PhosphorIcons.Regular.MagnifyingGlass,
+ imageVector = if (searching) PhosphorIcons.Fill.MagnifyingGlass else PhosphorIcons.Bold.MagnifyingGlass,
contentDescription = stringResource(R.string.search),
tint = Ink,
modifier = Modifier.size(24.dp),
@@ -2586,6 +3524,14 @@ private fun savedPlaybackSeed(context: android.content.Context): PlaybackState?
mediaId = track.uri,
title = track.name,
artist = track.artist,
+ // The record too, and not only for the caption under the title: it is
+ // what the other catalogue is searched by. Left out, the first lookup of
+ // every cold start went to the search-by-song fallback and came back
+ // with whichever release ranked first — a single, or a compilation —
+ // which is why a song could open under a different cover each time the
+ // app was started.
+ album = track.album,
+ albumUri = track.albumUri,
artworkUrl = track.artworkUrl,
durationMs = track.durationMs,
// Not "paused": what it is doing is unknown until the controller
@@ -2607,6 +3553,8 @@ private fun BarSearchField(
query: String,
onQuery: (String) -> Unit,
modifier: Modifier = Modifier,
+ /** The bar's own white, carrying the colour of the page behind it. */
+ ink: Color = Ink,
) {
val focus = remember { FocusRequester() }
LaunchedEffect(Unit) { runCatching { focus.requestFocus() } }
@@ -2616,17 +3564,17 @@ private fun BarSearchField(
verticalAlignment = Alignment.CenterVertically,
) {
Icon(
- PhosphorIcons.Regular.MagnifyingGlass,
+ PhosphorIcons.Bold.MagnifyingGlass,
contentDescription = null,
- tint = Ink.copy(alpha = 0.7f),
+ tint = ink.copy(alpha = 0.7f),
modifier = Modifier.size(20.dp),
)
BasicTextField(
value = query,
onValueChange = onQuery,
singleLine = true,
- textStyle = MaterialTheme.typography.bodyLarge.copy(color = Ink),
- cursorBrush = androidx.compose.ui.graphics.SolidColor(Ink),
+ textStyle = MaterialTheme.typography.bodyLarge.copy(color = ink),
+ cursorBrush = androidx.compose.ui.graphics.SolidColor(ink),
modifier = Modifier
.weight(1f)
.padding(start = 12.dp)
@@ -2636,7 +3584,7 @@ private fun BarSearchField(
Text(
stringResource(R.string.search_placeholder),
style = MaterialTheme.typography.bodyLarge,
- color = Ink.copy(alpha = 0.5f),
+ color = ink.copy(alpha = 0.5f),
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
diff --git a/app/src/main/java/dev/lelonio/square/ui/browse/NewScreen.kt b/app/src/main/java/dev/lelonio/square/ui/browse/NewScreen.kt
new file mode 100644
index 0000000..532b834
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/ui/browse/NewScreen.kt
@@ -0,0 +1,287 @@
+package dev.lelonio.square.ui.browse
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.PaddingValues
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.aspectRatio
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.lazy.LazyRow
+import androidx.compose.foundation.lazy.items
+import androidx.compose.foundation.lazy.itemsIndexed
+import androidx.compose.foundation.lazy.LazyListScope
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material3.CircularProgressIndicator
+import androidx.compose.material3.MaterialTheme
+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.res.stringResource
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import dev.lelonio.square.R
+import dev.lelonio.square.data.CatalogTrack
+import dev.lelonio.square.data.SearchItem
+import dev.lelonio.square.ui.MainViewModel
+import dev.lelonio.square.ui.components.Artwork
+import dev.lelonio.square.ui.glass.pressable
+import dev.lelonio.square.ui.theme.InkDim
+
+/**
+ * What has just come out, as a page rather than as one shelf on the home page.
+ *
+ * Laid out the way the reference lays this page out: a few records at the top
+ * drawn large enough to be an editorial choice rather than a result, then the
+ * songs out of them, then the week, then everything else. The order is how
+ * specific each part is — the picks are for this listener, the week is for
+ * everyone, and by the bottom it is a catalogue.
+ *
+ * The reference fills the rest of its page with charts, city charts and radio
+ * shows, none of which Spotify hands out to an application like this one. What
+ * is here is what can be answered honestly.
+ */
+@Composable
+fun NewScreen(
+ page: MainViewModel.NewPage,
+ contentPadding: PaddingValues,
+ onOpen: (SearchItem) -> Unit,
+ onPlaySong: (List<CatalogTrack>, Int) -> Unit,
+) {
+ val empty = page.hero.isEmpty() && page.thisWeek.isEmpty() && page.recent.isEmpty()
+ if (empty) {
+ Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
+ if (page.loading) {
+ CircularProgressIndicator(strokeWidth = 2.dp)
+ } else {
+ Text(
+ stringResource(R.string.nothing_here),
+ style = MaterialTheme.typography.bodyMedium,
+ color = InkDim,
+ )
+ }
+ }
+ return
+ }
+
+ LazyColumn(
+ contentPadding = PaddingValues(
+ top = contentPadding.calculateTopPadding() + 8.dp,
+ bottom = contentPadding.calculateBottomPadding(),
+ ),
+ ) {
+ item(contentType = "title") {
+ Text(
+ stringResource(R.string.tab_new),
+ style = MaterialTheme.typography.headlineMedium,
+ fontWeight = FontWeight.Bold,
+ modifier = Modifier.padding(start = 20.dp, top = 4.dp, bottom = 10.dp),
+ )
+ }
+
+ if (page.hero.isNotEmpty()) {
+ item(contentType = "hero") {
+ LazyRow(
+ contentPadding = PaddingValues(horizontal = 20.dp),
+ horizontalArrangement = Arrangement.spacedBy(14.dp),
+ ) {
+ items(page.hero, key = { it.uri }) { item ->
+ HeroCard(item) { onOpen(item) }
+ }
+ }
+ }
+ }
+
+ if (page.songs.isNotEmpty()) {
+ item(contentType = "songsHeading") { Heading(stringResource(R.string.new_songs)) }
+ songRows(page.songs, onPlaySong)
+ }
+
+ if (page.thisWeek.isNotEmpty()) {
+ item(contentType = "weekHeading") { Heading(stringResource(R.string.new_this_week)) }
+ item(contentType = "week") { Shelf(page.thisWeek, onOpen) }
+ }
+
+ if (page.recent.isNotEmpty()) {
+ item(contentType = "recentHeading") {
+ Heading(stringResource(R.string.new_releases_title))
+ }
+ item(contentType = "recent") { Shelf(page.recent, onOpen) }
+ }
+ }
+}
+
+/** The songs, one row each, played as a list rather than one at a time. */
+private fun LazyListScope.songRows(
+ songs: List<CatalogTrack>,
+ onPlay: (List<CatalogTrack>, Int) -> Unit,
+) {
+ itemsIndexed(
+ items = songs,
+ key = { _, track -> "song ${track.uri}" },
+ contentType = { _, _ -> "song" },
+ ) { index, track ->
+ SongRow(track) { onPlay(songs, index) }
+ }
+}
+
+/**
+ * A record the page is leading with.
+ *
+ * Wide rather than square: the reference's picks carry a line of editorial
+ * under them and read as a card, and a square cover in a row of square covers
+ * is a result no matter how large it is drawn.
+ */
+@Composable
+private fun HeroCard(item: SearchItem, onClick: () -> Unit) {
+ val shape = RoundedCornerShape(16.dp)
+ Column(
+ Modifier
+ .width(268.dp)
+ .clip(shape)
+ .background(Color.White.copy(alpha = 0.06f))
+ .pressable(onClick, shape = shape, pressedScale = 0.98f)
+ .padding(bottom = 14.dp),
+ ) {
+ Artwork(
+ url = item.artworkUrl,
+ title = item.title,
+ modifier = Modifier
+ .fillMaxWidth()
+ .aspectRatio(1f),
+ corner = 0.dp,
+ )
+ Text(
+ stringResource(R.string.new_release_tag).uppercase(),
+ style = MaterialTheme.typography.labelSmall,
+ fontSize = 10.sp,
+ fontWeight = FontWeight.Bold,
+ color = MaterialTheme.colorScheme.primary,
+ modifier = Modifier.padding(start = 14.dp, end = 14.dp, top = 12.dp),
+ )
+ Text(
+ item.title,
+ style = MaterialTheme.typography.titleMedium,
+ fontWeight = FontWeight.SemiBold,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ modifier = Modifier.padding(horizontal = 14.dp),
+ )
+ if (item.subtitle.isNotBlank()) {
+ Text(
+ item.subtitle,
+ style = MaterialTheme.typography.bodySmall,
+ color = InkDim,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ modifier = Modifier.padding(horizontal = 14.dp),
+ )
+ }
+ }
+}
+
+/** A row of records, scrolled sideways. */
+@Composable
+private fun Shelf(items: List<SearchItem>, onOpen: (SearchItem) -> Unit) {
+ LazyRow(
+ contentPadding = PaddingValues(horizontal = 20.dp),
+ horizontalArrangement = Arrangement.spacedBy(14.dp),
+ ) {
+ items(items, key = { it.uri }) { item ->
+ Column(
+ Modifier
+ .width(146.dp)
+ .pressable({ onOpen(item) }, pressedScale = 0.97f),
+ ) {
+ Artwork(
+ url = item.artworkUrl,
+ title = item.title,
+ modifier = Modifier
+ .fillMaxWidth()
+ .aspectRatio(1f),
+ corner = 10.dp,
+ decodeSize = 146.dp,
+ )
+ Text(
+ item.title,
+ style = MaterialTheme.typography.bodyMedium,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ modifier = Modifier.padding(top = 8.dp),
+ )
+ if (item.subtitle.isNotBlank()) {
+ Text(
+ item.subtitle,
+ style = MaterialTheme.typography.bodySmall,
+ color = InkDim,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ )
+ }
+ }
+ }
+ }
+}
+
+/** One new song, in the same shape the track lists everywhere else use. */
+@Composable
+private fun SongRow(track: CatalogTrack, onClick: () -> Unit) {
+ val shape = RoundedCornerShape(12.dp)
+ Row(
+ Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 18.dp, vertical = 2.dp)
+ .clip(shape)
+ .pressable(onClick, shape = shape, pressedScale = 0.985f)
+ .padding(horizontal = 6.dp, vertical = 8.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ Artwork(
+ url = track.artworkUrl,
+ title = track.name,
+ modifier = Modifier.size(46.dp),
+ corner = 8.dp,
+ decodeSize = 46.dp,
+ )
+ Column(
+ Modifier
+ .weight(1f)
+ .padding(start = 14.dp),
+ ) {
+ Text(
+ track.name,
+ style = MaterialTheme.typography.titleMedium,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ )
+ Text(
+ track.artist,
+ style = MaterialTheme.typography.bodySmall,
+ color = InkDim,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ )
+ }
+ }
+}
+
+@Composable
+private fun Heading(text: String) {
+ Text(
+ text,
+ style = MaterialTheme.typography.titleLarge,
+ fontWeight = FontWeight.Bold,
+ modifier = Modifier.padding(start = 20.dp, end = 20.dp, top = 26.dp, bottom = 10.dp),
+ )
+}
diff --git a/app/src/main/java/dev/lelonio/square/ui/browse/RadioScreen.kt b/app/src/main/java/dev/lelonio/square/ui/browse/RadioScreen.kt
new file mode 100644
index 0000000..28cec09
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/ui/browse/RadioScreen.kt
@@ -0,0 +1,191 @@
+package dev.lelonio.square.ui.browse
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.PaddingValues
+import androidx.compose.foundation.layout.aspectRatio
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.lazy.grid.GridCells
+import androidx.compose.foundation.lazy.grid.GridItemSpan
+import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
+import androidx.compose.foundation.lazy.grid.items
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material3.CircularProgressIndicator
+import androidx.compose.material3.Icon
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Brush
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import com.adamglin.PhosphorIcons
+import com.adamglin.phosphoricons.Fill
+import com.adamglin.phosphoricons.fill.Broadcast
+import dev.lelonio.square.R
+import dev.lelonio.square.data.CatalogTrack
+import dev.lelonio.square.ui.components.Artwork
+import dev.lelonio.square.ui.glass.pressable
+import dev.lelonio.square.ui.theme.InkDim
+
+/**
+ * Radio: one station per artist the account actually listens to.
+ *
+ * Spotify has no "browse radio" of its own to read, so the page is built rather
+ * than fetched. Every station is seeded from a song — `spotify:station:track:…`
+ * is the one form the access point reliably answers — and named after the
+ * artist, because two stations seeded from two songs by the same person are the
+ * same station to a listener, and "Radio" alone names the feature rather than
+ * the station.
+ *
+ * One card per artist for that reason: seeds are taken from the account's most
+ * played songs, and those repeat the same names over and over.
+ */
+@Composable
+fun RadioScreen(
+ /** Seeds, already reduced to one per artist by the caller. */
+ seeds: List<CatalogTrack>,
+ loading: Boolean,
+ contentPadding: PaddingValues,
+ onOpen: (CatalogTrack) -> Unit,
+) {
+ if (seeds.isEmpty()) {
+ Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
+ if (loading) {
+ CircularProgressIndicator(strokeWidth = 2.dp)
+ } else {
+ Text(
+ stringResource(R.string.radio_empty),
+ style = MaterialTheme.typography.bodyMedium,
+ color = InkDim,
+ textAlign = TextAlign.Center,
+ modifier = Modifier.padding(horizontal = 40.dp),
+ )
+ }
+ }
+ return
+ }
+
+ LazyVerticalGrid(
+ columns = GridCells.Fixed(2),
+ contentPadding = PaddingValues(
+ start = 16.dp,
+ end = 16.dp,
+ top = contentPadding.calculateTopPadding() + 8.dp,
+ bottom = contentPadding.calculateBottomPadding(),
+ ),
+ horizontalArrangement = Arrangement.spacedBy(14.dp),
+ verticalArrangement = Arrangement.spacedBy(18.dp),
+ ) {
+ item(span = { GridItemSpan(maxLineSpan) }) {
+ Text(
+ stringResource(R.string.tab_radio),
+ style = MaterialTheme.typography.headlineMedium,
+ fontWeight = FontWeight.Bold,
+ modifier = Modifier.padding(top = 4.dp, bottom = 6.dp),
+ )
+ }
+
+ item(span = { GridItemSpan(maxLineSpan) }) {
+ Text(
+ stringResource(R.string.stations_for_you),
+ style = MaterialTheme.typography.titleLarge,
+ fontWeight = FontWeight.Bold,
+ modifier = Modifier.padding(bottom = 2.dp),
+ )
+ }
+
+ items(seeds, key = { it.uri }) { seed ->
+ StationTile(seed) { onOpen(seed) }
+ }
+ }
+}
+
+/**
+ * A station, drawn as the thing it plays rather than as a list icon.
+ *
+ * The cover of the song it grew from, darkened, with the artist's name over it:
+ * a grid of identical broadcast glyphs would be unreadable, and the cover is
+ * what makes one station recognisable at a glance.
+ */
+@Composable
+private fun StationTile(seed: CatalogTrack, onClick: () -> Unit) {
+ val shape = RoundedCornerShape(14.dp)
+ Box(
+ Modifier
+ .fillMaxWidth()
+ .aspectRatio(1f)
+ .clip(shape)
+ .pressable(onClick, shape = shape, pressedScale = 0.97f),
+ ) {
+ Artwork(
+ url = seed.artworkUrl,
+ title = seed.artist,
+ modifier = Modifier.fillMaxSize(),
+ corner = 0.dp,
+ )
+
+ Box(
+ Modifier
+ .fillMaxSize()
+ .background(
+ Brush.verticalGradient(
+ 0f to Color.Black.copy(alpha = 0.15f),
+ 0.45f to Color.Black.copy(alpha = 0.45f),
+ 1f to Color.Black.copy(alpha = 0.8f),
+ ),
+ ),
+ )
+
+ Box(
+ Modifier
+ .align(Alignment.TopStart)
+ .padding(10.dp)
+ .size(28.dp)
+ .clip(CircleShape)
+ .background(Color.White.copy(alpha = 0.18f)),
+ contentAlignment = Alignment.Center,
+ ) {
+ Icon(
+ PhosphorIcons.Fill.Broadcast,
+ contentDescription = null,
+ tint = Color.White,
+ modifier = Modifier.size(15.dp),
+ )
+ }
+
+ Column(
+ Modifier
+ .align(Alignment.BottomStart)
+ .padding(12.dp),
+ ) {
+ Text(
+ stringResource(R.string.radio_of, seed.artist),
+ style = MaterialTheme.typography.titleSmall,
+ fontWeight = FontWeight.SemiBold,
+ color = Color.White,
+ maxLines = 2,
+ overflow = TextOverflow.Ellipsis,
+ )
+ Text(
+ seed.name,
+ style = MaterialTheme.typography.bodySmall,
+ color = Color.White.copy(alpha = 0.7f),
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ )
+ }
+ }
+}
diff --git a/app/src/main/java/dev/lelonio/square/ui/components/Artwork.kt b/app/src/main/java/dev/lelonio/square/ui/components/Artwork.kt
index 0870663..4699ad4 100644
--- a/app/src/main/java/dev/lelonio/square/ui/components/Artwork.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/components/Artwork.kt
@@ -7,6 +7,12 @@ import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
+import androidx.compose.animation.core.animateFloatAsState
+import androidx.compose.animation.core.tween
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
@@ -52,6 +58,26 @@ fun Artwork(
* rows of it is what makes a list stutter.
*/
decodeSize: Dp = 0.dp,
+ /**
+ * How long a new picture takes to replace the one before it.
+ *
+ * Zero in lists, and deliberately: a crossfade animates every row that
+ * scrolls into view, which is exactly when frames are scarcest. Somewhere
+ * that shows one picture the size of the screen, and sometimes replaces it
+ * with a better copy of the same thing, wants the opposite.
+ */
+ crossfadeMs: Int = 0,
+ /**
+ * Whether a missing picture is worth drawing a stand-in for.
+ *
+ * A row with no cover needs one: the alternative is a hole in a list. A
+ * screen that is *about* to have a picture does not — the generated tile is
+ * a large letter in the middle of the screen, and a letter that appears for
+ * half a second on every track change and is then replaced by the artwork
+ * reads as a fault. Where the wait is known to be short, the ground under
+ * it is the better placeholder.
+ */
+ fallback: Boolean = true,
) {
val shape = remember(corner) { RoundedCornerShape(corner) }
val context = LocalContext.current
@@ -62,10 +88,16 @@ fun Artwork(
DownloadsCover()
} else if (url == dev.lelonio.square.data.LocalLibrary.COVER) {
LocalFilesCover()
- } else if (url != null) {
- val request = remember(url, decodeSize) {
+ } else if (url != null && (!offlineOnly() || isOnThisPhone(url))) {
+ // Offline the url is not something that can be fetched, so what is
+ // handed to the loader is the copy on the disk. Online the url
+ // stays: covers are kept keyed on the picture rather than its size,
+ // so the file behind a url may be a smaller print of it, and a page
+ // that can fetch the large one should.
+ val source = remember(url) { artSource(url) }
+ val request = remember(source, decodeSize, crossfadeMs) {
ImageRequest.Builder(context)
- .data(url)
+ .data(source)
.scale(Scale.FILL)
.apply {
if (decodeSize > 0.dp) {
@@ -73,19 +105,46 @@ fun Artwork(
size(px, px)
}
}
- // No crossfade: it animates every row that scrolls into view,
- // which is exactly when frames are scarcest.
+ // The fade is done here rather than by the loader; see
+ // below.
.crossfade(false)
.build()
}
+ // Faded in by hand, and deliberately.
+ //
+ // The loader's own crossfade is skipped whenever the picture comes
+ // out of memory — which, since the next song's cover is fetched
+ // while the current one plays, is exactly the case that matters:
+ // the artwork appeared with a cut while everything around it was
+ // still animating, and arrived before the colour it is supposed to
+ // bring with it. An animation of our own does not care where the
+ // bytes came from.
+ var arrived by remember(source) { mutableStateOf(false) }
+ val appear by animateFloatAsState(
+ targetValue = if (arrived || crossfadeMs <= 0) 1f else 0f,
+ animationSpec = tween(crossfadeMs),
+ label = "artwork",
+ )
+
AsyncImage(
model = request,
contentDescription = null,
contentScale = ContentScale.Crop,
- modifier = Modifier.fillMaxSize(),
+ onState = { state ->
+ if (state is coil.compose.AsyncImagePainter.State.Success) arrived = true
+ },
+ modifier = Modifier
+ .fillMaxSize()
+ .then(
+ if (crossfadeMs > 0) {
+ Modifier.graphicsLayer { alpha = appear }
+ } else {
+ Modifier
+ }
+ ),
)
- } else {
+ } else if (fallback) {
GeneratedCover(title, corner)
}
}
@@ -129,6 +188,42 @@ private fun LocalFilesCover() {
}
/** The two colours of that tile, deep enough to sit in a grid of covers. */
+/**
+ * What the image loader should actually be handed for a picture.
+ *
+ * Online, the url: covers are kept keyed on the picture rather than on its
+ * size, so the file behind a url may be a smaller print of the same artwork,
+ * and a screen that can fetch the large one should. Offline the url is nothing
+ * that can be fetched, and the copy on the disk is the only picture there is.
+ */
+fun artSource(url: String): Any =
+ if (!offlineOnly()) url
+ else dev.lelonio.square.download.DownloadExtras.fileOf(url, "art") ?: url
+
+/**
+ * Whether only what is already here may be drawn.
+ *
+ * Offline a url handed to the loader is a request going out on a connection the
+ * app has been told it does not have — and on a metered one, somebody's data.
+ */
+private fun offlineOnly(): Boolean =
+ dev.lelonio.square.playback.OfflineMode.active.value
+
+/**
+ * Whether this picture is on the phone already.
+ *
+ * A file path counts as much as a saved copy does, and missing that was a bug
+ * of its own: the notification and the player are handed the local file
+ * directly — that is how a downloaded song shows its sleeve on the lock screen
+ * — and a check that only knew how to look up remote urls decided those were
+ * unavailable and drew a generated tile over a picture sitting on the disk.
+ */
+private fun isOnThisPhone(url: String): Boolean =
+ url.startsWith("file:") ||
+ url.startsWith("/") ||
+ url.startsWith("content:") ||
+ dev.lelonio.square.download.DownloadExtras.fileOf(url, "art") != null
+
/** The shelf of songs downloaded on their own; see DownloadStore.SINGLES. */
const val DOWNLOADS_COVER = "square:downloads-cover"
diff --git a/app/src/main/java/dev/lelonio/square/ui/components/HeroBackdrop.kt b/app/src/main/java/dev/lelonio/square/ui/components/HeroBackdrop.kt
new file mode 100644
index 0000000..bcc1ed2
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/ui/components/HeroBackdrop.kt
@@ -0,0 +1,183 @@
+package dev.lelonio.square.ui.components
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.aspectRatio
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.drawWithContent
+import androidx.compose.ui.graphics.BlendMode
+import androidx.compose.ui.graphics.Brush
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.CompositingStrategy
+import androidx.compose.ui.graphics.graphicsLayer
+import androidx.compose.ui.layout.ContentScale
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.unit.dp
+import coil.compose.AsyncImage
+import coil.request.ImageRequest
+
+/**
+ * A picture that stops being a picture on its way down the screen.
+ *
+ * Two copies of the same image: the sharp one, and over its lower half a
+ * blurred one that fades in, and then the page's own colour arriving under
+ * that. It is what makes a photograph dissolve into a page instead of ending —
+ * a straight fade to a flat colour leaves the image crisp right up to the point
+ * where it vanishes, which reads as a photo behind a curtain.
+ *
+ * Shared by the pages that are made of one picture — an artist, a record, a
+ * list — and by the player when the track has nothing moving to show. One
+ * treatment, so the cover looks the same wherever the app puts it up large.
+ *
+ * Blurred at decode time rather than with `Modifier.blur`: that modifier is a
+ * render effect over the whole layer, re-run on every frame the layer changes,
+ * and this sits under everything.
+ */
+@Composable
+fun HeroBackdrop(
+ artworkUrl: String?,
+ /** Named for the description a reader hears; the picture is decorative. */
+ title: String,
+ /** The tone the picture ends on, which is the page's own. */
+ pageColor: Color,
+ modifier: Modifier = Modifier,
+ /** The cover as a moving picture, where there is one; see [MotionCover]. */
+ motionUrl: String? = null,
+ /**
+ * Whether the picture is still being looked up.
+ *
+ * While it is, nothing stands in for it: see [Artwork]'s `fallback`. The
+ * page colour is already drawn under this, so the wait reads as a header
+ * that has not finished arriving rather than as a song with no cover.
+ */
+ pending: Boolean = false,
+ /** Where the blurred copy starts and where it is complete, top to bottom. */
+ softenFrom: Float = 0.42f,
+ softenTo: Float = 0.72f,
+ /**
+ * The picture's own proportions, when it is to be shown at them.
+ *
+ * Null crops it to fill whatever it is given, which is right for a header
+ * measured in advance. A number lays it across the top at that ratio
+ * instead, untouched: a picture drawn for a record is a composition, and
+ * cropping it to a phone's shape enlarges it and cuts the sides off the
+ * thing somebody framed.
+ */
+ imageAspect: Float? = null,
+) {
+ Box(modifier) {
+ if (imageAspect != null) {
+ // The colour first, because the picture no longer covers the slot.
+ Box(Modifier.fillMaxSize().background(pageColor))
+ }
+ Box(
+ Modifier
+ .fillMaxWidth()
+ .then(
+ if (imageAspect != null) {
+ Modifier.aspectRatio(imageAspect)
+ } else {
+ Modifier.fillMaxSize()
+ },
+ )
+ .align(Alignment.TopCenter),
+ ) {
+ Artwork(
+ url = artworkUrl,
+ title = title,
+ modifier = Modifier.fillMaxSize(),
+ corner = 0.dp,
+ // One picture, sometimes replaced by a better copy of itself — the
+ // catalogue's scan arriving after the one the queue carried. A cut
+ // between two versions of the same artwork is the most visible
+ // change this screen ever makes; a fade makes it a refinement.
+ crossfadeMs = SWAP_MS,
+ fallback = !pending,
+ )
+
+ // The moving cover over the still one, which stays underneath as what is
+ // shown until the first frame arrives.
+ if (motionUrl != null) {
+ MotionCover(url = motionUrl, modifier = Modifier.fillMaxSize())
+ }
+
+ if (artworkUrl != null) {
+ AsyncImage(
+ model = ImageRequest.Builder(LocalContext.current)
+ // The same picture the sharp copy above draws, which
+ // offline is the file on the disk rather than the url.
+ .data(artSource(artworkUrl))
+ .size(HERO_BLUR_PX)
+ .transformations(HeroBlur)
+ // A hardware bitmap cannot be read back, and the blur reads
+ // every pixel of it.
+ .allowHardware(false)
+ .crossfade(true)
+ .build(),
+ contentDescription = null,
+ contentScale = ContentScale.Crop,
+ modifier = Modifier
+ .fillMaxSize()
+ // Its own layer, so the mask below erases this copy alone
+ // and not the sharp one underneath it.
+ .graphicsLayer { compositingStrategy = CompositingStrategy.Offscreen }
+ .drawWithContent {
+ drawContent()
+ drawRect(
+ brush = Brush.verticalGradient(
+ 0f to Color.Transparent,
+ softenFrom to Color.Transparent,
+ softenTo to Color.Black,
+ 1f to Color.Black,
+ ),
+ blendMode = BlendMode.DstIn,
+ )
+ },
+ )
+ }
+
+ // And the colour, arriving under the blur. It ends on the page's own
+ // tone rather than on black: the last row of the picture and the first
+ // row of the background are then the same colour, which is what leaves
+ // no seam to find.
+ Box(
+ Modifier
+ .fillMaxSize()
+ .background(
+ Brush.verticalGradient(
+ // Tied to where the picture is being softened rather
+ // than to fixed fractions. With them, a picture asked to
+ // stay sharp most of the way down was still being washed
+ // out from halfway — the colour arrived on its own
+ // schedule and paled the very part that was meant to be
+ // legible.
+ 0f to Color.Black.copy(alpha = 0.22f),
+ (softenFrom * 0.45f) to Color.Transparent,
+ softenFrom to pageColor.copy(alpha = 0.12f),
+ ((softenFrom + softenTo) / 2f) to pageColor.copy(alpha = 0.55f),
+ // Opaque at the end of the softening, not nearly
+ // opaque: the last few percent of the picture were
+ // showing through, and a picture that is still faintly
+ // there has an edge — which is the seam this whole
+ // gradient exists to remove.
+ softenTo to pageColor,
+ 1f to pageColor,
+ ),
+ ),
+ )
+ }
+ }
+}
+
+/** How long a better copy of the same picture takes to arrive. */
+private const val SWAP_MS = 450
+
+/** Decode size for the soft copy, in pixels. */
+private const val HERO_BLUR_PX = 240
+
+/** Soft enough to be a wash, sharp enough to keep the picture's shapes. */
+private val HeroBlur = BlurTransformation(radius = 10, passes = 2)
diff --git a/app/src/main/java/dev/lelonio/square/ui/components/MotionCover.kt b/app/src/main/java/dev/lelonio/square/ui/components/MotionCover.kt
new file mode 100644
index 0000000..f53433d
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/ui/components/MotionCover.kt
@@ -0,0 +1,92 @@
+package dev.lelonio.square.ui.components
+
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.DisposableEffect
+import androidx.compose.runtime.remember
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.platform.LocalLifecycleOwner
+import androidx.compose.ui.viewinterop.AndroidView
+import androidx.lifecycle.Lifecycle
+import androidx.lifecycle.LifecycleEventObserver
+import androidx.media3.common.AudioAttributes
+import androidx.media3.common.MediaItem
+import androidx.media3.common.Player
+import androidx.media3.exoplayer.ExoPlayer
+import androidx.media3.ui.AspectRatioFrameLayout
+import androidx.media3.ui.PlayerView
+
+/**
+ * A cover that moves.
+ *
+ * Some records have one: a few seconds of the sleeve animating, which the
+ * reference plays at the top of the page instead of showing a still. It is a
+ * picture, not a video — there is no sound, no controls, and it loops.
+ *
+ * Its own player rather than the app's. The one in the service is what the
+ * listener is playing and is bound to a media session, a notification and the
+ * car; handing it a silent loop of album art would replace the song on the lock
+ * screen. This one holds no audio focus and is released with the screen.
+ */
[email protected](androidx.media3.common.util.UnstableApi::class)
+@Composable
+fun MotionCover(url: String, modifier: Modifier = Modifier) {
+ val context = LocalContext.current
+
+ val player = remember(url) {
+ ExoPlayer.Builder(context).build().apply {
+ // Explicitly not asking for focus: what is playing keeps playing.
+ setAudioAttributes(AudioAttributes.DEFAULT, false)
+ volume = 0f
+ repeatMode = Player.REPEAT_MODE_ALL
+ setMediaItem(MediaItem.fromUri(url))
+ playWhenReady = true
+ prepare()
+ }
+ }
+
+ // Stopped while the app is away. A loop nobody is looking at is a radio
+ // that costs battery and data for a picture on a screen that is off.
+ val lifecycle = LocalLifecycleOwner.current.lifecycle
+ DisposableEffect(lifecycle, player) {
+ val observer = LifecycleEventObserver { _, event ->
+ when (event) {
+ Lifecycle.Event.ON_STOP -> player.pause()
+ Lifecycle.Event.ON_START -> player.play()
+ else -> Unit
+ }
+ }
+ lifecycle.addObserver(observer)
+ onDispose {
+ lifecycle.removeObserver(observer)
+ player.release()
+ }
+ }
+
+ AndroidView(
+ factory = { ctx ->
+ // Inflated, for the surface type; see the layout's own note. Built
+ // in code this is a SurfaceView — a second window under the app's,
+ // which does not fade or move with the composition, so a page
+ // leaving the screen left its video behind for a moment after
+ // everything else had gone.
+ val view = android.view.LayoutInflater.from(ctx)
+ .inflate(dev.lelonio.square.R.layout.motion_cover, null) as PlayerView
+ view.apply {
+ useController = false
+ // Filling the frame, cropping what does not fit: the header is
+ // whatever shape the phone is, and letterboxing a cover leaves
+ // two bars of black across the top of the page.
+ resizeMode = AspectRatioFrameLayout.RESIZE_MODE_ZOOM
+ setShutterBackgroundColor(android.graphics.Color.TRANSPARENT)
+ setBackgroundColor(android.graphics.Color.TRANSPARENT)
+ this.player = player
+ }
+ },
+ update = { it.player = player },
+ // Released with the composition rather than left to the view pool: the
+ // surface has to go when the page does.
+ onRelease = { it.player = null },
+ modifier = modifier,
+ )
+}
diff --git a/app/src/main/java/dev/lelonio/square/ui/glass/LiquidBottomTabs.kt b/app/src/main/java/dev/lelonio/square/ui/glass/LiquidBottomTabs.kt
index fd99979..7422c3b 100644
--- a/app/src/main/java/dev/lelonio/square/ui/glass/LiquidBottomTabs.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/glass/LiquidBottomTabs.kt
@@ -98,6 +98,15 @@ fun LiquidBottomTabs(
// indicator claimed the app was somewhere it was not. Faded rather than
// removed, so it comes back where it left and the drag target stays alive.
indicatorVisible: Boolean = true,
+ /**
+ * LOCAL CHANGE: what the moving indicator is filled with.
+ *
+ * Upstream lightens the slot it marks — white at a tenth on a dark bar. The
+ * reference this app is matched against does the opposite: it sinks the lit
+ * slot into the bar, so the mark is darker than the glass around it. Null
+ * keeps upstream's.
+ */
+ indicatorColor: Color? = null,
content: @Composable RowScope.() -> Unit
) {
val isLightTheme = !isSystemInDarkTheme()
@@ -322,7 +331,7 @@ fun LiquidBottomTabs(
onDrawSurface = {
val progress = dampedDragAnimation.pressProgress
drawRect(
- if (isLightTheme) Color.Black.copy(0.1f)
+ indicatorColor ?: if (isLightTheme) Color.Black.copy(0.1f)
else Color.White.copy(0.1f),
alpha = 1f - progress
)
diff --git a/app/src/main/java/dev/lelonio/square/ui/glass/NavTransitionFreeze.kt b/app/src/main/java/dev/lelonio/square/ui/glass/NavTransitionFreeze.kt
new file mode 100644
index 0000000..f2548fb
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/ui/glass/NavTransitionFreeze.kt
@@ -0,0 +1,52 @@
+package dev.lelonio.square.ui.glass
+
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.remember
+
+/**
+ * Holds the app's glass still while one screen is replacing another.
+ *
+ * The page backdrop is a recorded layer, and every frame that layer changes it
+ * is captured again for the surfaces that refract it — the bars, the sheets,
+ * the buttons. Scrolling already stops that: the tab bar's scroll connection
+ * says when a list is moving and the glass reuses its last capture until it
+ * settles. A navigation is neither a scroll nor a fling, so nothing covered it,
+ * and every push and pop paid a full re-record on every frame of its own
+ * animation — which is exactly when the phone has the least to spare.
+ *
+ * Timed rather than tied to the transition itself: Navigation's own
+ * `AnimatedContent` does not offer the call site a "running" flag, and the
+ * durations here are fixed constants, so a window is enough. It must cover the
+ * longest of them and no more — thawing early puts the cost back where it
+ * hurts, and freezing late is stale content behind the glass, which is visible.
+ *
+ * Read during draw, from a plain field rather than snapshot state: a state read
+ * in a draw-phase provider invalidates the frame that read it, which is a
+ * redraw that never stops.
+ */
+class NavTransitionFreeze {
+ private var startedAtNs = 0L
+
+ val frozen: () -> Boolean = {
+ val started = startedAtNs
+ started != 0L && System.nanoTime() - started < WINDOW_NS
+ }
+
+ fun mark() {
+ startedAtNs = System.nanoTime()
+ }
+
+ private companion object {
+ /** The longest transition in the app plus slop for frame delivery. */
+ const val WINDOW_NS = 330_000_000L
+ }
+}
+
+/** Starts the window again every time [key] changes — a route, or a page. */
+@Composable
+fun rememberNavTransitionFreeze(key: Any?): NavTransitionFreeze {
+ val freeze = remember { NavTransitionFreeze() }
+ LaunchedEffect(key) { freeze.mark() }
+ return freeze
+}
diff --git a/app/src/main/java/dev/lelonio/square/ui/glass/ScrollActivity.kt b/app/src/main/java/dev/lelonio/square/ui/glass/ScrollActivity.kt
new file mode 100644
index 0000000..7c6c634
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/ui/glass/ScrollActivity.kt
@@ -0,0 +1,93 @@
+package dev.lelonio.square.ui.glass
+
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
+import androidx.compose.ui.input.nestedscroll.NestedScrollSource
+import androidx.compose.ui.unit.Velocity
+
+/**
+ * Whether a page is being scrolled right now.
+ *
+ * The glass surfaces ask this during draw and stop re-sampling the page while
+ * it moves; see LocalGlassFrozen. It used to be a flag on the tab bar's own
+ * scroll connection — a local addition to a vendored library — which meant the
+ * library could not be updated without carrying it forward. This is the same
+ * flag, kept where it belongs: a connection of this app's own, chained beside
+ * the bar's rather than welded into it.
+ *
+ * Deliberately consumes nothing. Every callback reports what it saw and returns
+ * zero, so the list scrolls exactly as it would with nothing attached.
+ */
+class ScrollActivity(
+ /** Called once a scroll down has gone far enough to fold the bar. */
+ private val onFold: () -> Unit = {},
+ /** Called when a scroll up arrives with nowhere left to go: the top. */
+ private val onTop: () -> Unit = {},
+ /** How far down the page has to move before the bar folds. */
+ private val foldThresholdPx: Float = 0f,
+) : NestedScrollConnection {
+
+ private var downwards = 0f
+
+ /**
+ * Read during draw, so it is a plain field rather than a state.
+ *
+ * Nothing recomposes when it changes — the surfaces that care call it back
+ * on their own frame — which is the point: a scroll would otherwise
+ * recompose the whole window twice, once to say it started and once to say
+ * it stopped.
+ */
+ var scrolling: Boolean = false
+ private set
+
+ override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
+ if (available.y != 0f) scrolling = true
+
+ // Folding is a matter of travel, not of direction alone: a few pixels
+ // either way while a finger settles must not close the bar.
+ if (available.y < 0f) {
+ downwards += -available.y
+ if (foldThresholdPx > 0f && downwards >= foldThresholdPx) {
+ downwards = 0f
+ onFold()
+ }
+ } else if (available.y > 0f) {
+ downwards = 0f
+ }
+ return Offset.Zero
+ }
+
+ /**
+ * What is left of a scroll once the page has taken its share.
+ *
+ * A page that is already at its top consumes nothing of a downward drag, so
+ * the whole of it arrives here — which is the one moment that means "the
+ * top", and the only one the bar opens on. Anything less and the bar came
+ * back on any small upward flick, halfway down a list, over the very rows
+ * the reader was going back to.
+ */
+ override fun onPostScroll(
+ consumed: Offset,
+ available: Offset,
+ source: NestedScrollSource,
+ ): Offset {
+ if (available.y > 0f) onTop()
+ return Offset.Zero
+ }
+
+ override suspend fun onPreFling(available: Velocity): Velocity {
+ scrolling = true
+ return Velocity.Zero
+ }
+
+ /**
+ * A fling ends here, and so does a drag that never became one.
+ *
+ * The frames right after are the ones worth having sharp again: the page has
+ * stopped and the glass is being looked at rather than moved.
+ */
+ override suspend fun onPostFling(consumed: Velocity, available: Velocity): Velocity {
+ scrolling = false
+ return Velocity.Zero
+ }
+}
diff --git a/app/src/main/java/dev/lelonio/square/ui/glass/backdrop/catalog/components/LiquidBottomTabs.kt b/app/src/main/java/dev/lelonio/square/ui/glass/backdrop/catalog/components/LiquidBottomTabs.kt
index c8b38db..29bc240 100644
--- a/app/src/main/java/dev/lelonio/square/ui/glass/backdrop/catalog/components/LiquidBottomTabs.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/glass/backdrop/catalog/components/LiquidBottomTabs.kt
@@ -84,13 +84,22 @@ fun LiquidBottomTabs(
// Nav-bar pill defaults; pass a caller color/height to blend into a
// specific screen (e.g. that screen's own hero tint) instead.
containerColor: Color? = null,
+ /**
+ * LOCAL CHANGE: the colour the selected tab is drawn in.
+ *
+ * Upstream picks a system blue. This app has one accent — the colour the
+ * cover gave the theme — and a bar that keeps its own says the app is two
+ * things. Null keeps upstream's.
+ */
+ accentColor: Color? = null,
height: Dp = 64.dp,
content: @Composable RowScope.() -> Unit
) {
val isLightTheme = !isSystemInDarkTheme()
- val accentColor =
+ val resolvedAccentColor = accentColor ?: (
if (isLightTheme) Color(0xFF0088FF)
else Color(0xFF0091FF)
+ )
val resolvedContainerColor = containerColor ?: (
if (isLightTheme) Color(0xFFFAFAFA).copy(0.4f)
else Color(0xFF121212).copy(0.4f)
@@ -246,7 +255,7 @@ fun LiquidBottomTabs(
.height(innerHeight)
.fillMaxWidth()
.padding(horizontal = 4f.dp)
- .graphicsLayer(colorFilter = ColorFilter.tint(accentColor)),
+ .graphicsLayer(colorFilter = ColorFilter.tint(resolvedAccentColor)),
verticalAlignment = Alignment.CenterVertically,
content = content
)
diff --git a/app/src/main/java/dev/lelonio/square/ui/glass/floatingtabbar/FloatingTabBar.kt b/app/src/main/java/dev/lelonio/square/ui/glass/floatingtabbar/FloatingTabBar.kt
index 1026f11..06ac06e 100644
--- a/app/src/main/java/dev/lelonio/square/ui/glass/floatingtabbar/FloatingTabBar.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/glass/floatingtabbar/FloatingTabBar.kt
@@ -1,32 +1,25 @@
-@file:OptIn(ExperimentalSharedTransitionApi::class)
-
/*
- * FloatingTabBar v1.0.1 by Elyes Mansour
+ * FloatingTabBar by Elyes Mansour
* https://github.com/elyesmansour/compose-floating-tab-bar
* Licensed under the Apache License, Version 2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
- * Vendored from the v1.0.1 tag: the published AAR is compiled against
- * Compose 1.8 and crashes with NoSuchMethodError on
- * SharedTransitionScope.sharedElement under the Compose version this app uses.
- * Compiling the source here keeps it binary-compatible.
+ * Vendored from the repository's main branch rather than taken as a
+ * dependency: the published AAR is compiled against a Compose version this app
+ * does not use, and it crashes with NoSuchMethodError on
+ * SharedTransitionScope.sharedElement. Compiling the source here keeps it
+ * binary-compatible.
*
- * Local modifications on top of v1.0.1:
- * - Package renamed.
- * - InlineBar/ExpandedBar use Row/Column instead of ConstraintLayout, and the
- * tab pill + standalone tab cluster is centered (iOS 26 style) instead of
- * being pinned to opposite screen edges.
- * - The inline/expanded AnimatedContent is center-aligned so the collapse
- * animation morphs around the center instead of the start edge.
- * - ExpandedTabs grew a draggable selection puck ported from Kyant0's
- * AndroidLiquidGlass catalog (LiquidBottomTabs/LiquidBottomTab): equal-width
- * tabs, a spring-damped indicator you can press-drag between tabs (release
- * snaps to and navigates the nearest tab), a finger-tracking glow, and —
- * when an optional [Backdrop] is supplied — chromatic lens refraction and
- * an accent-tinted glass sample of the selected tab's icon showing through
- * the puck. See [DampedDragAnimation] and [InteractiveHighlight].
+ * Kept as close to upstream as it can be. The library animates the fold itself
+ * — shared bounds on a spring, with the crossfade only clearing away what has
+ * no counterpart in the other state — and every local attempt to describe that
+ * movement by hand made it worse. What this app adds goes through the seams the
+ * library already has: the glass through tabBarContentModifier, the selection
+ * shape through colors.selectedTabBackgroundColor.
*/
+@file:OptIn(ExperimentalSharedTransitionApi::class)
+
package dev.lelonio.square.ui.glass.floatingtabbar
import androidx.compose.animation.AnimatedContent
@@ -35,13 +28,13 @@ import androidx.compose.animation.EnterExitState
import androidx.compose.animation.ExperimentalSharedTransitionApi
import androidx.compose.animation.SharedTransitionLayout
import androidx.compose.animation.SharedTransitionScope
-import androidx.compose.animation.core.Animatable
-import androidx.compose.animation.core.EaseOut
+import androidx.compose.animation.animateColorAsState
+import androidx.compose.animation.animateContentSize
import androidx.compose.animation.core.FastOutSlowInEasing
+import androidx.compose.animation.core.animateFloatAsState
+import androidx.compose.animation.core.spring
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.keyframes
-import androidx.compose.animation.core.spring
-import androidx.compose.animation.core.tween
import androidx.compose.animation.core.updateTransition
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
@@ -54,116 +47,152 @@ import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
-import androidx.compose.foundation.layout.IntrinsicSize
+import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
-import androidx.compose.foundation.layout.defaultMinSize
-import androidx.compose.foundation.layout.calculateEndPadding
-import androidx.compose.foundation.layout.calculateStartPadding
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
-import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentWidth
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
-import androidx.compose.runtime.CompositionLocalProvider
-import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.LaunchedEffect
-import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
-import androidx.compose.runtime.rememberUpdatedState
-import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
-import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
-import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.BlurEffect
import androidx.compose.ui.graphics.Color
-import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.CompositingStrategy
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
-import androidx.compose.ui.draw.drawBehind
-import androidx.compose.ui.graphics.drawOutline
-import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalDensity
-import androidx.compose.ui.platform.LocalLayoutDirection
-import androidx.compose.ui.semantics.clearAndSetSemantics
import androidx.compose.ui.unit.Dp
-import androidx.compose.ui.unit.LayoutDirection
-import androidx.compose.ui.unit.Velocity
import androidx.compose.ui.unit.dp
-import androidx.compose.ui.util.fastCoerceIn
-import androidx.compose.ui.util.fastRoundToInt
-import dev.lelonio.square.ui.glass.LocalGlassEffectConfig
-import dev.lelonio.square.ui.glass.glassResolutionScale
-import androidx.compose.ui.util.lerp
-import androidx.compose.ui.graphics.isSpecified
-import androidx.compose.ui.graphics.luminance
-import dev.lelonio.square.ui.glass.backdrop.Backdrop
-import dev.lelonio.square.ui.glass.backdrop.backdrops.layerBackdrop
-import dev.lelonio.square.ui.glass.backdrop.backdrops.rememberCombinedBackdrop
-import dev.lelonio.square.ui.glass.backdrop.backdrops.rememberLayerBackdrop
-import dev.lelonio.square.ui.glass.backdrop.catalog.utils.DampedDragAnimation
-import dev.lelonio.square.ui.glass.backdrop.catalog.utils.InteractiveHighlight
-import dev.lelonio.square.ui.glass.backdrop.drawBackdrop
-import dev.lelonio.square.ui.glass.backdrop.effects.blur
-import dev.lelonio.square.ui.glass.backdrop.effects.lens
-import dev.lelonio.square.ui.glass.backdrop.effects.vibrancy
-import dev.lelonio.square.ui.glass.backdrop.highlight.Highlight
-import dev.lelonio.square.ui.glass.backdrop.shadow.InnerShadow
-import dev.lelonio.square.ui.glass.backdrop.shadow.Shadow
-import dev.lelonio.square.ui.glass.shapes.ContinuousRoundedRectangle
-import kotlinx.coroutines.launch
-import kotlin.math.abs
-import kotlin.math.sign
-
-
-
-// Tuning for the gooey merge/split pulse across the inline<->expanded
-// crossfade — see GooeyTransition.kt. Not derived from fadeIn()/fadeOut()'s
-// own duration; just a reasonable match for it.
-private val GooeyPeakBlur = 12.dp
-private const val GooeyDurationMs = 300
-
-// Rim/shadow the selection puck keeps when it is NOT being pressed. Both used to
-// be driven straight off pressProgress, i.e. zero at rest, which left the puck
-// defined only by its own dark surface wash — invisible against a dark bar.
-// How long the selection puck takes to arrive when the bar unfolds, and how
-// small it starts. Matched to [GooeyDurationMs], the length of the fold itself:
-// the puck is not part of the shared element that travels, so the only thing
-// keeping the two together is that they take the same time.
-private const val PuckEnterMs = GooeyDurationMs
-private const val PuckEnterScale = 0.82f
-
-private const val PuckRestHighlightAlpha = 0.5f
-private const val PuckRestShadowAlpha = 0.35f
-
-// Vendored addition: the three shapes the bar can render. INLINE is the
-// scroll-collapsed row (unchanged by search mode); EXPANDED is the normal
-// all-tabs pill; SEARCH_EXPANDED replaces EXPANDED while search mode is
-// active (see SearchExpandedBar).
-private enum class FloatingTabBarVisual { INLINE, EXPANDED, SEARCH_EXPANDED }
-
-// Matches the established inline-row height (InlineStandaloneTab's own
-// defaultMinSize floor at the FloatingNavBar call site, and the inline mini
-// player's own ~48dp content height) so the search-expanded row doesn't read
-// shorter than the bar's own shrunk state.
-private val SearchBarRowHeight = 48.dp
+
+
+/**
+ * A floating tab bar that can transition between inline and expanded states.
+ *
+ * @param isInline controls the FloatingTabBar's inline state
+ * @param selectedTabKey the key of the currently selected tab
+ * @param modifier the modifier to be applied to the tab bar
+ * @param colors the colors used by the tab bar components
+ * @param shapes the shapes used by the tab bar components
+ * @param sizes the sizes and spacing used by the tab bar components
+ * @param elevations the elevation values used by the tab bar components
+ * @param tabBarContentModifier modifier applied to the tab bar sections containing the grouped tabs and standalone tab.
+ * It is applied after the default styling (background, shadow, clip) but before any content padding.
+ * @param inlineAccessory the accessory composable that appears in inline state (e.g., compact media player)
+ * @param expandedAccessory the accessory composable that appears in expanded state (e.g., full media player)
+ * @param contentKey optional key that when changed retriggers the content lambda
+ * @param content the content defining the tabs
+ */
+@Composable
+fun FloatingTabBar(
+ isInline: Boolean,
+ selectedTabKey: Any?,
+ modifier: Modifier = Modifier,
+ tabBarContentModifier: Modifier = Modifier,
+ inlineAccessory: (@Composable SharedTransitionScope.(Modifier, AnimatedVisibilityScope) -> Unit)? = null,
+ expandedAccessory: (@Composable SharedTransitionScope.(Modifier, AnimatedVisibilityScope) -> Unit)? = null,
+ colors: FloatingTabBarColors = FloatingTabBarDefaults.colors(),
+ shapes: FloatingTabBarShapes = FloatingTabBarDefaults.shapes(),
+ sizes: FloatingTabBarSizes = FloatingTabBarDefaults.sizes(),
+ elevations: FloatingTabBarElevations = FloatingTabBarDefaults.elevations(),
+ tabsFillWidth: Boolean = false,
+ selectedTabSurface: (@Composable () -> Modifier)? = null,
+ /**
+ * LOCAL CHANGE: the open bar's tab group, drawn by the caller.
+ *
+ * The catalog this app's glass comes from ships its own bottom tabs — the
+ * pill, the tabs and the indicator that can be dragged between them — and
+ * that component is what this app wants in the open bar. It is handed the
+ * modifier the group would have had, so it still takes its place in the row
+ * beside the standalone tab, and it still travels as the shared "tabGroup"
+ * element when the bar folds. Null draws the library's own tabs.
+ */
+ expandedTabs: (@Composable SharedTransitionScope.(Modifier, AnimatedVisibilityScope) -> Unit)? = null,
+ /**
+ * LOCAL CHANGE: how tall [expandedTabs] stands.
+ *
+ * Not a preference: the row measures its children's intrinsic height to size
+ * the standalone tab's square, and a component built on SubcomposeLayout —
+ * which the catalog's tabs are, they measure themselves against their own
+ * width — cannot answer that question at all. A height stated here is
+ * answered without asking it.
+ */
+ expandedTabsHeight: Dp = Dp.Unspecified,
+ /**
+ * LOCAL CHANGE: the search control, grown into the row.
+ *
+ * With this true and [searchBarContent] given, the open bar becomes the tab
+ * you are on and a field taking the rest of the row: the tab group folds
+ * away and the standalone circle is what the field grows out of — they share
+ * bounds, so it is one shape stretching rather than a circle vanishing and a
+ * pill appearing. The folded state is untouched.
+ */
+ /**
+ * LOCAL CHANGE: whether the standalone tab keeps a circle of its own while
+ * the bar is open.
+ *
+ * Upstream it always does — the places in a pill and search beside it. Here
+ * search is one of the places, so the circle would be the same control
+ * twice; it is kept for the folded bar, where the pill is gone and there is
+ * nothing else to tap.
+ */
+ standaloneInExpanded: Boolean = true,
+ searchMode: Boolean = false,
+ searchBarContent: (@Composable (Modifier) -> Unit)? = null,
+ contentKey: Any? = null,
+ content: FloatingTabBarScope.() -> Unit
+) {
+ val scrollConnection = rememberFloatingTabBarScrollConnection(
+ initialIsInline = isInline,
+ inlineBehavior = FloatingTabBarInlineBehavior.Never
+ )
+
+ LaunchedEffect(isInline) {
+ if (isInline) scrollConnection.inline() else scrollConnection.expand()
+ }
+
+ FloatingTabBar(
+ selectedTabKey = selectedTabKey,
+ scrollConnection = scrollConnection,
+ modifier = modifier,
+ tabBarContentModifier = tabBarContentModifier,
+ inlineAccessory = inlineAccessory,
+ expandedAccessory = expandedAccessory,
+ colors = colors,
+ shapes = shapes,
+ sizes = sizes,
+ elevations = elevations,
+ tabsFillWidth = tabsFillWidth,
+ selectedTabSurface = selectedTabSurface,
+ expandedTabs = expandedTabs,
+ expandedTabsHeight = expandedTabsHeight,
+ standaloneInExpanded = standaloneInExpanded,
+ searchMode = searchMode,
+ searchBarContent = searchBarContent,
+ contentKey = contentKey,
+ content = content
+ )
+}
/**
* A floating tab bar that transitions between inline and expanded states based on scroll behavior.
@@ -179,6 +208,7 @@ private val SearchBarRowHeight = 48.dp
* It is applied after the default styling (background, shadow, clip) but before any content padding.
* @param inlineAccessory the accessory composable that appears in inline state (e.g., compact media player)
* @param expandedAccessory the accessory composable that appears in expanded state (e.g., full media player)
+ * @param contentKey optional key that when changed retriggers the content lambda
* @param content the content defining the tabs
*/
@Composable
@@ -193,228 +223,284 @@ fun FloatingTabBar(
shapes: FloatingTabBarShapes = FloatingTabBarDefaults.shapes(),
sizes: FloatingTabBarSizes = FloatingTabBarDefaults.sizes(),
elevations: FloatingTabBarElevations = FloatingTabBarDefaults.elevations(),
- // Vendored addition: when non-null, the expanded selection puck samples this
- // backdrop for lens refraction and an accent-tinted glass preview of the
- // selected tab's icon. Null falls back to a flat colored puck.
- backdrop: Backdrop? = null,
- accentColor: Color? = null,
- // Vendored addition: when true (and searchBarContent non-null), the
- // expanded state renders SearchExpandedBar instead of ExpandedBar — the
- // tab group shrinks to the current screen's own icon and the standalone
- // slot expands to fill the rest of the row with searchBarContent. The
- // inline (scrolled) state is unaffected — it stays the normal collapsed
- // icon+accessory+standalone row regardless of searchMode.
+ /**
+ * LOCAL CHANGE: whether the open tab group spreads across the row.
+ *
+ * Upstream sizes the group to its own content, which is right for the bar
+ * it was written for — three long labels fill the row on their own. Four
+ * short ones do not: the pill stopped two thirds of the way across and left
+ * a hole between it and the search circle. With this true the group takes
+ * the width the row has and its tabs share it equally, which is what the
+ * reference looks like whatever its labels happen to say.
+ */
+ tabsFillWidth: Boolean = false,
+ /**
+ * LOCAL CHANGE: what the lit slot is made of.
+ *
+ * Upstream fills the selected tab with a colour, which is right for a bar
+ * drawn in paint. This app's bar is glass, and a painted rectangle on it is
+ * the one thing that reads as pasted on — so the caller hands over a
+ * modifier instead, and it is applied to a shape that travels between the
+ * tabs rather than to the tabs themselves. Null keeps upstream's colour.
+ *
+ * Whatever it returns must draw something of its own: a surface that only
+ * samples the page behind the bar redraws it sharp inside the puck, which
+ * reads as a hole rather than as a lit slot.
+ */
+ selectedTabSurface: (@Composable () -> Modifier)? = null,
+ /**
+ * LOCAL CHANGE: the open bar's tab group, drawn by the caller.
+ *
+ * The catalog this app's glass comes from ships its own bottom tabs — the
+ * pill, the tabs and the indicator that can be dragged between them — and
+ * that component is what this app wants in the open bar. It is handed the
+ * modifier the group would have had, so it still takes its place in the row
+ * beside the standalone tab, and it still travels as the shared "tabGroup"
+ * element when the bar folds. Null draws the library's own tabs.
+ */
+ expandedTabs: (@Composable SharedTransitionScope.(Modifier, AnimatedVisibilityScope) -> Unit)? = null,
+ /**
+ * LOCAL CHANGE: how tall [expandedTabs] stands.
+ *
+ * Not a preference: the row measures its children's intrinsic height to size
+ * the standalone tab's square, and a component built on SubcomposeLayout —
+ * which the catalog's tabs are, they measure themselves against their own
+ * width — cannot answer that question at all. A height stated here is
+ * answered without asking it.
+ */
+ expandedTabsHeight: Dp = Dp.Unspecified,
+ /**
+ * LOCAL CHANGE: the search control, grown into the row.
+ *
+ * With this true and [searchBarContent] given, the open bar becomes the tab
+ * you are on and a field taking the rest of the row: the tab group folds
+ * away and the standalone circle is what the field grows out of — they share
+ * bounds, so it is one shape stretching rather than a circle vanishing and a
+ * pill appearing. The folded state is untouched.
+ */
+ /**
+ * LOCAL CHANGE: whether the standalone tab keeps a circle of its own while
+ * the bar is open.
+ *
+ * Upstream it always does — the places in a pill and search beside it. Here
+ * search is one of the places, so the circle would be the same control
+ * twice; it is kept for the folded bar, where the pill is gone and there is
+ * nothing else to tap.
+ */
+ standaloneInExpanded: Boolean = true,
searchMode: Boolean = false,
searchBarContent: (@Composable (Modifier) -> Unit)? = null,
- // Vendored addition: caller-held width (from a previous onExpandedWidthChanged
- // report) that SearchExpandedBar holds its row to, so the bar doesn't visibly
- // widen to fill available space when entering search mode. Null/0 falls back
- // to filling available space (e.g. first-ever composition in search mode).
- expandedContentWidthPx: Int? = null,
- onExpandedWidthChanged: ((Int) -> Unit)? = null,
+ contentKey: Any? = null,
content: FloatingTabBarScope.() -> Unit
) {
- // Rebuilt every composition, deliberately not remembered. The tabs hold
- // @Composable lambdas that close over selection state and colours; caching
- // them behind a key meant every value they captured had to be listed in that
- // key by hand, and anything forgotten showed up as a stale icon or colour on
- // one navigation path only. Re-running the builder is a handful of
- // allocations for a few tabs, and it makes that whole class of bug
- // unrepresentable.
- val scope = FloatingTabBarScopeImpl().apply { content() }
+ val scope = remember(contentKey) { FloatingTabBarScopeImpl().apply { content() } }
val isAccessoryShared = inlineAccessory != null && expandedAccessory != null
+ // Three shapes rather than two; see searchMode.
val visual = when {
scrollConnection.isInline -> FloatingTabBarVisual.INLINE
- searchMode && searchBarContent != null -> FloatingTabBarVisual.SEARCH_EXPANDED
+ searchMode && searchBarContent != null -> FloatingTabBarVisual.SEARCH
else -> FloatingTabBarVisual.EXPANDED
}
- // updateTransition (rather than the sugared top-level AnimatedContent) so
- // the transition object is available here to drive the gooey blur pulse,
- // not just inside the content lambda.
- val transition = updateTransition(targetState = visual, label = "floatingTabBarVisual")
- val gooeyBlurPx = with(LocalDensity.current) { GooeyPeakBlur.toPx() }
- // Liquid "gooey" merge/split (see GooeyTransition.kt): peaks mid-crossfade
- // and returns to 0 at rest, on every transition regardless of direction —
- // the keyframes spec defines the peak explicitly rather than deriving it
- // from a start/end value, since the steady-state target is always 0.
- // LOCAL CHANGE: held as State and read in the draw phase, not unwrapped
- // here. Read as a value, every frame of the fold recomposed this whole
- // subtree — the bar, both of its states, and the accessory inside them —
- // which is what made the animation stutter on a mid-range phone. The
- // modifier below reads it inside its own graphicsLayer block instead, so a
- // frame of the fold costs a draw and nothing more.
- val gooeyProgress = transition.animateFloat(
- transitionSpec = {
- keyframes {
- durationMillis = GooeyDurationMs
- 0f at 0
- 1f atFraction 0.5f using FastOutSlowInEasing
- 0f at GooeyDurationMs
- }
- },
- label = "gooeyProgress"
- ) { _ -> 0f }
-
SharedTransitionLayout(modifier = modifier) {
- // Wrapping AnimatedContent itself (not SharedTransitionLayout's own
- // modifier) so the offscreen gooey capture stays under
- // SharedTransitionLayout's own overlay mechanism — sharedElement-
- // tracked content (like the search tab's shared "standaloneTab"
- // bounds) renders via that overlay, and capturing it into the gooey
- // layer at the wrong level made it visibly pop in a frame late when
- // re-expanding. This way the overlay draws normally, on top.
- // Held as a lambda rather than a Boolean so flipping it costs no
- // recomposition — the glass surfaces call it during draw. See
- // LocalTabBarBackdropFrozen.
- val frozenWhileAnimating = remember(transition) {
- { transition.currentState != transition.targetState }
- }
- // LOCAL CHANGE: and the same fact where the caller can see it.
+ // LOCAL CHANGE: the fold as two drops of water rather than two layouts.
//
- // The composition local only reaches surfaces built inside this
- // composable — the selection puck. The bar's own pane and the pill above
- // it are built by the caller and passed in as `tabBarContentModifier`,
- // so reading the local there gave the default, "never frozen", and the
- // one moment the freeze exists for was the one it never covered. The
- // scroll connection is the object both sides already share.
- val morphing = transition.currentState != transition.targetState
- LaunchedEffect(scrollConnection, morphing) {
- scrollConnection.morphing = morphing
- }
- CompositionLocalProvider(LocalTabBarBackdropFrozen provides frozenWhileAnimating) {
- // Always applied: `gooey` is a no-op at radius 0 (no offscreen layer,
- // no filter), so there is nothing to gate on and nothing to recompose.
- Box(Modifier.gooey { gooeyBlurPx * gooeyProgress.value }) {
- transition.AnimatedContent(
- transitionSpec = { fadeIn() togetherWith fadeOut() },
- contentAlignment = Alignment.BottomCenter
- ) { targetVisual ->
- // Vendored addition: the accessory is built for the state being
- // arrived at, and not for the one being left.
- //
- // Both states are composed for the length of a fold, so everything
- // in them is built twice — and the accessory is by far the heaviest
- // thing either of them holds: a cover to decode and draw, two lines
- // of text to lay out, controls, a progress line. It is a shared
- // element, so only one copy was ever drawn; the other was built,
- // measured and thrown away sixty times a second. Measured on the
- // fold, having it at all costs a third of the animation.
- val leaving = targetVisual != transition.targetState
- when (targetVisual) {
- FloatingTabBarVisual.INLINE -> InlineBar(
+ // Held as a transition of its own so the merge can be timed against it:
+ // the shapes travel through the middle of the fold, and it is only there
+ // that the blur-and-threshold pass has anything to join. The radius runs
+ // 0 at both ends and peaks halfway, which is what draws the neck between
+ // the circles, thins it, and pinches it off. See gooey.
+ val fold = updateTransition(targetState = visual, label = "fold")
+ val gooeyRadius by fold.animateFloat(
+ transitionSpec = {
+ keyframes {
+ durationMillis = GooeyDurationMs
+ 0f at 0
+ GooeyPeakBlur at GooeyDurationMs / 2 using FastOutSlowInEasing
+ 0f at GooeyDurationMs
+ }
+ },
+ label = "gooey",
+ ) { 0f }
+
+ Box(Modifier.gooey { gooeyRadius }) {
+ fold.AnimatedContent(
+ transitionSpec = { fadeIn() togetherWith fadeOut() },
+ contentAlignment = Alignment.BottomStart
+ ) { target ->
+ if (target == FloatingTabBarVisual.SEARCH) {
+ SearchExpandedBar(
scope = scope,
selectedTabKey = selectedTabKey,
- accessory = inlineAccessory.takeIf { !leaving },
+ accessory = expandedAccessory,
isAccessoryShared = isAccessoryShared,
- onInlineTabClick = { scrollConnection.expand() },
colors = colors,
shapes = shapes,
sizes = sizes,
elevations = elevations,
tabBarContentModifier = tabBarContentModifier,
- animatedVisibilityScope = this@AnimatedContent
+ animatedVisibilityScope = this@AnimatedContent,
+ searchBarContent = searchBarContent ?: {},
+ rowHeight = expandedTabsHeight,
)
- FloatingTabBarVisual.EXPANDED -> ExpandedBar(
+ } else if (target == FloatingTabBarVisual.INLINE) {
+ InlineBar(
scope = scope,
selectedTabKey = selectedTabKey,
- accessory = expandedAccessory.takeIf { !leaving },
+ accessory = inlineAccessory,
isAccessoryShared = isAccessoryShared,
+ onInlineTabClick = { scrollConnection.expand() },
colors = colors,
shapes = shapes,
sizes = sizes,
elevations = elevations,
tabBarContentModifier = tabBarContentModifier,
- animatedVisibilityScope = this@AnimatedContent,
- backdrop = backdrop,
- accentColor = accentColor,
- onWidthMeasured = onExpandedWidthChanged
+ animatedVisibilityScope = this@AnimatedContent
)
- FloatingTabBarVisual.SEARCH_EXPANDED -> SearchExpandedBar(
+ } else {
+ ExpandedBar(
scope = scope,
+ tabsFillWidth = tabsFillWidth,
+ selectedTabSurface = selectedTabSurface,
+ expandedTabs = expandedTabs,
+ expandedTabsHeight = expandedTabsHeight,
+ standaloneInExpanded = standaloneInExpanded,
selectedTabKey = selectedTabKey,
- accessory = expandedAccessory.takeIf { !leaving },
+ accessory = expandedAccessory,
isAccessoryShared = isAccessoryShared,
colors = colors,
shapes = shapes,
sizes = sizes,
elevations = elevations,
tabBarContentModifier = tabBarContentModifier,
- animatedVisibilityScope = this@AnimatedContent,
- searchBarContent = searchBarContent ?: {},
- targetWidthPx = expandedContentWidthPx
+ animatedVisibilityScope = this@AnimatedContent
)
}
- }
}
}
}
}
/**
- * True for exactly the frames of a tab bar transition (inline <-> expanded <->
- * search). The bar's glass surfaces pass it to `drawBackdrop`'s `frozen`, which
- * makes them reuse their last backdrop capture instead of re-recording the whole
- * screen every frame while their bounds animate.
+ * The merge, and how long it lasts.
*
- * A lambda, not a Boolean, so flipping it triggers no recomposition — the surfaces
- * call it during draw. Static local for the same reason: the lambda's identity is
- * stable, only what it reads changes.
+ * Blur enough for the two circles' edges to reach each other and no more: at a
+ * larger radius the icons inside them smear, and the pass covers the whole bar.
+ * The window is the fold's own — the shapes are between places for about that
+ * long — and the radius is zero at both ends, so at rest this costs nothing: no
+ * offscreen layer, no filter. See gooey.
*/
-val LocalTabBarBackdropFrozen = staticCompositionLocalOf<() -> Boolean> { { false } }
+private const val GooeyPeakBlur = 14f
+private const val GooeyDurationMs = 260
+
+/** LOCAL CHANGE: the three shapes the bar can take; see searchMode. */
+private enum class FloatingTabBarVisual { INLINE, EXPANDED, SEARCH }
+
+/**
+ * LOCAL CHANGE: the open bar with the field in it.
+ *
+ * The tab you are on stays as a round button at the start of the row — it is
+ * how you get back — and the search control fills the rest. That control shares
+ * its bounds with the standalone circle of the other two states, so entering
+ * search is the circle stretching into a field rather than two shapes swapping.
+ */
+@Composable
+private fun SharedTransitionScope.SearchExpandedBar(
+ scope: FloatingTabBarScopeImpl,
+ selectedTabKey: Any?,
+ accessory: (@Composable SharedTransitionScope.(Modifier, AnimatedVisibilityScope) -> Unit)?,
+ isAccessoryShared: Boolean,
+ colors: FloatingTabBarColors,
+ shapes: FloatingTabBarShapes,
+ sizes: FloatingTabBarSizes,
+ elevations: FloatingTabBarElevations,
+ tabBarContentModifier: Modifier,
+ animatedVisibilityScope: AnimatedVisibilityScope,
+ searchBarContent: @Composable (Modifier) -> Unit,
+ /** As tall as the open bar, so entering search does not change its height. */
+ rowHeight: Dp,
+) {
+ val inlineTab = scope.getInlineTab(selectedTabKey)
+
+ Column(
+ horizontalAlignment = Alignment.CenterHorizontally,
+ verticalArrangement = Arrangement.spacedBy(sizes.componentSpacing),
+ modifier = Modifier.fillMaxWidth()
+ ) {
+ if (accessory != null) {
+ ExpandedAccessory(
+ accessory = accessory,
+ isAccessoryShared = isAccessoryShared,
+ shapes = shapes,
+ colors = colors,
+ elevations = elevations,
+ animatedVisibilityScope = animatedVisibilityScope,
+ modifier = Modifier.fillMaxWidth()
+ )
+ }
+
+ Row(
+ horizontalArrangement = Arrangement.spacedBy(sizes.componentSpacing),
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = Modifier
+ .fillMaxWidth()
+ .then(
+ if (rowHeight != Dp.Unspecified) Modifier.height(rowHeight) else Modifier
+ )
+ ) {
+ if (inlineTab != null) {
+ InlineTab(
+ inlineTab = inlineTab,
+ // Already open: a tap here navigates, and does not have to
+ // unfold anything.
+ onInlineTabClick = {},
+ shapes = shapes,
+ sizes = sizes,
+ colors = colors,
+ elevations = elevations,
+ animatedVisibilityScope = animatedVisibilityScope,
+ tabBarContentModifier = tabBarContentModifier,
+ modifier = Modifier
+ .fillMaxHeight()
+ .aspectRatio(1f, matchHeightConstraintsFirst = true)
+ )
+ }
+
+ searchBarContent(
+ Modifier
+ .weight(1f)
+ .fillMaxHeight()
+ .sharedElement(
+ sharedContentState = rememberSharedContentState("standaloneTab"),
+ animatedVisibilityScope = animatedVisibilityScope,
+ zIndexInOverlay = 1f
+ )
+ .shadow(shape = shapes.tabBarShape, elevation = elevations.expandedElevation)
+ .background(color = colors.backgroundColor, shape = shapes.tabBarShape)
+ .clip(shapes.tabBarShape)
+ .then(tabBarContentModifier)
+ )
+ }
+ }
+}
/**
* A [NestedScrollConnection] that handles scroll events to transition between inline and expanded states.
*
* @param initialIsInline Initial state of the tab bar (inline or expanded).
- * @param scrollThresholdPx The minimum scroll distance in pixels required to collapse to inline.
- * @param expandThresholdPx The minimum scroll distance in pixels required to expand back. Kept
- * well below [scrollThresholdPx] so the bar returns as soon as the user scrolls up.
+ * @param scrollThresholdPx The minimum scroll distance in pixels required to trigger a state change.
* @param inlineBehavior Defines when the tab bar should transition to inline state.
*/
class FloatingTabBarScrollConnection(
initialIsInline: Boolean = false,
private val scrollThresholdPx: Float,
- private val expandThresholdPx: Float = scrollThresholdPx,
private val inlineBehavior: FloatingTabBarInlineBehavior = FloatingTabBarInlineBehavior.OnScrollDown
) : NestedScrollConnection {
var isInline by mutableStateOf(initialIsInline)
private set
- /**
- * LOCAL CHANGE: while true, scrolling leaves the bar alone.
- *
- * For searching. The bar carries the text field, and folding it takes the
- * field away mid-search: scrolling the results put it back a moment later,
- * which re-created the field, which asked for the focus again, which opened
- * the keyboard — every scroll up. And a bar that folds while you are typing
- * in it is wrong even without that.
- */
- var locked by mutableStateOf(false)
-
- /**
- * LOCAL CHANGE: true for exactly the frames the bar is changing shape.
- *
- * Published here rather than through a composition local because the bar's
- * glass is applied by whoever uses the bar, from outside its composition.
- */
- var morphing by mutableStateOf(false)
-
- /**
- * LOCAL CHANGE: true while the page under the bar is moving.
- *
- * Every glass surface samples a recording of the screen, and a recording of
- * a scrolling screen is a new recording sixty times a second — so each pane
- * re-captures and re-runs its blur and lens on every frame of every scroll.
- * Measured on the home page: 57ms a frame with the glass on, 25ms with it
- * off. Nobody can read the refraction through a surface while the thing
- * behind it is flying past, so during the scroll they hold the last one.
- */
- var scrolling by mutableStateOf(false)
- private set
-
private var accumulatedScroll = 0f
fun expand() {
@@ -429,12 +515,11 @@ class FloatingTabBarScrollConnection(
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
// If behavior is Never, don't change state
- if (inlineBehavior == FloatingTabBarInlineBehavior.Never || locked) {
+ if (inlineBehavior == FloatingTabBarInlineBehavior.Never) {
return Offset.Zero
}
val scrollDelta = available.y
- if (scrollDelta != 0f) scrolling = true
// Reset accumulated scroll if changing direction
if ((accumulatedScroll > 0 && scrollDelta < 0) || (accumulatedScroll < 0 && scrollDelta > 0)) {
@@ -446,25 +531,15 @@ class FloatingTabBarScrollConnection(
when (inlineBehavior) {
FloatingTabBarInlineBehavior.OnScrollDown -> {
- // Asymmetric on purpose. Collapsing wants hysteresis so a jittery
- // downward scroll can't flicker the bar, and the distance is free
- // there — the user is already moving away. Expanding is the
- // opposite: the bar is what they are reaching for, so making them
- // drag the same distance back reads as the bar being slow to
- // return. Coming back is near-immediate, with just enough travel
- // required that a shaky finger mid-scroll can't oscillate it.
- // LOCAL CHANGE: scrolling down folds it, scrolling up does not
- // bring it back. Only arriving at the top of the page does (see
- // onPostScroll), or tapping a tab.
- //
- // Upstream is symmetric, and symmetric is what a scrolling reader
- // feels as the bar flickering: every small correction upwards
- // pulled the whole thing open over the text again. The top of the
- // page is a place rather than a direction, so the bar comes back
- // when you have actually arrived somewhere.
+ // Check if we've scrolled enough to trigger state change
if (accumulatedScroll <= -scrollThresholdPx && !isInline) {
+ // Scrolling down enough - transition to inline mode
isInline = true
accumulatedScroll = 0f // Reset after state change
+ } else if (accumulatedScroll >= scrollThresholdPx && isInline) {
+ // Scrolling up enough - transition to expanded mode
+ isInline = false
+ accumulatedScroll = 0f // Reset after state change
}
}
@@ -488,42 +563,13 @@ class FloatingTabBarScrollConnection(
return Offset.Zero // Don't consume the scroll, let it pass through
}
-
- /**
- * LOCAL CHANGE: the bar comes back at the top of the page.
- *
- * What reaches here is what the content could not use. Dragging downwards
- * with nothing left to scroll means the list is already at its first item,
- * which is the one moment the bar is asked for rather than in the way.
- */
- override suspend fun onPreFling(available: Velocity): Velocity {
- // The end of the gesture, fling or not: Compose calls this on release
- // either way, with a velocity of zero when there was none.
- scrolling = false
- return Velocity.Zero
- }
-
- override fun onPostScroll(
- consumed: Offset,
- available: Offset,
- source: NestedScrollSource,
- ): Offset {
- if (inlineBehavior == FloatingTabBarInlineBehavior.Never || locked) {
- return Offset.Zero
- }
- if (isInline && available.y > 0f) expand()
- return Offset.Zero
- }
}
/**
* Creates and remembers a [FloatingTabBarScrollConnection] instance.
*
* @param initialIsInline Initial state of the tab bar (inline or expanded). Default is false.
- * @param scrollThreshold The scroll distance required to collapse to inline. Default is 50.dp.
- * @param expandThreshold The scroll distance required to expand back. Default is 8.dp — small
- * enough that the bar returns immediately on scroll up, large enough that a shaky finger
- * mid-scroll cannot oscillate it.
+ * @param scrollThreshold The minimum scroll distance required to trigger a state change. Default is 50.dp.
* @param inlineBehavior Defines when the tab bar should transition to inline state. Default is [FloatingTabBarInlineBehavior.OnScrollDown].
* @return A remembered [FloatingTabBarScrollConnection] instance.
*/
@@ -531,18 +577,11 @@ class FloatingTabBarScrollConnection(
fun rememberFloatingTabBarScrollConnection(
initialIsInline: Boolean = false,
scrollThreshold: Dp = 50.dp,
- expandThreshold: Dp = 8.dp,
inlineBehavior: FloatingTabBarInlineBehavior = FloatingTabBarInlineBehavior.OnScrollDown
): FloatingTabBarScrollConnection = with(LocalDensity.current) {
val scrollThresholdPx = scrollThreshold.toPx()
- val expandThresholdPx = expandThreshold.toPx()
- remember(scrollThresholdPx, expandThresholdPx, inlineBehavior, initialIsInline) {
- FloatingTabBarScrollConnection(
- initialIsInline,
- scrollThresholdPx,
- expandThresholdPx,
- inlineBehavior,
- )
+ remember(scrollThresholdPx, inlineBehavior, initialIsInline) {
+ FloatingTabBarScrollConnection(initialIsInline, scrollThresholdPx, inlineBehavior)
}
}
@@ -587,36 +626,12 @@ interface FloatingTabBarScope {
* @param icon Composable content for the tab icon
* @param onClick Callback invoked when the tab is clicked
* @param indication Optional indication provider for touch feedback, defaults to LocalIndication.current
- * @param title Composable content for the tab title. Never actually shown —
- * the standalone tab is always an icon-only floating circle, in both inline
- * and expanded states (see InlineStandaloneTab / ExpandedStandaloneTab).
*/
fun standaloneTab(
key: Any,
icon: @Composable () -> Unit,
onClick: () -> Unit,
- indication: (@Composable () -> Indication)? = { LocalIndication.current },
- title: @Composable () -> Unit = {}
- )
-}
-
-/**
- * Plain release-triggered [clickable]. Firing on finger-DOWN (the old behaviour)
- * meant any touch that turned into a scroll or a puck drag still navigated first —
- * "opens a screen even when I didn't drop the puck". Release-fire lets Compose's
- * touch-slop arbitration cancel the tap when the gesture becomes a drag/scroll, so
- * only a real tap navigates. Keeps the custom [indication].
- */
-@Composable
-private fun Modifier.tapClickable(
- indication: Indication?,
- onClick: () -> Unit,
-): Modifier {
- val interactionSource = remember { MutableInteractionSource() }
- return clickable(
- onClick = onClick,
- indication = indication,
- interactionSource = interactionSource
+ indication: (@Composable () -> Indication)? = { LocalIndication.current }
)
}
@@ -637,16 +652,17 @@ private fun SharedTransitionScope.InlineBar(
val inlineTab = scope.getInlineTab(selectedTabKey)
val standaloneTab = scope.standaloneTab
val hasInlineTab = inlineTab != null
+ val hasStandaloneTab = standaloneTab != null
- // With an accessory the row spans the full width ([tab][accessory][standalone],
- // iOS 26 Apple Music style); without one, the cluster is packed and centered.
+ // IntrinsicSize.Min makes the Row only as tall as its tallest child's intrinsic height,
+ // which lets the standalone tab (fillMaxHeight + aspectRatio 1:1) become a square sized to
+ // the tab group's height, and lets the accessory fill that same height via fillMaxHeight.
Row(
- horizontalArrangement = Arrangement.spacedBy(sizes.componentSpacing),
- verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
- .then(if (accessory == null) Modifier.wrapContentWidth() else Modifier)
- .height(IntrinsicSize.Max)
+ .height(IntrinsicSize.Min),
+ horizontalArrangement = Arrangement.spacedBy(sizes.componentSpacing),
+ verticalAlignment = Alignment.CenterVertically
) {
if (hasInlineTab) {
InlineTab(
@@ -676,28 +692,30 @@ private fun SharedTransitionScope.InlineBar(
)
}
- if (standaloneTab != null) {
+ if (hasStandaloneTab) {
+ // The accessory's weight already consumes the slack and pushes the standalone tab to
+ // the end. Without an accessory, a flexible spacer pins it to the end.
+ if (accessory == null) {
+ Spacer(Modifier.weight(1f))
+ }
+
InlineStandaloneTab(
standaloneTab = standaloneTab,
shapes = shapes,
- sizes = sizes,
colors = colors,
elevations = elevations,
animatedVisibilityScope = animatedVisibilityScope,
tabBarContentModifier = tabBarContentModifier,
- // fillMaxHeight() + the row's IntrinsicSize.Max is supposed to
- // match this to the docked mini player's height, but intrinsic
- // measurement can under-report the mini player's actual
- // (dynamically-measured) content height — floor it explicitly
- // so the standalone tab pill can't end up shorter.
- modifier = Modifier
- .defaultMinSize(minHeight = 48.dp)
- .fillMaxHeight()
- // Height-first: aspectRatio resolves from maxWidth by default,
- // so on a narrow bar the leftover width — not the row height —
- // decided the circle's diameter and it came out smaller than the
- // bar beside it.
- .aspectRatio(1f, matchHeightConstraintsFirst = true)
+ // When there is no tab group to match height with, the square would collapse to the
+ // bare icon size. Apply the inline tab content padding so it stays a reasonable size.
+ contentPadding = if (hasInlineTab) null else sizes.tabInlineContentPadding,
+ modifier = if (hasInlineTab) {
+ Modifier
+ .fillMaxHeight()
+ .aspectRatio(1f)
+ } else {
+ Modifier.aspectRatio(1f)
+ }
)
}
}
@@ -716,6 +734,11 @@ private fun SharedTransitionScope.InlineTab(
tabBarContentModifier: Modifier
) {
Box(
+ // LOCAL CHANGE: centred. Upstream's default is top-start, which nobody
+ // notices while this box is sized to its own content — it shows the
+ // moment a caller makes it square, with the glyph sitting up in the
+ // corner of its circle.
+ contentAlignment = Alignment.Center,
modifier = modifier
.sharedElement(
sharedContentState = rememberSharedContentState("tabGroup"),
@@ -732,12 +755,13 @@ private fun SharedTransitionScope.InlineTab(
)
.clip(shapes.tabBarShape)
.then(tabBarContentModifier)
- .tapClickable(
- indication = inlineTab.indication?.invoke(),
+ .clickable(
onClick = {
onInlineTabClick()
inlineTab.onClick()
- }
+ },
+ indication = inlineTab.indication?.invoke(),
+ interactionSource = remember { MutableInteractionSource() }
)
.padding(sizes.tabInlineContentPadding)
) {
@@ -763,18 +787,13 @@ private fun SharedTransitionScope.InlineTab(
private fun SharedTransitionScope.InlineStandaloneTab(
standaloneTab: FloatingTabBarTab,
shapes: FloatingTabBarShapes,
- sizes: FloatingTabBarSizes,
colors: FloatingTabBarColors,
elevations: FloatingTabBarElevations,
animatedVisibilityScope: AnimatedVisibilityScope,
modifier: Modifier,
- tabBarContentModifier: Modifier
+ tabBarContentModifier: Modifier,
+ contentPadding: PaddingValues?
) {
- // Same finger-tracking glow as the keyboard-active search pill
- // (NavBarSearchInputBar) — a soft radial light following the touch point.
- val glowScope = rememberCoroutineScope()
- val glow = remember(glowScope) { InteractiveHighlight(animationScope = glowScope) }
-
Tab(
icon = standaloneTab.icon,
title = standaloneTab.title,
@@ -796,15 +815,12 @@ private fun SharedTransitionScope.InlineStandaloneTab(
)
.clip(shapes.standaloneTabShape)
.then(tabBarContentModifier)
- .then(glow.gestureModifier)
- .then(glow.modifier)
- .tapClickable(
+ .clickable(
+ onClick = standaloneTab.onClick,
indication = standaloneTab.indication?.invoke(),
- onClick = standaloneTab.onClick
+ interactionSource = remember { MutableInteractionSource() }
)
- // Unlike the regular tab pill (InlineTab, ExpandedTabs), this circle had
- // no inset at all — the icon sat flush against its edge.
- .padding(sizes.tabInlineContentPadding)
+ .then(if (contentPadding != null) Modifier.padding(contentPadding) else Modifier)
)
}
@@ -853,6 +869,20 @@ private fun SharedTransitionScope.InlineAccessory(
@Composable
private fun SharedTransitionScope.ExpandedBar(
scope: FloatingTabBarScopeImpl,
+ tabsFillWidth: Boolean = false,
+ standaloneInExpanded: Boolean = true,
+ selectedTabSurface: (@Composable () -> Modifier)? = null,
+ expandedTabs: (@Composable SharedTransitionScope.(Modifier, AnimatedVisibilityScope) -> Unit)? = null,
+ /**
+ * LOCAL CHANGE: how tall [expandedTabs] stands.
+ *
+ * Not a preference: the row measures its children's intrinsic height to size
+ * the standalone tab's square, and a component built on SubcomposeLayout —
+ * which the catalog's tabs are, they measure themselves against their own
+ * width — cannot answer that question at all. A height stated here is
+ * answered without asking it.
+ */
+ expandedTabsHeight: Dp = Dp.Unspecified,
selectedTabKey: Any?,
accessory: (@Composable SharedTransitionScope.(Modifier, AnimatedVisibilityScope) -> Unit)?,
isAccessoryShared: Boolean,
@@ -861,64 +891,15 @@ private fun SharedTransitionScope.ExpandedBar(
sizes: FloatingTabBarSizes,
elevations: FloatingTabBarElevations,
tabBarContentModifier: Modifier,
- animatedVisibilityScope: AnimatedVisibilityScope,
- backdrop: Backdrop?,
- accentColor: Color?,
- // Vendored addition: reports this row's own measured width upward so
- // SearchExpandedBar can hold the bar at the exact same overall width
- // instead of expanding to fill all available space in search mode.
- onWidthMeasured: ((Int) -> Unit)? = null,
+ animatedVisibilityScope: AnimatedVisibilityScope
) {
- val hasTabGroup = scope.tabs.isNotEmpty()
val standaloneTab = scope.standaloneTab
+ val hasStandaloneTab = standaloneTab != null && standaloneInExpanded
+ val hasTabGroup = scope.tabs.isNotEmpty()
- // The accessory matches the tab row's own (content-sized, not full-bleed)
- // width, so both pills line up edge to edge. The tab row is measured first
- // (onSizeChanged below); the accessory falls back to fillMaxWidth until
- // that first measurement lands — a one-frame lag, same pattern as
- // FloatingMiniPlayer's measuredHeightPx.
- val density = LocalDensity.current
- var tabRowWidthPx by remember { mutableIntStateOf(0) }
-
- // Vendored addition: the pill is never wider than the room the circle
- // beside it leaves.
- //
- // tabWidth is a ceiling and not a promise. The pill was laid out at that
- // width whatever the screen could take, and on a narrow one — a 360dp
- // phone, or any phone at a larger display size — the tabs plus the circle
- // came to more than the bar had. A row does not clip what does not fit, so
- // what was left over was the circle drawn on top of the last tab.
- //
- // Both halves are measured rather than assumed: the bar's own width, and
- // the circle's, which is the row's height and so does not depend on this.
- // Measured, therefore a frame late — the weight below is what holds the
- // first frame together, since a weighted child cannot be given more room
- // than the row has left.
- val layoutDirection = LocalLayoutDirection.current
- var barWidthPx by remember { mutableIntStateOf(0) }
- var circleWidthPx by remember { mutableIntStateOf(0) }
- val tabsCount = scope.tabs.size
- val fittedSizes = if (barWidthPx > 0 && circleWidthPx > 0 && tabsCount > 0) {
- val inset = sizes.tabBarContentPadding.calculateStartPadding(layoutDirection) +
- sizes.tabBarContentPadding.calculateEndPadding(layoutDirection)
- val room = with(density) {
- ((barWidthPx - circleWidthPx).toDp() - sizes.componentSpacing - inset) / tabsCount
- }
- if (room < sizes.tabWidth) sizes.copy(tabWidth = room.coerceAtLeast(0.dp)) else sizes
- } else {
- sizes
- }
-
- // The standalone tab (search) is always its own floating circle — same as
- // the inline (collapsed) state — never merged into the tab group pill, so
- // it reads as one consistent circular element through both inline and
- // expanded states (see ExpandedStandaloneTab / InlineStandaloneTab, tied
- // together by the shared "standaloneTab" element).
Column(
- horizontalAlignment = Alignment.CenterHorizontally,
- verticalArrangement = Arrangement.spacedBy(sizes.componentSpacing),
- // fillMaxWidth, so this measures the bar rather than its contents.
- modifier = Modifier.fillMaxWidth().onSizeChanged { barWidthPx = it.width }
+ modifier = Modifier.fillMaxWidth(),
+ verticalArrangement = Arrangement.spacedBy(sizes.componentSpacing)
) {
if (accessory != null) {
ExpandedAccessory(
@@ -928,222 +909,98 @@ private fun SharedTransitionScope.ExpandedBar(
colors = colors,
elevations = elevations,
animatedVisibilityScope = animatedVisibilityScope,
- modifier = if (tabRowWidthPx > 0) {
- Modifier.width(with(density) { tabRowWidthPx.toDp() })
- } else {
- Modifier.fillMaxWidth()
- }
+ modifier = Modifier.fillMaxWidth()
)
}
+ // IntrinsicSize.Min makes the Row only as tall as its tallest child's intrinsic height,
+ // letting the standalone tab (fillMaxHeight + aspectRatio 1:1) become a square sized to
+ // the tab group's height. The tab group takes weight(1f) but wraps its own content, so it
+ // only occupies what it needs while the standalone tab stays pinned to the end.
Row(
- horizontalArrangement = Arrangement.spacedBy(sizes.componentSpacing),
- verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
- .height(IntrinsicSize.Max)
- .onSizeChanged {
- tabRowWidthPx = it.width
- onWidthMeasured?.invoke(it.width)
- }
+ .fillMaxWidth()
+ .height(IntrinsicSize.Min),
+ // With a tab group present, its weight(1f) pushes the standalone tab to the end and
+ // spacedBy provides the gap. Without one, End alignment pins the lone standalone tab
+ // to the end.
+ horizontalArrangement = if (hasTabGroup) {
+ Arrangement.spacedBy(sizes.componentSpacing)
+ } else {
+ Arrangement.End
+ },
+ verticalAlignment = Alignment.CenterVertically
) {
- if (hasTabGroup) {
+ if (hasTabGroup && expandedTabs != null) {
+ // The caller's own tab group, in the place the library's would
+ // have had and travelling as the same shared element; see the
+ // parameter.
+ Box(
+ Modifier
+ .weight(1f)
+ .then(
+ if (expandedTabsHeight != Dp.Unspecified) {
+ Modifier.height(expandedTabsHeight)
+ } else {
+ Modifier
+ }
+ )
+ .sharedElement(
+ sharedContentState = rememberSharedContentState("tabGroup"),
+ animatedVisibilityScope = animatedVisibilityScope,
+ zIndexInOverlay = 1f
+ )
+ ) {
+ // The scopes go with it: the row is drawn by the caller,
+ // and the parts of it that survive the fold — the search
+ // slot, which becomes the circle — have to be able to say
+ // so. Same shape the accessory is handed.
+ expandedTabs(Modifier.fillMaxWidth(), animatedVisibilityScope)
+ }
+ } else if (hasTabGroup) {
ExpandedTabs(
scope = scope,
+ tabsFillWidth = tabsFillWidth,
+ selectedTabSurface = selectedTabSurface,
selectedTabKey = selectedTabKey,
shapes = shapes,
- sizes = fittedSizes,
- colors = colors,
- elevations = elevations,
- animatedVisibilityScope = animatedVisibilityScope,
- tabBarContentModifier = tabBarContentModifier,
- backdrop = backdrop,
- accentColor = accentColor ?: colors.backgroundColor,
- // Weighted, so the row can never hand it more than what is
- // left beside the circle; fill = false so a wide screen
- // does not stretch it past its own width either.
- modifier = Modifier.weight(1f, fill = false)
- )
- }
-
- if (standaloneTab != null) {
- ExpandedStandaloneTab(
- standaloneTab = standaloneTab,
- shapes = shapes,
- sizes = sizes,
+ sizes = sizes,
colors = colors,
elevations = elevations,
animatedVisibilityScope = animatedVisibilityScope,
tabBarContentModifier = tabBarContentModifier,
modifier = Modifier
- .onSizeChanged { circleWidthPx = it.width }
- // Same floor the inline row already needed: IntrinsicSize.Max
- // can under-report the tab group's real height, and without a
- // floor this circle shrinks to that under-reported value while
- // the tab pill measures its true (taller) content — which is
- // the search pill looking smaller than the nav bar.
- .defaultMinSize(minHeight = 48.dp)
- .fillMaxHeight()
- // Height-first, as in the inline row: the default resolves the
- // square from maxWidth, so leftover row width could decide the
- // diameter instead of the bar height.
- .aspectRatio(1f, matchHeightConstraintsFirst = true)
+ .weight(1f)
+ .wrapContentWidth(align = Alignment.Start)
)
}
- }
- }
-}
-/**
- * Vendored addition: the search-active expanded shape. Same accessory-above
- * treatment as [ExpandedBar], but the row below it is the collapsed-style
- * single current-screen icon ([InlineTab], reused as-is) next to
- * [searchBarContent] filling the rest of the row — instead of the full
- * tab-group pill + circular standalone tab.
- */
-@Composable
-private fun SharedTransitionScope.SearchExpandedBar(
- scope: FloatingTabBarScopeImpl,
- selectedTabKey: Any?,
- accessory: (@Composable SharedTransitionScope.(Modifier, AnimatedVisibilityScope) -> Unit)?,
- isAccessoryShared: Boolean,
- colors: FloatingTabBarColors,
- shapes: FloatingTabBarShapes,
- sizes: FloatingTabBarSizes,
- elevations: FloatingTabBarElevations,
- tabBarContentModifier: Modifier,
- animatedVisibilityScope: AnimatedVisibilityScope,
- searchBarContent: @Composable (Modifier) -> Unit,
- // Vendored addition: the normal-expanded row's own last-measured width
- // (see ExpandedBar's onWidthMeasured) — holding this row to that same
- // width keeps the bar's overall footprint constant across search mode
- // instead of the searchBarContent's weight(1f) filling all available
- // space. Null/0 (nothing measured yet) falls back to filling available
- // width.
- targetWidthPx: Int?,
-) {
- val inlineTab = scope.getInlineTab(selectedTabKey)
- val density = LocalDensity.current
- val targetWidthModifier = if (targetWidthPx != null && targetWidthPx > 0) {
- Modifier.width(with(density) { targetWidthPx.toDp() })
- } else {
- Modifier.fillMaxWidth()
- }
-
- Column(
- horizontalAlignment = Alignment.CenterHorizontally,
- verticalArrangement = Arrangement.spacedBy(sizes.componentSpacing),
- modifier = Modifier.fillMaxWidth()
- ) {
- if (accessory != null) {
- ExpandedAccessory(
- accessory = accessory,
- isAccessoryShared = isAccessoryShared,
- shapes = shapes,
- colors = colors,
- elevations = elevations,
- animatedVisibilityScope = animatedVisibilityScope,
- modifier = targetWidthModifier
- )
- }
-
- Row(
- horizontalArrangement = Arrangement.spacedBy(sizes.componentSpacing),
- verticalAlignment = Alignment.CenterVertically,
- // Fixed rather than IntrinsicSize.Max: matches the mini player's own
- // inline (shrunk) height exactly instead of letting a short
- // searchBarContent under-report its intrinsic height and shrink the row.
- modifier = Modifier.height(SearchBarRowHeight).then(targetWidthModifier)
- ) {
- if (inlineTab != null) {
- InlineTab(
- inlineTab = inlineTab,
- // Already expanded — a tap here should just navigate
- // (inlineTab.onClick, fired inside InlineTab itself), not
- // trigger the inline scroll-connection's expand().
- onInlineTabClick = {},
+ if (hasStandaloneTab) {
+ ExpandedStandaloneTab(
+ selectedTabKey = selectedTabKey,
+ standaloneTab = standaloneTab,
shapes = shapes,
- sizes = sizes,
colors = colors,
elevations = elevations,
animatedVisibilityScope = animatedVisibilityScope,
tabBarContentModifier = tabBarContentModifier,
- modifier = Modifier.fillMaxHeight()
+ // When there is no tab group to match height with, the square would collapse to
+ // the bare icon size. Apply the expanded tab content padding so it stays sized
+ // like a tab would be.
+ contentPadding = if (hasTabGroup) null else sizes.tabExpandedContentPadding,
+ modifier = if (hasTabGroup) {
+ Modifier
+ .fillMaxHeight()
+ .aspectRatio(1f)
+ } else {
+ Modifier.aspectRatio(1f)
+ }
)
}
-
- searchBarContent(
- Modifier
- .weight(1f)
- .fillMaxHeight()
- // Same "standaloneTab" key as ExpandedStandaloneTab/InlineStandaloneTab
- // (the search circle) — without this the circle just pops out and the
- // bar pops in as two unrelated fades instead of one smoothly growing
- // pill; this is what makes the tab-group icon side already morph
- // smoothly, and lets the search-inline (scrolled) state morph back
- // down to a circle too.
- .sharedElement(
- sharedContentState = rememberSharedContentState("standaloneTab"),
- animatedVisibilityScope = animatedVisibilityScope,
- zIndexInOverlay = 1f
- )
- .shadow(shape = shapes.tabBarShape, elevation = elevations.expandedElevation)
- .background(color = colors.backgroundColor, shape = shapes.tabBarShape)
- .clip(shapes.tabBarShape)
- .then(tabBarContentModifier)
- )
}
}
}
-@Composable
-private fun SharedTransitionScope.ExpandedStandaloneTab(
- standaloneTab: FloatingTabBarTab,
- shapes: FloatingTabBarShapes,
- sizes: FloatingTabBarSizes,
- colors: FloatingTabBarColors,
- elevations: FloatingTabBarElevations,
- animatedVisibilityScope: AnimatedVisibilityScope,
- modifier: Modifier,
- tabBarContentModifier: Modifier
-) {
- // Same finger-tracking glow as the keyboard-active search pill
- // (NavBarSearchInputBar) — a soft radial light following the touch point.
- val glowScope = rememberCoroutineScope()
- val glow = remember(glowScope) { InteractiveHighlight(animationScope = glowScope) }
-
- Tab(
- icon = standaloneTab.icon,
- title = standaloneTab.title,
- isInline = true,
- isStandalone = true,
- modifier = modifier
- .sharedElement(
- sharedContentState = rememberSharedContentState("standaloneTab"),
- animatedVisibilityScope = animatedVisibilityScope,
- zIndexInOverlay = 1f
- )
- .shadow(
- shape = shapes.standaloneTabShape,
- elevation = elevations.expandedElevation
- )
- .background(
- color = colors.backgroundColor,
- shape = shapes.standaloneTabShape
- )
- .clip(shapes.standaloneTabShape)
- .then(tabBarContentModifier)
- .then(glow.gestureModifier)
- .then(glow.modifier)
- .tapClickable(
- indication = standaloneTab.indication?.invoke(),
- onClick = standaloneTab.onClick
- )
- // Unlike the regular tab pill (ExpandedTabs), this circle had no inset
- // at all — the icon sat flush against its edge.
- .padding(sizes.tabExpandedContentPadding)
- )
-}
-
@Composable
private fun SharedTransitionScope.ExpandedAccessory(
accessory: @Composable SharedTransitionScope.(Modifier, AnimatedVisibilityScope) -> Unit,
@@ -1182,10 +1039,11 @@ private fun SharedTransitionScope.ExpandedAccessory(
)
}
}
-
@Composable
private fun SharedTransitionScope.ExpandedTabs(
scope: FloatingTabBarScopeImpl,
+ tabsFillWidth: Boolean = false,
+ selectedTabSurface: (@Composable () -> Modifier)? = null,
selectedTabKey: Any?,
shapes: FloatingTabBarShapes,
sizes: FloatingTabBarSizes,
@@ -1193,660 +1051,189 @@ private fun SharedTransitionScope.ExpandedTabs(
elevations: FloatingTabBarElevations,
animatedVisibilityScope: AnimatedVisibilityScope,
modifier: Modifier,
- tabBarContentModifier: Modifier,
- backdrop: Backdrop?,
- accentColor: Color
+ tabBarContentModifier: Modifier
) {
- // The standalone tab (e.g. search) never appears here — it's always its
- // own floating circle, rendered as a sibling by ExpandedBar (see
- // ExpandedStandaloneTab). Only the regular tabs form this pill/puck group.
- val allTabs = scope.tabs
- val tabsCount = allTabs.size
- if (tabsCount == 0) return
- // dampedDragAnimation is remember(...)-ed and its onDragStopped closure would
- // otherwise capture the FIRST composition's allTabs — freezing each tab's
- // onClick (and the isSelected it closed over). That stranded drag-to-Home:
- // Home started selected, so its frozen onClick did scroll-to-top forever
- // instead of navigating. Read the live tabs through this instead.
- val currentTabs = rememberUpdatedState(allTabs)
-
- val density = LocalDensity.current
- val layoutDirection = LocalLayoutDirection.current
- val isLtr = layoutDirection == LayoutDirection.Ltr
- val animationScope = rememberCoroutineScope()
- val glassConfig = LocalGlassEffectConfig.current
- // Puck wash. Unset follows the theme rather than assuming a dark bar: a light
- // scheme gets a light wash, so the pill still reads as a raised surface instead
- // of a black patch.
- val puckWash = if (glassConfig.puckColor.isSpecified) {
- glassConfig.puckColor
- } else if (MaterialTheme.colorScheme.surface.luminance() > 0.5f) {
- Color(0xFFF2F2F2)
- } else {
- Color(28, 27, 28)
- }
- val puckRestAlpha = glassConfig.puckOpacity.coerceIn(0f, 1f)
-
- val tabWidthPx = with(density) { sizes.tabWidth.toPx() }
- // The row's own content padding insets the tabs from the pill's edges, so
- // the puck (a sibling, not a row child) has to account for it explicitly —
- // otherwise it drifts out of alignment with where the tabs actually sit.
- val paddingStartPx = with(density) { sizes.tabBarContentPadding.calculateStartPadding(layoutDirection).toPx() }
- val paddingEndPx = with(density) { sizes.tabBarContentPadding.calculateEndPadding(layoutDirection).toPx() }
- val totalWidthPx = tabWidthPx * tabsCount + paddingStartPx + paddingEndPx
-
- // Ported from LiquidBottomTabs: the whole pill nudges a few dp in the drag
- // direction (eased, clamped) so it feels like it's being tugged, not just
- // the puck sliding inside a static shell.
- val offsetAnimation = remember(tabsCount) { Animatable(0f) }
- val panelOffset by remember(density, totalWidthPx) {
- derivedStateOf {
- val fraction = (offsetAnimation.value / totalWidthPx).fastCoerceIn(-1f, 1f)
- with(density) {
- 4f.dp.toPx() * fraction.sign * EaseOut.transform(abs(fraction))
- }
- }
- }
+ val inlineTab = scope.getInlineTab(selectedTabKey)
- var currentIndex by remember(tabsCount) {
- mutableIntStateOf(
- allTabs.indexOfFirst { it.key == selectedTabKey }.coerceIn(0, tabsCount - 1)
- )
- }
- // Matches Kyant's LiquidBottomTabs behavior exactly: navigation fires ONLY
- // in onDragStopped (finger lifted, puck settling onto its target) — never
- // mid-drag. An earlier "predictive fire" here navigated while the puck was
- // still being dragged, which opened screens before the drop.
- // inspectDragGestures (vendored) fires onDragStart/onDrag/onDragEnd for a
- // plain tap-through too, with zero net movement, and never consumes the
- // touch — so a tap that lands on the puck while it's mid-sweep between
- // two tabs would otherwise re-navigate to targetValue (the sweep's
- // destination) on top of whatever the tapped tab's own tapClickable just
- // navigated to. Gate the puck's own navigate-on-release to genuine drags.
- var hasDraggedPuck = false
- val dampedDragAnimation = remember(animationScope, tabsCount) {
- DampedDragAnimation(
- animationScope = animationScope,
- initialValue = currentIndex.toFloat(),
- valueRange = 0f..(tabsCount - 1).toFloat(),
- visibilityThreshold = 0.001f,
- initialScale = 1f,
- // Matches LiquidBottomTabs' literal ratio (78dp/56dp) rather than a
- // fraction of our own tab width — a proportional scale factor, not
- // an absolute size, so it should track the source value directly.
- pressedScale = 78f / 56f,
- onDragStarted = { hasDraggedPuck = false },
- onDragStopped = {
- val targetIndex = targetValue.fastRoundToInt().coerceIn(0, tabsCount - 1)
- currentIndex = targetIndex
- // updateValue (not animateToValue): the modifier's own
- // onDragStart/onDragEnd already own the press-grow + release
- // shrink. animateToValue pressed a SECOND time and, worse, ran
- // under mutatorMutex — a later sync could cancel it mid-settle
- // and strand the puck at the old index (puck stuck on Home while
- // a different screen is showing). updateValue just springs the
- // position, no press, no mutex.
- updateValue(targetIndex.toFloat())
- animationScope.launch {
- offsetAnimation.animateTo(0f, spring(1f, 300f, 0.5f))
- }
- if (hasDraggedPuck) {
- currentTabs.value.getOrNull(targetIndex)?.onClick?.invoke()
- }
- },
- onDrag = { _, dragAmount ->
- if (dragAmount != Offset.Zero) hasDraggedPuck = true
- updateValue(
- (targetValue + dragAmount.x / tabWidthPx * if (isLtr) 1f else -1f)
- .fastCoerceIn(0f, (tabsCount - 1).toFloat())
- )
- animationScope.launch {
- offsetAnimation.snapTo(offsetAnimation.value + dragAmount.x)
+ // LOCAL CHANGE: the lit slot as a shape that travels.
+ //
+ // Upstream fades a colour in behind whichever tab is selected, so the mark
+ // appears in its new place rather than moving there. With the tabs sharing
+ // the row equally, where the mark belongs is arithmetic — the slot index
+ // times the slot width — so it can simply be drawn once and moved, and a
+ // spring is what carries it. See selectedTabSurface.
+ val puckIndex = scope.tabs.indexOfFirst { it.key == selectedTabKey }
+ val travellingPuck = selectedTabSurface != null && tabsFillWidth && puckIndex >= 0
+ val puckOffset by animateFloatAsState(
+ targetValue = puckIndex.coerceAtLeast(0).toFloat(),
+ animationSpec = spring(dampingRatio = 0.8f, stiffness = 500f),
+ label = "puckOffset"
+ )
+
+ Row(
+ horizontalArrangement = Arrangement.spacedBy(sizes.tabSpacing),
+ modifier = modifier
+ .sharedElement(
+ sharedContentState = rememberSharedContentState("tabGroup"),
+ animatedVisibilityScope = animatedVisibilityScope,
+ zIndexInOverlay = 1f
+ )
+ .shadow(
+ shape = shapes.tabBarShape,
+ elevation = elevations.expandedElevation
+ )
+ .background(
+ color = colors.backgroundColor,
+ shape = shapes.tabBarShape
+ )
+ .clip(shapes.tabBarShape)
+ .then(tabBarContentModifier)
+ .padding(sizes.tabBarContentPadding)
+ .then(
+ if (tabsFillWidth) {
+ Modifier
+ } else {
+ Modifier.wrapContentWidth(align = Alignment.Start, unbounded = true)
}
- },
- // Critically damped, so the stretch tracks the drag instead of ringing
- // after it: the library's underdamped default is what made the puck
- // wobble as it crossed each tab.
- )
- }
- // False until this bar has run its selection sync once. Expanding back from
- // inline builds a brand new ExpandedBar (it is its own AnimatedContent
- // branch), so everything here re-remembers and this effect fires on first
- // composition — with the puck ALREADY on the right tab, because
- // dampedDragAnimation starts at currentIndex. animateToValue would then
- // press-grow and release the puck without moving it anywhere, launched into a
- // coroutine under mutatorMutex so it lands a frame or two into the crossfade:
- // the indicator appears to pop in late and twitch. On that first pass the
- // position is already correct, so there is nothing to animate.
- var hasSyncedSelection by remember(tabsCount) { mutableStateOf(false) }
- // Keeps the puck synced when selection changes from a tap (or external
- // navigation) rather than a drag on this bar.
- LaunchedEffect(selectedTabKey, tabsCount) {
- val index = allTabs.indexOfFirst { it.key == selectedTabKey }
- if (index != -1) {
- currentIndex = index
- if (!hasSyncedSelection) {
- hasSyncedSelection = true
- // Pin without the press animation; already in the right place.
- dampedDragAnimation.updateValue(index.toFloat())
- return@LaunchedEffect
- }
- // Re-pin on EVERY selection change, not only when currentIndex differs:
- // the puck's animated value can drift out from under a matching currentIndex
- // (a cancelled drag, an interrupted settle) and strand the indicator on the
- // wrong tab — the "selected icon doesn't update" bug. Forcing this here
- // always snaps it back to the actually-selected route.
- //
- // animateToValue (not updateValue): a tap should feel like a drag-release —
- // the same press/grow-then-settle the puck does when you actually drag it,
- // not just a bare position slide. This used to fall back to updateValue
- // because animateToValue's press-grow visibly doubled the selected icon
- // against the puck's glass copy — that's fixed now (the hidden backdrop row's
- // contentScale and padding are kept in sync with the visible row, see above).
- dampedDragAnimation.animateToValue(index.toFloat())
+ )
+ .animateContentSize()
+ ) {
+ if (travellingPuck) {
+ val slots = scope.tabs.size.coerceAtLeast(1)
+ Box(
+ Modifier
+ // Laid out as one slot of the row, then moved by whole slots:
+ // it occupies the same width a tab does, so the shape is the
+ // tab's own rather than something sized by eye.
+ .fillMaxWidth(1f / slots)
+ .fillMaxHeight()
+ .graphicsLayer {
+ translationX = puckOffset * size.width
+ }
+ .then(selectedTabSurface!!())
+ )
}
- }
-
- val interactiveHighlight = remember(animationScope) {
- InteractiveHighlight(
- animationScope = animationScope,
- position = { size, offset ->
- Offset(
- if (isLtr) paddingStartPx + (dampedDragAnimation.value + 0.5f) * tabWidthPx + panelOffset
- else size.width - paddingStartPx - (dampedDragAnimation.value + 0.5f) * tabWidthPx + panelOffset,
- size.height / 2f
- )
- }
- )
- }
-
- // Invisible tinted copy of the tabs, sampled by the puck below so the
- // selected icon shows through the glass in the accent color.
- val tabsBackdrop = rememberLayerBackdrop()
- // Whether the accent-tinted copy of the tabs is worth keeping alive; see
- // where it is composed below.
- val tabsTinted = dampedDragAnimation.pressProgress > 0f
-
- Box(modifier.width(with(density) { totalWidthPx.toDp() })) {
- Row(
- Modifier
- .fillMaxSize()
- .graphicsLayer { translationX = panelOffset }
- .sharedElement(
- sharedContentState = rememberSharedContentState("tabGroup"),
- animatedVisibilityScope = animatedVisibilityScope,
- zIndexInOverlay = 1f
- )
- .shadow(
- shape = shapes.tabBarShape,
- elevation = elevations.expandedElevation
- )
- .background(
- color = colors.backgroundColor,
- shape = shapes.tabBarShape
- )
- .clip(shapes.tabBarShape)
- .then(tabBarContentModifier)
- .then(interactiveHighlight.modifier)
- .padding(sizes.tabBarContentPadding),
- horizontalArrangement = Arrangement.spacedBy(sizes.tabSpacing)
- ) {
- allTabs.forEachIndexed { index, tab ->
- Tab(
- icon = {
- Box(
- modifier = Modifier
- .graphicsLayer {
- // Unselected tabs sit back; the selected one is
- // never dimmed, so the puck must not darken it.
- alpha = if (tab.key == selectedTabKey) 1f else 0.6f
- }
- .then(
- if (tab.key == selectedTabKey) {
- Modifier.sharedElement(
- sharedContentState = rememberSharedContentState("tab#${tab.key}-icon"),
- animatedVisibilityScope = animatedVisibilityScope,
- zIndexInOverlay = 1f
- )
- } else {
- Modifier.animateEnterExitTab(
- sharedTransitionScope = this@ExpandedTabs,
- animatedVisibilityScope = animatedVisibilityScope
- )
- }
- )
- ) {
- tab.icon()
- }
- },
- title = {
- Box(
+ scope.tabs.forEach { tab ->
+ val isSelected = tab.key == selectedTabKey
+ val animatedBgColor by animateColorAsState(
+ targetValue = if (isSelected && !travellingPuck) {
+ colors.selectedTabBackgroundColor
+ } else {
+ Color.Transparent
+ },
+ label = "tab_selected_bg"
+ )
+ Tab(
+ icon = {
+ Box(
+ modifier = if (tab.key == inlineTab?.key) {
+ Modifier.sharedElement(
+ sharedContentState = rememberSharedContentState("tab#${tab.key}-icon"),
+ animatedVisibilityScope = animatedVisibilityScope,
+ zIndexInOverlay = 1f
+ )
+ } else {
Modifier.animateEnterExitTab(
sharedTransitionScope = this@ExpandedTabs,
animatedVisibilityScope = animatedVisibilityScope
)
- ) {
- tab.title()
}
- },
- isInline = false,
- isStandalone = false,
- contentScale = if (index == currentIndex) {
- lerp(1f, 1.12f, dampedDragAnimation.pressProgress)
- } else {
- 1f
- },
- modifier = Modifier
- .weight(1f)
- .fillMaxHeight()
- .skipToLookaheadSize()
- .clip(shapes.tabShape)
- .tapClickable(
- indication = tab.indication?.invoke(),
- onClick = tab.onClick
- )
- .padding(sizes.tabExpandedContentPadding)
- )
- }
- }
-
- // LOCAL CHANGE: only while the puck is being touched.
- //
- // This is a second, invisible copy of the whole tab row, kept so the
- // selected icon can show through the puck's glass in the accent colour.
- // It is also a full row composed, measured and recorded into a layer for
- // every frame the bar is on screen, which is every frame of every scroll:
- // measured at 8ms a frame on the home page, for a tint that only exists
- // while a finger is on the puck. Composed when that happens instead.
- if (backdrop != null && tabsTinted) {
- // Fixed 1dp blur here (see the blur() call below), so this is a
- // stable fraction, not something that needs recomputing per frame.
- val tabsBackdropScale = glassResolutionScale(1f)
- Row(
- Modifier
- .fillMaxWidth()
- .clearAndSetSemantics {}
- .alpha(0f)
- .layerBackdrop(tabsBackdrop)
- .graphicsLayer { translationX = panelOffset }
- // Padding here (not after drawBackdrop, like the tail
- // .padding below) so it actually shrinks this row's own
- // measured bounds — matching LiquidBottomTabs' explicit
- // .height(56dp) vs the main row's 64dp: what tabsBackdrop
- // captures needs to be genuinely inset, not full-bleed.
- .padding(sizes.tabBarContentPadding)
- // Ported from LiquidBottomTabs: this hidden row isn't just a
- // tinted icon cutout, it's a real blurred/lensed glass sample
- // of the screen behind the bar — that's what makes the puck
- // below look like it's made of the *bar's* frosted material
- // (not a flat color) when it slides underneath.
- .drawBackdrop(
- backdrop = backdrop,
- shape = { shapes.tabBarShape },
- effects = {
- val progress = dampedDragAnimation.pressProgress
- vibrancy()
- // Without any blur here, this hidden row's lens()
- // distortion (below) samples the raw, sharp backdrop —
- // that's what made the puck look like undistorted,
- // "blur gone" background while dragging. Kyant's source
- // uses a fixed 8dp; we drive it from the user's own
- // glass blur-intensity setting instead of hardcoding.
- blur(glassConfig.blurRadius.dp.toPx() * tabsBackdropScale)
- lens(
- 15f.dp.toPx() * progress * tabsBackdropScale,
- 18f.dp.toPx() * progress * tabsBackdropScale
- )
- },
- highlight = {
- val progress = dampedDragAnimation.pressProgress
- Highlight.Default.copy(alpha = progress)
- },
- onDrawSurface = { drawRect(colors.backgroundColor) },
- backdropScale = tabsBackdropScale,
- frozen = LocalTabBarBackdropFrozen.current,
- // Same GPU-saving trick as Modifier.liquidGlass: record this
- // hidden row at a fraction of surface resolution and let the
- // blur hide the upscale — was left at the 1f (full-res)
- // default here even though liquidGlass already uses this.
- )
- .then(interactiveHighlight.modifier)
- // NOT a second .padding(sizes.tabBarContentPadding) here — the one
- // above (before drawBackdrop) already insets this row's measured
- // bounds. A second one compounded the inset only on this hidden
- // row (the visible row above applies it exactly once), shifting
- // its tabs right of their real counterparts — the puck's sampled
- // icon then visibly drifted from the real icon under it.
- .graphicsLayer(colorFilter = ColorFilter.tint(accentColor)),
- horizontalArrangement = Arrangement.spacedBy(sizes.tabSpacing)
- ) {
- allTabs.forEachIndexed { index, tab ->
- Tab(
- icon = tab.icon,
- title = tab.title,
- isInline = false,
- isStandalone = false,
- // Must match the visible row's per-tab contentScale (see
- // above) — this hidden row is what the puck's glass samples,
- // so if it doesn't zoom in sync with the real icon during a
- // press/drag, the accent-tinted copy visibly drifts from the
- // real icon on top, reading as a ghosted double image.
- contentScale = if (index == currentIndex) {
- lerp(1f, 1.12f, dampedDragAnimation.pressProgress)
- } else {
- 1f
- },
- modifier = Modifier
- .weight(1f)
- .fillMaxHeight()
- // Must match the visible row's skipToLookaheadSize() too
- // (see below) — without it this hidden row can measure a
- // hair differently under the shared-transition lookahead
- // pass, leaving the puck's sampled icon slightly off from
- // the real one even at rest.
- .skipToLookaheadSize()
- .padding(sizes.tabExpandedContentPadding)
- )
- }
- }
- }
-
- // The draggable selection puck. Position and press/velocity-driven
- // scale come from dampedDragAnimation; tapping a tab still works via
- // each tab's own clickable — the puck only intercepts drags.
- //
- // LOCAL CHANGE: it grows in with the tabs it belongs to. The tab group is
- // a shared element and travels between the two states; the puck is not
- // part of it, so coming back from the folded bar it simply appeared,
- // final size and full strength, over tabs that were still on their way.
- //
- // A fade alone was not enough to fix that, and it is worth saying why: at
- // 160ms over a fold that takes twice as long, what you see is a
- // fully-formed puck arriving early and quickly — which is the same
- // complaint. It has to be the same length as the movement it belongs to,
- // and it has to move: the scale is what makes it read as the puck
- // settling onto the tab rather than being switched on there.
- // Driven from this composable's own first frame rather than from the
- // enter transition, which was the second wrong answer here and is worth
- // recording. Hung off `animatedVisibilityScope.transition`, the animation
- // starts at whatever the transition already is — and by the time the
- // expanded bar composes its puck, the transition has usually moved on, so
- // the value began at 1 and nothing animated at all. An Animatable started
- // on composition cannot miss its own beginning.
- val puckEnter = remember { Animatable(0f) }
- LaunchedEffect(Unit) {
- puckEnter.animateTo(1f, tween(durationMillis = PuckEnterMs, easing = FastOutSlowInEasing))
- }
- // See the `frozen` argument below: the puck may only hold a capture once
- // it has one. A lambda so flipping it costs no recomposition — the glass
- // asks during draw.
- val tabBarFrozen = LocalTabBarBackdropFrozen.current
- val puckFrozen = remember(tabBarFrozen, puckEnter) {
- { tabBarFrozen() && puckEnter.value >= 1f }
- }
- Box(
- Modifier
- .padding(sizes.tabBarContentPadding)
- // NOT rendered in the shared transition overlay, though the tab
- // row above it is, and that is why the indicator only becomes
- // visible when the unfold ends: for the frames of the transition
- // the row is drawn in the overlay, over everything else in the
- // layout, and the puck fades in underneath it. Putting the puck
- // in the overlay too is the obvious answer and was tried: the
- // overlay positions it in its own coordinates, so it left the bar
- // entirely and sat lit up over the mini player. Left as it is,
- // rather than half-fixed.
- .graphicsLayer {
- val enter = puckEnter.value
- alpha = enter
- val enterScale = lerp(PuckEnterScale, 1f, enter)
- scaleX = enterScale
- scaleY = enterScale
- translationX =
- if (isLtr) dampedDragAnimation.value * tabWidthPx + panelOffset
- else size.width - (dampedDragAnimation.value + 1f) * tabWidthPx + panelOffset
- }
- .then(interactiveHighlight.gestureModifier)
- .then(dampedDragAnimation.modifier)
- .width(sizes.tabWidth)
- .fillMaxHeight()
- // The puck's shape in plain paint, under the glass, while it is
- // arriving. Fading a pane of glass in is fading in something that
- // has nothing to show yet: a backdrop-sampling surface has no
- // capture on its first frames, so for the length of the entrance
- // the animation was running over an empty pill and the puck still
- // looked like it appeared all at once, at the end. This is what
- // grows into place; the glass takes over from underneath it as
- // soon as it has something to refract, and both draw the same
- // wash, so the hand-over is not a change of colour.
- .drawBehind {
- val enter = puckEnter.value
- if (enter < 1f) {
- drawOutline(
- shapes.tabShape.createOutline(size, layoutDirection, this),
- color = puckWash.copy(alpha = puckRestAlpha * (1f - enter)),
- )
+ ) {
+ tab.icon()
}
- }
- .then(
- if (backdrop != null) {
- Modifier.drawBackdrop(
- // Only combined while the hidden row above exists.
- // An empty layer has no version for the surface to
- // compare against, so sampling one makes the puck
- // re-record the screen on every single frame — which
- // is worse than the row it was meant to save.
- backdrop = rememberCombinedBackdrop(backdrop, tabsBackdrop)
- .takeIf { tabsTinted } ?: backdrop,
- shape = { shapes.tabShape },
- effects = {
- val progress = dampedDragAnimation.pressProgress
- // Soft frosted puck at rest (constant blur), deepening
- //
- blur(3f.dp.toPx() * (1f - progress))
-
- // Refraction is weakest at REST and deepens while the
- // puck is held and dragged: at rest the sharp overlay
- // icon sits on top at full alpha, and any real bend
- // there splits it from its lensed copy underneath —
- // the doubled/ghosted icon. That overlay fades out
- // over the first third of the press ramp, so by the
- // time the bend is at full strength there is only one
- // copy left to warp.
- lens(
- lerp(0f.dp.toPx(), 10f.dp.toPx(), progress),
- lerp(0f.dp.toPx(), 12f.dp.toPx(), progress),
- // Dispersion is a drag-only flourish. It costs a
- // second, heavier shader, so a puck sitting still
- // should not be paying for it.
- chromaticAberration = progress > 0.01f
- )
- },
- highlight = {
- val progress = dampedDragAnimation.pressProgress
- // Floored, not 0-at-rest. With no rim the puck's
- // shape came entirely from its dark wash below,
- // so it vanished into the bar whenever the bar
- // itself sat on dark content. A specular rim
- // reads against light AND dark, and unlike
- // lightening the wash it leaves the selected
- // icon (white by default, drawn on top) legible.
- Highlight.Default.copy(
- alpha = lerp(PuckRestHighlightAlpha, 1f, progress)
- )
- },
- shadow = {
- val progress = dampedDragAnimation.pressProgress
- // Same reasoning: a little separation at rest so
- // the puck reads as a raised element rather than
- // a flat patch of the bar.
- Shadow(alpha = lerp(PuckRestShadowAlpha, 1f, progress))
- },
- innerShadow = {
- val progress = dampedDragAnimation.pressProgress
- InnerShadow(radius = 8f.dp * progress, alpha = progress)
- },
- layerBlock = {
- scaleX = dampedDragAnimation.scaleX
- scaleY = dampedDragAnimation.scaleY
- val velocity = dampedDragAnimation.velocity / 10f
- scaleX /= 1f - (velocity * 0.75f).fastCoerceIn(-0.2f, 0.2f)
- scaleY *= 1f - (velocity * 0.25f).fastCoerceIn(-0.2f, 0.2f)
- },
- onDrawSurface = {
- // What shows inside the puck is the hidden tinted tab
- // row sampled back through this glass, so anything
- // painted here lands ON TOP of the selected icon.
- // Black at any real strength crushes it — hence an
- // accent wash that defines the pill's shape while
- // leaving the icon at full strength, deepening only
- // while pressed.
- val progress = dampedDragAnimation.pressProgress
-
- // Was a hardcoded near-black at 0.8 alpha, which on a
- // dark bar made the whole puck read as a dark blob and
- // on a light theme was simply wrong. Colour and resting
- // opacity are configurable now, and the unset default
- // follows the theme instead of assuming dark.
- drawRect(puckWash.copy(alpha = puckRestAlpha * (1f - 0.75f * progress)))
- },
- // LOCAL CHANGE, and this is what actually made the
- // indicator appear out of nowhere. Freezing tells a
- // surface to reuse its last capture instead of
- // re-recording the screen while its bounds animate —
- // which is right for the bar, and wrong for the puck:
- // the puck does not exist while the bar is folded, so
- // for the whole of the unfold it was reusing a capture
- // it had never taken, and drew nothing at all. It
- // arrived the instant the transition ended and the
- // freeze lifted, at full strength, on the frame after
- // everything else had finished moving. So it records
- // for the frames it is arriving on, and freezes with
- // the rest of the bar once it is there.
- frozen = puckFrozen,
+ },
+ title = {
+ Box(
+ Modifier.animateEnterExitTab(
+ sharedTransitionScope = this@ExpandedTabs,
+ animatedVisibilityScope = animatedVisibilityScope
)
- } else {
- Modifier
- .graphicsLayer {
- scaleX = dampedDragAnimation.scaleX
- scaleY = dampedDragAnimation.scaleY
- }
- .shadow(
- shape = shapes.tabShape,
- elevation = elevations.expandedElevation * dampedDragAnimation.pressProgress
- )
- .background(
- colors.backgroundColor.copy(
- alpha = 0.5f + 0.5f * dampedDragAnimation.pressProgress
- ),
- shapes.tabShape
- )
- .clip(shapes.tabShape)
+ ) {
+ tab.title()
}
- )
- )
-
- // The selected icon, drawn a second time above the puck.
- //
- // What shows *through* the puck is the hidden accent-tinted tab row
- // refracted by the glass, and the puck's surface tint necessarily paints
- // over it — so that copy can never be at full opacity. Redrawing the icon
- // here is the only way to keep it crisp.
- //
- // It rides the puck's own translation and squash, so the two cannot drift
- // apart mid-drag, and it always covers the dimmed copy underneath rather
- // than ghosting beside it. Which icon to draw is derived state, so this
- // recomposes when the puck crosses into a new tab, not every frame.
- val puckIndex by remember(tabsCount) {
- derivedStateOf {
- dampedDragAnimation.value
- .fastRoundToInt()
- .coerceIn(0, (tabsCount - 1).coerceAtLeast(0))
- }
- }
- Box(
- Modifier
- .padding(sizes.tabBarContentPadding)
- .graphicsLayer {
- translationX =
- if (isLtr) dampedDragAnimation.value * tabWidthPx + panelOffset
- else size.width - (dampedDragAnimation.value + 1f) * tabWidthPx + panelOffset
- scaleX = dampedDragAnimation.scaleX
- scaleY = dampedDragAnimation.scaleY
- // Settled state only. Fades roughly three times faster than the
- // press ramp, so it is fully gone a third of the way into the
- // gesture instead of lingering over the moving puck. Read in the
- // draw phase, so it costs no recomposition.
- alpha = (1f - dampedDragAnimation.pressProgress * 3f).fastCoerceIn(0f, 1f)
- }
- .width(sizes.tabWidth)
- .fillMaxHeight()
- // Purely decorative: the tab underneath keeps the click and the
- // semantics, and this must never swallow either.
- .clearAndSetSemantics {},
- ) {
- currentTabs.value.getOrNull(puckIndex)?.let { tab ->
- // Must go through Tab, not just tab.icon(): Tab is a Column of
- // icon THEN title, so drawing the icon alone centres it on the
- // puck while the row centres it on the icon+title pair — which is
- // exactly how far off it looked. Same props as the row's selected
- // tab, so the two line up.
- Tab(
- // No tint override: the icon keeps the selected colour its
- // caller gave it, which is the point of drawing it again.
- icon = { tab.icon() },
- title = { tab.title() },
- isInline = false,
- isStandalone = false,
- // No press zoom: only visible at rest, where the row's own lerp
- // lands on 1f. Leaving it out also stops the overlay recomposing
- // on every frame of a drag.
- modifier = Modifier
- .fillMaxSize()
- .padding(sizes.tabExpandedContentPadding),
- )
- }
+ },
+ isInline = false,
+ modifier = Modifier
+ .then(if (tabsFillWidth) Modifier.weight(1f) else Modifier)
+ .skipToLookaheadSize()
+ .clip(shapes.tabShape)
+ .background(
+ color = animatedBgColor,
+ shape = shapes.tabShape
+ )
+ .clickable(
+ onClick = tab.onClick,
+ indication = tab.indication?.invoke(),
+ interactionSource = remember { MutableInteractionSource() }
+ )
+ .padding(sizes.tabExpandedContentPadding)
+ )
}
}
}
+@Composable
+private fun SharedTransitionScope.ExpandedStandaloneTab(
+ selectedTabKey: Any?,
+ standaloneTab: FloatingTabBarTab,
+ shapes: FloatingTabBarShapes,
+ colors: FloatingTabBarColors,
+ elevations: FloatingTabBarElevations,
+ animatedVisibilityScope: AnimatedVisibilityScope,
+ modifier: Modifier,
+ tabBarContentModifier: Modifier,
+ contentPadding: PaddingValues?
+) {
+ val isSelected = standaloneTab.key == selectedTabKey
+ val animatedBgColor by animateColorAsState(
+ targetValue = if (isSelected) colors.selectedStandaloneTabBackgroundColor else colors.backgroundColor,
+ label = "standalone_tab_selected_bg"
+ )
+ Tab(
+ icon = standaloneTab.icon,
+ title = standaloneTab.title,
+ isInline = false,
+ isStandalone = true,
+ modifier = modifier
+ .sharedElement(
+ sharedContentState = rememberSharedContentState("standaloneTab"),
+ animatedVisibilityScope = animatedVisibilityScope,
+ zIndexInOverlay = 1f
+ )
+ .shadow(
+ shape = shapes.standaloneTabShape,
+ elevation = elevations.expandedElevation
+ )
+ .background(
+ color = animatedBgColor,
+ shape = shapes.standaloneTabShape
+ )
+ .clip(shapes.standaloneTabShape)
+ .then(tabBarContentModifier)
+ .clickable(
+ onClick = standaloneTab.onClick,
+ indication = standaloneTab.indication?.invoke(),
+ interactionSource = remember { MutableInteractionSource() }
+ )
+ .then(if (contentPadding != null) Modifier.padding(contentPadding) else Modifier)
+ )
+}
+
@Composable
private fun Tab(
icon: @Composable () -> Unit,
title: @Composable () -> Unit,
isInline: Boolean,
modifier: Modifier = Modifier,
- isStandalone: Boolean = false,
- // Vendored addition: press-zoom scale for the icon+label, driven by the
- // drag puck's press progress (Kyant's LocalLiquidBottomTabScale trick).
- contentScale: Float = 1f
+ isStandalone: Boolean = false
) {
- val showTitle = !isStandalone && !isInline
Column(
- // A real gap between icon and title, centered as a group — rather than
- // nudging the icon down with a raw offset(), which shifts its drawn
- // position without growing the Column's measured height and gets it
- // clipped by the tab bar's own bounds.
- verticalArrangement = if (showTitle) {
- Arrangement.spacedBy((-2).dp, Alignment.CenterVertically)
- } else {
- Arrangement.Center
- },
+ verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
modifier = modifier
- .then(
- if (contentScale != 1f) {
- Modifier.graphicsLayer {
- scaleX = contentScale
- scaleY = contentScale
- }
- } else {
- Modifier
- }
- )
) {
icon()
- if (showTitle) {
+ if (!isStandalone && !isInline) {
title()
}
}
@@ -1943,18 +1330,17 @@ private class FloatingTabBarScopeImpl : FloatingTabBarScope {
private var inlineTab: FloatingTabBarTab? = null
fun getInlineTab(selectedTabKey: Any?): FloatingTabBarTab? {
- // Screen-accurate: only ever report a regular tab as "the inline tab"
- // when it's actually the current screen. selectedTabKey not matching
- // any regular tab (e.g. currently on the standalone tab) falls back to
- // the last regular tab that really was selected — never a hardcoded
- // default like tabs.firstOrNull(), which would misrepresent Home as
- // selected when the user has never actually been there.
- val selectedTab = tabs.find { it.key == selectedTabKey }
- if (selectedTab != null) {
- inlineTab = selectedTab
- return selectedTab
+ return if (selectedTabKey != standaloneTab?.key) {
+ val selectedTab = tabs.find { it.key == selectedTabKey }
+ if (selectedTab != null) {
+ inlineTab = selectedTab
+ selectedTab
+ } else {
+ inlineTab ?: tabs.firstOrNull()
+ }
+ } else {
+ inlineTab ?: tabs.firstOrNull()
}
- return inlineTab
}
override fun tab(
@@ -1979,12 +1365,11 @@ private class FloatingTabBarScopeImpl : FloatingTabBarScope {
key: Any,
icon: @Composable () -> Unit,
onClick: () -> Unit,
- indication: (@Composable () -> Indication)?,
- title: @Composable () -> Unit
+ indication: (@Composable () -> Indication)?
) {
standaloneTab = FloatingTabBarTab(
key = key,
- title = title,
+ title = {},
icon = icon,
onClick = onClick,
indication = indication
@@ -2007,6 +1392,8 @@ private data class FloatingTabBarTab(
data class FloatingTabBarColors(
val backgroundColor: Color,
val accessoryBackgroundColor: Color,
+ val selectedTabBackgroundColor: Color,
+ val selectedStandaloneTabBackgroundColor: Color,
)
/**
@@ -2039,37 +1426,31 @@ data class FloatingTabBarSizes(
val tabExpandedContentPadding: PaddingValues,
val componentSpacing: Dp,
val tabSpacing: Dp,
- // Vendored addition: fixed width of one expanded tab slot. The drag-puck
- // indicator needs a known per-tab width to map drag offset to tab index,
- // so expanded tabs are equal-width instead of sized to their content.
- val tabWidth: Dp = FloatingTabBarDefaults.TabWidth,
)
/**
* Contains the default values used by [FloatingTabBar].
*/
object FloatingTabBarDefaults {
- /**
- * Width of one expanded tab slot at full size. Callers that have to fit the
- * pill plus the standalone tab into a narrow screen shrink below this — see
- * [com.convx.music.ui.component.AppFloatingNavBar] — so it is the ceiling,
- * not a guarantee.
- */
- val TabWidth: Dp = 88.dp
-
/**
* Creates a [FloatingTabBarColors] that represents the default colors used in a [FloatingTabBar].
*
* @param backgroundColor the color used for the tab bar background
* @param accessoryBackgroundColor the color used for the accessory background
+ * @param selectedTabBackgroundColor the color used for the selected tab background in expanded state
+ * @param selectedStandaloneTabBackgroundColor the color used for the selected standalone tab background in expanded state
*/
@Composable
fun colors(
backgroundColor: Color = MaterialTheme.colorScheme.surfaceContainerHigh,
accessoryBackgroundColor: Color = MaterialTheme.colorScheme.surfaceContainerHigh,
+ selectedTabBackgroundColor: Color = Color.Transparent,
+ selectedStandaloneTabBackgroundColor: Color = Color.Transparent,
): FloatingTabBarColors = FloatingTabBarColors(
backgroundColor = backgroundColor,
accessoryBackgroundColor = accessoryBackgroundColor,
+ selectedTabBackgroundColor = selectedTabBackgroundColor,
+ selectedStandaloneTabBackgroundColor = selectedStandaloneTabBackgroundColor,
)
/**
@@ -2082,14 +1463,10 @@ object FloatingTabBarDefaults {
*/
@Composable
fun shapes(
- // ContinuousRoundedRectangle(percent = 50) instead of RoundedCornerShape/
- // CircleShape: same capsule/circle silhouette, but Kyant0/Capsule's
- // continuous (superellipse) corners instead of Android's circular-arc
- // ones — smoother, and lerp-able for the puck's drag-to-search morph.
- tabBarShape: Shape = ContinuousRoundedRectangle(percent = 50),
- tabShape: Shape = ContinuousRoundedRectangle(percent = 50),
- standaloneTabShape: Shape = ContinuousRoundedRectangle(percent = 50),
- accessoryShape: Shape = ContinuousRoundedRectangle(percent = 50),
+ tabBarShape: Shape = RoundedCornerShape(100),
+ tabShape: Shape = RoundedCornerShape(100),
+ standaloneTabShape: Shape = CircleShape,
+ accessoryShape: Shape = RoundedCornerShape(100),
): FloatingTabBarShapes = FloatingTabBarShapes(
tabBarShape = tabBarShape,
tabShape = tabShape,
@@ -2110,20 +1487,15 @@ object FloatingTabBarDefaults {
fun sizes(
tabBarContentPadding: PaddingValues = PaddingValues(vertical = 4.dp, horizontal = 4.dp),
tabInlineContentPadding: PaddingValues = PaddingValues(10.dp),
- // horizontal was 20dp (the source lib's default for content-hugging
- // tabs); with fixed-width tabWidth cells that ate too much of the
- // budget and clipped labels like "Settings" — tightened to fit text.
- tabExpandedContentPadding: PaddingValues = PaddingValues(vertical = 6.dp, horizontal = 6.dp),
+ tabExpandedContentPadding: PaddingValues = PaddingValues(vertical = 6.dp, horizontal = 20.dp),
componentSpacing: Dp = 8.dp,
tabSpacing: Dp = 0.dp,
- tabWidth: Dp = TabWidth,
): FloatingTabBarSizes = FloatingTabBarSizes(
tabBarContentPadding = tabBarContentPadding,
tabInlineContentPadding = tabInlineContentPadding,
tabExpandedContentPadding = tabExpandedContentPadding,
componentSpacing = componentSpacing,
tabSpacing = tabSpacing,
- tabWidth = tabWidth,
)
/**
diff --git a/app/src/main/java/dev/lelonio/square/ui/library/PlaylistScreen.kt b/app/src/main/java/dev/lelonio/square/ui/library/PlaylistScreen.kt
index 8d91bb7..93982e1 100644
--- a/app/src/main/java/dev/lelonio/square/ui/library/PlaylistScreen.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/library/PlaylistScreen.kt
@@ -19,6 +19,7 @@ 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.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
@@ -42,9 +43,12 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.res.pluralStringResource
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.toArgb
+import androidx.compose.ui.graphics.Shadow
import androidx.compose.ui.graphics.lerp
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.text.AnnotatedString
@@ -52,6 +56,16 @@ 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.compose.ui.unit.TextUnit
+import androidx.compose.ui.draw.drawWithContent
+import androidx.compose.ui.graphics.BlendMode
+import androidx.compose.ui.graphics.CompositingStrategy
+import androidx.compose.ui.layout.ContentScale
+import androidx.compose.ui.platform.LocalContext
+import coil.compose.AsyncImage
+import coil.request.ImageRequest
+import dev.lelonio.square.ui.components.BlurTransformation
import androidx.compose.ui.layout.layout
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
@@ -83,19 +97,45 @@ import dev.lelonio.square.ui.components.GlassChoiceMenu
import dev.lelonio.square.ui.components.LazyScrollBar
import dev.lelonio.square.ui.components.SwipeToQueue
import dev.lelonio.square.ui.glass.LiquidButton
+import dev.lelonio.square.ui.glass.shapes.ContinuousCapsule
import dev.lelonio.square.ui.glass.pressable
import dev.lelonio.square.ui.theme.InkDim
import dev.lelonio.square.ui.theme.rememberArtworkColor
+import dev.lelonio.square.ui.theme.PageFloor
+import dev.lelonio.square.ui.theme.pageColorFor
import dev.lelonio.square.ui.theme.softShadow
import java.util.Locale
import java.util.concurrent.TimeUnit
import com.adamglin.PhosphorIcons
import com.adamglin.phosphoricons.Fill
+import com.adamglin.phosphoricons.Bold
import com.adamglin.phosphoricons.Regular
import com.adamglin.phosphoricons.fill.ArrowCircleDown
import com.adamglin.phosphoricons.fill.Check
import com.adamglin.phosphoricons.fill.MagnifyingGlass
import com.adamglin.phosphoricons.fill.Play
+import com.adamglin.phosphoricons.bold.Shuffle
+import com.adamglin.phosphoricons.bold.Info
+import com.adamglin.phosphoricons.bold.ArrowDown
+import com.adamglin.phosphoricons.bold.CaretLeft
+import com.adamglin.phosphoricons.bold.Export
+import com.adamglin.phosphoricons.bold.DotsThree
+import com.adamglin.phosphoricons.bold.Plus
+import com.adamglin.phosphoricons.bold.Check
+import com.adamglin.phosphoricons.bold.Star
+import com.adamglin.phosphoricons.bold.ArrowsDownUp
+import com.adamglin.phosphoricons.bold.ArrowCircleDown
+import com.adamglin.phosphoricons.fill.Shuffle
+import com.adamglin.phosphoricons.fill.Info
+import com.adamglin.phosphoricons.fill.ArrowDown
+import com.adamglin.phosphoricons.fill.CaretLeft
+import com.adamglin.phosphoricons.fill.Export
+import com.adamglin.phosphoricons.fill.DotsThree
+import com.adamglin.phosphoricons.fill.Plus
+import com.adamglin.phosphoricons.fill.ArrowsDownUp
+import com.adamglin.phosphoricons.fill.Star
+import com.adamglin.phosphoricons.regular.Star
+import com.adamglin.phosphoricons.regular.Info
import com.adamglin.phosphoricons.fill.Waveform
import com.adamglin.phosphoricons.regular.ArrowLeft
import com.adamglin.phosphoricons.regular.ArrowsDownUp
@@ -146,6 +186,8 @@ fun PlaylistScreen(
onOpenItem: (dev.lelonio.square.data.SearchItem) -> Unit = {},
/** Follows or unfollows the artist this page is about. */
onToggleFollow: () -> Unit = {},
+ /** Keeps the record on the artist page's top card, or lets it go. */
+ onToggleLatestSaved: () -> Unit = {},
/** Whether this page is kept on the phone, and how far along that is. */
downloadState: dev.lelonio.square.data.OwnerState = dev.lelonio.square.data.OwnerState.None,
onToggleDownload: () -> Unit = {},
@@ -191,10 +233,18 @@ fun PlaylistScreen(
) {
var query by remember { mutableStateOf("") }
var searching by remember { mutableStateOf(false) }
- // Asked before a downloaded page is given back to the network. Pressing the
- // button that says "this is on your phone" is how a listener takes it off
- // again — the same control both ways — so the question is what stops a
- // mis-tap from deleting a hundred songs.
+ // An artist is not a list with a cover on top of it. It is a photograph of
+ // a person with their name written across it, and the songs come after —
+ // which is a different page, not a differently-worded one, so the header,
+ // the height it opens at and what the rows say are all chosen from here.
+ val isArtist = state.kind == MainViewModel.DetailKind.ARTIST
+ // The follower count and the genres, behind the button that asks for them.
+ // On the reference they are a screen of their own reached from an "i"; here
+ // they unfold in place, which is the same answer without the round trip.
+ var infoOpen by remember(state.uri) { mutableStateOf(false) }
+ // Asked before a kept page is given back to the network. The button that
+ // says "this is on your phone" is also how it comes off again, so the
+ // question is what stops a mis-tap from deleting a hundred songs.
var confirmingRemoval by remember { mutableStateOf(false) }
// Seeded from the stored choice and written back on change: picking an
// order and finding it gone on the next playlist is the kind of thing that
@@ -237,8 +287,53 @@ fun PlaylistScreen(
// Taken from *this* screen's cover, not from whatever is playing. The two
// are usually different things, and colouring an album page after an
// unrelated track makes the page look like it belongs to something else.
- val accent by rememberArtworkColor(state.artworkUrl)
- val pageColor = remember(accent) { pageColorFor(accent) }
+ // Whose record this is. An album says its artist; a playlist says nothing
+ // here, because the name under a playlist's title on the reference is the
+ // curator, and Spotify's owner field is an account id as often as a person.
+ val byline = remember(state.kind, state.tracks, state.byline) {
+ if (state.kind == MainViewModel.DetailKind.ALBUM) {
+ state.tracks.firstOrNull()?.artist.orEmpty()
+ } else {
+ state.byline
+ }
+ }
+
+ // The third line: the year for a record, and for a playlist how long ago
+ // somebody last put something in it — which is the one fact about a list
+ // that changes, and the one the reference prints here.
+ val updated = remember(state.kind, state.tracks) {
+ if (state.kind == MainViewModel.DetailKind.PLAYLIST) {
+ state.tracks.mapNotNull { it.addedAt }.maxOrNull()
+ } else {
+ null
+ }
+ }
+
+ // Taken from the picture the page is actually showing, which since Apple's
+ // artwork arrived is not always Spotify's square: colouring a page after an
+ // image it is not displaying is what leaves the header and the page below it
+ // visibly two different browns.
+ val accent by rememberArtworkColor(state.heroUrl ?: state.coverUrl ?: state.artworkUrl)
+ // The catalogue's own colour for the page where there is one, and a colour
+ // worked out from the cover where there is not. Theirs is chosen for the
+ // record; ours is the most common colour in a photograph, which on a
+ // portrait is usually somebody's face.
+ // White, with the page's own colour in it.
+ //
+ // The reference never draws pure white on a coloured page: on a green page
+ // its icons are a green-tinted white, and that is most of why the controls
+ // look like part of the picture rather than pasted onto it. A sixth of the
+ // page colour is enough to see and not enough to read as grey.
+ val pageInk = remember(accent, state.tintHex) {
+ val source = state.tintHex
+ ?.let { hex -> runCatching { Color(android.graphics.Color.parseColor("#$hex")) }.getOrNull() }
+ ?: accent
+ source?.let(::inkTintedBy) ?: Color.White
+ }
+
+ val pageColor = remember(accent, state.tintHex) {
+ state.tintHex?.let(::tintOf) ?: pageColorFor(accent)
+ }
// What the glass on this screen refracts.
//
@@ -258,6 +353,7 @@ fun PlaylistScreen(
val topPadding = contentPadding.calculateTopPadding()
val collapsedHeight = topPadding + COLLAPSED_BAR_HEIGHT
+ val heroHeight = HERO_HEIGHT
// The header is not in the list. It sits above it and shrinks as the list is
// dragged upwards, which is the difference between a hero that collapses and
@@ -267,7 +363,7 @@ fun PlaylistScreen(
// reaches the header first and only what the header cannot use scrolls the
// list, so a single gesture closes the cover and then carries on into the
// tracks.
- val collapseRange = with(density) { (HERO_HEIGHT - collapsedHeight).toPx() }
+ val collapseRange = with(density) { (heroHeight - collapsedHeight).toPx() }
var collapsed by remember { mutableFloatStateOf(0f) }
val collapseFraction = { (collapsed / collapseRange).coerceIn(0f, 1f) }
@@ -293,9 +389,14 @@ fun PlaylistScreen(
}
}
- val heroPx = with(density) { HERO_HEIGHT.roundToPx() }
+ val heroPx = with(density) { heroHeight.roundToPx() }
val collapsedPx = with(density) { collapsedHeight.roundToPx() }
+ // Where the page colour starts giving way, as a fraction of the screen: just
+ // past the bottom of the header, whatever height this page's header is.
+ val screenHeight = androidx.compose.ui.platform.LocalConfiguration.current.screenHeightDp.dp
+ val floorStart = ((heroHeight + 40.dp) / screenHeight).coerceIn(0.35f, 0.95f)
+
Box(Modifier.fillMaxSize()) {
// The page, without the things that sample it.
//
@@ -316,20 +417,38 @@ fun PlaylistScreen(
// does not show through and re-tint the page.
.background(
Brush.verticalGradient(
- // Held flat over the top half rather than falling away
- // immediately: the header has to end on the same colour
- // the page starts with, and the list scrolls, so the
- // meeting point moves. A slow gradient makes that seam
- // impossible to catch.
+ // Held flat until below the header, then falling away.
+ //
+ // Not a fixed fraction, which is what this was: the
+ // header's last row is opaque page colour, so wherever
+ // the fall starts above its bottom edge the page under
+ // it is already darker — and the two meet as a line
+ // across the screen. Starting the fall where the header
+ // ends is what makes the picture and the page one
+ // surface.
0f to pageColor,
- 0.45f to pageColor,
+ floorStart to pageColor,
1f to PageFloor,
),
)
.layerBackdrop(pageBackdrop),
) {
+ // Every page is its own picture, filling the top of the screen:
+ // the editorial photograph where the catalogue has one, and the
+ // cover itself where it does not. A square sleeve floating in the
+ // middle of a coloured field is the older design, and the reference
+ // only still uses it for the records nobody made a picture for.
HeroArt(
- artworkUrl = state.artworkUrl,
+ // Nothing at all while the other catalogue is still being
+ // asked: this page is about to have a different photograph, and
+ // opening on Spotify's only to replace it a second later is the
+ // swap the reader sees. The wait is capped in the view model.
+ artworkUrl = (state.heroUrl ?: state.coverUrl ?: state.artworkUrl)
+ .takeIf { state.heroUrl != null || !state.heroPending },
+ // Played over the still where the record has one; see
+ // MotionCover. Offline it is left alone: a header that streams
+ // video is the last thing a page with no network should try.
+ motionUrl = state.motionUrl.takeIf { !offline },
name = state.name,
pageColor = pageColor,
heroPx = heroPx,
@@ -339,7 +458,33 @@ fun PlaylistScreen(
}
Column(Modifier.fillMaxSize()) {
+ if (isArtist) {
+ ArtistHeader(
+ ink = pageInk,
+ name = state.name,
+ logoUrl = state.logoUrl,
+ following = state.following,
+ onToggleFollow = onToggleFollow,
+ infoOpen = infoOpen,
+ onToggleInfo = { infoOpen = !infoOpen },
+ pageColor = pageColor,
+ backdrop = pageBackdrop,
+ collapse = collapseFraction,
+ heroHeight = heroHeight,
+ collapsedHeight = collapsedHeight,
+ topPadding = topPadding,
+ searching = searching,
+ onBack = onBack,
+ onPlay = { visible.takeIf { it.isNotEmpty() }?.let { onPlay(it, 0, asContext) } },
+ onShuffle = { visible.takeIf { it.isNotEmpty() }?.let(onShuffle) },
+ onToggleSearch = {
+ searching = !searching
+ if (!searching) query = ""
+ },
+ )
+ } else {
DetailHeader(
+ ink = pageInk,
name = state.name,
kind = state.kind,
description = state.description,
@@ -356,9 +501,14 @@ fun PlaylistScreen(
downloadState is dev.lelonio.square.data.OwnerState.Partial
if (kept) confirmingRemoval = true else onToggleDownload()
},
- canDownload = canDownload,
- trackCount = state.tracks.size,
- totalMs = state.tracks.sumOf { it.durationMs },
+ // Only where the reference puts one: a record or a list. An artist
+ // page keeps it in the menu, beside the rest of what a page can do.
+ canDownload = canDownload && !isArtist,
+ byline = byline,
+ year = state.tracks.firstOrNull()?.year.orEmpty()
+ .takeIf { state.kind == MainViewModel.DetailKind.ALBUM }
+ .orEmpty(),
+ updatedAt = updated,
backdrop = pageBackdrop,
collapse = collapseFraction,
collapsedHeight = collapsedHeight,
@@ -373,7 +523,25 @@ fun PlaylistScreen(
if (!searching) query = ""
},
searching = searching,
+ heroHeight = heroHeight,
)
+ }
+
+ // Behind the "i", and above the list rather than inside it. On the
+ // reference this is a screen of its own; unfolding it under the
+ // photograph says the same thing without taking the reader off the page
+ // they came for — and outside the lazy list, because a row that is not
+ // currently composed does not notice the button being pressed.
+ if (isArtist) {
+ AnimatedVisibility(visible = infoOpen) {
+ ArtistAbout(
+ followers = state.followers,
+ genres = state.genres,
+ origin = state.origin,
+ bio = state.notes,
+ )
+ }
+ }
LazyColumn(
state = listState,
@@ -387,9 +555,34 @@ fun PlaylistScreen(
.nestedScroll(headerScroll),
contentPadding = PaddingValues(bottom = contentPadding.calculateBottomPadding()),
) {
- if (state.kind == MainViewModel.DetailKind.ARTIST) {
- item(contentType = "artistAbout") {
- ArtistAbout(followers = state.followers, genres = state.genres)
+ if (isArtist) {
+ state.latest?.let { release ->
+ item(contentType = "latestRelease") {
+ LatestReleaseCard(
+ release = release,
+ saved = state.latestSaved,
+ onOpen = {
+ onOpenItem(
+ dev.lelonio.square.data.SearchItem(
+ uri = release.uri,
+ title = release.title,
+ subtitle = "",
+ artworkUrl = release.artworkUrl,
+ ),
+ )
+ },
+ onToggleSaved = onToggleLatestSaved,
+ )
+ }
+ }
+ }
+
+ // What the editors wrote about the record, where they wrote
+ // anything. Three lines and then a word to open it: it is worth
+ // reading and it is not worth a screenful before the songs.
+ if (!isArtist) {
+ state.notes?.takeIf { it.isNotBlank() }?.let { notes ->
+ item(contentType = "notes") { EditorialNotes(notes) }
}
}
@@ -397,9 +590,12 @@ fun PlaylistScreen(
item(contentType = "sectionTitle") {
SectionHeader(
title = stringResource(
- if (state.kind == MainViewModel.DetailKind.ARTIST) R.string.top_tracks
- else R.string.tracks,
+ if (isArtist) R.string.top_songs else R.string.tracks,
),
+ // Set as a page heading on an artist, the way the
+ // reference does: there the songs are one section among
+ // several, not the whole of what is below the fold.
+ large = isArtist,
sort = sort,
onSortOpen = { sortOpen = it },
onAnchor = { sortAnchor = it },
@@ -495,6 +691,25 @@ fun PlaylistScreen(
TrackRow(
track = track,
position = index + 1,
+ // An artist page is a page about one artist, so
+ // printing their name under every title says
+ // nothing. What the reference puts there is the
+ // record the song is on and when it came out, which
+ // is the thing a listener is actually placing.
+ subtitle = when {
+ isArtist -> track.releaseLine()
+ // On a record by one artist, printing their
+ // name under every title says nothing; the
+ // length alone is what the reference leaves.
+ state.kind == MainViewModel.DetailKind.ALBUM ->
+ formatDuration(track.durationMs)
+ else -> null
+ },
+ // Every row on an album carries the same cover, so
+ // the reference puts the track's number there
+ // instead — the one thing that differs, and the
+ // thing a record is read by.
+ numbered = state.kind == MainViewModel.DetailKind.ALBUM,
isCurrent = track.uri == nowPlayingUri,
onClick = { onPlay(visible, index, asContext) },
onMenu = { onTrackMenu(track) },
@@ -510,6 +725,24 @@ fun PlaylistScreen(
}
}
+ // How much of it there is, at the end rather than under the title.
+ // That is where the reference puts it, and it is the right place: it
+ // is what you read after the list, not before it.
+ if (!isArtist && state.tracks.isNotEmpty() && query.isBlank()) {
+ item(contentType = "totals") {
+ Text(
+ stringResource(
+ R.string.songs_and_length,
+ state.tracks.size,
+ formatTotal(state.tracks.sumOf { it.durationMs }),
+ ),
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ modifier = Modifier.padding(start = 24.dp, end = 24.dp, top = 20.dp),
+ )
+ }
+ }
+
// Everything the artist is in, under the songs they are known for.
//
// The tracks come first because that is what an artist page is
@@ -587,6 +820,21 @@ fun PlaylistScreen(
}
}
+ dev.lelonio.square.ui.components.ConfirmSheet(
+ visible = confirmingRemoval,
+ title = stringResource(R.string.remove_download),
+ message = stringResource(R.string.remove_download_confirm, state.name),
+ confirmLabel = stringResource(R.string.remove_download_confirm_action),
+ cancelLabel = stringResource(R.string.cancel),
+ backdrop = pageBackdrop,
+ destructive = true,
+ onConfirm = {
+ confirmingRemoval = false
+ onToggleDownload()
+ },
+ onDismiss = { confirmingRemoval = false },
+ )
+
LazyScrollBar(
state = listState,
startAfter = "track",
@@ -612,21 +860,37 @@ fun PlaylistScreen(
.align(Alignment.TopEnd)
.graphicsLayer { alpha = 1f - collapseFraction() },
) {
+ // Keeping the page, first in the row — where the reference puts the
+ // one action that changes what your library holds, apart from the
+ // controls that only start the music. Absent while the answer is
+ // unknown and on the pages the question does not apply to.
+ if (state.saved != null) {
+ CapsuleAction(
+ tint = pageInk,
+ icon = if (state.saved) {
+ PhosphorIcons.Bold.Check
+ } else {
+ PhosphorIcons.Bold.Plus
+ },
+ description = stringResource(
+ if (state.saved) R.string.remove_from_library else R.string.add_to_library,
+ ),
+ onClick = onToggleSaved,
+ )
+ CapsuleDivider()
+ }
CapsuleAction(
- icon = PhosphorIcons.Regular.Export,
+ icon = PhosphorIcons.Bold.Export,
description = stringResource(R.string.copy_link),
onClick = onShare,
+ tint = pageInk,
)
- Box(
- Modifier
- .height(20.dp)
- .width(1.dp)
- .background(Color.White.copy(alpha = 0.22f)),
- )
+ CapsuleDivider()
CapsuleAction(
- icon = PhosphorIcons.Regular.DotsThree,
+ icon = PhosphorIcons.Bold.DotsThree,
description = stringResource(R.string.more),
onClick = onMenu,
+ tint = pageInk,
)
}
@@ -645,9 +909,9 @@ fun PlaylistScreen(
contentPadding = 0.dp,
) {
Icon(
- PhosphorIcons.Regular.ArrowLeft,
+ PhosphorIcons.Bold.CaretLeft,
contentDescription = stringResource(R.string.back),
- tint = Color.White,
+ tint = pageInk,
modifier = Modifier.size(20.dp),
)
}
@@ -682,24 +946,6 @@ fun PlaylistScreen(
}
}
- // Last inside the page, so it is drawn over it. Mounted before the
- // Box it used to sit above, where the page covered it completely:
- // the question never appeared, and with nothing to answer, nothing
- // was ever removed either.
- dev.lelonio.square.ui.components.ConfirmSheet(
- visible = confirmingRemoval,
- title = stringResource(R.string.remove_download),
- message = stringResource(R.string.remove_download_confirm, state.name),
- confirmLabel = stringResource(R.string.remove_download_confirm_action),
- cancelLabel = stringResource(R.string.cancel),
- backdrop = pageBackdrop,
- destructive = true,
- onConfirm = {
- confirmingRemoval = false
- onToggleDownload()
- },
- onDismiss = { confirmingRemoval = false },
- )
}
}
@@ -727,6 +973,8 @@ private fun IntOffset.leftOf(density: androidx.compose.ui.unit.Density): IntOffs
*/
@Composable
private fun DetailHeader(
+ /** White with the page's colour in it; see where it is worked out. */
+ ink: Color,
name: String,
kind: MainViewModel.DetailKind,
description: String,
@@ -745,12 +993,16 @@ private fun DetailHeader(
*/
following: Boolean?,
onToggleFollow: () -> Unit,
- /** Kept on the phone, being kept, or not; see the button below. */
+ /** Whose record it is: the artist, or the account that made the list. */
+ byline: String,
+ /** When it came out, where the source says. */
+ year: String,
+ /** When a playlist last changed, ISO-8601; null on everything else. */
+ updatedAt: String?,
+ /** Kept on the phone, being kept, or not; see the button beside play. */
download: dev.lelonio.square.data.OwnerState,
onToggleDownload: () -> Unit,
canDownload: Boolean,
- trackCount: Int,
- totalMs: Long,
backdrop: Backdrop,
/** 0 fully open, 1 collapsed into the bar. A lambda, so reading it costs a
* re-layout rather than a recomposition of the header on every frame. */
@@ -762,9 +1014,11 @@ private fun DetailHeader(
onPlay: () -> Unit,
onShuffle: () -> Unit,
onToggleSearch: () -> Unit,
+ /** What the header opens at, which the artist page makes taller. */
+ heroHeight: Dp = HERO_HEIGHT,
) {
val density = LocalDensity.current
- val heroPx = with(density) { HERO_HEIGHT.roundToPx() }
+ val heroPx = with(density) { heroHeight.roundToPx() }
val collapsedPx = with(density) { collapsedHeight.roundToPx() }
Box(
@@ -779,74 +1033,82 @@ private fun DetailHeader(
Modifier
.align(Alignment.BottomCenter)
.fillMaxWidth()
- .padding(horizontal = 24.dp, vertical = 18.dp)
+ .padding(horizontal = 24.dp)
+ .padding(bottom = 20.dp)
// Gone by the time the header is half closed: below that there
- // is no room for a 68dp play button and a two-line title, and
- // watching them be squeezed is worse than watching them leave.
+ // is no room for a cover and a two-line title, and watching them
+ // be squeezed is worse than watching them leave.
.graphicsLayer { alpha = (1f - collapse() * 2f).coerceIn(0f, 1f) },
horizontalAlignment = Alignment.CenterHorizontally,
) {
- // The name first and what it is underneath, which is the order
- // somebody reads them in: the title is the thing, "Album" is a
- // caption on it.
+ // The record itself, as an object on the page. The reference draws
+ // it this way and it is not decoration: a square with an edge and a
+ // shadow is a thing you are looking at, where a picture bled to the
+ // screen's edges is a background the words happen to sit on.
Text(
text = name,
- style = MaterialTheme.typography.headlineMedium,
+ style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.Bold,
- color = Color.White,
+ color = ink,
textAlign = TextAlign.Center,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
+ modifier = Modifier.padding(top = 16.dp),
)
+ // Whose record it is, in the page's own accent — the one line the
+ // reference colours, because it is the one that is also a link.
+ if (byline.isNotEmpty()) {
+ Text(
+ text = byline,
+ style = MaterialTheme.typography.titleMedium,
+ fontWeight = FontWeight.SemiBold,
+ color = ink.copy(alpha = 0.92f),
+ textAlign = TextAlign.Center,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ modifier = Modifier.padding(top = 2.dp),
+ )
+ }
+
Text(
- text = stringResource(kind.label) + if (trackCount > 0) {
- stringResource(R.string.track_count_and_length, trackCount, formatTotal(totalMs))
- } else {
- ""
+ text = when {
+ updatedAt != null -> stringResource(R.string.updated_ago, agoOf(updatedAt))
+ year.isNotEmpty() -> stringResource(kind.label) + " · " + year
+ else -> stringResource(kind.label)
},
style = MaterialTheme.typography.labelMedium,
- color = Color.White.copy(alpha = 0.72f),
- modifier = Modifier.padding(top = 4.dp),
+ fontWeight = FontWeight.Bold,
+ color = ink.copy(alpha = 0.66f),
+ modifier = Modifier.padding(top = 6.dp),
)
- // Three controls and two labels do not fit across a phone, so the
- // row tightens once there is more than one thing beside Play.
- // Counted rather than asked of any one control: this used to key
- // off the follow pill alone, and adding the download button let a
- // playlist overflow — the button went off the edge and the tap
- // landed on Play, which started the music instead.
- val extras = listOfNotNull(saved, following).size + if (canDownload) 1 else 0
- val tight = extras >= 2
-
+ // Shuffle, play, keep — in that order and in those three shapes,
+ // which is exactly how the reference lays out a list: a round
+ // control either side of one wide button that says what it does.
Row(
- Modifier.padding(top = 16.dp),
- horizontalArrangement = Arrangement.spacedBy(if (tight) 10.dp else 14.dp),
+ Modifier.padding(top = 18.dp),
+ horizontalArrangement = Arrangement.spacedBy(22.dp),
verticalAlignment = Alignment.CenterVertically,
) {
CircleAction(
- icon = PhosphorIcons.Regular.Shuffle,
+ icon = PhosphorIcons.Bold.Shuffle,
description = stringResource(R.string.shuffle),
- size = 52.dp,
+ size = 46.dp,
backdrop = backdrop,
onClick = onShuffle,
+ tint = ink,
)
- // The one solid control on the screen, and the only one that
- // says what it does in words. Everything else here is glass, so
- // weight has to come from the fill rather than from size.
+
+ // The one solid control on the page, and the only one that says
+ // what it does in words.
Row(
Modifier
- .softShadow(CircleShape, elevation = 18.dp, spot = 0.3f)
- .clip(CircleShape)
+ .softShadow(ContinuousCapsule, elevation = 20.dp, spot = 0.32f)
+ .clip(ContinuousCapsule)
.background(Color.White)
- .pressable(onPlay, pressedScale = 0.95f)
- // Narrower with a word button beside it. Three controls
- // and two labels do not fit across a phone at the width
- // this has to itself on every other page.
- .padding(
- horizontal = if (tight) 26.dp else 40.dp,
- vertical = 14.dp,
- ),
+ .pressable(onPlay, shape = ContinuousCapsule, pressedScale = 0.96f)
+ .padding(horizontal = 30.dp, vertical = 15.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
@@ -854,7 +1116,7 @@ private fun DetailHeader(
PhosphorIcons.Fill.Play,
contentDescription = null,
tint = pageColor,
- modifier = Modifier.size(22.dp),
+ modifier = Modifier.size(20.dp),
)
Text(
stringResource(R.string.play),
@@ -863,39 +1125,22 @@ private fun DetailHeader(
color = pageColor,
)
}
- // Keeping the page, which is what the reference puts here.
- // Absent while the answer is unknown and on the pages the
- // question does not apply to: a button that cannot say whether
- // it is on or off is worse than no button.
- if (saved != null) {
- CircleAction(
- icon = if (saved) PhosphorIcons.Fill.Check else PhosphorIcons.Regular.Plus,
- description = stringResource(
- if (saved) R.string.remove_from_library else R.string.add_to_library,
- ),
- size = 52.dp,
- backdrop = backdrop,
- onClick = onToggleSaved,
- )
- }
-
- // An artist has no library button — the question does not apply
- // — so this stands where that one would.
- if (following != null) {
- FollowPill(following = following, onClick = onToggleFollow)
- }
- // Keeping the music itself, next to keeping the page. Always
- // present where a download is possible, unlike the two above:
- // its off state is what starts one, so hiding it until there
- // was something to show would leave no way in.
+ // Keeping the music, where the reference keeps it: opposite
+ // shuffle, on the other side of the button that starts it.
if (canDownload) {
DownloadAction(
state = download,
backdrop = backdrop,
onClick = onToggleDownload,
+ tint = ink,
)
}
+
+ if (following != null) {
+ FollowPill(following = following, onClick = onToggleFollow)
+ }
+
}
// What the list is, in its own words. Only the sources that carry
@@ -913,114 +1158,434 @@ private fun DetailHeader(
}
}
- // What the header becomes: the same title and the same three controls,
- // at the size a bar can carry them. It arrives in the second half of the
- // travel, as the full-size version finishes leaving.
- Row(
- Modifier
- .align(Alignment.BottomStart)
- .fillMaxWidth()
- .height(collapsedHeight)
- .padding(top = topPadding)
- .padding(horizontal = 6.dp)
- .graphicsLayer { alpha = (collapse() * 2f - 1f).coerceIn(0f, 1f) },
- verticalAlignment = Alignment.CenterVertically,
- ) {
- IconButton(onClick = onBack) {
- Icon(
- PhosphorIcons.Regular.ArrowLeft,
- contentDescription = stringResource(R.string.back),
- tint = Color.White,
- modifier = Modifier.size(20.dp),
- )
- }
- Text(
- name,
- style = MaterialTheme.typography.titleMedium,
- color = Color.White,
- maxLines = 1,
- overflow = TextOverflow.Ellipsis,
- modifier = Modifier
- .weight(1f)
- .padding(horizontal = 6.dp),
+ CollapsedBar(
+ ink = ink,
+ name = name,
+ collapse = collapse,
+ collapsedHeight = collapsedHeight,
+ topPadding = topPadding,
+ searching = searching,
+ onBack = onBack,
+ onToggleSearch = onToggleSearch,
+ onShuffle = onShuffle,
+ onPlay = onPlay,
+ modifier = Modifier.align(Alignment.BottomStart),
+ )
+ }
+}
+
+/**
+ * What every header becomes once it is scrolled shut.
+ *
+ * The same title and the same controls at the size a bar can carry them,
+ * arriving in the second half of the travel as the full-size version finishes
+ * leaving. Shared by both headers: a page whose collapsed bar behaved
+ * differently from the page next to it would read as a different app.
+ */
+@Composable
+private fun CollapsedBar(
+ /** White with the page's colour in it; see where it is worked out. */
+ ink: Color,
+ name: String,
+ collapse: () -> Float,
+ collapsedHeight: Dp,
+ topPadding: Dp,
+ searching: Boolean,
+ onBack: () -> Unit,
+ onToggleSearch: () -> Unit,
+ onShuffle: () -> Unit,
+ onPlay: () -> Unit,
+ modifier: Modifier = Modifier,
+) {
+ Row(
+ modifier
+ .fillMaxWidth()
+ .height(collapsedHeight)
+ .padding(top = topPadding)
+ .padding(horizontal = 6.dp)
+ .graphicsLayer { alpha = (collapse() * 2f - 1f).coerceIn(0f, 1f) },
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ IconButton(onClick = onBack) {
+ Icon(
+ PhosphorIcons.Regular.ArrowLeft,
+ contentDescription = stringResource(R.string.back),
+ tint = ink,
+ modifier = Modifier.size(20.dp),
+ )
+ }
+ Text(
+ name,
+ style = MaterialTheme.typography.titleMedium,
+ color = ink,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ modifier = Modifier
+ .weight(1f)
+ .padding(horizontal = 6.dp),
+ )
+ IconButton(onClick = onToggleSearch) {
+ Icon(
+ if (searching) PhosphorIcons.Regular.X else PhosphorIcons.Fill.MagnifyingGlass,
+ contentDescription = stringResource(R.string.search_in_tracks),
+ tint = ink,
+ modifier = Modifier.size(18.dp),
+ )
+ }
+ IconButton(onClick = onShuffle) {
+ Icon(
+ PhosphorIcons.Bold.Shuffle,
+ contentDescription = stringResource(R.string.shuffle),
+ tint = ink,
+ modifier = Modifier.size(18.dp),
+ )
+ }
+ IconButton(onClick = onPlay) {
+ Icon(
+ PhosphorIcons.Fill.Play,
+ contentDescription = stringResource(R.string.play),
+ tint = ink,
+ modifier = Modifier.size(22.dp),
)
- IconButton(onClick = onToggleSearch) {
- Icon(
- if (searching) PhosphorIcons.Regular.X else PhosphorIcons.Fill.MagnifyingGlass,
- contentDescription = stringResource(R.string.search_in_tracks),
- tint = Color.White,
- modifier = Modifier.size(18.dp),
- )
- }
- IconButton(onClick = onShuffle) {
- Icon(
- PhosphorIcons.Regular.Shuffle,
- contentDescription = stringResource(R.string.shuffle),
- tint = Color.White,
- modifier = Modifier.size(18.dp),
- )
- }
- IconButton(onClick = onPlay) {
- Icon(
- PhosphorIcons.Fill.Play,
- contentDescription = stringResource(R.string.play),
- tint = Color.White,
- modifier = Modifier.size(22.dp),
- )
- }
}
}
}
/**
- * The cover at the top of the page, and the fade that ends it.
+ * The artist's photograph, and the way it stops being a photograph.
*
- * Drawn below the header rather than in it, because the header holds the glass
- * controls and glass cannot sample a layer it is part of. Both use
- * [heroCollapse], so the picture and the title it sits under close together.
+ * Two copies of the same image: the sharp one, and over its lower half a blurred
+ * one that fades in. That is what makes the picture dissolve into the page
+ * instead of ending — a straight fade to a flat colour leaves the face crisp
+ * right up to the point where it vanishes, which reads as a photo behind a
+ * curtain. Softening it first is the whole trick.
+ *
+ * Blurred at decode time rather than with `Modifier.blur`, for the reason
+ * written over the app backdrop: the modifier is a render effect over the whole
+ * layer, re-run on every frame the header collapses.
*/
@Composable
private fun HeroArt(
artworkUrl: String?,
+ motionUrl: String?,
name: String,
pageColor: Color,
heroPx: Int,
collapsedPx: Int,
collapse: () -> Float,
) {
+ // The picture and its fade are the same everywhere the app shows a cover
+ // large — here and in the player; see HeroBackdrop. What belongs to this
+ // screen alone is the collapse, so that is all that is left here.
+ dev.lelonio.square.ui.components.HeroBackdrop(
+ artworkUrl = artworkUrl,
+ title = name,
+ pageColor = pageColor,
+ motionUrl = motionUrl,
+ modifier = Modifier
+ .fillMaxWidth()
+ .heroCollapse(heroPx, collapsedPx, collapse),
+ )
+}
+
+/**
+ * The artist's name across their own photograph, and the three things there are
+ * to do with them.
+ *
+ * Deliberately not the header the other pages use. A playlist is a list with a
+ * cover, so its header says what the list is and how long it runs; an artist is
+ * a person, and the page is their picture with their name written on it. Under
+ * the name: what they are about, play, and follow — one word each, in the order
+ * a listener wants them.
+ */
+@Composable
+private fun ArtistHeader(
+ /** White with the page's colour in it; see where it is worked out. */
+ ink: Color,
+ name: String,
+ /** Their name as Apple draws it; null falls back to setting it in type. */
+ logoUrl: String?,
+ /** Null until Spotify has answered; the star waits rather than guessing. */
+ following: Boolean?,
+ onToggleFollow: () -> Unit,
+ infoOpen: Boolean,
+ onToggleInfo: () -> Unit,
+ pageColor: Color,
+ backdrop: Backdrop,
+ collapse: () -> Float,
+ heroHeight: Dp,
+ collapsedHeight: Dp,
+ topPadding: Dp,
+ searching: Boolean,
+ onBack: () -> Unit,
+ onPlay: () -> Unit,
+ onShuffle: () -> Unit,
+ onToggleSearch: () -> Unit,
+) {
+ val density = LocalDensity.current
+ val heroPx = with(density) { heroHeight.roundToPx() }
+ val collapsedPx = with(density) { collapsedHeight.roundToPx() }
+
Box(
Modifier
.fillMaxWidth()
.heroCollapse(heroPx, collapsedPx, collapse),
+ ) {
+ Column(
+ Modifier
+ .align(Alignment.BottomCenter)
+ .fillMaxWidth()
+ .padding(horizontal = 18.dp)
+ .padding(bottom = 24.dp)
+ .graphicsLayer { alpha = (1f - collapse() * 2f).coerceIn(0f, 1f) },
+ horizontalAlignment = Alignment.CenterHorizontally,
+ ) {
+ // Set in capitals and as large as the name allows. The reference
+ // draws every artist's name in a face chosen for them, which no
+ // client can reproduce; what carries across is the weight and the
+ // width — the name is the picture's caption and the page's title at
+ // once, so it is sized to fill the frame rather than to a style.
+ if (logoUrl != null) {
+ // The name as their own artwork, which is what the reference
+ // puts here — a face chosen for that artist and set once, not a
+ // system font pretending to be one.
+ AsyncImage(
+ model = ImageRequest.Builder(LocalContext.current)
+ .data(logoUrl)
+ .crossfade(true)
+ .build(),
+ contentDescription = name,
+ contentScale = ContentScale.Fit,
+ modifier = Modifier
+ .fillMaxWidth(0.82f)
+ .heightIn(max = LOGO_HEIGHT),
+ )
+ } else {
+ Text(
+ // As the artist spells it. Setting it in capitals was an
+ // imitation of the drawn names the catalogue supplies for
+ // the artists that have one — but those are lettering
+ // somebody designed, and a system font shouted in capitals
+ // is not the same thing: it is the same font, louder, and it
+ // loses the spelling the artist chose.
+ text = name,
+ style = MaterialTheme.typography.displaySmall.copy(
+ fontSize = nameSize(name),
+ lineHeight = nameSize(name) * 1.04f,
+ // The photo behind it is somebody's face and cannot be
+ // relied on for contrast. A soft shadow costs nothing
+ // and keeps the name readable over a white shirt.
+ shadow = Shadow(Color.Black.copy(alpha = 0.5f), Offset(0f, 2f), 18f),
+ ),
+ fontWeight = FontWeight.Black,
+ color = Color.White,
+ textAlign = TextAlign.Center,
+ maxLines = 2,
+ overflow = TextOverflow.Ellipsis,
+ )
+ }
+
+ Row(
+ Modifier.padding(top = 20.dp),
+ horizontalArrangement = Arrangement.spacedBy(24.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ CircleAction(
+ icon = PhosphorIcons.Bold.Info,
+ description = stringResource(R.string.about),
+ size = 46.dp,
+ backdrop = backdrop,
+ onClick = onToggleInfo,
+ tint = if (infoOpen) ink else ink.copy(alpha = 0.86f),
+ )
+
+ // The one solid control on the page. Round rather than the
+ // capsule the other headers carry: with the name above it in
+ // capitals, a word inside the button would be a second title.
+ Box(
+ Modifier
+ .size(66.dp)
+ .softShadow(CircleShape, elevation = 20.dp, spot = 0.32f)
+ .clip(CircleShape)
+ .background(Color.White)
+ .pressable(onPlay, shape = CircleShape, pressedScale = 0.94f),
+ contentAlignment = Alignment.Center,
+ ) {
+ Icon(
+ PhosphorIcons.Fill.Play,
+ contentDescription = stringResource(R.string.play),
+ tint = pageColor,
+ modifier = Modifier
+ .size(28.dp)
+ // The glyph's own weight sits left of the circle's
+ // centre; nudged back, or the triangle looks like it
+ // is falling out of the button.
+ .padding(start = 3.dp),
+ )
+ }
+
+ // Following, said the way the reference says it. The star is
+ // absent rather than empty while the answer is unknown: a
+ // control that draws itself as "not followed" and corrects
+ // itself a second later has told the reader something false.
+ if (following != null) {
+ CircleAction(
+ icon = if (following) PhosphorIcons.Fill.Star else PhosphorIcons.Bold.Star,
+ description = stringResource(
+ if (following) R.string.following else R.string.follow,
+ ),
+ size = 46.dp,
+ backdrop = backdrop,
+ onClick = onToggleFollow,
+ tint = ink,
+ )
+ }
+
+ }
+ }
+
+ CollapsedBar(
+ ink = ink,
+ name = name,
+ collapse = collapse,
+ collapsedHeight = collapsedHeight,
+ topPadding = topPadding,
+ searching = searching,
+ onBack = onBack,
+ onToggleSearch = onToggleSearch,
+ onShuffle = onShuffle,
+ onPlay = onPlay,
+ modifier = Modifier.align(Alignment.BottomStart),
+ )
+ }
+}
+
+/**
+ * How big a name can be drawn without breaking the frame.
+ *
+ * Stepped rather than measured: text that is auto-fitted to the pixel changes
+ * size as the page loads and as the header collapses, and a title that resizes
+ * while being read is worse than one that is a point too small.
+ */
+private fun nameSize(name: String): TextUnit = when (name.length) {
+ in 0..9 -> 46.sp
+ in 10..14 -> 38.sp
+ in 15..20 -> 31.sp
+ in 21..28 -> 26.sp
+ else -> 22.sp
+}
+
+/**
+ * The record they put out last, above everything else on the page.
+ *
+ * One card rather than a shelf, and it is the first thing under the photo,
+ * because "what is new from them" is the question an artist page is most often
+ * opened with — the discography further down answers the other one.
+ */
+@Composable
+private fun LatestReleaseCard(
+ release: MainViewModel.ArtistRelease,
+ /** Whether it is already in the library; null while nobody knows yet. */
+ saved: Boolean?,
+ onOpen: () -> Unit,
+ onToggleSaved: () -> Unit,
+) {
+ val shape = RoundedCornerShape(14.dp)
+ Row(
+ Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 18.dp, vertical = 10.dp)
+ .clip(shape)
+ .background(Color.White.copy(alpha = 0.08f))
+ .pressable(onOpen, shape = shape, pressedScale = 0.99f)
+ .padding(10.dp),
+ verticalAlignment = Alignment.CenterVertically,
) {
Artwork(
- url = artworkUrl,
- title = name,
- modifier = Modifier.fillMaxSize(),
- corner = 0.dp,
+ url = release.artworkUrl,
+ title = release.title,
+ modifier = Modifier.size(58.dp),
+ corner = 8.dp,
+ decodeSize = 58.dp,
)
- // The bottom stops fade to the page colour itself, not to black. That is
- // what makes the cover run into the page instead of ending on an edge:
- // the last row of the image and the first row of the background are the
- // same colour. Fading to black over a page that is not black just moves
- // the seam and adds a dark band.
- Box(
+ Column(
Modifier
- .fillMaxSize()
- .background(
- Brush.verticalGradient(
- 0f to Color.Black.copy(alpha = 0.35f),
- 0.28f to Color.Transparent,
- 0.58f to pageColor.copy(alpha = 0.55f),
- 0.82f to pageColor.copy(alpha = 0.94f),
- 1f to pageColor,
- ),
+ .weight(1f)
+ .padding(horizontal = 14.dp),
+ ) {
+ Text(
+ releaseDateLabel(release.releaseDate),
+ style = MaterialTheme.typography.bodySmall,
+ color = InkDim,
+ maxLines = 1,
+ )
+ Text(
+ release.title,
+ style = MaterialTheme.typography.titleSmall,
+ color = MaterialTheme.colorScheme.onSurface,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ modifier = Modifier.padding(top = 2.dp),
+ )
+ Text(
+ pluralStringResource(
+ R.plurals.song_count,
+ release.trackCount,
+ release.trackCount,
),
- )
+ style = MaterialTheme.typography.bodySmall,
+ color = InkDim,
+ maxLines = 1,
+ )
+ }
+
+ // Absent until Spotify has said whether the record is already kept —
+ // the same rule as the star above.
+ if (saved != null) {
+ IconButton(onClick = onToggleSaved, modifier = Modifier.size(38.dp)) {
+ Icon(
+ if (saved) PhosphorIcons.Fill.Check else PhosphorIcons.Bold.Plus,
+ contentDescription = stringResource(
+ if (saved) R.string.remove_from_library else R.string.add_to_library,
+ ),
+ tint = if (saved) {
+ MaterialTheme.colorScheme.primary
+ } else {
+ MaterialTheme.colorScheme.onSurfaceVariant
+ },
+ modifier = Modifier.size(20.dp),
+ )
+ }
+ }
}
}
+/**
+ * A release date as a person would write it, from however much Spotify knows.
+ *
+ * The field is a full date for most records, a month for some and a year for
+ * the oldest, and printing "2019-01-01" for a record that only says 2019 is
+ * inventing a day it did not come out on.
+ */
+@Composable
+private fun releaseDateLabel(date: String): String {
+ if (date.isBlank()) return ""
+ return runCatching {
+ when (date.length) {
+ 4 -> date
+ 7 -> java.time.YearMonth.parse(date).format(
+ java.time.format.DateTimeFormatter.ofPattern("MMMM yyyy", Locale.getDefault()),
+ )
+ else -> java.time.LocalDate.parse(date).format(
+ java.time.format.DateTimeFormatter.ofLocalizedDate(
+ java.time.format.FormatStyle.MEDIUM,
+ ).withLocale(Locale.getDefault()),
+ )
+ }
+ }.getOrDefault(date)
+}
+
/**
* The header genuinely shrinks: the content keeps its full size and is clipped
* by the box around it, which is what makes the cover look like it is being
@@ -1053,6 +1618,17 @@ private fun Modifier.heroCollapse(
* the pane is a shade lighter than what it lies on, and a bright rim where the
* light would catch it.
*/
+/** The hairline between two actions in the capsule above. */
+@Composable
+private fun CapsuleDivider() {
+ Box(
+ Modifier
+ .height(20.dp)
+ .width(1.dp)
+ .background(Color.White.copy(alpha = 0.22f)),
+ )
+}
+
@Composable
private fun GlassCapsule(
backdrop: Backdrop,
@@ -1084,6 +1660,7 @@ private fun CapsuleAction(
icon: androidx.compose.ui.graphics.vector.ImageVector,
description: String,
onClick: () -> Unit,
+ tint: Color = Color.White,
) {
Box(
Modifier
@@ -1094,8 +1671,8 @@ private fun CapsuleAction(
Icon(
icon,
contentDescription = description,
- tint = Color.White,
- modifier = Modifier.size(19.dp),
+ tint = tint,
+ modifier = Modifier.size(20.dp),
)
}
}
@@ -1118,6 +1695,7 @@ private fun DownloadAction(
state: dev.lelonio.square.data.OwnerState,
backdrop: Backdrop,
onClick: () -> Unit,
+ tint: Color = Color.White,
) {
val kept = state is dev.lelonio.square.data.OwnerState.Complete ||
state is dev.lelonio.square.data.OwnerState.Partial
@@ -1125,31 +1703,33 @@ private fun DownloadAction(
Box(contentAlignment = Alignment.Center) {
CircleAction(
- // The filled arrow-in-a-circle, which is what every music app
- // means by "this is on your phone". A tick says "done", which is
- // about the act rather than about the song.
+ // A heavy arrow pointing down, which is what the reference puts
+ // here — and once it is on the phone, the same arrow inside a ring
+ // to say the journey is over. A tick would be about the act rather
+ // than about the music.
icon = if (kept) {
- PhosphorIcons.Fill.ArrowCircleDown
+ PhosphorIcons.Bold.ArrowCircleDown
} else {
- PhosphorIcons.Regular.Download
+ PhosphorIcons.Bold.ArrowDown
},
description = stringResource(
if (kept) R.string.remove_download else R.string.download,
),
- size = 52.dp,
+ size = 46.dp,
backdrop = backdrop,
onClick = onClick,
+ tint = tint,
)
// Around the button rather than inside it: the icon still has to be
// legible while this turns.
running?.let {
CircularProgressIndicator(
progress = { it.progress },
- color = Color.White,
+ color = tint,
trackColor = Color.White.copy(alpha = 0.22f),
strokeWidth = 2.dp,
gapSize = 0.dp,
- modifier = Modifier.size(52.dp),
+ modifier = Modifier.size(46.dp),
)
}
}
@@ -1162,6 +1742,7 @@ private fun CircleAction(
size: androidx.compose.ui.unit.Dp,
backdrop: Backdrop,
onClick: () -> Unit,
+ tint: Color = Color.White,
) {
LiquidButton(
onClick = onClick,
@@ -1170,14 +1751,19 @@ private fun CircleAction(
// nothing to bend, and only the film and the rim say this is glass.
modifier = Modifier
.size(size)
- .border(0.6.dp, Color.White.copy(alpha = 0.30f), CircleShape),
+ // A film of its own over the glass. The reference's round controls
+ // read as pale discs against the photograph rather than as holes
+ // cut in it, and refraction alone cannot do that over a picture as
+ // dark as most artist photographs are.
+ .background(Color.White.copy(alpha = 0.17f), CircleShape)
+ .border(0.6.dp, Color.White.copy(alpha = 0.26f), CircleShape),
contentHeight = size,
contentPadding = 0.dp,
) {
Icon(
icon,
contentDescription = description,
- tint = Color.White,
+ tint = tint,
modifier = Modifier.size(size * 0.44f),
)
}
@@ -1238,6 +1824,8 @@ private fun AlbumStrip(
private fun SectionHeader(
title: String,
sort: TrackSort,
+ /** Drawn as a page heading rather than as a label over a list. */
+ large: Boolean = false,
onSortOpen: (Boolean) -> Unit,
/** Where the sort button is, for the menu drawn above the list. */
onAnchor: (IntOffset) -> Unit,
@@ -1248,7 +1836,16 @@ private fun SectionHeader(
.padding(start = 24.dp, end = 14.dp, top = 22.dp, bottom = 6.dp),
verticalAlignment = Alignment.CenterVertically,
) {
- Text(title, style = MaterialTheme.typography.titleMedium, modifier = Modifier.weight(1f))
+ Text(
+ title,
+ style = if (large) {
+ MaterialTheme.typography.titleLarge
+ } else {
+ MaterialTheme.typography.titleMedium
+ },
+ fontWeight = FontWeight.Bold,
+ modifier = Modifier.weight(1f),
+ )
IconButton(
onClick = { onSortOpen(true) },
@@ -1259,7 +1856,7 @@ private fun SectionHeader(
) {
run {
Icon(
- PhosphorIcons.Regular.ArrowsDownUp,
+ PhosphorIcons.Bold.ArrowsDownUp,
contentDescription = stringResource(R.string.sort),
tint = if (sort == TrackSort.ORIGINAL) {
MaterialTheme.colorScheme.onSurfaceVariant
@@ -1276,22 +1873,53 @@ private fun SectionHeader(
/** What the hero shrinks to: a bar, under the status bar's own inset. */
private val COLLAPSED_BAR_HEIGHT = 56.dp
-/** Tall enough to be the top of the screen rather than a banner above a list. */
-private val HERO_HEIGHT = 420.dp
+/**
+ * Tall enough for a record and everything written under it.
+ *
+ * Measured rather than chosen: the cover, the title, the artist, the two
+ * buttons and the row of small ones stack to just under this, and a header
+ * shorter than its contents squeezes them — which is what a fixed-height header
+ * does when it is too small, since the column inside it keeps its own size.
+ */
+private val HERO_HEIGHT = 512.dp
+
+/** As tall as a drawn name gets before it starts crowding the controls. */
+private val LOGO_HEIGHT = 96.dp
-/** Where the page ends up once the cover's colour has faded out of it. */
-private val PageFloor = Color(0xFF0A0A0C)
+/** Decode size for the soft copy of the artist's photo, in pixels. */
+private const val HERO_BLUR_PX = 240
+
+/** Soft enough to be a wash, sharp enough to keep the picture's shapes. */
+private val HeroBlur = BlurTransformation(radius = 10, passes = 2)
+
+/**
+ * A page tone from the six hex digits the catalogue files with the artwork.
+ *
+ * Darkened, but much less than a colour taken out of a photograph: this one was
+ * picked to be a background and is already the right kind of colour, where a
+ * dominant colour arrives at whatever saturation the picture had.
+ */
+private fun tintOf(hex: String): Color =
+ dev.lelonio.square.ui.theme.pageColorForHex(hex)
/**
- * The page tone for a cover.
+ * White, carrying a colour's hue and none of its darkness.
*
- * The dominant colour arrives at full saturation — it has to, it is picked to
- * identify the artwork — and using it as a background would put text on a
- * fluorescent field. Most of the way to black keeps the hue recognisable and
- * nothing else. A null cover falls back to the floor rather than to grey.
+ * Mixing white with the page colour itself is what this did first, and on a page
+ * whose colour is a deep purple that gives grey — the darkness comes along with
+ * the hue. Taking the hue and the saturation, setting the brightness where a
+ * tint belongs, and only then mixing gives a purple-white on a purple page and a
+ * green-white on a green one.
*/
-private fun pageColorFor(accent: Color?): Color =
- accent?.let { lerp(it, PageFloor, 0.78f) } ?: PageFloor
+private fun inkTintedBy(color: Color): Color {
+ val hsv = FloatArray(3)
+ android.graphics.Color.colorToHSV(color.toArgb(), hsv)
+ if (hsv[1] < 0.06f) return Color.White
+ hsv[1] = hsv[1].coerceIn(0.5f, 1f)
+ hsv[2] = 0.92f
+ return lerp(Color.White, Color(android.graphics.Color.HSVToColor(hsv)), 0.26f)
+}
+
/**
* The little mark in a row that says this song is here.
@@ -1374,6 +2002,10 @@ private fun TrackRow(
isCurrent: Boolean,
onClick: () -> Unit,
onMenu: () -> Unit,
+ /** What the second line says; null for the artist and the length. */
+ subtitle: String? = null,
+ /** Its place on the record, drawn where the cover would be. */
+ numbered: Boolean = false,
/** Nothing is drawn until a download for this track exists; see below. */
download: dev.lelonio.square.data.DownloadState =
dev.lelonio.square.data.DownloadState.None,
@@ -1430,6 +2062,27 @@ private fun TrackRow(
// playlist is the least interesting thing about it. The playing row
// still says so, with the meter drawn over its own cover.
Box(contentAlignment = Alignment.Center) {
+ if (numbered) {
+ Box(
+ Modifier.size(width = 30.dp, height = 46.dp),
+ contentAlignment = Alignment.Center,
+ ) {
+ if (isCurrent) {
+ Icon(
+ PhosphorIcons.Fill.Waveform,
+ contentDescription = stringResource(R.string.now_playing),
+ tint = MaterialTheme.colorScheme.primary,
+ modifier = Modifier.size(18.dp),
+ )
+ } else {
+ Text(
+ position.toString(),
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ }
+ }
+ } else {
Artwork(
url = track.artworkUrl,
title = track.name,
@@ -1453,6 +2106,7 @@ private fun TrackRow(
)
}
}
+ }
}
Column(
@@ -1463,12 +2117,15 @@ private fun TrackRow(
Text(
text = track.name,
style = MaterialTheme.typography.titleMedium,
+ // A notch heavier than the app's own default: on the reference
+ // the title of a row is the one thing set in a weight you can
+ // pick out while scrolling.
color = if (isCurrent) {
MaterialTheme.colorScheme.primary
} else {
MaterialTheme.colorScheme.onSurface
},
- fontWeight = if (isCurrent) FontWeight.SemiBold else FontWeight.Medium,
+ fontWeight = if (isCurrent) FontWeight.Bold else FontWeight.SemiBold,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
@@ -1486,7 +2143,8 @@ private fun TrackRow(
// Artist and length on one line, as the reference has it:
// two stacked grey lines under every title turn the list
// into a wall of secondary text.
- text = "${track.artist} · ${formatDuration(track.durationMs)}",
+ text = subtitle
+ ?: "${track.artist} · ${formatDuration(track.durationMs)}",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
@@ -1497,7 +2155,7 @@ private fun TrackRow(
IconButton(onClick = onMenu, modifier = Modifier.size(32.dp)) {
Icon(
- PhosphorIcons.Regular.DotsThree,
+ PhosphorIcons.Bold.DotsThree,
contentDescription = stringResource(R.string.more),
tint = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.6f),
modifier = Modifier.size(18.dp),
@@ -1545,6 +2203,76 @@ fun openLinkOf(uri: String): String {
return "https://open.spotify.com/$kind/$id"
}
+/**
+ * The record a song is on and the year it came out, in one line.
+ *
+ * Whichever half is known: an album with no year is still worth naming, and a
+ * year with no album name is never the case. Empty when there is neither, and
+ * the row then falls back to the artist and the length.
+ */
+private fun CatalogTrack.releaseLine(): String = listOf(album, year)
+ .filter { it.isNotBlank() }
+ .joinToString(" · ")
+ .ifBlank { artist }
+
+/**
+ * The paragraph a record's page carries about itself.
+ *
+ * Folded to three lines with a word to open it, the way the reference folds it:
+ * some of these run to six paragraphs, and a page that begins with an essay
+ * buries the thing it is a page for.
+ */
+@Composable
+private fun EditorialNotes(notes: String) {
+ var open by remember(notes) { mutableStateOf(false) }
+ Column(
+ Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 24.dp, vertical = 12.dp)
+ .pressable({ open = !open }, pressedScale = 0.995f),
+ ) {
+ Text(
+ // The notes arrive as HTML often enough to matter, and a stray
+ // <p> in the middle of a paragraph reads as a bug in the app.
+ notes.replace(Regex("<[^>]+>"), "").trim(),
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ maxLines = if (open) Int.MAX_VALUE else 3,
+ overflow = TextOverflow.Ellipsis,
+ )
+ if (!open) {
+ Text(
+ stringResource(R.string.more_notes),
+ style = MaterialTheme.typography.labelMedium,
+ fontWeight = FontWeight.SemiBold,
+ color = MaterialTheme.colorScheme.onSurface,
+ modifier = Modifier.padding(top = 4.dp),
+ )
+ }
+ }
+}
+
+/**
+ * How long ago something happened, in the coarsest unit that still says it.
+ *
+ * "2 g" rather than "2 giorni, 4 ore": this is the line under a playlist's
+ * title, and what it is for is telling a live list from one nobody has touched
+ * in a year.
+ */
+@Composable
+private fun agoOf(iso: String): String {
+ val then = runCatching { java.time.Instant.parse(iso) }.getOrNull()
+ ?: return ""
+ val days = java.time.Duration.between(then, java.time.Instant.now()).toDays()
+ return when {
+ days <= 0 -> stringResource(R.string.ago_today)
+ days < 7 -> stringResource(R.string.ago_days, days)
+ days < 31 -> stringResource(R.string.ago_weeks, days / 7)
+ days < 365 -> stringResource(R.string.ago_months, days / 30)
+ else -> stringResource(R.string.ago_years, days / 365)
+ }
+}
+
@Composable
private fun StatusBox(content: @Composable () -> Unit) {
Box(
@@ -1606,9 +2334,16 @@ private fun formatTotal(ms: Long): String {
private fun ArtistAbout(
followers: Int,
genres: List<String>,
+ /** Where they are from, from Apple's catalogue; absent for most acts. */
+ origin: String?,
+ /** And what its editors wrote about them. */
+ bio: String?,
) {
- Column(Modifier.padding(start = 24.dp, end = 24.dp, top = 14.dp)) {
+ Column(Modifier.padding(start = 24.dp, end = 24.dp, top = 14.dp, bottom = 6.dp)) {
+ // The facts first and the prose under them, because the facts are what
+ // somebody who pressed "i" on an artist they do not know wants first.
val line = listOfNotNull(
+ origin?.takeIf { it.isNotBlank() },
followers.takeIf { it > 0 }?.let { stringResource(R.string.followers_count, compact(it)) },
genres.take(2).joinToString(" · ") { it.replaceFirstChar(Char::uppercase) }
.takeIf { it.isNotEmpty() },
@@ -1617,13 +2352,35 @@ private fun ArtistAbout(
if (line.isNotEmpty()) {
Text(
line,
- style = MaterialTheme.typography.bodySmall,
+ style = MaterialTheme.typography.labelMedium,
color = InkDim,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
}
+ if (!bio.isNullOrBlank()) {
+ var open by remember(bio) { mutableStateOf(false) }
+ Text(
+ bio.replace(Regex("<[^>]+>"), "").trim(),
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ maxLines = if (open) Int.MAX_VALUE else 4,
+ overflow = TextOverflow.Ellipsis,
+ modifier = Modifier
+ .padding(top = 10.dp)
+ .pressable({ open = !open }, pressedScale = 0.995f),
+ )
+ if (!open) {
+ Text(
+ stringResource(R.string.more_notes),
+ style = MaterialTheme.typography.labelMedium,
+ fontWeight = FontWeight.SemiBold,
+ color = MaterialTheme.colorScheme.onSurface,
+ modifier = Modifier.padding(top = 4.dp),
+ )
+ }
+ }
}
}
diff --git a/app/src/main/java/dev/lelonio/square/ui/player/GlassSurface.kt b/app/src/main/java/dev/lelonio/square/ui/player/GlassSurface.kt
index d9c77bc..a5ea7c9 100644
--- a/app/src/main/java/dev/lelonio/square/ui/player/GlassSurface.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/player/GlassSurface.kt
@@ -45,6 +45,22 @@ import dev.lelonio.square.ui.glass.liquidGlass
*/
val LocalGlassEnabled = androidx.compose.runtime.staticCompositionLocalOf { true }
+/**
+ * Whether the player is standing still.
+ *
+ * False for the frames of an opening or a closing, and read by the two things
+ * in the player that are video: a TextureView inside a layer that is being
+ * scaled and faded has its surface detached and re-attached around the change,
+ * and draws black for the length of the travel — a black rectangle sliding down
+ * the screen, and the last thing to go.
+ *
+ * Kept apart from [LocalGlassEnabled], which the sheet used to answer this
+ * question with. That one carries the listener's glass setting as well, so a
+ * player with the glass turned off had no moving cover either — two unrelated
+ * things behind one flag.
+ */
+val LocalPlayerSettled = androidx.compose.runtime.staticCompositionLocalOf { true }
+
@Composable
fun GlassSurface(
backdrop: Backdrop,
diff --git a/app/src/main/java/dev/lelonio/square/ui/player/NowPlayingSheet.kt b/app/src/main/java/dev/lelonio/square/ui/player/NowPlayingSheet.kt
index c60a2af..0579c3a 100644
--- a/app/src/main/java/dev/lelonio/square/ui/player/NowPlayingSheet.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/player/NowPlayingSheet.kt
@@ -145,6 +145,7 @@ fun NowPlayingSheet(
background()
androidx.compose.runtime.CompositionLocalProvider(
LocalGlassEnabled provides settled,
+ LocalPlayerSettled provides settled,
) {
expandedContent()
}
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 3a193dc..e39d73a 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
@@ -65,6 +65,8 @@ import androidx.compose.ui.draw.blur
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.graphics.Brush
+import androidx.compose.ui.graphics.CompositingStrategy
+import androidx.compose.ui.graphics.BlendMode
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
@@ -145,6 +147,17 @@ private const val PAUSED_DIM = 0.55f
* back here as a full-bleed backdrop.
*/
/** What occupies the middle of the player. */
+/**
+ * How long the cover and a Canvas take to change places.
+ *
+ * Matched to the clip's own fade below: the two are one movement, and a
+ * handover where each half runs at its own speed is visible as a dip.
+ */
+private const val CANVAS_HANDOVER = 500
+
+/** The shape the catalogue files an extended cover in: three by four. */
+private const val DETAIL_ASPECT = 3f / 4f
+
/** How long each half of a change between the cover and a panel takes. */
private const val STAGE_FADE_MS = 180
@@ -200,6 +213,32 @@ fun PlayerScreen(
backdrop: Backdrop,
/** The track's Canvas clip, or null when it has none. */
canvas: dev.lelonio.square.data.CanvasClip?,
+ /**
+ * The tall picture the record carries, where the catalogue has one.
+ *
+ * A song has one square cover and nothing else; the extended artwork
+ * belongs to its album, which is where the reference's own player takes it
+ * from as well. Null falls back to the square cover.
+ */
+ coverHeroUrl: String? = null,
+ /** And the moving version of it, for the records that have one. */
+ coverMotionUrl: String? = null,
+ /**
+ * The catalogue's own square scan, for the records with no tall picture.
+ *
+ * Better than falling straight back to the cover the queue carries: that
+ * one is sized for a list row, and this screen enlarges whatever it is
+ * given to fill a phone.
+ */
+ coverSquareUrl: String? = null,
+ /**
+ * The other catalogue has not answered yet.
+ *
+ * Holds the queue's own cover back for that moment: it is the fallback, and
+ * drawing it first only to replace it with a sharper copy of the same
+ * picture is the swap the listener sees.
+ */
+ coverPending: Boolean = false,
/** See MiniPlayer: the cover is shared with the bar this screen grew out of. */
sharedScope: androidx.compose.animation.SharedTransitionScope? = null,
animatedScope: androidx.compose.animation.AnimatedVisibilityScope? = null,
@@ -222,6 +261,8 @@ fun PlayerScreen(
* it loads. The player closes itself first; see the two callers.
*/
onOpenUri: (String, String) -> Unit = { _, _ -> },
+ /** Opens the record the playing track is on; null when there is none. */
+ onOpenAlbum: (() -> Unit)? = null,
/**
* Whether this track is already in one of the account's playlists.
*
@@ -341,6 +382,10 @@ fun PlayerScreen(
state.artworkUrl.takeIf { canvas == null },
)
+ // The tone the cover fades into, worked out the same way the pages do it.
+ val coverAccent by dev.lelonio.square.ui.theme.rememberArtworkColor(state.artworkUrl)
+ val coverTone = dev.lelonio.square.ui.theme.pageColorFor(coverAccent)
+
Box(Modifier.fillMaxSize()) {
Box(
Modifier
@@ -376,8 +421,106 @@ fun PlayerScreen(
// video playing there is something, and the glow above is taken
// from its own frames: drawing the cover's aura over that would
// paint the song's colours on top of the video's.
- if (canvas == null && !videoOn) {
- CoverAura(colors = auraColors, playing = state.isPlaying)
+ // The picture leaves on the same clock the clip arrives on.
+ //
+ // It used to be a condition: the moment a Canvas existed, the cover
+ // was dropped from the composition and the clip faded up over
+ // whatever was behind it — a cut on one side of a crossfade, which
+ // reads as the screen blinking. Held as an opacity instead, so the
+ // two overlap for the length of the change, and it comes back the
+ // same way on a track that has no clip.
+ val coverFade by animateFloatAsState(
+ targetValue = if (!videoOn && (canvas == null || !canvasReady)) 1f else 0f,
+ animationSpec = tween(CANVAS_HANDOVER),
+ label = "coverFade",
+ )
+
+ if (coverFade > 0f) {
+ Box(Modifier.fillMaxSize().graphicsLayer { alpha = coverFade }) {
+ // The cover, shown the way every other screen in the app shows
+ // a picture it is built around: filling the top, softening on
+ // the way down, ending on the colour taken from it. A track
+ // with no clip used to get moving light in those same colours
+ // and nothing of the picture itself — which was a stand-in for
+ // an image the app had all along.
+ dev.lelonio.square.ui.components.HeroBackdrop(
+ artworkUrl = coverHeroUrl
+ ?: coverSquareUrl
+ ?: state.artworkUrl.takeIf { !coverPending },
+ // The moving cover only while the player is standing
+ // still. Otherwise its TextureView goes black for the
+ // length of the closing animation and is the last thing
+ // left on screen — see LocalPlayerSettled. The still
+ // picture underneath is what the travel shows instead, and
+ // at that size and speed the swap is invisible.
+ motionUrl = coverMotionUrl.takeIf { LocalPlayerSettled.current },
+ title = state.title,
+ pageColor = coverTone,
+ pending = coverPending,
+ // Where the picture stops being a picture. It runs longer
+ // when it is the only one on the screen — there is no sleeve
+ // over it to look at, so it has to hold the top of the
+ // player on its own — and ends earlier when it is only the
+ // ground under a square cover.
+ // Left alone to its own bottom edge, and softened only in
+ // the last stretch before it.
+ //
+ // Measured on the screen: the picture is three by four from
+ // the top, so it ends where the "watch the video" button
+ // begins, and the fade runs in the last stretch above that
+ // line rather than starting a third of the way up.
+ //
+ // It has to *finish* before that line, though, and not on
+ // it. Softening right up to the edge leaves the picture
+ // still faintly there where it stops, and a picture that is
+ // faintly there has a border — which is the seam the fade is
+ // for. This lands the colour a few percent early, so what
+ // reaches the bottom of the frame is colour and nothing
+ // else.
+ softenFrom = 0.84f,
+ softenTo = 0.96f,
+ // Three by four, whichever picture it is — the shape the
+ // extended covers are drawn in, and the shape that reaches
+ // down to the title with nothing empty in between.
+ //
+ // A square sleeve is trimmed at the sides to fit it, not
+ // enlarged: the catalogue's scan is 1600 across and the
+ // screen is 1080, so what is cropped is real picture and
+ // what is drawn is still smaller than the source.
+ imageAspect = DETAIL_ASPECT,
+ modifier = Modifier.fillMaxSize(),
+ )
+ // And the light still moves, in the cover's own colours: it is
+ // what the glass above has to bend. Only *under* the picture,
+ // though — beams sweeping across a photograph wash it out, and
+ // the part of this screen that needs something alive in it is
+ // the colour field below, where the controls sit.
+ Box(
+ Modifier
+ .fillMaxSize()
+ .graphicsLayer { compositingStrategy = CompositingStrategy.Offscreen }
+ .drawWithContent {
+ drawContent()
+ // Where the picture ends, in this box's own terms:
+ // it is as tall as the screen is wide, times four
+ // thirds. Measured rather than guessed, since the
+ // slot is whatever the phone leaves it.
+ val ends = (size.width / DETAIL_ASPECT / size.height)
+ .coerceIn(0f, 1f)
+ drawRect(
+ brush = Brush.verticalGradient(
+ 0f to Color.Transparent,
+ (ends * 0.8f) to Color.Transparent,
+ ends to Color.Black,
+ 1f to Color.Black,
+ ),
+ blendMode = BlendMode.DstIn,
+ )
+ },
+ ) {
+ CoverAura(colors = auraColors, playing = state.isPlaying)
+ }
+ }
}
@@ -549,6 +692,11 @@ fun PlayerScreen(
// left to fade. The panels go on swapping between
// themselves; the cover is simply the floor of this
// slot, and opening a panel takes its opacity away.
+ // No square cover on a record that has a picture of its
+ // own. The extended artwork behind this slot is the
+ // cover, at the size the record was given one for, and
+ // putting the sleeve back on top of it is the same image
+ // twice — which is what the reference stopped doing.
val coverShowing = panel == PlayerPanel.NONE &&
!(videoOn && videoPlayer != null && LocalGlassEnabled.current) &&
(canvas == null || !canvasReady)
@@ -609,31 +757,16 @@ fun PlayerScreen(
}
}
- if (coverAlpha > 0f) {
- Box(
- Modifier
- .fillMaxSize()
- .graphicsLayer { alpha = coverAlpha },
- contentAlignment = Alignment.Center,
- ) {
- Cover(
- state,
- // Always as if nothing were open: the
- // cover shrinks towards the size it
- // takes beside a panel, and doing that
- // while it fades is two movements where
- // one was asked for. It is only ever
- // seen at full size now.
- PlayerPanel.NONE,
- onNext,
- onPrevious,
- // Only for the journey the bar's
- // thumbnail makes into this cover.
- sharedScope.takeIf { coverShowing },
- animatedScope.takeIf { coverShowing },
- )
- }
- }
+ // No sleeve on this screen any more.
+ //
+ // What used to sit here was the square cover, drawn
+ // over a blurred copy of itself — the same image
+ // twice, the small one hiding the middle of the
+ // large one. The picture behind this slot *is* the
+ // cover now: the record's own extended artwork
+ // where the catalogue has one, and the sleeve itself
+ // laid across the top where it does not, both of
+ // them ending in the colour the page is made of.
AnimatedContent(
targetState = when (panel) {
@@ -873,6 +1006,7 @@ fun PlayerScreen(
onCollapse()
onOpenUri(uri, name)
},
+ onOpenAlbum = onOpenAlbum,
)
// A station built from this track, the way the
// official client's own radio button does it.
@@ -1438,6 +1572,14 @@ private fun TitleBlock(
state: PlaybackState,
modifier: Modifier = Modifier,
onOpenArtist: (uri: String, name: String) -> Unit = { _, _ -> },
+ /**
+ * Opens the record this track is on. Null where there is none to open.
+ *
+ * A plain callback rather than a URI: the queue does not always carry the
+ * album's address — a list resolved before the app started keeping it has
+ * only the name — and whoever hands this in is the one that can look it up.
+ */
+ onOpenAlbum: (() -> Unit)? = null,
) {
// Slid rather than swapped on a track change: this capsule is the only place
// the track is named now that the big cover is gone, so the change has to be
@@ -1452,11 +1594,22 @@ private fun TitleBlock(
modifier = modifier,
) { (title, artist) ->
Column {
+ // The title is the way to the record it is on — the same idea as
+ // the artist's name below it being the way to them. Only where
+ // there is somewhere to go: a queue built from search results, or a
+ // track another device is playing, names a record this app has no
+ // address for, and a title that looks like a link and does nothing
+ // is worse than a caption.
Text(
text = title,
style = MaterialTheme.typography.titleLarge,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
+ modifier = if (onOpenAlbum != null) {
+ Modifier.pressable(onOpenAlbum, pressedScale = 0.98f)
+ } else {
+ Modifier
+ },
)
ArtistLine(state, artist, onOpenArtist)
}
diff --git a/app/src/main/java/dev/lelonio/square/ui/player/PlayerState.kt b/app/src/main/java/dev/lelonio/square/ui/player/PlayerState.kt
index 82982f8..c7e2a73 100644
--- a/app/src/main/java/dev/lelonio/square/ui/player/PlayerState.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/player/PlayerState.kt
@@ -25,6 +25,16 @@ data class PlaybackState(
val mediaId: String? = null,
val title: String = "",
val artist: String = "",
+ /**
+ * The record it is from, where the queue knows it.
+ *
+ * Only the player uses it, and only to ask the other catalogue for that
+ * record's own artwork — the tall picture and the moving cover a song
+ * inherits from its album; see AppleCatalog.
+ */
+ val album: String = "",
+ /** And its address, where the queue knows it; see EXTRA_ALBUM_URI. */
+ val albumUri: String? = null,
val artworkUrl: String? = null,
val isPlaying: Boolean = false,
/**
@@ -179,6 +189,7 @@ fun rememberPlaybackState(
mediaId = player.currentMediaItem?.mediaId,
title = metadata.title?.toString().orEmpty(),
artist = metadata.artist?.toString().orEmpty(),
+ album = metadata.albumTitle?.toString().orEmpty(),
artworkUrl = metadata.artworkUri?.toString(),
isPlaying = player.isPlaying,
wantsPlay = player.playWhenReady,
@@ -192,6 +203,7 @@ fun rememberPlaybackState(
pitch = player.playbackParameters.pitch,
source = metadata.extras?.getString(EXTRA_CONTEXT_LABEL).orEmpty(),
artistUri = metadata.extras?.getString(dev.lelonio.square.ui.EXTRA_ARTIST_URI),
+ albumUri = metadata.extras?.getString(dev.lelonio.square.ui.EXTRA_ALBUM_URI),
artists = run {
val names = metadata.extras
?.getStringArrayList(dev.lelonio.square.ui.EXTRA_ARTIST_NAMES)
diff --git a/app/src/main/java/dev/lelonio/square/ui/search/SearchScreen.kt b/app/src/main/java/dev/lelonio/square/ui/search/SearchScreen.kt
index 9287c96..e62ca22 100644
--- a/app/src/main/java/dev/lelonio/square/ui/search/SearchScreen.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/search/SearchScreen.kt
@@ -21,7 +21,9 @@ import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
+import androidx.compose.foundation.text.BasicTextField
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
@@ -29,6 +31,8 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
+import androidx.compose.ui.focus.FocusRequester
+import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
@@ -47,9 +51,13 @@ import dev.lelonio.square.ui.player.GlassFilm
import dev.lelonio.square.ui.settings.WebApiSetup
import dev.lelonio.square.ui.theme.Ink
import dev.lelonio.square.ui.theme.InkDim
+import androidx.compose.foundation.clickable
import com.adamglin.PhosphorIcons
+import com.adamglin.phosphoricons.Bold
import com.adamglin.phosphoricons.Fill
import com.adamglin.phosphoricons.Regular
+import com.adamglin.phosphoricons.bold.MagnifyingGlass
+import com.adamglin.phosphoricons.bold.X
import com.adamglin.phosphoricons.regular.DotsThree
/** Which kind of result the page is showing. */
@@ -93,6 +101,15 @@ fun SearchScreen(
/** Opens the same track sheet the library rows open. */
onTrackMenu: (CatalogTrack) -> Unit,
onOpenContext: (SearchItem) -> Unit,
+ /**
+ * What is typed goes here.
+ *
+ * The field used to live in the bottom bar, growing out of the search
+ * circle. That was a local change to the bar, and the bar is the library's
+ * again — so the box you type in is back on the page that answers it, which
+ * is also where every other client puts it.
+ */
+ onQuery: (String) -> Unit,
backdrop: Backdrop,
) {
var kind by remember { mutableStateOf(Kind.ALL) }
@@ -102,11 +119,9 @@ fun SearchScreen(
remember(query) { kind = Kind.ALL }
LazyColumn(Modifier.fillMaxSize(), contentPadding = contentPadding) {
- // No field, and no title over it. Both are in the bottom bar now: the
- // search button there grows into the box you type in, which is the whole
- // point of that control, and a page that answers it by drawing a second
- // box asks which of the two is listening. What is left here is the
- // answer, which is what the page was ever for.
+ // No field here: it is in the bar, where the search button grows into
+ // it. A page that answers a query by drawing a second box asks which of
+ // the two is listening.
if (!state.results.isEmpty && !state.loading) {
item(contentType = "chips") {
diff --git a/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt b/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt
index 8334ec4..9ebef05 100644
--- a/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt
@@ -272,6 +272,12 @@ fun SettingsScreen(
CrossfadeSection()
}
+ // Spotify's own, served by its access point: on another source there is
+ // no clip to ask for and nothing this switch could turn off.
+ if (open == SettingsPage.Playback && showSpotify) item("canvas") {
+ CanvasSection(backdrop)
+ }
+
// The effects run on our own output, so this one holds for both backends.
if (open == SettingsPage.Playback) item("effect-quality") {
EffectQualitySection()
@@ -624,6 +630,31 @@ private fun YouTubeAccountSection(onSignIn: () -> Unit, onChannelChange: () -> U
}
}
+/**
+ * The looping clip, on or off for everything.
+ *
+ * Off is not only "do not draw it": no clip is fetched at all, so a listener who
+ * turns this off stops paying for a video on every track as well as seeing one.
+ */
+@Composable
+private fun CanvasSection(backdrop: Backdrop) {
+ val context = LocalContext.current
+ val store = remember(context) {
+ (context.applicationContext as dev.lelonio.square.SquareApplication).preferences
+ }
+ val enabled by store.canvasEnabled.collectAsStateWithLifecycle()
+
+ Section(stringResource(R.string.canvas)) {
+ DownloadSwitch(
+ label = stringResource(R.string.canvas_show),
+ note = stringResource(R.string.canvas_note),
+ checked = enabled,
+ backdrop = backdrop,
+ onChange = store::setCanvasEnabled,
+ )
+ }
+}
+
@Composable
private fun EffectQualitySection() {
val context = LocalContext.current
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 af0fe1e..7fa24a7 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
@@ -17,6 +17,42 @@ import coil.request.SuccessResult
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
+/**
+ * Where a page ends up once the artwork's colour has faded out of it.
+ *
+ * Not pure black: a page that ends on #000 against a phone's own black bezel
+ * has no bottom edge, and the last shelf on it looks like it is falling off.
+ */
+val PageFloor = Color(0xFF0A0A0C)
+
+/**
+ * The page tone for a cover.
+ *
+ * The dominant colour arrives at full saturation — it has to, it is picked to
+ * identify the artwork — and using it as a background would put text on a
+ * fluorescent field. Most of the way to the floor keeps the hue recognisable
+ * and nothing else. A null cover falls back to the floor rather than to grey.
+ */
+fun pageColorFor(accent: Color?): Color =
+ accent?.let { androidx.compose.ui.graphics.lerp(it, PageFloor, 0.7f) } ?: PageFloor
+
+/**
+ * The page tone the other catalogue chose for a record, as six hex digits.
+ *
+ * Kept apart from [pageColorFor] and mixed much lighter, because the two
+ * sources are not the same kind of colour. A dominant colour is picked out of a
+ * photograph at full strength and has to be taken most of the way down before
+ * text can sit on it; this one was chosen by somebody as the ground for a page,
+ * so taking it that far down would throw away the choice — and it is what makes
+ * a record's page read as coloured rather than as dark grey.
+ *
+ * Null, or anything unparseable, ends on the floor like everything else.
+ */
+fun pageColorForHex(hex: String?): Color = hex
+ ?.let { runCatching { Color(android.graphics.Color.parseColor("#$it")) }.getOrNull() }
+ ?.let { androidx.compose.ui.graphics.lerp(it, PageFloor, 0.42f) }
+ ?: PageFloor
+
/**
* The dominant colour of an artwork URL, for seeding the theme.
*
@@ -47,6 +83,21 @@ private val cached = object : LinkedHashMap<String, Color>(16, 0.75f, true) {
override fun removeEldestEntry(eldest: Map.Entry<String, Color>?) = size > 64
}
+/**
+ * Works out a cover's colour before anything asks for it.
+ *
+ * The picture and the colour it tints the page with are two different reads of
+ * the same file, and only the first of them is prefetched with the song that is
+ * coming. Left alone, the artwork arrived out of memory in a single frame while
+ * its colour was still being extracted — the cover changed, and the page caught
+ * up with it a moment later. This puts the answer in the same place the screen
+ * will look for it, at the same time as the picture.
+ */
+suspend fun warmArtworkColor(context: Context, url: String) {
+ if (cached.containsKey(url)) return
+ extractDominant(context, url)?.let { cached[url] = it }
+}
+
/**
* A handful of colours from an artwork, for something that has to move.
*
diff --git a/app/src/main/java/dev/lelonio/square/ui/theme/Fonts.kt b/app/src/main/java/dev/lelonio/square/ui/theme/Fonts.kt
new file mode 100644
index 0000000..46d9211
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/ui/theme/Fonts.kt
@@ -0,0 +1,38 @@
+package dev.lelonio.square.ui.theme
+
+import androidx.compose.ui.text.ExperimentalTextApi
+import androidx.compose.ui.text.font.Font
+import androidx.compose.ui.text.font.FontFamily
+import androidx.compose.ui.text.font.FontVariation
+import androidx.compose.ui.text.font.FontWeight
+import dev.lelonio.square.R
+
+/** The weights the app sets; anything else is interpolated between them. */
+private val WEIGHTS = listOf(300, 400, 500, 600, 700, 800, 900)
+
+/**
+ * The app's own face.
+ *
+ * Inter rather than the face the reference uses. Apple's is SF Pro, and its
+ * licence covers interfaces on Apple's platforms — putting the file inside an
+ * Android package is redistribution, which that licence does not grant, whatever
+ * the app is imitating. Inter was drawn for screens against the same brief and
+ * shares what makes the reference's text look the way it does: an upright
+ * grotesque with a tall x-height, open apertures and flat terminals. At the same
+ * sizes and tracking it is very close, and it is ours to ship.
+ *
+ * One variable file rather than seven static ones: it weighs less than three of
+ * them, and every weight in between is available — which the display sizes here
+ * want, since a name set at 46sp needs a different weight from the same name at
+ * 22.
+ */
+@OptIn(ExperimentalTextApi::class)
+val Inter = FontFamily(
+ WEIGHTS.map { weight ->
+ Font(
+ R.font.inter,
+ weight = FontWeight(weight),
+ variationSettings = FontVariation.Settings(FontVariation.weight(weight)),
+ )
+ },
+)
diff --git a/app/src/main/java/dev/lelonio/square/ui/theme/Theme.kt b/app/src/main/java/dev/lelonio/square/ui/theme/Theme.kt
index 20b3643..ac368f1 100644
--- a/app/src/main/java/dev/lelonio/square/ui/theme/Theme.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/theme/Theme.kt
@@ -178,20 +178,22 @@ fun Modifier.softShadow(
*/
private val SpotTypography = Typography(
displayLarge = TextStyle(
+ fontFamily = Inter,
fontSize = 34.sp,
lineHeight = 38.sp,
fontWeight = FontWeight.Bold,
letterSpacing = (-1.2).sp,
),
headlineLarge = TextStyle(
+ fontFamily = Inter,
fontSize = 27.sp,
lineHeight = 31.sp,
fontWeight = FontWeight.Bold,
letterSpacing = (-0.8).sp,
),
- titleLarge = TextStyle(fontSize = 19.sp, fontWeight = FontWeight.SemiBold, letterSpacing = (-0.3).sp),
- titleMedium = TextStyle(fontSize = 15.5.sp, fontWeight = FontWeight.Medium, letterSpacing = (-0.1).sp),
- bodyMedium = TextStyle(fontSize = 13.5.sp, fontWeight = FontWeight.Normal),
- bodySmall = TextStyle(fontSize = 12.sp, fontWeight = FontWeight.Normal),
- labelLarge = TextStyle(fontSize = 10.5.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.2.sp),
+ titleLarge = TextStyle(fontFamily = Inter, fontSize = 19.sp, fontWeight = FontWeight.SemiBold, letterSpacing = (-0.3).sp),
+ titleMedium = TextStyle(fontFamily = Inter, fontSize = 15.5.sp, fontWeight = FontWeight.Medium, letterSpacing = (-0.1).sp),
+ bodyMedium = TextStyle(fontFamily = Inter, fontSize = 13.5.sp, fontWeight = FontWeight.Normal),
+ bodySmall = TextStyle(fontFamily = Inter, fontSize = 12.sp, fontWeight = FontWeight.Normal),
+ labelLarge = TextStyle(fontFamily = Inter, fontSize = 10.5.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.2.sp),
)
diff --git a/app/src/main/res/font/inter.ttf b/app/src/main/res/font/inter.ttf
new file mode 100644
index 0000000..047c92f
Binary files /dev/null and b/app/src/main/res/font/inter.ttf differ
diff --git a/app/src/main/res/layout/motion_cover.xml b/app/src/main/res/layout/motion_cover.xml
new file mode 100644
index 0000000..843dcf7
--- /dev/null
+++ b/app/src/main/res/layout/motion_cover.xml
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ The moving cover's own view.
+
+ Inflated rather than constructed in code for one attribute: surface_type. A
+ PlayerView built in Kotlin gets a SurfaceView, which is a separate window
+ punched through the app's own — it ignores the alpha and the transforms of the
+ composition around it, so a page fading out left its video hanging on screen
+ after everything else had gone. A TextureView is an ordinary view: it fades
+ and moves with whatever holds it, at the cost of one more copy per frame,
+ which for a few seconds of album art is a trade worth making.
+-->
+<androidx.media3.ui.PlayerView
+ xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:app="http://schemas.android.com/apk/res-auto"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ app:surface_type="texture_view"
+ app:use_controller="false"
+ app:resize_mode="zoom" />
diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml
index eb88bf8..905e012 100644
--- a/app/src/main/res/values-de/strings.xml
+++ b/app/src/main/res/values-de/strings.xml
@@ -345,6 +345,7 @@
<string name="download_waiting_wifi">Wartet auf WLAN</string>
<string name="download_waiting_network">Wartet auf eine Verbindung</string>
<string name="download_waiting_engine">Wartet auf Spotify</string>
+ <string name="download_extras">Cover und Songtexte werden ergänzt</string>
<string name="download_quality">Downloadqualität</string>
<string name="download_quality_note">In welcher Qualität ein Download gespeichert wird. Hier gibt es kein Automatisch: ein Download passiert einmal und bleibt, also sollte er nicht die Kopie sein, die die Verbindung gerade zuließ.</string>
<string name="download_wifi_only">Nur über WLAN herunterladen</string>
@@ -370,4 +371,31 @@
<string name="radio_of">Radio zu %1$s</string>
<string name="remove_download_confirm">Die heruntergeladenen Songs von „%1$s“ von diesem Telefon entfernen?</string>
<string name="remove_download_confirm_action">Entfernen</string>
+ <string name="tab_new">Neu</string>
+ <string name="tab_radio">Radio</string>
+ <string name="latest_release">Neueste Veröffentlichung</string>
+ <string name="top_songs">Top-Titel</string>
+ <string name="stations_for_you">Sender für dich</string>
+ <string name="made_for_you">Für dich gemacht</string>
+ <string name="new_releases_title">Neuerscheinungen</string>
+ <string name="nothing_here">Hier ist noch nichts</string>
+ <string name="radio_empty">Sender entstehen aus dem, was du hörst.</string>
+ <string name="new_songs">Neue Titel</string>
+ <string name="new_this_week">Neu diese Woche</string>
+ <string name="new_release_tag">Neuerscheinung</string>
+ <plurals name="song_count">
+ <item quantity="one">%1$d Titel</item>
+ <item quantity="other">%1$d Titel</item>
+ </plurals>
+ <string name="songs_and_length">%1$d Titel, %2$s</string>
+ <string name="more_notes">MEHR</string>
+ <string name="updated_ago">Aktualisiert: %1$s</string>
+ <string name="ago_today">heute</string>
+ <string name="ago_days">%1$d T</string>
+ <string name="ago_weeks">%1$d Wo</string>
+ <string name="ago_months">%1$d Mon</string>
+ <string name="ago_years">%1$d J</string>
+ <string name="canvas">Canvas</string>
+ <string name="canvas_show">Loop-Clips zeigen</string>
+ <string name="canvas_note">Das kurze Video, das manche Titel mitbringen. Aus wird es auch nicht geladen.</string>
</resources>
diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml
index d3e8084..fc04aa6 100644
--- a/app/src/main/res/values-es/strings.xml
+++ b/app/src/main/res/values-es/strings.xml
@@ -345,6 +345,7 @@
<string name="download_waiting_wifi">Esperando al Wi‑Fi</string>
<string name="download_waiting_network">Esperando una conexión</string>
<string name="download_waiting_engine">Esperando a Spotify</string>
+ <string name="download_extras">Completando portadas y letras</string>
<string name="download_quality">Calidad de las descargas</string>
<string name="download_quality_note">Con qué calidad se guarda una descarga. Aquí no hay automático: una descarga se hace una vez y se queda, así que no debería ser la copia que la conexión permitió ese minuto.</string>
<string name="download_wifi_only">Descargar solo con Wi‑Fi</string>
@@ -370,4 +371,31 @@
<string name="radio_of">Radio de %1$s</string>
<string name="remove_download_confirm">¿Quitar de este teléfono las canciones descargadas de «%1$s»?</string>
<string name="remove_download_confirm_action">Quitar</string>
+ <string name="tab_new">Novedades</string>
+ <string name="tab_radio">Radio</string>
+ <string name="latest_release">Último lanzamiento</string>
+ <string name="top_songs">Canciones principales</string>
+ <string name="stations_for_you">Emisoras para ti</string>
+ <string name="made_for_you">Hechas para ti</string>
+ <string name="new_releases_title">Novedades</string>
+ <string name="nothing_here">Aquí no hay nada todavía</string>
+ <string name="radio_empty">Las emisoras se crean a partir de lo que escuchas.</string>
+ <string name="new_songs">Canciones nuevas</string>
+ <string name="new_this_week">Novedades de la semana</string>
+ <string name="new_release_tag">Nuevo lanzamiento</string>
+ <plurals name="song_count">
+ <item quantity="one">%1$d canción</item>
+ <item quantity="other">%1$d canciones</item>
+ </plurals>
+ <string name="songs_and_length">%1$d canciones, %2$s</string>
+ <string name="more_notes">MÁS</string>
+ <string name="updated_ago">Actualizada: %1$s</string>
+ <string name="ago_today">hoy</string>
+ <string name="ago_days">%1$d d</string>
+ <string name="ago_weeks">%1$d sem</string>
+ <string name="ago_months">%1$d meses</string>
+ <string name="ago_years">%1$d años</string>
+ <string name="canvas">Canvas</string>
+ <string name="canvas_show">Mostrar clips en bucle</string>
+ <string name="canvas_note">El vídeo corto que traen algunas canciones. Desactivado, tampoco se descarga.</string>
</resources>
diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml
index 41ae04c..a70be6e 100644
--- a/app/src/main/res/values-fr/strings.xml
+++ b/app/src/main/res/values-fr/strings.xml
@@ -345,6 +345,7 @@
<string name="download_waiting_wifi">En attente du Wi‑Fi</string>
<string name="download_waiting_network">En attente d\'une connexion</string>
<string name="download_waiting_engine">En attente de Spotify</string>
+ <string name="download_extras">Finalisation des pochettes et paroles</string>
<string name="download_quality">Qualité des téléchargements</string>
<string name="download_quality_note">La qualité à laquelle un téléchargement est gardé. Pas d\'automatique ici : un téléchargement se fait une fois et reste, il ne devrait donc pas être la copie que la connexion permettait à cette minute.</string>
<string name="download_wifi_only">Télécharger uniquement en Wi‑Fi</string>
@@ -370,4 +371,31 @@
<string name="radio_of">Radio de %1$s</string>
<string name="remove_download_confirm">Retirer de ce téléphone les titres téléchargés de « %1$s » ?</string>
<string name="remove_download_confirm_action">Retirer</string>
+ <string name="tab_new">Nouveautés</string>
+ <string name="tab_radio">Radio</string>
+ <string name="latest_release">Dernière sortie</string>
+ <string name="top_songs">Titres populaires</string>
+ <string name="stations_for_you">Stations pour vous</string>
+ <string name="made_for_you">Faites pour vous</string>
+ <string name="new_releases_title">Nouvelles sorties</string>
+ <string name="nothing_here">Rien ici pour le moment</string>
+ <string name="radio_empty">Les stations sont créées à partir de vos écoutes.</string>
+ <string name="new_songs">Nouveaux titres</string>
+ <string name="new_this_week">Nouveautés de la semaine</string>
+ <string name="new_release_tag">Nouvelle sortie</string>
+ <plurals name="song_count">
+ <item quantity="one">%1$d titre</item>
+ <item quantity="other">%1$d titres</item>
+ </plurals>
+ <string name="songs_and_length">%1$d titres, %2$s</string>
+ <string name="more_notes">PLUS</string>
+ <string name="updated_ago">Mise à jour : %1$s</string>
+ <string name="ago_today">aujourd\'hui</string>
+ <string name="ago_days">%1$d j</string>
+ <string name="ago_weeks">%1$d sem</string>
+ <string name="ago_months">%1$d mois</string>
+ <string name="ago_years">%1$d ans</string>
+ <string name="canvas">Canvas</string>
+ <string name="canvas_show">Afficher les clips en boucle</string>
+ <string name="canvas_note">La courte vidéo que portent certains titres. Désactivé, elle n\'est pas téléchargée non plus.</string>
</resources>
diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml
index ea3a59b..4597588 100644
--- a/app/src/main/res/values-hi/strings.xml
+++ b/app/src/main/res/values-hi/strings.xml
@@ -360,6 +360,7 @@
<string name="download_waiting_wifi">Wi‑Fi का इंतज़ार</string>
<string name="download_waiting_network">कनेक्शन का इंतज़ार</string>
<string name="download_waiting_engine">Spotify का इंतज़ार</string>
+ <string name="download_extras">कवर और बोल पूरे किए जा रहे हैं</string>
<string name="download_quality">डाउनलोड क्वालिटी</string>
<string name="download_quality_note">डाउनलोड किस क्वालिटी में रखा जाएगा। यहाँ ऑटोमैटिक नहीं है: डाउनलोड एक बार होता है और रह जाता है।</string>
<string name="download_wifi_only">केवल Wi‑Fi पर डाउनलोड करें</string>
@@ -385,4 +386,31 @@
<string name="radio_of">%1$s का रेडियो</string>
<string name="remove_download_confirm">“%1$s” के डाउनलोड किए गए गाने इस फ़ोन से हटाएँ?</string>
<string name="remove_download_confirm_action">हटाएँ</string>
+ <string name="tab_new">नया</string>
+ <string name="tab_radio">रेडियो</string>
+ <string name="latest_release">नवीनतम रिलीज़</string>
+ <string name="top_songs">टॉप गाने</string>
+ <string name="stations_for_you">आपके लिए स्टेशन</string>
+ <string name="made_for_you">आपके लिए बने</string>
+ <string name="new_releases_title">नई रिलीज़</string>
+ <string name="nothing_here">यहाँ अभी कुछ नहीं है</string>
+ <string name="radio_empty">स्टेशन आपकी सुनी हुई चीज़ों से बनते हैं.</string>
+ <string name="new_songs">नए गाने</string>
+ <string name="new_this_week">इस हफ़्ते नया</string>
+ <string name="new_release_tag">नई रिलीज़</string>
+ <plurals name="song_count">
+ <item quantity="one">%1$d गाना</item>
+ <item quantity="other">%1$d गाने</item>
+ </plurals>
+ <string name="songs_and_length">%1$d गाने, %2$s</string>
+ <string name="more_notes">और</string>
+ <string name="updated_ago">अपडेट: %1$s</string>
+ <string name="ago_today">आज</string>
+ <string name="ago_days">%1$d दि</string>
+ <string name="ago_weeks">%1$d सप्ता</string>
+ <string name="ago_months">%1$d माह</string>
+ <string name="ago_years">%1$d वर्ष</string>
+ <string name="canvas">Canvas</string>
+ <string name="canvas_show">लूप क्लिप दिखाएँ</string>
+ <string name="canvas_note">कुछ गानों के साथ आने वाला छोटा वीडियो. बंद होने पर डाउनलोड भी नहीं होता.</string>
</resources>
diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml
index bfd8e3e..cc16d81 100644
--- a/app/src/main/res/values-it/strings.xml
+++ b/app/src/main/res/values-it/strings.xml
@@ -346,6 +346,7 @@
<string name="download_waiting_wifi">In attesa del Wi‑Fi</string>
<string name="download_waiting_network">In attesa di una connessione</string>
<string name="download_waiting_engine">In attesa di Spotify</string>
+ <string name="download_extras">Completamento di copertine e testi</string>
<string name="download_quality">Qualità dei download</string>
<string name="download_quality_note">A che qualità viene tenuto un download. Qui non c\'è l\'automatico: un download si fa una volta e resta, quindi non deve essere la copia che la connessione permetteva in quel minuto.</string>
<string name="download_wifi_only">Scarica solo su Wi‑Fi</string>
@@ -371,4 +372,31 @@
<string name="radio_of">Radio di %1$s</string>
<string name="remove_download_confirm">Vuoi togliere da questo telefono i brani scaricati di “%1$s”?</string>
<string name="remove_download_confirm_action">Rimuovi</string>
+ <string name="tab_new">Novità</string>
+ <string name="tab_radio">Radio</string>
+ <string name="latest_release">Ultima uscita</string>
+ <string name="top_songs">Brani principali</string>
+ <string name="stations_for_you">Stazioni per te</string>
+ <string name="made_for_you">Fatte per te</string>
+ <string name="new_releases_title">Nuove uscite</string>
+ <string name="nothing_here">Ancora niente qui</string>
+ <string name="radio_empty">Le stazioni nascono da ciò che ascolti.</string>
+ <string name="new_songs">Nuovi brani</string>
+ <string name="new_this_week">Novità della settimana</string>
+ <string name="new_release_tag">Nuova uscita</string>
+ <plurals name="song_count">
+ <item quantity="one">%1$d brano</item>
+ <item quantity="other">%1$d brani</item>
+ </plurals>
+ <string name="songs_and_length">%1$d brani, %2$s</string>
+ <string name="more_notes">ALTRO</string>
+ <string name="updated_ago">Aggiornata: %1$s</string>
+ <string name="ago_today">oggi</string>
+ <string name="ago_days">%1$d g</string>
+ <string name="ago_weeks">%1$d sett</string>
+ <string name="ago_months">%1$d mesi</string>
+ <string name="ago_years">%1$d anni</string>
+ <string name="canvas">Canvas</string>
+ <string name="canvas_show">Mostra i video in loop</string>
+ <string name="canvas_note">Il breve video che alcuni brani portano con sé. Disattivato, non viene nemmeno scaricato.</string>
</resources>
diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml
index 659a32d..4615196 100644
--- a/app/src/main/res/values-pt/strings.xml
+++ b/app/src/main/res/values-pt/strings.xml
@@ -345,6 +345,7 @@
<string name="download_waiting_wifi">Aguardando o Wi‑Fi</string>
<string name="download_waiting_network">Aguardando uma conexão</string>
<string name="download_waiting_engine">Aguardando o Spotify</string>
+ <string name="download_extras">A concluir capas e letras</string>
<string name="download_quality">Qualidade dos downloads</string>
<string name="download_quality_note">Com que qualidade um download é guardado. Aqui não existe automático: um download acontece uma vez e fica, então não deveria ser a cópia que a conexão permitiu naquele minuto.</string>
<string name="download_wifi_only">Baixar somente no Wi‑Fi</string>
@@ -370,4 +371,31 @@
<string name="radio_of">Rádio de %1$s</string>
<string name="remove_download_confirm">Remover deste telemóvel as músicas transferidas de “%1$s”?</string>
<string name="remove_download_confirm_action">Remover</string>
+ <string name="tab_new">Novidades</string>
+ <string name="tab_radio">Rádio</string>
+ <string name="latest_release">Último lançamento</string>
+ <string name="top_songs">Faixas principais</string>
+ <string name="stations_for_you">Estações para você</string>
+ <string name="made_for_you">Feitas para você</string>
+ <string name="new_releases_title">Novos lançamentos</string>
+ <string name="nothing_here">Ainda não há nada aqui</string>
+ <string name="radio_empty">As estações são criadas a partir do que você ouve.</string>
+ <string name="new_songs">Novas faixas</string>
+ <string name="new_this_week">Novidades da semana</string>
+ <string name="new_release_tag">Novo lançamento</string>
+ <plurals name="song_count">
+ <item quantity="one">%1$d faixa</item>
+ <item quantity="other">%1$d faixas</item>
+ </plurals>
+ <string name="songs_and_length">%1$d faixas, %2$s</string>
+ <string name="more_notes">MAIS</string>
+ <string name="updated_ago">Atualizada: %1$s</string>
+ <string name="ago_today">hoje</string>
+ <string name="ago_days">%1$d d</string>
+ <string name="ago_weeks">%1$d sem</string>
+ <string name="ago_months">%1$d meses</string>
+ <string name="ago_years">%1$d anos</string>
+ <string name="canvas">Canvas</string>
+ <string name="canvas_show">Mostrar clipes em loop</string>
+ <string name="canvas_note">O vídeo curto que algumas faixas trazem. Desligado, também não é baixado.</string>
</resources>
diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml
index 2897a8b..e4fd9e9 100644
--- a/app/src/main/res/values-tr/strings.xml
+++ b/app/src/main/res/values-tr/strings.xml
@@ -360,6 +360,7 @@
<string name="download_waiting_wifi">Wi‑Fi bekleniyor</string>
<string name="download_waiting_network">Bağlantı bekleniyor</string>
<string name="download_waiting_engine">Spotify bekleniyor</string>
+ <string name="download_extras">Kapaklar ve sözler tamamlanıyor</string>
<string name="download_quality">İndirme kalitesi</string>
<string name="download_quality_note">Bir indirmenin hangi kalitede saklanacağı. Burada otomatik yok: indirme bir kez yapılır ve kalır, o yüzden bağlantının o dakika izin verdiği kopya olmamalı.</string>
<string name="download_wifi_only">Yalnızca Wi‑Fi ile indir</string>
@@ -385,4 +386,30 @@
<string name="radio_of">%1$s radyosu</string>
<string name="remove_download_confirm">“%1$s” içindeki indirilmiş şarkılar bu telefondan kaldırılsın mı?</string>
<string name="remove_download_confirm_action">Kaldır</string>
+ <string name="tab_new">Yeni</string>
+ <string name="tab_radio">Radyo</string>
+ <string name="latest_release">Son çıkan</string>
+ <string name="top_songs">En iyi şarkılar</string>
+ <string name="stations_for_you">Sana özel istasyonlar</string>
+ <string name="made_for_you">Senin için</string>
+ <string name="new_releases_title">Yeni çıkanlar</string>
+ <string name="nothing_here">Burada henüz bir şey yok</string>
+ <string name="radio_empty">İstasyonlar dinlediklerinden oluşturulur.</string>
+ <string name="new_songs">Yeni şarkılar</string>
+ <string name="new_this_week">Bu hafta yeni</string>
+ <string name="new_release_tag">Yeni çıkan</string>
+ <plurals name="song_count">
+ <item quantity="other">%1$d şarkı</item>
+ </plurals>
+ <string name="songs_and_length">%1$d şarkı, %2$s</string>
+ <string name="more_notes">DAHA</string>
+ <string name="updated_ago">Güncellendi: %1$s</string>
+ <string name="ago_today">bugün</string>
+ <string name="ago_days">%1$d g</string>
+ <string name="ago_weeks">%1$d hf</string>
+ <string name="ago_months">%1$d ay</string>
+ <string name="ago_years">%1$d yıl</string>
+ <string name="canvas">Canvas</string>
+ <string name="canvas_show">Döngü kliplerini göster</string>
+ <string name="canvas_note">Bazı şarkıların getirdiği kısa video. Kapalıyken indirilmez de.</string>
</resources>
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index a594c33..75604e4 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -366,6 +366,7 @@
<string name="download_waiting_wifi">Waiting for Wi‑Fi</string>
<string name="download_waiting_network">Waiting for a connection</string>
<string name="download_waiting_engine">Waiting for Spotify</string>
+ <string name="download_extras">Finishing covers and lyrics</string>
<string name="download_quality">Download quality</string>
<string name="download_quality_note">What a download is kept at. There is no automatic setting here: a download happens once and stays, so it should not be the copy your connection happened to allow that minute.</string>
<string name="download_wifi_only">Download over Wi‑Fi only</string>
@@ -391,4 +392,31 @@
<string name="radio_of">Radio of %1$s</string>
<string name="remove_download_confirm">Take the downloaded songs of “%1$s” off this phone?</string>
<string name="remove_download_confirm_action">Remove</string>
+ <string name="tab_new">New</string>
+ <string name="tab_radio">Radio</string>
+ <string name="latest_release">Latest Release</string>
+ <string name="top_songs">Top Songs</string>
+ <string name="stations_for_you">Stations for you</string>
+ <string name="made_for_you">Made for you</string>
+ <string name="new_releases_title">New releases</string>
+ <string name="nothing_here">Nothing here yet</string>
+ <string name="radio_empty">Radio stations are built from what you listen to.</string>
+ <string name="new_songs">New Songs</string>
+ <string name="new_this_week">New This Week</string>
+ <string name="new_release_tag">New release</string>
+ <plurals name="song_count">
+ <item quantity="one">%1$d song</item>
+ <item quantity="other">%1$d songs</item>
+ </plurals>
+ <string name="songs_and_length">%1$d songs, %2$s</string>
+ <string name="more_notes">MORE</string>
+ <string name="updated_ago">Updated: %1$s</string>
+ <string name="ago_today">today</string>
+ <string name="ago_days">%1$d d</string>
+ <string name="ago_weeks">%1$d w</string>
+ <string name="ago_months">%1$d mo</string>
+ <string name="ago_years">%1$d y</string>
+ <string name="canvas">Canvas</string>
+ <string name="canvas_show">Show looping clips</string>
+ <string name="canvas_note">The short video some tracks come with. Off, none is downloaded either.</string>
</resources>
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml
index 83fc540..51f74d6 100644
--- a/gradle/libs.versions.toml
+++ b/gradle/libs.versions.toml
@@ -32,6 +32,7 @@ media3-session = { module = "androidx.media3:media3-session", version.ref = "med
# still comes from the librespot engine instead.
media3-exoplayer = { module = "androidx.media3:media3-exoplayer", version.ref = "media3" }
media3-exoplayer-dash = { module = "androidx.media3:media3-exoplayer-dash", version.ref = "media3" }
+media3-exoplayer-hls = { module = "androidx.media3:media3-exoplayer-hls", version.ref = "media3" }
media3-ui = { module = "androidx.media3:media3-ui", version.ref = "media3" }
kotlinx-coroutines-android = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-android", version.ref = "coroutines" }
diff --git a/native/src/catalog.rs b/native/src/catalog.rs
index 28c3f17..f654191 100644
--- a/native/src/catalog.rs
+++ b/native/src/catalog.rs
@@ -294,6 +294,9 @@ fn track_json(track: &Track) -> Value {
.map(|a| json!({ "name": a.name, "uri": a.id.to_uri().ok() }))
.collect::<Vec<_>>(),
"album": track.album.name,
+ // And its address, so the title in the player is a way onto the record
+ // rather than a caption. The Web API side fills the same field.
+ "albumUri": track.album.id.to_uri().ok(),
"durationMs": track.duration,
"explicit": track.is_explicit,
"artworkUrl": largest_cover(&track.album.covers),
diff --git a/native/vendor/librespot-playback/src/player.rs b/native/vendor/librespot-playback/src/player.rs
index 2e88b31..c9333f8 100644
--- a/native/vendor/librespot-playback/src/player.rs
+++ b/native/vendor/librespot-playback/src/player.rs
@@ -1900,6 +1900,36 @@ impl Future for PlayerInternal {
}
}
+ // LOCAL PATCH: the outgoing track keeps sounding while the one it
+ // is dissolving into is still being loaded.
+ //
+ // `apply_fade` mixes the tail into the incoming track's own
+ // packets, so it can only run once that track is producing audio.
+ // Between the load starting and the first packet arriving there is
+ // nothing to mix into, and the fade fell silent there — which is a
+ // cut, not a dissolve. Online it was brief enough to pass; offline,
+ // where this side loads the next track itself, it was the whole of
+ // what a crossfade sounded like.
+ //
+ // `Loading` only, and only a load meant to play: a fade is the
+ // sound of one song ending under another, and a load that will sit
+ // paused is not that.
+ if self.fade_out.is_some()
+ && matches!(
+ self.state,
+ PlayerState::Loading {
+ start_playback: true,
+ ..
+ }
+ )
+ && self.pump_fade_out()
+ {
+ // Round again rather than to sleep: the write inside blocks for
+ // as long as the audio it just handed over lasts, so this paces
+ // itself the way playback does.
+ all_futures_completed_or_not_ready = false;
+ }
+
if self.state.is_playing() {
self.ensure_sink_running();
@@ -2271,6 +2301,72 @@ impl PlayerInternal {
}
}
+ /// LOCAL PATCH: writes the outgoing track on its own, with no incoming one.
+ ///
+ /// The same curve [`apply_fade`] uses, applied to the tail alone: there is
+ /// nothing to mix it with yet. Returns whether anything was written, so the
+ /// caller knows to come round again rather than wait to be woken.
+ fn pump_fade_out(&mut self) -> bool {
+ let volume = self.volume_getter.attenuation_factor();
+
+ let (samples, drained) = {
+ let Some(fade) = self.fade_out.as_mut() else {
+ return false;
+ };
+
+ let mut samples: Vec<f64> = fade.spare.drain(..).collect();
+ if !fade.drained {
+ match fade.decoder.next_packet() {
+ Ok(Some((_, packet))) => match packet.samples() {
+ Ok(decoded) => samples.extend_from_slice(decoded),
+ Err(_) => fade.drained = true,
+ },
+ Ok(None) => fade.drained = true,
+ Err(e) => {
+ debug!("crossfade: the outgoing track stopped early: {e}");
+ fade.drained = true;
+ }
+ }
+ }
+
+ let x = fade.done as f64 / fade.total as f64;
+ let gain = (x * std::f64::consts::FRAC_PI_2).cos()
+ * fade.normalisation_factor
+ * volume;
+ for sample in samples.iter_mut() {
+ *sample = (*sample * gain).clamp(-1.0, MAX_SAMPLE);
+ }
+
+ // Counted here as well, or the curve would stand still through the
+ // load and the fade would restart at full level once the incoming
+ // track arrived.
+ fade.done = (fade.done + samples.len()).min(fade.total);
+
+ (samples, fade.drained)
+ };
+
+ if samples.is_empty() {
+ if drained {
+ // Dropping it closes the outgoing stream.
+ self.fade_out = None;
+ }
+ return false;
+ }
+
+ if let Err(e) = self
+ .sink
+ .write(AudioPacket::Samples(samples), &mut self.converter)
+ {
+ // The fade goes rather than the playback: what failed is the tail of
+ // a song that is already over, and the track being loaded has its
+ // own sink errors to report if it hits any.
+ error!("{e}");
+ self.fade_out = None;
+ return false;
+ }
+ true
+ }
+
fn handle_player_stop(&mut self) {
// LOCAL PATCH: nothing is being faded into any more.
self.fade_out = None;